code
stringlengths 40
729k
| docstring
stringlengths 22
46.3k
| func_name
stringlengths 1
97
| language
stringclasses 1
value | repo
stringlengths 6
48
| path
stringlengths 8
176
| url
stringlengths 47
228
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
pub fn set_physical_cursor_position(&mut self, position: Option<DVec2>) {
self.internal.physical_cursor_position = position;
}
|
Set the cursor position in this window in physical pixels.
See [`WindowResolution`] for an explanation about logical/physical sizes.
|
set_physical_cursor_position
|
rust
|
bevyengine/bevy
|
crates/bevy_window/src/window.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_window/src/window.rs
|
Apache-2.0
|
pub fn set(&mut self, position: IVec2) {
*self = WindowPosition::At(position);
}
|
Set the position to a specific point.
|
set
|
rust
|
bevyengine/bevy
|
crates/bevy_window/src/window.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_window/src/window.rs
|
Apache-2.0
|
pub fn center(&mut self, monitor: MonitorSelection) {
*self = WindowPosition::Centered(monitor);
}
|
Set the window to a specific monitor.
|
center
|
rust
|
bevyengine/bevy
|
crates/bevy_window/src/window.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_window/src/window.rs
|
Apache-2.0
|
pub fn with_scale_factor_override(mut self, scale_factor_override: f32) -> Self {
self.set_scale_factor_override(Some(scale_factor_override));
self
}
|
Builder method for adding a scale factor override to the resolution.
|
with_scale_factor_override
|
rust
|
bevyengine/bevy
|
crates/bevy_window/src/window.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_window/src/window.rs
|
Apache-2.0
|
pub fn scale_factor(&self) -> f32 {
self.scale_factor_override
.unwrap_or_else(|| self.base_scale_factor())
}
|
The ratio of physical pixels to logical pixels.
`physical_pixels = logical_pixels * scale_factor`
|
scale_factor
|
rust
|
bevyengine/bevy
|
crates/bevy_window/src/window.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_window/src/window.rs
|
Apache-2.0
|
pub fn take_move_request(&mut self) -> bool {
core::mem::take(&mut self.drag_move_request)
}
|
Consumes the current move request, if it exists. This should only be called by window backends.
|
take_move_request
|
rust
|
bevyengine/bevy
|
crates/bevy_window/src/window.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_window/src/window.rs
|
Apache-2.0
|
pub fn convert_system_cursor_icon(cursor_icon: SystemCursorIcon) -> winit::window::CursorIcon {
match cursor_icon {
SystemCursorIcon::Crosshair => winit::window::CursorIcon::Crosshair,
SystemCursorIcon::Pointer => winit::window::CursorIcon::Pointer,
SystemCursorIcon::Move => winit::window::CursorIcon::Move,
SystemCursorIcon::Text => winit::window::CursorIcon::Text,
SystemCursorIcon::Wait => winit::window::CursorIcon::Wait,
SystemCursorIcon::Help => winit::window::CursorIcon::Help,
SystemCursorIcon::Progress => winit::window::CursorIcon::Progress,
SystemCursorIcon::NotAllowed => winit::window::CursorIcon::NotAllowed,
SystemCursorIcon::ContextMenu => winit::window::CursorIcon::ContextMenu,
SystemCursorIcon::Cell => winit::window::CursorIcon::Cell,
SystemCursorIcon::VerticalText => winit::window::CursorIcon::VerticalText,
SystemCursorIcon::Alias => winit::window::CursorIcon::Alias,
SystemCursorIcon::Copy => winit::window::CursorIcon::Copy,
SystemCursorIcon::NoDrop => winit::window::CursorIcon::NoDrop,
SystemCursorIcon::Grab => winit::window::CursorIcon::Grab,
SystemCursorIcon::Grabbing => winit::window::CursorIcon::Grabbing,
SystemCursorIcon::AllScroll => winit::window::CursorIcon::AllScroll,
SystemCursorIcon::ZoomIn => winit::window::CursorIcon::ZoomIn,
SystemCursorIcon::ZoomOut => winit::window::CursorIcon::ZoomOut,
SystemCursorIcon::EResize => winit::window::CursorIcon::EResize,
SystemCursorIcon::NResize => winit::window::CursorIcon::NResize,
SystemCursorIcon::NeResize => winit::window::CursorIcon::NeResize,
SystemCursorIcon::NwResize => winit::window::CursorIcon::NwResize,
SystemCursorIcon::SResize => winit::window::CursorIcon::SResize,
SystemCursorIcon::SeResize => winit::window::CursorIcon::SeResize,
SystemCursorIcon::SwResize => winit::window::CursorIcon::SwResize,
SystemCursorIcon::WResize => winit::window::CursorIcon::WResize,
SystemCursorIcon::EwResize => winit::window::CursorIcon::EwResize,
SystemCursorIcon::NsResize => winit::window::CursorIcon::NsResize,
SystemCursorIcon::NeswResize => winit::window::CursorIcon::NeswResize,
SystemCursorIcon::NwseResize => winit::window::CursorIcon::NwseResize,
SystemCursorIcon::ColResize => winit::window::CursorIcon::ColResize,
SystemCursorIcon::RowResize => winit::window::CursorIcon::RowResize,
_ => winit::window::CursorIcon::Default,
}
}
|
Converts a [`SystemCursorIcon`] to a [`winit::window::CursorIcon`].
|
convert_system_cursor_icon
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/converters.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/converters.rs
|
Apache-2.0
|
pub(crate) fn convert_screen_edge(edge: ScreenEdge) -> winit::platform::ios::ScreenEdge {
match edge {
ScreenEdge::None => winit::platform::ios::ScreenEdge::NONE,
ScreenEdge::Top => winit::platform::ios::ScreenEdge::TOP,
ScreenEdge::Bottom => winit::platform::ios::ScreenEdge::BOTTOM,
ScreenEdge::Left => winit::platform::ios::ScreenEdge::LEFT,
ScreenEdge::Right => winit::platform::ios::ScreenEdge::RIGHT,
ScreenEdge::All => winit::platform::ios::ScreenEdge::ALL,
}
}
|
Converts a [`bevy_window::ScreenEdge`] to a [`winit::platform::ios::ScreenEdge`].
|
convert_screen_edge
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/converters.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/converters.rs
|
Apache-2.0
|
fn on_remove_cursor_icon(trigger: On<Remove, CursorIcon>, mut commands: Commands) {
// Use `try_insert` to avoid panic if the window is being destroyed.
commands
.entity(trigger.target())
.try_insert(PendingCursor(Some(CursorSource::System(
convert_system_cursor_icon(SystemCursorIcon::Default),
))));
}
|
Resets the cursor to the default icon when `CursorIcon` is removed.
|
on_remove_cursor_icon
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/cursor.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/cursor.rs
|
Apache-2.0
|
pub(crate) fn extract_rgba_pixels(image: &Image) -> Option<Vec<u8>> {
match image.texture_descriptor.format {
TextureFormat::Rgba8Unorm
| TextureFormat::Rgba8UnormSrgb
| TextureFormat::Rgba8Snorm
| TextureFormat::Rgba8Uint
| TextureFormat::Rgba8Sint => Some(image.data.clone()?),
TextureFormat::Rgba32Float => image.data.as_ref().map(|data| {
data.chunks(4)
.map(|chunk| {
let chunk = chunk.try_into().unwrap();
let num = bytemuck::cast_ref::<[u8; 4], f32>(chunk);
ops::round(num.clamp(0.0, 1.0) * 255.0) as u8
})
.collect()
}),
_ => None,
}
}
|
Extracts the RGBA pixel data from `image`, converting it if necessary.
Only supports rgba8 and rgba32float formats.
|
extract_rgba_pixels
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/custom_cursor.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/custom_cursor.rs
|
Apache-2.0
|
pub(crate) fn extract_and_transform_rgba_pixels(
image: &Image,
flip_x: bool,
flip_y: bool,
rect: Rect,
) -> Option<Vec<u8>> {
let image_data = extract_rgba_pixels(image)?;
let width = rect.width() as usize;
let height = rect.height() as usize;
let mut sub_image_data = Vec::with_capacity(width * height * 4); // assuming 4 bytes per pixel (RGBA8)
for y in 0..height {
for x in 0..width {
let src_x = if flip_x { width - 1 - x } else { x };
let src_y = if flip_y { height - 1 - y } else { y };
let index = ((rect.min.y as usize + src_y)
* image.texture_descriptor.size.width as usize
+ (rect.min.x as usize + src_x))
* 4;
sub_image_data.extend_from_slice(&image_data[index..index + 4]);
}
}
Some(sub_image_data)
}
|
Returns the `image` data as a `Vec<u8>` for the specified sub-region.
The image is flipped along the x and y axes if `flip_x` and `flip_y` are
`true`, respectively.
Only supports rgba8 and rgba32float formats.
|
extract_and_transform_rgba_pixels
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/custom_cursor.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/custom_cursor.rs
|
Apache-2.0
|
pub(crate) fn transform_hotspot(
hotspot: (u16, u16),
flip_x: bool,
flip_y: bool,
rect: Rect,
) -> (u16, u16) {
let hotspot_x = hotspot.0 as f32;
let hotspot_y = hotspot.1 as f32;
let (width, height) = (rect.width(), rect.height());
let hotspot_x = if flip_x {
(width - 1.0).max(0.0) - hotspot_x
} else {
hotspot_x
};
let hotspot_y = if flip_y {
(height - 1.0).max(0.0) - hotspot_y
} else {
hotspot_y
};
(hotspot_x as u16, hotspot_y as u16)
}
|
Transforms the `hotspot` coordinates based on whether the image is flipped
or not. The `rect` is used to determine the image's dimensions.
|
transform_hotspot
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/custom_cursor.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/custom_cursor.rs
|
Apache-2.0
|
pub fn winit_runner<T: BufferedEvent>(mut app: App, event_loop: EventLoop<T>) -> AppExit {
if app.plugins_state() == PluginsState::Ready {
app.finish();
app.cleanup();
}
app.world_mut()
.insert_resource(EventLoopProxyWrapper(event_loop.create_proxy()));
let runner_state = WinitAppRunnerState::new(app);
trace!("starting winit event loop");
// The winit docs mention using `spawn` instead of `run` on Wasm.
// https://docs.rs/winit/latest/winit/platform/web/trait.EventLoopExtWebSys.html#tymethod.spawn_app
cfg_if::cfg_if! {
if #[cfg(target_arch = "wasm32")] {
event_loop.spawn_app(runner_state);
AppExit::Success
} else {
let mut runner_state = runner_state;
if let Err(err) = event_loop.run_app(&mut runner_state) {
error!("winit event loop returned an error: {err}");
}
// If everything is working correctly then the event loop only exits after it's sent an exit code.
runner_state.app_exit.unwrap_or_else(|| {
error!("Failed to receive an app exit code! This is a bug");
AppExit::error()
})
}
}
}
|
The default [`App::runner`] for the [`WinitPlugin`](crate::WinitPlugin) plugin.
Overriding the app's [runner](bevy_app::App::runner) while using `WinitPlugin` will bypass the
`EventLoop`.
|
winit_runner
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/state.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/state.rs
|
Apache-2.0
|
pub fn create_windows<F: QueryFilter + 'static>(
event_loop: &ActiveEventLoop,
(
mut commands,
mut created_windows,
mut window_created_events,
mut handlers,
accessibility_requested,
monitors,
): SystemParamItem<CreateWindowParams<F>>,
) {
WINIT_WINDOWS.with_borrow_mut(|winit_windows| {
ACCESS_KIT_ADAPTERS.with_borrow_mut(|adapters| {
for (entity, mut window, handle_holder) in &mut created_windows {
if winit_windows.get_window(entity).is_some() {
continue;
}
info!("Creating new window {} ({})", window.title.as_str(), entity);
let winit_window = winit_windows.create_window(
event_loop,
entity,
&window,
adapters,
&mut handlers,
&accessibility_requested,
&monitors,
);
if let Some(theme) = winit_window.theme() {
window.window_theme = Some(convert_winit_theme(theme));
}
window
.resolution
.set_scale_factor_and_apply_to_physical_size(winit_window.scale_factor() as f32);
commands.entity(entity).insert((
CachedWindow {
window: window.clone(),
},
WinitWindowPressedKeys::default(),
));
if let Ok(handle_wrapper) = RawHandleWrapper::new(winit_window) {
commands.entity(entity).insert(handle_wrapper.clone());
if let Some(handle_holder) = handle_holder {
*handle_holder.0.lock().unwrap() = Some(handle_wrapper);
}
}
#[cfg(target_arch = "wasm32")]
{
if window.fit_canvas_to_parent {
let canvas = winit_window
.canvas()
.expect("window.canvas() can only be called in main thread.");
let style = canvas.style();
style.set_property("width", "100%").unwrap();
style.set_property("height", "100%").unwrap();
}
}
#[cfg(target_os = "ios")]
{
winit_window.recognize_pinch_gesture(window.recognize_pinch_gesture);
winit_window.recognize_rotation_gesture(window.recognize_rotation_gesture);
winit_window.recognize_doubletap_gesture(window.recognize_doubletap_gesture);
if let Some((min, max)) = window.recognize_pan_gesture {
winit_window.recognize_pan_gesture(true, min, max);
} else {
winit_window.recognize_pan_gesture(false, 0, 0);
}
}
window_created_events.write(WindowCreated { window: entity });
}
});
});
}
|
Creates new windows on the [`winit`] backend for each entity with a newly-added
[`Window`] component.
If any of these entities are missing required components, those will be added with their
default values.
|
create_windows
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/system.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/system.rs
|
Apache-2.0
|
pub(crate) fn check_keyboard_focus_lost(
mut focus_events: EventReader<WindowFocused>,
mut keyboard_focus: EventWriter<KeyboardFocusLost>,
mut keyboard_input: EventWriter<KeyboardInput>,
mut window_events: EventWriter<WindowEvent>,
mut q_windows: Query<&mut WinitWindowPressedKeys>,
) {
let mut focus_lost = vec![];
let mut focus_gained = false;
for e in focus_events.read() {
if e.focused {
focus_gained = true;
} else {
focus_lost.push(e.window);
}
}
if !focus_gained {
if !focus_lost.is_empty() {
window_events.write(WindowEvent::KeyboardFocusLost(KeyboardFocusLost));
keyboard_focus.write(KeyboardFocusLost);
}
for window in focus_lost {
let Ok(mut pressed_keys) = q_windows.get_mut(window) else {
continue;
};
for (key_code, logical_key) in pressed_keys.0.drain() {
let event = KeyboardInput {
key_code,
logical_key,
state: bevy_input::ButtonState::Released,
repeat: false,
window,
text: None,
};
window_events.write(WindowEvent::KeyboardInput(event.clone()));
keyboard_input.write(event);
}
}
}
}
|
Check whether keyboard focus was lost. This is different from window
focus in that swapping between Bevy windows keeps window focus.
|
check_keyboard_focus_lost
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/system.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/system.rs
|
Apache-2.0
|
pub fn create_monitors(
event_loop: &ActiveEventLoop,
(mut commands, mut monitors): SystemParamItem<CreateMonitorParams>,
) {
let primary_monitor = event_loop.primary_monitor();
let mut seen_monitors = vec![false; monitors.monitors.len()];
'outer: for monitor in event_loop.available_monitors() {
for (idx, (m, _)) in monitors.monitors.iter().enumerate() {
if &monitor == m {
seen_monitors[idx] = true;
continue 'outer;
}
}
let size = monitor.size();
let position = monitor.position();
let entity = commands
.spawn(Monitor {
name: monitor.name(),
physical_height: size.height,
physical_width: size.width,
physical_position: IVec2::new(position.x, position.y),
refresh_rate_millihertz: monitor.refresh_rate_millihertz(),
scale_factor: monitor.scale_factor(),
video_modes: monitor
.video_modes()
.map(|v| {
let size = v.size();
VideoMode {
physical_size: UVec2::new(size.width, size.height),
bit_depth: v.bit_depth(),
refresh_rate_millihertz: v.refresh_rate_millihertz(),
}
})
.collect(),
})
.id();
if primary_monitor.as_ref() == Some(&monitor) {
commands.entity(entity).insert(PrimaryMonitor);
}
seen_monitors.push(true);
monitors.monitors.push((monitor, entity));
}
let mut idx = 0;
monitors.monitors.retain(|(_m, entity)| {
if seen_monitors[idx] {
idx += 1;
true
} else {
info!("Monitor removed {}", entity);
commands.entity(*entity).despawn();
idx += 1;
false
}
});
}
|
Synchronize available monitors as reported by [`winit`] with [`Monitor`] entities in the world.
|
create_monitors
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/system.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/system.rs
|
Apache-2.0
|
pub(crate) fn changed_windows(
mut changed_windows: Query<(Entity, &mut Window, &mut CachedWindow), Changed<Window>>,
monitors: Res<WinitMonitors>,
mut window_resized: EventWriter<WindowResized>,
_non_send_marker: NonSendMarker,
) {
WINIT_WINDOWS.with_borrow(|winit_windows| {
for (entity, mut window, mut cache) in &mut changed_windows {
let Some(winit_window) = winit_windows.get_window(entity) else {
continue;
};
if window.title != cache.window.title {
winit_window.set_title(window.title.as_str());
}
if window.mode != cache.window.mode {
let new_mode = match window.mode {
WindowMode::BorderlessFullscreen(monitor_selection) => {
Some(Some(winit::window::Fullscreen::Borderless(select_monitor(
&monitors,
winit_window.primary_monitor(),
winit_window.current_monitor(),
&monitor_selection,
))))
}
WindowMode::Fullscreen(monitor_selection, video_mode_selection) => {
let monitor = &select_monitor(
&monitors,
winit_window.primary_monitor(),
winit_window.current_monitor(),
&monitor_selection,
)
.unwrap_or_else(|| {
panic!("Could not find monitor for {:?}", monitor_selection)
});
if let Some(video_mode) = get_selected_videomode(monitor, &video_mode_selection)
{
Some(Some(winit::window::Fullscreen::Exclusive(video_mode)))
} else {
warn!(
"Could not find valid fullscreen video mode for {:?} {:?}",
monitor_selection, video_mode_selection
);
None
}
}
WindowMode::Windowed => Some(None),
};
if let Some(new_mode) = new_mode {
if winit_window.fullscreen() != new_mode {
winit_window.set_fullscreen(new_mode);
}
}
}
if window.resolution != cache.window.resolution {
let mut physical_size = PhysicalSize::new(
window.resolution.physical_width(),
window.resolution.physical_height(),
);
let cached_physical_size = PhysicalSize::new(
cache.window.physical_width(),
cache.window.physical_height(),
);
let base_scale_factor = window.resolution.base_scale_factor();
// Note: this may be different from `winit`'s base scale factor if
// `scale_factor_override` is set to Some(f32)
let scale_factor = window.scale_factor();
let cached_scale_factor = cache.window.scale_factor();
// Check and update `winit`'s physical size only if the window is not maximized
if scale_factor != cached_scale_factor && !winit_window.is_maximized() {
let logical_size =
if let Some(cached_factor) = cache.window.resolution.scale_factor_override() {
physical_size.to_logical::<f32>(cached_factor as f64)
} else {
physical_size.to_logical::<f32>(base_scale_factor as f64)
};
// Scale factor changed, updating physical and logical size
if let Some(forced_factor) = window.resolution.scale_factor_override() {
// This window is overriding the OS-suggested DPI, so its physical size
// should be set based on the overriding value. Its logical size already
// incorporates any resize constraints.
physical_size = logical_size.to_physical::<u32>(forced_factor as f64);
} else {
physical_size = logical_size.to_physical::<u32>(base_scale_factor as f64);
}
}
if physical_size != cached_physical_size {
if let Some(new_physical_size) = winit_window.request_inner_size(physical_size) {
react_to_resize(entity, &mut window, new_physical_size, &mut window_resized);
}
}
}
if window.physical_cursor_position() != cache.window.physical_cursor_position() {
if let Some(physical_position) = window.physical_cursor_position() {
let position = PhysicalPosition::new(physical_position.x, physical_position.y);
if let Err(err) = winit_window.set_cursor_position(position) {
error!("could not set cursor position: {}", err);
}
}
}
if window.cursor_options.grab_mode != cache.window.cursor_options.grab_mode
&& crate::winit_windows::attempt_grab(winit_window, window.cursor_options.grab_mode)
.is_err()
{
window.cursor_options.grab_mode = cache.window.cursor_options.grab_mode;
}
if window.cursor_options.visible != cache.window.cursor_options.visible {
winit_window.set_cursor_visible(window.cursor_options.visible);
}
if window.cursor_options.hit_test != cache.window.cursor_options.hit_test {
if let Err(err) = winit_window.set_cursor_hittest(window.cursor_options.hit_test) {
window.cursor_options.hit_test = cache.window.cursor_options.hit_test;
warn!(
"Could not set cursor hit test for window {}: {}",
window.title, err
);
}
}
if window.decorations != cache.window.decorations
&& window.decorations != winit_window.is_decorated()
{
winit_window.set_decorations(window.decorations);
}
if window.resizable != cache.window.resizable
&& window.resizable != winit_window.is_resizable()
{
winit_window.set_resizable(window.resizable);
}
if window.enabled_buttons != cache.window.enabled_buttons {
winit_window.set_enabled_buttons(convert_enabled_buttons(window.enabled_buttons));
}
if window.resize_constraints != cache.window.resize_constraints {
let constraints = window.resize_constraints.check_constraints();
let min_inner_size = LogicalSize {
width: constraints.min_width,
height: constraints.min_height,
};
let max_inner_size = LogicalSize {
width: constraints.max_width,
height: constraints.max_height,
};
winit_window.set_min_inner_size(Some(min_inner_size));
if constraints.max_width.is_finite() && constraints.max_height.is_finite() {
winit_window.set_max_inner_size(Some(max_inner_size));
}
}
if window.position != cache.window.position {
if let Some(position) = crate::winit_window_position(
&window.position,
&window.resolution,
&monitors,
winit_window.primary_monitor(),
winit_window.current_monitor(),
) {
let should_set = match winit_window.outer_position() {
Ok(current_position) => current_position != position,
_ => true,
};
if should_set {
winit_window.set_outer_position(position);
}
}
}
if let Some(maximized) = window.internal.take_maximize_request() {
winit_window.set_maximized(maximized);
}
if let Some(minimized) = window.internal.take_minimize_request() {
winit_window.set_minimized(minimized);
}
if window.internal.take_move_request() {
if let Err(e) = winit_window.drag_window() {
warn!("Winit returned an error while attempting to drag the window: {e}");
}
}
if let Some(resize_direction) = window.internal.take_resize_request() {
if let Err(e) =
winit_window.drag_resize_window(convert_resize_direction(resize_direction))
{
warn!("Winit returned an error while attempting to drag resize the window: {e}");
}
}
if window.focused != cache.window.focused && window.focused {
winit_window.focus_window();
}
if window.window_level != cache.window.window_level {
winit_window.set_window_level(convert_window_level(window.window_level));
}
// Currently unsupported changes
if window.transparent != cache.window.transparent {
window.transparent = cache.window.transparent;
warn!("Winit does not currently support updating transparency after window creation.");
}
#[cfg(target_arch = "wasm32")]
if window.canvas != cache.window.canvas {
window.canvas.clone_from(&cache.window.canvas);
warn!(
"Bevy currently doesn't support modifying the window canvas after initialization."
);
}
if window.ime_enabled != cache.window.ime_enabled {
winit_window.set_ime_allowed(window.ime_enabled);
}
if window.ime_position != cache.window.ime_position {
winit_window.set_ime_cursor_area(
LogicalPosition::new(window.ime_position.x, window.ime_position.y),
PhysicalSize::new(10, 10),
);
}
if window.window_theme != cache.window.window_theme {
winit_window.set_theme(window.window_theme.map(convert_window_theme));
}
if window.visible != cache.window.visible {
winit_window.set_visible(window.visible);
}
#[cfg(target_os = "ios")]
{
if window.recognize_pinch_gesture != cache.window.recognize_pinch_gesture {
winit_window.recognize_pinch_gesture(window.recognize_pinch_gesture);
}
if window.recognize_rotation_gesture != cache.window.recognize_rotation_gesture {
winit_window.recognize_rotation_gesture(window.recognize_rotation_gesture);
}
if window.recognize_doubletap_gesture != cache.window.recognize_doubletap_gesture {
winit_window.recognize_doubletap_gesture(window.recognize_doubletap_gesture);
}
if window.recognize_pan_gesture != cache.window.recognize_pan_gesture {
match (
window.recognize_pan_gesture,
cache.window.recognize_pan_gesture,
) {
(Some(_), Some(_)) => {
warn!("Bevy currently doesn't support modifying PanGesture number of fingers recognition. Please disable it before re-enabling it with the new number of fingers");
}
(Some((min, max)), _) => winit_window.recognize_pan_gesture(true, min, max),
_ => winit_window.recognize_pan_gesture(false, 0, 0),
}
}
if window.prefers_home_indicator_hidden != cache.window.prefers_home_indicator_hidden {
winit_window
.set_prefers_home_indicator_hidden(window.prefers_home_indicator_hidden);
}
if window.prefers_status_bar_hidden != cache.window.prefers_status_bar_hidden {
winit_window.set_prefers_status_bar_hidden(window.prefers_status_bar_hidden);
}
if window.preferred_screen_edges_deferring_system_gestures
!= cache
.window
.preferred_screen_edges_deferring_system_gestures
{
use crate::converters::convert_screen_edge;
let preferred_edge =
convert_screen_edge(window.preferred_screen_edges_deferring_system_gestures);
winit_window.set_preferred_screen_edges_deferring_system_gestures(preferred_edge);
}
}
cache.window = window.clone();
}
});
}
|
Propagates changes from [`Window`] entities to the [`winit`] backend.
# Notes
- [`Window::present_mode`] and [`Window::composite_alpha_mode`] changes are handled by the `bevy_render` crate.
- [`Window::transparent`] cannot be changed after the window is created.
- [`Window::canvas`] cannot be changed after the window is created.
- [`Window::focused`] cannot be manually changed to `false` after the window is created.
|
changed_windows
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/system.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/system.rs
|
Apache-2.0
|
pub fn game() -> Self {
WinitSettings {
focused_mode: UpdateMode::Continuous,
unfocused_mode: UpdateMode::reactive_low_power(Duration::from_secs_f64(1.0 / 60.0)), /* 60Hz, */
}
}
|
Default settings for games.
[`Continuous`](UpdateMode::Continuous) if windows have focus,
[`reactive_low_power`](UpdateMode::reactive_low_power) otherwise.
|
game
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/winit_config.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/winit_config.rs
|
Apache-2.0
|
pub fn desktop_app() -> Self {
WinitSettings {
focused_mode: UpdateMode::reactive(Duration::from_secs(5)),
unfocused_mode: UpdateMode::reactive_low_power(Duration::from_secs(60)),
}
}
|
Default settings for desktop applications.
[`Reactive`](UpdateMode::Reactive) if windows have focus,
[`reactive_low_power`](UpdateMode::reactive_low_power) otherwise.
Use the [`EventLoopProxy`](crate::EventLoopProxy) to request a redraw from outside bevy.
|
desktop_app
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/winit_config.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/winit_config.rs
|
Apache-2.0
|
pub fn mobile() -> Self {
WinitSettings {
focused_mode: UpdateMode::reactive(Duration::from_secs_f32(1.0 / 60.0)),
unfocused_mode: UpdateMode::reactive_low_power(Duration::from_secs(1)),
}
}
|
Default settings for mobile.
[`Reactive`](UpdateMode::Reactive) if windows have focus,
[`reactive_low_power`](UpdateMode::reactive_low_power) otherwise.
Use the [`EventLoopProxy`](crate::EventLoopProxy) to request a redraw from outside bevy.
|
mobile
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/winit_config.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/winit_config.rs
|
Apache-2.0
|
pub fn update_mode(&self, focused: bool) -> UpdateMode {
match focused {
true => self.focused_mode,
false => self.unfocused_mode,
}
}
|
Returns the current [`UpdateMode`].
**Note:** The output depends on whether the window has focus or not.
|
update_mode
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/winit_config.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/winit_config.rs
|
Apache-2.0
|
pub fn reactive(wait: Duration) -> Self {
Self::Reactive {
wait,
react_to_device_events: true,
react_to_user_events: true,
react_to_window_events: true,
}
}
|
Reactive mode, will update the app for any kind of event
|
reactive
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/winit_config.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/winit_config.rs
|
Apache-2.0
|
pub fn reactive_low_power(wait: Duration) -> Self {
Self::Reactive {
wait,
react_to_device_events: false,
react_to_user_events: true,
react_to_window_events: true,
}
}
|
Low power mode
Unlike [`Reactive`](`UpdateMode::reactive()`), this will ignore events that
don't come from interacting with a window, like [`MouseMotion`](winit::event::DeviceEvent::MouseMotion).
Use this if, for example, you only want your app to update when the mouse cursor is
moving over a window, not just moving in general. This can greatly reduce power consumption.
|
reactive_low_power
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/winit_config.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/winit_config.rs
|
Apache-2.0
|
pub fn create_window(
&mut self,
event_loop: &ActiveEventLoop,
entity: Entity,
window: &Window,
adapters: &mut AccessKitAdapters,
handlers: &mut WinitActionRequestHandlers,
accessibility_requested: &AccessibilityRequested,
monitors: &WinitMonitors,
) -> &WindowWrapper<WinitWindow> {
let mut winit_window_attributes = WinitWindow::default_attributes();
// Due to a UIA limitation, winit windows need to be invisible for the
// AccessKit adapter is initialized.
winit_window_attributes = winit_window_attributes.with_visible(false);
let maybe_selected_monitor = &match window.mode {
WindowMode::BorderlessFullscreen(monitor_selection)
| WindowMode::Fullscreen(monitor_selection, _) => select_monitor(
monitors,
event_loop.primary_monitor(),
None,
&monitor_selection,
),
WindowMode::Windowed => None,
};
winit_window_attributes = match window.mode {
WindowMode::BorderlessFullscreen(_) => winit_window_attributes
.with_fullscreen(Some(Fullscreen::Borderless(maybe_selected_monitor.clone()))),
WindowMode::Fullscreen(monitor_selection, video_mode_selection) => {
let select_monitor = &maybe_selected_monitor
.clone()
.expect("Unable to get monitor.");
if let Some(video_mode) =
get_selected_videomode(select_monitor, &video_mode_selection)
{
winit_window_attributes.with_fullscreen(Some(Fullscreen::Exclusive(video_mode)))
} else {
warn!(
"Could not find valid fullscreen video mode for {:?} {:?}",
monitor_selection, video_mode_selection
);
winit_window_attributes
}
}
WindowMode::Windowed => {
if let Some(position) = winit_window_position(
&window.position,
&window.resolution,
monitors,
event_loop.primary_monitor(),
None,
) {
winit_window_attributes = winit_window_attributes.with_position(position);
}
let logical_size = LogicalSize::new(window.width(), window.height());
if let Some(sf) = window.resolution.scale_factor_override() {
let inner_size = logical_size.to_physical::<f64>(sf.into());
winit_window_attributes.with_inner_size(inner_size)
} else {
winit_window_attributes.with_inner_size(logical_size)
}
}
};
// It's crucial to avoid setting the window's final visibility here;
// as explained above, the window must be invisible until the AccessKit
// adapter is created.
winit_window_attributes = winit_window_attributes
.with_window_level(convert_window_level(window.window_level))
.with_theme(window.window_theme.map(convert_window_theme))
.with_resizable(window.resizable)
.with_enabled_buttons(convert_enabled_buttons(window.enabled_buttons))
.with_decorations(window.decorations)
.with_transparent(window.transparent)
.with_active(window.focused);
#[cfg(target_os = "windows")]
{
use winit::platform::windows::WindowAttributesExtWindows;
winit_window_attributes =
winit_window_attributes.with_skip_taskbar(window.skip_taskbar);
winit_window_attributes =
winit_window_attributes.with_clip_children(window.clip_children);
}
#[cfg(target_os = "macos")]
{
use winit::platform::macos::WindowAttributesExtMacOS;
winit_window_attributes = winit_window_attributes
.with_movable_by_window_background(window.movable_by_window_background)
.with_fullsize_content_view(window.fullsize_content_view)
.with_has_shadow(window.has_shadow)
.with_titlebar_hidden(!window.titlebar_shown)
.with_titlebar_transparent(window.titlebar_transparent)
.with_title_hidden(!window.titlebar_show_title)
.with_titlebar_buttons_hidden(!window.titlebar_show_buttons);
}
#[cfg(target_os = "ios")]
{
use crate::converters::convert_screen_edge;
use winit::platform::ios::WindowAttributesExtIOS;
let preferred_edge =
convert_screen_edge(window.preferred_screen_edges_deferring_system_gestures);
winit_window_attributes = winit_window_attributes
.with_preferred_screen_edges_deferring_system_gestures(preferred_edge);
winit_window_attributes = winit_window_attributes
.with_prefers_home_indicator_hidden(window.prefers_home_indicator_hidden);
winit_window_attributes = winit_window_attributes
.with_prefers_status_bar_hidden(window.prefers_status_bar_hidden);
}
let display_info = DisplayInfo {
window_physical_resolution: (
window.resolution.physical_width(),
window.resolution.physical_height(),
),
window_logical_resolution: (window.resolution.width(), window.resolution.height()),
monitor_name: maybe_selected_monitor
.as_ref()
.and_then(MonitorHandle::name),
scale_factor: maybe_selected_monitor
.as_ref()
.map(MonitorHandle::scale_factor),
refresh_rate_millihertz: maybe_selected_monitor
.as_ref()
.and_then(MonitorHandle::refresh_rate_millihertz),
};
bevy_log::debug!("{display_info}");
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "windows"
))]
if let Some(name) = &window.name {
#[cfg(all(
feature = "wayland",
any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
)
))]
{
winit_window_attributes =
winit::platform::wayland::WindowAttributesExtWayland::with_name(
winit_window_attributes,
name.clone(),
"",
);
}
#[cfg(all(
feature = "x11",
any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
)
))]
{
winit_window_attributes = winit::platform::x11::WindowAttributesExtX11::with_name(
winit_window_attributes,
name.clone(),
"",
);
}
#[cfg(target_os = "windows")]
{
winit_window_attributes =
winit::platform::windows::WindowAttributesExtWindows::with_class_name(
winit_window_attributes,
name.clone(),
);
}
}
let constraints = window.resize_constraints.check_constraints();
let min_inner_size = LogicalSize {
width: constraints.min_width,
height: constraints.min_height,
};
let max_inner_size = LogicalSize {
width: constraints.max_width,
height: constraints.max_height,
};
let winit_window_attributes =
if constraints.max_width.is_finite() && constraints.max_height.is_finite() {
winit_window_attributes
.with_min_inner_size(min_inner_size)
.with_max_inner_size(max_inner_size)
} else {
winit_window_attributes.with_min_inner_size(min_inner_size)
};
#[expect(clippy::allow_attributes, reason = "`unused_mut` is not always linted")]
#[allow(
unused_mut,
reason = "This variable needs to be mutable if `cfg(target_arch = \"wasm32\")`"
)]
let mut winit_window_attributes = winit_window_attributes.with_title(window.title.as_str());
#[cfg(target_arch = "wasm32")]
{
use wasm_bindgen::JsCast;
use winit::platform::web::WindowAttributesExtWebSys;
if let Some(selector) = &window.canvas {
let window = web_sys::window().unwrap();
let document = window.document().unwrap();
let canvas = document
.query_selector(selector)
.expect("Cannot query for canvas element.");
if let Some(canvas) = canvas {
let canvas = canvas.dyn_into::<web_sys::HtmlCanvasElement>().ok();
winit_window_attributes = winit_window_attributes.with_canvas(canvas);
} else {
panic!("Cannot find element: {}.", selector);
}
}
winit_window_attributes =
winit_window_attributes.with_prevent_default(window.prevent_default_event_handling);
winit_window_attributes = winit_window_attributes.with_append(true);
}
let winit_window = event_loop.create_window(winit_window_attributes).unwrap();
let name = window.title.clone();
prepare_accessibility_for_window(
event_loop,
&winit_window,
entity,
name,
accessibility_requested.clone(),
adapters,
handlers,
);
// Now that the AccessKit adapter is created, it's safe to show
// the window.
winit_window.set_visible(window.visible);
// Do not set the grab mode on window creation if it's none. It can fail on mobile.
if window.cursor_options.grab_mode != CursorGrabMode::None {
let _ = attempt_grab(&winit_window, window.cursor_options.grab_mode);
}
winit_window.set_cursor_visible(window.cursor_options.visible);
// Do not set the cursor hittest on window creation if it's false, as it will always fail on
// some platforms and log an unfixable warning.
if !window.cursor_options.hit_test {
if let Err(err) = winit_window.set_cursor_hittest(window.cursor_options.hit_test) {
warn!(
"Could not set cursor hit test for window {}: {}",
window.title, err
);
}
}
self.entity_to_winit.insert(entity, winit_window.id());
self.winit_to_entity.insert(winit_window.id(), entity);
self.windows
.entry(winit_window.id())
.insert(WindowWrapper::new(winit_window))
.into_mut()
}
|
Creates a `winit` window and associates it with our entity.
|
create_window
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/winit_windows.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/winit_windows.rs
|
Apache-2.0
|
pub fn get_window(&self, entity: Entity) -> Option<&WindowWrapper<WinitWindow>> {
self.entity_to_winit
.get(&entity)
.and_then(|winit_id| self.windows.get(winit_id))
}
|
Get the winit window that is associated with our entity.
|
get_window
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/winit_windows.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/winit_windows.rs
|
Apache-2.0
|
pub fn remove_window(&mut self, entity: Entity) -> Option<WindowWrapper<WinitWindow>> {
let winit_id = self.entity_to_winit.remove(&entity)?;
self.winit_to_entity.remove(&winit_id);
self.windows.remove(&winit_id)
}
|
Remove a window from winit.
This should mostly just be called when the window is closing.
|
remove_window
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/winit_windows.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/winit_windows.rs
|
Apache-2.0
|
pub fn get_selected_videomode(
monitor: &MonitorHandle,
selection: &VideoModeSelection,
) -> Option<VideoModeHandle> {
match selection {
VideoModeSelection::Current => get_current_videomode(monitor),
VideoModeSelection::Specific(specified) => monitor.video_modes().find(|mode| {
mode.size().width == specified.physical_size.x
&& mode.size().height == specified.physical_size.y
&& mode.refresh_rate_millihertz() == specified.refresh_rate_millihertz
&& mode.bit_depth() == specified.bit_depth
}),
}
}
|
Returns some [`winit::monitor::VideoModeHandle`] given a [`MonitorHandle`] and a
[`VideoModeSelection`] or None if no valid matching video mode was found.
|
get_selected_videomode
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/winit_windows.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/winit_windows.rs
|
Apache-2.0
|
fn get_current_videomode(monitor: &MonitorHandle) -> Option<VideoModeHandle> {
monitor
.video_modes()
.filter(|mode| {
mode.size() == monitor.size()
&& Some(mode.refresh_rate_millihertz()) == monitor.refresh_rate_millihertz()
})
.max_by_key(VideoModeHandle::bit_depth)
}
|
Gets a monitor's current video-mode.
TODO: When Winit 0.31 releases this function can be removed and replaced with
`MonitorHandle::current_video_mode()`
|
get_current_videomode
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/winit_windows.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/winit_windows.rs
|
Apache-2.0
|
pub fn select_monitor(
monitors: &WinitMonitors,
primary_monitor: Option<MonitorHandle>,
current_monitor: Option<MonitorHandle>,
monitor_selection: &MonitorSelection,
) -> Option<MonitorHandle> {
use bevy_window::MonitorSelection::*;
match monitor_selection {
Current => {
if current_monitor.is_none() {
warn!("Can't select current monitor on window creation or cannot find current monitor!");
}
current_monitor
}
Primary => primary_monitor,
Index(n) => monitors.nth(*n),
Entity(entity) => monitors.find_entity(*entity),
}
}
|
Selects a monitor based on the given [`MonitorSelection`].
|
select_monitor
|
rust
|
bevyengine/bevy
|
crates/bevy_winit/src/winit_windows.rs
|
https://github.com/bevyengine/bevy/blob/master/crates/bevy_winit/src/winit_windows.rs
|
Apache-2.0
|
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>,
mut seeded_rng: ResMut<SeededRng>,
) {
if *i == 0 {
// Generate a random color on first run.
*draw_color = Color::linear_rgb(
seeded_rng.0.r#gen(),
seeded_rng.0.r#gen(),
seeded_rng.0.r#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(
seeded_rng.0.r#gen(),
seeded_rng.0.r#gen(),
seeded_rng.0.r#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;
}
|
Every fixed update tick, draw one more pixel to make a spiral pattern
|
draw
|
rust
|
bevyengine/bevy
|
examples/2d/cpu_draw.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/2d/cpu_draw.rs
|
Apache-2.0
|
pub fn extract_colored_mesh2d(
mut commands: Commands,
mut previous_len: Local<usize>,
// When extracting, you must use `Extract` to mark the `SystemParam`s
// which should be taken from the main world.
query: Extract<
Query<
(
Entity,
RenderEntity,
&ViewVisibility,
&GlobalTransform,
&Mesh2d,
),
With<ColoredMesh2d>,
>,
>,
mut render_mesh_instances: ResMut<RenderColoredMesh2dInstances>,
) {
let mut values = Vec::with_capacity(*previous_len);
for (entity, render_entity, view_visibility, transform, handle) in &query {
if !view_visibility.get() {
continue;
}
let transforms = Mesh2dTransforms {
world_from_local: (&transform.affine()).into(),
flags: MeshFlags::empty().bits(),
};
values.push((render_entity, ColoredMesh2d));
render_mesh_instances.insert(
entity.into(),
RenderMesh2dInstance {
mesh_asset_id: handle.0.id(),
transforms,
material_bind_group_id: Material2dBindGroupId::default(),
automatic_batching: false,
tag: 0,
},
);
}
*previous_len = values.len();
commands.try_insert_batch(values);
}
|
Extract the [`ColoredMesh2d`] marker component into the render app
|
extract_colored_mesh2d
|
rust
|
bevyengine/bevy
|
examples/2d/mesh2d_manual.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/2d/mesh2d_manual.rs
|
Apache-2.0
|
pub fn queue_colored_mesh2d(
transparent_draw_functions: Res<DrawFunctions<Transparent2d>>,
colored_mesh2d_pipeline: Res<ColoredMesh2dPipeline>,
mut pipelines: ResMut<SpecializedRenderPipelines<ColoredMesh2dPipeline>>,
pipeline_cache: Res<PipelineCache>,
render_meshes: Res<RenderAssets<RenderMesh>>,
render_mesh_instances: Res<RenderColoredMesh2dInstances>,
mut transparent_render_phases: ResMut<ViewSortedRenderPhases<Transparent2d>>,
views: Query<(&RenderVisibleEntities, &ExtractedView, &Msaa)>,
) {
if render_mesh_instances.is_empty() {
return;
}
// Iterate each view (a camera is a view)
for (visible_entities, view, msaa) in &views {
let Some(transparent_phase) = transparent_render_phases.get_mut(&view.retained_view_entity)
else {
continue;
};
let draw_colored_mesh2d = transparent_draw_functions.read().id::<DrawColoredMesh2d>();
let mesh_key = Mesh2dPipelineKey::from_msaa_samples(msaa.samples())
| Mesh2dPipelineKey::from_hdr(view.hdr);
// Queue all entities visible to that view
for (render_entity, visible_entity) in visible_entities.iter::<Mesh2d>() {
if let Some(mesh_instance) = render_mesh_instances.get(visible_entity) {
let mesh2d_handle = mesh_instance.mesh_asset_id;
let mesh2d_transforms = &mesh_instance.transforms;
// Get our specialized pipeline
let mut mesh2d_key = mesh_key;
let Some(mesh) = render_meshes.get(mesh2d_handle) else {
continue;
};
mesh2d_key |= Mesh2dPipelineKey::from_primitive_topology(mesh.primitive_topology());
let pipeline_id =
pipelines.specialize(&pipeline_cache, &colored_mesh2d_pipeline, mesh2d_key);
let mesh_z = mesh2d_transforms.world_from_local.translation.z;
transparent_phase.add(Transparent2d {
entity: (*render_entity, *visible_entity),
draw_function: draw_colored_mesh2d,
pipeline: pipeline_id,
// The 2d render items are sorted according to their z value before rendering,
// in order to get correct transparency
sort_key: FloatOrd(mesh_z),
// This material is not batched
batch_range: 0..1,
extra_index: PhaseItemExtraIndex::None,
extracted_index: usize::MAX,
indexed: mesh.indexed(),
});
}
}
}
}
|
Queue the 2d meshes marked with [`ColoredMesh2d`] using our custom pipeline and draw function
|
queue_colored_mesh2d
|
rust
|
bevyengine/bevy
|
examples/2d/mesh2d_manual.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/2d/mesh2d_manual.rs
|
Apache-2.0
|
fn sprite_movement(time: Res<Time>, mut sprite_position: Query<(&mut Direction, &mut Transform)>) {
for (mut logo, mut transform) in &mut sprite_position {
match *logo {
Direction::Right => transform.translation.x += 150. * time.delta_secs(),
Direction::Left => transform.translation.x -= 150. * time.delta_secs(),
}
if transform.translation.x > 200. {
*logo = Direction::Left;
} else if transform.translation.x < -200. {
*logo = Direction::Right;
}
}
}
|
The sprite is animated by changing its translation depending on the time that has passed since
the last frame.
|
sprite_movement
|
rust
|
bevyengine/bevy
|
examples/2d/move_sprite.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/2d/move_sprite.rs
|
Apache-2.0
|
fn setup_mesh(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
) {
commands.spawn((
Mesh2d(meshes.add(Capsule2d::default())),
MeshMaterial2d(materials.add(Color::BLACK)),
Transform::from_xyz(25., 0., 2.).with_scale(Vec3::splat(32.)),
Rotate,
PIXEL_PERFECT_LAYERS,
));
}
|
Spawns a capsule mesh on the pixel-perfect layer.
|
setup_mesh
|
rust
|
bevyengine/bevy
|
examples/2d/pixel_grid_snap.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/2d/pixel_grid_snap.rs
|
Apache-2.0
|
fn rotate(time: Res<Time>, mut transforms: Query<&mut Transform, With<Rotate>>) {
for mut transform in &mut transforms {
let dt = time.delta_secs();
transform.rotate_z(dt);
}
}
|
Rotates entities to demonstrate grid snapping.
|
rotate
|
rust
|
bevyengine/bevy
|
examples/2d/pixel_grid_snap.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/2d/pixel_grid_snap.rs
|
Apache-2.0
|
fn fit_canvas(
mut resize_events: EventReader<WindowResized>,
mut projection: Single<&mut Projection, With<OuterCamera>>,
) {
let Projection::Orthographic(projection) = &mut **projection else {
return;
};
for event in resize_events.read() {
let h_scale = event.width / RES_WIDTH as f32;
let v_scale = event.height / RES_HEIGHT as f32;
projection.scale = 1. / h_scale.min(v_scale).round();
}
}
|
Scales camera projection to fit the window (integer multiples only).
|
fit_canvas
|
rust
|
bevyengine/bevy
|
examples/2d/pixel_grid_snap.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/2d/pixel_grid_snap.rs
|
Apache-2.0
|
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let ship_handle = asset_server.load("textures/simplespace/ship_C.png");
let enemy_a_handle = asset_server.load("textures/simplespace/enemy_A.png");
let enemy_b_handle = asset_server.load("textures/simplespace/enemy_B.png");
commands.spawn(Camera2d);
// Create a minimal UI explaining how to interact with the example
commands.spawn((
Text::new("Up Arrow: Move Forward\nLeft / Right Arrow: Turn"),
Node {
position_type: PositionType::Absolute,
top: Val::Px(12.0),
left: Val::Px(12.0),
..default()
},
));
let horizontal_margin = BOUNDS.x / 4.0;
let vertical_margin = BOUNDS.y / 4.0;
// Player controlled ship
commands.spawn((
Sprite::from_image(ship_handle),
Player {
movement_speed: 500.0, // Meters per second
rotation_speed: f32::to_radians(360.0), // Degrees per second
},
));
// Enemy that snaps to face the player spawns on the bottom and left
commands.spawn((
Sprite::from_image(enemy_a_handle.clone()),
Transform::from_xyz(0.0 - horizontal_margin, 0.0, 0.0),
SnapToPlayer,
));
commands.spawn((
Sprite::from_image(enemy_a_handle),
Transform::from_xyz(0.0, 0.0 - vertical_margin, 0.0),
SnapToPlayer,
));
// Enemy that rotates to face the player enemy spawns on the top and right
commands.spawn((
Sprite::from_image(enemy_b_handle.clone()),
Transform::from_xyz(0.0 + horizontal_margin, 0.0, 0.0),
RotateToPlayer {
rotation_speed: f32::to_radians(45.0), // Degrees per second
},
));
commands.spawn((
Sprite::from_image(enemy_b_handle),
Transform::from_xyz(0.0, 0.0 + vertical_margin, 0.0),
RotateToPlayer {
rotation_speed: f32::to_radians(90.0), // Degrees per second
},
));
}
|
Add the game's entities to our world and creates an orthographic camera for 2D rendering.
The Bevy coordinate system is the same for 2D and 3D, in terms of 2D this means that:
* `X` axis goes from left to right (`+X` points right)
* `Y` axis goes from bottom to top (`+Y` point up)
* `Z` axis goes from far to near (`+Z` points towards you, out of the screen)
The origin is at the center of the screen.
|
setup
|
rust
|
bevyengine/bevy
|
examples/2d/rotation.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/2d/rotation.rs
|
Apache-2.0
|
fn player_movement_system(
time: Res<Time>,
keyboard_input: Res<ButtonInput<KeyCode>>,
query: Single<(&Player, &mut Transform)>,
) {
let (ship, mut transform) = query.into_inner();
let mut rotation_factor = 0.0;
let mut movement_factor = 0.0;
if keyboard_input.pressed(KeyCode::ArrowLeft) {
rotation_factor += 1.0;
}
if keyboard_input.pressed(KeyCode::ArrowRight) {
rotation_factor -= 1.0;
}
if keyboard_input.pressed(KeyCode::ArrowUp) {
movement_factor += 1.0;
}
// Update the ship rotation around the Z axis (perpendicular to the 2D plane of the screen)
transform.rotate_z(rotation_factor * ship.rotation_speed * time.delta_secs());
// Get the ship's forward vector by applying the current rotation to the ships initial facing
// vector
let movement_direction = transform.rotation * Vec3::Y;
// Get the distance the ship will move based on direction, the ship's movement speed and delta
// time
let movement_distance = movement_factor * ship.movement_speed * time.delta_secs();
// Create the change in translation using the new movement direction and distance
let translation_delta = movement_direction * movement_distance;
// Update the ship translation with our new translation delta
transform.translation += translation_delta;
// Bound the ship within the invisible level bounds
let extents = Vec3::from((BOUNDS / 2.0, 0.0));
transform.translation = transform.translation.min(extents).max(-extents);
}
|
Demonstrates applying rotation and movement based on keyboard input.
|
player_movement_system
|
rust
|
bevyengine/bevy
|
examples/2d/rotation.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/2d/rotation.rs
|
Apache-2.0
|
fn snap_to_player_system(
mut query: Query<&mut Transform, (With<SnapToPlayer>, Without<Player>)>,
player_transform: Single<&Transform, With<Player>>,
) {
// Get the player translation in 2D
let player_translation = player_transform.translation.xy();
for mut enemy_transform in &mut query {
// Get the vector from the enemy ship to the player ship in 2D and normalize it.
let to_player = (player_translation - enemy_transform.translation.xy()).normalize();
// Get the quaternion to rotate from the initial enemy facing direction to the direction
// facing the player
let rotate_to_player = Quat::from_rotation_arc(Vec3::Y, to_player.extend(0.));
// Rotate the enemy to face the player
enemy_transform.rotation = rotate_to_player;
}
}
|
Demonstrates snapping the enemy ship to face the player ship immediately.
|
snap_to_player_system
|
rust
|
bevyengine/bevy
|
examples/2d/rotation.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/2d/rotation.rs
|
Apache-2.0
|
fn rotate_to_player_system(
time: Res<Time>,
mut query: Query<(&RotateToPlayer, &mut Transform), Without<Player>>,
player_transform: Single<&Transform, With<Player>>,
) {
// Get the player translation in 2D
let player_translation = player_transform.translation.xy();
for (config, mut enemy_transform) in &mut query {
// Get the enemy ship forward vector in 2D (already unit length)
let enemy_forward = (enemy_transform.rotation * Vec3::Y).xy();
// Get the vector from the enemy ship to the player ship in 2D and normalize it.
let to_player = (player_translation - enemy_transform.translation.xy()).normalize();
// Get the dot product between the enemy forward vector and the direction to the player.
let forward_dot_player = enemy_forward.dot(to_player);
// If the dot product is approximately 1.0 then the enemy is already facing the player and
// we can early out.
if (forward_dot_player - 1.0).abs() < f32::EPSILON {
continue;
}
// Get the right vector of the enemy ship in 2D (already unit length)
let enemy_right = (enemy_transform.rotation * Vec3::X).xy();
// Get the dot product of the enemy right vector and the direction to the player ship.
// If the dot product is negative them we need to rotate counter clockwise, if it is
// positive we need to rotate clockwise. Note that `copysign` will still return 1.0 if the
// dot product is 0.0 (because the player is directly behind the enemy, so perpendicular
// with the right vector).
let right_dot_player = enemy_right.dot(to_player);
// Determine the sign of rotation from the right dot player. We need to negate the sign
// here as the 2D bevy co-ordinate system rotates around +Z, which is pointing out of the
// screen. Due to the right hand rule, positive rotation around +Z is counter clockwise and
// negative is clockwise.
let rotation_sign = -f32::copysign(1.0, right_dot_player);
// Limit rotation so we don't overshoot the target. We need to convert our dot product to
// an angle here so we can get an angle of rotation to clamp against.
let max_angle = ops::acos(forward_dot_player.clamp(-1.0, 1.0)); // Clamp acos for safety
// Calculate angle of rotation with limit
let rotation_angle =
rotation_sign * (config.rotation_speed * time.delta_secs()).min(max_angle);
// Rotate the enemy to face the player
enemy_transform.rotate_z(rotation_angle);
}
}
|
Demonstrates rotating an enemy ship to face the player ship at a given rotation speed.
This method uses the vector dot product to determine if the enemy is facing the player and
if not, which way to rotate to face the player. The dot product on two unit length vectors
will return a value between -1.0 and +1.0 which tells us the following about the two vectors:
* If the result is 1.0 the vectors are pointing in the same direction, the angle between them is
0 degrees.
* If the result is 0.0 the vectors are perpendicular, the angle between them is 90 degrees.
* If the result is -1.0 the vectors are parallel but pointing in opposite directions, the angle
between them is 180 degrees.
* If the result is positive the vectors are pointing in roughly the same direction, the angle
between them is greater than 0 and less than 90 degrees.
* If the result is negative the vectors are pointing in roughly opposite directions, the angle
between them is greater than 90 and less than 180 degrees.
It is possible to get the angle by taking the arc cosine (`acos`) of the dot product. It is
often unnecessary to do this though. Beware than `acos` will return `NaN` if the input is less
than -1.0 or greater than 1.0. This can happen even when working with unit vectors due to
floating point precision loss, so it pays to clamp your dot product value before calling
`acos`.
|
rotate_to_player_system
|
rust
|
bevyengine/bevy
|
examples/2d/rotation.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/2d/rotation.rs
|
Apache-2.0
|
fn create_texture_atlas(
folder: &LoadedFolder,
padding: Option<UVec2>,
sampling: Option<ImageSampler>,
textures: &mut ResMut<Assets<Image>>,
) -> (TextureAtlasLayout, TextureAtlasSources, Handle<Image>) {
// Build a texture atlas using the individual sprites
let mut texture_atlas_builder = TextureAtlasBuilder::default();
texture_atlas_builder.padding(padding.unwrap_or_default());
for handle in folder.handles.iter() {
let id = handle.id().typed_unchecked::<Image>();
let Some(texture) = textures.get(id) else {
warn!(
"{} did not resolve to an `Image` asset.",
handle.path().unwrap()
);
continue;
};
texture_atlas_builder.add_texture(Some(id), texture);
}
let (texture_atlas_layout, texture_atlas_sources, texture) =
texture_atlas_builder.build().unwrap();
let texture = textures.add(texture);
// Update the sampling settings of the texture atlas
let image = textures.get_mut(&texture).unwrap();
image.sampler = sampling.unwrap_or_default();
(texture_atlas_layout, texture_atlas_sources, texture)
}
|
Create a texture atlas with the given padding and sampling settings
from the individual sprites in the given folder.
|
create_texture_atlas
|
rust
|
bevyengine/bevy
|
examples/2d/texture_atlas.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/2d/texture_atlas.rs
|
Apache-2.0
|
fn create_sprite_from_atlas(
commands: &mut Commands,
translation: (f32, f32, f32),
atlas_texture: Handle<Image>,
atlas_sources: TextureAtlasSources,
atlas_handle: Handle<TextureAtlasLayout>,
vendor_handle: &Handle<Image>,
) {
commands.spawn((
Transform {
translation: Vec3::new(translation.0, translation.1, translation.2),
scale: Vec3::splat(3.0),
..default()
},
Sprite::from_atlas_image(
atlas_texture,
atlas_sources.handle(atlas_handle, vendor_handle).unwrap(),
),
));
}
|
Create and spawn a sprite from a texture atlas
|
create_sprite_from_atlas
|
rust
|
bevyengine/bevy
|
examples/2d/texture_atlas.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/2d/texture_atlas.rs
|
Apache-2.0
|
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()
};
}
}
}
|
This system lets you toggle various wireframe settings
|
update_colors
|
rust
|
bevyengine/bevy
|
examples/2d/wireframe_2d.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/2d/wireframe_2d.rs
|
Apache-2.0
|
fn create_material_variants(
mut commands: Commands,
mut materials: ResMut<Assets<StandardMaterial>>,
new_meshes: Query<
(Entity, &MeshMaterial3d<StandardMaterial>),
(
Added<MeshMaterial3d<StandardMaterial>>,
Without<MaterialVariants>,
),
>,
) {
for (entity, anisotropic_material_handle) in new_meshes.iter() {
let Some(anisotropic_material) = materials.get(anisotropic_material_handle).cloned() else {
continue;
};
commands.entity(entity).insert(MaterialVariants {
anisotropic: anisotropic_material_handle.0.clone(),
isotropic: materials.add(StandardMaterial {
anisotropy_texture: None,
anisotropy_strength: 0.0,
anisotropy_rotation: 0.0,
..anisotropic_material
}),
});
}
}
|
For each material, creates a version with the anisotropy removed.
This allows the user to press Enter to toggle anisotropy on and off.
|
create_material_variants
|
rust
|
bevyengine/bevy
|
examples/3d/anisotropy.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/anisotropy.rs
|
Apache-2.0
|
fn animate_light(
mut lights: Query<&mut Transform, Or<(With<DirectionalLight>, With<PointLight>)>>,
time: Res<Time>,
) {
let now = time.elapsed_secs();
for mut transform in lights.iter_mut() {
transform.translation = vec3(ops::cos(now), 1.0, ops::sin(now)) * vec3(3.0, 4.0, 3.0);
transform.look_at(Vec3::ZERO, Vec3::Y);
}
}
|
A system that animates the light every frame, if there is one.
|
animate_light
|
rust
|
bevyengine/bevy
|
examples/3d/anisotropy.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/anisotropy.rs
|
Apache-2.0
|
fn rotate_camera(
mut camera: Query<&mut Transform, With<Camera>>,
app_status: Res<AppStatus>,
time: Res<Time>,
mut stopwatch: Local<Stopwatch>,
) {
if app_status.light_mode == LightMode::EnvironmentMap {
stopwatch.tick(time.delta());
}
let now = stopwatch.elapsed_secs();
for mut transform in camera.iter_mut() {
*transform = Transform::from_translation(
Quat::from_rotation_y(now).mul_vec3(CAMERA_INITIAL_POSITION),
)
.looking_at(Vec3::ZERO, Vec3::Y);
}
}
|
A system that rotates the camera if the environment map is enabled.
|
rotate_camera
|
rust
|
bevyengine/bevy
|
examples/3d/anisotropy.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/anisotropy.rs
|
Apache-2.0
|
fn handle_input(
mut commands: Commands,
asset_server: Res<AssetServer>,
cameras: Query<Entity, With<Camera>>,
lights: Query<Entity, Or<(With<DirectionalLight>, With<PointLight>)>>,
mut meshes: Query<(&mut MeshMaterial3d<StandardMaterial>, &MaterialVariants)>,
mut scenes: Query<(&mut Visibility, &Scene)>,
keyboard: Res<ButtonInput<KeyCode>>,
mut app_status: ResMut<AppStatus>,
) {
// If Space was pressed, change the lighting.
if keyboard.just_pressed(KeyCode::Space) {
match app_status.light_mode {
LightMode::Directional => {
// Switch to a point light. Despawn all existing lights and
// create the light point.
app_status.light_mode = LightMode::Point;
for light in lights.iter() {
commands.entity(light).despawn();
}
spawn_point_light(&mut commands);
}
LightMode::Point => {
// Switch to the environment map. Despawn all existing lights,
// and create the skybox and environment map.
app_status.light_mode = LightMode::EnvironmentMap;
for light in lights.iter() {
commands.entity(light).despawn();
}
for camera in cameras.iter() {
add_skybox_and_environment_map(&mut commands, &asset_server, camera);
}
}
LightMode::EnvironmentMap => {
// Switch back to a directional light. Despawn the skybox and
// environment map light, and recreate the directional light.
app_status.light_mode = LightMode::Directional;
for camera in cameras.iter() {
commands
.entity(camera)
.remove::<Skybox>()
.remove::<EnvironmentMapLight>();
}
spawn_directional_light(&mut commands);
}
}
}
// If Enter was pressed, toggle anisotropy on and off.
if keyboard.just_pressed(KeyCode::Enter) {
app_status.anisotropy_enabled = !app_status.anisotropy_enabled;
// Go through each mesh and alter its material.
for (mut material_handle, material_variants) in meshes.iter_mut() {
material_handle.0 = if app_status.anisotropy_enabled {
material_variants.anisotropic.clone()
} else {
material_variants.isotropic.clone()
}
}
}
if keyboard.just_pressed(KeyCode::KeyQ) {
app_status.visible_scene = app_status.visible_scene.next();
for (mut visibility, scene) in scenes.iter_mut() {
let new_vis = if *scene == app_status.visible_scene {
Visibility::Inherited
} else {
Visibility::Hidden
};
*visibility = new_vis;
}
}
}
|
Handles requests from the user to change the lighting or toggle anisotropy.
|
handle_input
|
rust
|
bevyengine/bevy
|
examples/3d/anisotropy.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/anisotropy.rs
|
Apache-2.0
|
fn update_help_text(mut text_query: Query<&mut Text>, app_status: Res<AppStatus>) {
for mut text in text_query.iter_mut() {
*text = app_status.create_help_text();
}
}
|
A system that updates the help text based on the current app status.
|
update_help_text
|
rust
|
bevyengine/bevy
|
examples/3d/anisotropy.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/anisotropy.rs
|
Apache-2.0
|
fn add_skybox_and_environment_map(
commands: &mut Commands,
asset_server: &AssetServer,
entity: Entity,
) {
commands
.entity(entity)
.insert(Skybox {
brightness: 5000.0,
image: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
..default()
})
.insert(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: 2500.0,
..default()
});
}
|
Adds the skybox and environment map to the scene.
|
add_skybox_and_environment_map
|
rust
|
bevyengine/bevy
|
examples/3d/anisotropy.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/anisotropy.rs
|
Apache-2.0
|
fn create_help_text(&self) -> Text {
// Choose the appropriate help text for the anisotropy toggle.
let material_variant_help_text = if self.anisotropy_enabled {
"Press Enter to disable anisotropy"
} else {
"Press Enter to enable anisotropy"
};
// Choose the appropriate help text for the light toggle.
let light_help_text = match self.light_mode {
LightMode::Directional => "Press Space to switch to a point light",
LightMode::Point => "Press Space to switch to an environment map",
LightMode::EnvironmentMap => "Press Space to switch to a directional light",
};
// Choose the appropriate help text for the scene selector.
let mesh_help_text = format!("Press Q to change to {}", self.visible_scene.next());
// Build the `Text` object.
format!(
"{}\n{}\n{}",
material_variant_help_text, light_help_text, mesh_help_text,
)
.into()
}
|
Creates the help text as appropriate for the current app status.
|
create_help_text
|
rust
|
bevyengine/bevy
|
examples/3d/anisotropy.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/anisotropy.rs
|
Apache-2.0
|
fn draw_selectable_menu_item(ui: &mut String, label: &str, shortcut: char, enabled: bool) {
let star = if enabled { "*" } else { "" };
let _ = writeln!(*ui, "({shortcut}) {star}{label}{star}");
}
|
Writes a simple menu item that can be on or off.
|
draw_selectable_menu_item
|
rust
|
bevyengine/bevy
|
examples/3d/anti_aliasing.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/anti_aliasing.rs
|
Apache-2.0
|
fn spawn_car_paint_sphere(
commands: &mut Commands,
materials: &mut Assets<StandardMaterial>,
asset_server: &AssetServer,
sphere: &Handle<Mesh>,
) {
commands
.spawn((
Mesh3d(sphere.clone()),
MeshMaterial3d(materials.add(StandardMaterial {
clearcoat: 1.0,
clearcoat_perceptual_roughness: 0.1,
normal_map_texture: Some(asset_server.load_with_settings(
"textures/BlueNoise-Normal.png",
|settings: &mut ImageLoaderSettings| settings.is_srgb = false,
)),
metallic: 0.9,
perceptual_roughness: 0.5,
base_color: BLUE.into(),
..default()
})),
Transform::from_xyz(-1.0, 1.0, 0.0).with_scale(Vec3::splat(SPHERE_SCALE)),
))
.insert(ExampleSphere);
}
|
Spawn a regular object with a clearcoat layer. This looks like car paint.
|
spawn_car_paint_sphere
|
rust
|
bevyengine/bevy
|
examples/3d/clearcoat.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/clearcoat.rs
|
Apache-2.0
|
fn spawn_golf_ball(commands: &mut Commands, asset_server: &AssetServer) {
commands.spawn((
SceneRoot(
asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/GolfBall/GolfBall.glb")),
),
Transform::from_xyz(1.0, 1.0, 0.0).with_scale(Vec3::splat(SPHERE_SCALE)),
ExampleSphere,
));
}
|
Spawns an object with both a clearcoat normal map (a scratched varnish) and
a main layer normal map (the golf ball pattern).
This object is in glTF format, using the `KHR_materials_clearcoat`
extension.
|
spawn_golf_ball
|
rust
|
bevyengine/bevy
|
examples/3d/clearcoat.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/clearcoat.rs
|
Apache-2.0
|
fn spawn_scratched_gold_ball(
commands: &mut Commands,
materials: &mut Assets<StandardMaterial>,
asset_server: &AssetServer,
sphere: &Handle<Mesh>,
) {
commands
.spawn((
Mesh3d(sphere.clone()),
MeshMaterial3d(materials.add(StandardMaterial {
clearcoat: 1.0,
clearcoat_perceptual_roughness: 0.3,
clearcoat_normal_texture: Some(asset_server.load_with_settings(
"textures/ScratchedGold-Normal.png",
|settings: &mut ImageLoaderSettings| settings.is_srgb = false,
)),
metallic: 0.9,
perceptual_roughness: 0.1,
base_color: GOLD.into(),
..default()
})),
Transform::from_xyz(1.0, -1.0, 0.0).with_scale(Vec3::splat(SPHERE_SCALE)),
))
.insert(ExampleSphere);
}
|
Spawns an object with only a clearcoat normal map (a scratch pattern) and no
main layer normal map.
|
spawn_scratched_gold_ball
|
rust
|
bevyengine/bevy
|
examples/3d/clearcoat.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/clearcoat.rs
|
Apache-2.0
|
fn spawn_camera(commands: &mut Commands, asset_server: &AssetServer) {
commands
.spawn((
Camera3d::default(),
Hdr,
Projection::Perspective(PerspectiveProjection {
fov: 27.0 / 180.0 * PI,
..default()
}),
Transform::from_xyz(0.0, 0.0, 10.0),
AcesFitted,
))
.insert(Skybox {
brightness: 5000.0,
image: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
..default()
})
.insert(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()
});
}
|
Spawns a camera with associated skybox and environment map.
|
spawn_camera
|
rust
|
bevyengine/bevy
|
examples/3d/clearcoat.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/clearcoat.rs
|
Apache-2.0
|
fn handle_input(
mut commands: Commands,
mut light_query: Query<Entity, Or<(With<PointLight>, With<DirectionalLight>)>>,
keyboard: Res<ButtonInput<KeyCode>>,
mut light_mode: ResMut<LightMode>,
) {
if !keyboard.just_pressed(KeyCode::Space) {
return;
}
for light in light_query.iter_mut() {
match *light_mode {
LightMode::Point => {
*light_mode = LightMode::Directional;
commands
.entity(light)
.remove::<PointLight>()
.insert(create_directional_light());
}
LightMode::Directional => {
*light_mode = LightMode::Point;
commands
.entity(light)
.remove::<DirectionalLight>()
.insert(create_point_light());
}
}
}
}
|
Handles the user pressing Space to change the type of light from point to
directional and vice versa.
|
handle_input
|
rust
|
bevyengine/bevy
|
examples/3d/clearcoat.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/clearcoat.rs
|
Apache-2.0
|
fn update_help_text(mut text_query: Query<&mut Text>, light_mode: Res<LightMode>) {
for mut text in text_query.iter_mut() {
*text = light_mode.create_help_text();
}
}
|
Updates the help text at the bottom of the screen.
|
update_help_text
|
rust
|
bevyengine/bevy
|
examples/3d/clearcoat.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/clearcoat.rs
|
Apache-2.0
|
fn create_point_light() -> PointLight {
PointLight {
color: WHITE.into(),
intensity: 100000.0,
..default()
}
}
|
Creates or recreates the moving point light.
|
create_point_light
|
rust
|
bevyengine/bevy
|
examples/3d/clearcoat.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/clearcoat.rs
|
Apache-2.0
|
fn create_directional_light() -> DirectionalLight {
DirectionalLight {
color: WHITE.into(),
illuminance: 1000.0,
..default()
}
}
|
Creates or recreates the moving directional light.
|
create_directional_light
|
rust
|
bevyengine/bevy
|
examples/3d/clearcoat.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/clearcoat.rs
|
Apache-2.0
|
fn create_help_text(&self) -> Text {
let help_text = match *self {
LightMode::Point => "Press Space to switch to a directional light",
LightMode::Directional => "Press Space to switch to a point light",
};
Text::new(help_text)
}
|
Creates the help text at the bottom of the screen.
|
create_help_text
|
rust
|
bevyengine/bevy
|
examples/3d/clearcoat.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/clearcoat.rs
|
Apache-2.0
|
fn spawn_cube(
commands: &mut Commands,
meshes: &mut Assets<Mesh>,
materials: &mut Assets<ExtendedMaterial<StandardMaterial, CustomDecalExtension>>,
) {
// Rotate the cube a bit just to make it more interesting.
let mut transform = Transform::IDENTITY;
transform.rotate_y(FRAC_PI_3);
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(3.0, 3.0, 3.0))),
MeshMaterial3d(materials.add(ExtendedMaterial {
base: StandardMaterial {
base_color: SILVER.into(),
..default()
},
extension: CustomDecalExtension {},
})),
transform,
));
}
|
Spawns the cube onto which the decals are projected.
|
spawn_cube
|
rust
|
bevyengine/bevy
|
examples/3d/clustered_decals.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/clustered_decals.rs
|
Apache-2.0
|
fn spawn_buttons(commands: &mut Commands) {
// Spawn the radio buttons that allow the user to select an object to
// control.
commands
.spawn(widgets::main_ui_node())
.with_children(|parent| {
widgets::spawn_option_buttons(
parent,
"Drag to Move",
&[
(Selection::Camera, "Camera"),
(Selection::DecalA, "Decal A"),
(Selection::DecalB, "Decal B"),
],
);
});
// Spawn the drag buttons that allow the user to control the scale and roll
// of the selected object.
commands
.spawn(Node {
flex_direction: FlexDirection::Row,
position_type: PositionType::Absolute,
right: Val::Px(10.0),
bottom: Val::Px(10.0),
column_gap: Val::Px(6.0),
..default()
})
.with_children(|parent| {
spawn_drag_button(parent, "Scale").insert(DragMode::Scale);
spawn_drag_button(parent, "Roll").insert(DragMode::Roll);
});
}
|
Spawns the buttons at the bottom of the screen.
|
spawn_buttons
|
rust
|
bevyengine/bevy
|
examples/3d/clustered_decals.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/clustered_decals.rs
|
Apache-2.0
|
fn spawn_drag_button<'a>(
commands: &'a mut ChildSpawnerCommands,
label: &str,
) -> EntityCommands<'a> {
let mut kid = commands.spawn(Node {
border: BUTTON_BORDER,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
padding: BUTTON_PADDING,
..default()
});
kid.insert((
Button,
BackgroundColor(Color::BLACK),
BorderRadius::all(BUTTON_BORDER_RADIUS_SIZE),
BUTTON_BORDER_COLOR,
))
.with_children(|parent| {
widgets::spawn_ui_text(parent, label, Color::WHITE);
});
kid
}
|
Spawns a button that the user can drag to change a parameter.
|
spawn_drag_button
|
rust
|
bevyengine/bevy
|
examples/3d/clustered_decals.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/clustered_decals.rs
|
Apache-2.0
|
fn spawn_help_text(commands: &mut Commands, app_status: &AppStatus) {
commands.spawn((
Text::new(create_help_string(app_status)),
Node {
position_type: PositionType::Absolute,
top: Val::Px(12.0),
left: Val::Px(12.0),
..default()
},
HelpText,
));
}
|
Spawns the help text at the top of the screen.
|
spawn_help_text
|
rust
|
bevyengine/bevy
|
examples/3d/clustered_decals.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/clustered_decals.rs
|
Apache-2.0
|
fn add_buttons(commands: &mut Commands, font: &Handle<Font>, color_grading: &ColorGrading) {
// Spawn the parent node that contains all the buttons.
commands
.spawn(Node {
flex_direction: FlexDirection::Column,
position_type: PositionType::Absolute,
row_gap: Val::Px(6.0),
left: Val::Px(12.0),
bottom: Val::Px(12.0),
..default()
})
.with_children(|parent| {
// Create the first row, which contains the global controls.
add_buttons_for_global_controls(parent, color_grading, font);
// Create the rows for individual controls.
for section in [
SelectedColorGradingSection::Highlights,
SelectedColorGradingSection::Midtones,
SelectedColorGradingSection::Shadows,
] {
add_buttons_for_section(parent, section, color_grading, font);
}
});
}
|
Adds all the buttons on the bottom of the scene.
|
add_buttons
|
rust
|
bevyengine/bevy
|
examples/3d/color_grading.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/color_grading.rs
|
Apache-2.0
|
fn add_buttons_for_global_controls(
parent: &mut ChildSpawnerCommands,
color_grading: &ColorGrading,
font: &Handle<Font>,
) {
// Add the parent node for the row.
parent.spawn(Node::default()).with_children(|parent| {
// Add some placeholder text to fill this column.
parent.spawn(Node {
width: Val::Px(125.0),
..default()
});
// Add each global color grading option button.
for option in [
SelectedGlobalColorGradingOption::Exposure,
SelectedGlobalColorGradingOption::Temperature,
SelectedGlobalColorGradingOption::Tint,
SelectedGlobalColorGradingOption::Hue,
] {
add_button_for_value(
parent,
SelectedColorGradingOption::Global(option),
color_grading,
font,
);
}
});
}
|
Adds the buttons for the global controls (those that control the scene as a
whole as opposed to shadows, midtones, or highlights).
|
add_buttons_for_global_controls
|
rust
|
bevyengine/bevy
|
examples/3d/color_grading.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/color_grading.rs
|
Apache-2.0
|
fn add_buttons_for_section(
parent: &mut ChildSpawnerCommands,
section: SelectedColorGradingSection,
color_grading: &ColorGrading,
font: &Handle<Font>,
) {
// Spawn the row container.
parent
.spawn(Node {
align_items: AlignItems::Center,
..default()
})
.with_children(|parent| {
// Spawn the label ("Highlights", etc.)
add_text(parent, §ion.to_string(), font, Color::WHITE).insert(Node {
width: Val::Px(125.0),
..default()
});
// Spawn the buttons.
for option in [
SelectedSectionColorGradingOption::Saturation,
SelectedSectionColorGradingOption::Contrast,
SelectedSectionColorGradingOption::Gamma,
SelectedSectionColorGradingOption::Gain,
SelectedSectionColorGradingOption::Lift,
] {
add_button_for_value(
parent,
SelectedColorGradingOption::Section(section, option),
color_grading,
font,
);
}
});
}
|
Adds the buttons that control color grading for individual sections
(highlights, midtones, shadows).
|
add_buttons_for_section
|
rust
|
bevyengine/bevy
|
examples/3d/color_grading.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/color_grading.rs
|
Apache-2.0
|
fn add_button_for_value(
parent: &mut ChildSpawnerCommands,
option: SelectedColorGradingOption,
color_grading: &ColorGrading,
font: &Handle<Font>,
) {
// Add the button node.
parent
.spawn((
Button,
Node {
border: UiRect::all(Val::Px(1.0)),
width: Val::Px(200.0),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
padding: UiRect::axes(Val::Px(12.0), Val::Px(6.0)),
margin: UiRect::right(Val::Px(12.0)),
..default()
},
BorderColor::all(Color::WHITE),
BorderRadius::MAX,
BackgroundColor(Color::BLACK),
))
.insert(ColorGradingOptionWidget {
widget_type: ColorGradingOptionWidgetType::Button,
option,
})
.with_children(|parent| {
// Add the button label.
let label = match option {
SelectedColorGradingOption::Global(option) => option.to_string(),
SelectedColorGradingOption::Section(_, option) => option.to_string(),
};
add_text(parent, &label, font, Color::WHITE).insert(ColorGradingOptionWidget {
widget_type: ColorGradingOptionWidgetType::Label,
option,
});
// Add a spacer.
parent.spawn(Node {
flex_grow: 1.0,
..default()
});
// Add the value text.
add_text(
parent,
&format!("{:.3}", option.get(color_grading)),
font,
Color::WHITE,
)
.insert(ColorGradingOptionWidget {
widget_type: ColorGradingOptionWidgetType::Value,
option,
});
});
}
|
Adds a button that controls one of the color grading values.
|
add_button_for_value
|
rust
|
bevyengine/bevy
|
examples/3d/color_grading.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/color_grading.rs
|
Apache-2.0
|
fn add_help_text(
commands: &mut Commands,
font: &Handle<Font>,
currently_selected_option: &SelectedColorGradingOption,
) {
commands.spawn((
Text::new(create_help_text(currently_selected_option)),
TextFont {
font: font.clone(),
..default()
},
Node {
position_type: PositionType::Absolute,
left: Val::Px(12.0),
top: Val::Px(12.0),
..default()
},
HelpText,
));
}
|
Creates the help text at the top of the screen.
|
add_help_text
|
rust
|
bevyengine/bevy
|
examples/3d/color_grading.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/color_grading.rs
|
Apache-2.0
|
fn add_text<'a>(
parent: &'a mut ChildSpawnerCommands,
label: &str,
font: &Handle<Font>,
color: Color,
) -> EntityCommands<'a> {
parent.spawn((
Text::new(label),
TextFont {
font: font.clone(),
font_size: 15.0,
..default()
},
TextColor(color),
))
}
|
Adds some text to the scene.
|
add_text
|
rust
|
bevyengine/bevy
|
examples/3d/color_grading.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/color_grading.rs
|
Apache-2.0
|
fn get(&self, section: &ColorGradingSection) -> f32 {
match *self {
SelectedSectionColorGradingOption::Saturation => section.saturation,
SelectedSectionColorGradingOption::Contrast => section.contrast,
SelectedSectionColorGradingOption::Gamma => section.gamma,
SelectedSectionColorGradingOption::Gain => section.gain,
SelectedSectionColorGradingOption::Lift => section.lift,
}
}
|
Returns the appropriate value in the given color grading section.
|
get
|
rust
|
bevyengine/bevy
|
examples/3d/color_grading.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/color_grading.rs
|
Apache-2.0
|
fn get(&self, global: &ColorGradingGlobal) -> f32 {
match *self {
SelectedGlobalColorGradingOption::Exposure => global.exposure,
SelectedGlobalColorGradingOption::Temperature => global.temperature,
SelectedGlobalColorGradingOption::Tint => global.tint,
SelectedGlobalColorGradingOption::Hue => global.hue,
}
}
|
Returns the appropriate value in the given set of global color grading
values.
|
get
|
rust
|
bevyengine/bevy
|
examples/3d/color_grading.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/color_grading.rs
|
Apache-2.0
|
fn set(&self, global: &mut ColorGradingGlobal, value: f32) {
match *self {
SelectedGlobalColorGradingOption::Exposure => global.exposure = value,
SelectedGlobalColorGradingOption::Temperature => global.temperature = value,
SelectedGlobalColorGradingOption::Tint => global.tint = value,
SelectedGlobalColorGradingOption::Hue => global.hue = value,
}
}
|
Sets the appropriate value in the given set of global color grading
values.
|
set
|
rust
|
bevyengine/bevy
|
examples/3d/color_grading.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/color_grading.rs
|
Apache-2.0
|
fn get(&self, color_grading: &ColorGrading) -> f32 {
match self {
SelectedColorGradingOption::Global(option) => option.get(&color_grading.global),
SelectedColorGradingOption::Section(
SelectedColorGradingSection::Highlights,
option,
) => option.get(&color_grading.highlights),
SelectedColorGradingOption::Section(SelectedColorGradingSection::Midtones, option) => {
option.get(&color_grading.midtones)
}
SelectedColorGradingOption::Section(SelectedColorGradingSection::Shadows, option) => {
option.get(&color_grading.shadows)
}
}
}
|
Returns the appropriate value in the given set of color grading values.
|
get
|
rust
|
bevyengine/bevy
|
examples/3d/color_grading.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/color_grading.rs
|
Apache-2.0
|
fn set(&self, color_grading: &mut ColorGrading, value: f32) {
match self {
SelectedColorGradingOption::Global(option) => {
option.set(&mut color_grading.global, value);
}
SelectedColorGradingOption::Section(
SelectedColorGradingSection::Highlights,
option,
) => option.set(&mut color_grading.highlights, value),
SelectedColorGradingOption::Section(SelectedColorGradingSection::Midtones, option) => {
option.set(&mut color_grading.midtones, value);
}
SelectedColorGradingOption::Section(SelectedColorGradingSection::Shadows, option) => {
option.set(&mut color_grading.shadows, value);
}
}
}
|
Sets the appropriate value in the given set of color grading values.
|
set
|
rust
|
bevyengine/bevy
|
examples/3d/color_grading.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/color_grading.rs
|
Apache-2.0
|
fn handle_button_presses(
mut interactions: Query<(&Interaction, &ColorGradingOptionWidget), Changed<Interaction>>,
mut currently_selected_option: ResMut<SelectedColorGradingOption>,
) {
for (interaction, widget) in interactions.iter_mut() {
if widget.widget_type == ColorGradingOptionWidgetType::Button
&& *interaction == Interaction::Pressed
{
*currently_selected_option = widget.option;
}
}
}
|
Handles mouse clicks on the buttons when the user clicks on a new one.
|
handle_button_presses
|
rust
|
bevyengine/bevy
|
examples/3d/color_grading.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/color_grading.rs
|
Apache-2.0
|
fn update_ui_state(
mut buttons: Query<(
&mut BackgroundColor,
&mut BorderColor,
&ColorGradingOptionWidget,
)>,
button_text: Query<(Entity, &ColorGradingOptionWidget), (With<Text>, Without<HelpText>)>,
help_text: Single<Entity, With<HelpText>>,
mut writer: TextUiWriter,
cameras: Single<Ref<ColorGrading>>,
currently_selected_option: Res<SelectedColorGradingOption>,
) {
// Exit early if the UI didn't change
if !currently_selected_option.is_changed() && !cameras.is_changed() {
return;
}
// The currently-selected option is drawn with inverted colors.
for (mut background, mut border_color, widget) in buttons.iter_mut() {
if *currently_selected_option == widget.option {
*background = Color::WHITE.into();
*border_color = Color::BLACK.into();
} else {
*background = Color::BLACK.into();
*border_color = Color::WHITE.into();
}
}
let value_label = format!("{:.3}", currently_selected_option.get(cameras.as_ref()));
// Update the buttons.
for (entity, widget) in button_text.iter() {
// Set the text color.
let color = if *currently_selected_option == widget.option {
Color::BLACK
} else {
Color::WHITE
};
writer.for_each_color(entity, |mut text_color| {
text_color.0 = color;
});
// Update the displayed value, if this is the currently-selected option.
if widget.widget_type == ColorGradingOptionWidgetType::Value
&& *currently_selected_option == widget.option
{
writer.for_each_text(entity, |mut text| {
text.clone_from(&value_label);
});
}
}
// Update the help text.
*writer.text(*help_text, 0) = create_help_text(¤tly_selected_option);
}
|
Updates the state of the UI based on the current state.
|
update_ui_state
|
rust
|
bevyengine/bevy
|
examples/3d/color_grading.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/color_grading.rs
|
Apache-2.0
|
fn create_help_text(currently_selected_option: &SelectedColorGradingOption) -> String {
format!("Press Left/Right to adjust {currently_selected_option}")
}
|
Creates the help text at the top left of the window.
|
create_help_text
|
rust
|
bevyengine/bevy
|
examples/3d/color_grading.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/color_grading.rs
|
Apache-2.0
|
fn adjust_color_grading_option(
mut color_grading: Single<&mut ColorGrading>,
input: Res<ButtonInput<KeyCode>>,
currently_selected_option: Res<SelectedColorGradingOption>,
) {
let mut delta = 0.0;
if input.pressed(KeyCode::ArrowLeft) {
delta -= OPTION_ADJUSTMENT_SPEED;
}
if input.pressed(KeyCode::ArrowRight) {
delta += OPTION_ADJUSTMENT_SPEED;
}
if delta != 0.0 {
let new_value = currently_selected_option.get(color_grading.as_ref()) + delta;
currently_selected_option.set(&mut color_grading, new_value);
}
}
|
Processes keyboard input to change the value of the currently-selected color
grading option.
|
adjust_color_grading_option
|
rust
|
bevyengine/bevy
|
examples/3d/color_grading.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/color_grading.rs
|
Apache-2.0
|
fn adjust_focus(input: Res<ButtonInput<KeyCode>>, mut app_settings: ResMut<AppSettings>) {
// Change the focal distance if the user requested.
let distance_delta = if input.pressed(KeyCode::ArrowDown) {
-FOCAL_DISTANCE_SPEED
} else if input.pressed(KeyCode::ArrowUp) {
FOCAL_DISTANCE_SPEED
} else {
0.0
};
// Change the f-number if the user requested.
let f_stop_delta = if input.pressed(KeyCode::ArrowLeft) {
-APERTURE_F_STOP_SPEED
} else if input.pressed(KeyCode::ArrowRight) {
APERTURE_F_STOP_SPEED
} else {
0.0
};
app_settings.focal_distance =
(app_settings.focal_distance + distance_delta).max(MIN_FOCAL_DISTANCE);
app_settings.aperture_f_stops =
(app_settings.aperture_f_stops + f_stop_delta).max(MIN_APERTURE_F_STOPS);
}
|
Adjusts the focal distance and f-number per user inputs.
|
adjust_focus
|
rust
|
bevyengine/bevy
|
examples/3d/depth_of_field.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/depth_of_field.rs
|
Apache-2.0
|
fn change_mode(input: Res<ButtonInput<KeyCode>>, mut app_settings: ResMut<AppSettings>) {
if !input.just_pressed(KeyCode::Space) {
return;
}
app_settings.mode = match app_settings.mode {
Some(DepthOfFieldMode::Bokeh) => Some(DepthOfFieldMode::Gaussian),
Some(DepthOfFieldMode::Gaussian) => None,
None => Some(DepthOfFieldMode::Bokeh),
}
}
|
Changes the depth of field mode (Gaussian, bokeh, off) per user inputs.
|
change_mode
|
rust
|
bevyengine/bevy
|
examples/3d/depth_of_field.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/depth_of_field.rs
|
Apache-2.0
|
fn update_dof_settings(
mut commands: Commands,
view_targets: Query<Entity, With<Camera>>,
app_settings: Res<AppSettings>,
) {
let depth_of_field: Option<DepthOfField> = (*app_settings).into();
for view in view_targets.iter() {
match depth_of_field {
None => {
commands.entity(view).remove::<DepthOfField>();
}
Some(depth_of_field) => {
commands.entity(view).insert(depth_of_field);
}
}
}
}
|
Writes the depth of field settings into the camera.
|
update_dof_settings
|
rust
|
bevyengine/bevy
|
examples/3d/depth_of_field.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/depth_of_field.rs
|
Apache-2.0
|
fn tweak_scene(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut lights: Query<&mut DirectionalLight, Changed<DirectionalLight>>,
mut named_entities: Query<
(Entity, &GltfMeshName, &MeshMaterial3d<StandardMaterial>),
(With<Mesh3d>, Without<Lightmap>),
>,
) {
// Turn on shadows.
for mut light in lights.iter_mut() {
light.shadows_enabled = true;
}
// Add a nice lightmap to the circuit board.
for (entity, name, material) in named_entities.iter_mut() {
if &**name == "CircuitBoard" {
materials.get_mut(material).unwrap().lightmap_exposure = 10000.0;
commands.entity(entity).insert(Lightmap {
image: asset_server.load("models/DepthOfFieldExample/CircuitBoardLightmap.hdr"),
..default()
});
}
}
}
|
Makes one-time adjustments to the scene that can't be encoded in glTF.
|
tweak_scene
|
rust
|
bevyengine/bevy
|
examples/3d/depth_of_field.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/depth_of_field.rs
|
Apache-2.0
|
fn update_text(mut texts: Query<&mut Text>, app_settings: Res<AppSettings>) {
for mut text in texts.iter_mut() {
*text = create_text(&app_settings);
}
}
|
Update the help text entity per the current app settings.
|
update_text
|
rust
|
bevyengine/bevy
|
examples/3d/depth_of_field.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/depth_of_field.rs
|
Apache-2.0
|
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
// Spawn a fog volume with a voxelized version of the Stanford bunny.
commands.spawn((
Transform::from_xyz(0.0, 0.5, 0.0),
FogVolume {
density_texture: Some(asset_server.load("volumes/bunny.ktx2")),
density_factor: 1.0,
// Scatter as much of the light as possible, to brighten the bunny
// up.
scattering: 1.0,
..default()
},
));
// Spawn a bright directional light that illuminates the fog well.
commands.spawn((
Transform::from_xyz(1.0, 1.0, -0.3).looking_at(vec3(0.0, 0.5, 0.0), Vec3::Y),
DirectionalLight {
shadows_enabled: true,
illuminance: 32000.0,
..default()
},
// Make sure to add this for the light to interact with the fog.
VolumetricLight,
));
// Spawn a camera.
commands.spawn((
Camera3d::default(),
Transform::from_xyz(-0.75, 1.0, 2.0).looking_at(vec3(0.0, 0.0, 0.0), Vec3::Y),
Hdr,
VolumetricFog {
// Make this relatively high in order to increase the fog quality.
step_count: 64,
// Disable ambient light.
ambient_intensity: 0.0,
..default()
},
));
}
|
Spawns all the objects in the scene.
|
setup
|
rust
|
bevyengine/bevy
|
examples/3d/fog_volumes.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/fog_volumes.rs
|
Apache-2.0
|
fn rotate_camera(mut cameras: Query<&mut Transform, With<Camera3d>>) {
for mut camera_transform in cameras.iter_mut() {
*camera_transform =
Transform::from_translation(Quat::from_rotation_y(0.01) * camera_transform.translation)
.looking_at(vec3(0.0, 0.5, 0.0), Vec3::Y);
}
}
|
Rotates the camera a bit every frame.
|
rotate_camera
|
rust
|
bevyengine/bevy
|
examples/3d/fog_volumes.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/fog_volumes.rs
|
Apache-2.0
|
fn spawn_scene(commands: &mut Commands, asset_server: &AssetServer) {
commands
.spawn(SceneRoot(
asset_server.load(
GltfAssetLabel::Scene(0)
.from_asset("models/MixedLightingExample/MixedLightingExample.gltf"),
),
))
.observe(
|_: On<SceneInstanceReady>,
mut lighting_mode_change_event_writer: EventWriter<LightingModeChanged>| {
// When the scene loads, send a `LightingModeChanged` event so
// that we set up the lightmaps.
lighting_mode_change_event_writer.write(LightingModeChanged);
},
);
}
|
Spawns the scene.
The scene is loaded from a glTF file.
|
spawn_scene
|
rust
|
bevyengine/bevy
|
examples/3d/mixed_lighting.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/mixed_lighting.rs
|
Apache-2.0
|
fn spawn_buttons(commands: &mut Commands) {
commands
.spawn(widgets::main_ui_node())
.with_children(|parent| {
widgets::spawn_option_buttons(
parent,
"Lighting",
&[
(LightingMode::Baked, "Baked"),
(LightingMode::MixedDirect, "Mixed (Direct)"),
(LightingMode::MixedIndirect, "Mixed (Indirect)"),
(LightingMode::RealTime, "Real-Time"),
],
);
});
}
|
Spawns the buttons that allow the user to change the lighting mode.
|
spawn_buttons
|
rust
|
bevyengine/bevy
|
examples/3d/mixed_lighting.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/mixed_lighting.rs
|
Apache-2.0
|
fn spawn_help_text(commands: &mut Commands, app_status: &AppStatus) {
commands.spawn((
create_help_text(app_status),
Node {
position_type: PositionType::Absolute,
top: Val::Px(12.0),
left: Val::Px(12.0),
..default()
},
HelpText,
));
}
|
Spawns the help text at the top of the window.
|
spawn_help_text
|
rust
|
bevyengine/bevy
|
examples/3d/mixed_lighting.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/mixed_lighting.rs
|
Apache-2.0
|
fn update_lightmaps(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut materials: ResMut<Assets<StandardMaterial>>,
meshes: Query<(Entity, &GltfMeshName, &MeshMaterial3d<StandardMaterial>), With<Mesh3d>>,
mut lighting_mode_change_event_reader: EventReader<LightingModeChanged>,
app_status: Res<AppStatus>,
) {
// Only run if the lighting mode changed. (Note that a change event is fired
// when the scene first loads.)
if lighting_mode_change_event_reader.read().next().is_none() {
return;
}
// Select the lightmap to use, based on the lighting mode.
let lightmap: Option<Handle<Image>> = match app_status.lighting_mode {
LightingMode::Baked => {
Some(asset_server.load("lightmaps/MixedLightingExample-Baked.zstd.ktx2"))
}
LightingMode::MixedDirect => {
Some(asset_server.load("lightmaps/MixedLightingExample-MixedDirect.zstd.ktx2"))
}
LightingMode::MixedIndirect => {
Some(asset_server.load("lightmaps/MixedLightingExample-MixedIndirect.zstd.ktx2"))
}
LightingMode::RealTime => None,
};
'outer: for (entity, name, material) in &meshes {
// Add lightmaps to or remove lightmaps from the scenery objects in the
// scene (all objects but the sphere).
//
// Note that doing a linear search through the `LIGHTMAPS` array is
// inefficient, but we do it anyway in this example to improve clarity.
for (lightmap_name, uv_rect) in LIGHTMAPS {
if &**name != lightmap_name {
continue;
}
// Lightmap exposure defaults to zero, so we need to set it.
if let Some(ref mut material) = materials.get_mut(material) {
material.lightmap_exposure = LIGHTMAP_EXPOSURE;
}
// Add or remove the lightmap.
match lightmap {
Some(ref lightmap) => {
commands.entity(entity).insert(Lightmap {
image: (*lightmap).clone(),
uv_rect,
bicubic_sampling: false,
});
}
None => {
commands.entity(entity).remove::<Lightmap>();
}
}
continue 'outer;
}
// Add lightmaps to or remove lightmaps from the sphere.
if &**name == "Sphere" {
// Lightmap exposure defaults to zero, so we need to set it.
if let Some(ref mut material) = materials.get_mut(material) {
material.lightmap_exposure = LIGHTMAP_EXPOSURE;
}
// Add or remove the lightmap from the sphere. We only apply the
// lightmap in fully-baked mode.
match (&lightmap, app_status.lighting_mode) {
(Some(lightmap), LightingMode::Baked) => {
commands.entity(entity).insert(Lightmap {
image: (*lightmap).clone(),
uv_rect: SPHERE_UV_RECT,
bicubic_sampling: false,
});
}
_ => {
commands.entity(entity).remove::<Lightmap>();
}
}
}
}
}
|
Adds lightmaps to and/or removes lightmaps from objects in the scene when
the lighting mode changes.
This is also called right after the scene loads in order to set up the
lightmaps.
|
update_lightmaps
|
rust
|
bevyengine/bevy
|
examples/3d/mixed_lighting.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/mixed_lighting.rs
|
Apache-2.0
|
const fn uv_rect_opengl(gl_min: Vec2, size: Vec2) -> Rect {
let min = vec2(gl_min.x, 1.0 - gl_min.y - size.y);
Rect {
min,
max: vec2(min.x + size.x, min.y + size.y),
}
}
|
Converts a uv rectangle from the OpenGL coordinate system (origin in the
lower left) to the Vulkan coordinate system (origin in the upper left) that
Bevy uses.
For this particular example, the baking tool happened to use the OpenGL
coordinate system, so it was more convenient to do the conversion at compile
time than to pre-calculate and hard-code the values.
|
uv_rect_opengl
|
rust
|
bevyengine/bevy
|
examples/3d/mixed_lighting.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/mixed_lighting.rs
|
Apache-2.0
|
fn make_sphere_nonpickable(
mut commands: Commands,
mut query: Query<(Entity, &Name), (With<Mesh3d>, Without<Pickable>)>,
) {
for (sphere, name) in &mut query {
if &**name == "Sphere" {
commands.entity(sphere).insert(Pickable::IGNORE);
}
}
}
|
Ensures that clicking on the scene to move the sphere doesn't result in a
hit on the sphere itself.
|
make_sphere_nonpickable
|
rust
|
bevyengine/bevy
|
examples/3d/mixed_lighting.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/mixed_lighting.rs
|
Apache-2.0
|
fn update_directional_light(
mut lights: Query<&mut DirectionalLight>,
mut lighting_mode_change_event_reader: EventReader<LightingModeChanged>,
app_status: Res<AppStatus>,
) {
// Only run if the lighting mode changed. (Note that a change event is fired
// when the scene first loads.)
if lighting_mode_change_event_reader.read().next().is_none() {
return;
}
// Real-time direct light is used on the scenery if we're using mixed
// indirect or real-time mode.
let scenery_is_lit_in_real_time = matches!(
app_status.lighting_mode,
LightingMode::MixedIndirect | LightingMode::RealTime
);
for mut light in &mut lights {
light.affects_lightmapped_mesh_diffuse = scenery_is_lit_in_real_time;
// Don't bother enabling shadows if they won't show up on the scenery.
light.shadows_enabled = scenery_is_lit_in_real_time;
}
}
|
Updates the directional light settings as necessary when the lighting mode
changes.
|
update_directional_light
|
rust
|
bevyengine/bevy
|
examples/3d/mixed_lighting.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/mixed_lighting.rs
|
Apache-2.0
|
fn update_radio_buttons(
mut widgets: Query<
(
Entity,
Option<&mut BackgroundColor>,
Has<Text>,
&WidgetClickSender<LightingMode>,
),
Or<(With<RadioButton>, With<RadioButtonText>)>,
>,
app_status: Res<AppStatus>,
mut writer: TextUiWriter,
) {
for (entity, image, has_text, sender) in &mut widgets {
let selected = **sender == app_status.lighting_mode;
if let Some(mut bg_color) = image {
widgets::update_ui_radio_button(&mut bg_color, selected);
}
if has_text {
widgets::update_ui_radio_button_text(entity, &mut writer, selected);
}
}
}
|
Updates the state of the selection widgets at the bottom of the window when
the lighting mode changes.
|
update_radio_buttons
|
rust
|
bevyengine/bevy
|
examples/3d/mixed_lighting.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/mixed_lighting.rs
|
Apache-2.0
|
fn handle_lighting_mode_change(
mut widget_click_event_reader: EventReader<WidgetClickEvent<LightingMode>>,
mut lighting_mode_change_event_writer: EventWriter<LightingModeChanged>,
mut app_status: ResMut<AppStatus>,
) {
for event in widget_click_event_reader.read() {
app_status.lighting_mode = **event;
lighting_mode_change_event_writer.write(LightingModeChanged);
}
}
|
Handles clicks on the widgets at the bottom of the screen and fires
[`LightingModeChanged`] events.
|
handle_lighting_mode_change
|
rust
|
bevyengine/bevy
|
examples/3d/mixed_lighting.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/mixed_lighting.rs
|
Apache-2.0
|
fn reset_sphere_position(
mut objects: Query<(&Name, &mut Transform)>,
mut lighting_mode_change_event_reader: EventReader<LightingModeChanged>,
app_status: Res<AppStatus>,
) {
// Only run if the lighting mode changed and if the lighting mode is
// `LightingMode::Baked`. (Note that a change event is fired when the scene
// first loads.)
if lighting_mode_change_event_reader.read().next().is_none()
|| app_status.lighting_mode != LightingMode::Baked
{
return;
}
for (name, mut transform) in &mut objects {
if &**name == "Sphere" {
transform.translation = INITIAL_SPHERE_POSITION;
break;
}
}
}
|
Moves the sphere to its original position when the user selects the baked
lighting mode.
As the light from the sphere is precomputed and depends on the sphere's
original position, the sphere must be placed there in order for the lighting
to be correct.
|
reset_sphere_position
|
rust
|
bevyengine/bevy
|
examples/3d/mixed_lighting.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/mixed_lighting.rs
|
Apache-2.0
|
fn move_sphere(
mouse_button_input: Res<ButtonInput<MouseButton>>,
pointers: Query<&PointerInteraction>,
mut meshes: Query<(&GltfMeshName, &ChildOf), With<Mesh3d>>,
mut transforms: Query<&mut Transform>,
app_status: Res<AppStatus>,
) {
// Only run when the left button is clicked and we're not in baked lighting
// mode.
if app_status.lighting_mode == LightingMode::Baked
|| !mouse_button_input.pressed(MouseButton::Left)
{
return;
}
// Find the sphere.
let Some(child_of) = meshes
.iter_mut()
.filter_map(|(name, child_of)| {
if &**name == "Sphere" {
Some(child_of)
} else {
None
}
})
.next()
else {
return;
};
// Grab its transform.
let Ok(mut transform) = transforms.get_mut(child_of.parent()) else {
return;
};
// Set its transform to the appropriate position, as determined by the
// picking subsystem.
for interaction in pointers.iter() {
if let Some(&(
_,
HitData {
position: Some(position),
..
},
)) = interaction.get_nearest_hit()
{
transform.translation = position + vec3(0.0, SPHERE_OFFSET, 0.0);
}
}
}
|
Updates the position of the sphere when the user clicks on a spot in the
scene.
Note that the position of the sphere is locked in baked lighting mode.
|
move_sphere
|
rust
|
bevyengine/bevy
|
examples/3d/mixed_lighting.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/mixed_lighting.rs
|
Apache-2.0
|
fn adjust_help_text(
mut commands: Commands,
help_texts: Query<Entity, With<HelpText>>,
app_status: Res<AppStatus>,
mut lighting_mode_change_event_reader: EventReader<LightingModeChanged>,
) {
if lighting_mode_change_event_reader.read().next().is_none() {
return;
}
for help_text in &help_texts {
commands
.entity(help_text)
.insert(create_help_text(&app_status));
}
}
|
Changes the help text at the top of the screen when the lighting mode
changes.
|
adjust_help_text
|
rust
|
bevyengine/bevy
|
examples/3d/mixed_lighting.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/mixed_lighting.rs
|
Apache-2.0
|
fn create_help_text(app_status: &AppStatus) -> Text {
match app_status.lighting_mode {
LightingMode::Baked => Text::new(
"Scenery: Static, baked direct light, baked indirect light
Sphere: Static, baked direct light, baked indirect light",
),
LightingMode::MixedDirect => Text::new(
"Scenery: Static, baked direct light, baked indirect light
Sphere: Dynamic, real-time direct light, no indirect light
Click in the scene to move the sphere",
),
LightingMode::MixedIndirect => Text::new(
"Scenery: Static, real-time direct light, baked indirect light
Sphere: Dynamic, real-time direct light, no indirect light
Click in the scene to move the sphere",
),
LightingMode::RealTime => Text::new(
"Scenery: Dynamic, real-time direct light, no indirect light
Sphere: Dynamic, real-time direct light, no indirect light
Click in the scene to move the sphere",
),
}
}
|
Returns appropriate text to display at the top of the screen.
|
create_help_text
|
rust
|
bevyengine/bevy
|
examples/3d/mixed_lighting.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/mixed_lighting.rs
|
Apache-2.0
|
fn race_track_pos(offset: f32, t: f32) -> Vec2 {
let x_tweak = 2.0;
let y_tweak = 3.0;
let scale = 8.0;
let x0 = ops::sin(x_tweak * t);
let y0 = ops::cos(y_tweak * t);
let dx = x_tweak * ops::cos(x_tweak * t);
let dy = y_tweak * -ops::sin(y_tweak * t);
let dl = ops::hypot(dx, dy);
let x = x0 + offset * dy / dl;
let y = y0 - offset * dx / dl;
Vec2::new(x, y) * scale
}
|
Parametric function for a looping race track. `offset` will return the point offset
perpendicular to the track at the given point.
|
race_track_pos
|
rust
|
bevyengine/bevy
|
examples/3d/motion_blur.rs
|
https://github.com/bevyengine/bevy/blob/master/examples/3d/motion_blur.rs
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.