pub enum Color {
Srgba(Srgba),
LinearRgba(LinearRgba),
Hsla(Hsla),
Hsva(Hsva),
Hwba(Hwba),
Laba(Laba),
Lcha(Lcha),
Oklaba(Oklaba),
Oklcha(Oklcha),
Xyza(Xyza),
}
Expand description
An enumerated type that can represent any of the color types in this crate.
This is useful when you need to store a color in a data structure that can’t be generic over the color type.
§Conversion
Conversion between the various color spaces is achieved using Rust’s native From trait. Because certain color spaces are defined by their transformation to and from another space, these From implementations reflect that set of definitions.
let color = Srgba::rgb(0.5, 0.5, 0.5);
// Using From explicitly
let linear_color = LinearRgba::from(color);
// Using Into
let linear_color: LinearRgba = color.into();
For example, the sRGB space is defined by its relationship with Linear RGB, and HWB by its with sRGB. As such, it is the responsibility of sRGB to provide From implementations for Linear RGB, and HWB for sRGB. To then provide conversion between Linear RGB and HWB directly, HWB is responsible for implementing these conversions, delegating to sRGB as an intermediatory. This ensures that all conversions take the shortest path between any two spaces, and limit the proliferation of domain specific knowledge for each color space to their respective definitions.
§Operations
Color
supports all the standard color operations, such as mixing,
luminance and hue adjustment,
and diffing. These operations delegate to the concrete color space contained
by Color
, but will convert to Oklch
for operations which aren’t supported in the
current space. After performing the operation, if a conversion was required, the result will be
converted back into the original color space.
let red_hsv = Color::hsv(0., 1., 1.);
let red_srgb = Color::srgb(1., 0., 0.);
// HSV has a definition of hue, so it will be returned.
red_hsv.hue();
// SRGB doesn't have a native definition for hue.
// Converts to Oklch and returns that result.
red_srgb.hue();
Oklch
has been chosen as the intermediary space in cases where conversion is required
due to its perceptual uniformity and broad support for Bevy’s color operations.
To avoid the cost of repeated conversion, and ensure consistent results where that is desired,
first convert this Color
into your desired color space.
Variants§
Srgba(Srgba)
A color in the sRGB color space with alpha.
LinearRgba(LinearRgba)
A color in the linear sRGB color space with alpha.
Hsla(Hsla)
A color in the HSL color space with alpha.
Hsva(Hsva)
A color in the HSV color space with alpha.
Hwba(Hwba)
A color in the HWB color space with alpha.
Laba(Laba)
A color in the LAB color space with alpha.
Lcha(Lcha)
A color in the LCH color space with alpha.
Oklaba(Oklaba)
A color in the Oklab color space with alpha.
Oklcha(Oklcha)
A color in the Oklch color space with alpha.
Xyza(Xyza)
A color in the XYZ color space with alpha.
Implementations§
Source§impl Color
impl Color
Sourcepub const WHITE: Color
pub const WHITE: Color
A fully white Color::LinearRgba
color with an alpha of 1.0.
Sourcepub const BLACK: Color
pub const BLACK: Color
A fully black Color::LinearRgba
color with an alpha of 1.0.
Sourcepub const NONE: Color
pub const NONE: Color
A fully transparent Color::LinearRgba
color with 0 red, green and blue.
Sourcepub fn to_linear(&self) -> LinearRgba
pub fn to_linear(&self) -> LinearRgba
Return the color as a linear RGBA color.
Examples found in repository?
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
fn animate(
mut materials: ResMut<Assets<CustomUiMaterial>>,
q: Query<&MaterialNode<CustomUiMaterial>>,
time: Res<Time>,
) {
let duration = 2.0;
for handle in &q {
if let Some(material) = materials.get_mut(handle) {
// rainbow color effect
let new_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 1., 0.5);
let border_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 0.75, 0.75);
material.color = new_color.to_linear().to_vec4();
material.slider =
((time.elapsed_secs() % (duration * 2.0)) - duration).abs() / duration;
material.border_color = border_color.to_linear().to_vec4();
}
}
}
Sourcepub fn to_srgba(&self) -> Srgba
pub fn to_srgba(&self) -> Srgba
Return the color as an SRGBA color.
Examples found in repository?
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
fn update_colors(
keyboard_input: Res<ButtonInput<KeyCode>>,
mut config: ResMut<Wireframe2dConfig>,
mut wireframe_colors: Query<&mut Wireframe2dColor>,
mut text: Single<&mut Text>,
) {
text.0 = format!(
"Controls
---------------
Z - Toggle global
X - Change global color
C - Change color of the circle wireframe
Wireframe2dConfig
-------------
Global: {}
Color: {:?}",
config.global,
config.default_color.to_srgba(),
);
// Toggle showing a wireframe on all meshes
if keyboard_input.just_pressed(KeyCode::KeyZ) {
config.global = !config.global;
}
// Toggle the global wireframe color
if keyboard_input.just_pressed(KeyCode::KeyX) {
config.default_color = if config.default_color == WHITE.into() {
RED.into()
} else {
WHITE.into()
};
}
// Toggle the color of a wireframe using `Wireframe2dColor` and not the global color
if keyboard_input.just_pressed(KeyCode::KeyC) {
for mut color in &mut wireframe_colors {
color.color = if color.color == GREEN.into() {
RED.into()
} else {
GREEN.into()
};
}
}
}
Sourcepub const fn rgba(red: f32, green: f32, blue: f32, alpha: f32) -> Color
👎Deprecated: Use Color::srgba
instead
pub const fn rgba(red: f32, green: f32, blue: f32, alpha: f32) -> Color
Color::srgba
insteadSourcepub const fn srgba(red: f32, green: f32, blue: f32, alpha: f32) -> Color
pub const fn srgba(red: f32, green: f32, blue: f32, alpha: f32) -> Color
Examples found in repository?
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
fn spawn_coated_glass_bubble_sphere(
commands: &mut Commands,
materials: &mut Assets<StandardMaterial>,
sphere: &Handle<Mesh>,
) {
commands
.spawn((
Mesh3d(sphere.clone()),
MeshMaterial3d(materials.add(StandardMaterial {
clearcoat: 1.0,
clearcoat_perceptual_roughness: 0.1,
metallic: 0.5,
perceptual_roughness: 0.1,
base_color: Color::srgba(0.9, 0.9, 0.9, 0.3),
alpha_mode: AlphaMode::Blend,
..default()
})),
Transform::from_xyz(-1.0, -1.0, 0.0).with_scale(Vec3::splat(SPHERE_SCALE)),
))
.insert(ExampleSphere);
}
More examples
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
let sprite_handle = asset_server.load("branding/icon.png");
commands.spawn(Sprite::from_image(sprite_handle.clone()));
commands.spawn((
Sprite {
image: sprite_handle.clone(),
// Alpha channel of the color controls transparency.
color: Color::srgba(0.0, 0.0, 1.0, 0.7),
..default()
},
Transform::from_xyz(100.0, 0.0, 0.0),
));
commands.spawn((
Sprite {
image: sprite_handle,
color: Color::srgba(0.0, 1.0, 0.0, 0.3),
..default()
},
Transform::from_xyz(200.0, 0.0, 0.0),
));
}
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
fn setup_camera_fog(mut commands: Commands) {
commands.spawn((
Camera3d::default(),
Transform::from_xyz(-1.0, 0.1, 1.0).looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y),
DistanceFog {
color: Color::srgba(0.35, 0.48, 0.66, 1.0),
directional_light_color: Color::srgba(1.0, 0.95, 0.85, 0.5),
directional_light_exponent: 30.0,
falloff: FogFalloff::from_visibility_colors(
15.0, // distance in world units up to which objects retain visibility (>= 5% contrast)
Color::srgb(0.35, 0.5, 0.66), // atmospheric extinction color (after light is lost due to absorption by atmospheric particles)
Color::srgb(0.8, 0.844, 1.0), // atmospheric inscattering color (light gained due to scattering from the sun)
),
},
));
}
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// load a texture and retrieve its aspect ratio
let texture_handle = asset_server.load("branding/bevy_logo_dark_big.png");
let aspect = 0.25;
// create a new quad mesh. this is what we will apply the texture to
let quad_width = 8.0;
let quad_handle = meshes.add(Rectangle::new(quad_width, quad_width * aspect));
// this material renders the texture normally
let material_handle = materials.add(StandardMaterial {
base_color_texture: Some(texture_handle.clone()),
alpha_mode: AlphaMode::Blend,
unlit: true,
..default()
});
// this material modulates the texture to make it red (and slightly transparent)
let red_material_handle = materials.add(StandardMaterial {
base_color: Color::srgba(1.0, 0.0, 0.0, 0.5),
base_color_texture: Some(texture_handle.clone()),
alpha_mode: AlphaMode::Blend,
unlit: true,
..default()
});
// and lets make this one blue! (and also slightly transparent)
let blue_material_handle = materials.add(StandardMaterial {
base_color: Color::srgba(0.0, 0.0, 1.0, 0.5),
base_color_texture: Some(texture_handle),
alpha_mode: AlphaMode::Blend,
unlit: true,
..default()
});
// textured quad - normal
commands.spawn((
Mesh3d(quad_handle.clone()),
MeshMaterial3d(material_handle),
Transform::from_xyz(0.0, 0.0, 1.5).with_rotation(Quat::from_rotation_x(-PI / 5.0)),
));
// textured quad - modulated
commands.spawn((
Mesh3d(quad_handle.clone()),
MeshMaterial3d(red_material_handle),
Transform::from_rotation(Quat::from_rotation_x(-PI / 5.0)),
));
// textured quad - modulated
commands.spawn((
Mesh3d(quad_handle),
MeshMaterial3d(blue_material_handle),
Transform::from_xyz(0.0, 0.0, -1.5).with_rotation(Quat::from_rotation_x(-PI / 5.0)),
));
// camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(3.0, 5.0, 8.0).looking_at(Vec3::ZERO, Vec3::Y),
));
}
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
let font_handle = asset_server.load("fonts/FiraSans-Bold.ttf");
commands
.spawn(Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
align_items: AlignItems::Center,
justify_content: JustifyContent::SpaceAround,
..default()
})
.with_children(|parent| {
parent
.spawn((
Button,
Node {
width: Val::Px(150.0),
height: Val::Px(65.0),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(Color::srgb(0.1, 0.5, 0.1)),
))
.with_children(|parent| {
parent.spawn((
Text::new("Button 1"),
TextFont {
font: font_handle.clone(),
font_size: 33.0,
..default()
},
// Alpha channel of the color controls transparency.
TextColor(Color::srgba(1.0, 1.0, 1.0, 0.2)),
));
});
// Button with a different color,
// to demonstrate the text looks different due to its transparency.
parent
.spawn((
Button,
Node {
width: Val::Px(150.0),
height: Val::Px(65.0),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(Color::srgb(0.5, 0.1, 0.5)),
))
.with_children(|parent| {
parent.spawn((
Text::new("Button 2"),
TextFont {
font: font_handle.clone(),
font_size: 33.0,
..default()
},
// Alpha channel of the color controls transparency.
TextColor(Color::srgba(1.0, 1.0, 1.0, 0.2)),
));
});
});
}
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// Use seeded rng and store it in a resource; this makes the random output reproducible.
let seeded_rng = ChaCha8Rng::seed_from_u64(19878367467712);
commands.insert_resource(RandomSource(seeded_rng));
// Make a plane for establishing space.
commands.spawn((
Mesh3d(meshes.add(Plane3d::default().mesh().size(12.0, 12.0))),
MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
Transform::from_xyz(0.0, -2.5, 0.0),
));
// Store the shape we sample from in a resource:
let shape = Cuboid::from_length(2.9);
commands.insert_resource(SampledShape(shape));
// The sampled shape shown transparently:
commands.spawn((
Mesh3d(meshes.add(shape)),
MeshMaterial3d(materials.add(StandardMaterial {
base_color: Color::srgba(0.2, 0.1, 0.6, 0.3),
alpha_mode: AlphaMode::Blend,
cull_mode: None,
..default()
})),
));
// A light:
commands.spawn((
PointLight {
shadows_enabled: true,
..default()
},
Transform::from_xyz(4.0, 8.0, 4.0),
));
// A camera:
commands.spawn((
Camera3d::default(),
Transform::from_xyz(-2.0, 3.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
));
// Store the mesh and material for sample points in resources:
commands.insert_resource(PointMesh(
meshes.add(
Sphere::new(0.03)
.mesh()
.kind(SphereKind::Ico { subdivisions: 3 }),
),
));
commands.insert_resource(PointMaterial(materials.add(StandardMaterial {
base_color: Color::srgb(1.0, 0.8, 0.8),
metallic: 0.8,
..default()
})));
// Instructions for the example:
commands.spawn((
Text::new(
"Controls:\n\
M: Toggle between sampling boundary and interior.\n\
R: Restart (erase all samples).\n\
S: Add one random sample.\n\
D: Add 100 random samples.\n\
Rotate camera by holding left mouse and panning left/right.",
),
Node {
position_type: PositionType::Absolute,
top: Val::Px(12.0),
left: Val::Px(12.0),
..default()
},
));
// The mode starts with interior points.
commands.insert_resource(Mode::Interior);
// Starting mouse-pressed state is false.
commands.insert_resource(MousePressed(false));
}
Sourcepub const fn rgb(red: f32, green: f32, blue: f32) -> Color
👎Deprecated: Use Color::srgb
instead
pub const fn rgb(red: f32, green: f32, blue: f32) -> Color
Color::srgb
insteadSourcepub const fn srgb(red: f32, green: f32, blue: f32) -> Color
pub const fn srgb(red: f32, green: f32, blue: f32) -> Color
Examples found in repository?
More examples
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
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,
))
.with_children(|parent| {
parent.spawn((
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,
))
.with_children(|parent| {
// First create a `Node` for centering what we want to display
parent
.spawn((
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),
))
.with_children(|p| {
p.spawn((
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()
},
));
p.spawn((
Text::default(),
Node {
margin: UiRect::all(Val::Px(50.0)),
..default()
},
))
.with_children(|p| {
p.spawn((
TextSpan(format!("quality: {:?}", *display_quality)),
TextFont {
font_size: 50.0,
..default()
},
TextColor(BLUE.into()),
));
p.spawn((
TextSpan::new(" - "),
TextFont {
font_size: 50.0,
..default()
},
TextColor(TEXT_COLOR),
));
p.spawn((
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, 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);
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
const SKY_COLOR: Color = Color::srgb(0.02, 0.06, 0.15);
const SMALL_3D: f32 = 0.5;
const BIG_3D: f32 = 1.0;
// primitives
const CUBOID: Cuboid = Cuboid {
half_size: Vec3::new(SMALL_3D, BIG_3D, SMALL_3D),
};
const SPHERE: Sphere = Sphere {
radius: 1.5 * SMALL_3D,
};
const TRIANGLE_3D: Triangle3d = Triangle3d {
vertices: [
Vec3::new(BIG_3D, -BIG_3D * 0.5, 0.0),
Vec3::new(0.0, BIG_3D, 0.0),
Vec3::new(-BIG_3D, -BIG_3D * 0.5, 0.0),
],
};
const CAPSULE_3D: Capsule3d = Capsule3d {
radius: SMALL_3D,
half_length: SMALL_3D,
};
const CYLINDER: Cylinder = Cylinder {
radius: SMALL_3D,
half_height: SMALL_3D,
};
const TETRAHEDRON: Tetrahedron = Tetrahedron {
vertices: [
Vec3::new(-BIG_3D, -BIG_3D * 0.67, BIG_3D * 0.5),
Vec3::new(BIG_3D, -BIG_3D * 0.67, BIG_3D * 0.5),
Vec3::new(0.0, -BIG_3D * 0.67, -BIG_3D * 1.17),
Vec3::new(0.0, BIG_3D, 0.0),
],
};
// Components, Resources
/// Resource for the random sampling mode, telling whether to sample the interior or the boundary.
#[derive(Resource)]
enum SamplingMode {
Interior,
Boundary,
}
/// Resource for storing whether points should spawn by themselves
#[derive(Resource)]
enum SpawningMode {
Manual,
Automatic,
}
/// Resource for tracking how many points should be spawned
#[derive(Resource)]
struct SpawnQueue(usize);
#[derive(Resource)]
struct PointCounter(usize);
/// Resource storing the shapes being sampled and their translations.
#[derive(Resource)]
struct SampledShapes(Vec<(Shape, Vec3)>);
impl SampledShapes {
fn new() -> Self {
let shapes = Shape::list_all_shapes();
let n_shapes = shapes.len();
let translations =
(0..n_shapes).map(|i| (i as f32 - n_shapes as f32 / 2.0) * DISTANCE_BETWEEN_SHAPES);
SampledShapes(shapes.into_iter().zip(translations).collect())
}
}
/// Enum listing the shapes that can be sampled
#[derive(Clone, Copy)]
enum Shape {
Cuboid,
Sphere,
Capsule,
Cylinder,
Tetrahedron,
Triangle,
}
struct ShapeMeshBuilder {
shape: Shape,
}
impl Shape {
/// Return a vector containing all implemented shapes
fn list_all_shapes() -> Vec<Shape> {
vec![
Shape::Cuboid,
Shape::Sphere,
Shape::Capsule,
Shape::Cylinder,
Shape::Tetrahedron,
Shape::Triangle,
]
}
}
impl ShapeSample for Shape {
type Output = Vec3;
fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec3 {
match self {
Shape::Cuboid => CUBOID.sample_interior(rng),
Shape::Sphere => SPHERE.sample_interior(rng),
Shape::Capsule => CAPSULE_3D.sample_interior(rng),
Shape::Cylinder => CYLINDER.sample_interior(rng),
Shape::Tetrahedron => TETRAHEDRON.sample_interior(rng),
Shape::Triangle => TRIANGLE_3D.sample_interior(rng),
}
}
fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output {
match self {
Shape::Cuboid => CUBOID.sample_boundary(rng),
Shape::Sphere => SPHERE.sample_boundary(rng),
Shape::Capsule => CAPSULE_3D.sample_boundary(rng),
Shape::Cylinder => CYLINDER.sample_boundary(rng),
Shape::Tetrahedron => TETRAHEDRON.sample_boundary(rng),
Shape::Triangle => TRIANGLE_3D.sample_boundary(rng),
}
}
}
impl Meshable for Shape {
type Output = ShapeMeshBuilder;
fn mesh(&self) -> Self::Output {
ShapeMeshBuilder { shape: *self }
}
}
impl MeshBuilder for ShapeMeshBuilder {
fn build(&self) -> Mesh {
match self.shape {
Shape::Cuboid => CUBOID.mesh().into(),
Shape::Sphere => SPHERE.mesh().into(),
Shape::Capsule => CAPSULE_3D.mesh().into(),
Shape::Cylinder => CYLINDER.mesh().into(),
Shape::Tetrahedron => TETRAHEDRON.mesh().into(),
Shape::Triangle => TRIANGLE_3D.mesh().into(),
}
}
}
/// The source of randomness used by this example.
#[derive(Resource)]
struct RandomSource(ChaCha8Rng);
/// A container for the handle storing the mesh used to display sampled points as spheres.
#[derive(Resource)]
struct PointMesh(Handle<Mesh>);
/// A container for the handle storing the material used to display sampled points.
#[derive(Resource)]
struct PointMaterial {
interior: Handle<StandardMaterial>,
boundary: Handle<StandardMaterial>,
}
/// Marker component for sampled points.
#[derive(Component)]
struct SamplePoint;
/// Component for animating the spawn animation of lights.
#[derive(Component)]
struct SpawningPoint {
progress: f32,
}
/// Marker component for lights which should change intensity.
#[derive(Component)]
struct DespawningPoint {
progress: f32,
}
/// Marker component for lights which should change intensity.
#[derive(Component)]
struct FireflyLights;
/// The pressed state of the mouse, used for camera motion.
#[derive(Resource)]
struct MousePressed(bool);
/// Camera movement component.
#[derive(Component)]
struct CameraRig {
/// Rotation around the vertical axis of the camera (radians).
/// Positive changes makes the camera look more from the right.
pub yaw: f32,
/// Rotation around the horizontal axis of the camera (radians) (-pi/2; pi/2).
/// Positive looks down from above.
pub pitch: f32,
/// Distance from the center, smaller distance causes more zoom.
pub distance: f32,
/// Location in 3D space at which the camera is looking and around which it is orbiting.
pub target: Vec3,
}
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
shapes: Res<SampledShapes>,
) {
// Use seeded rng and store it in a resource; this makes the random output reproducible.
let seeded_rng = ChaCha8Rng::seed_from_u64(4); // Chosen by a fair die roll, guaranteed to be random.
commands.insert_resource(RandomSource(seeded_rng));
// Make a plane for establishing space.
commands.spawn((
Mesh3d(meshes.add(Plane3d::default().mesh().size(20.0, 20.0))),
MeshMaterial3d(materials.add(StandardMaterial {
base_color: Color::srgb(0.3, 0.5, 0.3),
perceptual_roughness: 0.95,
metallic: 0.0,
..default()
})),
Transform::from_xyz(0.0, -2.5, 0.0),
));
let shape_material = materials.add(StandardMaterial {
base_color: Color::srgba(0.2, 0.1, 0.6, 0.3),
reflectance: 0.0,
alpha_mode: AlphaMode::Blend,
cull_mode: None,
..default()
});
// Spawn shapes to be sampled
for (shape, translation) in shapes.0.iter() {
// The sampled shape shown transparently:
commands.spawn((
Mesh3d(meshes.add(shape.mesh())),
MeshMaterial3d(shape_material.clone()),
Transform::from_translation(*translation),
));
// Lights which work as the bulk lighting of the fireflies:
commands.spawn((
PointLight {
range: 4.0,
radius: 0.6,
intensity: 1.0,
shadows_enabled: false,
color: Color::LinearRgba(INSIDE_POINT_COLOR),
..default()
},
Transform::from_translation(*translation),
FireflyLights,
));
}
// Global light:
commands.spawn((
PointLight {
color: SKY_COLOR,
intensity: 2_000.0,
shadows_enabled: false,
..default()
},
Transform::from_xyz(4.0, 8.0, 4.0),
));
// A camera:
commands.spawn((
Camera3d::default(),
Camera {
hdr: true, // HDR is required for bloom
clear_color: ClearColorConfig::Custom(SKY_COLOR),
..default()
},
Tonemapping::TonyMcMapface,
Transform::from_xyz(-2.0, 3.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
Bloom::NATURAL,
CameraRig {
yaw: 0.56,
pitch: 0.45,
distance: 8.0,
target: Vec3::ZERO,
},
));
// Store the mesh and material for sample points in resources:
commands.insert_resource(PointMesh(
meshes.add(Sphere::new(0.03).mesh().ico(1).unwrap()),
));
commands.insert_resource(PointMaterial {
interior: materials.add(StandardMaterial {
base_color: Color::BLACK,
reflectance: 0.05,
emissive: 2.5 * INSIDE_POINT_COLOR,
..default()
}),
boundary: materials.add(StandardMaterial {
base_color: Color::BLACK,
reflectance: 0.05,
emissive: 1.5 * BOUNDARY_POINT_COLOR,
..default()
}),
});
// Instructions for the example:
commands.spawn((
Text::new(
"Controls:\n\
M: Toggle between sampling boundary and interior.\n\
A: Toggle automatic spawning & despawning of points.\n\
R: Restart (erase all samples).\n\
S: Add one random sample.\n\
D: Add 100 random samples.\n\
Rotate camera by holding left mouse and panning.\n\
Zoom camera by scrolling via mouse or +/-.\n\
Move camera by L/R arrow keys.\n\
Tab: Toggle this text",
),
Node {
position_type: PositionType::Absolute,
top: Val::Px(12.0),
left: Val::Px(12.0),
..default()
},
));
// No points are scheduled to spawn initially.
commands.insert_resource(SpawnQueue(0));
// No points have been spawned initially.
commands.insert_resource(PointCounter(0));
// The mode starts with interior points.
commands.insert_resource(SamplingMode::Interior);
// Points spawn automatically by default.
commands.insert_resource(SpawningMode::Automatic);
// Starting mouse-pressed state is false.
commands.insert_resource(MousePressed(false));
}
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
const HIDDEN_COLOR: Color = Color::srgb(1.0, 0.7, 0.7);
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// Only run the app when there is user input. This will significantly reduce CPU/GPU use.
.insert_resource(WinitSettings::desktop_app())
.add_systems(Startup, setup)
.add_systems(
Update,
(
buttons_handler::<Display>,
buttons_handler::<Visibility>,
text_hover,
),
)
.run();
}
#[derive(Component)]
struct Target<T> {
id: Entity,
phantom: std::marker::PhantomData<T>,
}
impl<T> Target<T> {
fn new(id: Entity) -> Self {
Self {
id,
phantom: std::marker::PhantomData,
}
}
}
trait TargetUpdate {
type TargetComponent: Component;
const NAME: &'static str;
fn update_target(&self, target: &mut Self::TargetComponent) -> String;
}
impl TargetUpdate for Target<Display> {
type TargetComponent = Node;
const NAME: &'static str = "Display";
fn update_target(&self, node: &mut Self::TargetComponent) -> String {
node.display = match node.display {
Display::Flex => Display::None,
Display::None => Display::Flex,
Display::Block | Display::Grid => unreachable!(),
};
format!("{}::{:?} ", Self::NAME, node.display)
}
}
impl TargetUpdate for Target<Visibility> {
type TargetComponent = Visibility;
const NAME: &'static str = "Visibility";
fn update_target(&self, visibility: &mut Self::TargetComponent) -> String {
*visibility = match *visibility {
Visibility::Inherited => Visibility::Visible,
Visibility::Visible => Visibility::Hidden,
Visibility::Hidden => Visibility::Inherited,
};
format!("{}::{visibility:?}", Self::NAME)
}
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let palette: [Color; 4] = PALETTE.map(|hex| Srgba::hex(hex).unwrap().into());
let text_font = TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
..default()
};
commands.spawn(Camera2d);
commands
.spawn((
Node {
width: Val::Percent(100.),
height: Val::Percent(100.),
flex_direction: FlexDirection::Column,
align_items: AlignItems::Center,
justify_content: JustifyContent::SpaceEvenly,
..Default::default()
},
BackgroundColor(Color::BLACK),
))
.with_children(|parent| {
parent.spawn((
Text::new("Use the panel on the right to change the Display and Visibility properties for the respective nodes of the panel on the left"),
text_font.clone(),
TextLayout::new_with_justify(JustifyText::Center),
Node {
margin: UiRect::bottom(Val::Px(10.)),
..Default::default()
},
));
parent
.spawn(Node {
width: Val::Percent(100.),
..default()
})
.with_children(|parent| {
let mut target_ids = vec![];
parent
.spawn(Node {
width: Val::Percent(50.),
height: Val::Px(520.),
justify_content: JustifyContent::Center,
..default()
})
.with_children(|parent| {
target_ids = spawn_left_panel(parent, &palette);
});
parent
.spawn(Node {
width: Val::Percent(50.),
justify_content: JustifyContent::Center,
..default()
})
.with_children(|parent| {
spawn_right_panel(parent, text_font, &palette, target_ids);
});
});
parent
.spawn(Node {
flex_direction: FlexDirection::Row,
align_items: AlignItems::Start,
justify_content: JustifyContent::Start,
column_gap: Val::Px(10.),
..default()
})
.with_children(|builder| {
let text_font = TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
..default()
};
builder.spawn((
Text::new("Display::None\nVisibility::Hidden\nVisibility::Inherited"),
text_font.clone(),
TextColor(HIDDEN_COLOR),
TextLayout::new_with_justify(JustifyText::Center),
));
builder.spawn((
Text::new("-\n-\n-"),
text_font.clone(),
TextColor(DARK_GRAY.into()),
TextLayout::new_with_justify(JustifyText::Center),
));
builder.spawn((Text::new("The UI Node and its descendants will not be visible and will not be allotted any space in the UI layout.\nThe UI Node will not be visible but will still occupy space in the UI layout.\nThe UI node will inherit the visibility property of its parent. If it has no parent it will be visible."), text_font));
});
});
}
fn spawn_left_panel(builder: &mut ChildBuilder, palette: &[Color; 4]) -> Vec<Entity> {
let mut target_ids = vec![];
builder
.spawn((
Node {
padding: UiRect::all(Val::Px(10.)),
..default()
},
BackgroundColor(Color::WHITE),
))
.with_children(|parent| {
parent
.spawn((Node::default(), BackgroundColor(Color::BLACK)))
.with_children(|parent| {
let id = parent
.spawn((
Node {
align_items: AlignItems::FlexEnd,
justify_content: JustifyContent::FlexEnd,
..default()
},
BackgroundColor(palette[0]),
Outline {
width: Val::Px(4.),
color: DARK_CYAN.into(),
offset: Val::Px(10.),
},
))
.with_children(|parent| {
parent.spawn(Node {
width: Val::Px(100.),
height: Val::Px(500.),
..default()
});
let id = parent
.spawn((
Node {
height: Val::Px(400.),
align_items: AlignItems::FlexEnd,
justify_content: JustifyContent::FlexEnd,
..default()
},
BackgroundColor(palette[1]),
))
.with_children(|parent| {
parent.spawn(Node {
width: Val::Px(100.),
height: Val::Px(400.),
..default()
});
let id = parent
.spawn((
Node {
height: Val::Px(300.),
align_items: AlignItems::FlexEnd,
justify_content: JustifyContent::FlexEnd,
..default()
},
BackgroundColor(palette[2]),
))
.with_children(|parent| {
parent.spawn(Node {
width: Val::Px(100.),
height: Val::Px(300.),
..default()
});
let id = parent
.spawn((
Node {
width: Val::Px(200.),
height: Val::Px(200.),
..default()
},
BackgroundColor(palette[3]),
))
.id();
target_ids.push(id);
})
.id();
target_ids.push(id);
})
.id();
target_ids.push(id);
})
.id();
target_ids.push(id);
});
});
target_ids
}
fn spawn_right_panel(
parent: &mut ChildBuilder,
text_font: TextFont,
palette: &[Color; 4],
mut target_ids: Vec<Entity>,
) {
let spawn_buttons = |parent: &mut ChildBuilder, target_id| {
spawn_button::<Display>(parent, text_font.clone(), target_id);
spawn_button::<Visibility>(parent, text_font.clone(), target_id);
};
parent
.spawn((
Node {
padding: UiRect::all(Val::Px(10.)),
..default()
},
BackgroundColor(Color::WHITE),
))
.with_children(|parent| {
parent
.spawn((
Node {
width: Val::Px(500.),
height: Val::Px(500.),
flex_direction: FlexDirection::Column,
align_items: AlignItems::FlexEnd,
justify_content: JustifyContent::SpaceBetween,
padding: UiRect {
left: Val::Px(5.),
top: Val::Px(5.),
..default()
},
..default()
},
BackgroundColor(palette[0]),
Outline {
width: Val::Px(4.),
color: DARK_CYAN.into(),
offset: Val::Px(10.),
},
))
.with_children(|parent| {
spawn_buttons(parent, target_ids.pop().unwrap());
parent
.spawn((
Node {
width: Val::Px(400.),
height: Val::Px(400.),
flex_direction: FlexDirection::Column,
align_items: AlignItems::FlexEnd,
justify_content: JustifyContent::SpaceBetween,
padding: UiRect {
left: Val::Px(5.),
top: Val::Px(5.),
..default()
},
..default()
},
BackgroundColor(palette[1]),
))
.with_children(|parent| {
spawn_buttons(parent, target_ids.pop().unwrap());
parent
.spawn((
Node {
width: Val::Px(300.),
height: Val::Px(300.),
flex_direction: FlexDirection::Column,
align_items: AlignItems::FlexEnd,
justify_content: JustifyContent::SpaceBetween,
padding: UiRect {
left: Val::Px(5.),
top: Val::Px(5.),
..default()
},
..default()
},
BackgroundColor(palette[2]),
))
.with_children(|parent| {
spawn_buttons(parent, target_ids.pop().unwrap());
parent
.spawn((
Node {
width: Val::Px(200.),
height: Val::Px(200.),
align_items: AlignItems::FlexStart,
justify_content: JustifyContent::SpaceBetween,
flex_direction: FlexDirection::Column,
padding: UiRect {
left: Val::Px(5.),
top: Val::Px(5.),
..default()
},
..default()
},
BackgroundColor(palette[3]),
))
.with_children(|parent| {
spawn_buttons(parent, target_ids.pop().unwrap());
parent.spawn(Node {
width: Val::Px(100.),
height: Val::Px(100.),
..default()
});
});
});
});
});
});
}
fn spawn_button<T>(parent: &mut ChildBuilder, text_font: TextFont, target: Entity)
where
T: Default + std::fmt::Debug + Send + Sync + 'static,
Target<T>: TargetUpdate,
{
parent
.spawn((
Button,
Node {
align_self: AlignSelf::FlexStart,
padding: UiRect::axes(Val::Px(5.), Val::Px(1.)),
..default()
},
BackgroundColor(Color::BLACK.with_alpha(0.5)),
Target::<T>::new(target),
))
.with_children(|builder| {
builder.spawn((
Text(format!("{}::{:?}", Target::<T>::NAME, T::default())),
text_font,
TextLayout::new_with_justify(JustifyText::Center),
));
});
}
fn buttons_handler<T>(
mut left_panel_query: Query<&mut <Target<T> as TargetUpdate>::TargetComponent>,
mut visibility_button_query: Query<(&Target<T>, &Interaction, &Children), Changed<Interaction>>,
mut text_query: Query<(&mut Text, &mut TextColor)>,
) where
T: Send + Sync,
Target<T>: TargetUpdate + Component,
{
for (target, interaction, children) in visibility_button_query.iter_mut() {
if matches!(interaction, Interaction::Pressed) {
let mut target_value = left_panel_query.get_mut(target.id).unwrap();
for &child in children {
if let Ok((mut text, mut text_color)) = text_query.get_mut(child) {
**text = target.update_target(target_value.as_mut());
text_color.0 = if text.contains("None") || text.contains("Hidden") {
Color::srgb(1.0, 0.7, 0.7)
} else {
Color::WHITE
};
}
}
}
}
}
- examples/state/custom_transitions.rs
- examples/state/states.rs
- examples/ui/button.rs
- examples/games/desk_toy.rs
- examples/ui/flex_layout.rs
- examples/ui/size_constraints.rs
- examples/state/computed_states.rs
- examples/state/sub_states.rs
- examples/window/clear_color.rs
- examples/3d/fog.rs
- examples/ecs/removal_detection.rs
- examples/math/cubic_splines.rs
- examples/async_tasks/async_compute.rs
- examples/ui/text.rs
- examples/ui/ghost_nodes.rs
- examples/camera/2d_top_down_camera.rs
- examples/3d/3d_viewport_to_world.rs
- examples/asset/multi_asset_sync.rs
- tests/window/minimizing.rs
- tests/window/resizing.rs
- examples/3d/atmospheric_fog.rs
- examples/shader/custom_post_processing.rs
- examples/3d/mesh_ray_cast.rs
- examples/animation/animation_graph.rs
- examples/testbed/2d.rs
- examples/shader/shader_material_screenspace_texture.rs
- examples/camera/camera_orbit.rs
- examples/animation/animation_masks.rs
- examples/3d/parenting.rs
- examples/window/screenshot.rs
- examples/3d/two_passes.rs
- examples/window/scale_factor_override.rs
- examples/stress_tests/many_buttons.rs
- examples/camera/2d_screen_shake.rs
- examples/ui/overflow_debug.rs
- examples/window/low_power.rs
- examples/movement/smooth_follow.rs
- examples/ui/relative_cursor_position.rs
- examples/3d/vertex_colors.rs
- examples/3d/orthographic.rs
- examples/3d/spherical_area_lights.rs
- examples/2d/bloom_2d.rs
- examples/gizmos/axes.rs
- examples/gizmos/3d_gizmos.rs
- examples/3d/ssao.rs
- examples/camera/projection_zoom.rs
- examples/3d/order_independent_transparency.rs
- examples/animation/animated_fox.rs
- examples/ui/ui_texture_slice.rs
- examples/3d/visibility_range.rs
- examples/time/virtual_time.rs
- examples/3d/anti_aliasing.rs
- examples/transforms/align.rs
- examples/ui/transparency_ui.rs
- examples/math/random_sampling.rs
- examples/picking/sprite_picking.rs
- examples/ui/ui_texture_atlas_slice.rs
- examples/ecs/iter_combinations.rs
- examples/ui/text_wrap_debug.rs
- examples/games/alien_cake_addict.rs
- examples/asset/alter_mesh.rs
- examples/3d/transparency_3d.rs
- examples/3d/render_to_texture.rs
- examples/asset/asset_loading.rs
- examples/3d/auto_exposure.rs
- examples/ui/overflow.rs
- examples/2d/text2d.rs
- examples/ui/overflow_clip_margin.rs
- examples/shader/shader_prepass.rs
- examples/stress_tests/many_foxes.rs
- examples/3d/split_screen.rs
- examples/3d/deferred_rendering.rs
- examples/animation/custom_skinned_mesh.rs
- examples/3d/blend_modes.rs
- examples/animation/animated_transform.rs
- examples/3d/camera_sub_view.rs
- examples/ui/text_debug.rs
- examples/ui/grid.rs
- examples/3d/transmission.rs
- examples/ui/borders.rs
- examples/ui/ui.rs
- examples/ui/scroll.rs
Sourcepub fn rgb_from_array(_: [f32; 3]) -> Color
👎Deprecated: Use Color::srgb_from_array
instead
pub fn rgb_from_array(_: [f32; 3]) -> Color
Color::srgb_from_array
insteadSourcepub fn srgb_from_array(array: [f32; 3]) -> Color
pub fn srgb_from_array(array: [f32; 3]) -> Color
Sourcepub fn rgba_u8(red: u8, green: u8, blue: u8, alpha: u8) -> Color
👎Deprecated: Use Color::srgba_u8
instead
pub fn rgba_u8(red: u8, green: u8, blue: u8, alpha: u8) -> Color
Color::srgba_u8
insteadSourcepub fn srgba_u8(red: u8, green: u8, blue: u8, alpha: u8) -> Color
pub fn srgba_u8(red: u8, green: u8, blue: u8, alpha: u8) -> Color
Creates a new Color
object storing a Srgba
color from u8
values.
A value of 0 is interpreted as 0.0, and a value of 255 is interpreted as 1.0.
Examples found in repository?
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut images: ResMut<Assets<Image>>,
asset_server: Res<AssetServer>,
) {
// Plane
commands.spawn((
Mesh3d(meshes.add(Plane3d::default().mesh().size(50.0, 50.0))),
MeshMaterial3d(materials.add(Color::srgb(0.1, 0.2, 0.1))),
));
let cube_material = materials.add(StandardMaterial {
base_color_texture: Some(images.add(uv_debug_texture())),
..default()
});
// Cubes
for i in 0..5 {
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(0.25, 0.25, 0.25))),
MeshMaterial3d(cube_material.clone()),
Transform::from_xyz(i as f32 * 0.25 - 1.0, 0.125, -i as f32 * 0.5),
));
}
// Flight Helmet
commands.spawn(SceneRoot(asset_server.load(
GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf"),
)));
// Light
commands.spawn((
DirectionalLight {
illuminance: light_consts::lux::FULL_DAYLIGHT,
shadows_enabled: true,
..default()
},
Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, PI * -0.15, PI * -0.15)),
CascadeShadowConfigBuilder {
maximum_distance: 3.0,
first_cascade_far_bound: 0.9,
..default()
}
.build(),
));
// Camera
commands.spawn((
Camera3d::default(),
Camera {
hdr: true,
..default()
},
Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y),
ContrastAdaptiveSharpening {
enabled: false,
..default()
},
EnvironmentMapLight {
diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
intensity: 150.0,
..default()
},
DistanceFog {
color: Color::srgba_u8(43, 44, 47, 255),
falloff: FogFalloff::Linear {
start: 1.0,
end: 4.0,
},
..default()
},
));
// example instructions
commands.spawn((
Text::default(),
Node {
position_type: PositionType::Absolute,
top: Val::Px(12.0),
left: Val::Px(12.0),
..default()
},
));
}
Sourcepub fn srgb_u8(red: u8, green: u8, blue: u8) -> Color
pub fn srgb_u8(red: u8, green: u8, blue: u8) -> Color
Creates a new Color
object storing a Srgba
color from u8
values with an alpha of 1.0.
A value of 0 is interpreted as 0.0, and a value of 255 is interpreted as 1.0.
Examples found in repository?
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
fn on_click_spawn_cube(
_click: Trigger<Pointer<Click>>,
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut num: Local<usize>,
) {
commands
.spawn((
Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
Transform::from_xyz(0.0, 0.25 + 0.55 * *num as f32, 0.0),
))
// With the MeshPickingPlugin added, you can add pointer event observers to meshes:
.observe(on_drag_rotate);
*num += 1;
}
More examples
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
fn add_camera(commands: &mut Commands, asset_server: &AssetServer, color_grading: ColorGrading) {
commands.spawn((
Camera3d::default(),
Camera {
hdr: true,
..default()
},
Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y),
color_grading,
DistanceFog {
color: Color::srgb_u8(43, 44, 47),
falloff: FogFalloff::Linear {
start: 1.0,
end: 8.0,
},
..default()
},
EnvironmentMapLight {
diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
intensity: 2000.0,
..default()
},
));
}
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
fn spawn_barriers(
meshes: &mut Assets<Mesh>,
materials: &mut Assets<StandardMaterial>,
commands: &mut Commands,
) {
const N_CONES: usize = 100;
let capsule = meshes.add(Capsule3d::default());
let matl = materials.add(StandardMaterial {
base_color: Color::srgb_u8(255, 87, 51),
reflectance: 1.0,
..default()
});
let mut spawn_with_offset = |offset: f32| {
for i in 0..N_CONES {
let pos = race_track_pos(
offset,
(i as f32) / (N_CONES as f32) * std::f32::consts::PI * 2.0,
);
commands.spawn((
Mesh3d(capsule.clone()),
MeshMaterial3d(matl.clone()),
Transform::from_xyz(pos.x, -0.65, pos.y).with_scale(Vec3::splat(0.07)),
));
}
};
spawn_with_offset(0.04);
spawn_with_offset(-0.04);
}
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
fn spawn_camera(commands: &mut Commands, asset_server: &AssetServer) {
commands.spawn((
Camera3d::default(),
Camera {
hdr: true,
..default()
},
Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y),
DistanceFog {
color: Color::srgb_u8(43, 44, 47),
falloff: FogFalloff::Linear {
start: 1.0,
end: 8.0,
},
..default()
},
EnvironmentMapLight {
diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
intensity: 2000.0,
..default()
},
// Include the `ChromaticAberration` component.
ChromaticAberration::default(),
));
}
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// circular base
commands.spawn((
Mesh3d(meshes.add(Circle::new(4.0))),
MeshMaterial3d(materials.add(Color::WHITE)),
Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
));
// cube
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
Transform::from_xyz(0.0, 0.5, 0.0),
));
// light
commands.spawn((
PointLight {
shadows_enabled: true,
..default()
},
Transform::from_xyz(4.0, 8.0, 4.0),
));
// camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
));
}
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// circular base
commands.spawn((
Mesh3d(meshes.add(Circle::new(4.0))),
MeshMaterial3d(materials.add(Color::WHITE)),
Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
));
// cube
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
Transform::from_xyz(0.0, 0.5, 0.0),
Cube(1.0),
));
// light
commands.spawn((
PointLight {
shadows_enabled: true,
..default()
},
Transform::from_xyz(4.0, 8.0, 4.0),
));
// camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
));
}
- examples/3d/tonemapping.rs
- examples/app/headless_renderer.rs
- examples/3d/skybox.rs
- examples/shader/automatic_instancing.rs
- examples/stress_tests/many_cubes.rs
- examples/stress_tests/bevymark.rs
- examples/gizmos/light_gizmos.rs
- examples/3d/spotlight.rs
- examples/3d/parallax_mapping.rs
- examples/3d/deferred_rendering.rs
Sourcepub const fn rbga_linear(red: f32, green: f32, blue: f32, alpha: f32) -> Color
👎Deprecated: Use Color::linear_rgba instead.
pub const fn rbga_linear(red: f32, green: f32, blue: f32, alpha: f32) -> Color
Creates a new Color
object storing a LinearRgba
color.
Sourcepub const fn linear_rgba(red: f32, green: f32, blue: f32, alpha: f32) -> Color
pub const fn linear_rgba(red: f32, green: f32, blue: f32, alpha: f32) -> Color
Creates a new Color
object storing a LinearRgba
color.
Sourcepub const fn rgb_linear(red: f32, green: f32, blue: f32) -> Color
👎Deprecated: Use Color::linear_rgb instead.
pub const fn rgb_linear(red: f32, green: f32, blue: f32) -> Color
Creates a new Color
object storing a LinearRgba
color with an alpha of 1.0.
Sourcepub const fn linear_rgb(red: f32, green: f32, blue: f32) -> Color
pub const fn linear_rgb(red: f32, green: f32, blue: f32) -> Color
Creates a new Color
object storing a LinearRgba
color with an alpha of 1.0.
Examples found in repository?
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
fn mouse_handler(
mut commands: Commands,
args: Res<Args>,
time: Res<Time>,
mouse_button_input: Res<ButtonInput<MouseButton>>,
window: Single<&Window>,
bird_resources: ResMut<BirdResources>,
mut counter: ResMut<BevyCounter>,
mut rng: Local<Option<ChaCha8Rng>>,
mut wave: Local<usize>,
) {
if rng.is_none() {
// 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.
*rng = Some(ChaCha8Rng::seed_from_u64(42));
}
let rng = rng.as_mut().unwrap();
if mouse_button_input.just_released(MouseButton::Left) {
counter.color = Color::linear_rgb(rng.gen(), rng.gen(), rng.gen());
}
if mouse_button_input.pressed(MouseButton::Left) {
let spawn_count = (BIRDS_PER_SECOND as f64 * time.delta_secs_f64()) as usize;
spawn_birds(
&mut commands,
args.into_inner(),
&window.resolution,
&mut counter,
spawn_count,
bird_resources.into_inner(),
None,
*wave,
);
*wave += 1;
}
}
fn bird_velocity_transform(
half_extents: Vec2,
mut translation: Vec3,
velocity_rng: &mut ChaCha8Rng,
waves: Option<usize>,
dt: f32,
) -> (Transform, Vec3) {
let mut velocity = Vec3::new(MAX_VELOCITY * (velocity_rng.gen::<f32>() - 0.5), 0., 0.);
if let Some(waves) = waves {
// Step the movement and handle collisions as if the wave had been spawned at fixed time intervals
// and with dt-spaced frames of simulation
for _ in 0..(waves * (FIXED_TIMESTEP / dt).round() as usize) {
step_movement(&mut translation, &mut velocity, dt);
handle_collision(half_extents, &translation, &mut velocity);
}
}
(
Transform::from_translation(translation).with_scale(Vec3::splat(BIRD_SCALE)),
velocity,
)
}
const FIXED_DELTA_TIME: f32 = 1.0 / 60.0;
#[allow(clippy::too_many_arguments)]
fn spawn_birds(
commands: &mut Commands,
args: &Args,
primary_window_resolution: &WindowResolution,
counter: &mut BevyCounter,
spawn_count: usize,
bird_resources: &mut BirdResources,
waves_to_simulate: Option<usize>,
wave: usize,
) {
let bird_x = (primary_window_resolution.width() / -2.) + HALF_BIRD_SIZE;
let bird_y = (primary_window_resolution.height() / 2.) - HALF_BIRD_SIZE;
let half_extents = 0.5 * primary_window_resolution.size();
let color = counter.color;
let current_count = counter.count;
match args.mode {
Mode::Sprite => {
let batch = (0..spawn_count)
.map(|count| {
let bird_z = if args.ordered_z {
(current_count + count) as f32 * 0.00001
} else {
bird_resources.transform_rng.gen::<f32>()
};
let (transform, velocity) = bird_velocity_transform(
half_extents,
Vec3::new(bird_x, bird_y, bird_z),
&mut bird_resources.velocity_rng,
waves_to_simulate,
FIXED_DELTA_TIME,
);
let color = if args.vary_per_instance {
Color::linear_rgb(
bird_resources.color_rng.gen(),
bird_resources.color_rng.gen(),
bird_resources.color_rng.gen(),
)
} else {
color
};
(
Sprite {
image: bird_resources
.textures
.choose(&mut bird_resources.material_rng)
.unwrap()
.clone(),
color,
..default()
},
transform,
Bird { velocity },
)
})
.collect::<Vec<_>>();
commands.spawn_batch(batch);
}
Mode::Mesh2d => {
let batch = (0..spawn_count)
.map(|count| {
let bird_z = if args.ordered_z {
(current_count + count) as f32 * 0.00001
} else {
bird_resources.transform_rng.gen::<f32>()
};
let (transform, velocity) = bird_velocity_transform(
half_extents,
Vec3::new(bird_x, bird_y, bird_z),
&mut bird_resources.velocity_rng,
waves_to_simulate,
FIXED_DELTA_TIME,
);
let material =
if args.vary_per_instance || args.material_texture_count > args.waves {
bird_resources
.materials
.choose(&mut bird_resources.material_rng)
.unwrap()
.clone()
} else {
bird_resources.materials[wave % bird_resources.materials.len()].clone()
};
(
Mesh2d(bird_resources.quad.clone()),
MeshMaterial2d(material),
transform,
Bird { velocity },
)
})
.collect::<Vec<_>>();
commands.spawn_batch(batch);
}
}
counter.count += spawn_count;
counter.color = Color::linear_rgb(
bird_resources.color_rng.gen(),
bird_resources.color_rng.gen(),
bird_resources.color_rng.gen(),
);
}
More examples
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
fn draw(
my_handle: Res<MyProcGenImage>,
mut images: ResMut<Assets<Image>>,
// used to keep track of where we are
mut i: Local<u32>,
mut draw_color: Local<Color>,
) {
let mut rng = rand::thread_rng();
if *i == 0 {
// Generate a random color on first run.
*draw_color = Color::linear_rgb(rng.gen(), rng.gen(), rng.gen());
}
// Get the image from Bevy's asset storage.
let image = images.get_mut(&my_handle.0).expect("Image not found");
// Compute the position of the pixel to draw.
let center = Vec2::new(IMAGE_WIDTH as f32 / 2.0, IMAGE_HEIGHT as f32 / 2.0);
let max_radius = IMAGE_HEIGHT.min(IMAGE_WIDTH) as f32 / 2.0;
let rot_speed = 0.0123;
let period = 0.12345;
let r = ops::sin(*i as f32 * period) * max_radius;
let xy = Vec2::from_angle(*i as f32 * rot_speed) * r + center;
let (x, y) = (xy.x as u32, xy.y as u32);
// Get the old color of that pixel.
let old_color = image.get_color_at(x, y).unwrap();
// If the old color is our current color, change our drawing color.
let tolerance = 1.0 / 255.0;
if old_color.distance(&draw_color) <= tolerance {
*draw_color = Color::linear_rgb(rng.gen(), rng.gen(), rng.gen());
}
// Set the new color, but keep old alpha value from image.
image
.set_color_at(x, y, draw_color.with_alpha(old_color.alpha()))
.unwrap();
*i += 1;
}
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
fn setup_scene(
asset_server: Res<AssetServer>,
mut images: ResMut<Assets<Image>>,
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
commands.insert_resource(AmbientLight {
color: Color::WHITE,
brightness: 300.0,
});
commands.insert_resource(CameraMode::Chase);
commands.spawn((
DirectionalLight {
illuminance: 3_000.0,
shadows_enabled: true,
..default()
},
Transform::default().looking_to(Vec3::new(-1.0, -0.7, -1.0), Vec3::X),
));
// Sky
commands.spawn((
Mesh3d(meshes.add(Sphere::default())),
MeshMaterial3d(materials.add(StandardMaterial {
unlit: true,
base_color: Color::linear_rgb(0.1, 0.6, 1.0),
..default()
})),
Transform::default().with_scale(Vec3::splat(-4000.0)),
));
// Ground
let mut plane: Mesh = Plane3d::default().into();
let uv_size = 4000.0;
let uvs = vec![[uv_size, 0.0], [0.0, 0.0], [0.0, uv_size], [uv_size; 2]];
plane.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
commands.spawn((
Mesh3d(meshes.add(plane)),
MeshMaterial3d(materials.add(StandardMaterial {
base_color: Color::WHITE,
perceptual_roughness: 1.0,
base_color_texture: Some(images.add(uv_debug_texture())),
..default()
})),
Transform::from_xyz(0.0, -0.65, 0.0).with_scale(Vec3::splat(80.)),
));
spawn_cars(&asset_server, &mut meshes, &mut materials, &mut commands);
spawn_trees(&mut meshes, &mut materials, &mut commands);
spawn_barriers(&mut meshes, &mut materials, &mut commands);
}
fn spawn_cars(
asset_server: &AssetServer,
meshes: &mut Assets<Mesh>,
materials: &mut Assets<StandardMaterial>,
commands: &mut Commands,
) {
const N_CARS: usize = 20;
let box_mesh = meshes.add(Cuboid::new(0.3, 0.15, 0.55));
let cylinder = meshes.add(Cylinder::default());
let logo = asset_server.load("branding/icon.png");
let wheel_matl = materials.add(StandardMaterial {
base_color: Color::WHITE,
base_color_texture: Some(logo.clone()),
..default()
});
let mut matl = |color| {
materials.add(StandardMaterial {
base_color: color,
..default()
})
};
let colors = [
matl(Color::linear_rgb(1.0, 0.0, 0.0)),
matl(Color::linear_rgb(1.0, 1.0, 0.0)),
matl(Color::BLACK),
matl(Color::linear_rgb(0.0, 0.0, 1.0)),
matl(Color::linear_rgb(0.0, 1.0, 0.0)),
matl(Color::linear_rgb(1.0, 0.0, 1.0)),
matl(Color::linear_rgb(0.5, 0.5, 0.0)),
matl(Color::linear_rgb(1.0, 0.5, 0.0)),
];
for i in 0..N_CARS {
let color = colors[i % colors.len()].clone();
commands
.spawn((
Mesh3d(box_mesh.clone()),
MeshMaterial3d(color.clone()),
Transform::from_scale(Vec3::splat(0.5)),
Moves(i as f32 * 2.0),
))
.insert_if(CameraTracked, || i == 0)
.with_children(|parent| {
parent.spawn((
Mesh3d(box_mesh.clone()),
MeshMaterial3d(color),
Transform::from_xyz(0.0, 0.08, 0.03).with_scale(Vec3::new(1.0, 1.0, 0.5)),
));
let mut spawn_wheel = |x: f32, z: f32| {
parent.spawn((
Mesh3d(cylinder.clone()),
MeshMaterial3d(wheel_matl.clone()),
Transform::from_xyz(0.14 * x, -0.045, 0.15 * z)
.with_scale(Vec3::new(0.15, 0.04, 0.15))
.with_rotation(Quat::from_rotation_z(std::f32::consts::FRAC_PI_2)),
Rotates,
));
};
spawn_wheel(1.0, 1.0);
spawn_wheel(1.0, -1.0);
spawn_wheel(-1.0, 1.0);
spawn_wheel(-1.0, -1.0);
});
}
}
fn spawn_barriers(
meshes: &mut Assets<Mesh>,
materials: &mut Assets<StandardMaterial>,
commands: &mut Commands,
) {
const N_CONES: usize = 100;
let capsule = meshes.add(Capsule3d::default());
let matl = materials.add(StandardMaterial {
base_color: Color::srgb_u8(255, 87, 51),
reflectance: 1.0,
..default()
});
let mut spawn_with_offset = |offset: f32| {
for i in 0..N_CONES {
let pos = race_track_pos(
offset,
(i as f32) / (N_CONES as f32) * std::f32::consts::PI * 2.0,
);
commands.spawn((
Mesh3d(capsule.clone()),
MeshMaterial3d(matl.clone()),
Transform::from_xyz(pos.x, -0.65, pos.y).with_scale(Vec3::splat(0.07)),
));
}
};
spawn_with_offset(0.04);
spawn_with_offset(-0.04);
}
fn spawn_trees(
meshes: &mut Assets<Mesh>,
materials: &mut Assets<StandardMaterial>,
commands: &mut Commands,
) {
const N_TREES: usize = 30;
let capsule = meshes.add(Capsule3d::default());
let sphere = meshes.add(Sphere::default());
let leaves = materials.add(Color::linear_rgb(0.0, 1.0, 0.0));
let trunk = materials.add(Color::linear_rgb(0.4, 0.2, 0.2));
let mut spawn_with_offset = |offset: f32| {
for i in 0..N_TREES {
let pos = race_track_pos(
offset,
(i as f32) / (N_TREES as f32) * std::f32::consts::PI * 2.0,
);
let [x, z] = pos.into();
commands.spawn((
Mesh3d(sphere.clone()),
MeshMaterial3d(leaves.clone()),
Transform::from_xyz(x, -0.3, z).with_scale(Vec3::splat(0.3)),
));
commands.spawn((
Mesh3d(capsule.clone()),
MeshMaterial3d(trunk.clone()),
Transform::from_xyz(x, -0.5, z).with_scale(Vec3::new(0.05, 0.3, 0.05)),
));
}
};
spawn_with_offset(0.07);
spawn_with_offset(-0.07);
}
Sourcepub const fn hsla(
hue: f32,
saturation: f32,
lightness: f32,
alpha: f32,
) -> Color
pub const fn hsla( hue: f32, saturation: f32, lightness: f32, alpha: f32, ) -> Color
Examples found in repository?
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
InstanceMaterialData(
(1..=10)
.flat_map(|x| (1..=10).map(move |y| (x as f32 / 10.0, y as f32 / 10.0)))
.map(|(x, y)| InstanceData {
position: Vec3::new(x * 10.0 - 5.0, y * 10.0 - 5.0, 0.0),
scale: 1.0,
color: LinearRgba::from(Color::hsla(x * 360., y, 0.5, 1.0)).to_f32_array(),
})
.collect(),
),
// NOTE: Frustum culling is done based on the Aabb of the Mesh and the GlobalTransform.
// As the cube is at the origin, if its Aabb moves outside the view frustum, all the
// instanced cubes will be culled.
// The InstanceMaterialData contains the 'GlobalTransform' information for this custom
// instancing, and that is not taken into account with the built-in frustum culling.
// We must disable the built-in frustum culling by adding the `NoFrustumCulling` marker
// component to avoid incorrect culling.
NoFrustumCulling,
));
// camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(0.0, 0.0, 15.0).looking_at(Vec3::ZERO, Vec3::Y),
));
}
Sourcepub const fn hsl(hue: f32, saturation: f32, lightness: f32) -> Color
pub const fn hsl(hue: f32, saturation: f32, lightness: f32) -> Color
Examples found in repository?
More examples
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
fn animate(
mut materials: ResMut<Assets<CustomUiMaterial>>,
q: Query<&MaterialNode<CustomUiMaterial>>,
time: Res<Time>,
) {
let duration = 2.0;
for handle in &q {
if let Some(material) = materials.get_mut(handle) {
// rainbow color effect
let new_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 1., 0.5);
let border_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 0.75, 0.75);
material.color = new_color.to_linear().to_vec4();
material.slider =
((time.elapsed_secs() % (duration * 2.0)) - duration).abs() / duration;
material.border_color = border_color.to_linear().to_vec4();
}
}
}
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
pub fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
) {
commands.spawn((Camera2d, StateScoped(super::Scene::Shapes)));
let shapes = [
meshes.add(Circle::new(50.0)),
meshes.add(CircularSector::new(50.0, 1.0)),
meshes.add(CircularSegment::new(50.0, 1.25)),
meshes.add(Ellipse::new(25.0, 50.0)),
meshes.add(Annulus::new(25.0, 50.0)),
meshes.add(Capsule2d::new(25.0, 50.0)),
meshes.add(Rhombus::new(75.0, 100.0)),
meshes.add(Rectangle::new(50.0, 100.0)),
meshes.add(RegularPolygon::new(50.0, 6)),
meshes.add(Triangle2d::new(
Vec2::Y * 50.0,
Vec2::new(-50.0, -50.0),
Vec2::new(50.0, -50.0),
)),
];
let num_shapes = shapes.len();
for (i, shape) in shapes.into_iter().enumerate() {
// Distribute colors evenly across the rainbow.
let color = Color::hsl(360. * i as f32 / num_shapes as f32, 0.95, 0.7);
commands.spawn((
Mesh2d(shape),
MeshMaterial2d(materials.add(color)),
Transform::from_xyz(
// Distribute shapes from -X_EXTENT/2 to +X_EXTENT/2.
-X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * X_EXTENT,
0.0,
0.0,
),
StateScoped(super::Scene::Shapes),
));
}
}
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
) {
commands.spawn(Camera2d);
let shapes = [
meshes.add(Circle::new(50.0)),
meshes.add(CircularSector::new(50.0, 1.0)),
meshes.add(CircularSegment::new(50.0, 1.25)),
meshes.add(Ellipse::new(25.0, 50.0)),
meshes.add(Annulus::new(25.0, 50.0)),
meshes.add(Capsule2d::new(25.0, 50.0)),
meshes.add(Rhombus::new(75.0, 100.0)),
meshes.add(Rectangle::new(50.0, 100.0)),
meshes.add(RegularPolygon::new(50.0, 6)),
meshes.add(Triangle2d::new(
Vec2::Y * 50.0,
Vec2::new(-50.0, -50.0),
Vec2::new(50.0, -50.0),
)),
];
let num_shapes = shapes.len();
for (i, shape) in shapes.into_iter().enumerate() {
// Distribute colors evenly across the rainbow.
let color = Color::hsl(360. * i as f32 / num_shapes as f32, 0.95, 0.7);
commands.spawn((
Mesh2d(shape),
MeshMaterial2d(materials.add(color)),
Transform::from_xyz(
// Distribute shapes from -X_EXTENT/2 to +X_EXTENT/2.
-X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * X_EXTENT,
0.0,
0.0,
),
));
}
#[cfg(not(target_arch = "wasm32"))]
commands.spawn((
Text::new("Press space to toggle wireframes"),
Node {
position_type: PositionType::Absolute,
top: Val::Px(12.0),
left: Val::Px(12.0),
..default()
},
));
}
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
fn setup_flex(mut commands: Commands, asset_server: Res<AssetServer>, args: Res<Args>) {
warn!(include_str!("warning_string.txt"));
let image = if 0 < args.image_freq {
Some(asset_server.load("branding/icon.png"))
} else {
None
};
let buttons_f = args.buttons as f32;
let border = if args.no_borders {
UiRect::ZERO
} else {
UiRect::all(Val::VMin(0.05 * 90. / buttons_f))
};
let as_rainbow = |i: usize| Color::hsl((i as f32 / buttons_f) * 360.0, 0.9, 0.8);
commands.spawn(Camera2d);
commands
.spawn(Node {
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
width: Val::Percent(100.),
height: Val::Percent(100.),
..default()
})
.with_children(|commands| {
for column in 0..args.buttons {
commands.spawn(Node::default()).with_children(|commands| {
for row in 0..args.buttons {
let color = as_rainbow(row % column.max(1));
let border_color = Color::WHITE.with_alpha(0.5).into();
spawn_button(
commands,
color,
buttons_f,
column,
row,
!args.no_text,
border,
border_color,
image
.as_ref()
.filter(|_| (column + row) % args.image_freq == 0)
.cloned(),
);
}
});
}
});
}
fn setup_grid(mut commands: Commands, asset_server: Res<AssetServer>, args: Res<Args>) {
warn!(include_str!("warning_string.txt"));
let image = if 0 < args.image_freq {
Some(asset_server.load("branding/icon.png"))
} else {
None
};
let buttons_f = args.buttons as f32;
let border = if args.no_borders {
UiRect::ZERO
} else {
UiRect::all(Val::VMin(0.05 * 90. / buttons_f))
};
let as_rainbow = |i: usize| Color::hsl((i as f32 / buttons_f) * 360.0, 0.9, 0.8);
commands.spawn(Camera2d);
commands
.spawn(Node {
display: Display::Grid,
width: Val::Percent(100.),
height: Val::Percent(100.0),
grid_template_columns: RepeatedGridTrack::flex(args.buttons as u16, 1.0),
grid_template_rows: RepeatedGridTrack::flex(args.buttons as u16, 1.0),
..default()
})
.with_children(|commands| {
for column in 0..args.buttons {
for row in 0..args.buttons {
let color = as_rainbow(row % column.max(1));
let border_color = Color::WHITE.with_alpha(0.5).into();
spawn_button(
commands,
color,
buttons_f,
column,
row,
!args.no_text,
border,
border_color,
image
.as_ref()
.filter(|_| (column + row) % args.image_freq == 0)
.cloned(),
);
}
}
});
}
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
warn!(include_str!("warning_string.txt"));
const LIGHT_RADIUS: f32 = 0.3;
const LIGHT_INTENSITY: f32 = 1000.0;
const RADIUS: f32 = 50.0;
const N_LIGHTS: usize = 100_000;
commands.spawn((
Mesh3d(meshes.add(Sphere::new(RADIUS).mesh().ico(9).unwrap())),
MeshMaterial3d(materials.add(Color::WHITE)),
Transform::from_scale(Vec3::NEG_ONE),
));
let mesh = meshes.add(Cuboid::default());
let material = materials.add(StandardMaterial {
base_color: DEEP_PINK.into(),
..default()
});
// NOTE: This pattern is good for testing performance of culling as it provides roughly
// the same number of visible meshes regardless of the viewing angle.
// NOTE: f64 is used to avoid precision issues that produce visual artifacts in the distribution
let golden_ratio = 0.5f64 * (1.0f64 + 5.0f64.sqrt());
// Spawn N_LIGHTS many lights
commands.spawn_batch((0..N_LIGHTS).map(move |i| {
let mut rng = thread_rng();
let spherical_polar_theta_phi = fibonacci_spiral_on_sphere(golden_ratio, i, N_LIGHTS);
let unit_sphere_p = spherical_polar_to_cartesian(spherical_polar_theta_phi);
(
PointLight {
range: LIGHT_RADIUS,
intensity: LIGHT_INTENSITY,
color: Color::hsl(rng.gen_range(0.0..360.0), 1.0, 0.5),
..default()
},
Transform::from_translation((RADIUS as f64 * unit_sphere_p).as_vec3()),
)
}));
// camera
match std::env::args().nth(1).as_deref() {
Some("orthographic") => commands.spawn((
Camera3d::default(),
Projection::from(OrthographicProjection {
scaling_mode: ScalingMode::FixedHorizontal {
viewport_width: 20.0,
},
..OrthographicProjection::default_3d()
}),
)),
_ => commands.spawn(Camera3d::default()),
};
// add one cube, the only one with strong handles
// also serves as a reference point during rotation
commands.spawn((
Mesh3d(mesh),
MeshMaterial3d(material),
Transform {
translation: Vec3::new(0.0, RADIUS, 0.0),
scale: Vec3::splat(5.0),
..default()
},
));
}
Sourcepub const fn hsv(hue: f32, saturation: f32, value: f32) -> Color
pub const fn hsv(hue: f32, saturation: f32, value: f32) -> Color
Examples found in repository?
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
window: Query<&Window>,
) {
// circular base
commands.spawn((
Mesh3d(meshes.add(Circle::new(4.0))),
MeshMaterial3d(materials.add(Color::WHITE)),
Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
));
// cube
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
MeshMaterial3d(materials.add(Color::WHITE)),
Transform::from_xyz(0.0, 0.5, 0.0),
));
// lights
for i in 0..NUM_LIGHTS {
let angle = (i as f32) / (NUM_LIGHTS as f32) * PI * 2.0;
commands.spawn((
PointLight {
color: Color::hsv(angle.to_degrees(), 1.0, 1.0),
intensity: 2_000_000.0 / NUM_LIGHTS as f32,
shadows_enabled: true,
..default()
},
Transform::from_xyz(sin(angle) * 4.0, 2.0, cos(angle) * 4.0),
));
}
// cameras
let window = window.single();
let width = window.resolution.width() / CAMERA_COLS as f32 * window.resolution.scale_factor();
let height = window.resolution.height() / CAMERA_ROWS as f32 * window.resolution.scale_factor();
let mut i = 0;
for y in 0..CAMERA_COLS {
for x in 0..CAMERA_ROWS {
let angle = i as f32 / (CAMERA_ROWS * CAMERA_COLS) as f32 * PI * 2.0;
commands.spawn((
Camera3d::default(),
Camera {
viewport: Some(Viewport {
physical_position: UVec2::new(
(x as f32 * width) as u32,
(y as f32 * height) as u32,
),
physical_size: UVec2::new(width as u32, height as u32),
..default()
}),
order: i,
..default()
},
Transform::from_xyz(sin(angle) * 4.0, 2.5, cos(angle) * 4.0)
.looking_at(Vec3::ZERO, Vec3::Y),
));
i += 1;
}
}
}
Trait Implementations§
Source§impl Alpha for Color
impl Alpha for Color
Source§fn with_alpha(&self, alpha: f32) -> Color
fn with_alpha(&self, alpha: f32) -> Color
Source§fn is_fully_transparent(&self) -> bool
fn is_fully_transparent(&self) -> bool
Source§fn is_fully_opaque(&self) -> bool
fn is_fully_opaque(&self) -> bool
Source§impl Default for Color
impl Default for Color
Source§fn default() -> Color
fn default() -> Color
A fully white Color::LinearRgba
color with an alpha of 1.0.
Source§impl<'de> Deserialize<'de> for Color
impl<'de> Deserialize<'de> for Color
Source§fn deserialize<__D>(
__deserializer: __D,
) -> Result<Color, <__D as Deserializer<'de>>::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(
__deserializer: __D,
) -> Result<Color, <__D as Deserializer<'de>>::Error>where
__D: Deserializer<'de>,
Source§impl Enum for Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl Enum for Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§fn field(&self, __name_param: &str) -> Option<&(dyn PartialReflect + 'static)>
fn field(&self, __name_param: &str) -> Option<&(dyn PartialReflect + 'static)>
Source§fn field_at(
&self,
__index_param: usize,
) -> Option<&(dyn PartialReflect + 'static)>
fn field_at( &self, __index_param: usize, ) -> Option<&(dyn PartialReflect + 'static)>
Source§fn field_mut(
&mut self,
__name_param: &str,
) -> Option<&mut (dyn PartialReflect + 'static)>
fn field_mut( &mut self, __name_param: &str, ) -> Option<&mut (dyn PartialReflect + 'static)>
Source§fn field_at_mut(
&mut self,
__index_param: usize,
) -> Option<&mut (dyn PartialReflect + 'static)>
fn field_at_mut( &mut self, __index_param: usize, ) -> Option<&mut (dyn PartialReflect + 'static)>
Source§fn index_of(&self, __name_param: &str) -> Option<usize>
fn index_of(&self, __name_param: &str) -> Option<usize>
Source§fn name_at(&self, __index_param: usize) -> Option<&str>
fn name_at(&self, __index_param: usize) -> Option<&str>
Source§fn iter_fields(&self) -> VariantFieldIter<'_> ⓘ
fn iter_fields(&self) -> VariantFieldIter<'_> ⓘ
Source§fn variant_name(&self) -> &str
fn variant_name(&self) -> &str
Source§fn variant_index(&self) -> usize
fn variant_index(&self) -> usize
Source§fn variant_type(&self) -> VariantType
fn variant_type(&self) -> VariantType
fn clone_dynamic(&self) -> DynamicEnum
Source§fn is_variant(&self, variant_type: VariantType) -> bool
fn is_variant(&self, variant_type: VariantType) -> bool
Source§fn variant_path(&self) -> String
fn variant_path(&self) -> String
Source§impl EuclideanDistance for Color
impl EuclideanDistance for Color
Source§impl From<Color> for ClearColorConfig
impl From<Color> for ClearColorConfig
Source§fn from(value: Color) -> ClearColorConfig
fn from(value: Color) -> ClearColorConfig
Source§impl From<Color> for ColorMaterial
impl From<Color> for ColorMaterial
Source§fn from(color: Color) -> ColorMaterial
fn from(color: Color) -> ColorMaterial
Source§impl From<Color> for LinearRgba
impl From<Color> for LinearRgba
Source§fn from(value: Color) -> LinearRgba
fn from(value: Color) -> LinearRgba
Source§impl From<Color> for StandardMaterial
impl From<Color> for StandardMaterial
Source§fn from(color: Color) -> StandardMaterial
fn from(color: Color) -> StandardMaterial
Source§impl From<LinearRgba> for Color
impl From<LinearRgba> for Color
Source§fn from(value: LinearRgba) -> Color
fn from(value: LinearRgba) -> Color
Source§impl FromArg for &'static Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl FromArg for &'static Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§impl FromArg for &'static mut Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl FromArg for &'static mut Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§impl FromArg for Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl FromArg for Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§impl FromReflect for Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl FromReflect for Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§fn from_reflect(__param0: &(dyn PartialReflect + 'static)) -> Option<Color>
fn from_reflect(__param0: &(dyn PartialReflect + 'static)) -> Option<Color>
Self
from a reflected value.Source§fn take_from_reflect(
reflect: Box<dyn PartialReflect>,
) -> Result<Self, Box<dyn PartialReflect>>
fn take_from_reflect( reflect: Box<dyn PartialReflect>, ) -> Result<Self, Box<dyn PartialReflect>>
Self
using,
constructing the value using from_reflect
if that fails. Read moreSource§impl GetOwnership for &Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl GetOwnership for &Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§impl GetOwnership for &mut Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl GetOwnership for &mut Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§impl GetOwnership for Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl GetOwnership for Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§impl GetTypeRegistration for Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl GetTypeRegistration for Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§fn get_type_registration() -> TypeRegistration
fn get_type_registration() -> TypeRegistration
TypeRegistration
for this type.Source§fn register_type_dependencies(registry: &mut TypeRegistry)
fn register_type_dependencies(registry: &mut TypeRegistry)
Source§impl Hue for Color
impl Hue for Color
Source§impl IntoReturn for &Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl IntoReturn for &Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§impl IntoReturn for &mut Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl IntoReturn for &mut Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§impl IntoReturn for Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl IntoReturn for Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§impl Luminance for Color
impl Luminance for Color
Source§fn with_luminance(&self, value: f32) -> Color
fn with_luminance(&self, value: f32) -> Color
Source§fn darker(&self, amount: f32) -> Color
fn darker(&self, amount: f32) -> Color
amount
should be between 0.0 and 1.0.
The amount represents an absolute decrease in luminance, and is distributive:
color.darker(a).darker(b) == color.darker(a + b)
. Colors are clamped to black
if the amount would cause them to go below black. Read moreSource§fn lighter(&self, amount: f32) -> Color
fn lighter(&self, amount: f32) -> Color
amount
should be between 0.0 and 1.0.
The amount represents an absolute increase in luminance, and is distributive:
color.lighter(a).lighter(b) == color.lighter(a + b)
. Colors are clamped to white
if the amount would cause them to go above white. Read moreSource§impl Mix for Color
impl Mix for Color
Source§fn mix(&self, other: &Color, factor: f32) -> Color
fn mix(&self, other: &Color, factor: f32) -> Color
Source§fn mix_assign(&mut self, other: Self, factor: f32)
fn mix_assign(&mut self, other: Self, factor: f32)
Source§impl PartialReflect for Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl PartialReflect for Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§fn get_represented_type_info(&self) -> Option<&'static TypeInfo>
fn get_represented_type_info(&self) -> Option<&'static TypeInfo>
Source§fn clone_value(&self) -> Box<dyn PartialReflect>
fn clone_value(&self) -> Box<dyn PartialReflect>
Reflect
trait object. Read moreSource§fn try_apply(
&mut self,
__value_param: &(dyn PartialReflect + 'static),
) -> Result<(), ApplyError>
fn try_apply( &mut self, __value_param: &(dyn PartialReflect + 'static), ) -> Result<(), ApplyError>
Source§fn reflect_kind(&self) -> ReflectKind
fn reflect_kind(&self) -> ReflectKind
Source§fn reflect_ref(&self) -> ReflectRef<'_>
fn reflect_ref(&self) -> ReflectRef<'_>
Source§fn reflect_mut(&mut self) -> ReflectMut<'_>
fn reflect_mut(&mut self) -> ReflectMut<'_>
Source§fn reflect_owned(self: Box<Color>) -> ReflectOwned
fn reflect_owned(self: Box<Color>) -> ReflectOwned
Source§fn try_into_reflect(
self: Box<Color>,
) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>
fn try_into_reflect( self: Box<Color>, ) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>
Source§fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>
fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>
Source§fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>
fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>
Source§fn into_partial_reflect(self: Box<Color>) -> Box<dyn PartialReflect>
fn into_partial_reflect(self: Box<Color>) -> Box<dyn PartialReflect>
Source§fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)
fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)
Source§fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)
fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)
Source§fn reflect_hash(&self) -> Option<u64>
fn reflect_hash(&self) -> Option<u64>
Source§fn reflect_partial_eq(
&self,
value: &(dyn PartialReflect + 'static),
) -> Option<bool>
fn reflect_partial_eq( &self, value: &(dyn PartialReflect + 'static), ) -> Option<bool>
Source§fn apply(&mut self, value: &(dyn PartialReflect + 'static))
fn apply(&mut self, value: &(dyn PartialReflect + 'static))
Source§fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>
fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>
Source§fn serializable(&self) -> Option<Serializable<'_>>
fn serializable(&self) -> Option<Serializable<'_>>
Source§fn is_dynamic(&self) -> bool
fn is_dynamic(&self) -> bool
Source§impl Reflect for Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl Reflect for Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut dyn Any
. Read moreSource§fn into_reflect(self: Box<Color>) -> Box<dyn Reflect>
fn into_reflect(self: Box<Color>) -> Box<dyn Reflect>
Source§fn as_reflect(&self) -> &(dyn Reflect + 'static)
fn as_reflect(&self) -> &(dyn Reflect + 'static)
Source§fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)
fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)
Source§impl Serialize for Color
impl Serialize for Color
Source§fn serialize<__S>(
&self,
__serializer: __S,
) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>where
__S: Serializer,
fn serialize<__S>(
&self,
__serializer: __S,
) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>where
__S: Serializer,
Source§impl TypePath for Color
impl TypePath for Color
Source§fn type_path() -> &'static str
fn type_path() -> &'static str
Source§fn short_type_path() -> &'static str
fn short_type_path() -> &'static str
Source§fn type_ident() -> Option<&'static str>
fn type_ident() -> Option<&'static str>
Source§fn crate_name() -> Option<&'static str>
fn crate_name() -> Option<&'static str>
Source§impl Typed for Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl Typed for Colorwhere
Color: Any + Send + Sync,
Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl Copy for Color
impl StructuralPartialEq for Color
Auto Trait Implementations§
impl Freeze for Color
impl RefUnwindSafe for Color
impl Send for Color
impl Sync for Color
impl Unpin for Color
impl UnwindSafe for Color
Blanket Implementations§
Source§impl<T, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
Source§fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
T
ShaderType
for self
. When used in AsBindGroup
derives, it is safe to assume that all images in self
exist.Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
. Box<dyn Any>
can
then be further downcast
into Box<ConcreteType>
where ConcreteType
implements Trait
.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
. Rc<Any>
can then be
further downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s.Source§impl<T> DowncastSync for T
impl<T> DowncastSync for T
Source§impl<T> DynamicTypePath for Twhere
T: TypePath,
impl<T> DynamicTypePath for Twhere
T: TypePath,
Source§fn reflect_type_path(&self) -> &str
fn reflect_type_path(&self) -> &str
TypePath::type_path
.Source§fn reflect_short_type_path(&self) -> &str
fn reflect_short_type_path(&self) -> &str
Source§fn reflect_type_ident(&self) -> Option<&str>
fn reflect_type_ident(&self) -> Option<&str>
TypePath::type_ident
.Source§fn reflect_crate_name(&self) -> Option<&str>
fn reflect_crate_name(&self) -> Option<&str>
TypePath::crate_name
.Source§fn reflect_module_path(&self) -> Option<&str>
fn reflect_module_path(&self) -> Option<&str>
Source§impl<T> DynamicTyped for Twhere
T: Typed,
impl<T> DynamicTyped for Twhere
T: Typed,
Source§fn reflect_type_info(&self) -> &'static TypeInfo
fn reflect_type_info(&self) -> &'static TypeInfo
Typed::type_info
.Source§impl<T> FmtForward for T
impl<T> FmtForward for T
Source§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self
to use its Binary
implementation when Debug
-formatted.Source§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self
to use its Display
implementation when
Debug
-formatted.Source§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self
to use its LowerExp
implementation when
Debug
-formatted.Source§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self
to use its LowerHex
implementation when
Debug
-formatted.Source§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self
to use its Octal
implementation when Debug
-formatted.Source§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self
to use its Pointer
implementation when
Debug
-formatted.Source§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self
to use its UpperExp
implementation when
Debug
-formatted.Source§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self
to use its UpperHex
implementation when
Debug
-formatted.Source§impl<S> FromSample<S> for S
impl<S> FromSample<S> for S
fn from_sample_(s: S) -> S
Source§impl<T> FromWorld for Twhere
T: Default,
impl<T> FromWorld for Twhere
T: Default,
Source§fn from_world(_world: &mut World) -> T
fn from_world(_world: &mut World) -> T
Creates Self
using default()
.
Source§impl<T> GetPath for T
impl<T> GetPath for T
Source§fn reflect_path<'p>(
&self,
path: impl ReflectPath<'p>,
) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>
fn reflect_path<'p>( &self, path: impl ReflectPath<'p>, ) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>
path
. Read moreSource§fn reflect_path_mut<'p>(
&mut self,
path: impl ReflectPath<'p>,
) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>
fn reflect_path_mut<'p>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>
path
. Read moreSource§fn path<'p, T>(
&self,
path: impl ReflectPath<'p>,
) -> Result<&T, ReflectPathError<'p>>where
T: Reflect,
fn path<'p, T>(
&self,
path: impl ReflectPath<'p>,
) -> Result<&T, ReflectPathError<'p>>where
T: Reflect,
path
. Read moreSource§fn path_mut<'p, T>(
&mut self,
path: impl ReflectPath<'p>,
) -> Result<&mut T, ReflectPathError<'p>>where
T: Reflect,
fn path_mut<'p, T>(
&mut self,
path: impl ReflectPath<'p>,
) -> Result<&mut T, ReflectPathError<'p>>where
T: Reflect,
path
. Read moreSource§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
fn into_sample(self) -> T
Source§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
Source§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
Source§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read moreSource§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read moreSource§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
Source§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R,
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
Source§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
self
, then passes self.as_ref()
into the pipe function.Source§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
self
, then passes self.as_mut()
into the pipe
function.Source§fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self
, then passes self.deref()
into the pipe function.Source§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<R, P> ReadPrimitive<R> for P
impl<R, P> ReadPrimitive<R> for P
Source§fn read_from_little_endian(read: &mut R) -> Result<Self, Error>
fn read_from_little_endian(read: &mut R) -> Result<Self, Error>
ReadEndian::read_from_little_endian()
.Source§impl<T> Serialize for T
impl<T> Serialize for T
fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>
fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>
Source§impl<T> Tap for T
impl<T> Tap for T
Source§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B>
of a value. Read moreSource§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B>
of a value. Read moreSource§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R>
view of a value. Read moreSource§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R>
view of a value. Read moreSource§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target
of a value. Read moreSource§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target
of a value. Read moreSource§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap()
only in debug builds, and is erased in release builds.Source§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut()
only in debug builds, and is erased in release
builds.Source§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.tap_borrow()
only in debug builds, and is erased in release
builds.Source§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.tap_borrow_mut()
only in debug builds, and is erased in release
builds.Source§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.tap_ref()
only in debug builds, and is erased in release
builds.Source§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.tap_ref_mut()
only in debug builds, and is erased in release
builds.Source§fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref()
only in debug builds, and is erased in release
builds.