Doc/module style doc blocks for examples (#4438)

# Objective

Provide a starting point for #3951, or a partial solution. 
Providing a few comment blocks to discuss, and hopefully find better one in the process. 

## Solution

Since I am pretty new to pretty much anything in this context, I figured I'd just start with a draft for some file level doc blocks. For some of them I found more relevant details (or at least things I considered interessting), for some others there is less. 

## Changelog

- Moved some existing comments from main() functions in the 2d examples to the file header level
- Wrote some more comment blocks for most other 2d examples

TODO: 
- [x] 2d/sprite_sheet, wasnt able to come up with something good yet 
- [x] all other example groups...


Also: Please let me know if the commit style is okay, or to verbose. I could certainly squash these things, or add more details if needed. 
I also hope its okay to raise this PR this early, with just a few files changed. Took me long enough and I dont wanted to let it go to waste because I lost motivation to do the whole thing. Additionally I am somewhat uncertain over the style and contents of the commets. So let me know what you thing please.
This commit is contained in:
Mark Schmale 2022-05-16 13:53:20 +00:00
parent 7462f21be4
commit 1ba7429371
120 changed files with 425 additions and 177 deletions

View file

@ -1,3 +1,5 @@
//! Shows how to render a polygonal [`Mesh`], generated from a [`Quad`] primitive, in a 2D scene.
use bevy::{prelude::*, sprite::MaterialMesh2dBundle};
fn main() {

View file

@ -1,3 +1,8 @@
//! This example shows how to manually render 2d items using "mid level render apis" with a custom
//! pipeline for 2d meshes.
//! It doesn't use the [`Material2d`] abstraction, but changes the vertex buffer to include vertex color.
//! Check out the "mesh2d" example for simpler / higher level 2d meshes.
use bevy::{
core_pipeline::Transparent2d,
prelude::*,
@ -23,9 +28,6 @@ use bevy::{
utils::FloatOrd,
};
/// This example shows how to manually render 2d items using "mid level render apis" with a custom pipeline for 2d meshes
/// It doesn't use the [`Material2d`] abstraction, but changes the vertex buffer to include vertex color
/// Check out the "mesh2d" example for simpler / higher level 2d meshes
fn main() {
App::new()
.add_plugins(DefaultPlugins)

View file

@ -1,3 +1,5 @@
//! Renders a 2D scene containing a single, moving sprite.
use bevy::prelude::*;
fn main() {
@ -25,6 +27,8 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
.insert(Direction::Up);
}
/// The sprite is animated by changing its translation depending on the time that has passed since
/// the last frame.
fn sprite_movement(time: Res<Time>, mut sprite_position: Query<(&mut Direction, &mut Transform)>) {
for (mut logo, mut transform) in sprite_position.iter_mut() {
match *logo {

View file

@ -1,3 +1,5 @@
//! Demonstrates rotating entities in 2D using quaternions.
use bevy::{
core::FixedTimestep,
math::{const_vec2, Vec3Swizzles},

View file

@ -1,3 +1,5 @@
//! Shows how to render simple primitive shapes with a single color.
use bevy::{prelude::*, sprite::MaterialMesh2dBundle};
fn main() {

View file

@ -1,3 +1,5 @@
//! Displays a single [`Sprite`], created from an image.
use bevy::prelude::*;
fn main() {

View file

@ -1,3 +1,5 @@
//! Displays a single [`Sprite`], created from an image, but flipped on one axis.
use bevy::prelude::*;
fn main() {

View file

@ -1,3 +1,6 @@
//! Renders an animated sprite by loading all animation frames from a single image (a sprite sheet)
//! into a texture atlas, and changing the displayed image periodically.
use bevy::prelude::*;
fn main() {

View file

@ -1,3 +1,10 @@
//! Shows text rendering with moving, rotating and scaling text.
//!
//! Note that this uses [`Text2dBundle`] to display text alongside your other entities in a 2D scene.
//!
//! For an example on how to render text as part of a user interface, independent from the world
//! viewport, you may want to look at `2d/contributors.rs` or `ui/text.rs`.
use bevy::{prelude::*, text::Text2dBounds};
fn main() {

View file

@ -1,7 +1,8 @@
//! In this example we generate a new texture atlas (sprite sheet) from a folder containing
//! individual sprites.
use bevy::{asset::LoadState, prelude::*};
/// In this example we generate a new texture atlas (sprite sheet) from a folder containing
/// individual sprites
fn main() {
App::new()
.init_resource::<RpgSpriteHandles>()

View file

@ -1,3 +1,5 @@
//! A simple 3D scene with light shining over a cube sitting on a plane.
use bevy::prelude::*;
fn main() {

View file

@ -1,3 +1,6 @@
//! Illustrates different lights of various types and colors, some static, some moving over
//! a simple scene.
use bevy::prelude::*;
fn main() {

View file

@ -1,3 +1,5 @@
//! Loads and renders a glTF file as a scene.
use bevy::prelude::*;
fn main() {

View file

@ -1,12 +1,13 @@
//! This example shows how to configure Multi-Sample Anti-Aliasing. Setting the sample count higher
//! will result in smoother edges, but it will also increase the cost to render those edges. The
//! range should generally be somewhere between 1 (no multi sampling, but cheap) to 8 (crisp but
//! expensive).
//! Note that WGPU currently only supports 1 or 4 samples.
//! Ultimately we plan on supporting whatever is natively supported on a given device.
//! Check out [this issue](https://github.com/gfx-rs/wgpu/issues/1832) for more info.
use bevy::prelude::*;
/// This example shows how to configure Multi-Sample Anti-Aliasing. Setting the sample count higher
/// will result in smoother edges, but it will also increase the cost to render those edges. The
/// range should generally be somewhere between 1 (no multi sampling, but cheap) to 8 (crisp but
/// expensive).
/// Note that WGPU currently only supports 1 or 4 samples.
/// Ultimately we plan on supporting whatever is natively supported on a given device.
/// Check out [this issue](https://github.com/gfx-rs/wgpu/issues/1832) for more info.
fn main() {
App::new()
.insert_resource(Msaa { samples: 4 })

View file

@ -1,3 +1,5 @@
//! Shows how to create a 3D orthographic view (for isometric-look games or CAD applications).
use bevy::prelude::*;
fn main() {

View file

@ -1,7 +1,8 @@
//! Illustrates how to create parent-child relationships between entities and how parent transforms
//! are propagated to their descendants.
use bevy::prelude::*;
/// This example illustrates how to create parent->child relationships between entities how parent
/// transforms are propagated to their descendants
fn main() {
App::new()
.insert_resource(Msaa { samples: 4 })

View file

@ -1,6 +1,7 @@
//! This example shows how to configure Physically Based Rendering (PBR) parameters.
use bevy::prelude::*;
/// This example shows how to configure Physically Based Rendering (PBR) parameters.
fn main() {
App::new()
.add_plugins(DefaultPlugins)

View file

@ -1,3 +1,5 @@
//! Shows how to render to a texture. Useful for mirrors, UI, or exporting images.
use bevy::{
core_pipeline::{
draw_3d_graph, node, AlphaMask3d, Opaque3d, RenderTargetClearColors, Transparent3d,

View file

@ -1,3 +1,5 @@
//! Demonstrates how shadow biases affect shadows in a 3d scene.
use bevy::{input::mouse::MouseMotion, prelude::*};
fn main() {

View file

@ -1,3 +1,5 @@
//! Demonstrates how to prevent meshes from casting/receiving shadows in a 3d scene.
use bevy::{
pbr::{NotShadowCaster, NotShadowReceiver},
prelude::*,

View file

@ -1,3 +1,5 @@
//! Demonstrates how lighting is affected by different radius of point lights.
use bevy::prelude::*;
fn main() {

View file

@ -1,6 +1,7 @@
//! This example shows various ways to configure texture materials in 3D.
use bevy::prelude::*;
/// This example shows various ways to configure texture materials in 3D
fn main() {
App::new()
.add_plugins(DefaultPlugins)

View file

@ -1,3 +1,6 @@
//! Shows how to render multiple passes to the same window, useful for rendering different views
//! or drawing an object on top regardless of depth.
use bevy::{
core_pipeline::{draw_3d_graph, node, AlphaMask3d, Opaque3d, Transparent3d},
prelude::*,
@ -68,6 +71,7 @@ fn extract_first_pass_camera_phases(
));
}
}
// A node for the first pass camera that runs draw_3d_graph with this camera.
struct FirstPassCameraDriver {
query: QueryState<Entity, With<FirstPassCamera>>,

View file

@ -1,3 +1,6 @@
//! Update a scene from a glTF file, either by spawning the scene as a child of another entity,
//! or by accessing the entities of the scene.
use bevy::{prelude::*, scene::InstanceId};
fn main() {

View file

@ -1,3 +1,5 @@
//! Illustrates the use of vertex colors.
use bevy::{prelude::*, render::mesh::VertexAttributeValues};
fn main() {

View file

@ -1,3 +1,5 @@
//! Showcases wireframe rendering.
use bevy::{
pbr::wireframe::{Wireframe, WireframeConfig, WireframePlugin},
prelude::*,

View file

@ -241,14 +241,14 @@ Example | File | Description
Example | File | Description
--- | --- | ---
`custom_vertex_attribute` | [`shader/custom_vertex_attribute.rs`](./shader/custom_vertex_attribute.rs) | Illustrates creating a custom shader material that reads a mesh's custom vertex attribute.
`shader_material` | [`shader/shader_material.rs`](./shader/shader_material.rs) | Illustrates creating a custom material and a shader that uses it
`shader_material_screenspace_texture` | [`shader/shader_material_screenspace_texture.rs`](./shader/shader_material_screenspace_texture.rs) | A custom shader sampling a texture with view-independent UV coordinates
`shader_material_glsl` | [`shader/shader_material_glsl.rs`](./shader/shader_material_glsl.rs) | A custom shader using the GLSL shading language.
`shader_instancing` | [`shader/shader_instancing.rs`](./shader/shader_instancing.rs) | A custom shader showing off rendering a mesh multiple times in one draw call.
`animate_shader` | [`shader/animate_shader.rs`](./shader/animate_shader.rs) | Shows how to pass changing data like the time since startup into a shader.
`compute_shader_game_of_life` | [`shader/compute_shader_game_of_life.rs`](./shader/compute_shader_game_of_life.rs) | A compute shader simulating Conway's Game of Life
`custom_vertex_attribute` | [`shader/custom_vertex_attribute.rs`](./shader/custom_vertex_attribute.rs) | Illustrates creating a custom shader material that reads a mesh's custom vertex attribute.
`shader_defs` | [`shader/shader_defs.rs`](./shader/shader_defs.rs) | Demonstrates creating a custom material that uses "shaders defs" (a tool to selectively toggle parts of a shader)
`shader_instancing` | [`shader/shader_instancing.rs`](./shader/shader_instancing.rs) | A custom shader showing off rendering a mesh multiple times in one draw call.
`shader_material` | [`shader/shader_material.rs`](./shader/shader_material.rs) | Illustrates creating a custom material and a shader that uses it
`shader_material_glsl` | [`shader/shader_material_glsl.rs`](./shader/shader_material_glsl.rs) | A custom shader using the GLSL shading language.
`shader_material_screenspace_texture` | [`shader/shader_material_screenspace_texture.rs`](./shader/shader_material_screenspace_texture.rs) | A custom shader sampling a texture with view-independent UV coordinates.
## Stress Tests
@ -279,14 +279,14 @@ Example | File | Description
Example | File | Description
--- | --- | ---
`scene_viewer` | [`tools/scene_viewer.rs`](./tools/scene_viewer.rs) | A simple way to view glTF models with Bevy. Just run `cargo run --release --example scene_viewer -- /path/to/model.gltf#Scene0`, replacing the path as appropriate. With no arguments it will load the FieldHelmet glTF model from the repository assets subdirectory.
`scene_viewer` | [`tools/scene_viewer.rs`](./tools/scene_viewer.rs) | A simple way to view glTF models with Bevy. Just run `cargo run --release --example scene_viewer /path/to/model.gltf#Scene0`, replacing the path as appropriate. With no arguments it will load the FieldHelmet glTF model from the repository assets subdirectory.
## Transforms
Example | File | Description
--- | --- | ---
`global_vs_local_translation` | [`transforms/global_vs_local_translation.rs`](./transforms/global_vs_local_translation.rs) | Illustrates the difference between direction of a translation in respect to local object or global object Transform
`3d_rotation` | [`transforms/3d_rotation.rs`](./transforms/3d_rotation.rs) | Illustrates how to (constantly) rotate an object around an axis
`global_vs_local_translation` | [`transforms/global_vs_local_translation.rs`](./transforms/global_vs_local_translation.rs) | Illustrates the difference between direction of a translation in respect to local object or global object Transform.
`scale` | [`transforms/scale.rs`](./transforms/scale.rs) | Illustrates how to scale an object in each direction
`transform` | [`transforms/transfrom.rs`](./transforms/transform.rs) | Shows multiple transformations of objects
`translation` | [`transforms/translation.rs`](./transforms/translation.rs) | Illustrates how to move an object along an axis

View file

@ -1,3 +1,5 @@
//! Plays animations from a skinned glTF.
use bevy::prelude::*;
fn main() {

View file

@ -1,3 +1,5 @@
//! Create and play an animation defined by code that operates on the `Transform` component.
use std::f32::consts::{FRAC_PI_2, PI};
use bevy::prelude::*;

View file

@ -1,3 +1,6 @@
//! Skinned mesh example with mesh and joints data defined in code.
//! Example taken from <https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_019_SimpleSkin.md>
use std::f32::consts::PI;
use bevy::{
@ -10,8 +13,6 @@ use bevy::{
};
use rand::Rng;
/// Skinned mesh example with mesh and joints data defined in code.
/// Example taken from <https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_019_SimpleSkin.md>
fn main() {
App::new()
.add_plugins(DefaultPlugins)

View file

@ -1,9 +1,10 @@
//! Skinned mesh example with mesh and joints data loaded from a glTF file.
//! Example taken from <https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_019_SimpleSkin.md>
use std::f32::consts::PI;
use bevy::{pbr::AmbientLight, prelude::*, render::mesh::skinning::SkinnedMesh};
/// Skinned mesh example with mesh and joints data loaded from a glTF file.
/// Example taken from <https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_019_SimpleSkin.md>
fn main() {
App::new()
.add_plugins(DefaultPlugins)
@ -27,7 +28,7 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn_scene(asset_server.load::<Scene, _>("models/SimpleSkin/SimpleSkin.gltf#Scene0"));
}
/// The scene hierachy currently looks somewhat like this:
/// The scene hierarchy currently looks somewhat like this:
///
/// ```ignore
/// <Parent entity>

View file

@ -1,10 +1,11 @@
//! This example demonstrates you can create a custom runner (to update an app manually). It reads
//! lines from stdin and prints them from within the ecs.
use bevy::prelude::*;
use std::{io, io::BufRead};
struct Input(String);
/// This example demonstrates you can create a custom runner (to update an app manually). It reads
/// lines from stdin and prints them from within the ecs.
fn my_runner(mut app: App) {
println!("Type stuff into the console");
for line in io::stdin().lock().lines() {

View file

@ -1,3 +1,5 @@
//! An example that shows how to handle drag and drop of files in an app.
use bevy::prelude::*;
fn main() {

View file

@ -1,3 +1,5 @@
//! An empty application (does nothing)
use bevy::prelude::*;
fn main() {

View file

@ -1,3 +1,5 @@
//! An empty application with default plugins.
use bevy::prelude::*;
fn main() {

View file

@ -1,12 +1,12 @@
use bevy::{app::ScheduleRunnerSettings, prelude::*, utils::Duration};
//! This example only enables a minimal set of plugins required for bevy to run.
//! You can also completely remove rendering / windowing Plugin code from bevy
//! by making your import look like this in your Cargo.toml.
//!
//! [dependencies]
//! bevy = { version = "*", default-features = false }
//! # replace "*" with the most recent version of bevy
// This example only enables a minimal set of plugins required for bevy to run.
// You can also completely remove rendering / windowing Plugin code from bevy
// by making your import look like this in your Cargo.toml
//
// [dependencies]
// bevy = { version = "*", default-features = false }
// # replace "*" with the most recent version of bevy
use bevy::{app::ScheduleRunnerSettings, prelude::*, utils::Duration};
fn main() {
// this app runs once

View file

@ -1,3 +1,6 @@
//! An application that runs with default plugins, but without an actual renderer.
//! This can be very useful for integration tests or CI.
use bevy::{prelude::*, render::settings::WgpuSettings};
fn main() {

View file

@ -1,6 +1,7 @@
//! This example illustrates how to use logs in bevy.
use bevy::prelude::*;
/// This example illustrates how to use logs in bevy
fn main() {
App::new()
// Uncomment this to override the default log settings:

View file

@ -1,8 +1,11 @@
//! Demonstrates the creation and registration of a custom plugin.
//!
//! Plugins are the foundation of Bevy. They are scoped sets of components, resources, and systems
//! that provide a specific piece of functionality (generally the smaller the scope, the better).
//! This example illustrates how to create a simple plugin that prints out a message.
use bevy::{prelude::*, utils::Duration};
/// Plugins are the foundation of Bevy. They are scoped sets of components, resources, and systems
/// that provide a specific piece of functionality (generally the smaller the scope, the better).
/// This example illustrates how to create a simple plugin that prints out a message.
fn main() {
App::new()
.add_plugins(DefaultPlugins)

View file

@ -1,6 +1,8 @@
//! Demonstrates the creation and registration of a custom plugin group.
//! [`PluginGroup`]s are a way to group sets of plugins that should be registered together.
use bevy::{app::PluginGroupBuilder, prelude::*};
/// [`PluginGroups`] are a way to group sets of plugins that should be registered together.
fn main() {
App::new()
// Two PluginGroups that are included with bevy are DefaultPlugins and MinimalPlugins

View file

@ -1,3 +1,5 @@
//! Shows how to return to the calling function after a windowed Bevy app has exited.
use bevy::{prelude::*, winit::WinitSettings};
fn main() {

View file

@ -1,7 +1,8 @@
//! This example illustrates how to customize the thread pool used internally (e.g. to only use a
//! certain number of threads).
use bevy::prelude::*;
/// This example illustrates how to customize the thread pool used internally (e.g. to only use a
/// certain number of threads).
fn main() {
App::new()
.insert_resource(DefaultTaskPoolOptions::with_num_threads(4))

View file

@ -1,3 +1,5 @@
//! Create an application without winit (runs single time, no event loop).
use bevy::prelude::*;
use bevy::winit::WinitPlugin;

View file

@ -1,6 +1,7 @@
//! This example illustrates various ways to load assets.
use bevy::prelude::*;
/// This example illustrates various ways to load assets
fn main() {
App::new()
.insert_resource(Msaa { samples: 4 })

View file

@ -1,3 +1,5 @@
//! Implements loader for a custom asset type.
use bevy::{
asset::{AssetLoader, LoadContext, LoadedAsset},
prelude::*,

View file

@ -1,3 +1,7 @@
//! Implements a custom asset io loader.
//! An [`AssetIo`] is what the asset server uses to read the raw bytes of assets.
//! It does not know anything about the asset formats, only how to talk to the underlying storage.
use bevy::{
asset::{AssetIo, AssetIoError, Metadata},
prelude::*,

View file

@ -1,8 +1,9 @@
//! Hot reloading allows you to modify assets files to be immediately reloaded while your game is
//! running. This lets you immediately see the results of your changes without restarting the game.
//! This example illustrates hot reloading mesh changes.
use bevy::{asset::AssetServerSettings, prelude::*};
/// Hot reloading allows you to modify assets on disk and they will be "live reloaded" while your
/// game is running. This lets you immediately see the results of your changes without restarting
/// the game. This example illustrates hot reloading mesh changes.
fn main() {
App::new()
// Tell the asset server to watch for asset changes on disk:

View file

@ -1,3 +1,6 @@
//! This example shows how to use the ECS and the [`AsyncComputeTaskPool`]
//! to spawn, poll, and complete tasks across systems and system ticks.
use bevy::{
prelude::*,
tasks::{AsyncComputeTaskPool, Task},
@ -6,8 +9,6 @@ use futures_lite::future;
use rand::Rng;
use std::time::{Duration, Instant};
/// This example shows how to use the ECS and the [`AsyncComputeTaskPool`]
/// to spawn, poll, and complete tasks across systems and system ticks.
fn main() {
App::new()
.insert_resource(Msaa { samples: 4 })

View file

@ -1,3 +1,5 @@
//! How to use an external thread to run an infinite task and communicate with a channel.
use bevy::prelude::*;
// Using crossbeam_channel instead of std as std `Receiver` is `!Sync`
use crossbeam_channel::{bounded, Receiver};

View file

@ -1,6 +1,7 @@
//! This example illustrates how to load and play an audio file.
use bevy::prelude::*;
/// This example illustrates how to load and play an audio file
fn main() {
App::new()
.add_plugins(DefaultPlugins)

View file

@ -1,6 +1,7 @@
//! This example illustrates how to load and play an audio file, and control how it's played.
use bevy::{audio::AudioSink, prelude::*};
/// This example illustrates how to load and play an audio file, and control how it's played
fn main() {
App::new()
.add_plugins(DefaultPlugins)

View file

@ -1,22 +1,23 @@
//! This example illustrates how to create a custom diagnostic.
use bevy::{
diagnostic::{Diagnostic, DiagnosticId, Diagnostics, LogDiagnosticsPlugin},
prelude::*,
};
/// This example illustrates how to create a custom diagnostic
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// The "print diagnostics" plugin is optional. It just visualizes our diagnostics in the
// console
// The "print diagnostics" plugin is optional.
// It just visualizes our diagnostics in the console.
.add_plugin(LogDiagnosticsPlugin::default())
.add_startup_system(setup_diagnostic_system)
.add_system(my_system)
.run();
}
// All diagnostics should have a unique DiagnosticId. for each new diagnostic, generate a new random
// number
// All diagnostics should have a unique DiagnosticId.
// For each new diagnostic, generate a new random number.
pub const SYSTEM_ITERATION_COUNT: DiagnosticId =
DiagnosticId::from_u128(337040787172757619024841343456040760896);
@ -31,6 +32,6 @@ fn setup_diagnostic_system(mut diagnostics: ResMut<Diagnostics>) {
}
fn my_system(mut diagnostics: ResMut<Diagnostics>) {
// Add a measurement of 10.0 for our diagnostic each time this system runs
// Add a measurement of 10.0 for our diagnostic each time this system runs.
diagnostics.add_measurement(SYSTEM_ITERATION_COUNT, 10.0);
}

View file

@ -1,3 +1,5 @@
//! Shows different built-in plugins that logs diagnostics, like frames per second (FPS), to the console.
use bevy::{
diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin},
prelude::*,

View file

@ -1,7 +1,8 @@
//! This example illustrates how to react to component change.
use bevy::prelude::*;
use rand::Rng;
// This example illustrates how to react to component change
fn main() {
App::new()
.add_plugins(DefaultPlugins)

View file

@ -1,22 +1,23 @@
//! This example illustrates the usage of the `WorldQuery` derive macro, which allows
//! defining custom query and filter types.
//!
//! While regular tuple queries work great in most of simple scenarios, using custom queries
//! declared as named structs can bring the following advantages:
//! - They help to avoid destructuring or using `q.0, q.1, ...` access pattern.
//! - Adding, removing components or changing items order with structs greatly reduces maintenance
//! burden, as you don't need to update statements that destructure tuples, care about order
//! of elements, etc. Instead, you can just add or remove places where a certain element is used.
//! - Named structs enable the composition pattern, that makes query types easier to re-use.
//! - You can bypass the limit of 15 components that exists for query tuples.
//!
//! For more details on the `WorldQuery` derive macro, see the trait documentation.
use bevy::{
ecs::{component::Component, query::WorldQuery},
prelude::*,
};
use std::fmt::Debug;
/// This examples illustrates the usage of the `WorldQuery` derive macro, which allows
/// defining custom query and filter types.
///
/// While regular tuple queries work great in most of simple scenarios, using custom queries
/// declared as named structs can bring the following advantages:
/// - They help to avoid destructuring or using `q.0, q.1, ...` access pattern.
/// - Adding, removing components or changing items order with structs greatly reduces maintenance
/// burden, as you don't need to update statements that destructure tuples, care about order
/// of elements, etc. Instead, you can just add or remove places where a certain element is used.
/// - Named structs enable the composition pattern, that makes query types easier to re-use.
/// - You can bypass the limit of 15 components that exists for query tuples.
///
/// For more details on the `WorldQuery` derive macro, see the trait documentation.
fn main() {
App::new()
.add_startup_system(spawn)

View file

@ -1,3 +1,29 @@
//! This is a guided introduction to Bevy's "Entity Component System" (ECS)
//! All Bevy app logic is built using the ECS pattern, so definitely pay attention!
//!
//! Why ECS?
//! * Data oriented: Functionality is driven by data
//! * Clean Architecture: Loose coupling of functionality / prevents deeply nested inheritance
//! * High Performance: Massively parallel and cache friendly
//!
//! ECS Definitions:
//!
//! Component: just a normal Rust data type. generally scoped to a single piece of functionality
//! Examples: position, velocity, health, color, name
//!
//! Entity: a collection of components with a unique id
//! Examples: Entity1 { Name("Alice"), Position(0, 0) },
//! Entity2 { Name("Bill"), Position(10, 5) }
//!
//! Resource: a shared global piece of data
//! Examples: asset storage, events, system state
//!
//! System: runs logic on entities, components, and resources
//! Examples: move system, damage system
//!
//! Now that you know a little bit about ECS, lets look at some Bevy code!
//! We will now make a simple "game" to illustrate what Bevy's ECS looks like in practice.
use bevy::{
app::{AppExit, ScheduleRunnerPlugin, ScheduleRunnerSettings},
ecs::schedule::ReportExecutionOrderAmbiguities,
@ -7,32 +33,6 @@ use bevy::{
};
use rand::random;
/// This is a guided introduction to Bevy's "Entity Component System" (ECS)
/// All Bevy app logic is built using the ECS pattern, so definitely pay attention!
///
/// Why ECS?
/// * Data oriented: Functionality is driven by data
/// * Clean Architecture: Loose coupling of functionality / prevents deeply nested inheritance
/// * High Performance: Massively parallel and cache friendly
///
/// ECS Definitions:
///
/// Component: just a normal Rust data type. generally scoped to a single piece of functionality
/// Examples: position, velocity, health, color, name
///
/// Entity: a collection of components with a unique id
/// Examples: Entity1 { Name("Alice"), Position(0, 0) }, Entity2 { Name("Bill"), Position(10, 5)
/// }
/// Resource: a shared global piece of data
/// Examples: asset storage, events, system state
///
/// System: runs logic on entities, components, and resources
/// Examples: move system, damage system
///
/// Now that you know a little bit about ECS, lets look at some Bevy code!
/// We will now make a simple "game" to illustrate what Bevy's ECS looks like in practice.
// COMPONENTS: Pieces of functionality we add to entities. These are just normal Rust data types
//

View file

@ -1,7 +1,8 @@
//! This example creates a new event, a system that triggers the event once per second,
//! and a system that prints a message whenever the event is received.
use bevy::prelude::*;
/// This example creates a new event, a system that triggers the event once per second,
/// and a system that prints a message whenever the event is received.
fn main() {
App::new()
.add_plugins(DefaultPlugins)

View file

@ -1,3 +1,5 @@
//! Shows how to create systems that run every fixed timestep, rather than every tick.
use bevy::{
core::{FixedTimestep, FixedTimesteps},
prelude::*,

View file

@ -1,15 +1,15 @@
use bevy::{ecs::component::Component, prelude::*};
//! Generic types allow us to reuse logic across many related systems,
//! allowing us to specialize our function's behavior based on which type (or types) are passed in.
//!
//! This is commonly useful for working on related components or resources,
//! where we want to have unique types for querying purposes but want them all to work the same way.
//! This is particularly powerful when combined with user-defined traits to add more functionality to these related types.
//! Remember to insert a specialized copy of the system into the schedule for each type that you want to operate on!
//!
//! For more advice on working with generic types in Rust, check out <https://doc.rust-lang.org/book/ch10-01-syntax.html>
//! or <https://doc.rust-lang.org/rust-by-example/generics.html>
/// Generic types allow us to reuse logic across many related systems,
/// allowing us to specialize our function's behavior based on which type (or types) are passed in.
///
/// This is commonly useful for working on related components or resources,
/// where we want to have unique types for querying purposes but want them all to work the same way.
/// This is particularly powerful when combined with user-defined traits to add more functionality to these related types.
/// Remember to insert a specialized copy of the system into the schedule for each type that you want to operate on!
///
/// For more advice on working with generic types in Rust, check out <https://doc.rust-lang.org/book/ch10-01-syntax.html>
/// or <https://doc.rust-lang.org/rust-by-example/generics.html>
use bevy::{ecs::component::Component, prelude::*};
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
enum AppState {

View file

@ -1,3 +1,5 @@
//! Creates a hierarchy of parents and children entities.
use bevy::prelude::*;
fn main() {

View file

@ -1,3 +1,5 @@
//! Shows how to iterate over combinations of query results.
use bevy::{core::FixedTimestep, pbr::AmbientLight, prelude::*, render::camera::Camera};
use rand::{thread_rng, Rng};

View file

@ -1,3 +1,5 @@
//! Illustrates parallel queries with `ParallelIterator`.
use bevy::{prelude::*, tasks::prelude::*};
use rand::random;

View file

@ -1,4 +1,4 @@
// This example shows how you can know when a `Component` has been removed, so you can react to it.
//! This example shows how you can know when a `Component` has been removed, so you can react to it.
use bevy::prelude::*;

View file

@ -1,3 +1,5 @@
//! Demonstrates a startup system (one that runs once when the app starts up).
use bevy::prelude::*;
fn main() {

View file

@ -1,7 +1,8 @@
//! This example illustrates how to use [`States`] to control transitioning from a `Menu` state to
//! an `InGame` state.
use bevy::prelude::*;
/// This example illustrates how to use [`States`] to control transitioning from a `Menu` state to
/// an `InGame` state.
fn main() {
App::new()
.add_plugins(DefaultPlugins)

View file

@ -1,3 +1,6 @@
//! Illustrates how to make a single system from multiple functions running in sequence and sharing
//! their inputs and outputs.
use anyhow::Result;
use bevy::prelude::*;

View file

@ -1,3 +1,5 @@
//! Shows how anonymous functions / closures can be used as systems.
use bevy::{log::LogPlugin, prelude::*};
fn main() {

View file

@ -1,6 +1,7 @@
//! This example creates a custom [`SystemParam`] struct that counts the number of players.
use bevy::{ecs::system::SystemParam, prelude::*};
/// This example creates a [`SystemParam`] struct that counts the number of players
fn main() {
App::new()
.insert_resource(PlayerCount(0))

View file

@ -1,3 +1,26 @@
//! Shows how systems with a similar purpose can be grouped into sets.
//!
//! ```none
//! Physics (Criteria: App has run < 1.0 seconds)
//! \--> update_velocity (via label PhysicsSystem::UpdateVelocity)
//! \--> movement (via label PhysicsSystem::Movement)
//! PostPhysics (Criteria: Resource `done` is false)
//! \--> collision || sfx
//! Exit (Criteria: Resource `done` is true)
//! \--> exit
//! ```
//!
//! The `Physics` label represents a [`SystemSet`] containing two systems.
//! This set's criteria is to stop after a second has elapsed.
//! The two systems (`update_velocity`, `movement`) run in a specified order.
//!
//! Another label `PostPhysics` uses run criteria to only run after `Physics` has finished.
//! This set's criteria is to run only when _not done_, as specified via a resource.
//! The two systems here (collision, sfx) are not specified to run in any order, and the actual
//! ordering can then change between invocations.
//!
//! Lastly a system with run criteria _done_ is used to exit the app.
use bevy::{app::AppExit, ecs::schedule::ShouldRun, prelude::*};
/// A [`SystemLabel`] can be applied as a label to systems and system sets,
@ -16,28 +39,6 @@ struct PostPhysics;
#[derive(Default)]
struct Done(bool);
/// This example realizes the following scheme:
///
/// ```none
/// Physics (Criteria: App has run < 1.0 seconds)
/// \--> update_velocity (via label PhysicsSystem::UpdateVelocity)
/// \--> movement (via label PhysicsSystem::Movement)
/// PostPhysics (Criteria: Resource `done` is false)
/// \--> collision || sfx
/// Exit (Criteria: Resource `done` is true)
/// \--> exit
/// ```
///
/// The `Physics` label represents a [`SystemSet`] containing two systems.
/// This set's criteria is to stop after a second has elapsed.
/// The two systems (`update_velocity`, `movement`) run in a specified order.
///
/// Another label `PostPhysics` uses run criteria to only run after `Physics` has finished.
/// This set's criteria is to run only when _not done_, as specified via a resource.
/// The two systems here (collision, sfx) are not specified to run in any order, and the actual
/// ordering can then change between invocations.
///
/// Lastly a system with run criterion _done_ is used to exit the app.
fn main() {
App::new()
.add_plugins(DefaultPlugins)

View file

@ -1,3 +1,5 @@
//! Illustrates how `Timer`s can be used both as resources and components.
use bevy::{log::info, prelude::*};
fn main() {

View file

@ -1,3 +1,5 @@
//! Eat the cakes. Eat them all. An example 3D game.
use bevy::{core::FixedTimestep, ecs::schedule::SystemSet, prelude::*, render::camera::Camera3d};
use rand::Rng;
@ -268,12 +270,12 @@ fn focus_camera(
.translation
.lerp(bonus_transform.translation, 0.5);
}
// otherwise, if there is only a player, target the player
// 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
// otherwise, target the middle
} else {
game.camera_should_focus = Vec3::from(RESET_FOCUS);
}

View file

@ -1,4 +1,4 @@
//! A simplified implementation of the classic game "Breakout"
//! A simplified implementation of the classic game "Breakout".
use bevy::{
core::FixedTimestep,

View file

@ -1,3 +1,5 @@
//! This example displays each contributor to the bevy source code as a bouncing bevy-ball.
use bevy::{prelude::*, utils::HashSet};
use rand::{prelude::SliceRandom, Rng};
use std::{

View file

@ -1,8 +1,8 @@
use bevy::prelude::*;
//! 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.
// 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::rgb(0.9, 0.9, 0.9);

View file

@ -1,3 +1,5 @@
//! Prints out all chars as they are inputted.
use bevy::{prelude::*, window::ReceivedCharacter};
fn main() {

View file

@ -1,3 +1,5 @@
//! Shows handling of gamepad input, connections, and disconnections.
use bevy::{input::gamepad::GamepadButton, prelude::*};
fn main() {

View file

@ -1,3 +1,5 @@
//! Iterates and prints gamepad input and connection events.
use bevy::{
input::gamepad::{GamepadEvent, GamepadEventType},
prelude::*,

View file

@ -1,3 +1,5 @@
//! Demonstrates handling a key press/release.
use bevy::{
input::{keyboard::KeyCode, Input},
prelude::*,

View file

@ -1,3 +1,5 @@
//! Prints out all keyboard events.
use bevy::{input::keyboard::KeyboardInput, prelude::*};
fn main() {

View file

@ -1,3 +1,5 @@
//! Demonstrates using key modifiers (ctrl, shift).
use bevy::{
input::{keyboard::KeyCode, Input},
prelude::*,

View file

@ -1,3 +1,5 @@
//! Demonstrates how to grab and hide the mouse cursor.
use bevy::prelude::*;
fn main() {

View file

@ -1,3 +1,5 @@
//! Prints mouse button events.
use bevy::prelude::*;
fn main() {

View file

@ -1,3 +1,5 @@
//! Prints all mouse events to the console.
use bevy::{
input::mouse::{MouseButtonInput, MouseMotion, MouseWheel},
prelude::*,

View file

@ -1,3 +1,5 @@
//! Displays touch presses, releases, and cancels.
use bevy::{input::touch::*, prelude::*};
fn main() {

View file

@ -1,3 +1,5 @@
//! Prints out all touch inputs.
use bevy::{input::touch::*, prelude::*};
fn main() {

View file

@ -1,10 +1,12 @@
//! Demonstrates how reflection is used with generic Rust types.
use bevy::{prelude::*, reflect::TypeRegistry};
use std::any::TypeId;
/// You must manually register each instance of a generic type
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// You must manually register each instance of a generic type
.register_type::<MyType<u32>>()
.add_startup_system(setup)
.run();

View file

@ -1,3 +1,9 @@
//! Illustrates how "reflection" works in Bevy.
//!
//! Reflection provides a way to dynamically interact with Rust types, such as accessing fields
//! by their string name. Reflection is a core part of Bevy and enables a number of interesting
//! features (like scenes).
use bevy::{
prelude::*,
reflect::{
@ -7,9 +13,6 @@ use bevy::{
};
use serde::de::DeserializeSeed;
/// This example illustrates how "reflection" works in Bevy. Reflection provide a way to dynamically
/// interact with Rust types, such as accessing fields by their string name. Reflection is a core
/// part of Bevy and enables a number of interesting scenarios (like scenes).
fn main() {
App::new()
.add_plugins(DefaultPlugins)

View file

@ -1,3 +1,6 @@
//! This example illustrates how reflection works for simple data structures, like
//! structs, tuples and vectors.
use bevy::{
prelude::*,
reflect::{DynamicList, ReflectRef},
@ -5,7 +8,6 @@ use bevy::{
};
use serde::{Deserialize, Serialize};
/// This example illustrates the various reflection types available
fn main() {
App::new()
.add_plugins(DefaultPlugins)

View file

@ -1,3 +1,5 @@
//! Allows reflection with trait objects.
use bevy::{prelude::*, reflect::TypeRegistry};
fn main() {

View file

@ -1,6 +1,7 @@
//! This example illustrates loading scenes from files.
use bevy::{prelude::*, reflect::TypeRegistry, utils::Duration};
/// This example illustrates loading and saving scenes from files
fn main() {
App::new()
.add_plugins(DefaultPlugins)

View file

@ -1,3 +1,6 @@
//! Shows how to pass changing data like the time since startup into a shader, using a custom
//! specialized pipeline.
use bevy::{
core_pipeline::Transparent3d,
ecs::system::{lifetimeless::SRes, SystemParamItem},
@ -244,6 +247,7 @@ type DrawCustom = (
);
struct SetTimeBindGroup<const I: usize>;
impl<const I: usize> EntityRenderCommand for SetTimeBindGroup<I> {
type Param = SRes<TimeMeta>;

View file

@ -1,3 +1,8 @@
//! A compute shader simulating Conway's Game of Life.
//!
//! Compute shaders use the GPU for computing arbitrary information, that may be independent of what
//! is rendered to the screen.
use bevy::{
core_pipeline::node::MAIN_PASS_DEPENDENCIES,
prelude::*,
@ -77,6 +82,7 @@ impl Plugin for GameOfLifeComputePlugin {
#[derive(Deref)]
struct GameOfLifeImage(Handle<Image>);
struct GameOfLifeImageBindGroup(BindGroup);
fn extract_game_of_life_image(mut commands: Commands, image: Res<GameOfLifeImage>) {

View file

@ -1,3 +1,5 @@
//! Illustrates creating a custom shader material that reads a mesh's custom vertex attribute.
use bevy::{
ecs::system::{lifetimeless::SRes, SystemParamItem},
pbr::MaterialPipeline,

View file

@ -1,3 +1,6 @@
//! Demonstrates creating a custom material that uses "shaders defs", a tool that enables
//! conditional compilation in shaders.
use bevy::{
core_pipeline::Transparent3d,
pbr::{

View file

@ -1,3 +1,5 @@
//! A custom shader showing off rendering a mesh multiple times in one draw call.
use bevy::{
core_pipeline::Transparent3d,
ecs::system::{lifetimeless::*, SystemParamItem},
@ -64,6 +66,7 @@ fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
#[derive(Component, Deref)]
struct InstanceMaterialData(Vec<InstanceData>);
impl ExtractComponent for InstanceMaterialData {
type Query = &'static InstanceMaterialData;
type Filter = ();
@ -226,6 +229,7 @@ type DrawCustom = (
);
pub struct DrawMeshInstanced;
impl EntityRenderCommand for DrawMeshInstanced {
type Param = (
SRes<RenderAssets<Mesh>>,

View file

@ -1,3 +1,5 @@
//! Illustrates creating a custom material and a shader that uses it.
use bevy::{
ecs::system::{lifetimeless::SRes, SystemParamItem},
pbr::MaterialPipeline,

View file

@ -1,3 +1,5 @@
//! A custom shader using the GLSL shading language.
use bevy::{
ecs::system::{lifetimeless::SRes, SystemParamItem},
pbr::{MaterialPipeline, SpecializedMaterial},

View file

@ -1,3 +1,5 @@
//! A custom shader sampling a texture with view-independent UV coordinates.
use bevy::{
ecs::system::{lifetimeless::SRes, SystemParamItem},
pbr::MaterialPipeline,

View file

@ -1,3 +1,7 @@
//! This example provides a 2D benchmark.
//!
//! Usage: spawn more entities by clicking on the screen.
use bevy::{
core::FixedTimestep,
diagnostic::{Diagnostics, FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin},
@ -22,9 +26,6 @@ struct Bird {
velocity: Vec3,
}
/// This example provides a 2D benchmark.
///
/// Usage: spawn more entities by clicking on the screen.
fn main() {
App::new()
.insert_resource(WindowDescriptor {

View file

@ -1,8 +1,21 @@
//! Simple benchmark to test per-entity draw overhead.
//!
//! To measure performance realistically, be sure to run this in release mode.
//! `cargo run --example many_cubes --release`
//!
//! By default, this arranges the meshes in a cubical pattern, where the number of visible meshes
//! varies with the viewing angle. You can choose to run the demo with a spherical pattern that
//! distributes the meshes evenly.
//!
//! To start the demo using the spherical layout run
//! `cargo run --example many_cubes --release sphere`
use bevy::{
diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin},
math::{DVec2, DVec3},
prelude::*,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
@ -119,6 +132,7 @@ fn setup(
// http://extremelearning.com.au/how-to-evenly-distribute-points-on-a-sphere-more-effectively-than-the-canonical-fibonacci-lattice/
// for details.
const EPSILON: f64 = 0.36;
fn fibonacci_spiral_on_sphere(golden_ratio: f64, i: usize, n: usize) -> DVec2 {
DVec2::new(
2.0 * std::f64::consts::PI * (i as f64 / golden_ratio),

Some files were not shown because too many files have changed in this diff Show more