repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_winit/src/winit_windows.rs
crates/bevy_winit/src/winit_windows.rs
use bevy_a11y::AccessibilityRequested; use bevy_ecs::entity::Entity; use bevy_ecs::entity::EntityHashMap; use bevy_platform::collections::HashMap; use bevy_window::{ CursorGrabMode, CursorOptions, MonitorSelection, VideoModeSelection, Window, WindowMode, WindowPosition, WindowResolution, WindowWrapper, }; use tracing::warn; use winit::{ dpi::{LogicalSize, PhysicalPosition}, error::ExternalError, event_loop::ActiveEventLoop, monitor::{MonitorHandle, VideoModeHandle}, window::{CursorGrabMode as WinitCursorGrabMode, Fullscreen, Window as WinitWindow, WindowId}, }; use crate::{ accessibility::{ prepare_accessibility_for_window, AccessKitAdapters, WinitActionRequestHandlers, }, converters::{convert_enabled_buttons, convert_window_level, convert_window_theme}, winit_monitors::WinitMonitors, }; /// A resource mapping window entities to their `winit`-backend [`Window`](winit::window::Window) /// states. #[derive(Debug, Default)] pub struct WinitWindows { /// Stores [`winit`] windows by window identifier. pub windows: HashMap<WindowId, WindowWrapper<WinitWindow>>, /// Maps entities to `winit` window identifiers. pub entity_to_winit: EntityHashMap<WindowId>, /// Maps `winit` window identifiers to entities. pub winit_to_entity: HashMap<WindowId, Entity>, // Many `winit` window functions (e.g. `set_window_icon`) can only be called on the main thread. // If they're called on other threads, the program might hang. This marker indicates that this // type is not thread-safe and will be `!Send` and `!Sync`. _not_send_sync: core::marker::PhantomData<*const ()>, } impl WinitWindows { /// Creates a new instance of `WinitWindows`. pub const fn new() -> Self { Self { windows: HashMap::new(), entity_to_winit: EntityHashMap::new(), winit_to_entity: HashMap::new(), _not_send_sync: core::marker::PhantomData, } } /// Creates a `winit` window and associates it with our entity. pub fn create_window( &mut self, event_loop: &ActiveEventLoop, entity: Entity, window: &Window, cursor_options: &CursorOptions, 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( all( any(feature = "wayland", feature = "x11"), 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 cursor_options.grab_mode != CursorGrabMode::None { let _ = attempt_grab(&winit_window, cursor_options.grab_mode); } winit_window.set_cursor_visible(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 !cursor_options.hit_test && let Err(err) = winit_window.set_cursor_hittest(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() } /// Get the winit window that is associated with our entity. 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 entity associated with the winit window id. /// /// This is mostly just an intermediary step between us and winit. pub fn get_window_entity(&self, winit_id: WindowId) -> Option<Entity> { self.winit_to_entity.get(&winit_id).cloned() } /// Remove a window from winit. /// /// This should mostly just be called when the window is closing. 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) } } /// Returns some [`winit::monitor::VideoModeHandle`] given a [`MonitorHandle`] and a /// [`VideoModeSelection`] or None if no valid matching video mode was found. 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 }), } } /// 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()` 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) } #[cfg(target_arch = "wasm32")] fn pointer_supported() -> Result<bool, ExternalError> { Ok(js_sys::Reflect::has( web_sys::window() .ok_or(ExternalError::Ignored)? .document() .ok_or(ExternalError::Ignored)? .as_ref(), &"exitPointerLock".into(), ) .unwrap_or(false)) } pub(crate) fn attempt_grab( winit_window: &WinitWindow, grab_mode: CursorGrabMode, ) -> Result<(), ExternalError> { // Do not attempt to grab on web if unsupported (e.g. mobile) #[cfg(target_arch = "wasm32")] if !pointer_supported()? { return Err(ExternalError::Ignored); } let grab_result = match grab_mode { CursorGrabMode::None => winit_window.set_cursor_grab(WinitCursorGrabMode::None), CursorGrabMode::Confined => winit_window .set_cursor_grab(WinitCursorGrabMode::Confined) .or_else(|_e| winit_window.set_cursor_grab(WinitCursorGrabMode::Locked)), CursorGrabMode::Locked => winit_window .set_cursor_grab(WinitCursorGrabMode::Locked) .or_else(|_e| winit_window.set_cursor_grab(WinitCursorGrabMode::Confined)), }; if let Err(err) = grab_result { let err_desc = match grab_mode { CursorGrabMode::Confined | CursorGrabMode::Locked => "grab", CursorGrabMode::None => "ungrab", }; tracing::error!("Unable to {} cursor: {}", err_desc, err); Err(err) } else { Ok(()) } } /// Compute the physical window position for a given [`WindowPosition`]. // Ideally we could generify this across window backends, but we only really have winit atm // so whatever. pub fn winit_window_position( position: &WindowPosition, resolution: &WindowResolution, monitors: &WinitMonitors, primary_monitor: Option<MonitorHandle>, current_monitor: Option<MonitorHandle>, ) -> Option<PhysicalPosition<i32>> { match position { WindowPosition::Automatic => { // Window manager will handle position None } WindowPosition::Centered(monitor_selection) => { let maybe_monitor = select_monitor( monitors, primary_monitor, current_monitor, monitor_selection, ); if let Some(monitor) = maybe_monitor { let screen_size = monitor.size(); let scale_factor = match resolution.scale_factor_override() { Some(scale_factor_override) => scale_factor_override as f64, // We use the monitors scale factor here since `WindowResolution.scale_factor` is // not yet populated when windows are created during plugin setup. None => monitor.scale_factor(), }; // Logical to physical window size let (width, height): (u32, u32) = LogicalSize::new(resolution.width(), resolution.height()) .to_physical::<u32>(scale_factor) .into(); let position = PhysicalPosition { x: screen_size.width.saturating_sub(width) as f64 / 2. + monitor.position().x as f64, y: screen_size.height.saturating_sub(height) as f64 / 2. + monitor.position().y as f64, }; Some(position.cast::<i32>()) } else { warn!("Couldn't get monitor selected with: {monitor_selection:?}"); None } } WindowPosition::At(position) => { Some(PhysicalPosition::new(position[0] as f64, position[1] as f64).cast::<i32>()) } } } /// Selects a monitor based on the given [`MonitorSelection`]. 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), } } struct DisplayInfo { window_physical_resolution: (u32, u32), window_logical_resolution: (f32, f32), monitor_name: Option<String>, scale_factor: Option<f64>, refresh_rate_millihertz: Option<u32>, } impl core::fmt::Display for DisplayInfo { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "Display information:")?; write!( f, " Window physical resolution: {}x{}", self.window_physical_resolution.0, self.window_physical_resolution.1 )?; write!( f, " Window logical resolution: {}x{}", self.window_logical_resolution.0, self.window_logical_resolution.1 )?; write!( f, " Monitor name: {}", self.monitor_name.as_deref().unwrap_or("") )?; write!(f, " Scale factor: {}", self.scale_factor.unwrap_or(0.))?; let millihertz = self.refresh_rate_millihertz.unwrap_or(0); let hertz = millihertz / 1000; let extra_millihertz = millihertz % 1000; write!(f, " Refresh rate (Hz): {hertz}.{extra_millihertz:03}")?; Ok(()) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_winit/src/system.rs
crates/bevy_winit/src/system.rs
use std::collections::HashMap; use bevy_derive::{Deref, DerefMut}; use bevy_ecs::{ change_detection::DetectChangesMut, entity::Entity, lifecycle::RemovedComponents, message::MessageWriter, prelude::{Changed, Component}, system::{Local, NonSendMarker, Query, SystemParamItem}, }; use bevy_input::keyboard::{Key, KeyCode, KeyboardFocusLost, KeyboardInput}; use bevy_window::{ ClosingWindow, CursorOptions, Monitor, PrimaryMonitor, RawHandleWrapper, VideoMode, Window, WindowClosed, WindowClosing, WindowCreated, WindowEvent, WindowFocused, WindowMode, WindowResized, WindowWrapper, }; use tracing::{error, info, warn}; use winit::{ dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize}, event_loop::ActiveEventLoop, }; use bevy_app::AppExit; use bevy_ecs::{prelude::MessageReader, query::With, system::Res}; use bevy_math::{IVec2, UVec2}; #[cfg(target_os = "ios")] use winit::platform::ios::WindowExtIOS; #[cfg(target_arch = "wasm32")] use winit::platform::web::WindowExtWebSys; use crate::{ accessibility::ACCESS_KIT_ADAPTERS, converters::{ convert_enabled_buttons, convert_resize_direction, convert_window_level, convert_window_theme, convert_winit_theme, }, get_selected_videomode, select_monitor, state::react_to_resize, winit_monitors::WinitMonitors, CreateMonitorParams, CreateWindowParams, WINIT_WINDOWS, }; /// 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. pub fn create_windows( event_loop: &ActiveEventLoop, ( mut commands, mut created_windows, mut window_created_events, mut handlers, accessibility_requested, monitors, ): SystemParamItem<CreateWindowParams>, ) { WINIT_WINDOWS.with_borrow_mut(|winit_windows| { ACCESS_KIT_ADAPTERS.with_borrow_mut(|adapters| { for (entity, mut window, cursor_options, 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, cursor_options, 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.clone()), CachedCursorOptions(cursor_options.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 }); } }); }); } /// Check whether keyboard focus was lost. This is different from window /// focus in that swapping between Bevy windows keeps window focus. pub(crate) fn check_keyboard_focus_lost( mut window_focused_reader: MessageReader<WindowFocused>, mut keyboard_focus_lost_writer: MessageWriter<KeyboardFocusLost>, mut keyboard_input_writer: MessageWriter<KeyboardInput>, mut window_event_writer: MessageWriter<WindowEvent>, mut q_windows: Query<&mut WinitWindowPressedKeys>, ) { let mut focus_lost = vec![]; let mut focus_gained = false; for e in window_focused_reader.read() { if e.focused { focus_gained = true; } else { focus_lost.push(e.window); } } if !focus_gained { if !focus_lost.is_empty() { window_event_writer.write(WindowEvent::KeyboardFocusLost(KeyboardFocusLost)); keyboard_focus_lost_writer.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_event_writer.write(WindowEvent::KeyboardInput(event.clone())); keyboard_input_writer.write(event); } } } } /// Synchronize available monitors as reported by [`winit`] with [`Monitor`] entities in the world. 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 } }); } pub(crate) fn despawn_windows( closing: Query<Entity, With<ClosingWindow>>, mut closed: RemovedComponents<Window>, window_entities: Query<Entity, With<Window>>, mut closing_event_writer: MessageWriter<WindowClosing>, mut closed_event_writer: MessageWriter<WindowClosed>, mut windows_to_drop: Local<Vec<WindowWrapper<winit::window::Window>>>, mut exit_event_reader: MessageReader<AppExit>, _non_send_marker: NonSendMarker, ) { // Drop all the windows that are waiting to be closed windows_to_drop.clear(); for window in closing.iter() { closing_event_writer.write(WindowClosing { window }); } for window in closed.read() { info!("Closing window {}", window); // Guard to verify that the window is in fact actually gone, // rather than having the component added // and removed in the same frame. if !window_entities.contains(window) { WINIT_WINDOWS.with_borrow_mut(|winit_windows| { if let Some(window) = winit_windows.remove_window(window) { // Keeping WindowWrapper that are dropped for one frame // Otherwise the last `Arc` of the window could be in the rendering thread, and dropped there // This would hang on macOS // Keeping the wrapper and dropping it next frame in this system ensure its dropped in the main thread windows_to_drop.push(window); } }); closed_event_writer.write(WindowClosed { window }); } } // On macOS, when exiting, we need to tell the rendering thread the windows are about to // close to ensure that they are dropped on the main thread. Otherwise, the app will hang. if !exit_event_reader.is_empty() { exit_event_reader.clear(); for window in window_entities.iter() { closing_event_writer.write(WindowClosing { window }); } } } /// The cached state of the window so we can check which properties were changed from within the app. #[derive(Debug, Clone, Component, Deref, DerefMut)] pub(crate) struct CachedWindow(Window); /// The cached state of the window so we can check which properties were changed from within the app. #[derive(Debug, Clone, Component, Deref, DerefMut)] pub(crate) struct CachedCursorOptions(CursorOptions); /// 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. pub(crate) fn changed_windows( mut changed_windows: Query<(Entity, &mut Window, &mut CachedWindow), Changed<Window>>, monitors: Res<WinitMonitors>, mut window_resized: MessageWriter<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.title { winit_window.set_title(window.title.as_str()); } if window.mode != cache.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 && winit_window.fullscreen() != new_mode { winit_window.set_fullscreen(new_mode); } } if window.resolution != cache.resolution { let mut physical_size = PhysicalSize::new( window.resolution.physical_width(), window.resolution.physical_height(), ); let cached_physical_size = PhysicalSize::new( cache.physical_width(), cache.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.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.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 && 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.physical_cursor_position() && 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.decorations != cache.decorations && window.decorations != winit_window.is_decorated() { winit_window.set_decorations(window.decorations); } if window.resizable != cache.resizable && window.resizable != winit_window.is_resizable() { winit_window.set_resizable(window.resizable); } if window.enabled_buttons != cache.enabled_buttons { winit_window.set_enabled_buttons(convert_enabled_buttons(window.enabled_buttons)); } if window.resize_constraints != cache.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.position && 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() && 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() && 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.focused && window.focused { winit_window.focus_window(); } if window.window_level != cache.window_level { winit_window.set_window_level(convert_window_level(window.window_level)); } // Currently unsupported changes if window.transparent != cache.transparent { window.transparent = cache.transparent; warn!("Winit does not currently support updating transparency after window creation."); } #[cfg(target_arch = "wasm32")] if window.canvas != cache.canvas { window.canvas.clone_from(&cache.canvas); warn!( "Bevy currently doesn't support modifying the window canvas after initialization." ); } if window.ime_enabled != cache.ime_enabled { winit_window.set_ime_allowed(window.ime_enabled); } if window.ime_position != cache.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_theme { winit_window.set_theme(window.window_theme.map(convert_window_theme)); } if window.visible != cache.visible { winit_window.set_visible(window.visible); } #[cfg(target_os = "ios")] { if window.recognize_pinch_gesture != cache.recognize_pinch_gesture { winit_window.recognize_pinch_gesture(window.recognize_pinch_gesture); } if window.recognize_rotation_gesture != cache.recognize_rotation_gesture { winit_window.recognize_rotation_gesture(window.recognize_rotation_gesture); } if window.recognize_doubletap_gesture != cache.recognize_doubletap_gesture { winit_window.recognize_doubletap_gesture(window.recognize_doubletap_gesture); } if window.recognize_pan_gesture != cache.recognize_pan_gesture { match ( window.recognize_pan_gesture, cache.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.prefers_home_indicator_hidden { winit_window .set_prefers_home_indicator_hidden(window.prefers_home_indicator_hidden); } if window.prefers_status_bar_hidden != cache.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 .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.clone(); } }); } pub(crate) fn changed_cursor_options( mut changed_windows: Query< ( Entity, &Window, &mut CursorOptions, &mut CachedCursorOptions, ), Changed<CursorOptions>, >, _non_send_marker: NonSendMarker, ) { WINIT_WINDOWS.with_borrow(|winit_windows| { for (entity, window, mut cursor_options, mut cache) in &mut changed_windows { // This system already only runs when the cursor options change, so we need to bypass change detection or the next frame will also run this system let cursor_options = cursor_options.bypass_change_detection(); let Some(winit_window) = winit_windows.get_window(entity) else { continue; }; // Don't check the cache for the grab mode. It can change through external means, leaving the cache outdated. if let Err(err) = crate::winit_windows::attempt_grab(winit_window, cursor_options.grab_mode) { warn!( "Could not set cursor grab mode for window {}: {}", window.title, err ); cursor_options.grab_mode = cache.grab_mode; } else { cache.grab_mode = cursor_options.grab_mode; } if cursor_options.visible != cache.visible { winit_window.set_cursor_visible(cursor_options.visible); cache.visible = cursor_options.visible; } if cursor_options.hit_test != cache.hit_test { if let Err(err) = winit_window.set_cursor_hittest(cursor_options.hit_test) { warn!( "Could not set cursor hit test for window {}: {}", window.title, err ); cursor_options.hit_test = cache.hit_test; } else { cache.hit_test = cursor_options.hit_test; } } } }); } /// This keeps track of which keys are pressed on each window. /// When a window is unfocused, this is used to send key release events for all the currently held keys. #[derive(Default, Component)] pub struct WinitWindowPressedKeys(pub(crate) HashMap<KeyCode, Key>);
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_winit/src/accessibility.rs
crates/bevy_winit/src/accessibility.rs
//! Helpers for mapping window entities to accessibility types use alloc::{collections::VecDeque, sync::Arc}; use bevy_input_focus::InputFocus; use core::cell::RefCell; use std::sync::Mutex; use winit::event_loop::ActiveEventLoop; use accesskit::{ ActionHandler, ActionRequest, ActivationHandler, DeactivationHandler, Node, NodeId, Role, Tree, TreeUpdate, }; use accesskit_winit::Adapter; use bevy_a11y::{ AccessibilityNode, AccessibilityRequested, AccessibilitySystems, ActionRequest as ActionRequestWrapper, ManageAccessibilityUpdates, }; use bevy_app::{App, Plugin, PostUpdate}; use bevy_derive::{Deref, DerefMut}; use bevy_ecs::{entity::EntityHashMap, prelude::*, system::NonSendMarker}; use bevy_window::{PrimaryWindow, Window, WindowClosed}; thread_local! { /// Temporary storage of access kit adapter data to replace usage of `!Send` resources. This will be replaced with proper /// storage of `!Send` data after issue #17667 is complete. pub static ACCESS_KIT_ADAPTERS: RefCell<AccessKitAdapters> = const { RefCell::new(AccessKitAdapters::new()) }; } /// Maps window entities to their `AccessKit` [`Adapter`]s. #[derive(Default, Deref, DerefMut)] pub struct AccessKitAdapters(pub EntityHashMap<Adapter>); impl AccessKitAdapters { /// Creates a new empty `AccessKitAdapters`. pub const fn new() -> Self { Self(EntityHashMap::new()) } } /// Maps window entities to their respective [`ActionRequest`]s. #[derive(Resource, Default, Deref, DerefMut)] pub struct WinitActionRequestHandlers(pub EntityHashMap<Arc<Mutex<WinitActionRequestHandler>>>); /// Forwards `AccessKit` [`ActionRequest`]s from winit to an event channel. #[derive(Clone, Default, Deref, DerefMut)] pub struct WinitActionRequestHandler(pub VecDeque<ActionRequest>); impl WinitActionRequestHandler { fn new() -> Arc<Mutex<Self>> { Arc::new(Mutex::new(Self(VecDeque::new()))) } } struct AccessKitState { name: String, entity: Entity, requested: AccessibilityRequested, } impl AccessKitState { fn new( name: impl Into<String>, entity: Entity, requested: AccessibilityRequested, ) -> Arc<Mutex<Self>> { let name = name.into(); Arc::new(Mutex::new(Self { name, entity, requested, })) } fn build_root(&mut self) -> Node { let mut node = Node::new(Role::Window); node.set_label(self.name.clone()); node } fn build_initial_tree(&mut self) -> TreeUpdate { let root = self.build_root(); let accesskit_window_id = NodeId(self.entity.to_bits()); let tree = Tree::new(accesskit_window_id); self.requested.set(true); TreeUpdate { nodes: vec![(accesskit_window_id, root)], tree: Some(tree), focus: accesskit_window_id, } } } struct WinitActivationHandler(Arc<Mutex<AccessKitState>>); impl ActivationHandler for WinitActivationHandler { fn request_initial_tree(&mut self) -> Option<TreeUpdate> { Some(self.0.lock().unwrap().build_initial_tree()) } } impl WinitActivationHandler { pub fn new(state: Arc<Mutex<AccessKitState>>) -> Self { Self(state) } } #[derive(Clone, Default)] struct WinitActionHandler(Arc<Mutex<WinitActionRequestHandler>>); impl ActionHandler for WinitActionHandler { fn do_action(&mut self, request: ActionRequest) { let mut requests = self.0.lock().unwrap(); requests.push_back(request); } } impl WinitActionHandler { pub fn new(handler: Arc<Mutex<WinitActionRequestHandler>>) -> Self { Self(handler) } } struct WinitDeactivationHandler; impl DeactivationHandler for WinitDeactivationHandler { fn deactivate_accessibility(&mut self) {} } /// Prepares accessibility for a winit window. pub(crate) fn prepare_accessibility_for_window( event_loop: &ActiveEventLoop, winit_window: &winit::window::Window, entity: Entity, name: String, accessibility_requested: AccessibilityRequested, adapters: &mut AccessKitAdapters, handlers: &mut WinitActionRequestHandlers, ) { let state = AccessKitState::new(name, entity, accessibility_requested); let activation_handler = WinitActivationHandler::new(Arc::clone(&state)); let action_request_handler = WinitActionRequestHandler::new(); let action_handler = WinitActionHandler::new(Arc::clone(&action_request_handler)); let deactivation_handler = WinitDeactivationHandler; let adapter = Adapter::with_direct_handlers( event_loop, winit_window, activation_handler, action_handler, deactivation_handler, ); adapters.insert(entity, adapter); handlers.insert(entity, action_request_handler); } fn window_closed( mut handlers: ResMut<WinitActionRequestHandlers>, mut window_closed_reader: MessageReader<WindowClosed>, _non_send_marker: NonSendMarker, ) { ACCESS_KIT_ADAPTERS.with_borrow_mut(|adapters| { for WindowClosed { window, .. } in window_closed_reader.read() { adapters.remove(window); handlers.remove(window); } }); } fn poll_receivers( handlers: Res<WinitActionRequestHandlers>, mut actions: MessageWriter<ActionRequestWrapper>, ) { for (_id, handler) in handlers.iter() { let mut handler = handler.lock().unwrap(); while let Some(event) = handler.pop_front() { actions.write(ActionRequestWrapper(event)); } } } fn should_update_accessibility_nodes( accessibility_requested: Res<AccessibilityRequested>, manage_accessibility_updates: Res<ManageAccessibilityUpdates>, ) -> bool { accessibility_requested.get() && manage_accessibility_updates.get() } fn update_accessibility_nodes( focus: Option<Res<InputFocus>>, primary_window: Query<(Entity, &Window), With<PrimaryWindow>>, nodes: Query<( Entity, &AccessibilityNode, Option<&Children>, Option<&ChildOf>, )>, node_entities: Query<Entity, With<AccessibilityNode>>, _non_send_marker: NonSendMarker, ) { ACCESS_KIT_ADAPTERS.with_borrow_mut(|adapters| { let Ok((primary_window_id, primary_window)) = primary_window.single() else { return; }; let Some(adapter) = adapters.get_mut(&primary_window_id) else { return; }; let Some(focus) = focus else { return; }; if focus.is_changed() || !nodes.is_empty() { // Don't panic if the focused entity does not currently exist // It's probably waiting to be spawned if let Some(focused_entity) = focus.0 && !node_entities.contains(focused_entity) { return; } adapter.update_if_active(|| { update_adapter( nodes, node_entities, primary_window, primary_window_id, focus, ) }); } }); } fn update_adapter( nodes: Query<( Entity, &AccessibilityNode, Option<&Children>, Option<&ChildOf>, )>, node_entities: Query<Entity, With<AccessibilityNode>>, primary_window: &Window, primary_window_id: Entity, focus: Res<InputFocus>, ) -> TreeUpdate { let mut to_update = vec![]; let mut window_children = vec![]; for (entity, node, children, child_of) in &nodes { let mut node = (**node).clone(); queue_node_for_update(entity, child_of, &node_entities, &mut window_children); add_children_nodes(children, &node_entities, &mut node); let node_id = NodeId(entity.to_bits()); to_update.push((node_id, node)); } let mut window_node = Node::new(Role::Window); if primary_window.focused { let title = primary_window.title.clone(); window_node.set_label(title.into_boxed_str()); } window_node.set_children(window_children); let node_id = NodeId(primary_window_id.to_bits()); let window_update = (node_id, window_node); to_update.insert(0, window_update); TreeUpdate { nodes: to_update, tree: None, focus: NodeId(focus.0.unwrap_or(primary_window_id).to_bits()), } } #[inline] fn queue_node_for_update( node_entity: Entity, child_of: Option<&ChildOf>, node_entities: &Query<Entity, With<AccessibilityNode>>, window_children: &mut Vec<NodeId>, ) { let should_push = if let Some(child_of) = child_of { !node_entities.contains(child_of.parent()) } else { true }; if should_push { window_children.push(NodeId(node_entity.to_bits())); } } #[inline] fn add_children_nodes( children: Option<&Children>, node_entities: &Query<Entity, With<AccessibilityNode>>, node: &mut Node, ) { let Some(children) = children else { return; }; for child in children { if node_entities.contains(*child) { node.push_child(NodeId(child.to_bits())); } } } /// Implements winit-specific `AccessKit` functionality. pub struct AccessKitPlugin; impl Plugin for AccessKitPlugin { fn build(&self, app: &mut App) { app.init_resource::<WinitActionRequestHandlers>() .add_message::<ActionRequestWrapper>() .add_systems( PostUpdate, ( poll_receivers, update_accessibility_nodes.run_if(should_update_accessibility_nodes), window_closed .before(poll_receivers) .before(update_accessibility_nodes), ) .in_set(AccessibilitySystems::Update), ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_winit/src/cursor/custom_cursor.rs
crates/bevy_winit/src/cursor/custom_cursor.rs
use bevy_asset::{AssetId, Assets}; use bevy_ecs::resource::Resource; use bevy_image::{Image, TextureAtlas, TextureAtlasLayout}; use bevy_math::{ops, Rect, URect, UVec2, Vec2}; use bevy_platform::collections::HashMap; use wgpu_types::TextureFormat; /// Caches custom cursors. On many platforms, creating custom cursors is expensive, especially on /// the web. #[derive(Debug, Clone, Default, Resource)] pub struct WinitCustomCursorCache(pub HashMap<CustomCursorCacheKey, winit::window::CustomCursor>); /// Identifiers for custom cursors used in caching. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub enum CustomCursorCacheKey { /// A custom cursor with an image. Image { id: AssetId<Image>, texture_atlas_layout_id: Option<AssetId<TextureAtlasLayout>>, texture_atlas_index: Option<usize>, flip_x: bool, flip_y: bool, rect: Option<URect>, }, #[cfg(all(target_family = "wasm", target_os = "unknown"))] /// A custom cursor with a URL. Url(String), } /// Determines the effective rect and returns it along with a flag to indicate /// whether a sub-image operation is needed. The flag allows the caller to /// determine whether the image data needs a sub-image extracted from it. Note: /// To avoid lossy comparisons between [`Rect`] and [`URect`], the flag is /// always set to `true` when a [`TextureAtlas`] is used. #[inline(always)] pub(crate) fn calculate_effective_rect( texture_atlas_layouts: &Assets<TextureAtlasLayout>, image: &Image, texture_atlas: &Option<TextureAtlas>, rect: &Option<URect>, ) -> (Rect, bool) { let atlas_rect = texture_atlas .as_ref() .and_then(|s| s.texture_rect(texture_atlas_layouts)) .map(|r| r.as_rect()); match (atlas_rect, rect) { (None, None) => ( Rect { min: Vec2::ZERO, max: Vec2::new( image.texture_descriptor.size.width as f32, image.texture_descriptor.size.height as f32, ), }, false, ), (None, Some(image_rect)) => ( image_rect.as_rect(), image_rect != &URect { min: UVec2::ZERO, max: UVec2::new( image.texture_descriptor.size.width, image.texture_descriptor.size.height, ), }, ), (Some(atlas_rect), None) => (atlas_rect, true), (Some(atlas_rect), Some(image_rect)) => ( { let mut image_rect = image_rect.as_rect(); image_rect.min += atlas_rect.min; image_rect.max += atlas_rect.min; image_rect }, true, ), } } /// Extracts the RGBA pixel data from `image`, converting it if necessary. /// /// Only supports rgba8 and rgba32float formats. 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, } } /// 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. 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) } /// Transforms the `hotspot` coordinates based on whether the image is flipped /// or not. The `rect` is used to determine the image's dimensions. 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) } #[cfg(test)] mod tests { use bevy_app::App; use bevy_asset::RenderAssetUsages; use bevy_image::Image; use bevy_math::Rect; use bevy_math::Vec2; use wgpu_types::{Extent3d, TextureDimension}; use super::*; fn create_image_rgba8(data: &[u8]) -> Image { Image::new( Extent3d { width: 3, height: 3, depth_or_array_layers: 1, }, TextureDimension::D2, data.to_vec(), TextureFormat::Rgba8UnormSrgb, RenderAssetUsages::default(), ) } macro_rules! test_calculate_effective_rect { ($name:ident, $use_texture_atlas:expr, $rect:expr, $expected_rect:expr, $expected_needs_sub_image:expr) => { #[test] fn $name() { let mut app = App::new(); let mut texture_atlas_layout_assets = Assets::<TextureAtlasLayout>::default(); // Create a simple 3x3 texture atlas layout for the test cases // that use a texture atlas. In the future we could adjust the // test cases to use different texture atlas layouts. let layout = TextureAtlasLayout::from_grid(UVec2::new(3, 3), 1, 1, None, None); let layout_handle = texture_atlas_layout_assets.add(layout); app.insert_resource(texture_atlas_layout_assets); let texture_atlases = app .world() .get_resource::<Assets<TextureAtlasLayout>>() .unwrap(); let image = create_image_rgba8(&[0; 3 * 3 * 4]); // 3x3 image let texture_atlas = if $use_texture_atlas { Some(TextureAtlas::from(layout_handle)) } else { None }; let rect = $rect; let (result_rect, needs_sub_image) = calculate_effective_rect(&texture_atlases, &image, &texture_atlas, &rect); assert_eq!(result_rect, $expected_rect); assert_eq!(needs_sub_image, $expected_needs_sub_image); } }; } test_calculate_effective_rect!( no_texture_atlas_no_rect, false, None, Rect { min: Vec2::ZERO, max: Vec2::new(3.0, 3.0) }, false ); test_calculate_effective_rect!( no_texture_atlas_with_partial_rect, false, Some(URect { min: UVec2::new(1, 1), max: UVec2::new(3, 3) }), Rect { min: Vec2::new(1.0, 1.0), max: Vec2::new(3.0, 3.0) }, true ); test_calculate_effective_rect!( no_texture_atlas_with_full_rect, false, Some(URect { min: UVec2::ZERO, max: UVec2::new(3, 3) }), Rect { min: Vec2::ZERO, max: Vec2::new(3.0, 3.0) }, false ); test_calculate_effective_rect!( texture_atlas_no_rect, true, None, Rect { min: Vec2::ZERO, max: Vec2::new(3.0, 3.0) }, true // always needs sub-image to avoid comparing Rect against URect ); test_calculate_effective_rect!( texture_atlas_rect, true, Some(URect { min: UVec2::ZERO, max: UVec2::new(3, 3) }), Rect { min: Vec2::new(0.0, 0.0), max: Vec2::new(3.0, 3.0) }, true // always needs sub-image to avoid comparing Rect against URect ); fn create_image_rgba32float(data: &[u8]) -> Image { let float_data: Vec<f32> = data .chunks(4) .flat_map(|chunk| { chunk .iter() .map(|&x| x as f32 / 255.0) // convert each channel to f32 .collect::<Vec<f32>>() }) .collect(); Image::new( Extent3d { width: 3, height: 3, depth_or_array_layers: 1, }, TextureDimension::D2, bytemuck::cast_slice(&float_data).to_vec(), TextureFormat::Rgba32Float, RenderAssetUsages::default(), ) } macro_rules! test_extract_and_transform_rgba_pixels { ($name:ident, $flip_x:expr, $flip_y:expr, $rect:expr, $expected:expr) => { #[test] fn $name() { let image_data: &[u8] = &[ // Row 1: Red, Green, Blue 255, 0, 0, 255, // Red 0, 255, 0, 255, // Green 0, 0, 255, 255, // Blue // Row 2: Yellow, Cyan, Magenta 255, 255, 0, 255, // Yellow 0, 255, 255, 255, // Cyan 255, 0, 255, 255, // Magenta // Row 3: White, Gray, Black 255, 255, 255, 255, // White 128, 128, 128, 255, // Gray 0, 0, 0, 255, // Black ]; // RGBA8 test { let image = create_image_rgba8(image_data); let rect = $rect; let result = extract_and_transform_rgba_pixels(&image, $flip_x, $flip_y, rect); assert_eq!(result, Some($expected.to_vec())); } // RGBA32Float test { let image = create_image_rgba32float(image_data); let rect = $rect; let result = extract_and_transform_rgba_pixels(&image, $flip_x, $flip_y, rect); assert_eq!(result, Some($expected.to_vec())); } } }; } test_extract_and_transform_rgba_pixels!( no_flip_full_image, false, false, Rect { min: Vec2::ZERO, max: Vec2::new(3.0, 3.0) }, [ // Row 1: Red, Green, Blue 255, 0, 0, 255, // Red 0, 255, 0, 255, // Green 0, 0, 255, 255, // Blue // Row 2: Yellow, Cyan, Magenta 255, 255, 0, 255, // Yellow 0, 255, 255, 255, // Cyan 255, 0, 255, 255, // Magenta // Row 3: White, Gray, Black 255, 255, 255, 255, // White 128, 128, 128, 255, // Gray 0, 0, 0, 255, // Black ] ); test_extract_and_transform_rgba_pixels!( flip_x_full_image, true, false, Rect { min: Vec2::ZERO, max: Vec2::new(3.0, 3.0) }, [ // Row 1 flipped: Blue, Green, Red 0, 0, 255, 255, // Blue 0, 255, 0, 255, // Green 255, 0, 0, 255, // Red // Row 2 flipped: Magenta, Cyan, Yellow 255, 0, 255, 255, // Magenta 0, 255, 255, 255, // Cyan 255, 255, 0, 255, // Yellow // Row 3 flipped: Black, Gray, White 0, 0, 0, 255, // Black 128, 128, 128, 255, // Gray 255, 255, 255, 255, // White ] ); test_extract_and_transform_rgba_pixels!( flip_y_full_image, false, true, Rect { min: Vec2::ZERO, max: Vec2::new(3.0, 3.0) }, [ // Row 3: White, Gray, Black 255, 255, 255, 255, // White 128, 128, 128, 255, // Gray 0, 0, 0, 255, // Black // Row 2: Yellow, Cyan, Magenta 255, 255, 0, 255, // Yellow 0, 255, 255, 255, // Cyan 255, 0, 255, 255, // Magenta // Row 1: Red, Green, Blue 255, 0, 0, 255, // Red 0, 255, 0, 255, // Green 0, 0, 255, 255, // Blue ] ); test_extract_and_transform_rgba_pixels!( flip_both_full_image, true, true, Rect { min: Vec2::ZERO, max: Vec2::new(3.0, 3.0) }, [ // Row 3 flipped: Black, Gray, White 0, 0, 0, 255, // Black 128, 128, 128, 255, // Gray 255, 255, 255, 255, // White // Row 2 flipped: Magenta, Cyan, Yellow 255, 0, 255, 255, // Magenta 0, 255, 255, 255, // Cyan 255, 255, 0, 255, // Yellow // Row 1 flipped: Blue, Green, Red 0, 0, 255, 255, // Blue 0, 255, 0, 255, // Green 255, 0, 0, 255, // Red ] ); test_extract_and_transform_rgba_pixels!( no_flip_rect, false, false, Rect { min: Vec2::new(1.0, 1.0), max: Vec2::new(3.0, 3.0) }, [ // Only includes part of the original image (sub-rectangle) // Row 2, columns 2-3: Cyan, Magenta 0, 255, 255, 255, // Cyan 255, 0, 255, 255, // Magenta // Row 3, columns 2-3: Gray, Black 128, 128, 128, 255, // Gray 0, 0, 0, 255, // Black ] ); test_extract_and_transform_rgba_pixels!( flip_x_rect, true, false, Rect { min: Vec2::new(1.0, 1.0), max: Vec2::new(3.0, 3.0) }, [ // Row 2 flipped: Magenta, Cyan 255, 0, 255, 255, // Magenta 0, 255, 255, 255, // Cyan // Row 3 flipped: Black, Gray 0, 0, 0, 255, // Black 128, 128, 128, 255, // Gray ] ); test_extract_and_transform_rgba_pixels!( flip_y_rect, false, true, Rect { min: Vec2::new(1.0, 1.0), max: Vec2::new(3.0, 3.0) }, [ // Row 3 first: Gray, Black 128, 128, 128, 255, // Gray 0, 0, 0, 255, // Black // Row 2 second: Cyan, Magenta 0, 255, 255, 255, // Cyan 255, 0, 255, 255, // Magenta ] ); test_extract_and_transform_rgba_pixels!( flip_both_rect, true, true, Rect { min: Vec2::new(1.0, 1.0), max: Vec2::new(3.0, 3.0) }, [ // Row 3 flipped: Black, Gray 0, 0, 0, 255, // Black 128, 128, 128, 255, // Gray // Row 2 flipped: Magenta, Cyan 255, 0, 255, 255, // Magenta 0, 255, 255, 255, // Cyan ] ); #[test] fn test_transform_hotspot() { fn test(hotspot: (u16, u16), flip_x: bool, flip_y: bool, rect: Rect, expected: (u16, u16)) { let transformed = transform_hotspot(hotspot, flip_x, flip_y, rect); assert_eq!(transformed, expected); // Round-trip test: Applying the same transformation again should // reverse it. let transformed = transform_hotspot(transformed, flip_x, flip_y, rect); assert_eq!(transformed, hotspot); } let rect = Rect { min: Vec2::ZERO, max: Vec2::new(100.0, 200.0), }; test((10, 20), false, false, rect, (10, 20)); // no flip test((10, 20), true, false, rect, (89, 20)); // flip X test((10, 20), false, true, rect, (10, 179)); // flip Y test((10, 20), true, true, rect, (89, 179)); // flip both test((0, 0), true, true, rect, (99, 199)); // flip both (bounds check) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_winit/src/cursor/mod.rs
crates/bevy_winit/src/cursor/mod.rs
#[cfg(feature = "custom_cursor")] mod custom_cursor; #[cfg(feature = "custom_cursor")] pub use custom_cursor::*; use crate::{converters::convert_system_cursor_icon, state::WinitAppRunnerState, WINIT_WINDOWS}; use bevy_app::{App, Last, Plugin}; #[cfg(feature = "custom_cursor")] use bevy_asset::Assets; use bevy_ecs::{prelude::*, system::SystemState}; #[cfg(feature = "custom_cursor")] use bevy_image::{Image, TextureAtlasLayout}; use bevy_platform::collections::HashSet; #[cfg(feature = "custom_cursor")] use bevy_window::CustomCursor; use bevy_window::{CursorIcon, SystemCursorIcon, Window}; #[cfg(feature = "custom_cursor")] use winit::event_loop::ActiveEventLoop; /// Adds support for custom cursors. pub(crate) struct WinitCursorPlugin; impl Plugin for WinitCursorPlugin { fn build(&self, app: &mut App) { #[cfg(feature = "custom_cursor")] { if !app.is_plugin_added::<bevy_image::TextureAtlasPlugin>() { app.add_plugins(bevy_image::TextureAtlasPlugin); } app.init_resource::<WinitCustomCursorCache>(); } app.add_systems(Last, update_cursors) .add_observer(on_remove_cursor_icon); } } /// A source for a cursor. Consumed by the winit event loop. #[derive(Debug)] pub enum CursorSource { #[cfg(feature = "custom_cursor")] /// A custom cursor was identified to be cached, no reason to recreate it. CustomCached(CustomCursorCacheKey), #[cfg(feature = "custom_cursor")] /// A custom cursor was not cached, so it needs to be created by the winit event loop. Custom((CustomCursorCacheKey, winit::window::CustomCursorSource)), /// A system cursor was requested. System(winit::window::CursorIcon), } /// Component that indicates what cursor should be used for a window. Inserted /// automatically after changing `CursorIcon` and consumed by the winit event /// loop. #[derive(Component, Debug)] pub struct PendingCursor(pub Option<CursorSource>); impl WinitAppRunnerState { pub(crate) fn update_cursors( &mut self, #[cfg(feature = "custom_cursor")] event_loop: &ActiveEventLoop, ) { #[cfg(feature = "custom_cursor")] let mut windows_state: SystemState<( ResMut<WinitCustomCursorCache>, Query<(Entity, &mut PendingCursor), Changed<PendingCursor>>, )> = SystemState::new(self.world_mut()); #[cfg(feature = "custom_cursor")] let (mut cursor_cache, mut windows) = windows_state.get_mut(self.world_mut()); #[cfg(not(feature = "custom_cursor"))] let mut windows_state: SystemState<( Query<(Entity, &mut PendingCursor), Changed<PendingCursor>>, )> = SystemState::new(self.world_mut()); #[cfg(not(feature = "custom_cursor"))] let (mut windows,) = windows_state.get_mut(self.world_mut()); WINIT_WINDOWS.with_borrow(|winit_windows| { for (entity, mut pending_cursor) in windows.iter_mut() { let Some(winit_window) = winit_windows.get_window(entity) else { continue; }; let Some(pending_cursor) = pending_cursor.0.take() else { continue; }; let final_cursor: winit::window::Cursor = match pending_cursor { #[cfg(feature = "custom_cursor")] CursorSource::CustomCached(cache_key) => { let Some(cached_cursor) = cursor_cache.0.get(&cache_key) else { tracing::error!("Cursor should have been cached, but was not found"); continue; }; cached_cursor.clone().into() } #[cfg(feature = "custom_cursor")] CursorSource::Custom((cache_key, cursor)) => { let custom_cursor = event_loop.create_custom_cursor(cursor); cursor_cache.0.insert(cache_key, custom_cursor.clone()); custom_cursor.into() } CursorSource::System(system_cursor) => system_cursor.into(), }; winit_window.set_cursor(final_cursor); } }); } } fn update_cursors( mut commands: Commands, windows: Query<(Entity, Ref<CursorIcon>), With<Window>>, #[cfg(feature = "custom_cursor")] cursor_cache: Res<WinitCustomCursorCache>, #[cfg(feature = "custom_cursor")] images: Res<Assets<Image>>, #[cfg(feature = "custom_cursor")] texture_atlases: Res<Assets<TextureAtlasLayout>>, mut queue: Local<HashSet<Entity>>, ) { for (entity, cursor) in windows.iter() { if !(queue.remove(&entity) || cursor.is_changed()) { continue; } let cursor_source = match cursor.as_ref() { #[cfg(feature = "custom_cursor")] CursorIcon::Custom(CustomCursor::Image(c)) => { let bevy_window::CustomCursorImage { handle, texture_atlas, flip_x, flip_y, rect, hotspot, } = c; let cache_key = CustomCursorCacheKey::Image { id: handle.id(), texture_atlas_layout_id: texture_atlas.as_ref().map(|a| a.layout.id()), texture_atlas_index: texture_atlas.as_ref().map(|a| a.index), flip_x: *flip_x, flip_y: *flip_y, rect: *rect, }; if cursor_cache.0.contains_key(&cache_key) { CursorSource::CustomCached(cache_key) } else { let Some(image) = images.get(handle) else { tracing::warn!( "Cursor image {handle:?} is not loaded yet and couldn't be used. Trying again next frame." ); queue.insert(entity); continue; }; let (rect, needs_sub_image) = calculate_effective_rect(&texture_atlases, image, texture_atlas, rect); let (maybe_rgba, hotspot) = if *flip_x || *flip_y || needs_sub_image { ( extract_and_transform_rgba_pixels(image, *flip_x, *flip_y, rect), transform_hotspot(*hotspot, *flip_x, *flip_y, rect), ) } else { (extract_rgba_pixels(image), *hotspot) }; let Some(rgba) = maybe_rgba else { tracing::warn!("Cursor image {handle:?} not accepted because it's not rgba8 or rgba32float format"); continue; }; let source = match winit::window::CustomCursor::from_rgba( rgba, rect.width() as u16, rect.height() as u16, hotspot.0, hotspot.1, ) { Ok(source) => source, Err(err) => { tracing::warn!("Cursor image {handle:?} is invalid: {err}"); continue; } }; CursorSource::Custom((cache_key, source)) } } #[cfg(feature = "custom_cursor")] CursorIcon::Custom(CustomCursor::Url(_c)) => { #[cfg(all(target_family = "wasm", target_os = "unknown"))] { let cache_key = CustomCursorCacheKey::Url(_c.url.clone()); if cursor_cache.0.contains_key(&cache_key) { CursorSource::CustomCached(cache_key) } else { use crate::CustomCursorExtWebSys; let source = winit::window::CustomCursor::from_url( _c.url.clone(), _c.hotspot.0, _c.hotspot.1, ); CursorSource::Custom((cache_key, source)) } } #[cfg(not(all(target_family = "wasm", target_os = "unknown")))] { bevy_log::error_once!("CustomCursor::Url is not supported on this platform. Falling back to CursorIcon::System(SystemCursorIcon::Default)"); CursorSource::System(winit::window::CursorIcon::Default) } } CursorIcon::System(system_cursor_icon) => { CursorSource::System(convert_system_cursor_icon(*system_cursor_icon)) } }; commands .entity(entity) .insert(PendingCursor(Some(cursor_source))); } } /// Resets the cursor to the default icon when `CursorIcon` is removed. fn on_remove_cursor_icon(remove: On<Remove, CursorIcon>, mut commands: Commands) { // Use `try_insert` to avoid panic if the window is being destroyed. commands .entity(remove.entity) .try_insert(PendingCursor(Some(CursorSource::System( convert_system_cursor_icon(SystemCursorIcon::Default), )))); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/hello_world.rs
examples/hello_world.rs
//! A minimal example that outputs "hello world" use bevy::prelude::*; fn main() { App::new().add_systems(Update, hello_world_system).run(); } fn hello_world_system() { println!("hello world"); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/reflection/type_data.rs
examples/reflection/type_data.rs
//! The example demonstrates what type data is, how to create it, and how to use it. use bevy::{ prelude::*, reflect::{FromType, TypeRegistry}, }; // It's recommended to read this example from top to bottom. // Comments are provided to explain the code and its purpose as you go along. fn main() { trait Damageable { type Health; fn damage(&mut self, damage: Self::Health); } #[derive(Reflect, PartialEq, Debug)] struct Zombie { health: u32, } impl Damageable for Zombie { type Health = u32; fn damage(&mut self, damage: Self::Health) { self.health -= damage; } } // Let's say we have a reflected value. // Here we know it's a `Zombie`, but for demonstration purposes let's pretend we don't. // Pretend it's just some `Box<dyn Reflect>` value. let mut value: Box<dyn Reflect> = Box::new(Zombie { health: 100 }); // We think `value` might contain a type that implements `Damageable` // and now we want to call `Damageable::damage` on it. // How can we do this without knowing in advance the concrete type is `Zombie`? // This is where type data comes in. // Type data is a way of associating type-specific data with a type for use in dynamic contexts. // This type data can then be used at runtime to perform type-specific operations. // Let's create a type data struct for `Damageable` that we can associate with `Zombie`! // Firstly, type data must be cloneable. #[derive(Clone)] // Next, they are usually named with the `Reflect` prefix (we'll see why in a bit). struct ReflectDamageable { // Type data can contain whatever you want, but it's common to include function pointers // to the type-specific operations you want to perform (such as trait methods). // Just remember that we're working with `Reflect` data, // so we can't use `Self`, generics, or associated types. // In those cases, we'll have to use `dyn Reflect` trait objects. damage: fn(&mut dyn Reflect, damage: Box<dyn Reflect>), } // Now, we can create a blanket implementation of the `FromType` trait to construct our type data // for any type that implements `Reflect` and `Damageable`. impl<T: Reflect + Damageable<Health: Reflect>> FromType<T> for ReflectDamageable { fn from_type() -> Self { Self { damage: |reflect, damage| { // This requires that `reflect` is `T` and not a dynamic representation like `DynamicStruct`. // We could have the function pointer return a `Result`, but we'll just `unwrap` for simplicity. let damageable = reflect.downcast_mut::<T>().unwrap(); let damage = damage.take::<T::Health>().unwrap(); damageable.damage(damage); }, } } } // It's also common to provide convenience methods for calling the type-specific operations. impl ReflectDamageable { pub fn damage(&self, reflect: &mut dyn Reflect, damage: Box<dyn Reflect>) { (self.damage)(reflect, damage); } } // With all this done, we're ready to make use of `ReflectDamageable`! // It starts with registering our type along with its type data: let mut registry = TypeRegistry::default(); registry.register::<Zombie>(); registry.register_type_data::<Zombie, ReflectDamageable>(); // Then at any point we can retrieve the type data from the registry: let type_id = value.reflect_type_info().type_id(); let reflect_damageable = registry .get_type_data::<ReflectDamageable>(type_id) .unwrap(); // And call our method: reflect_damageable.damage(value.as_reflect_mut(), Box::new(25u32)); assert_eq!(value.take::<Zombie>().unwrap(), Zombie { health: 75 }); // This is a simple example, but type data can be used for much more complex operations. // Bevy also provides some useful shorthand for working with type data. // For example, we can have the type data be automatically registered when we register the type // by using the `#[reflect(MyTrait)]` attribute when defining our type. #[derive(Reflect)] // Notice that we don't need to type out `ReflectDamageable`. // This is why we named it with the `Reflect` prefix: // the derive macro will automatically look for a type named `ReflectDamageable` in the current scope. #[reflect(Damageable)] struct Skeleton { health: u32, } impl Damageable for Skeleton { type Health = u32; fn damage(&mut self, damage: Self::Health) { self.health -= damage; } } // This will now register `Skeleton` along with its `ReflectDamageable` type data. registry.register::<Skeleton>(); // And for object-safe traits (see https://doc.rust-lang.org/reference/items/traits.html#object-safety), // Bevy provides a convenience macro for generating type data that converts `dyn Reflect` into `dyn MyTrait`. #[reflect_trait] trait Health { fn health(&self) -> u32; } impl Health for Skeleton { fn health(&self) -> u32 { self.health } } // Using the `#[reflect_trait]` macro we're able to automatically generate a `ReflectHealth` type data struct, // which can then be registered like any other type data: registry.register_type_data::<Skeleton, ReflectHealth>(); // Now we can use `ReflectHealth` to convert `dyn Reflect` into `dyn Health`: let value: Box<dyn Reflect> = Box::new(Skeleton { health: 50 }); let type_id = value.reflect_type_info().type_id(); let reflect_health = registry.get_type_data::<ReflectHealth>(type_id).unwrap(); // Type data generated by `#[reflect_trait]` comes with a `get`, `get_mut`, and `get_boxed` method, // which convert `&dyn Reflect` into `&dyn MyTrait`, `&mut dyn Reflect` into `&mut dyn MyTrait`, // and `Box<dyn Reflect>` into `Box<dyn MyTrait>`, respectively. let value: &dyn Health = reflect_health.get(value.as_reflect()).unwrap(); assert_eq!(value.health(), 50); // Lastly, here's a list of some useful type data provided by Bevy that you might want to register for your types: // - `ReflectDefault` for types that implement `Default` // - `ReflectFromWorld` for types that implement `FromWorld` // - `ReflectComponent` for types that implement `Component` // - `ReflectResource` for types that implement `Resource` // - `ReflectSerialize` for types that implement `Serialize` // - `ReflectDeserialize` for types that implement `Deserialize` // // And here are some that are automatically registered by the `Reflect` derive macro: // - `ReflectFromPtr` // - `ReflectFromReflect` (if not `#[reflect(from_reflect = false)]`) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/reflection/serialization.rs
examples/reflection/serialization.rs
//! Illustrates how "reflection" serialization works in Bevy. //! //! Deriving `Reflect` will also register `SerializationData`, //! which powers reflect (de)serialization. //! Serializing reflected data *does not* require deriving serde's //! Serialize and Deserialize implementations. use bevy::{ prelude::*, reflect::serde::{ReflectDeserializer, ReflectSerializer}, }; use serde::de::DeserializeSeed; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, (deserialize, serialize).chain()) .run(); } /// Deriving `Reflect` includes reflecting `SerializationData` #[derive(Reflect)] pub struct Player { name: String, health: u32, } const PLAYER_JSON: &str = r#"{ "serialization::Player": { "name": "BevyPlayerOne", "health": 50 } }"#; fn deserialize(type_registry: Res<AppTypeRegistry>) { let type_registry = type_registry.read(); // a serde_json::Value that might have come from an API let value: serde_json::Value = serde_json::from_str(PLAYER_JSON).unwrap(); // alternatively, `TypedReflectDeserializer` can be used if the type // is known. let deserializer = ReflectDeserializer::new(&type_registry); // deserialize let reflect_value = deserializer.deserialize(value).unwrap(); // If Player implemented additional functionality, like Component, // this reflect_value could be used with commands.insert_reflect info!(?reflect_value); } fn serialize(type_registry: Res<AppTypeRegistry>) { let type_registry = type_registry.read(); // a concrete value let value = Player { name: "BevyPlayerSerialize".to_string(), health: 80, }; // By default, all derived `Reflect` types can be serialized using serde. No need to derive // Serialize! let serializer = ReflectSerializer::new(&value, &type_registry); let json = serde_json::to_string(&serializer).unwrap(); info!(?json); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/reflection/reflection.rs
examples/reflection/reflection.rs
//! Illustrates how "reflection" works in Bevy. //! //! Reflection provides a way to dynamically interact with Rust types, such as accessing fields //! by their string name. Reflection is a core part of Bevy and enables a number of interesting //! features (like scenes). use bevy::{ prelude::*, reflect::{ serde::{ReflectDeserializer, ReflectSerializer}, DynamicStruct, PartialReflect, }, }; use serde::de::DeserializeSeed; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } /// Deriving `Reflect` implements the relevant reflection traits. In this case, it implements the /// `Reflect` trait and the `Struct` trait `derive(Reflect)` assumes that all fields also implement /// Reflect. /// /// All fields in a reflected item will need to be `Reflect` as well. You can opt a field out of /// reflection by using the `#[reflect(ignore)]` attribute. /// If you choose to ignore a field, you need to let the automatically-derived `FromReflect` implementation /// how to handle the field. /// To do this, you can either define a `#[reflect(default = "...")]` attribute on the ignored field, or /// opt-out of `FromReflect`'s auto-derive using the `#[reflect(from_reflect = false)]` attribute. #[derive(Reflect)] #[reflect(from_reflect = false)] pub struct Foo { a: usize, nested: Bar, #[reflect(ignore)] _ignored: NonReflectedValue, } /// This `Bar` type is used in the `nested` field of the `Foo` type. We must derive `Reflect` here /// too (or ignore it) #[derive(Reflect)] pub struct Bar { b: usize, } #[derive(Default)] struct NonReflectedValue { _a: usize, } fn setup(type_registry: Res<AppTypeRegistry>) { let mut value = Foo { a: 1, _ignored: NonReflectedValue { _a: 10 }, nested: Bar { b: 8 }, }; // You can set field values like this. The type must match exactly or this will fail. *value.get_field_mut("a").unwrap() = 2usize; assert_eq!(value.a, 2); assert_eq!(*value.get_field::<usize>("a").unwrap(), 2); // You can also get the `&dyn PartialReflect` value of a field like this let field = value.field("a").unwrap(); // But values introspected via `PartialReflect` will not return `dyn Reflect` trait objects // (even if the containing type does implement `Reflect`), so we need to convert them: let fully_reflected_field = field.try_as_reflect().unwrap(); // Now, you can downcast your `Reflect` value like this: assert_eq!(*fully_reflected_field.downcast_ref::<usize>().unwrap(), 2); // For this specific case, we also support the shortcut `try_downcast_ref`: assert_eq!(*field.try_downcast_ref::<usize>().unwrap(), 2); // `DynamicStruct` also implements the `Struct` and `Reflect` traits. let mut patch = DynamicStruct::default(); patch.insert("a", 4usize); // You can "apply" Reflect implementations on top of other Reflect implementations. // This will only set fields with the same name, and it will fail if the types don't match. // You can use this to "patch" your types with new values. value.apply(&patch); assert_eq!(value.a, 4); let type_registry = type_registry.read(); // By default, all derived `Reflect` types can be Serialized using serde. No need to derive // Serialize! let serializer = ReflectSerializer::new(&value, &type_registry); let ron_string = ron::ser::to_string_pretty(&serializer, ron::ser::PrettyConfig::default()).unwrap(); info!("{}\n", ron_string); // Dynamic properties can be deserialized let reflect_deserializer = ReflectDeserializer::new(&type_registry); let mut deserializer = ron::de::Deserializer::from_str(&ron_string).unwrap(); let reflect_value = reflect_deserializer.deserialize(&mut deserializer).unwrap(); // Deserializing returns a `Box<dyn PartialReflect>` value. // Generally, deserializing a value will return the "dynamic" variant of a type. // For example, deserializing a struct will return the DynamicStruct type. // "Opaque types" will be deserialized as themselves. assert_eq!( reflect_value.reflect_type_path(), DynamicStruct::type_path(), ); // Reflect has its own `partial_eq` implementation, named `reflect_partial_eq`. This behaves // like normal `partial_eq`, but it treats "dynamic" and "non-dynamic" types the same. The // `Foo` struct and deserialized `DynamicStruct` are considered equal for this reason: assert!(reflect_value.reflect_partial_eq(&value).unwrap()); // By "patching" `Foo` with the deserialized DynamicStruct, we can "Deserialize" Foo. // This means we can serialize and deserialize with a single `Reflect` derive! value.apply(&*reflect_value); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/reflection/reflection_types.rs
examples/reflection/reflection_types.rs
//! This example illustrates how reflection works for simple data structures, like //! structs, tuples and vectors. use bevy::{ platform::collections::HashMap, prelude::*, reflect::{DynamicList, PartialReflect, ReflectRef}, }; use serde::{Deserialize, Serialize}; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } /// Deriving reflect on a struct will implement the `Reflect` and `Struct` traits #[derive(Reflect)] pub struct A { x: usize, y: Vec<u32>, z: HashMap<String, f32>, } /// Deriving reflect on a unit struct will implement the `Reflect` and `Struct` traits #[derive(Reflect)] pub struct B; /// Deriving reflect on a tuple struct will implement the `Reflect` and `TupleStruct` traits #[derive(Reflect)] pub struct C(usize); /// Deriving reflect on an enum will implement the `Reflect` and `Enum` traits #[derive(Reflect)] enum D { A, B(usize), C { value: f32 }, } /// Reflect has "built in" support for some common traits like `PartialEq`, `Hash`, and `Clone`. /// /// These are exposed via methods like `PartialReflect::reflect_hash()`, /// `PartialReflect::reflect_partial_eq()`, and `PartialReflect::reflect_clone()`. /// You can force these implementations to use the actual trait /// implementations (instead of their defaults) like this: #[derive(Reflect, Hash, PartialEq, Clone)] #[reflect(Hash, PartialEq, Clone)] pub struct E { x: usize, } /// By default, deriving with Reflect assumes the type is either a "struct" or an "enum". /// /// You can tell reflect to treat your type instead as an "opaque type" by using the `#[reflect(opaque)]`. /// It is generally a good idea to implement (and reflect) the `PartialEq` and `Clone` (optionally also `Serialize` and `Deserialize`) /// traits on opaque types to ensure that these values behave as expected when nested in other reflected types. #[derive(Reflect, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)] #[reflect(opaque)] #[reflect(PartialEq, Clone, Serialize, Deserialize)] enum F { X, Y, } fn setup() { let mut z = <HashMap<_, _>>::default(); z.insert("Hello".to_string(), 1.0); let value: Box<dyn Reflect> = Box::new(A { x: 1, y: vec![1, 2], z, }); // There are a number of different "reflect traits", which each expose different operations on // the underlying type match value.reflect_ref() { // `Struct` is a trait automatically implemented for structs that derive Reflect. This trait // allows you to interact with fields via their string names or indices ReflectRef::Struct(value) => { info!( "This is a 'struct' type with an 'x' value of {}", value.get_field::<usize>("x").unwrap() ); } // `TupleStruct` is a trait automatically implemented for tuple structs that derive Reflect. // This trait allows you to interact with fields via their indices ReflectRef::TupleStruct(_) => {} // `Tuple` is a special trait that can be manually implemented (instead of deriving // Reflect). This exposes "tuple" operations on your type, allowing you to interact // with fields via their indices. Tuple is automatically implemented for tuples of // arity 12 or less. ReflectRef::Tuple(_) => {} // `Enum` is a trait automatically implemented for enums that derive Reflect. This trait allows you // to interact with the current variant and its fields (if it has any) ReflectRef::Enum(_) => {} // `List` is a special trait that can be manually implemented (instead of deriving Reflect). // This exposes "list" operations on your type, such as insertion. `List` is automatically // implemented for relevant core types like Vec<T>. ReflectRef::List(_) => {} // `Array` is a special trait that can be manually implemented (instead of deriving Reflect). // This exposes "array" operations on your type, such as indexing. `Array` // is automatically implemented for relevant core types like [T; N]. ReflectRef::Array(_) => {} // `Map` is a special trait that can be manually implemented (instead of deriving Reflect). // This exposes "map" operations on your type, such as getting / inserting by key. // Map is automatically implemented for relevant core types like HashMap<K, V> ReflectRef::Map(_) => {} // `Set` is a special trait that can be manually implemented (instead of deriving Reflect). // This exposes "set" operations on your type, such as getting / inserting by value. // Set is automatically implemented for relevant core types like HashSet<T> ReflectRef::Set(_) => {} // `Function` is a special trait that can be manually implemented (instead of deriving Reflect). // This exposes "function" operations on your type, such as calling it with arguments. // This trait is automatically implemented for types like DynamicFunction. // This variant only exists if the `reflect_functions` feature is enabled. #[cfg(feature = "reflect_functions")] ReflectRef::Function(_) => {} // `Opaque` types do not implement any of the other traits above. They are simply a Reflect // implementation. Opaque is implemented for opaque types like String and Instant, // but also include primitive types like i32, usize, and f32 (despite not technically being opaque). ReflectRef::Opaque(_) => {} #[expect( clippy::allow_attributes, reason = "`unreachable_patterns` is not always linted" )] #[allow( unreachable_patterns, reason = "This example cannot always detect when `bevy_reflect/functions` is enabled." )] _ => {} } let mut dynamic_list = DynamicList::default(); dynamic_list.push(3u32); dynamic_list.push(4u32); dynamic_list.push(5u32); let mut value: A = value.take::<A>().unwrap(); value.y.apply(&dynamic_list); assert_eq!(value.y, vec![3u32, 4u32, 5u32]); // reference types defined above that are only used to demonstrate reflect // derive functionality: _ = || -> (A, B, C, D, E, F) { unreachable!() }; }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/reflection/function_reflection.rs
examples/reflection/function_reflection.rs
//! This example demonstrates how functions can be called dynamically using reflection. //! //! Function reflection is useful for calling regular Rust functions in a dynamic context, //! where the types of arguments, return values, and even the function itself aren't known at compile time. //! //! This can be used for things like adding scripting support to your application, //! processing deserialized reflection data, or even just storing type-erased versions of your functions. use bevy::reflect::{ func::{ ArgList, DynamicFunction, DynamicFunctionMut, FunctionResult, IntoFunction, IntoFunctionMut, Return, SignatureInfo, }, PartialReflect, Reflect, }; // Note that the `dbg!` invocations are used purely for demonstration purposes // and are not strictly necessary for the example to work. fn main() { // There are times when it may be helpful to store a function away for later. // In Rust, we can do this by storing either a function pointer or a function trait object. // For example, say we wanted to store the following function: fn add(left: i32, right: i32) -> i32 { left + right } // We could store it as either of the following: let fn_pointer: fn(i32, i32) -> i32 = add; let fn_trait_object: Box<dyn Fn(i32, i32) -> i32> = Box::new(add); // And we can call them like so: let result = fn_pointer(2, 2); assert_eq!(result, 4); let result = fn_trait_object(2, 2); assert_eq!(result, 4); // However, you'll notice that we have to know the types of the arguments and return value at compile time. // This means there's not really a way to store or call these functions dynamically at runtime. // Luckily, Bevy's reflection crate comes with a set of tools for doing just that! // We do this by first converting our function into the reflection-based `DynamicFunction` type // using the `IntoFunction` trait. let function: DynamicFunction<'static> = dbg!(add.into_function()); // This time, you'll notice that `DynamicFunction` doesn't take any information about the function's arguments or return value. // This is because `DynamicFunction` checks the types of the arguments and return value at runtime. // Now we can generate a list of arguments: let args: ArgList = dbg!(ArgList::new().with_owned(2_i32).with_owned(2_i32)); // And finally, we can call the function. // This returns a `Result` indicating whether the function was called successfully. // For now, we'll just unwrap it to get our `Return` value, // which is an enum containing the function's return value. let return_value: Return = dbg!(function.call(args).unwrap()); // The `Return` value can be pattern matched or unwrapped to get the underlying reflection data. // For the sake of brevity, we'll just unwrap it here and downcast it to the expected type of `i32`. let value: Box<dyn PartialReflect> = return_value.unwrap_owned(); assert_eq!(value.try_take::<i32>().unwrap(), 4); // The same can also be done for closures that capture references to their environment. // Closures that capture their environment immutably can be converted into a `DynamicFunction` // using the `IntoFunction` trait. let minimum = 5; let clamp = |value: i32| value.max(minimum); let function: DynamicFunction = dbg!(clamp.into_function()); let args = dbg!(ArgList::new().with_owned(2_i32)); let return_value = dbg!(function.call(args).unwrap()); let value: Box<dyn PartialReflect> = return_value.unwrap_owned(); assert_eq!(value.try_take::<i32>().unwrap(), 5); // We can also handle closures that capture their environment mutably // using the `IntoFunctionMut` trait. let mut count = 0; let increment = |amount: i32| count += amount; let closure: DynamicFunctionMut = dbg!(increment.into_function_mut()); let args = dbg!(ArgList::new().with_owned(5_i32)); // Because `DynamicFunctionMut` mutably borrows `total`, // it will need to be dropped before `total` can be accessed again. // This can be done manually with `drop(closure)` or by using the `DynamicFunctionMut::call_once` method. dbg!(closure.call_once(args).unwrap()); assert_eq!(count, 5); // Generic functions can also be converted into a `DynamicFunction`, // however, they will need to be manually monomorphized first. fn stringify<T: ToString>(value: T) -> String { value.to_string() } // We have to manually specify the concrete generic type we want to use. let function = stringify::<i32>.into_function(); let args = ArgList::new().with_owned(123_i32); let return_value = function.call(args).unwrap(); let value: Box<dyn PartialReflect> = return_value.unwrap_owned(); assert_eq!(value.try_take::<String>().unwrap(), "123"); // To make things a little easier, we can also "overload" functions. // This makes it so that a single `DynamicFunction` can represent multiple functions, // and the correct one is chosen based on the types of the arguments. // Each function overload must have a unique argument signature. let function = stringify::<i32> .into_function() .with_overload(stringify::<f32>); // Now our `function` accepts both `i32` and `f32` arguments. let args = ArgList::new().with_owned(1.23_f32); let return_value = function.call(args).unwrap(); let value: Box<dyn PartialReflect> = return_value.unwrap_owned(); assert_eq!(value.try_take::<String>().unwrap(), "1.23"); // Function overloading even allows us to have a variable number of arguments. let function = (|| 0) .into_function() .with_overload(|a: i32| a) .with_overload(|a: i32, b: i32| a + b) .with_overload(|a: i32, b: i32, c: i32| a + b + c); let args = ArgList::new() .with_owned(1_i32) .with_owned(2_i32) .with_owned(3_i32); let return_value = function.call(args).unwrap(); let value: Box<dyn PartialReflect> = return_value.unwrap_owned(); assert_eq!(value.try_take::<i32>().unwrap(), 6); // As stated earlier, `IntoFunction` works for many kinds of simple functions. // Functions with non-reflectable arguments or return values may not be able to be converted. // Generic functions are also not supported (unless manually monomorphized like `foo::<i32>.into_function()`). // Additionally, the lifetime of the return value is tied to the lifetime of the first argument. // However, this means that many methods (i.e. functions with a `self` parameter) are also supported: #[derive(Reflect, Default)] struct Data { value: String, } impl Data { fn set_value(&mut self, value: String) { self.value = value; } // Note that only `&'static str` implements `Reflect`. // To get around this limitation we can use `&String` instead. fn get_value(&self) -> &String { &self.value } } let mut data = Data::default(); let set_value = dbg!(Data::set_value.into_function()); let args = dbg!(ArgList::new().with_mut(&mut data)).with_owned(String::from("Hello, world!")); dbg!(set_value.call(args).unwrap()); assert_eq!(data.value, "Hello, world!"); let get_value = dbg!(Data::get_value.into_function()); let args = dbg!(ArgList::new().with_ref(&data)); let return_value = dbg!(get_value.call(args).unwrap()); let value: &dyn PartialReflect = return_value.unwrap_ref(); assert_eq!(value.try_downcast_ref::<String>().unwrap(), "Hello, world!"); // For more complex use cases, you can always create a custom `DynamicFunction` manually. // This is useful for functions that can't be converted via the `IntoFunction` trait. // For example, this function doesn't implement `IntoFunction` due to the fact that // the lifetime of the return value is not tied to the lifetime of the first argument. fn get_or_insert(value: i32, container: &mut Option<i32>) -> &i32 { if container.is_none() { *container = Some(value); } container.as_ref().unwrap() } let get_or_insert_function = dbg!(DynamicFunction::new( |mut args: ArgList| -> FunctionResult { // The `ArgList` contains the arguments in the order they were pushed. // The `DynamicFunction` will validate that the list contains // exactly the number of arguments we expect. // We can retrieve them out in order (note that this modifies the `ArgList`): let value = args.take::<i32>()?; let container = args.take::<&mut Option<i32>>()?; // We could have also done the following to make use of type inference: // let value = args.take_owned()?; // let container = args.take_mut()?; Ok(Return::Ref(get_or_insert(value, container))) }, // Functions can be either anonymous or named. // It's good practice, though, to try and name your functions whenever possible. // This makes it easier to debug and is also required for function registration. // We can either give it a custom name or use the function's type name as // derived from `std::any::type_name_of_val`. SignatureInfo::named(std::any::type_name_of_val(&get_or_insert)) // We can always change the name if needed. // It's a good idea to also ensure that the name is unique, // such as by using its type name or by prefixing it with your crate name. .with_name("my_crate::get_or_insert") // Since our function takes arguments, we should provide that argument information. // This is used to validate arguments when calling the function. // And it aids consumers of the function with their own validation and debugging. // Arguments should be provided in the order they are defined in the function. .with_arg::<i32>("value") .with_arg::<&mut Option<i32>>("container") // We can provide return information as well. .with_return::<&i32>(), )); let mut container: Option<i32> = None; let args = dbg!(ArgList::new().with_owned(5_i32).with_mut(&mut container)); let value = dbg!(get_or_insert_function.call(args).unwrap()).unwrap_ref(); assert_eq!(value.try_downcast_ref::<i32>(), Some(&5)); let args = dbg!(ArgList::new().with_owned(500_i32).with_mut(&mut container)); let value = dbg!(get_or_insert_function.call(args).unwrap()).unwrap_ref(); assert_eq!(value.try_downcast_ref::<i32>(), Some(&5)); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/reflection/generic_reflection.rs
examples/reflection/generic_reflection.rs
//! Demonstrates how reflection is used with generic Rust types. use bevy::prelude::*; use std::any::TypeId; fn main() { App::new() .add_plugins(DefaultPlugins) // You must manually register each instance of a generic type .register_type::<MyType<u32>>() .add_systems(Startup, setup) .run(); } /// The `#[derive(Reflect)]` macro will automatically add any required bounds to `T`, /// such as `Reflect` and `GetTypeRegistration`. #[derive(Reflect)] struct MyType<T> { value: T, } fn setup(type_registry: Res<AppTypeRegistry>) { let type_registry = type_registry.read(); let registration = type_registry.get(TypeId::of::<MyType<u32>>()).unwrap(); info!( "Registration for {} exists", registration.type_info().type_path(), ); // MyType<String> was not manually registered, so it does not exist assert!(type_registry.get(TypeId::of::<MyType<String>>()).is_none()); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/reflection/custom_attributes.rs
examples/reflection/custom_attributes.rs
//! Demonstrates how to register and access custom attributes on reflected types. use bevy::reflect::{Reflect, TypeInfo, Typed}; use std::{any::TypeId, ops::RangeInclusive}; fn main() { // Bevy supports statically registering custom attribute data on reflected types, // which can then be accessed at runtime via the type's `TypeInfo`. // Attributes are registered using the `#[reflect(@...)]` syntax, // where the `...` is any expression that resolves to a value which implements `Reflect`. // Note that these attributes are stored based on their type: // if two attributes have the same type, the second one will overwrite the first. // Here is an example of registering custom attributes on a type: #[derive(Reflect)] struct Slider { #[reflect(@RangeInclusive::<f32>::new(0.0, 1.0))] // Alternatively, we could have used the `0.0..=1.0` syntax, // but remember to ensure the type is the one you want! #[reflect(@0.0..=1.0_f32)] value: f32, } // Now, we can access the custom attributes at runtime: let TypeInfo::Struct(type_info) = Slider::type_info() else { panic!("expected struct"); }; let field = type_info.field("value").unwrap(); let range = field.get_attribute::<RangeInclusive<f32>>().unwrap(); assert_eq!(*range, 0.0..=1.0); // And remember that our attributes can be any type that implements `Reflect`: #[derive(Reflect)] struct Required; #[derive(Reflect, PartialEq, Debug)] struct Tooltip(String); impl Tooltip { fn new(text: &str) -> Self { Self(text.to_string()) } } #[derive(Reflect)] #[reflect(@Required, @Tooltip::new("An ID is required!"))] struct Id(u8); let TypeInfo::TupleStruct(type_info) = Id::type_info() else { panic!("expected struct"); }; // We can check if an attribute simply exists on our type: assert!(type_info.has_attribute::<Required>()); // We can also get attribute data dynamically: let some_type_id = TypeId::of::<Tooltip>(); let tooltip: &dyn Reflect = type_info.get_attribute_by_id(some_type_id).unwrap(); assert_eq!( tooltip.downcast_ref::<Tooltip>(), Some(&Tooltip::new("An ID is required!")) ); // And again, attributes of the same type will overwrite each other: #[derive(Reflect)] enum Status { // This will result in `false` being stored: #[reflect(@true)] #[reflect(@false)] Disabled, // This will result in `true` being stored: #[reflect(@false)] #[reflect(@true)] Enabled, } let TypeInfo::Enum(type_info) = Status::type_info() else { panic!("expected enum"); }; let disabled = type_info.variant("Disabled").unwrap(); assert!(!disabled.get_attribute::<bool>().unwrap()); let enabled = type_info.variant("Enabled").unwrap(); assert!(enabled.get_attribute::<bool>().unwrap()); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/reflection/dynamic_types.rs
examples/reflection/dynamic_types.rs
//! This example demonstrates the use of dynamic types in Bevy's reflection system. use bevy::reflect::{ reflect_trait, serde::TypedReflectDeserializer, std_traits::ReflectDefault, DynamicArray, DynamicEnum, DynamicList, DynamicMap, DynamicSet, DynamicStruct, DynamicTuple, DynamicTupleStruct, DynamicVariant, FromReflect, PartialReflect, Reflect, ReflectFromReflect, Set, TypeRegistry, Typed, }; use serde::de::DeserializeSeed; use std::collections::{HashMap, HashSet}; fn main() { #[derive(Reflect, Default, PartialEq, Debug)] #[reflect(Identifiable, Default)] struct Player { id: u32, } #[reflect_trait] trait Identifiable { fn id(&self) -> u32; } impl Identifiable for Player { fn id(&self) -> u32 { self.id } } // Normally, when instantiating a type, you get back exactly that type. // This is because the type is known at compile time. // We call this the "concrete" or "canonical" type. let player: Player = Player { id: 123 }; // When working with reflected types, however, we often "erase" this type information // using the `Reflect` trait object. // This trait object also gives us access to all the methods in the `PartialReflect` trait too. // The underlying type is still the same (in this case, `Player`), // but now we've hidden that information from the compiler. let reflected: Box<dyn Reflect> = Box::new(player); // Because it's the same type under the hood, we can still downcast it back to the original type. assert!(reflected.downcast_ref::<Player>().is_some()); // We can attempt to clone our value using `PartialReflect::reflect_clone`. // This will recursively call `PartialReflect::reflect_clone` on all fields of the type. // Or, if we had registered `ReflectClone` using `#[reflect(Clone)]`, it would simply call `Clone::clone` directly. let cloned: Box<dyn Reflect> = reflected.reflect_clone().unwrap(); assert_eq!(cloned.downcast_ref::<Player>(), Some(&Player { id: 123 })); // Another way we can "clone" our data is by converting it to a dynamic type. // Notice here we bind it as a `dyn PartialReflect` instead of `dyn Reflect`. // This is because it returns a dynamic type that simply represents the original type. // In this case, because `Player` is a struct, it will return a `DynamicStruct`. let dynamic: Box<dyn PartialReflect> = reflected.to_dynamic(); assert!(dynamic.is_dynamic()); // And if we try to convert it back to a `dyn Reflect` trait object, we'll get `None`. // Dynamic types cannot be directly cast to `dyn Reflect` trait objects. assert!(dynamic.try_as_reflect().is_none()); // Generally dynamic types are used to represent (or "proxy") the original type, // so that we can continue to access its fields and overall structure. let dynamic_ref = dynamic.reflect_ref().as_struct().unwrap(); let id = dynamic_ref.field("id").unwrap().try_downcast_ref::<u32>(); assert_eq!(id, Some(&123)); // It also enables us to create a representation of a type without having compile-time // access to the actual type. This is how the reflection deserializers work. // They generally can't know how to construct a type ahead of time, // so they instead build and return these dynamic representations. let input = "(id: 123)"; let mut registry = TypeRegistry::default(); registry.register::<Player>(); let registration = registry.get(std::any::TypeId::of::<Player>()).unwrap(); let deserialized = TypedReflectDeserializer::new(registration, &registry) .deserialize(&mut ron::Deserializer::from_str(input).unwrap()) .unwrap(); // Our deserialized output is a `DynamicStruct` that proxies/represents a `Player`. assert!(deserialized.represents::<Player>()); // And while this does allow us to access the fields and structure of the type, // there may be instances where we need the actual type. // For example, if we want to convert our `dyn Reflect` into a `dyn Identifiable`, // we can't use the `DynamicStruct` proxy. let reflect_identifiable = registration .data::<ReflectIdentifiable>() .expect("`ReflectIdentifiable` should be registered"); // Trying to access the registry with our `deserialized` will give a compile error // since it doesn't implement `Reflect`, only `PartialReflect`. // Similarly, trying to force the operation will fail. // This fails since the underlying type of `deserialized` is `DynamicStruct` and not `Player`. assert!(deserialized .try_as_reflect() .and_then(|reflect_trait_obj| reflect_identifiable.get(reflect_trait_obj)) .is_none()); // So how can we go from a dynamic type to a concrete type? // There are two ways: // 1. Using `PartialReflect::apply`. { // If you know the type at compile time, you can construct a new value and apply the dynamic // value to it. let mut value = Player::default(); value.apply(deserialized.as_ref()); assert_eq!(value.id, 123); // If you don't know the type at compile time, you need a dynamic way of constructing // an instance of the type. One such way is to use the `ReflectDefault` type data. let reflect_default = registration .data::<ReflectDefault>() .expect("`ReflectDefault` should be registered"); let mut value: Box<dyn Reflect> = reflect_default.default(); value.apply(deserialized.as_ref()); let identifiable: &dyn Identifiable = reflect_identifiable.get(value.as_reflect()).unwrap(); assert_eq!(identifiable.id(), 123); } // 2. Using `FromReflect` { // If you know the type at compile time, you can use the `FromReflect` trait to convert the // dynamic value into the concrete type directly. let value: Player = Player::from_reflect(deserialized.as_ref()).unwrap(); assert_eq!(value.id, 123); // If you don't know the type at compile time, you can use the `ReflectFromReflect` type data // to perform the conversion dynamically. let reflect_from_reflect = registration .data::<ReflectFromReflect>() .expect("`ReflectFromReflect` should be registered"); let value: Box<dyn Reflect> = reflect_from_reflect .from_reflect(deserialized.as_ref()) .unwrap(); let identifiable: &dyn Identifiable = reflect_identifiable.get(value.as_reflect()).unwrap(); assert_eq!(identifiable.id(), 123); } // Lastly, while dynamic types are commonly generated via reflection methods like // `PartialReflect::to_dynamic` or via the reflection deserializers, // you can also construct them manually. let mut my_dynamic_list = DynamicList::from_iter([1u32, 2u32, 3u32]); // This is useful when you just need to apply some subset of changes to a type. let mut my_list: Vec<u32> = Vec::new(); my_list.apply(&my_dynamic_list); assert_eq!(my_list, vec![1, 2, 3]); // And if you want it to actually proxy a type, you can configure it to do that as well: assert!(!my_dynamic_list .as_partial_reflect() .represents::<Vec<u32>>()); my_dynamic_list.set_represented_type(Some(<Vec<u32>>::type_info())); assert!(my_dynamic_list .as_partial_reflect() .represents::<Vec<u32>>()); // ============================= REFERENCE ============================= // // For reference, here are all the available dynamic types: // 1. `DynamicTuple` { let mut dynamic_tuple = DynamicTuple::default(); dynamic_tuple.insert(1u32); dynamic_tuple.insert(2u32); dynamic_tuple.insert(3u32); let mut my_tuple: (u32, u32, u32) = (0, 0, 0); my_tuple.apply(&dynamic_tuple); assert_eq!(my_tuple, (1, 2, 3)); } // 2. `DynamicArray` { let dynamic_array = DynamicArray::from_iter([1u32, 2u32, 3u32]); let mut my_array = [0u32; 3]; my_array.apply(&dynamic_array); assert_eq!(my_array, [1, 2, 3]); } // 3. `DynamicList` { let dynamic_list = DynamicList::from_iter([1u32, 2u32, 3u32]); let mut my_list: Vec<u32> = Vec::new(); my_list.apply(&dynamic_list); assert_eq!(my_list, vec![1, 2, 3]); } // 4. `DynamicSet` { let mut dynamic_set = DynamicSet::from_iter(["x", "y", "z"]); assert!(dynamic_set.contains(&"x")); dynamic_set.remove(&"y"); let mut my_set: HashSet<&str> = HashSet::default(); my_set.apply(&dynamic_set); assert_eq!(my_set, HashSet::from_iter(["x", "z"])); } // 5. `DynamicMap` { let dynamic_map = DynamicMap::from_iter([("x", 1u32), ("y", 2u32), ("z", 3u32)]); let mut my_map: HashMap<&str, u32> = HashMap::default(); my_map.apply(&dynamic_map); assert_eq!(my_map.get("x"), Some(&1)); assert_eq!(my_map.get("y"), Some(&2)); assert_eq!(my_map.get("z"), Some(&3)); } // 6. `DynamicStruct` { #[derive(Reflect, Default, Debug, PartialEq)] struct MyStruct { x: u32, y: u32, z: u32, } let mut dynamic_struct = DynamicStruct::default(); dynamic_struct.insert("x", 1u32); dynamic_struct.insert("y", 2u32); dynamic_struct.insert("z", 3u32); let mut my_struct = MyStruct::default(); my_struct.apply(&dynamic_struct); assert_eq!(my_struct, MyStruct { x: 1, y: 2, z: 3 }); } // 7. `DynamicTupleStruct` { #[derive(Reflect, Default, Debug, PartialEq)] struct MyTupleStruct(u32, u32, u32); let mut dynamic_tuple_struct = DynamicTupleStruct::default(); dynamic_tuple_struct.insert(1u32); dynamic_tuple_struct.insert(2u32); dynamic_tuple_struct.insert(3u32); let mut my_tuple_struct = MyTupleStruct::default(); my_tuple_struct.apply(&dynamic_tuple_struct); assert_eq!(my_tuple_struct, MyTupleStruct(1, 2, 3)); } // 8. `DynamicEnum` { #[derive(Reflect, Default, Debug, PartialEq)] enum MyEnum { #[default] Empty, Xyz(u32, u32, u32), } let mut values = DynamicTuple::default(); values.insert(1u32); values.insert(2u32); values.insert(3u32); let dynamic_variant = DynamicVariant::Tuple(values); let dynamic_enum = DynamicEnum::new("Xyz", dynamic_variant); let mut my_enum = MyEnum::default(); my_enum.apply(&dynamic_enum); assert_eq!(my_enum, MyEnum::Xyz(1, 2, 3)); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/reflection/auto_register_static/src/lib.rs
examples/reflection/auto_register_static/src/lib.rs
//! Demonstrates how to set up automatic reflect types registration for platforms without `inventory` support use bevy::prelude::*; // The type that should be automatically registered. // All types subject to automatic registration must not be defined in the same crate as `load_type_registrations!``. // Any `#[derive(Reflect)]` types within the `bin` crate are not guaranteed to be registered automatically. #[derive(Reflect)] struct Struct { a: i32, } mod private { mod very_private { use bevy::prelude::*; // Works with private types too! #[allow( clippy::allow_attributes, dead_code, reason = "This struct is used as a compilation test to test the derive macros, and as such is intentionally never constructed." )] #[derive(Reflect)] struct PrivateStruct { a: i32, } } } /// This is the main entrypoint, bin just forwards to it. pub fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, startup) .run(); } fn startup(reg: Res<AppTypeRegistry>) { let registry = reg.read(); info!( "Is `Struct` registered? {}", registry.contains(core::any::TypeId::of::<Struct>()) ); info!( "Type info of `PrivateStruct`: {:?}", registry .get_with_short_type_path("PrivateStruct") .expect("Not registered") ); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/reflection/auto_register_static/src/bin/main.rs
examples/reflection/auto_register_static/src/bin/main.rs
//! Demonstrates how to set up automatic reflect types registration for platforms without `inventory` support use auto_register_static::main as lib_main; use bevy::reflect::load_type_registrations; fn main() { // This must be called before our main to collect all type registration functions. load_type_registrations!(); // After running load_type_registrations! we just forward to our main. lib_main(); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/state/computed_states.rs
examples/state/computed_states.rs
//! This example illustrates the use of [`ComputedStates`] for more complex state handling patterns. //! //! In this case, we'll be implementing the following pattern: //! - The game will start in a `Menu` state, which we can return to with `Esc` //! - From there, we can enter the game - where our bevy symbol moves around and changes color //! - While in game, we can pause and unpause the game using `Space` //! - We can also toggle "Turbo Mode" with the `T` key - where the movement and color changes are all faster. This //! is retained between pauses, but not if we exit to the main menu. //! //! In addition, we want to enable a "tutorial" mode, which will involve its own state that is toggled in the main menu. //! This will display instructions about movement and turbo mode when in game and unpaused, and instructions on how to unpause when paused. //! //! To implement this, we will create 2 root-level states: [`AppState`] and [`TutorialState`]. //! We will then create some computed states that derive from [`AppState`]: [`InGame`] and [`TurboMode`] are marker states implemented //! as Zero-Sized Structs (ZSTs), while [`IsPaused`] is an enum with 2 distinct states. //! And lastly, we'll add [`Tutorial`], a computed state deriving from [`TutorialState`], [`InGame`] and [`IsPaused`], with 2 distinct //! states to display the 2 tutorial texts. use bevy::{dev_tools::states::*, prelude::*}; use ui::*; // To begin, we want to define our state objects. #[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)] enum AppState { #[default] Menu, // Unlike in the `states` example, we're adding more data in this // version of our AppState. In this case, we actually have // 4 distinct "InGame" states - unpaused and no turbo, paused and no // turbo, unpaused and turbo and paused and turbo. InGame { paused: bool, turbo: bool, }, } // The tutorial state object, on the other hand, is a fairly simple enum. #[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)] enum TutorialState { #[default] Active, Inactive, } // Because we have 4 distinct values of `AppState` that mean we're "InGame", we're going to define // a separate "InGame" type and implement `ComputedStates` for it. // This allows us to only need to check against one type // when otherwise we'd need to check against multiple. #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] struct InGame; impl ComputedStates for InGame { // Our computed state depends on `AppState`, so we need to specify it as the SourceStates type. type SourceStates = AppState; // The compute function takes in the `SourceStates` fn compute(sources: AppState) -> Option<Self> { // You might notice that InGame has no values - instead, in this case, the `State<InGame>` resource only exists // if the `compute` function would return `Some` - so only when we are in game. match sources { // No matter what the value of `paused` or `turbo` is, we're still in the game rather than a menu AppState::InGame { .. } => Some(Self), _ => None, } } } // Similarly, we want to have the TurboMode state - so we'll define that now. // // Having it separate from [`InGame`] and [`AppState`] like this allows us to check each of them separately, rather than // needing to compare against every version of the AppState that could involve them. // // In addition, it allows us to still maintain a strict type representation - you can't Turbo // if you aren't in game, for example - while still having the // flexibility to check for the states as if they were completely unrelated. #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] struct TurboMode; impl ComputedStates for TurboMode { type SourceStates = AppState; fn compute(sources: AppState) -> Option<Self> { match sources { AppState::InGame { turbo: true, .. } => Some(Self), _ => None, } } } // For the [`IsPaused`] state, we'll actually use an `enum` - because the difference between `Paused` and `NotPaused` // involve activating different systems. // // To clarify the difference, `InGame` and `TurboMode` both activate systems if they exist, and there is // no variation within them. So we defined them as Zero-Sized Structs. // // In contrast, pausing actually involve 3 distinct potential situations: // - it doesn't exist - this is when being paused is meaningless, like in the menu. // - it is `NotPaused` - in which elements like the movement system are active. // - it is `Paused` - in which those game systems are inactive, and a pause screen is shown. #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] enum IsPaused { NotPaused, Paused, } impl ComputedStates for IsPaused { type SourceStates = AppState; fn compute(sources: AppState) -> Option<Self> { // Here we convert from our [`AppState`] to all potential [`IsPaused`] versions. match sources { AppState::InGame { paused: true, .. } => Some(Self::Paused), AppState::InGame { paused: false, .. } => Some(Self::NotPaused), // If `AppState` is not `InGame`, pausing is meaningless, and so we set it to `None`. _ => None, } } } // Lastly, we have our tutorial, which actually has a more complex derivation. // // Like `IsPaused`, the tutorial has a few fully distinct possible states, so we want to represent them // as an Enum. However - in this case they are all dependent on multiple states: the root [`TutorialState`], // and both [`InGame`] and [`IsPaused`] - which are in turn derived from [`AppState`]. #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] enum Tutorial { MovementInstructions, PauseInstructions, } impl ComputedStates for Tutorial { // We can also use tuples of types that implement [`States`] as our [`SourceStates`]. // That includes other [`ComputedStates`] - though circular dependencies are not supported // and will produce a compile error. // // We could define this as relying on [`TutorialState`] and [`AppState`] instead, but // then we would need to duplicate the derivation logic for [`InGame`] and [`IsPaused`]. // In this example that is not a significant undertaking, but as a rule it is likely more // effective to rely on the already derived states to avoid the logic drifting apart. // // Notice that you can wrap any of the [`States`] here in [`Option`]s. If you do so, // the computation will get called even if the state does not exist. type SourceStates = (TutorialState, InGame, Option<IsPaused>); // Notice that we aren't using InGame - we're just using it as a source state to // prevent the computation from executing if we're not in game. Instead - this // ComputedState will just not exist in that situation. fn compute( (tutorial_state, _in_game, is_paused): (TutorialState, InGame, Option<IsPaused>), ) -> Option<Self> { // If the tutorial is inactive we don't need to worry about it. if !matches!(tutorial_state, TutorialState::Active) { return None; } // If we're paused, we're in the PauseInstructions tutorial // Otherwise, we're in the MovementInstructions tutorial match is_paused? { IsPaused::NotPaused => Some(Tutorial::MovementInstructions), IsPaused::Paused => Some(Tutorial::PauseInstructions), } } } fn main() { // We start the setup like we did in the states example. App::new() .add_plugins(DefaultPlugins) .init_state::<AppState>() .init_state::<TutorialState>() // After initializing the normal states, we'll use `.add_computed_state::<CS>()` to initialize our `ComputedStates` .add_computed_state::<InGame>() .add_computed_state::<IsPaused>() .add_computed_state::<TurboMode>() .add_computed_state::<Tutorial>() // we can then resume adding systems just like we would in any other case, // using our states as normal. .add_systems(Startup, setup) .add_systems(OnEnter(AppState::Menu), setup_menu) .add_systems(Update, menu.run_if(in_state(AppState::Menu))) .add_systems(OnExit(AppState::Menu), cleanup_menu) // We only want to run the [`setup_game`] function when we enter the [`AppState::InGame`] state, regardless // of whether the game is paused or not. .add_systems(OnEnter(InGame), setup_game) // We want the color change, toggle_pause and quit_to_menu systems to ignore the paused condition, so we can use the [`InGame`] derived // state here as well. .add_systems( Update, (toggle_pause, change_color, quit_to_menu).run_if(in_state(InGame)), ) // However, we only want to move or toggle turbo mode if we are not in a paused state. .add_systems( Update, (toggle_turbo, movement).run_if(in_state(IsPaused::NotPaused)), ) // We can continue setting things up, following all the same patterns used above and in the `states` example. .add_systems(OnEnter(IsPaused::Paused), setup_paused_screen) .add_systems(OnEnter(TurboMode), setup_turbo_text) .add_systems( OnEnter(Tutorial::MovementInstructions), movement_instructions, ) .add_systems(OnEnter(Tutorial::PauseInstructions), pause_instructions) .add_systems( Update, ( log_transitions::<AppState>, log_transitions::<TutorialState>, ), ) .run(); } fn menu( mut next_state: ResMut<NextState<AppState>>, tutorial_state: Res<State<TutorialState>>, mut next_tutorial: ResMut<NextState<TutorialState>>, mut interaction_query: Query< (&Interaction, &mut BackgroundColor, &MenuButton), (Changed<Interaction>, With<Button>), >, ) { for (interaction, mut color, menu_button) in &mut interaction_query { match *interaction { Interaction::Pressed => { *color = if menu_button == &MenuButton::Tutorial && tutorial_state.get() == &TutorialState::Active { PRESSED_ACTIVE_BUTTON.into() } else { PRESSED_BUTTON.into() }; match menu_button { MenuButton::Play => next_state.set(AppState::InGame { paused: false, turbo: false, }), MenuButton::Tutorial => next_tutorial.set(match tutorial_state.get() { TutorialState::Active => TutorialState::Inactive, TutorialState::Inactive => TutorialState::Active, }), }; } Interaction::Hovered => { if menu_button == &MenuButton::Tutorial && tutorial_state.get() == &TutorialState::Active { *color = HOVERED_ACTIVE_BUTTON.into(); } else { *color = HOVERED_BUTTON.into(); } } Interaction::None => { if menu_button == &MenuButton::Tutorial && tutorial_state.get() == &TutorialState::Active { *color = ACTIVE_BUTTON.into(); } else { *color = NORMAL_BUTTON.into(); } } } } } fn toggle_pause( input: Res<ButtonInput<KeyCode>>, current_state: Res<State<AppState>>, mut next_state: ResMut<NextState<AppState>>, ) { if input.just_pressed(KeyCode::Space) && let AppState::InGame { paused, turbo } = current_state.get() { next_state.set(AppState::InGame { paused: !*paused, turbo: *turbo, }); } } fn toggle_turbo( input: Res<ButtonInput<KeyCode>>, current_state: Res<State<AppState>>, mut next_state: ResMut<NextState<AppState>>, ) { if input.just_pressed(KeyCode::KeyT) && let AppState::InGame { paused, turbo } = current_state.get() { next_state.set(AppState::InGame { paused: *paused, turbo: !*turbo, }); } } fn quit_to_menu(input: Res<ButtonInput<KeyCode>>, mut next_state: ResMut<NextState<AppState>>) { if input.just_pressed(KeyCode::Escape) { next_state.set(AppState::Menu); } } mod ui { use crate::*; #[derive(Resource)] pub struct MenuData { pub root_entity: Entity, } #[derive(Component, PartialEq, Eq)] pub enum MenuButton { Play, Tutorial, } pub const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15); pub const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25); pub const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35); pub const ACTIVE_BUTTON: Color = Color::srgb(0.15, 0.85, 0.15); pub const HOVERED_ACTIVE_BUTTON: Color = Color::srgb(0.25, 0.55, 0.25); pub const PRESSED_ACTIVE_BUTTON: Color = Color::srgb(0.35, 0.95, 0.35); pub fn setup(mut commands: Commands) { commands.spawn(Camera2d); } pub fn setup_menu(mut commands: Commands, tutorial_state: Res<State<TutorialState>>) { let button_entity = commands .spawn(( Node { // center button width: percent(100), height: percent(100), justify_content: JustifyContent::Center, align_items: AlignItems::Center, flex_direction: FlexDirection::Column, row_gap: px(10), ..default() }, children![ ( Button, Node { width: px(200), height: px(65), // horizontally center child text justify_content: JustifyContent::Center, // vertically center child text align_items: AlignItems::Center, ..default() }, BackgroundColor(NORMAL_BUTTON), MenuButton::Play, children![( Text::new("Play"), TextFont { font_size: 33.0, ..default() }, TextColor(Color::srgb(0.9, 0.9, 0.9)), )], ), ( Button, Node { width: px(200), height: px(65), // horizontally center child text justify_content: JustifyContent::Center, // vertically center child text align_items: AlignItems::Center, ..default() }, BackgroundColor(match tutorial_state.get() { TutorialState::Active => ACTIVE_BUTTON, TutorialState::Inactive => NORMAL_BUTTON, }), MenuButton::Tutorial, children![( Text::new("Tutorial"), TextFont { font_size: 33.0, ..default() }, TextColor(Color::srgb(0.9, 0.9, 0.9)), )] ), ], )) .id(); commands.insert_resource(MenuData { root_entity: button_entity, }); } pub fn cleanup_menu(mut commands: Commands, menu_data: Res<MenuData>) { commands.entity(menu_data.root_entity).despawn(); } pub fn setup_game(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(( DespawnOnExit(InGame), Sprite::from_image(asset_server.load("branding/icon.png")), )); } const SPEED: f32 = 100.0; const TURBO_SPEED: f32 = 300.0; pub fn movement( time: Res<Time>, input: Res<ButtonInput<KeyCode>>, turbo: Option<Res<State<TurboMode>>>, mut query: Query<&mut Transform, With<Sprite>>, ) { for mut transform in &mut query { let mut direction = Vec3::ZERO; if input.pressed(KeyCode::ArrowLeft) { direction.x -= 1.0; } if input.pressed(KeyCode::ArrowRight) { direction.x += 1.0; } if input.pressed(KeyCode::ArrowUp) { direction.y += 1.0; } if input.pressed(KeyCode::ArrowDown) { direction.y -= 1.0; } if direction != Vec3::ZERO { transform.translation += direction.normalize() * if turbo.is_some() { TURBO_SPEED } else { SPEED } * time.delta_secs(); } } } pub fn setup_paused_screen(mut commands: Commands) { info!("Printing Pause"); commands.spawn(( DespawnOnExit(IsPaused::Paused), Node { // center button width: percent(100), height: percent(100), justify_content: JustifyContent::Center, align_items: AlignItems::Center, flex_direction: FlexDirection::Column, row_gap: px(10), position_type: PositionType::Absolute, ..default() }, children![( Node { width: px(400), height: px(400), // horizontally center child text justify_content: JustifyContent::Center, // vertically center child text align_items: AlignItems::Center, ..default() }, BackgroundColor(NORMAL_BUTTON), MenuButton::Play, children![( Text::new("Paused"), TextFont { font_size: 33.0, ..default() }, TextColor(Color::srgb(0.9, 0.9, 0.9)), )], ),], )); } pub fn setup_turbo_text(mut commands: Commands) { commands.spawn(( DespawnOnExit(TurboMode), Node { // center button width: percent(100), height: percent(100), justify_content: JustifyContent::Start, align_items: AlignItems::Center, flex_direction: FlexDirection::Column, row_gap: px(10), position_type: PositionType::Absolute, ..default() }, children![( Text::new("TURBO MODE"), TextFont { font_size: 33.0, ..default() }, TextColor(Color::srgb(0.9, 0.3, 0.1)), )], )); } pub fn change_color(time: Res<Time>, mut query: Query<&mut Sprite>) { for mut sprite in &mut query { let new_color = LinearRgba { blue: ops::sin(time.elapsed_secs() * 0.5) + 2.0, ..LinearRgba::from(sprite.color) }; sprite.color = new_color.into(); } } pub fn movement_instructions(mut commands: Commands) { commands.spawn(( DespawnOnExit(Tutorial::MovementInstructions), Node { // center button width: percent(100), height: percent(100), justify_content: JustifyContent::End, align_items: AlignItems::Center, flex_direction: FlexDirection::Column, row_gap: px(10), position_type: PositionType::Absolute, ..default() }, children![ ( Text::new("Move the bevy logo with the arrow keys"), TextFont { font_size: 33.0, ..default() }, TextColor(Color::srgb(0.3, 0.3, 0.7)), ), ( Text::new("Press T to enter TURBO MODE"), TextFont { font_size: 33.0, ..default() }, TextColor(Color::srgb(0.3, 0.3, 0.7)), ), ( Text::new("Press SPACE to pause"), TextFont { font_size: 33.0, ..default() }, TextColor(Color::srgb(0.3, 0.3, 0.7)), ), ( Text::new("Press ESCAPE to return to the menu"), TextFont { font_size: 33.0, ..default() }, TextColor(Color::srgb(0.3, 0.3, 0.7)), ), ], )); } pub fn pause_instructions(mut commands: Commands) { commands.spawn(( DespawnOnExit(Tutorial::PauseInstructions), Node { // center button width: percent(100), height: percent(100), justify_content: JustifyContent::End, align_items: AlignItems::Center, flex_direction: FlexDirection::Column, row_gap: px(10), position_type: PositionType::Absolute, ..default() }, children![ ( Text::new("Press SPACE to resume"), TextFont { font_size: 33.0, ..default() }, TextColor(Color::srgb(0.3, 0.3, 0.7)), ), ( Text::new("Press ESCAPE to return to the menu"), TextFont { font_size: 33.0, ..default() }, TextColor(Color::srgb(0.3, 0.3, 0.7)), ), ], )); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/state/sub_states.rs
examples/state/sub_states.rs
//! This example illustrates the use of [`SubStates`] for more complex state handling patterns. //! //! [`SubStates`] are [`States`] that only exist while the App is in another [`State`]. They can //! be used to create more complex patterns while relying on simple enums, or to de-couple certain //! elements of complex state objects. //! //! In this case, we're transitioning from a `Menu` state to an `InGame` state, at which point we create //! a substate called `IsPaused` to track whether the game is paused or not. use bevy::{dev_tools::states::*, prelude::*}; use ui::*; #[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)] enum AppState { #[default] Menu, InGame, } // In this case, instead of deriving `States`, we derive `SubStates` #[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, SubStates)] // And we need to add an attribute to let us know what the source state is // and what value it needs to have. This will ensure that unless we're // in [`AppState::InGame`], the [`IsPaused`] state resource // will not exist. #[source(AppState = AppState::InGame)] #[states(scoped_entities)] enum IsPaused { #[default] Running, Paused, } fn main() { App::new() .add_plugins(DefaultPlugins) .init_state::<AppState>() .add_sub_state::<IsPaused>() // We set the substate up here. // Most of these remain the same .add_systems(Startup, setup) .add_systems(OnEnter(AppState::Menu), setup_menu) .add_systems(Update, menu.run_if(in_state(AppState::Menu))) .add_systems(OnExit(AppState::Menu), cleanup_menu) .add_systems(OnEnter(AppState::InGame), setup_game) .add_systems(OnEnter(IsPaused::Paused), setup_paused_screen) .add_systems( Update, ( // Instead of relying on [`AppState::InGame`] here, we're relying on // [`IsPaused::Running`], since we don't want movement or color changes // if we're paused (movement, change_color).run_if(in_state(IsPaused::Running)), // The pause toggle, on the other hand, needs to work whether we're // paused or not, so it uses [`AppState::InGame`] instead. toggle_pause.run_if(in_state(AppState::InGame)), ), ) .add_systems(Update, log_transitions::<AppState>) .run(); } fn menu( mut next_state: ResMut<NextState<AppState>>, mut interaction_query: Query< (&Interaction, &mut BackgroundColor), (Changed<Interaction>, With<Button>), >, ) { for (interaction, mut color) in &mut interaction_query { match *interaction { Interaction::Pressed => { *color = PRESSED_BUTTON.into(); next_state.set(AppState::InGame); } Interaction::Hovered => { *color = HOVERED_BUTTON.into(); } Interaction::None => { *color = NORMAL_BUTTON.into(); } } } } fn cleanup_menu(mut commands: Commands, menu_data: Res<MenuData>) { commands.entity(menu_data.button_entity).despawn(); } const SPEED: f32 = 100.0; fn movement( time: Res<Time>, input: Res<ButtonInput<KeyCode>>, mut query: Query<&mut Transform, With<Sprite>>, ) { for mut transform in &mut query { let mut direction = Vec3::ZERO; if input.pressed(KeyCode::ArrowLeft) { direction.x -= 1.0; } if input.pressed(KeyCode::ArrowRight) { direction.x += 1.0; } if input.pressed(KeyCode::ArrowUp) { direction.y += 1.0; } if input.pressed(KeyCode::ArrowDown) { direction.y -= 1.0; } if direction != Vec3::ZERO { transform.translation += direction.normalize() * SPEED * time.delta_secs(); } } } fn change_color(time: Res<Time>, mut query: Query<&mut Sprite>) { for mut sprite in &mut query { let new_color = LinearRgba { blue: ops::sin(time.elapsed_secs() * 0.5) + 2.0, ..LinearRgba::from(sprite.color) }; sprite.color = new_color.into(); } } fn toggle_pause( input: Res<ButtonInput<KeyCode>>, current_state: Res<State<IsPaused>>, mut next_state: ResMut<NextState<IsPaused>>, ) { if input.just_pressed(KeyCode::Space) { next_state.set(match current_state.get() { IsPaused::Running => IsPaused::Paused, IsPaused::Paused => IsPaused::Running, }); } } mod ui { use crate::*; #[derive(Resource)] pub struct MenuData { pub button_entity: Entity, } pub const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15); pub const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25); pub const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35); pub fn setup(mut commands: Commands) { commands.spawn(Camera2d); } pub fn setup_menu(mut commands: Commands) { let button_entity = commands .spawn(( Node { // center button width: percent(100), height: percent(100), justify_content: JustifyContent::Center, align_items: AlignItems::Center, ..default() }, children![( Button, Node { width: px(150), height: px(65), // horizontally center child text justify_content: JustifyContent::Center, // vertically center child text align_items: AlignItems::Center, ..default() }, BackgroundColor(NORMAL_BUTTON), children![( Text::new("Play"), TextFont { font_size: 33.0, ..default() }, TextColor(Color::srgb(0.9, 0.9, 0.9)), )] )], )) .id(); commands.insert_resource(MenuData { button_entity }); } pub fn setup_game(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(Sprite::from_image(asset_server.load("branding/icon.png"))); } pub fn setup_paused_screen(mut commands: Commands) { commands.spawn(( DespawnOnExit(IsPaused::Paused), Node { // center button width: percent(100), height: percent(100), justify_content: JustifyContent::Center, align_items: AlignItems::Center, flex_direction: FlexDirection::Column, row_gap: px(10), ..default() }, children![( Node { width: px(400), height: px(400), // horizontally center child text justify_content: JustifyContent::Center, // vertically center child text align_items: AlignItems::Center, ..default() }, BackgroundColor(NORMAL_BUTTON), children![( Text::new("Paused"), TextFont { font_size: 33.0, ..default() }, TextColor(Color::srgb(0.9, 0.9, 0.9)), )] )], )); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/state/custom_transitions.rs
examples/state/custom_transitions.rs
//! This example illustrates how to register custom state transition behavior. //! //! In this case we are trying to add `OnReenter` and `OnReexit` //! which will work much like `OnEnter` and `OnExit`, //! but additionally trigger if the state changed into itself. //! //! While identity transitions exist internally in [`StateTransitionEvent`]s, //! the default schedules intentionally ignore them, as this behavior is not commonly needed or expected. //! //! While this example displays identity transitions for a single state, //! identity transitions are propagated through the entire state graph, //! meaning any change to parent state will be propagated to [`ComputedStates`] and [`SubStates`]. use std::marker::PhantomData; use bevy::{dev_tools::states::*, ecs::schedule::ScheduleLabel, prelude::*}; use custom_transitions::*; #[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)] enum AppState { #[default] Menu, InGame, } fn main() { App::new() // We insert the custom transitions plugin for `AppState`. .add_plugins(( DefaultPlugins, IdentityTransitionsPlugin::<AppState>::default(), )) .init_state::<AppState>() .add_systems(Startup, setup) .add_systems(OnEnter(AppState::Menu), setup_menu) .add_systems(Update, menu.run_if(in_state(AppState::Menu))) .add_systems(OnExit(AppState::Menu), cleanup_menu) // We will restart the game progress every time we re-enter into it. .add_systems(OnReenter(AppState::InGame), setup_game) .add_systems(OnReexit(AppState::InGame), teardown_game) // Doing it this way allows us to restart the game without any additional in-between states. .add_systems( Update, ((movement, change_color, trigger_game_restart).run_if(in_state(AppState::InGame)),), ) .add_systems(Update, log_transitions::<AppState>) .run(); } /// This module provides the custom `OnReenter` and `OnReexit` transitions for easy installation. mod custom_transitions { use crate::*; /// The plugin registers the transitions for one specific state. /// If you use this for multiple states consider: /// - installing the plugin multiple times, /// - create an [`App`] extension method that inserts /// those transitions during state installation. #[derive(Default)] pub struct IdentityTransitionsPlugin<S: States>(PhantomData<S>); impl<S: States> Plugin for IdentityTransitionsPlugin<S> { fn build(&self, app: &mut App) { app.add_systems( StateTransition, // The internals can generate at most one transition event of specific type per frame. // We take the latest one and clear the queue. last_transition::<S> // We insert the optional event into our schedule runner. .pipe(run_reenter::<S>) // State transitions are handled in three ordered steps, exposed as system sets. // We can add our systems to them, which will run the corresponding schedules when they're evaluated. // These are: // - [`ExitSchedules`] - Ran from leaf-states to root-states, // - [`TransitionSchedules`] - Ran in arbitrary order, // - [`EnterSchedules`] - Ran from root-states to leaf-states. .in_set(EnterSchedules::<S>::default()), ) .add_systems( StateTransition, last_transition::<S> .pipe(run_reexit::<S>) .in_set(ExitSchedules::<S>::default()), ); } } /// Custom schedule that will behave like [`OnEnter`], but run on identity transitions. #[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash)] pub struct OnReenter<S: States>(pub S); /// Schedule runner which checks conditions and if they're right /// runs out custom schedule. fn run_reenter<S: States>(transition: In<Option<StateTransitionEvent<S>>>, world: &mut World) { // We return early if no transition event happened. let Some(transition) = transition.0 else { return; }; // If we wanted to ignore identity transitions, // we'd compare `exited` and `entered` here, // and return if they were the same. // We check if we actually entered a state. // A [`None`] would indicate that the state was removed from the world. // This only happens in the case of [`SubStates`] and [`ComputedStates`]. let Some(entered) = transition.entered else { return; }; // If all conditions are valid, we run our custom schedule. let _ = world.try_run_schedule(OnReenter(entered)); // If you want to overwrite the default `OnEnter` behavior to act like re-enter, // you can do so by running the `OnEnter` schedule here. Note that you don't want // to run `OnEnter` when the default behavior does so. // ``` // if transition.entered != transition.exited { // return; // } // let _ = world.try_run_schedule(OnReenter(entered)); // ``` } /// Custom schedule that will behave like [`OnExit`], but run on identity transitions. #[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash)] pub struct OnReexit<S: States>(pub S); fn run_reexit<S: States>(transition: In<Option<StateTransitionEvent<S>>>, world: &mut World) { let Some(transition) = transition.0 else { return; }; let Some(exited) = transition.exited else { return; }; let _ = world.try_run_schedule(OnReexit(exited)); } } fn menu( mut next_state: ResMut<NextState<AppState>>, mut interaction_query: Query< (&Interaction, &mut BackgroundColor), (Changed<Interaction>, With<Button>), >, ) { for (interaction, mut color) in &mut interaction_query { match *interaction { Interaction::Pressed => { *color = PRESSED_BUTTON.into(); next_state.set(AppState::InGame); } Interaction::Hovered => { *color = HOVERED_BUTTON.into(); } Interaction::None => { *color = NORMAL_BUTTON.into(); } } } } fn cleanup_menu(mut commands: Commands, menu_data: Res<MenuData>) { commands.entity(menu_data.button_entity).despawn(); } const SPEED: f32 = 100.0; fn movement( time: Res<Time>, input: Res<ButtonInput<KeyCode>>, mut query: Query<&mut Transform, With<Sprite>>, ) { for mut transform in &mut query { let mut direction = Vec3::ZERO; if input.pressed(KeyCode::ArrowLeft) { direction.x -= 1.0; } if input.pressed(KeyCode::ArrowRight) { direction.x += 1.0; } if input.pressed(KeyCode::ArrowUp) { direction.y += 1.0; } if input.pressed(KeyCode::ArrowDown) { direction.y -= 1.0; } if direction != Vec3::ZERO { transform.translation += direction.normalize() * SPEED * time.delta_secs(); } } } fn change_color(time: Res<Time>, mut query: Query<&mut Sprite>) { for mut sprite in &mut query { let new_color = LinearRgba { blue: ops::sin(time.elapsed_secs() * 0.5) + 2.0, ..LinearRgba::from(sprite.color) }; sprite.color = new_color.into(); } } // We can restart the game by pressing "R". // This will trigger an [`AppState::InGame`] -> [`AppState::InGame`] // transition, which will run our custom schedules. fn trigger_game_restart( input: Res<ButtonInput<KeyCode>>, mut next_state: ResMut<NextState<AppState>>, ) { if input.just_pressed(KeyCode::KeyR) { // Although we are already in this state setting it again will generate an identity transition. // While default schedules ignore those kinds of transitions, our custom schedules will react to them. next_state.set(AppState::InGame); } } fn setup(mut commands: Commands) { commands.spawn(Camera2d); } fn setup_game(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(Sprite::from_image(asset_server.load("branding/icon.png"))); info!("Setup game"); } fn teardown_game(mut commands: Commands, player: Single<Entity, With<Sprite>>) { commands.entity(*player).despawn(); info!("Teardown game"); } #[derive(Resource)] struct MenuData { pub button_entity: Entity, } const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15); const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25); const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35); fn setup_menu(mut commands: Commands) { let button_entity = commands .spawn(( Node { // center button width: percent(100), height: percent(100), justify_content: JustifyContent::Center, align_items: AlignItems::Center, ..default() }, children![( Button, Node { width: px(150), height: px(65), // horizontally center child text justify_content: JustifyContent::Center, // vertically center child text align_items: AlignItems::Center, ..default() }, BackgroundColor(NORMAL_BUTTON), children![( Text::new("Play"), TextFont { font_size: 33.0, ..default() }, TextColor(Color::srgb(0.9, 0.9, 0.9)), )] )], )) .id(); commands.insert_resource(MenuData { button_entity }); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/state/states.rs
examples/state/states.rs
//! This example illustrates how to use [`States`] for high-level app control flow. //! States are a powerful but intuitive tool for controlling which logic runs when. //! You can have multiple independent states, and the [`OnEnter`] and [`OnExit`] schedules //! can be used to great effect to ensure that you handle setup and teardown appropriately. //! //! In this case, we're transitioning from a `Menu` state to an `InGame` state. use bevy::prelude::*; fn main() { let mut app = App::new(); app.add_plugins(DefaultPlugins) .init_state::<AppState>() // Alternatively we could use .insert_state(AppState::Menu) .add_systems(Startup, setup) // This system runs when we enter `AppState::Menu`, during the `StateTransition` schedule. // All systems from the exit schedule of the state we're leaving are run first, // and then all systems from the enter schedule of the state we're entering are run second. .add_systems(OnEnter(AppState::Menu), setup_menu) // By contrast, update systems are stored in the `Update` schedule. They simply // check the value of the `State<T>` resource to see if they should run each frame. .add_systems(Update, menu.run_if(in_state(AppState::Menu))) .add_systems(OnExit(AppState::Menu), cleanup_menu) .add_systems(OnEnter(AppState::InGame), setup_game) .add_systems( Update, (movement, change_color).run_if(in_state(AppState::InGame)), ); #[cfg(feature = "bevy_dev_tools")] app.add_systems(Update, bevy::dev_tools::states::log_transitions::<AppState>); #[cfg(not(feature = "bevy_dev_tools"))] warn!("Enable feature bevy_dev_tools to log state transitions"); app.run(); } #[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)] enum AppState { #[default] Menu, InGame, } #[derive(Resource)] struct MenuData { button_entity: Entity, } const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15); const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25); const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35); fn setup(mut commands: Commands) { commands.spawn(Camera2d); } fn setup_menu(mut commands: Commands) { let button_entity = commands .spawn(( Node { // center button width: percent(100), height: percent(100), justify_content: JustifyContent::Center, align_items: AlignItems::Center, ..default() }, children![( Button, Node { width: px(150), height: px(65), // horizontally center child text justify_content: JustifyContent::Center, // vertically center child text align_items: AlignItems::Center, ..default() }, BackgroundColor(NORMAL_BUTTON), children![( Text::new("Play"), TextFont { font_size: 33.0, ..default() }, TextColor(Color::srgb(0.9, 0.9, 0.9)), )], )], )) .id(); commands.insert_resource(MenuData { button_entity }); } fn menu( mut next_state: ResMut<NextState<AppState>>, mut interaction_query: Query< (&Interaction, &mut BackgroundColor), (Changed<Interaction>, With<Button>), >, ) { for (interaction, mut color) in &mut interaction_query { match *interaction { Interaction::Pressed => { *color = PRESSED_BUTTON.into(); next_state.set(AppState::InGame); } Interaction::Hovered => { *color = HOVERED_BUTTON.into(); } Interaction::None => { *color = NORMAL_BUTTON.into(); } } } } fn cleanup_menu(mut commands: Commands, menu_data: Res<MenuData>) { commands.entity(menu_data.button_entity).despawn(); } fn setup_game(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(Sprite::from_image(asset_server.load("branding/icon.png"))); } const SPEED: f32 = 100.0; fn movement( time: Res<Time>, input: Res<ButtonInput<KeyCode>>, mut query: Query<&mut Transform, With<Sprite>>, ) { for mut transform in &mut query { let mut direction = Vec3::ZERO; if input.pressed(KeyCode::ArrowLeft) { direction.x -= 1.0; } if input.pressed(KeyCode::ArrowRight) { direction.x += 1.0; } if input.pressed(KeyCode::ArrowUp) { direction.y += 1.0; } if input.pressed(KeyCode::ArrowDown) { direction.y -= 1.0; } if direction != Vec3::ZERO { transform.translation += direction.normalize() * SPEED * time.delta_secs(); } } } fn change_color(time: Res<Time>, mut query: Query<&mut Sprite>) { for mut sprite in &mut query { let new_color = LinearRgba { blue: ops::sin(time.elapsed_secs() * 0.5) + 2.0, ..LinearRgba::from(sprite.color) }; sprite.color = new_color.into(); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/tools/gamepad_viewer.rs
examples/tools/gamepad_viewer.rs
//! Shows a visualization of gamepad buttons, sticks, and triggers use std::f32::consts::PI; use bevy::{ input::gamepad::{GamepadAxisChangedEvent, GamepadButtonChangedEvent, GamepadConnectionEvent}, prelude::*, sprite::Anchor, }; const BUTTON_RADIUS: f32 = 25.; const BUTTON_CLUSTER_RADIUS: f32 = 50.; const START_SIZE: Vec2 = Vec2::new(30., 15.); const TRIGGER_SIZE: Vec2 = Vec2::new(70., 20.); const STICK_BOUNDS_SIZE: f32 = 100.; const BUTTONS_X: f32 = 150.; const BUTTONS_Y: f32 = 80.; const STICKS_X: f32 = 150.; const STICKS_Y: f32 = -135.; const NORMAL_BUTTON_COLOR: Color = Color::srgb(0.3, 0.3, 0.3); const ACTIVE_BUTTON_COLOR: Color = Color::srgb(0.5, 0., 0.5); const LIVE_COLOR: Color = Color::srgb(0.4, 0.4, 0.4); const DEAD_COLOR: Color = Color::srgb(0.13, 0.13, 0.13); #[derive(Component, Deref)] struct ReactTo(GamepadButton); #[derive(Component)] struct MoveWithAxes { x_axis: GamepadAxis, y_axis: GamepadAxis, scale: f32, } #[derive(Component)] struct TextWithAxes { x_axis: GamepadAxis, y_axis: GamepadAxis, } #[derive(Component, Deref)] struct TextWithButtonValue(GamepadButton); #[derive(Component)] struct ConnectedGamepadsText; #[derive(Resource)] struct ButtonMaterials { normal: MeshMaterial2d<ColorMaterial>, active: MeshMaterial2d<ColorMaterial>, } impl FromWorld for ButtonMaterials { fn from_world(world: &mut World) -> Self { Self { normal: world.add_asset(NORMAL_BUTTON_COLOR).into(), active: world.add_asset(ACTIVE_BUTTON_COLOR).into(), } } } #[derive(Resource)] struct ButtonMeshes { circle: Mesh2d, triangle: Mesh2d, start_pause: Mesh2d, trigger: Mesh2d, } impl FromWorld for ButtonMeshes { fn from_world(world: &mut World) -> Self { Self { circle: world.add_asset(Circle::new(BUTTON_RADIUS)).into(), triangle: world .add_asset(RegularPolygon::new(BUTTON_RADIUS, 3)) .into(), start_pause: world.add_asset(Rectangle::from_size(START_SIZE)).into(), trigger: world.add_asset(Rectangle::from_size(TRIGGER_SIZE)).into(), } } } #[derive(Bundle)] struct GamepadButtonBundle { mesh: Mesh2d, material: MeshMaterial2d<ColorMaterial>, transform: Transform, react_to: ReactTo, } impl GamepadButtonBundle { pub fn new( button_type: GamepadButton, mesh: Mesh2d, material: MeshMaterial2d<ColorMaterial>, x: f32, y: f32, ) -> Self { Self { mesh, material, transform: Transform::from_xyz(x, y, 0.), react_to: ReactTo(button_type), } } pub fn with_rotation(mut self, angle: f32) -> Self { self.transform.rotation = Quat::from_rotation_z(angle); self } } fn main() { App::new() .add_plugins(DefaultPlugins) .init_resource::<ButtonMaterials>() .init_resource::<ButtonMeshes>() .add_systems( Startup, (setup, setup_sticks, setup_triggers, setup_connected), ) .add_systems( Update, ( update_buttons, update_button_values, update_axes, update_connected, ), ) .run(); } fn setup(mut commands: Commands, meshes: Res<ButtonMeshes>, materials: Res<ButtonMaterials>) { commands.spawn(Camera2d); // Buttons commands.spawn(( Transform::from_xyz(BUTTONS_X, BUTTONS_Y, 0.), Visibility::default(), children![ GamepadButtonBundle::new( GamepadButton::North, meshes.circle.clone(), materials.normal.clone(), 0., BUTTON_CLUSTER_RADIUS, ), GamepadButtonBundle::new( GamepadButton::South, meshes.circle.clone(), materials.normal.clone(), 0., -BUTTON_CLUSTER_RADIUS, ), GamepadButtonBundle::new( GamepadButton::West, meshes.circle.clone(), materials.normal.clone(), -BUTTON_CLUSTER_RADIUS, 0., ), GamepadButtonBundle::new( GamepadButton::East, meshes.circle.clone(), materials.normal.clone(), BUTTON_CLUSTER_RADIUS, 0., ), ], )); // Start and Pause commands.spawn(GamepadButtonBundle::new( GamepadButton::Select, meshes.start_pause.clone(), materials.normal.clone(), -30., BUTTONS_Y, )); commands.spawn(GamepadButtonBundle::new( GamepadButton::Start, meshes.start_pause.clone(), materials.normal.clone(), 30., BUTTONS_Y, )); // D-Pad commands.spawn(( Transform::from_xyz(-BUTTONS_X, BUTTONS_Y, 0.), Visibility::default(), children![ GamepadButtonBundle::new( GamepadButton::DPadUp, meshes.triangle.clone(), materials.normal.clone(), 0., BUTTON_CLUSTER_RADIUS, ), GamepadButtonBundle::new( GamepadButton::DPadDown, meshes.triangle.clone(), materials.normal.clone(), 0., -BUTTON_CLUSTER_RADIUS, ) .with_rotation(PI), GamepadButtonBundle::new( GamepadButton::DPadLeft, meshes.triangle.clone(), materials.normal.clone(), -BUTTON_CLUSTER_RADIUS, 0., ) .with_rotation(PI / 2.), GamepadButtonBundle::new( GamepadButton::DPadRight, meshes.triangle.clone(), materials.normal.clone(), BUTTON_CLUSTER_RADIUS, 0., ) .with_rotation(-PI / 2.), ], )); // Triggers commands.spawn(GamepadButtonBundle::new( GamepadButton::LeftTrigger, meshes.trigger.clone(), materials.normal.clone(), -BUTTONS_X, BUTTONS_Y + 115., )); commands.spawn(GamepadButtonBundle::new( GamepadButton::RightTrigger, meshes.trigger.clone(), materials.normal.clone(), BUTTONS_X, BUTTONS_Y + 115., )); } fn setup_sticks( mut commands: Commands, meshes: Res<ButtonMeshes>, materials: Res<ButtonMaterials>, ) { // NOTE: This stops making sense because in entities because there isn't a "global" default, // instead each gamepad has its own default setting let gamepad_settings = GamepadSettings::default(); let dead_upper = STICK_BOUNDS_SIZE * gamepad_settings.default_axis_settings.deadzone_upperbound(); let dead_lower = STICK_BOUNDS_SIZE * gamepad_settings.default_axis_settings.deadzone_lowerbound(); let dead_size = dead_lower.abs() + dead_upper.abs(); let dead_mid = (dead_lower + dead_upper) / 2.0; let live_upper = STICK_BOUNDS_SIZE * gamepad_settings.default_axis_settings.livezone_upperbound(); let live_lower = STICK_BOUNDS_SIZE * gamepad_settings.default_axis_settings.livezone_lowerbound(); let live_size = live_lower.abs() + live_upper.abs(); let live_mid = (live_lower + live_upper) / 2.0; let mut spawn_stick = |x_pos, y_pos, x_axis, y_axis, button| { let style = TextFont { font_size: 13., ..default() }; commands.spawn(( Transform::from_xyz(x_pos, y_pos, 0.), Visibility::default(), children![ Sprite::from_color(DEAD_COLOR, Vec2::splat(STICK_BOUNDS_SIZE * 2.),), ( Sprite::from_color(LIVE_COLOR, Vec2::splat(live_size)), Transform::from_xyz(live_mid, live_mid, 2.), ), ( Sprite::from_color(DEAD_COLOR, Vec2::splat(dead_size)), Transform::from_xyz(dead_mid, dead_mid, 3.), ), ( Text2d::default(), Transform::from_xyz(0., STICK_BOUNDS_SIZE + 2., 4.), Anchor::BOTTOM_CENTER, TextWithAxes { x_axis, y_axis }, children![ (TextSpan(format!("{:.3}", 0.)), style.clone()), (TextSpan::new(", "), style.clone()), (TextSpan(format!("{:.3}", 0.)), style), ] ), ( meshes.circle.clone(), materials.normal.clone(), Transform::from_xyz(0., 0., 5.).with_scale(Vec2::splat(0.15).extend(1.)), MoveWithAxes { x_axis, y_axis, scale: STICK_BOUNDS_SIZE, }, ReactTo(button), ), ], )); }; spawn_stick( -STICKS_X, STICKS_Y, GamepadAxis::LeftStickX, GamepadAxis::LeftStickY, GamepadButton::LeftThumb, ); spawn_stick( STICKS_X, STICKS_Y, GamepadAxis::RightStickX, GamepadAxis::RightStickY, GamepadButton::RightThumb, ); } fn setup_triggers( mut commands: Commands, meshes: Res<ButtonMeshes>, materials: Res<ButtonMaterials>, ) { let mut spawn_trigger = |x, y, button_type| { commands.spawn(( GamepadButtonBundle::new( button_type, meshes.trigger.clone(), materials.normal.clone(), x, y, ), children![( Transform::from_xyz(0., 0., 1.), Text(format!("{:.3}", 0.)), TextFont { font_size: 13., ..default() }, TextWithButtonValue(button_type), )], )); }; spawn_trigger(-BUTTONS_X, BUTTONS_Y + 145., GamepadButton::LeftTrigger2); spawn_trigger(BUTTONS_X, BUTTONS_Y + 145., GamepadButton::RightTrigger2); } fn setup_connected(mut commands: Commands) { // This is UI text, unlike other text in this example which is 2d. commands.spawn(( Text::new("Connected Gamepads:\n"), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, ConnectedGamepadsText, children![TextSpan::new("None")], )); } fn update_buttons( gamepads: Query<&Gamepad>, materials: Res<ButtonMaterials>, mut query: Query<(&mut MeshMaterial2d<ColorMaterial>, &ReactTo)>, ) { for gamepad in &gamepads { for (mut handle, react_to) in query.iter_mut() { if gamepad.just_pressed(**react_to) { *handle = materials.active.clone(); } if gamepad.just_released(**react_to) { *handle = materials.normal.clone(); } } } } fn update_button_values( mut events: MessageReader<GamepadButtonChangedEvent>, mut query: Query<(&mut Text2d, &TextWithButtonValue)>, ) { for button_event in events.read() { for (mut text, text_with_button_value) in query.iter_mut() { if button_event.button == **text_with_button_value { **text = format!("{:.3}", button_event.value); } } } } fn update_axes( mut axis_events: MessageReader<GamepadAxisChangedEvent>, mut query: Query<(&mut Transform, &MoveWithAxes)>, text_query: Query<(Entity, &TextWithAxes)>, mut writer: Text2dWriter, ) { for axis_event in axis_events.read() { let axis_type = axis_event.axis; let value = axis_event.value; for (mut transform, move_with) in query.iter_mut() { if axis_type == move_with.x_axis { transform.translation.x = value * move_with.scale; } if axis_type == move_with.y_axis { transform.translation.y = value * move_with.scale; } } for (text, text_with_axes) in text_query.iter() { if axis_type == text_with_axes.x_axis { *writer.text(text, 1) = format!("{value:.3}"); } if axis_type == text_with_axes.y_axis { *writer.text(text, 3) = format!("{value:.3}"); } } } } fn update_connected( mut connected: MessageReader<GamepadConnectionEvent>, gamepads: Query<(Entity, &Name), With<Gamepad>>, text: Single<Entity, With<ConnectedGamepadsText>>, mut writer: TextUiWriter, ) { if connected.is_empty() { return; } connected.clear(); let formatted = gamepads .iter() .map(|(entity, name)| format!("{entity} - {name}")) .collect::<Vec<_>>() .join("\n"); *writer.text(*text, 1) = if !formatted.is_empty() { formatted } else { "None".to_string() } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/tools/scene_viewer/scene_viewer_plugin.rs
examples/tools/scene_viewer/scene_viewer_plugin.rs
//! A glTF scene viewer plugin. Provides controls for directional lighting, and switching between scene cameras. //! To use in your own application: //! - Copy the code for the `SceneViewerPlugin` and add the plugin to your App. //! - Insert an initialized `SceneHandle` resource into your App's `AssetServer`. use bevy::{ camera_controller::free_camera::FreeCamera, gltf::Gltf, input::common_conditions::input_just_pressed, prelude::*, scene::InstanceId, }; use std::{f32::consts::*, fmt}; #[derive(Resource)] pub struct SceneHandle { pub gltf_handle: Handle<Gltf>, scene_index: usize, instance_id: Option<InstanceId>, pub is_loaded: bool, pub has_light: bool, } impl SceneHandle { pub fn new(gltf_handle: Handle<Gltf>, scene_index: usize) -> Self { Self { gltf_handle, scene_index, instance_id: None, is_loaded: false, has_light: false, } } } #[cfg(not(feature = "gltf_animation"))] const INSTRUCTIONS: &str = r#" Scene Controls: L - animate light direction U - toggle shadows C - cycle through the camera controller and any cameras loaded from the scene compile with "--features animation" for animation controls. "#; #[cfg(feature = "gltf_animation")] const INSTRUCTIONS: &str = " Scene Controls: L - animate light direction U - toggle shadows B - toggle bounding boxes C - cycle through the camera controller and any cameras loaded from the scene Space - Play/Pause animation Enter - Cycle through animations "; impl fmt::Display for SceneHandle { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{INSTRUCTIONS}") } } pub struct SceneViewerPlugin; impl Plugin for SceneViewerPlugin { fn build(&self, app: &mut App) { app.init_resource::<CameraTracker>() .add_systems(PreUpdate, scene_load_check) .add_systems( Update, ( update_lights, camera_tracker, toggle_bounding_boxes.run_if(input_just_pressed(KeyCode::KeyB)), ), ); } } fn toggle_bounding_boxes(mut config: ResMut<GizmoConfigStore>) { config.config_mut::<AabbGizmoConfigGroup>().1.draw_all ^= true; } fn scene_load_check( asset_server: Res<AssetServer>, mut scenes: ResMut<Assets<Scene>>, gltf_assets: Res<Assets<Gltf>>, mut scene_handle: ResMut<SceneHandle>, mut scene_spawner: ResMut<SceneSpawner>, ) { match scene_handle.instance_id { None => { if asset_server .load_state(&scene_handle.gltf_handle) .is_loaded() { let gltf = gltf_assets.get(&scene_handle.gltf_handle).unwrap(); if gltf.scenes.len() > 1 { info!( "Displaying scene {} out of {}", scene_handle.scene_index, gltf.scenes.len() ); info!("You can select the scene by adding '#Scene' followed by a number to the end of the file path (e.g '#Scene1' to load the second scene)."); } let gltf_scene_handle = gltf.scenes .get(scene_handle.scene_index) .unwrap_or_else(|| { panic!( "glTF file doesn't contain scene {}!", scene_handle.scene_index ) }); let scene = scenes.get_mut(gltf_scene_handle).unwrap(); let mut query = scene .world .query::<(Option<&DirectionalLight>, Option<&PointLight>)>(); scene_handle.has_light = query .iter(&scene.world) .any(|(maybe_directional_light, maybe_point_light)| { maybe_directional_light.is_some() || maybe_point_light.is_some() }); scene_handle.instance_id = Some(scene_spawner.spawn(gltf_scene_handle.clone())); info!("Spawning scene..."); } } Some(instance_id) if !scene_handle.is_loaded => { if scene_spawner.instance_is_ready(instance_id) { info!("...done!"); scene_handle.is_loaded = true; } } Some(_) => {} } } fn update_lights( key_input: Res<ButtonInput<KeyCode>>, time: Res<Time>, mut query: Query<(&mut Transform, &mut DirectionalLight)>, mut animate_directional_light: Local<bool>, ) { for (_, mut light) in &mut query { if key_input.just_pressed(KeyCode::KeyU) { light.shadows_enabled = !light.shadows_enabled; } } if key_input.just_pressed(KeyCode::KeyL) { *animate_directional_light = !*animate_directional_light; } if *animate_directional_light { for (mut transform, _) in &mut query { transform.rotation = Quat::from_euler( EulerRot::ZYX, 0.0, time.elapsed_secs() * PI / 15.0, -FRAC_PI_4, ); } } } #[derive(Resource, Default)] struct CameraTracker { active_index: Option<usize>, cameras: Vec<Entity>, } impl CameraTracker { fn track_camera(&mut self, entity: Entity) -> bool { self.cameras.push(entity); if self.active_index.is_none() { self.active_index = Some(self.cameras.len() - 1); true } else { false } } fn active_camera(&self) -> Option<Entity> { self.active_index.map(|i| self.cameras[i]) } fn set_next_active(&mut self) -> Option<Entity> { let active_index = self.active_index?; let new_i = (active_index + 1) % self.cameras.len(); self.active_index = Some(new_i); Some(self.cameras[new_i]) } } fn camera_tracker( mut camera_tracker: ResMut<CameraTracker>, keyboard_input: Res<ButtonInput<KeyCode>>, mut queries: ParamSet<( Query<(Entity, &mut Camera), (Added<Camera>, Without<FreeCamera>)>, Query<(Entity, &mut Camera), (Added<Camera>, With<FreeCamera>)>, Query<&mut Camera>, )>, ) { // track added scene camera entities first, to ensure they are preferred for the // default active camera for (entity, mut camera) in queries.p0().iter_mut() { camera.is_active = camera_tracker.track_camera(entity); } // iterate added custom camera entities second for (entity, mut camera) in queries.p1().iter_mut() { camera.is_active = camera_tracker.track_camera(entity); } if keyboard_input.just_pressed(KeyCode::KeyC) { // disable currently active camera if let Some(e) = camera_tracker.active_camera() && let Ok(mut camera) = queries.p2().get_mut(e) { camera.is_active = false; } // enable next active camera if let Some(e) = camera_tracker.set_next_active() && let Ok(mut camera) = queries.p2().get_mut(e) { camera.is_active = true; } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/tools/scene_viewer/morph_viewer_plugin.rs
examples/tools/scene_viewer/morph_viewer_plugin.rs
//! Enable controls for morph targets detected in a loaded scene. //! //! Collect morph targets and assign keys to them, //! shows on screen additional controls for morph targets. //! //! Illustrates how to access and modify individual morph target weights. //! See the [`update_morphs`] system for details. //! //! Also illustrates how to read morph target names in [`detect_morphs`]. use crate::scene_viewer_plugin::SceneHandle; use bevy::prelude::*; use std::fmt; const FONT_SIZE: f32 = 13.0; const WEIGHT_PER_SECOND: f32 = 0.8; const ALL_MODIFIERS: &[KeyCode] = &[KeyCode::ShiftLeft, KeyCode::ControlLeft, KeyCode::AltLeft]; const AVAILABLE_KEYS: [MorphKey; 56] = [ MorphKey::new("r", &[], KeyCode::KeyR), MorphKey::new("t", &[], KeyCode::KeyT), MorphKey::new("z", &[], KeyCode::KeyZ), MorphKey::new("i", &[], KeyCode::KeyI), MorphKey::new("o", &[], KeyCode::KeyO), MorphKey::new("p", &[], KeyCode::KeyP), MorphKey::new("f", &[], KeyCode::KeyF), MorphKey::new("g", &[], KeyCode::KeyG), MorphKey::new("h", &[], KeyCode::KeyH), MorphKey::new("j", &[], KeyCode::KeyJ), MorphKey::new("k", &[], KeyCode::KeyK), MorphKey::new("y", &[], KeyCode::KeyY), MorphKey::new("x", &[], KeyCode::KeyX), MorphKey::new("c", &[], KeyCode::KeyC), MorphKey::new("v", &[], KeyCode::KeyV), MorphKey::new("b", &[], KeyCode::KeyB), MorphKey::new("n", &[], KeyCode::KeyN), MorphKey::new("m", &[], KeyCode::KeyM), MorphKey::new("0", &[], KeyCode::Digit0), MorphKey::new("1", &[], KeyCode::Digit1), MorphKey::new("2", &[], KeyCode::Digit2), MorphKey::new("3", &[], KeyCode::Digit3), MorphKey::new("4", &[], KeyCode::Digit4), MorphKey::new("5", &[], KeyCode::Digit5), MorphKey::new("6", &[], KeyCode::Digit6), MorphKey::new("7", &[], KeyCode::Digit7), MorphKey::new("8", &[], KeyCode::Digit8), MorphKey::new("9", &[], KeyCode::Digit9), MorphKey::new("lshift-R", &[KeyCode::ShiftLeft], KeyCode::KeyR), MorphKey::new("lshift-T", &[KeyCode::ShiftLeft], KeyCode::KeyT), MorphKey::new("lshift-Z", &[KeyCode::ShiftLeft], KeyCode::KeyZ), MorphKey::new("lshift-I", &[KeyCode::ShiftLeft], KeyCode::KeyI), MorphKey::new("lshift-O", &[KeyCode::ShiftLeft], KeyCode::KeyO), MorphKey::new("lshift-P", &[KeyCode::ShiftLeft], KeyCode::KeyP), MorphKey::new("lshift-F", &[KeyCode::ShiftLeft], KeyCode::KeyF), MorphKey::new("lshift-G", &[KeyCode::ShiftLeft], KeyCode::KeyG), MorphKey::new("lshift-H", &[KeyCode::ShiftLeft], KeyCode::KeyH), MorphKey::new("lshift-J", &[KeyCode::ShiftLeft], KeyCode::KeyJ), MorphKey::new("lshift-K", &[KeyCode::ShiftLeft], KeyCode::KeyK), MorphKey::new("lshift-Y", &[KeyCode::ShiftLeft], KeyCode::KeyY), MorphKey::new("lshift-X", &[KeyCode::ShiftLeft], KeyCode::KeyX), MorphKey::new("lshift-C", &[KeyCode::ShiftLeft], KeyCode::KeyC), MorphKey::new("lshift-V", &[KeyCode::ShiftLeft], KeyCode::KeyV), MorphKey::new("lshift-B", &[KeyCode::ShiftLeft], KeyCode::KeyB), MorphKey::new("lshift-N", &[KeyCode::ShiftLeft], KeyCode::KeyN), MorphKey::new("lshift-M", &[KeyCode::ShiftLeft], KeyCode::KeyM), MorphKey::new("lshift-0", &[KeyCode::ShiftLeft], KeyCode::Digit0), MorphKey::new("lshift-1", &[KeyCode::ShiftLeft], KeyCode::Digit1), MorphKey::new("lshift-2", &[KeyCode::ShiftLeft], KeyCode::Digit2), MorphKey::new("lshift-3", &[KeyCode::ShiftLeft], KeyCode::Digit3), MorphKey::new("lshift-4", &[KeyCode::ShiftLeft], KeyCode::Digit4), MorphKey::new("lshift-5", &[KeyCode::ShiftLeft], KeyCode::Digit5), MorphKey::new("lshift-6", &[KeyCode::ShiftLeft], KeyCode::Digit6), MorphKey::new("lshift-7", &[KeyCode::ShiftLeft], KeyCode::Digit7), MorphKey::new("lshift-8", &[KeyCode::ShiftLeft], KeyCode::Digit8), MorphKey::new("lshift-9", &[KeyCode::ShiftLeft], KeyCode::Digit9), ]; #[derive(Clone, Copy)] enum WeightChange { Increase, Decrease, } impl WeightChange { fn reverse(&mut self) { *self = match *self { WeightChange::Increase => WeightChange::Decrease, WeightChange::Decrease => WeightChange::Increase, } } fn sign(self) -> f32 { match self { WeightChange::Increase => 1.0, WeightChange::Decrease => -1.0, } } fn change_weight(&mut self, weight: f32, change: f32) -> f32 { let mut change = change * self.sign(); let new_weight = weight + change; if new_weight <= 0.0 || new_weight >= 1.0 { self.reverse(); change = -change; } weight + change } } struct Target { entity_name: Option<String>, entity: Entity, name: Option<String>, index: usize, weight: f32, change_dir: WeightChange, } impl fmt::Display for Target { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match (self.name.as_ref(), self.entity_name.as_ref()) { (None, None) => write!(f, "animation{} of {}", self.index, self.entity), (None, Some(entity)) => write!(f, "animation{} of {entity}", self.index), (Some(target), None) => write!(f, "{target} of {}", self.entity), (Some(target), Some(entity)) => write!(f, "{target} of {entity}"), }?; write!(f, ": {}", self.weight) } } impl Target { fn text_span(&self, key: &str, style: TextFont) -> (TextSpan, TextFont) { (TextSpan::new(format!("[{key}] {self}\n")), style) } fn new( entity_name: Option<&Name>, weights: &[f32], target_names: Option<&[String]>, entity: Entity, ) -> Vec<Target> { let get_name = |i| target_names.and_then(|names| names.get(i)); let entity_name = entity_name.map(Name::as_str); weights .iter() .enumerate() .map(|(index, weight)| Target { entity_name: entity_name.map(ToOwned::to_owned), entity, name: get_name(index).cloned(), index, weight: *weight, change_dir: WeightChange::Increase, }) .collect() } } #[derive(Resource)] struct WeightsControl { weights: Vec<Target>, } struct MorphKey { name: &'static str, modifiers: &'static [KeyCode], key: KeyCode, } impl MorphKey { const fn new(name: &'static str, modifiers: &'static [KeyCode], key: KeyCode) -> Self { MorphKey { name, modifiers, key, } } fn active(&self, inputs: &ButtonInput<KeyCode>) -> bool { let mut modifier = self.modifiers.iter(); let mut non_modifier = ALL_MODIFIERS.iter().filter(|m| !self.modifiers.contains(m)); let key = inputs.pressed(self.key); let modifier = modifier.all(|m| inputs.pressed(*m)); let non_modifier = non_modifier.all(|m| !inputs.pressed(*m)); key && modifier && non_modifier } } fn update_text( controls: Option<ResMut<WeightsControl>>, texts: Query<Entity, With<Text>>, morphs: Query<&MorphWeights>, mut writer: TextUiWriter, ) { let Some(mut controls) = controls else { return; }; let Ok(text) = texts.single() else { return; }; for (i, target) in controls.weights.iter_mut().enumerate() { let Ok(weights) = morphs.get(target.entity) else { continue; }; let Some(&actual_weight) = weights.weights().get(target.index) else { continue; }; if actual_weight != target.weight { target.weight = actual_weight; } let key_name = &AVAILABLE_KEYS[i].name; *writer.text(text, i + 3) = format!("[{key_name}] {target}\n"); } } fn update_morphs( controls: Option<ResMut<WeightsControl>>, mut morphs: Query<&mut MorphWeights>, input: Res<ButtonInput<KeyCode>>, time: Res<Time>, ) { let Some(mut controls) = controls else { return; }; for (i, target) in controls.weights.iter_mut().enumerate() { if !AVAILABLE_KEYS[i].active(&input) { continue; } let Ok(mut weights) = morphs.get_mut(target.entity) else { continue; }; // To update individual morph target weights, get the `MorphWeights` // component and call `weights_mut` to get access to the weights. let weights_slice = weights.weights_mut(); let i = target.index; let change = time.delta_secs() * WEIGHT_PER_SECOND; let new_weight = target.change_dir.change_weight(weights_slice[i], change); weights_slice[i] = new_weight; target.weight = new_weight; } } fn detect_morphs( mut commands: Commands, morphs: Query<(Entity, &MorphWeights, Option<&Name>)>, meshes: Res<Assets<Mesh>>, scene_handle: Res<SceneHandle>, mut setup: Local<bool>, ) { let no_morphing = morphs.iter().len() == 0; if no_morphing { return; } if scene_handle.is_loaded && !*setup { *setup = true; } else { return; } let mut detected = Vec::new(); for (entity, weights, name) in &morphs { let target_names = weights .first_mesh() .and_then(|h| meshes.get(h)) .and_then(|m| m.morph_target_names()); let targets = Target::new(name, weights.weights(), target_names, entity); detected.extend(targets); } detected.truncate(AVAILABLE_KEYS.len()); let style = TextFont { font_size: FONT_SIZE, ..default() }; let mut spans = vec![ (TextSpan::new("Morph Target Controls\n"), style.clone()), (TextSpan::new("---------------\n"), style.clone()), ]; let target_to_text = |(i, target): (usize, &Target)| target.text_span(AVAILABLE_KEYS[i].name, style.clone()); spans.extend(detected.iter().enumerate().map(target_to_text)); commands.insert_resource(WeightsControl { weights: detected }); commands.spawn(( Text::default(), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, Children::spawn(spans), )); } pub struct MorphViewerPlugin; impl Plugin for MorphViewerPlugin { fn build(&self, app: &mut App) { app.add_systems( Update, ( update_morphs, detect_morphs, update_text.after(update_morphs), ), ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/tools/scene_viewer/main.rs
examples/tools/scene_viewer/main.rs
//! A simple glTF scene viewer made with Bevy. //! //! Just run `cargo run --release --example scene_viewer /path/to/model.gltf`, //! replacing the path as appropriate. //! In case of multiple scenes, you can select which to display by adapting the file path: `/path/to/model.gltf#Scene1`. //! With no arguments it will load the `FlightHelmet` glTF model from the repository assets subdirectory. //! Pass `--help` to see all the supported arguments. //! //! If you want to hot reload asset changes, enable the `file_watcher` cargo feature. use argh::FromArgs; use bevy::{ asset::UnapprovedPathMode, camera::primitives::{Aabb, Sphere}, camera_controller::free_camera::{FreeCamera, FreeCameraPlugin}, core_pipeline::prepass::{DeferredPrepass, DepthPrepass}, gltf::{convert_coordinates::GltfConvertCoordinates, GltfPlugin}, pbr::DefaultOpaqueRendererMethod, prelude::*, render::experimental::occlusion_culling::OcclusionCulling, }; #[cfg(feature = "gltf_animation")] mod animation_plugin; mod morph_viewer_plugin; mod scene_viewer_plugin; use morph_viewer_plugin::MorphViewerPlugin; use scene_viewer_plugin::{SceneHandle, SceneViewerPlugin}; /// A simple glTF scene viewer made with Bevy #[derive(FromArgs, Resource)] struct Args { /// the path to the glTF scene #[argh( positional, default = "\"assets/models/FlightHelmet/FlightHelmet.gltf\".to_string()" )] scene_path: String, /// enable a depth prepass #[argh(switch)] depth_prepass: Option<bool>, /// enable occlusion culling #[argh(switch)] occlusion_culling: Option<bool>, /// enable deferred shading #[argh(switch)] deferred: Option<bool>, /// spawn a light even if the scene already has one #[argh(switch)] add_light: Option<bool>, /// enable `GltfPlugin::convert_coordinates::scenes` #[argh(switch)] convert_scene_coordinates: Option<bool>, /// enable `GltfPlugin::convert_coordinates::meshes` #[argh(switch)] convert_mesh_coordinates: Option<bool>, } impl Args { fn rotation(&self) -> Quat { if self.convert_scene_coordinates == Some(true) { // If the scene is converted then rotate everything else to match. This // makes comparisons easier - the scene will always face the same way // relative to the cameras and lights. Quat::from_xyzw(0.0, 1.0, 0.0, 0.0) } else { Quat::IDENTITY } } } fn main() { #[cfg(not(target_arch = "wasm32"))] let args: Args = argh::from_env(); #[cfg(target_arch = "wasm32")] let args: Args = Args::from_args(&[], &[]).unwrap(); let deferred = args.deferred; let mut app = App::new(); app.add_plugins(( DefaultPlugins .set(WindowPlugin { primary_window: Some(Window { title: "bevy scene viewer".to_string(), ..default() }), ..default() }) .set(AssetPlugin { file_path: std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string()), // Allow scenes to be loaded from anywhere on disk unapproved_path_mode: UnapprovedPathMode::Allow, ..default() }) .set(GltfPlugin { convert_coordinates: GltfConvertCoordinates { rotate_scene_entity: args.convert_scene_coordinates == Some(true), rotate_meshes: args.convert_mesh_coordinates == Some(true), }, ..default() }), FreeCameraPlugin, SceneViewerPlugin, MorphViewerPlugin, )) .insert_resource(args) .add_systems(Startup, setup) .add_systems(PreUpdate, setup_scene_after_load); // If deferred shading was requested, turn it on. if deferred == Some(true) { app.insert_resource(DefaultOpaqueRendererMethod::deferred()); } #[cfg(feature = "gltf_animation")] app.add_plugins(animation_plugin::AnimationManipulationPlugin); app.run(); } fn parse_scene(scene_path: String) -> (String, usize) { if scene_path.contains('#') { let gltf_and_scene = scene_path.split('#').collect::<Vec<_>>(); if let Some((last, path)) = gltf_and_scene.split_last() && let Some(index) = last .strip_prefix("Scene") .and_then(|index| index.parse::<usize>().ok()) { return (path.join("#"), index); } } (scene_path, 0) } fn setup(mut commands: Commands, asset_server: Res<AssetServer>, args: Res<Args>) { let scene_path = &args.scene_path; info!("Loading {}", scene_path); let (file_path, scene_index) = parse_scene((*scene_path).clone()); commands.insert_resource(SceneHandle::new(asset_server.load(file_path), scene_index)); } fn setup_scene_after_load( mut commands: Commands, mut setup: Local<bool>, mut scene_handle: ResMut<SceneHandle>, asset_server: Res<AssetServer>, args: Res<Args>, meshes: Query<(&GlobalTransform, Option<&Aabb>), With<Mesh3d>>, ) { if scene_handle.is_loaded && !*setup { *setup = true; // Find an approximate bounding box of the scene from its meshes if meshes.iter().any(|(_, maybe_aabb)| maybe_aabb.is_none()) { return; } let mut min = Vec3A::splat(f32::MAX); let mut max = Vec3A::splat(f32::MIN); for (transform, maybe_aabb) in &meshes { let aabb = maybe_aabb.unwrap(); // If the Aabb had not been rotated, applying the non-uniform scale would produce the // correct bounds. However, it could very well be rotated and so we first convert to // a Sphere, and then back to an Aabb to find the conservative min and max points. let sphere = Sphere { center: Vec3A::from(transform.transform_point(Vec3::from(aabb.center))), radius: transform.radius_vec3a(aabb.half_extents), }; let aabb = Aabb::from(sphere); min = min.min(aabb.min()); max = max.max(aabb.max()); } let size = (max - min).length(); let aabb = Aabb::from_min_max(Vec3::from(min), Vec3::from(max)); info!("Spawning a controllable 3D perspective camera"); let mut projection = PerspectiveProjection::default(); projection.far = projection.far.max(size * 10.0); let walk_speed = size * 3.0; let camera_controller = FreeCamera { walk_speed, run_speed: 3.0 * walk_speed, ..default() }; // Display the controls of the scene viewer info!("{}", camera_controller); info!("{}", *scene_handle); let mut camera = commands.spawn(( Camera3d::default(), Projection::from(projection), Transform::from_translation( Vec3::from(aabb.center) + size * (args.rotation() * Vec3::new(0.5, 0.25, 0.5)), ) .looking_at(Vec3::from(aabb.center), Vec3::Y), Camera { is_active: false, ..default() }, EnvironmentMapLight { diffuse_map: asset_server .load("assets/environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"), specular_map: asset_server .load("assets/environment_maps/pisa_specular_rgb9e5_zstd.ktx2"), intensity: 150.0, rotation: args.rotation(), ..default() }, camera_controller, )); // If occlusion culling was requested, include the relevant components. // The Z-prepass is currently required. if args.occlusion_culling == Some(true) { camera.insert((DepthPrepass, OcclusionCulling)); } // If the depth prepass was requested, include it. if args.depth_prepass == Some(true) { camera.insert(DepthPrepass); } // If deferred shading was requested, include the prepass. if args.deferred == Some(true) { camera .insert(Msaa::Off) .insert(DepthPrepass) .insert(DeferredPrepass); } // Spawn a default light if the scene does not have one if !scene_handle.has_light || args.add_light == Some(true) { info!("Spawning a directional light"); let mut light = commands.spawn(( DirectionalLight::default(), Transform::from_translation(args.rotation() * Vec3::new(1.0, 1.0, 0.0)) .looking_at(Vec3::ZERO, Vec3::Y), )); if args.occlusion_culling == Some(true) { light.insert(OcclusionCulling); } scene_handle.has_light = true; } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/tools/scene_viewer/animation_plugin.rs
examples/tools/scene_viewer/animation_plugin.rs
//! Control animations of entities in the loaded scene. use std::collections::HashMap; use bevy::{animation::AnimationTargetId, ecs::entity::EntityHashMap, gltf::Gltf, prelude::*}; use crate::scene_viewer_plugin::SceneHandle; /// Controls animation clips for a unique entity. #[derive(Component)] struct Clips { nodes: Vec<AnimationNodeIndex>, current: usize, } impl Clips { fn new(clips: Vec<AnimationNodeIndex>) -> Self { Clips { nodes: clips, current: 0, } } /// # Panics /// /// When no clips are present. fn current(&self) -> AnimationNodeIndex { self.nodes[self.current] } fn advance_to_next(&mut self) { self.current = (self.current + 1) % self.nodes.len(); } } /// Automatically assign [`AnimationClip`]s to [`AnimationPlayer`] and play /// them, if the clips refer to descendants of the animation player (which is /// the common case). fn assign_clips( mut players: Query<&mut AnimationPlayer>, targets: Query<(&AnimationTargetId, Entity)>, children: Query<&ChildOf>, scene_handle: Res<SceneHandle>, clips: Res<Assets<AnimationClip>>, gltf_assets: Res<Assets<Gltf>>, assets: Res<AssetServer>, mut graphs: ResMut<Assets<AnimationGraph>>, mut commands: Commands, mut setup: Local<bool>, ) { if scene_handle.is_loaded && !*setup { *setup = true; } else { return; } let gltf = gltf_assets.get(&scene_handle.gltf_handle).unwrap(); let animations = &gltf.animations; if animations.is_empty() { return; } let count = animations.len(); let plural = if count == 1 { "" } else { "s" }; info!("Found {} animation{plural}", animations.len()); let names: Vec<_> = gltf.named_animations.keys().collect(); info!("Animation names: {names:?}"); // Map animation target IDs to entities. let animation_target_id_to_entity: HashMap<_, _> = targets.iter().collect(); // Build up a list of all animation clips that belong to each player. A clip // is considered to belong to an animation player if all targets of the clip // refer to entities whose nearest ancestor player is that animation player. let mut player_to_graph: EntityHashMap<(AnimationGraph, Vec<AnimationNodeIndex>)> = EntityHashMap::default(); for (clip_id, clip) in clips.iter() { let mut ancestor_player = None; for target_id in clip.curves().keys() { // If the animation clip refers to entities that aren't present in // the scene, bail. let Some(&target) = animation_target_id_to_entity.get(target_id) else { continue; }; // Find the nearest ancestor animation player. let mut current = Some(target); while let Some(entity) = current { if players.contains(entity) { match ancestor_player { None => { // If we haven't found a player yet, record the one // we found. ancestor_player = Some(entity); } Some(ancestor) => { // If we have found a player, then make sure it's // the same player we located before. if ancestor != entity { // It's a different player. Bail. ancestor_player = None; break; } } } } // Go to the next parent. current = children.get(entity).ok().map(ChildOf::parent); } } let Some(ancestor_player) = ancestor_player else { warn!( "Unexpected animation hierarchy for animation clip {}; ignoring.", clip_id ); continue; }; let Some(clip_handle) = assets.get_id_handle(clip_id) else { warn!("Clip {} wasn't loaded.", clip_id); continue; }; let &mut (ref mut graph, ref mut clip_indices) = player_to_graph.entry(ancestor_player).or_default(); let node_index = graph.add_clip(clip_handle, 1.0, graph.root); clip_indices.push(node_index); } // Now that we've built up a list of all clips that belong to each player, // package them up into a `Clips` component, play the first such animation, // and add that component to the player. for (player_entity, (graph, clips)) in player_to_graph { let Ok(mut player) = players.get_mut(player_entity) else { warn!("Animation targets referenced a nonexistent player. This shouldn't happen."); continue; }; let graph = graphs.add(graph); let animations = Clips::new(clips); player.play(animations.current()).repeat(); commands .entity(player_entity) .insert(animations) .insert(AnimationGraphHandle(graph)); } } fn handle_inputs( keyboard_input: Res<ButtonInput<KeyCode>>, mut animation_player: Query<(&mut AnimationPlayer, &mut Clips, Entity, Option<&Name>)>, ) { for (mut player, mut clips, entity, name) in &mut animation_player { let display_entity_name = match name { Some(name) => name.to_string(), None => format!("entity {entity}"), }; if keyboard_input.just_pressed(KeyCode::Space) { if player.all_paused() { info!("resuming animations for {display_entity_name}"); player.resume_all(); } else { info!("pausing animation for {display_entity_name}"); player.pause_all(); } } if clips.nodes.len() <= 1 { continue; } if keyboard_input.just_pressed(KeyCode::Enter) { info!("switching to new animation for {display_entity_name}"); let paused = player.all_paused(); player.stop_all(); clips.advance_to_next(); let current_clip = clips.current(); player.play(current_clip).repeat(); if paused { player.pause_all(); } } } } pub struct AnimationManipulationPlugin; impl Plugin for AnimationManipulationPlugin { fn build(&self, app: &mut App) { app.add_systems(Update, (handle_inputs, assign_clips)); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/stress_tests/many_gradients.rs
examples/stress_tests/many_gradients.rs
//! Stress test demonstrating gradient performance improvements. //! //! This example creates many UI nodes with gradients to measure the performance //! impact of pre-converting colors to the target color space on the CPU. use argh::FromArgs; use bevy::{ color::palettes::css::*, diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, math::ops::sin, prelude::*, ui::{ BackgroundGradient, ColorStop, Display, Gradient, InterpolationColorSpace, LinearGradient, RepeatedGridTrack, }, window::{PresentMode, WindowResolution}, winit::{UpdateMode, WinitSettings}, }; const COLS: usize = 30; #[derive(FromArgs, Resource, Debug)] /// Gradient stress test struct Args { /// how many gradients per group (default: 900) #[argh(option, default = "900")] gradient_count: usize, /// whether to animate gradients by changing colors #[argh(switch)] animate: bool, /// use sRGB interpolation #[argh(switch)] srgb: bool, /// use HSL interpolation #[argh(switch)] hsl: bool, } fn main() { let args: Args = argh::from_env(); let total_gradients = args.gradient_count; println!("Gradient stress test with {total_gradients} gradients"); println!( "Color space: {}", if args.srgb { "sRGB" } else if args.hsl { "HSL" } else { "OkLab (default)" } ); App::new() .add_plugins(( LogDiagnosticsPlugin::default(), FrameTimeDiagnosticsPlugin::default(), DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "Gradient Stress Test".to_string(), resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0), present_mode: PresentMode::AutoNoVsync, ..default() }), ..default() }), )) .insert_resource(WinitSettings { focused_mode: UpdateMode::Continuous, unfocused_mode: UpdateMode::Continuous, }) .insert_resource(args) .insert_resource(WinitSettings::continuous()) .add_systems(Startup, setup) .add_systems(Update, animate_gradients) .run(); } fn setup(mut commands: Commands, args: Res<Args>) { commands.spawn(Camera2d); let rows_to_spawn = args.gradient_count.div_ceil(COLS); // Create a grid of gradients commands .spawn(Node { width: percent(100), height: percent(100), display: Display::Grid, grid_template_columns: RepeatedGridTrack::flex(COLS as u16, 1.0), grid_template_rows: RepeatedGridTrack::flex(rows_to_spawn as u16, 1.0), ..default() }) .with_children(|parent| { for i in 0..args.gradient_count { let angle = (i as f32 * 10.0) % 360.0; let mut gradient = LinearGradient::new( angle, vec![ ColorStop::new(RED, percent(0)), ColorStop::new(BLUE, percent(100)), ColorStop::new(GREEN, percent(20)), ColorStop::new(YELLOW, percent(40)), ColorStop::new(ORANGE, percent(60)), ColorStop::new(LIME, percent(80)), ColorStop::new(DARK_CYAN, percent(90)), ], ); gradient.color_space = if args.srgb { InterpolationColorSpace::Srgba } else if args.hsl { InterpolationColorSpace::Hsla } else { InterpolationColorSpace::Oklaba }; parent.spawn(( Node { width: percent(100), height: percent(100), ..default() }, BackgroundGradient(vec![Gradient::Linear(gradient)]), GradientNode { index: i }, )); } }); } #[derive(Component)] struct GradientNode { index: usize, } fn animate_gradients( mut gradients: Query<(&mut BackgroundGradient, &GradientNode)>, args: Res<Args>, time: Res<Time>, ) { if !args.animate { return; } let t = time.elapsed_secs(); for (mut bg_gradient, node) in &mut gradients { let offset = node.index as f32 * 0.01; let hue_shift = sin(t + offset) * 0.5 + 0.5; if let Some(Gradient::Linear(gradient)) = bg_gradient.0.get_mut(0) { let color1 = Color::hsl(hue_shift * 360.0, 1.0, 0.5); let color2 = Color::hsl((hue_shift + 0.3) * 360.0 % 360.0, 1.0, 0.5); gradient.stops = vec![ ColorStop::new(color1, percent(0)), ColorStop::new(color2, percent(100)), ColorStop::new( Color::hsl((hue_shift + 0.1) * 360.0 % 360.0, 1.0, 0.5), percent(20), ), ColorStop::new( Color::hsl((hue_shift + 0.15) * 360.0 % 360.0, 1.0, 0.5), percent(40), ), ColorStop::new( Color::hsl((hue_shift + 0.2) * 360.0 % 360.0, 1.0, 0.5), percent(60), ), ColorStop::new( Color::hsl((hue_shift + 0.25) * 360.0 % 360.0, 1.0, 0.5), percent(80), ), ColorStop::new( Color::hsl((hue_shift + 0.28) * 360.0 % 360.0, 1.0, 0.5), percent(90), ), ]; } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/stress_tests/many_gizmos.rs
examples/stress_tests/many_gizmos.rs
//! Test rendering of many gizmos. use std::f32::consts::TAU; use bevy::{ diagnostic::{Diagnostic, DiagnosticsStore, FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, prelude::*, window::{PresentMode, WindowResolution}, winit::WinitSettings, }; const SYSTEM_COUNT: u32 = 10; fn main() { let mut app = App::new(); app.add_plugins(( DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "Many Debug Lines".to_string(), present_mode: PresentMode::AutoNoVsync, resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0), ..default() }), ..default() }), FrameTimeDiagnosticsPlugin::default(), LogDiagnosticsPlugin::default(), )) .insert_resource(WinitSettings::continuous()) .insert_resource(Config { line_count: 50_000, fancy: false, }) .add_systems(Startup, setup) .add_systems(Update, (input, ui_system)); for _ in 0..SYSTEM_COUNT { app.add_systems(Update, system); } app.run(); } #[derive(Resource, Debug)] struct Config { line_count: u32, fancy: bool, } fn input(mut config: ResMut<Config>, input: Res<ButtonInput<KeyCode>>) { if input.just_pressed(KeyCode::ArrowUp) { config.line_count += 10_000; } if input.just_pressed(KeyCode::ArrowDown) { config.line_count = config.line_count.saturating_sub(10_000); } if input.just_pressed(KeyCode::Space) { config.fancy = !config.fancy; } } fn system(config: Res<Config>, time: Res<Time>, mut draw: Gizmos) { if !config.fancy { for _ in 0..(config.line_count / SYSTEM_COUNT) { draw.line(Vec3::NEG_Y, Vec3::Y, Color::BLACK); } } else { for i in 0..(config.line_count / SYSTEM_COUNT) { let angle = i as f32 / (config.line_count / SYSTEM_COUNT) as f32 * TAU; let vector = Vec2::from(ops::sin_cos(angle)).extend(ops::sin(time.elapsed_secs())); let start_color = LinearRgba::rgb(vector.x, vector.z, 0.5); let end_color = LinearRgba::rgb(-vector.z, -vector.y, 0.5); draw.line_gradient(vector, -vector, start_color, end_color); } } } fn setup(mut commands: Commands) { warn!(include_str!("warning_string.txt")); commands.spawn(( Camera3d::default(), Transform::from_xyz(3., 1., 5.).looking_at(Vec3::ZERO, Vec3::Y), )); commands.spawn(( Text::default(), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, )); } fn ui_system(mut text: Single<&mut Text>, config: Res<Config>, diag: Res<DiagnosticsStore>) { let Some(fps) = diag .get(&FrameTimeDiagnosticsPlugin::FPS) .and_then(Diagnostic::smoothed) else { return; }; text.0 = format!( "Line count: {}\n\ FPS: {:.0}\n\n\ Controls:\n\ Up/Down: Raise or lower the line count.\n\ Spacebar: Toggle fancy mode.", config.line_count, fps, ); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/stress_tests/transform_hierarchy.rs
examples/stress_tests/transform_hierarchy.rs
//! Hierarchy and transform propagation stress test. //! //! Running this example: //! //! ``` //! cargo r --release --example transform_hierarchy <configuration name> //! ``` //! //! | Configuration | Description | //! | -------------------- | ----------------------------------------------------------------- | //! | `large_tree` | A fairly wide and deep tree. | //! | `wide_tree` | A shallow but very wide tree. | //! | `deep_tree` | A deep but not very wide tree. | //! | `chain` | A chain. 2500 levels deep. | //! | `update_leaves` | Same as `large_tree`, but only leaves are updated. | //! | `update_shallow` | Same as `large_tree`, but only the first few levels are updated. | //! | `humanoids_active` | 4000 active humanoid rigs. | //! | `humanoids_inactive` | 4000 humanoid rigs. Only 10 are active. | //! | `humanoids_mixed` | 2000 active and 2000 inactive humanoid rigs. | use bevy::{ diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, prelude::*, window::ExitCondition, }; use rand::Rng; /// pre-defined test configurations with name const CONFIGS: [(&str, Cfg); 9] = [ ( "large_tree", Cfg { test_case: TestCase::NonUniformTree { depth: 18, branch_width: 8, }, update_filter: UpdateFilter { probability: 0.5, min_depth: 0, max_depth: u32::MAX, }, }, ), ( "wide_tree", Cfg { test_case: TestCase::Tree { depth: 3, branch_width: 500, }, update_filter: UpdateFilter { probability: 0.5, min_depth: 0, max_depth: u32::MAX, }, }, ), ( "deep_tree", Cfg { test_case: TestCase::NonUniformTree { depth: 25, branch_width: 2, }, update_filter: UpdateFilter { probability: 0.5, min_depth: 0, max_depth: u32::MAX, }, }, ), ( "chain", Cfg { test_case: TestCase::Tree { depth: 2500, branch_width: 1, }, update_filter: UpdateFilter { probability: 0.5, min_depth: 0, max_depth: u32::MAX, }, }, ), ( "update_leaves", Cfg { test_case: TestCase::Tree { depth: 18, branch_width: 2, }, update_filter: UpdateFilter { probability: 0.5, min_depth: 17, max_depth: u32::MAX, }, }, ), ( "update_shallow", Cfg { test_case: TestCase::Tree { depth: 18, branch_width: 2, }, update_filter: UpdateFilter { probability: 0.5, min_depth: 0, max_depth: 8, }, }, ), ( "humanoids_active", Cfg { test_case: TestCase::Humanoids { active: 4000, inactive: 0, }, update_filter: UpdateFilter { probability: 1.0, min_depth: 0, max_depth: u32::MAX, }, }, ), ( "humanoids_inactive", Cfg { test_case: TestCase::Humanoids { active: 10, inactive: 3990, }, update_filter: UpdateFilter { probability: 1.0, min_depth: 0, max_depth: u32::MAX, }, }, ), ( "humanoids_mixed", Cfg { test_case: TestCase::Humanoids { active: 2000, inactive: 2000, }, update_filter: UpdateFilter { probability: 1.0, min_depth: 0, max_depth: u32::MAX, }, }, ), ]; fn print_available_configs() { println!("available configurations:"); for (name, _) in CONFIGS { println!(" {name}"); } } fn main() { // parse cli argument and find the selected test configuration let cfg: Cfg = match std::env::args().nth(1) { Some(arg) => match CONFIGS.iter().find(|(name, _)| *name == arg) { Some((name, cfg)) => { println!("test configuration: {name}"); cfg.clone() } None => { println!("test configuration \"{arg}\" not found.\n"); print_available_configs(); return; } }, None => { println!("missing argument: <test configuration>\n"); print_available_configs(); return; } }; println!("\n{cfg:#?}"); App::new() .insert_resource(cfg) .add_plugins(( DefaultPlugins.set(WindowPlugin { primary_window: None, exit_condition: ExitCondition::DontExit, ..default() }), FrameTimeDiagnosticsPlugin::default(), LogDiagnosticsPlugin::default(), )) .add_systems(Startup, setup) // Updating transforms *must* be done before `PostUpdate` // or the hierarchy will momentarily be in an invalid state. .add_systems(Update, update) .run(); } /// test configuration #[derive(Resource, Debug, Clone)] struct Cfg { /// which test case should be inserted test_case: TestCase, /// which entities should be updated update_filter: UpdateFilter, } #[derive(Debug, Clone)] enum TestCase { /// a uniform tree, exponentially growing with depth Tree { /// total depth depth: u32, /// number of children per node branch_width: u32, }, /// a non uniform tree (one side is deeper than the other) /// creates significantly less nodes than `TestCase::Tree` with the same parameters NonUniformTree { /// the maximum depth depth: u32, /// max number of children per node branch_width: u32, }, /// one or multiple humanoid rigs Humanoids { /// number of active instances (uses the specified [`UpdateFilter`]) active: u32, /// number of inactive instances (always inactive) inactive: u32, }, } /// a filter to restrict which nodes are updated #[derive(Debug, Clone)] struct UpdateFilter { /// starting depth (inclusive) min_depth: u32, /// end depth (inclusive) max_depth: u32, /// probability of a node to get updated (evaluated at insertion time, not during update) /// 0 (never) .. 1 (always) probability: f32, } /// update component with some per-component value #[derive(Component)] struct UpdateValue(f32); /// update positions system fn update(time: Res<Time>, mut query: Query<(&mut Transform, &mut UpdateValue)>) { for (mut t, mut u) in &mut query { u.0 += time.delta_secs() * 0.1; set_translation(&mut t.translation, u.0); } } /// set translation based on the angle `a` fn set_translation(translation: &mut Vec3, a: f32) { translation.x = ops::cos(a) * 32.0; translation.y = ops::sin(a) * 32.0; } fn setup(mut commands: Commands, cfg: Res<Cfg>) { warn!(include_str!("warning_string.txt")); commands.spawn((Camera2d, Transform::from_xyz(0.0, 0.0, 100.0))); let result = match cfg.test_case { TestCase::Tree { depth, branch_width, } => { let tree = gen_tree(depth, branch_width); spawn_tree(&tree, &mut commands, &cfg.update_filter, default()) } TestCase::NonUniformTree { depth, branch_width, } => { let tree = gen_non_uniform_tree(depth, branch_width); spawn_tree(&tree, &mut commands, &cfg.update_filter, default()) } TestCase::Humanoids { active, inactive } => { let mut result = InsertResult::default(); let mut rng = rand::rng(); for _ in 0..active { result.combine(spawn_tree( &HUMANOID_RIG, &mut commands, &cfg.update_filter, Transform::from_xyz( rng.random::<f32>() * 500.0 - 250.0, rng.random::<f32>() * 500.0 - 250.0, 0.0, ), )); } for _ in 0..inactive { result.combine(spawn_tree( &HUMANOID_RIG, &mut commands, &UpdateFilter { // force inactive by setting the probability < 0 probability: -1.0, ..cfg.update_filter }, Transform::from_xyz( rng.random::<f32>() * 500.0 - 250.0, rng.random::<f32>() * 500.0 - 250.0, 0.0, ), )); } result } }; println!("\n{result:#?}"); } /// overview of the inserted hierarchy #[derive(Default, Debug)] struct InsertResult { /// total number of nodes inserted inserted_nodes: usize, /// number of nodes that get updated each frame active_nodes: usize, /// maximum depth of the hierarchy tree maximum_depth: usize, } impl InsertResult { fn combine(&mut self, rhs: Self) -> &mut Self { self.inserted_nodes += rhs.inserted_nodes; self.active_nodes += rhs.active_nodes; self.maximum_depth = self.maximum_depth.max(rhs.maximum_depth); self } } /// spawns a tree defined by a parent map (excluding root) /// the parent map must be ordered (parent must exist before child) fn spawn_tree( parent_map: &[usize], commands: &mut Commands, update_filter: &UpdateFilter, root_transform: Transform, ) -> InsertResult { // total count (# of nodes + root) let count = parent_map.len() + 1; #[derive(Default, Clone, Copy)] struct NodeInfo { child_count: u32, depth: u32, } // node index -> entity lookup list let mut ents: Vec<Entity> = Vec::with_capacity(count); let mut node_info: Vec<NodeInfo> = vec![default(); count]; for (i, &parent_idx) in parent_map.iter().enumerate() { // assert spawn order (parent must be processed before child) assert!(parent_idx <= i, "invalid spawn order"); node_info[parent_idx].child_count += 1; } // insert root ents.push(commands.spawn(root_transform).id()); let mut result = InsertResult::default(); let mut rng = rand::rng(); // used to count through the number of children (used only for visual layout) let mut child_idx: Vec<u16> = vec![0; count]; // insert children for (current_idx, &parent_idx) in parent_map.iter().enumerate() { let current_idx = current_idx + 1; // separation factor to visually separate children (0..1) let sep = child_idx[parent_idx] as f32 / node_info[parent_idx].child_count as f32; child_idx[parent_idx] += 1; // calculate and set depth // this works because it's guaranteed that we have already iterated over the parent let depth = node_info[parent_idx].depth + 1; let info = &mut node_info[current_idx]; info.depth = depth; // update max depth of tree result.maximum_depth = result.maximum_depth.max(depth.try_into().unwrap()); // insert child let child_entity = { let mut cmd = commands.spawn_empty(); // check whether or not to update this node let update = (rng.random::<f32>() <= update_filter.probability) && (depth >= update_filter.min_depth && depth <= update_filter.max_depth); if update { cmd.insert(UpdateValue(sep)); result.active_nodes += 1; } let transform = { let mut translation = Vec3::ZERO; // use the same placement fn as the `update` system // this way the entities won't be all at (0, 0, 0) when they don't have an `Update` component set_translation(&mut translation, sep); Transform::from_translation(translation) }; // only insert the components necessary for the transform propagation cmd.insert(transform); cmd.id() }; commands.entity(ents[parent_idx]).add_child(child_entity); ents.push(child_entity); } result.inserted_nodes = ents.len(); result } /// generate a tree `depth` levels deep, where each node has `branch_width` children fn gen_tree(depth: u32, branch_width: u32) -> Vec<usize> { // calculate the total count of branches let mut count: usize = 0; for i in 0..(depth - 1) { count += TryInto::<usize>::try_into(branch_width.pow(i)).unwrap(); } // the tree is built using this pattern: // 0, 0, 0, ... 1, 1, 1, ... 2, 2, 2, ... (count - 1) (0..count) .flat_map(|i| std::iter::repeat_n(i, branch_width.try_into().unwrap())) .collect() } /// recursive part of [`gen_non_uniform_tree`] fn add_children_non_uniform( tree: &mut Vec<usize>, parent: usize, mut curr_depth: u32, max_branch_width: u32, ) { for _ in 0..max_branch_width { tree.push(parent); curr_depth = curr_depth.checked_sub(1).unwrap(); if curr_depth == 0 { return; } add_children_non_uniform(tree, tree.len(), curr_depth, max_branch_width); } } /// generate a tree that has more nodes on one side that the other /// the deepest hierarchy path is `max_depth` and the widest branches have `max_branch_width` children fn gen_non_uniform_tree(max_depth: u32, max_branch_width: u32) -> Vec<usize> { let mut tree = Vec::new(); add_children_non_uniform(&mut tree, 0, max_depth, max_branch_width); tree } /// parent map for a decently complex humanoid rig (based on mixamo rig) const HUMANOID_RIG: [usize; 67] = [ // (0: root) 0, // 1: hips 1, // 2: spine 2, // 3: spine 1 3, // 4: spine 2 4, // 5: neck 5, // 6: head 6, // 7: head top 6, // 8: left eye 6, // 9: right eye 4, // 10: left shoulder 10, // 11: left arm 11, // 12: left forearm 12, // 13: left hand 13, // 14: left hand thumb 1 14, // 15: left hand thumb 2 15, // 16: left hand thumb 3 16, // 17: left hand thumb 4 13, // 18: left hand index 1 18, // 19: left hand index 2 19, // 20: left hand index 3 20, // 21: left hand index 4 13, // 22: left hand middle 1 22, // 23: left hand middle 2 23, // 24: left hand middle 3 24, // 25: left hand middle 4 13, // 26: left hand ring 1 26, // 27: left hand ring 2 27, // 28: left hand ring 3 28, // 29: left hand ring 4 13, // 30: left hand pinky 1 30, // 31: left hand pinky 2 31, // 32: left hand pinky 3 32, // 33: left hand pinky 4 4, // 34: right shoulder 34, // 35: right arm 35, // 36: right forearm 36, // 37: right hand 37, // 38: right hand thumb 1 38, // 39: right hand thumb 2 39, // 40: right hand thumb 3 40, // 41: right hand thumb 4 37, // 42: right hand index 1 42, // 43: right hand index 2 43, // 44: right hand index 3 44, // 45: right hand index 4 37, // 46: right hand middle 1 46, // 47: right hand middle 2 47, // 48: right hand middle 3 48, // 49: right hand middle 4 37, // 50: right hand ring 1 50, // 51: right hand ring 2 51, // 52: right hand ring 3 52, // 53: right hand ring 4 37, // 54: right hand pinky 1 54, // 55: right hand pinky 2 55, // 56: right hand pinky 3 56, // 57: right hand pinky 4 1, // 58: left upper leg 58, // 59: left leg 59, // 60: left foot 60, // 61: left toe base 61, // 62: left toe end 1, // 63: right upper leg 63, // 64: right leg 64, // 65: right foot 65, // 66: right toe base 66, // 67: right toe end ];
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/stress_tests/many_animated_sprites.rs
examples/stress_tests/many_animated_sprites.rs
//! Renders a lot of animated sprites to allow performance testing. //! //! This example sets up many animated sprites in different sizes, rotations, and scales in the world. //! It also moves the camera over them to see how well frustum culling works. use std::time::Duration; use bevy::{ diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, prelude::*, window::{PresentMode, WindowResolution}, winit::WinitSettings, }; use rand::Rng; const CAMERA_SPEED: f32 = 1000.0; fn main() { App::new() // Since this is also used as a benchmark, we want it to display performance data. .add_plugins(( LogDiagnosticsPlugin::default(), FrameTimeDiagnosticsPlugin::default(), DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { present_mode: PresentMode::AutoNoVsync, resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0), ..default() }), ..default() }), )) .insert_resource(WinitSettings::continuous()) .add_systems(Startup, setup) .add_systems( Update, ( animate_sprite, print_sprite_count, move_camera.after(print_sprite_count), ), ) .run(); } fn setup( mut commands: Commands, assets: Res<AssetServer>, mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>, ) { warn!(include_str!("warning_string.txt")); let mut rng = rand::rng(); let tile_size = Vec2::splat(64.0); let map_size = Vec2::splat(320.0); let half_x = (map_size.x / 2.0) as i32; let half_y = (map_size.y / 2.0) as i32; let texture_handle = assets.load("textures/rpg/chars/gabe/gabe-idle-run.png"); let texture_atlas = TextureAtlasLayout::from_grid(UVec2::splat(24), 7, 1, None, None); let texture_atlas_handle = texture_atlases.add(texture_atlas); // Spawns the camera commands.spawn(Camera2d); // Builds and spawns the sprites for y in -half_y..half_y { for x in -half_x..half_x { let position = Vec2::new(x as f32, y as f32); let translation = (position * tile_size).extend(rng.random::<f32>()); let rotation = Quat::from_rotation_z(rng.random::<f32>()); let scale = Vec3::splat(rng.random::<f32>() * 2.0); let mut timer = Timer::from_seconds(0.1, TimerMode::Repeating); timer.set_elapsed(Duration::from_secs_f32(rng.random::<f32>())); commands.spawn(( Sprite { image: texture_handle.clone(), texture_atlas: Some(TextureAtlas::from(texture_atlas_handle.clone())), custom_size: Some(tile_size), ..default() }, Transform { translation, rotation, scale, }, AnimationTimer(timer), )); } } } // System for rotating and translating the camera fn move_camera(time: Res<Time>, mut camera_transform: Single<&mut Transform, With<Camera>>) { camera_transform.rotate(Quat::from_rotation_z(time.delta_secs() * 0.5)); **camera_transform = **camera_transform * Transform::from_translation(Vec3::X * CAMERA_SPEED * time.delta_secs()); } #[derive(Component, Deref, DerefMut)] struct AnimationTimer(Timer); fn animate_sprite( time: Res<Time>, texture_atlases: Res<Assets<TextureAtlasLayout>>, mut query: Query<(&mut AnimationTimer, &mut Sprite)>, ) { for (mut timer, mut sprite) in query.iter_mut() { timer.tick(time.delta()); if timer.just_finished() { let Some(atlas) = &mut sprite.texture_atlas else { continue; }; let texture_atlas = texture_atlases.get(&atlas.layout).unwrap(); atlas.index = (atlas.index + 1) % texture_atlas.textures.len(); } } } #[derive(Deref, DerefMut)] struct PrintingTimer(Timer); impl Default for PrintingTimer { fn default() -> Self { Self(Timer::from_seconds(1.0, TimerMode::Repeating)) } } // System for printing the number of sprites on every tick of the timer fn print_sprite_count(time: Res<Time>, mut timer: Local<PrintingTimer>, sprites: Query<&Sprite>) { timer.tick(time.delta()); if timer.just_finished() { info!("Sprites: {}", sprites.iter().count()); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/stress_tests/many_materials.rs
examples/stress_tests/many_materials.rs
//! Benchmark to test rendering many animated materials use argh::FromArgs; use bevy::{ diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, prelude::*, window::{PresentMode, WindowResolution}, winit::{UpdateMode, WinitSettings}, }; use std::f32::consts::PI; #[derive(FromArgs, Resource)] /// Command-line arguments for the `many_materials` stress test. struct Args { /// the size of the grid of materials to render (n x n) #[argh(option, short = 'n', default = "10")] grid_size: usize, } fn main() { // `from_env` panics on the web #[cfg(not(target_arch = "wasm32"))] let args: Args = argh::from_env(); #[cfg(target_arch = "wasm32")] let args = Args::from_args(&[], &[]).unwrap(); App::new() .add_plugins(( DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0), title: "many_materials".into(), present_mode: PresentMode::AutoNoVsync, ..default() }), ..default() }), FrameTimeDiagnosticsPlugin::default(), LogDiagnosticsPlugin::default(), )) .insert_resource(WinitSettings { focused_mode: UpdateMode::Continuous, unfocused_mode: UpdateMode::Continuous, }) .insert_resource(args) .add_systems(Startup, setup) .add_systems(Update, animate_materials) .run(); } fn setup( mut commands: Commands, args: Res<Args>, mesh_assets: ResMut<Assets<Mesh>>, material_assets: ResMut<Assets<StandardMaterial>>, ) { let args = args.into_inner(); let material_assets = material_assets.into_inner(); let mesh_assets = mesh_assets.into_inner(); let n = args.grid_size; // Camera let w = n as f32; commands.spawn(( Camera3d::default(), Transform::from_xyz(w * 1.25, w + 1.0, w * 1.25) .looking_at(Vec3::new(0.0, (w * -1.1) + 1.0, 0.0), Vec3::Y), )); // Light commands.spawn(( Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)), DirectionalLight { illuminance: 3000.0, shadows_enabled: true, ..default() }, )); // Cubes let mesh_handle = mesh_assets.add(Cuboid::from_size(Vec3::ONE)); for x in 0..n { for z in 0..n { commands.spawn(( Mesh3d(mesh_handle.clone()), MeshMaterial3d(material_assets.add(Color::WHITE)), Transform::from_translation(Vec3::new(x as f32, 0.0, z as f32)), )); } } } fn animate_materials( material_handles: Query<&MeshMaterial3d<StandardMaterial>>, time: Res<Time>, mut materials: ResMut<Assets<StandardMaterial>>, ) { for (i, material_handle) in material_handles.iter().enumerate() { if let Some(material) = materials.get_mut(material_handle) { let color = Color::hsl( ((i as f32 * 2.345 + time.elapsed_secs()) * 100.0) % 360.0, 1.0, 0.5, ); material.base_color = color; } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/stress_tests/many_cameras_lights.rs
examples/stress_tests/many_cameras_lights.rs
//! Test rendering of many cameras and lights use std::f32::consts::PI; use bevy::{ camera::Viewport, math::ops::{cos, sin}, prelude::*, window::{PresentMode, WindowResolution}, winit::WinitSettings, }; fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { present_mode: PresentMode::AutoNoVsync, resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0), ..default() }), ..default() })) .insert_resource(WinitSettings::continuous()) .add_systems(Startup, setup) .add_systems(Update, rotate_cameras) .run(); } const CAMERA_ROWS: usize = 4; const CAMERA_COLS: usize = 4; const NUM_LIGHTS: usize = 5; /// set up a simple 3D scene fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, window: Query<&Window>, ) -> Result { // circular base commands.spawn(( Mesh3d(meshes.add(Circle::new(4.0))), MeshMaterial3d(materials.add(Color::WHITE)), Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)), )); // cube commands.spawn(( Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))), MeshMaterial3d(materials.add(Color::WHITE)), Transform::from_xyz(0.0, 0.5, 0.0), )); // lights for i in 0..NUM_LIGHTS { let angle = (i as f32) / (NUM_LIGHTS as f32) * PI * 2.0; commands.spawn(( PointLight { color: Color::hsv(angle.to_degrees(), 1.0, 1.0), intensity: 2_000_000.0 / NUM_LIGHTS as f32, shadows_enabled: true, ..default() }, Transform::from_xyz(sin(angle) * 4.0, 2.0, cos(angle) * 4.0), )); } // cameras let window = window.single()?; let width = window.resolution.width() / CAMERA_COLS as f32 * window.resolution.scale_factor(); let height = window.resolution.height() / CAMERA_ROWS as f32 * window.resolution.scale_factor(); let mut i = 0; for y in 0..CAMERA_COLS { for x in 0..CAMERA_ROWS { let angle = i as f32 / (CAMERA_ROWS * CAMERA_COLS) as f32 * PI * 2.0; commands.spawn(( Camera3d::default(), Camera { viewport: Some(Viewport { physical_position: UVec2::new( (x as f32 * width) as u32, (y as f32 * height) as u32, ), physical_size: UVec2::new(width as u32, height as u32), ..default() }), order: i, ..default() }, Transform::from_xyz(sin(angle) * 4.0, 2.5, cos(angle) * 4.0) .looking_at(Vec3::ZERO, Vec3::Y), )); i += 1; } } Ok(()) } fn rotate_cameras(time: Res<Time>, mut query: Query<&mut Transform, With<Camera>>) { for mut transform in query.iter_mut() { transform.rotate_around(Vec3::ZERO, Quat::from_rotation_y(time.delta_secs())); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/stress_tests/many_text2d.rs
examples/stress_tests/many_text2d.rs
//! Renders a lot of `Text2d`s use std::ops::RangeInclusive; use bevy::{ camera::visibility::NoFrustumCulling, diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, prelude::*, text::FontAtlasSet, window::{PresentMode, WindowResolution}, winit::WinitSettings, }; use argh::FromArgs; use rand::{ seq::{IndexedRandom, IteratorRandom}, Rng, SeedableRng, }; use rand_chacha::ChaCha8Rng; const CAMERA_SPEED: f32 = 1000.0; // Some code points for valid glyphs in `FiraSans-Bold.ttf` const CODE_POINT_RANGES: [RangeInclusive<u32>; 5] = [ 0x20..=0x7e, 0xa0..=0x17e, 0x180..=0x2b2, 0x3f0..=0x479, 0x48a..=0x52f, ]; #[derive(FromArgs, Resource)] /// `many_text2d` stress test struct Args { /// whether to use many different glyphs to increase the amount of font atlas textures used. #[argh(switch)] many_glyphs: bool, /// whether to use many different font sizes to increase the amount of font atlas textures used. #[argh(switch)] many_font_sizes: bool, /// whether to force the text to recompute every frame by triggering change detection. #[argh(switch)] recompute: bool, /// whether to disable all frustum culling. #[argh(switch)] no_frustum_culling: bool, /// whether the text should use `Justify::Center`. #[argh(switch)] center: bool, } #[derive(Resource)] struct FontHandle(Handle<Font>); impl FromWorld for FontHandle { fn from_world(world: &mut World) -> Self { Self(world.load_asset("fonts/FiraSans-Bold.ttf")) } } fn main() { // `from_env` panics on the web #[cfg(not(target_arch = "wasm32"))] let args: Args = argh::from_env(); #[cfg(target_arch = "wasm32")] let args = Args::from_args(&[], &[]).unwrap(); let mut app = App::new(); app.add_plugins(( FrameTimeDiagnosticsPlugin::default(), LogDiagnosticsPlugin::default(), DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { present_mode: PresentMode::AutoNoVsync, resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0), ..default() }), ..default() }), )) .insert_resource(WinitSettings::continuous()) .init_resource::<FontHandle>() .add_systems(Startup, setup) .add_systems(Update, (move_camera, print_counts)); if args.recompute { app.add_systems(Update, recompute); } app.insert_resource(args).run(); } #[derive(Deref, DerefMut)] struct PrintingTimer(Timer); impl Default for PrintingTimer { fn default() -> Self { Self(Timer::from_seconds(1.0, TimerMode::Repeating)) } } fn setup(mut commands: Commands, font: Res<FontHandle>, args: Res<Args>) { warn!(include_str!("warning_string.txt")); let mut rng = ChaCha8Rng::seed_from_u64(42); let tile_size = Vec2::splat(64.0); let map_size = Vec2::splat(640.0); let half_x = (map_size.x / 4.0) as i32; let half_y = (map_size.y / 4.0) as i32; // Spawns the camera commands.spawn(Camera2d); // Builds and spawns the `Text2d`s, distributing them in a way that ensures a // good distribution of on-screen and off-screen entities. let mut text2ds = vec![]; for y in -half_y..half_y { for x in -half_x..half_x { let position = Vec2::new(x as f32, y as f32); let translation = (position * tile_size).extend(rng.random::<f32>()); let rotation = Quat::from_rotation_z(rng.random::<f32>()); let scale = Vec3::splat(rng.random::<f32>() * 2.0); let color = Hsla::hsl(rng.random_range(0.0..360.0), 0.8, 0.8); text2ds.push(( Text2d(random_text(&mut rng, &args)), random_text_font(&mut rng, &args, font.0.clone()), TextColor(color.into()), TextLayout::new_with_justify(if args.center { Justify::Center } else { Justify::Left }), Transform { translation, rotation, scale, }, )); } } if args.no_frustum_culling { let bundles = text2ds.into_iter().map(|bundle| (bundle, NoFrustumCulling)); commands.spawn_batch(bundles); } else { commands.spawn_batch(text2ds); } } // System for rotating and translating the camera fn move_camera(time: Res<Time>, mut camera_query: Query<&mut Transform, With<Camera>>) { let Ok(mut camera_transform) = camera_query.single_mut() else { return; }; camera_transform.rotate_z(time.delta_secs() * 0.5); *camera_transform = *camera_transform * Transform::from_translation(Vec3::X * CAMERA_SPEED * time.delta_secs()); } // System for printing the number of texts on every tick of the timer fn print_counts( time: Res<Time>, mut timer: Local<PrintingTimer>, texts: Query<&ViewVisibility, With<Text2d>>, font_atlas_set: Res<FontAtlasSet>, ) { timer.tick(time.delta()); if !timer.just_finished() { return; } let num_atlases = font_atlas_set .iter() // Removed this filter for now as the keys no longer include the AssetIds // .filter(|(key, _)| key.0 == font_id) .map(|(_, atlases)| atlases.len()) .sum::<usize>(); let visible_texts = texts.iter().filter(|visibility| visibility.get()).count(); info!( "Texts: {} Visible: {} Atlases: {}", texts.iter().count(), visible_texts, num_atlases ); } fn random_text_font(rng: &mut ChaCha8Rng, args: &Args, font: Handle<Font>) -> TextFont { let font_size = if args.many_font_sizes { *[10.0, 20.0, 30.0, 40.0, 50.0, 60.0].choose(rng).unwrap() } else { 60.0 }; TextFont { font_size, font: font.into(), ..default() } } fn random_text(rng: &mut ChaCha8Rng, args: &Args) -> String { if !args.many_glyphs { return "Bevy".to_string(); } CODE_POINT_RANGES .choose(rng) .unwrap() .clone() .choose_multiple(rng, 4) .into_iter() .map(|cp| char::from_u32(cp).unwrap()) .collect::<String>() } fn recompute(mut query: Query<&mut Text2d>) { for mut text2d in &mut query { text2d.set_changed(); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/stress_tests/many_buttons.rs
examples/stress_tests/many_buttons.rs
//! General UI benchmark that stress tests layouting, text, interaction and rendering use argh::FromArgs; use bevy::{ color::palettes::css::ORANGE_RED, diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, prelude::*, text::TextColor, window::{PresentMode, WindowResolution}, winit::WinitSettings, }; const FONT_SIZE: f32 = 7.0; #[derive(FromArgs, Resource)] /// `many_buttons` general UI benchmark that stress tests layouting, text, interaction and rendering struct Args { /// whether to add labels to each button #[argh(switch)] text: bool, /// whether to add borders to each button #[argh(switch)] no_borders: bool, /// whether to perform a full relayout each frame #[argh(switch)] relayout: bool, /// whether to recompute all text each frame (if text enabled) #[argh(switch)] recompute_text: bool, /// how many buttons per row and column of the grid. #[argh(option, default = "110")] buttons: usize, /// change the button icon every nth button, if `0` no icons are added. #[argh(option, default = "4")] image_freq: usize, /// use the grid layout model #[argh(switch)] grid: bool, /// at the start of each frame despawn any existing UI nodes and spawn a new UI tree #[argh(switch)] respawn: bool, /// set the root node to display none, removing all nodes from the layout. #[argh(switch)] display_none: bool, /// spawn the layout without a camera #[argh(switch)] no_camera: bool, /// a layout with a separate camera for each button #[argh(switch)] many_cameras: bool, } /// This example shows what happens when there is a lot of buttons on screen. fn main() { // `from_env` panics on the web #[cfg(not(target_arch = "wasm32"))] let args: Args = argh::from_env(); #[cfg(target_arch = "wasm32")] let args = Args::from_args(&[], &[]).unwrap(); warn!(include_str!("warning_string.txt")); let mut app = App::new(); app.add_plugins(( DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { present_mode: PresentMode::AutoNoVsync, resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0), ..default() }), ..default() }), FrameTimeDiagnosticsPlugin::default(), LogDiagnosticsPlugin::default(), )) .insert_resource(WinitSettings::continuous()) .add_systems(Update, (button_system, set_text_colors_changed)); if !args.no_camera { app.add_systems(Startup, |mut commands: Commands| { commands.spawn(Camera2d); }); } if args.many_cameras { app.add_systems(Startup, setup_many_cameras); } else if args.grid { app.add_systems(Startup, setup_grid); } else { app.add_systems(Startup, setup_flex); } if args.relayout { app.add_systems(Update, |mut nodes: Query<&mut Node>| { nodes.iter_mut().for_each(|mut node| node.set_changed()); }); } if args.recompute_text { app.add_systems(Update, |mut text_query: Query<&mut Text>| { text_query .iter_mut() .for_each(|mut text| text.set_changed()); }); } if args.respawn { if args.grid { app.add_systems(Update, (despawn_ui, setup_grid).chain()); } else { app.add_systems(Update, (despawn_ui, setup_flex).chain()); } } app.insert_resource(args).run(); } fn set_text_colors_changed(mut colors: Query<&mut TextColor>) { for mut text_color in colors.iter_mut() { text_color.set_changed(); } } #[derive(Component)] struct IdleColor(Color); fn button_system( mut interaction_query: Query< (&Interaction, &mut BackgroundColor, &IdleColor), Changed<Interaction>, >, ) { for (interaction, mut color, &IdleColor(idle_color)) in interaction_query.iter_mut() { *color = match interaction { Interaction::Hovered => ORANGE_RED.into(), _ => idle_color.into(), }; } } fn setup_flex(mut commands: Commands, asset_server: Res<AssetServer>, args: Res<Args>) { let images = if 0 < args.image_freq { Some(vec![ asset_server.load("branding/icon.png"), asset_server.load("textures/Game Icons/wrench.png"), ]) } else { None }; let buttons_f = args.buttons as f32; let border = if args.no_borders { UiRect::ZERO } else { UiRect::all(vmin(0.05 * 90. / buttons_f)) }; let as_rainbow = |i: usize| Color::hsl((i as f32 / buttons_f) * 360.0, 0.9, 0.8); commands .spawn(Node { display: if args.display_none { Display::None } else { Display::Flex }, flex_direction: FlexDirection::Column, justify_content: JustifyContent::Center, align_items: AlignItems::Center, width: percent(100), height: percent(100), ..default() }) .with_children(|commands| { for column in 0..args.buttons { commands.spawn(Node::default()).with_children(|commands| { for row in 0..args.buttons { let color = as_rainbow(row % column.max(1)); let border_color = Color::WHITE.with_alpha(0.5).into(); spawn_button( commands, color, buttons_f, column, row, args.text, border, border_color, images.as_ref().map(|images| { images[((column + row) / args.image_freq) % images.len()].clone() }), ); } }); } }); } fn setup_grid(mut commands: Commands, asset_server: Res<AssetServer>, args: Res<Args>) { let images = if 0 < args.image_freq { Some(vec![ asset_server.load("branding/icon.png"), asset_server.load("textures/Game Icons/wrench.png"), ]) } else { None }; let buttons_f = args.buttons as f32; let border = if args.no_borders { UiRect::ZERO } else { UiRect::all(vmin(0.05 * 90. / buttons_f)) }; let as_rainbow = |i: usize| Color::hsl((i as f32 / buttons_f) * 360.0, 0.9, 0.8); commands .spawn(Node { display: if args.display_none { Display::None } else { Display::Grid }, width: percent(100), height: percent(100), grid_template_columns: RepeatedGridTrack::flex(args.buttons as u16, 1.0), grid_template_rows: RepeatedGridTrack::flex(args.buttons as u16, 1.0), ..default() }) .with_children(|commands| { for column in 0..args.buttons { for row in 0..args.buttons { let color = as_rainbow(row % column.max(1)); let border_color = Color::WHITE.with_alpha(0.5).into(); spawn_button( commands, color, buttons_f, column, row, args.text, border, border_color, images.as_ref().map(|images| { images[((column + row) / args.image_freq) % images.len()].clone() }), ); } } }); } fn spawn_button( commands: &mut ChildSpawnerCommands, background_color: Color, buttons: f32, column: usize, row: usize, spawn_text: bool, border: UiRect, border_color: BorderColor, image: Option<Handle<Image>>, ) { let width = vw(90.0 / buttons); let height = vh(90.0 / buttons); let margin = UiRect::axes(width * 0.05, height * 0.05); let mut builder = commands.spawn(( Button, Node { width, height, margin, align_items: AlignItems::Center, justify_content: JustifyContent::Center, border, ..default() }, BackgroundColor(background_color), border_color, IdleColor(background_color), )); if let Some(image) = image { builder.insert(ImageNode::new(image)); } if spawn_text { builder.with_children(|parent| { // These labels are split to stress test multi-span text parent .spawn(( Text(format!("{column}, ")), TextFont { font_size: FONT_SIZE, ..default() }, TextColor(Color::srgb(0.5, 0.2, 0.2)), )) .with_child(( TextSpan(format!("{row}")), TextFont { font_size: FONT_SIZE, ..default() }, TextColor(Color::srgb(0.2, 0.2, 0.5)), )); }); } } fn despawn_ui(mut commands: Commands, root_node: Single<Entity, (With<Node>, Without<ChildOf>)>) { commands.entity(*root_node).despawn(); } fn setup_many_cameras(mut commands: Commands, asset_server: Res<AssetServer>, args: Res<Args>) { let images = if 0 < args.image_freq { Some(vec![ asset_server.load("branding/icon.png"), asset_server.load("textures/Game Icons/wrench.png"), ]) } else { None }; let buttons_f = args.buttons as f32; let border = if args.no_borders { UiRect::ZERO } else { UiRect::all(vmin(0.05 * 90. / buttons_f)) }; let as_rainbow = |i: usize| Color::hsl((i as f32 / buttons_f) * 360.0, 0.9, 0.8); for column in 0..args.buttons { for row in 0..args.buttons { let color = as_rainbow(row % column.max(1)); let border_color = Color::WHITE.with_alpha(0.5).into(); let camera = commands .spawn(( Camera2d, Camera { order: (column * args.buttons + row) as isize + 1, ..Default::default() }, )) .id(); commands .spawn(( Node { display: if args.display_none { Display::None } else { Display::Flex }, flex_direction: FlexDirection::Column, justify_content: JustifyContent::Center, align_items: AlignItems::Center, width: percent(100), height: percent(100), ..default() }, UiTargetCamera(camera), )) .with_children(|commands| { commands .spawn(Node { position_type: PositionType::Absolute, top: vh(column as f32 * 100. / buttons_f), left: vw(row as f32 * 100. / buttons_f), ..Default::default() }) .with_children(|commands| { spawn_button( commands, color, buttons_f, column, row, args.text, border, border_color, images.as_ref().map(|images| { images[((column + row) / args.image_freq) % images.len()] .clone() }), ); }); }); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/stress_tests/text_pipeline.rs
examples/stress_tests/text_pipeline.rs
//! Text pipeline benchmark. //! //! Continuously recomputes a large block of text with 100 text spans. use bevy::{ color::palettes::basic::{BLUE, YELLOW}, diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, prelude::*, text::{LineBreak, TextBounds}, window::{PresentMode, WindowResolution}, winit::WinitSettings, }; fn main() { App::new() .add_plugins(( DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { present_mode: PresentMode::AutoNoVsync, resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0), ..default() }), ..default() }), FrameTimeDiagnosticsPlugin::default(), LogDiagnosticsPlugin::default(), )) .insert_resource(WinitSettings::continuous()) .add_systems(Startup, spawn) .add_systems(Update, update_text_bounds) .run(); } fn spawn(mut commands: Commands, asset_server: Res<AssetServer>) { warn!(include_str!("warning_string.txt")); commands.spawn(Camera2d); let make_spans = |i| { [ ( TextSpan("text".repeat(i)), TextFont { font: asset_server.load("fonts/FiraMono-Medium.ttf").into(), font_size: (4 + i % 10) as f32, ..Default::default() }, TextColor(BLUE.into()), ), ( TextSpan("pipeline".repeat(i)), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: (4 + i % 11) as f32, ..default() }, TextColor(YELLOW.into()), ), ] }; let spans = (1..50).flat_map(|i| make_spans(i).into_iter()); commands .spawn(( Text2d::default(), TextLayout { justify: Justify::Center, linebreak: LineBreak::AnyCharacter, }, TextBounds::default(), )) .with_children(|p| { for span in spans { p.spawn(span); } }); } // changing the bounds of the text will cause a recomputation fn update_text_bounds(time: Res<Time>, mut text_bounds_query: Query<&mut TextBounds>) { let width = (1. + ops::sin(time.elapsed_secs())) * 600.0; for mut text_bounds in text_bounds_query.iter_mut() { text_bounds.width = Some(width); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/stress_tests/many_sprites.rs
examples/stress_tests/many_sprites.rs
//! Renders a lot of sprites to allow performance testing. //! See <https://github.com/bevyengine/bevy/pull/1492> //! //! This example sets up many sprites in different sizes, rotations, and scales in the world. //! It also moves the camera over them to see how well frustum culling works. //! //! Add the `--colored` arg to run with color tinted sprites. This will cause the sprites to be rendered //! in multiple batches, reducing performance but useful for testing. use bevy::{ color::palettes::css::*, diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, prelude::*, window::{PresentMode, WindowResolution}, winit::WinitSettings, }; use rand::Rng; const CAMERA_SPEED: f32 = 1000.0; const COLORS: [Color; 3] = [Color::Srgba(BLUE), Color::Srgba(WHITE), Color::Srgba(RED)]; #[derive(Resource)] struct ColorTint(bool); fn main() { App::new() .insert_resource(ColorTint( std::env::args().nth(1).unwrap_or_default() == "--colored", )) // Since this is also used as a benchmark, we want it to display performance data. .add_plugins(( LogDiagnosticsPlugin::default(), FrameTimeDiagnosticsPlugin::default(), DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { present_mode: PresentMode::AutoNoVsync, resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0), ..default() }), ..default() }), )) .insert_resource(WinitSettings::continuous()) .add_systems(Startup, setup) .add_systems( Update, (print_sprite_count, move_camera.after(print_sprite_count)), ) .run(); } fn setup(mut commands: Commands, assets: Res<AssetServer>, color_tint: Res<ColorTint>) { warn!(include_str!("warning_string.txt")); let mut rng = rand::rng(); let tile_size = Vec2::splat(64.0); let map_size = Vec2::splat(320.0); let half_x = (map_size.x / 2.0) as i32; let half_y = (map_size.y / 2.0) as i32; let sprite_handle = assets.load("branding/icon.png"); // Spawns the camera commands.spawn(Camera2d); // Builds and spawns the sprites let mut sprites = vec![]; for y in -half_y..half_y { for x in -half_x..half_x { let position = Vec2::new(x as f32, y as f32); let translation = (position * tile_size).extend(rng.random::<f32>()); let rotation = Quat::from_rotation_z(rng.random::<f32>()); let scale = Vec3::splat(rng.random::<f32>() * 2.0); sprites.push(( Sprite { image: sprite_handle.clone(), custom_size: Some(tile_size), color: if color_tint.0 { COLORS[rng.random_range(0..3)] } else { Color::WHITE }, ..default() }, Transform { translation, rotation, scale, }, )); } } commands.spawn_batch(sprites); } // System for rotating and translating the camera fn move_camera(time: Res<Time>, mut camera_transform: Single<&mut Transform, With<Camera>>) { camera_transform.rotate_z(time.delta_secs() * 0.5); **camera_transform = **camera_transform * Transform::from_translation(Vec3::X * CAMERA_SPEED * time.delta_secs()); } #[derive(Deref, DerefMut)] struct PrintingTimer(Timer); impl Default for PrintingTimer { fn default() -> Self { Self(Timer::from_seconds(1.0, TimerMode::Repeating)) } } // System for printing the number of sprites on every tick of the timer fn print_sprite_count(time: Res<Time>, mut timer: Local<PrintingTimer>, sprites: Query<&Sprite>) { timer.tick(time.delta()); if timer.just_finished() { info!("Sprites: {}", sprites.iter().count()); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/stress_tests/many_components.rs
examples/stress_tests/many_components.rs
//! Stress test for large ECS worlds. //! //! Running this example: //! //! ``` //! cargo run --profile stress-test --example many_components [<num_entities>] [<num_components>] [<num_systems>] //! ``` //! //! `num_entities`: The number of entities in the world (must be nonnegative) //! `num_components`: the number of components in the world (must be at least 10) //! `num_systems`: the number of systems in the world (must be nonnegative) //! //! If no valid number is provided, for each argument there's a reasonable default. use bevy::{ diagnostic::{ DiagnosticPath, DiagnosticsPlugin, FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin, }, ecs::{ component::{ComponentCloneBehavior, ComponentDescriptor, ComponentId, StorageType}, system::QueryParamBuilder, world::FilteredEntityMut, }, log::LogPlugin, platform::collections::HashSet, prelude::{App, In, IntoSystem, Query, Schedule, SystemParamBuilder, Update}, ptr::{OwningPtr, PtrMut}, MinimalPlugins, }; use rand::prelude::{IndexedRandom, Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; use std::{alloc::Layout, mem::ManuallyDrop, num::Wrapping}; #[expect(unsafe_code, reason = "Reading dynamic components requires unsafe")] // A simple system that matches against several components and does some menial calculation to create // some non-trivial load. fn base_system(access_components: In<Vec<ComponentId>>, mut query: Query<FilteredEntityMut>) { #[cfg(feature = "trace")] let _span = tracing::info_span!("base_system", components = ?access_components.0, count = query.iter().len()).entered(); for mut filtered_entity in &mut query { // We calculate Faulhaber's formula mod 256 with n = value and p = exponent. // See https://en.wikipedia.org/wiki/Faulhaber%27s_formula // The time is takes to compute this depends on the number of entities and the values in // each entity. This is to ensure that each system takes a different amount of time. let mut total: Wrapping<u8> = Wrapping(0); let mut exponent: u32 = 1; for component_id in &access_components.0 { // find the value of the component let ptr = filtered_entity.get_by_id(*component_id).unwrap(); // SAFETY: All components have a u8 layout let value: u8 = unsafe { *ptr.deref::<u8>() }; for i in 0..=value { let mut product = Wrapping(1); for _ in 1..=exponent { product *= Wrapping(i); } total += product; } exponent += 1; } // we assign this value to all the components we can write to for component_id in &access_components.0 { if let Some(ptr) = filtered_entity.get_mut_by_id(*component_id) { // SAFETY: All components have a u8 layout unsafe { let mut value = ptr.with_type::<u8>(); *value = total.0; } } } } } #[expect(unsafe_code, reason = "Using dynamic components requires unsafe")] fn stress_test(num_entities: u32, num_components: u32, num_systems: u32) { let mut rng = ChaCha8Rng::seed_from_u64(42); let mut app = App::default(); let world = app.world_mut(); // register a bunch of components let component_ids: Vec<ComponentId> = (1..=num_components) .map(|i| { world.register_component_with_descriptor( // SAFETY: // * We don't implement a drop function // * u8 is Sync and Send unsafe { ComponentDescriptor::new_with_layout( format!("Component{i}").to_string(), StorageType::Table, Layout::new::<u8>(), None, true, // is mutable ComponentCloneBehavior::Default, None, ) }, ) }) .collect(); // fill the schedule with systems let mut schedule = Schedule::new(Update); for _ in 1..=num_systems { let num_access_components = rng.random_range(1..10); let access_components: Vec<ComponentId> = component_ids .choose_multiple(&mut rng, num_access_components) .copied() .collect(); let system = (QueryParamBuilder::new(|builder| { for &access_component in &access_components { if rand::random::<bool>() { builder.mut_id(access_component); } else { builder.ref_id(access_component); } } }),) .build_state(world) .build_any_system(base_system); schedule.add_systems((move || access_components.clone()).pipe(system)); } // spawn a bunch of entities for _ in 1..=num_entities { let num_components = rng.random_range(1..10); let components: Vec<ComponentId> = component_ids .choose_multiple(&mut rng, num_components) .copied() .collect(); let mut entity = world.spawn_empty(); // We use `ManuallyDrop` here as we need to avoid dropping the u8's when `values` is dropped // since ownership of the values is passed to the world in `insert_by_ids`. // But we do want to deallocate the memory when values is dropped. let mut values: Vec<ManuallyDrop<u8>> = components .iter() .map(|_id| ManuallyDrop::new(rng.random_range(0..255))) .collect(); let ptrs: Vec<OwningPtr> = values .iter_mut() .map(|value| { // SAFETY: // * We don't read/write `values` binding after this and values are `ManuallyDrop`, // so we have the right to drop/move the values unsafe { PtrMut::from(value).promote() } }) .collect(); // SAFETY: // * component_id's are from the same world // * `values` was initialized above, so references are valid unsafe { entity.insert_by_ids(&components, ptrs.into_iter()); } } // overwrite Update schedule in the app app.add_schedule(schedule); app.add_plugins(MinimalPlugins) .add_plugins(DiagnosticsPlugin) .add_plugins(LogPlugin::default()) .add_plugins(FrameTimeDiagnosticsPlugin::default()) .add_plugins(LogDiagnosticsPlugin::filtered(HashSet::from_iter([ DiagnosticPath::new("fps"), ]))); app.run(); } fn main() { const DEFAULT_NUM_ENTITIES: u32 = 50000; const DEFAULT_NUM_COMPONENTS: u32 = 1000; const DEFAULT_NUM_SYSTEMS: u32 = 800; // take input let num_entities = std::env::args() .nth(1) .and_then(|string| string.parse::<u32>().ok()) .unwrap_or_else(|| { println!("No valid number of entities provided, using default {DEFAULT_NUM_ENTITIES}"); DEFAULT_NUM_ENTITIES }); let num_components = std::env::args() .nth(2) .and_then(|string| string.parse::<u32>().ok()) .and_then(|n| if n >= 10 { Some(n) } else { None }) .unwrap_or_else(|| { println!( "No valid number of components provided (>= 10), using default {DEFAULT_NUM_COMPONENTS}" ); DEFAULT_NUM_COMPONENTS }); let num_systems = std::env::args() .nth(3) .and_then(|string| string.parse::<u32>().ok()) .unwrap_or_else(|| { println!("No valid number of systems provided, using default {DEFAULT_NUM_SYSTEMS}"); DEFAULT_NUM_SYSTEMS }); stress_test(num_entities, num_components, num_systems); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/stress_tests/bevymark.rs
examples/stress_tests/bevymark.rs
//! This example provides a 2D benchmark. //! //! Usage: spawn more entities by clicking on the screen. use core::time::Duration; use std::str::FromStr; use argh::FromArgs; use bevy::{ asset::RenderAssetUsages, color::palettes::basic::*, diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, prelude::*, render::render_resource::{Extent3d, TextureDimension, TextureFormat}, sprite_render::AlphaMode2d, window::{PresentMode, WindowResolution}, winit::WinitSettings, }; use rand::{seq::IndexedRandom, Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; const BIRDS_PER_SECOND: u32 = 10000; const GRAVITY: f32 = -9.8 * 100.0; const MAX_VELOCITY: f32 = 750.; const BIRD_SCALE: f32 = 0.15; const BIRD_TEXTURE_SIZE: usize = 256; const HALF_BIRD_SIZE: f32 = BIRD_TEXTURE_SIZE as f32 * BIRD_SCALE * 0.5; #[derive(Resource)] struct BevyCounter { pub count: usize, pub color: Color, } #[derive(Component)] struct Bird { velocity: Vec3, } #[derive(FromArgs, Resource)] /// `bevymark` sprite / 2D mesh stress test struct Args { /// whether to use sprite or mesh2d #[argh(option, default = "Mode::Sprite")] mode: Mode, /// whether to step animations by a fixed amount such that each frame is the same across runs. /// If spawning waves, all are spawned up-front to immediately start rendering at the heaviest /// load. #[argh(switch)] benchmark: bool, /// how many birds to spawn per wave. #[argh(option, default = "0")] per_wave: usize, /// the number of waves to spawn. #[argh(option, default = "0")] waves: usize, /// whether to vary the material data in each instance. #[argh(switch)] vary_per_instance: bool, /// the number of different textures from which to randomly select the material color. 0 means no textures. #[argh(option, default = "1")] material_texture_count: usize, /// generate z values in increasing order rather than randomly #[argh(switch)] ordered_z: bool, /// the alpha mode used to spawn the sprites #[argh(option, default = "AlphaMode::Blend")] alpha_mode: AlphaMode, } #[derive(Default, Clone)] enum Mode { #[default] Sprite, Mesh2d, } impl FromStr for Mode { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "sprite" => Ok(Self::Sprite), "mesh2d" => Ok(Self::Mesh2d), _ => Err(format!( "Unknown mode: '{s}', valid modes: 'sprite', 'mesh2d'" )), } } } #[derive(Default, Clone)] enum AlphaMode { Opaque, #[default] Blend, AlphaMask, } impl FromStr for AlphaMode { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "opaque" => Ok(Self::Opaque), "blend" => Ok(Self::Blend), "alpha_mask" => Ok(Self::AlphaMask), _ => Err(format!( "Unknown alpha mode: '{s}', valid modes: 'opaque', 'blend', 'alpha_mask'" )), } } } const FIXED_TIMESTEP: f32 = 0.2; fn main() { // `from_env` panics on the web #[cfg(not(target_arch = "wasm32"))] let args: Args = argh::from_env(); #[cfg(target_arch = "wasm32")] let args = Args::from_args(&[], &[]).unwrap(); App::new() .add_plugins(( DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "BevyMark".into(), resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0), present_mode: PresentMode::AutoNoVsync, ..default() }), ..default() }), FrameTimeDiagnosticsPlugin::default(), LogDiagnosticsPlugin::default(), )) .insert_resource(StaticTransformOptimizations::disabled()) .insert_resource(WinitSettings::continuous()) .insert_resource(args) .insert_resource(BevyCounter { count: 0, color: Color::WHITE, }) .add_systems(Startup, setup) .add_systems(FixedUpdate, scheduled_spawner) .add_systems( Update, ( mouse_handler, movement_system, collision_system, counter_system, ), ) .insert_resource(Time::<Fixed>::from_duration(Duration::from_secs_f32( FIXED_TIMESTEP, ))) .run(); } #[derive(Resource)] struct BirdScheduled { waves: usize, per_wave: usize, } fn scheduled_spawner( mut commands: Commands, args: Res<Args>, window: Single<&Window>, mut scheduled: ResMut<BirdScheduled>, mut counter: ResMut<BevyCounter>, bird_resources: ResMut<BirdResources>, ) { if scheduled.waves > 0 { let bird_resources = bird_resources.into_inner(); spawn_birds( &mut commands, args.into_inner(), &window.resolution, &mut counter, scheduled.per_wave, bird_resources, None, scheduled.waves - 1, ); scheduled.waves -= 1; } } #[derive(Resource)] struct BirdResources { textures: Vec<Handle<Image>>, materials: Vec<Handle<ColorMaterial>>, quad: Handle<Mesh>, color_rng: ChaCha8Rng, material_rng: ChaCha8Rng, velocity_rng: ChaCha8Rng, transform_rng: ChaCha8Rng, } #[derive(Component)] struct StatsText; fn setup( mut commands: Commands, args: Res<Args>, asset_server: Res<AssetServer>, mut meshes: ResMut<Assets<Mesh>>, material_assets: ResMut<Assets<ColorMaterial>>, images: ResMut<Assets<Image>>, window: Single<&Window>, counter: ResMut<BevyCounter>, ) { warn!(include_str!("warning_string.txt")); let args = args.into_inner(); let images = images.into_inner(); let mut textures = Vec::with_capacity(args.material_texture_count.max(1)); if matches!(args.mode, Mode::Sprite) || args.material_texture_count > 0 { textures.push(asset_server.load("branding/icon.png")); } init_textures(&mut textures, args, images); let material_assets = material_assets.into_inner(); let materials = init_materials(args, &textures, material_assets); let mut bird_resources = BirdResources { textures, materials, quad: meshes.add(Rectangle::from_size(Vec2::splat(BIRD_TEXTURE_SIZE as f32))), // We're seeding the PRNG here to make this example deterministic for testing purposes. // This isn't strictly required in practical use unless you need your app to be deterministic. color_rng: ChaCha8Rng::seed_from_u64(42), material_rng: ChaCha8Rng::seed_from_u64(42), velocity_rng: ChaCha8Rng::seed_from_u64(42), transform_rng: ChaCha8Rng::seed_from_u64(42), }; let font = TextFont { font_size: 40.0, ..Default::default() }; commands.spawn(Camera2d); commands .spawn(( Node { position_type: PositionType::Absolute, padding: UiRect::all(px(5)), ..default() }, BackgroundColor(Color::BLACK.with_alpha(0.75)), GlobalZIndex(i32::MAX), )) .with_children(|p| { p.spawn((Text::default(), StatsText)).with_children(|p| { p.spawn(( TextSpan::new("Bird Count: "), font.clone(), TextColor(LIME.into()), )); p.spawn((TextSpan::new(""), font.clone(), TextColor(AQUA.into()))); p.spawn(( TextSpan::new("\nFPS (raw): "), font.clone(), TextColor(LIME.into()), )); p.spawn((TextSpan::new(""), font.clone(), TextColor(AQUA.into()))); p.spawn(( TextSpan::new("\nFPS (SMA): "), font.clone(), TextColor(LIME.into()), )); p.spawn((TextSpan::new(""), font.clone(), TextColor(AQUA.into()))); p.spawn(( TextSpan::new("\nFPS (EMA): "), font.clone(), TextColor(LIME.into()), )); p.spawn((TextSpan::new(""), font.clone(), TextColor(AQUA.into()))); }); }); let mut scheduled = BirdScheduled { per_wave: args.per_wave, waves: args.waves, }; if args.benchmark { let counter = counter.into_inner(); for wave in (0..scheduled.waves).rev() { spawn_birds( &mut commands, args, &window.resolution, counter, scheduled.per_wave, &mut bird_resources, Some(wave), wave, ); } scheduled.waves = 0; } commands.insert_resource(bird_resources); commands.insert_resource(scheduled); } fn mouse_handler( mut commands: Commands, args: Res<Args>, time: Res<Time>, mouse_button_input: Res<ButtonInput<MouseButton>>, window: Query<&Window>, bird_resources: ResMut<BirdResources>, mut counter: ResMut<BevyCounter>, mut rng: Local<Option<ChaCha8Rng>>, mut wave: Local<usize>, ) { let Ok(window) = window.single() else { return; }; if rng.is_none() { // We're seeding the PRNG here to make this example deterministic for testing purposes. // This isn't strictly required in practical use unless you need your app to be deterministic. *rng = Some(ChaCha8Rng::seed_from_u64(42)); } let rng = rng.as_mut().unwrap(); if mouse_button_input.just_released(MouseButton::Left) { counter.color = Color::linear_rgb(rng.random(), rng.random(), rng.random()); } if mouse_button_input.pressed(MouseButton::Left) { let spawn_count = (BIRDS_PER_SECOND as f64 * time.delta_secs_f64()) as usize; spawn_birds( &mut commands, args.into_inner(), &window.resolution, &mut counter, spawn_count, bird_resources.into_inner(), None, *wave, ); *wave += 1; } } fn bird_velocity_transform( half_extents: Vec2, mut translation: Vec3, velocity_rng: &mut ChaCha8Rng, waves: Option<usize>, dt: f32, ) -> (Transform, Vec3) { let mut velocity = Vec3::new(MAX_VELOCITY * (velocity_rng.random::<f32>() - 0.5), 0., 0.); if let Some(waves) = waves { // Step the movement and handle collisions as if the wave had been spawned at fixed time intervals // and with dt-spaced frames of simulation for _ in 0..(waves * (FIXED_TIMESTEP / dt).round() as usize) { step_movement(&mut translation, &mut velocity, dt); handle_collision(half_extents, &translation, &mut velocity); } } ( Transform::from_translation(translation).with_scale(Vec3::splat(BIRD_SCALE)), velocity, ) } const FIXED_DELTA_TIME: f32 = 1.0 / 60.0; fn spawn_birds( commands: &mut Commands, args: &Args, primary_window_resolution: &WindowResolution, counter: &mut BevyCounter, spawn_count: usize, bird_resources: &mut BirdResources, waves_to_simulate: Option<usize>, wave: usize, ) { let bird_x = (primary_window_resolution.width() / -2.) + HALF_BIRD_SIZE; let bird_y = (primary_window_resolution.height() / 2.) - HALF_BIRD_SIZE; let half_extents = 0.5 * primary_window_resolution.size(); let color = counter.color; let current_count = counter.count; match args.mode { Mode::Sprite => { let batch = (0..spawn_count) .map(|count| { let bird_z = if args.ordered_z { (current_count + count) as f32 * 0.00001 } else { bird_resources.transform_rng.random::<f32>() }; let (transform, velocity) = bird_velocity_transform( half_extents, Vec3::new(bird_x, bird_y, bird_z), &mut bird_resources.velocity_rng, waves_to_simulate, FIXED_DELTA_TIME, ); let color = if args.vary_per_instance { Color::linear_rgb( bird_resources.color_rng.random(), bird_resources.color_rng.random(), bird_resources.color_rng.random(), ) } else { color }; ( Sprite { image: bird_resources .textures .choose(&mut bird_resources.material_rng) .unwrap() .clone(), color, ..default() }, transform, Bird { velocity }, ) }) .collect::<Vec<_>>(); commands.spawn_batch(batch); } Mode::Mesh2d => { let batch = (0..spawn_count) .map(|count| { let bird_z = if args.ordered_z { (current_count + count) as f32 * 0.00001 } else { bird_resources.transform_rng.random::<f32>() }; let (transform, velocity) = bird_velocity_transform( half_extents, Vec3::new(bird_x, bird_y, bird_z), &mut bird_resources.velocity_rng, waves_to_simulate, FIXED_DELTA_TIME, ); let material = if args.vary_per_instance || args.material_texture_count > args.waves { bird_resources .materials .choose(&mut bird_resources.material_rng) .unwrap() .clone() } else { bird_resources.materials[wave % bird_resources.materials.len()].clone() }; ( Mesh2d(bird_resources.quad.clone()), MeshMaterial2d(material), transform, Bird { velocity }, ) }) .collect::<Vec<_>>(); commands.spawn_batch(batch); } } counter.count += spawn_count; counter.color = Color::linear_rgb( bird_resources.color_rng.random(), bird_resources.color_rng.random(), bird_resources.color_rng.random(), ); } fn step_movement(translation: &mut Vec3, velocity: &mut Vec3, dt: f32) { translation.x += velocity.x * dt; translation.y += velocity.y * dt; velocity.y += GRAVITY * dt; } fn movement_system( args: Res<Args>, time: Res<Time>, mut bird_query: Query<(&mut Bird, &mut Transform)>, ) { let dt = if args.benchmark { FIXED_DELTA_TIME } else { time.delta_secs() }; for (mut bird, mut transform) in &mut bird_query { step_movement(&mut transform.translation, &mut bird.velocity, dt); } } fn handle_collision(half_extents: Vec2, translation: &Vec3, velocity: &mut Vec3) { if (velocity.x > 0. && translation.x + HALF_BIRD_SIZE > half_extents.x) || (velocity.x <= 0. && translation.x - HALF_BIRD_SIZE < -half_extents.x) { velocity.x = -velocity.x; } let velocity_y = velocity.y; if velocity_y < 0. && translation.y - HALF_BIRD_SIZE < -half_extents.y { velocity.y = -velocity_y; } if translation.y + HALF_BIRD_SIZE > half_extents.y && velocity_y > 0.0 { velocity.y = 0.0; } } fn collision_system(window: Query<&Window>, mut bird_query: Query<(&mut Bird, &Transform)>) { let Ok(window) = window.single() else { return; }; let half_extents = 0.5 * window.size(); for (mut bird, transform) in &mut bird_query { handle_collision(half_extents, &transform.translation, &mut bird.velocity); } } fn counter_system( diagnostics: Res<DiagnosticsStore>, counter: Res<BevyCounter>, query: Single<Entity, With<StatsText>>, mut writer: TextUiWriter, ) { let text = *query; if counter.is_changed() { *writer.text(text, 2) = counter.count.to_string(); } if let Some(fps) = diagnostics.get(&FrameTimeDiagnosticsPlugin::FPS) { if let Some(raw) = fps.value() { *writer.text(text, 4) = format!("{raw:.2}"); } if let Some(sma) = fps.average() { *writer.text(text, 6) = format!("{sma:.2}"); } if let Some(ema) = fps.smoothed() { *writer.text(text, 8) = format!("{ema:.2}"); } }; } fn init_textures(textures: &mut Vec<Handle<Image>>, args: &Args, images: &mut Assets<Image>) { // We're seeding the PRNG here to make this example deterministic for testing purposes. // This isn't strictly required in practical use unless you need your app to be deterministic. let mut color_rng = ChaCha8Rng::seed_from_u64(42); while textures.len() < args.material_texture_count { let pixel = [ color_rng.random(), color_rng.random(), color_rng.random(), 255, ]; textures.push(images.add(Image::new_fill( Extent3d { width: BIRD_TEXTURE_SIZE as u32, height: BIRD_TEXTURE_SIZE as u32, depth_or_array_layers: 1, }, TextureDimension::D2, &pixel, TextureFormat::Rgba8UnormSrgb, RenderAssetUsages::RENDER_WORLD, ))); } } fn init_materials( args: &Args, textures: &[Handle<Image>], assets: &mut Assets<ColorMaterial>, ) -> Vec<Handle<ColorMaterial>> { let capacity = if args.vary_per_instance { args.per_wave * args.waves } else { args.material_texture_count.max(args.waves) } .max(1); let alpha_mode = match args.alpha_mode { AlphaMode::Opaque => AlphaMode2d::Opaque, AlphaMode::Blend => AlphaMode2d::Blend, AlphaMode::AlphaMask => AlphaMode2d::Mask(0.5), }; let mut materials = Vec::with_capacity(capacity); materials.push(assets.add(ColorMaterial { color: Color::WHITE, texture: textures.first().cloned(), alpha_mode, ..default() })); // We're seeding the PRNG here to make this example deterministic for testing purposes. // This isn't strictly required in practical use unless you need your app to be deterministic. let mut color_rng = ChaCha8Rng::seed_from_u64(42); let mut texture_rng = ChaCha8Rng::seed_from_u64(42); materials.extend( std::iter::repeat_with(|| { assets.add(ColorMaterial { color: Color::srgb_u8(color_rng.random(), color_rng.random(), color_rng.random()), texture: textures.choose(&mut texture_rng).cloned(), alpha_mode, ..default() }) }) .take(capacity - materials.len()), ); materials }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/stress_tests/bevymark_3d.rs
examples/stress_tests/bevymark_3d.rs
//! This example provides a 3D benchmark. //! //! Usage: spawn more entities by clicking with the left mouse button. use core::time::Duration; use std::str::FromStr; use argh::FromArgs; use bevy::{ asset::RenderAssetUsages, color::palettes::basic::*, diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, prelude::*, render::render_resource::{Extent3d, TextureDimension, TextureFormat}, window::{PresentMode, WindowResolution}, winit::WinitSettings, }; use rand::{seq::IndexedRandom, Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; const CUBES_PER_SECOND: u32 = 10000; const GRAVITY: f32 = -9.8; const MAX_VELOCITY: f32 = 10.; const CUBE_SCALE: f32 = 1.0; const CUBE_TEXTURE_SIZE: usize = 256; const HALF_CUBE_SIZE: f32 = CUBE_SCALE * 0.5; const VOLUME_WIDTH: usize = 50; const VOLUME_SIZE: Vec3 = Vec3::splat(VOLUME_WIDTH as f32); #[derive(Resource)] struct BevyCounter { pub count: usize, pub color: Color, } #[derive(Component)] struct Cube { velocity: Vec3, } #[derive(FromArgs, Resource)] /// `bevymark_3d` cube stress test struct Args { /// whether to step animations by a fixed amount such that each frame is the same across runs. /// If spawning waves, all are spawned up-front to immediately start rendering at the heaviest /// load. #[argh(switch)] benchmark: bool, /// how many cubes to spawn per wave. #[argh(option, default = "0")] per_wave: usize, /// the number of waves to spawn. #[argh(option, default = "0")] waves: usize, /// whether to vary the material data in each instance. #[argh(switch)] vary_per_instance: bool, /// the number of different textures from which to randomly select the material color. 0 means no textures. #[argh(option, default = "1")] material_texture_count: usize, /// the alpha mode used to spawn the cubes #[argh(option, default = "AlphaMode::Opaque")] alpha_mode: AlphaMode, } #[derive(Default, Clone)] enum AlphaMode { #[default] Opaque, Blend, AlphaMask, } impl FromStr for AlphaMode { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "opaque" => Ok(Self::Opaque), "blend" => Ok(Self::Blend), "alpha_mask" => Ok(Self::AlphaMask), _ => Err(format!( "Unknown alpha mode: '{s}', valid modes: 'opaque', 'blend', 'alpha_mask'" )), } } } const FIXED_TIMESTEP: f32 = 0.2; fn main() { // `from_env` panics on the web #[cfg(not(target_arch = "wasm32"))] let args: Args = argh::from_env(); #[cfg(target_arch = "wasm32")] let args = Args::from_args(&[], &[]).unwrap(); App::new() .add_plugins(( DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "BevyMark 3D".into(), resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0), present_mode: PresentMode::AutoNoVsync, ..default() }), ..default() }), FrameTimeDiagnosticsPlugin::default(), LogDiagnosticsPlugin::default(), )) .insert_resource(WinitSettings::continuous()) .insert_resource(args) .insert_resource(BevyCounter { count: 0, color: Color::WHITE, }) .add_systems(Startup, setup) .add_systems(FixedUpdate, scheduled_spawner) .add_systems( Update, ( mouse_handler, movement_system, collision_system, counter_system, ), ) .insert_resource(Time::<Fixed>::from_duration(Duration::from_secs_f32( FIXED_TIMESTEP, ))) .run(); } #[derive(Resource)] struct CubeScheduled { waves: usize, per_wave: usize, } fn scheduled_spawner( mut commands: Commands, args: Res<Args>, mut scheduled: ResMut<CubeScheduled>, mut counter: ResMut<BevyCounter>, cube_resources: ResMut<CubeResources>, ) { if scheduled.waves > 0 { let cube_resources = cube_resources.into_inner(); spawn_cubes( &mut commands, args.into_inner(), &mut counter, scheduled.per_wave, cube_resources, None, scheduled.waves - 1, ); scheduled.waves -= 1; } } #[derive(Resource)] struct CubeResources { _textures: Vec<Handle<Image>>, materials: Vec<Handle<StandardMaterial>>, cube_mesh: Handle<Mesh>, color_rng: ChaCha8Rng, material_rng: ChaCha8Rng, velocity_rng: ChaCha8Rng, transform_rng: ChaCha8Rng, } #[derive(Component)] struct StatsText; fn setup( mut commands: Commands, args: Res<Args>, asset_server: Res<AssetServer>, mut meshes: ResMut<Assets<Mesh>>, material_assets: ResMut<Assets<StandardMaterial>>, images: ResMut<Assets<Image>>, counter: ResMut<BevyCounter>, ) { let args = args.into_inner(); let images = images.into_inner(); let mut textures = Vec::with_capacity(args.material_texture_count.max(1)); if args.material_texture_count > 0 { textures.push(asset_server.load("branding/icon.png")); } init_textures(&mut textures, args, images); let material_assets = material_assets.into_inner(); let materials = init_materials(args, &textures, material_assets); let mut cube_resources = CubeResources { _textures: textures, materials, cube_mesh: meshes.add(Cuboid::from_size(Vec3::splat(CUBE_SCALE))), color_rng: ChaCha8Rng::seed_from_u64(42), material_rng: ChaCha8Rng::seed_from_u64(12), velocity_rng: ChaCha8Rng::seed_from_u64(97), transform_rng: ChaCha8Rng::seed_from_u64(26), }; let font = TextFont { font_size: 40.0, ..Default::default() }; commands.spawn(( Camera3d::default(), Transform::from_translation(VOLUME_SIZE * 1.3).looking_at(Vec3::ZERO, Vec3::Y), )); commands.spawn(( DirectionalLight { illuminance: 10000.0, shadows_enabled: false, ..default() }, Transform::from_xyz(1.0, 2.0, 3.0).looking_at(Vec3::ZERO, Vec3::Y), )); commands.spawn(( Node { position_type: PositionType::Absolute, padding: UiRect::all(px(5)), ..default() }, BackgroundColor(Color::BLACK.with_alpha(0.75)), GlobalZIndex(i32::MAX), children![( Text::default(), StatsText, children![ ( TextSpan::new("Cube Count: "), font.clone(), TextColor(LIME.into()), ), (TextSpan::new(""), font.clone(), TextColor(AQUA.into())), ( TextSpan::new("\nFPS (raw): "), font.clone(), TextColor(LIME.into()), ), (TextSpan::new(""), font.clone(), TextColor(AQUA.into())), ( TextSpan::new("\nFPS (SMA): "), font.clone(), TextColor(LIME.into()), ), (TextSpan::new(""), font.clone(), TextColor(AQUA.into())), ( TextSpan::new("\nFPS (EMA): "), font.clone(), TextColor(LIME.into()), ), (TextSpan::new(""), font.clone(), TextColor(AQUA.into())) ] )], )); let mut scheduled = CubeScheduled { per_wave: args.per_wave, waves: args.waves, }; if args.benchmark { let counter = counter.into_inner(); for wave in (0..scheduled.waves).rev() { spawn_cubes( &mut commands, args, counter, scheduled.per_wave, &mut cube_resources, Some(wave), wave, ); } scheduled.waves = 0; } commands.insert_resource(cube_resources); commands.insert_resource(scheduled); } fn mouse_handler( mut commands: Commands, args: Res<Args>, time: Res<Time>, mouse_button_input: Res<ButtonInput<MouseButton>>, cube_resources: ResMut<CubeResources>, mut counter: ResMut<BevyCounter>, mut rng: Local<Option<ChaCha8Rng>>, mut wave: Local<usize>, ) { if rng.is_none() { *rng = Some(ChaCha8Rng::seed_from_u64(42)); } let rng = rng.as_mut().unwrap(); if mouse_button_input.just_released(MouseButton::Left) { counter.color = Color::linear_rgb(rng.random(), rng.random(), rng.random()); } if mouse_button_input.pressed(MouseButton::Left) { let spawn_count = (CUBES_PER_SECOND as f64 * time.delta_secs_f64()) as usize; spawn_cubes( &mut commands, args.into_inner(), &mut counter, spawn_count, cube_resources.into_inner(), None, *wave, ); *wave += 1; } } fn cube_velocity_transform( mut translation: Vec3, velocity_rng: &mut ChaCha8Rng, waves: Option<usize>, dt: f32, ) -> (Transform, Vec3) { let mut velocity = Vec3::new(0., 0., MAX_VELOCITY * velocity_rng.random::<f32>()); if let Some(waves) = waves { for _ in 0..(waves * (FIXED_TIMESTEP / dt).round() as usize) { step_movement(&mut translation, &mut velocity, dt); handle_collision(&translation, &mut velocity); } } (Transform::from_translation(translation), velocity) } const FIXED_DELTA_TIME: f32 = 1.0 / 60.0; fn spawn_cubes( commands: &mut Commands, args: &Args, counter: &mut BevyCounter, spawn_count: usize, cube_resources: &mut CubeResources, waves_to_simulate: Option<usize>, wave: usize, ) { let batch_material = cube_resources.materials[wave % cube_resources.materials.len()].clone(); let spawn_y = VOLUME_SIZE.y / 2.0 - HALF_CUBE_SIZE; let spawn_z = -VOLUME_SIZE.z / 2.0 + HALF_CUBE_SIZE; let batch = (0..spawn_count) .map(|_| { let spawn_pos = Vec3::new( (cube_resources.transform_rng.random::<f32>() - 0.5) * VOLUME_SIZE.x, spawn_y, spawn_z, ); let (transform, velocity) = cube_velocity_transform( spawn_pos, &mut cube_resources.velocity_rng, waves_to_simulate, FIXED_DELTA_TIME, ); let material = if args.vary_per_instance { cube_resources .materials .choose(&mut cube_resources.material_rng) .unwrap() .clone() } else { batch_material.clone() }; ( Mesh3d(cube_resources.cube_mesh.clone()), MeshMaterial3d(material), transform, Cube { velocity }, ) }) .collect::<Vec<_>>(); commands.spawn_batch(batch); counter.count += spawn_count; counter.color = Color::linear_rgb( cube_resources.color_rng.random(), cube_resources.color_rng.random(), cube_resources.color_rng.random(), ); } fn step_movement(translation: &mut Vec3, velocity: &mut Vec3, dt: f32) { translation.x += velocity.x * dt; translation.y += velocity.y * dt; translation.z += velocity.z * dt; velocity.y += GRAVITY * dt; } fn movement_system( args: Res<Args>, time: Res<Time>, mut cube_query: Query<(&mut Cube, &mut Transform)>, ) { let dt = if args.benchmark { FIXED_DELTA_TIME } else { time.delta_secs() }; for (mut cube, mut transform) in &mut cube_query { step_movement(&mut transform.translation, &mut cube.velocity, dt); } } fn handle_collision(translation: &Vec3, velocity: &mut Vec3) { if (velocity.x > 0. && translation.x + HALF_CUBE_SIZE > VOLUME_SIZE.x / 2.0) || (velocity.x <= 0. && translation.x - HALF_CUBE_SIZE < -VOLUME_SIZE.x / 2.0) { velocity.x = -velocity.x; } if (velocity.z > 0. && translation.z + HALF_CUBE_SIZE > VOLUME_SIZE.z / 2.0) || (velocity.z <= 0. && translation.z - HALF_CUBE_SIZE < -VOLUME_SIZE.z / 2.0) { velocity.z = -velocity.z; } let velocity_y = velocity.y; if velocity_y < 0. && translation.y - HALF_CUBE_SIZE < -VOLUME_SIZE.y / 2.0 { velocity.y = -velocity_y; } if translation.y + HALF_CUBE_SIZE > VOLUME_SIZE.y / 2.0 && velocity_y > 0.0 { velocity.y = 0.0; } } fn collision_system(mut cube_query: Query<(&mut Cube, &Transform)>) { cube_query.par_iter_mut().for_each(|(mut cube, transform)| { handle_collision(&transform.translation, &mut cube.velocity); }); } fn counter_system( diagnostics: Res<DiagnosticsStore>, counter: Res<BevyCounter>, query: Single<Entity, With<StatsText>>, mut writer: TextUiWriter, ) { let text = *query; if counter.is_changed() { *writer.text(text, 2) = counter.count.to_string(); } if let Some(fps) = diagnostics.get(&FrameTimeDiagnosticsPlugin::FPS) { if let Some(raw) = fps.value() { *writer.text(text, 4) = format!("{raw:.2}"); } if let Some(sma) = fps.average() { *writer.text(text, 6) = format!("{sma:.2}"); } if let Some(ema) = fps.smoothed() { *writer.text(text, 8) = format!("{ema:.2}"); } }; } fn init_textures(textures: &mut Vec<Handle<Image>>, args: &Args, images: &mut Assets<Image>) { let mut color_rng = ChaCha8Rng::seed_from_u64(42); while textures.len() < args.material_texture_count { let pixel = [ color_rng.random(), color_rng.random(), color_rng.random(), 255, ]; textures.push(images.add(Image::new_fill( Extent3d { width: CUBE_TEXTURE_SIZE as u32, height: CUBE_TEXTURE_SIZE as u32, depth_or_array_layers: 1, }, TextureDimension::D2, &pixel, TextureFormat::Rgba8UnormSrgb, RenderAssetUsages::RENDER_WORLD, ))); } } fn init_materials( args: &Args, textures: &[Handle<Image>], assets: &mut Assets<StandardMaterial>, ) -> Vec<Handle<StandardMaterial>> { let mut capacity = if args.vary_per_instance { args.per_wave * args.waves } else { args.material_texture_count.max(args.waves) }; if !args.benchmark { capacity = capacity.max(256); } capacity = capacity.max(1); let alpha_mode = match args.alpha_mode { AlphaMode::Opaque => bevy::prelude::AlphaMode::Opaque, AlphaMode::Blend => bevy::prelude::AlphaMode::Blend, AlphaMode::AlphaMask => bevy::prelude::AlphaMode::Mask(0.5), }; let mut materials = Vec::with_capacity(capacity); materials.push(assets.add(StandardMaterial { base_color: Color::WHITE, base_color_texture: textures.first().cloned(), alpha_mode, ..default() })); let mut color_rng = ChaCha8Rng::seed_from_u64(42); let mut texture_rng = ChaCha8Rng::seed_from_u64(42); materials.extend( std::iter::repeat_with(|| { assets.add(StandardMaterial { base_color: Color::linear_rgb( color_rng.random(), color_rng.random(), color_rng.random(), ), base_color_texture: textures.choose(&mut texture_rng).cloned(), alpha_mode, ..default() }) }) .take(capacity - materials.len()), ); materials }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/stress_tests/many_glyphs.rs
examples/stress_tests/many_glyphs.rs
//! Simple text rendering benchmark. //! //! Creates a text block with a single span containing `100_000` glyphs, //! and renders it with the UI in a white color and with Text2d in a red color. //! //! To recompute all text each frame run //! `cargo run --example many_glyphs --release recompute-text` use argh::FromArgs; use bevy::{ color::palettes::basic::RED, diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, prelude::*, text::{LineBreak, TextBounds}, window::{PresentMode, WindowResolution}, winit::WinitSettings, }; #[derive(FromArgs, Resource)] /// `many_glyphs` stress test struct Args { /// don't draw the UI text. #[argh(switch)] no_ui: bool, /// don't draw the Text2d text. #[argh(switch)] no_text2d: bool, /// whether to force the text to recompute every frame by triggering change detection. #[argh(switch)] recompute_text: bool, } fn main() { // `from_env` panics on the web #[cfg(not(target_arch = "wasm32"))] let args: Args = argh::from_env(); #[cfg(target_arch = "wasm32")] let args = Args::from_args(&[], &[]).unwrap(); let mut app = App::new(); app.add_plugins(( DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { present_mode: PresentMode::AutoNoVsync, resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0), ..default() }), ..default() }), FrameTimeDiagnosticsPlugin::default(), LogDiagnosticsPlugin::default(), )) .insert_resource(WinitSettings::continuous()) .add_systems(Startup, setup); if args.recompute_text { app.add_systems(Update, force_text_recomputation); } app.insert_resource(args).run(); } fn setup(mut commands: Commands, args: Res<Args>) { warn!(include_str!("warning_string.txt")); commands.spawn(Camera2d); let text_string = "0123456789".repeat(10_000); let text_font = TextFont { font_size: 4., ..Default::default() }; let text_block = TextLayout { justify: Justify::Left, linebreak: LineBreak::AnyCharacter, }; if !args.no_ui { commands .spawn(Node { width: percent(100), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }) .with_children(|commands| { commands .spawn(Node { width: px(1000), ..Default::default() }) .with_child((Text(text_string.clone()), text_font.clone(), text_block)); }); } if !args.no_text2d { commands.spawn(( Text2d::new(text_string), text_font.clone(), TextColor(RED.into()), bevy::sprite::Anchor::CENTER, TextBounds::new_horizontal(1000.), text_block, )); } } fn force_text_recomputation(mut text_query: Query<&mut TextLayout>) { for mut block in &mut text_query { block.set_changed(); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/stress_tests/many_foxes.rs
examples/stress_tests/many_foxes.rs
//! Loads animations from a skinned glTF, spawns many of them, and plays the //! animation to stress test skinned meshes. use std::{f32::consts::PI, time::Duration}; use argh::FromArgs; use bevy::{ diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, light::CascadeShadowConfigBuilder, prelude::*, scene::SceneInstanceReady, window::{PresentMode, WindowResolution}, winit::WinitSettings, }; #[derive(FromArgs, Resource)] /// `many_foxes` stress test struct Args { /// whether all foxes run in sync. #[argh(switch)] sync: bool, /// total number of foxes. #[argh(option, default = "1000")] count: usize, } #[derive(Resource)] struct Foxes { count: usize, speed: f32, moving: bool, sync: bool, } fn main() { // `from_env` panics on the web #[cfg(not(target_arch = "wasm32"))] let args: Args = argh::from_env(); #[cfg(target_arch = "wasm32")] let args = Args::from_args(&[], &[]).unwrap(); App::new() .add_plugins(( DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "🦊🦊🦊 Many Foxes! 🦊🦊🦊".into(), present_mode: PresentMode::AutoNoVsync, resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0), ..default() }), ..default() }), FrameTimeDiagnosticsPlugin::default(), LogDiagnosticsPlugin::default(), )) .insert_resource(StaticTransformOptimizations::disabled()) .insert_resource(WinitSettings::continuous()) .insert_resource(Foxes { count: args.count, speed: 2.0, moving: true, sync: args.sync, }) .add_systems(Startup, setup) .add_systems( Update, ( keyboard_animation_control, update_fox_rings.after(keyboard_animation_control), ), ) .run(); } #[derive(Resource)] struct Animations { node_indices: Vec<AnimationNodeIndex>, graph: Handle<AnimationGraph>, } const RING_SPACING: f32 = 2.0; const FOX_SPACING: f32 = 2.0; #[derive(Component, Clone, Copy)] enum RotationDirection { CounterClockwise, Clockwise, } impl RotationDirection { fn sign(&self) -> f32 { match self { RotationDirection::CounterClockwise => 1.0, RotationDirection::Clockwise => -1.0, } } } #[derive(Component)] struct Ring { radius: f32, } fn setup( mut commands: Commands, asset_server: Res<AssetServer>, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, mut animation_graphs: ResMut<Assets<AnimationGraph>>, foxes: Res<Foxes>, ) { warn!(include_str!("warning_string.txt")); // Insert a resource with the current scene information let animation_clips = [ asset_server.load(GltfAssetLabel::Animation(2).from_asset("models/animated/Fox.glb")), asset_server.load(GltfAssetLabel::Animation(1).from_asset("models/animated/Fox.glb")), asset_server.load(GltfAssetLabel::Animation(0).from_asset("models/animated/Fox.glb")), ]; let mut animation_graph = AnimationGraph::new(); let node_indices = animation_graph .add_clips(animation_clips, 1.0, animation_graph.root) .collect(); commands.insert_resource(Animations { node_indices, graph: animation_graphs.add(animation_graph), }); // Foxes // Concentric rings of foxes, running in opposite directions. The rings are spaced at 2m radius intervals. // The foxes in each ring are spaced at least 2m apart around its circumference.' // NOTE: This fox model faces +z let fox_handle = asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/animated/Fox.glb")); let ring_directions = [ ( Quat::from_rotation_y(PI), RotationDirection::CounterClockwise, ), (Quat::IDENTITY, RotationDirection::Clockwise), ]; let mut ring_index = 0; let mut radius = RING_SPACING; let mut foxes_remaining = foxes.count; info!("Spawning {} foxes...", foxes.count); while foxes_remaining > 0 { let (base_rotation, ring_direction) = ring_directions[ring_index % 2]; let ring_parent = commands .spawn(( Transform::default(), Visibility::default(), ring_direction, Ring { radius }, )) .id(); let circumference = PI * 2. * radius; let foxes_in_ring = ((circumference / FOX_SPACING) as usize).min(foxes_remaining); let fox_spacing_angle = circumference / (foxes_in_ring as f32 * radius); for fox_i in 0..foxes_in_ring { let fox_angle = fox_i as f32 * fox_spacing_angle; let (s, c) = ops::sin_cos(fox_angle); let (x, z) = (radius * c, radius * s); commands.entity(ring_parent).with_children(|builder| { builder .spawn(( SceneRoot(fox_handle.clone()), Transform::from_xyz(x, 0.0, z) .with_scale(Vec3::splat(0.01)) .with_rotation(base_rotation * Quat::from_rotation_y(-fox_angle)), )) .observe(setup_scene_once_loaded); }); } foxes_remaining -= foxes_in_ring; radius += RING_SPACING; ring_index += 1; } // Camera let zoom = 0.8; let translation = Vec3::new( radius * 1.25 * zoom, radius * 0.5 * zoom, radius * 1.5 * zoom, ); commands.spawn(( Camera3d::default(), Transform::from_translation(translation) .looking_at(0.2 * Vec3::new(translation.x, 0.0, translation.z), Vec3::Y), )); // Plane commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(5000.0, 5000.0))), MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))), )); // Light commands.spawn(( Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)), DirectionalLight { shadows_enabled: true, ..default() }, CascadeShadowConfigBuilder { first_cascade_far_bound: 0.9 * radius, maximum_distance: 2.8 * radius, ..default() } .build(), )); println!("Animation controls:"); println!(" - spacebar: play / pause"); println!(" - arrow up / down: speed up / slow down animation playback"); println!(" - arrow left / right: seek backward / forward"); println!(" - return: change animation"); } // Once the scene is loaded, start the animation fn setup_scene_once_loaded( scene_ready: On<SceneInstanceReady>, animations: Res<Animations>, foxes: Res<Foxes>, mut commands: Commands, children: Query<&Children>, mut players: Query<&mut AnimationPlayer>, ) { for child in children.iter_descendants(scene_ready.entity) { if let Ok(mut player) = players.get_mut(child) { let playing_animation = player.play(animations.node_indices[0]).repeat(); if !foxes.sync { playing_animation.seek_to(scene_ready.entity.index_u32() as f32 / 10.0); } commands.entity(child).insert(( AnimationGraphHandle(animations.graph.clone()), AnimationTransitions::default(), )); } } } fn update_fox_rings( time: Res<Time>, foxes: Res<Foxes>, mut rings: Query<(&Ring, &RotationDirection, &mut Transform)>, ) { if !foxes.moving { return; } let dt = time.delta_secs(); for (ring, rotation_direction, mut transform) in &mut rings { let angular_velocity = foxes.speed / ring.radius; transform.rotate_y(rotation_direction.sign() * angular_velocity * dt); } } fn keyboard_animation_control( keyboard_input: Res<ButtonInput<KeyCode>>, mut animation_player: Query<(&mut AnimationPlayer, &mut AnimationTransitions)>, animations: Res<Animations>, mut current_animation: Local<usize>, mut foxes: ResMut<Foxes>, ) { if keyboard_input.just_pressed(KeyCode::Space) { foxes.moving = !foxes.moving; } if keyboard_input.just_pressed(KeyCode::ArrowUp) { foxes.speed *= 1.25; } if keyboard_input.just_pressed(KeyCode::ArrowDown) { foxes.speed *= 0.8; } if keyboard_input.just_pressed(KeyCode::Enter) { *current_animation = (*current_animation + 1) % animations.node_indices.len(); } for (mut player, mut transitions) in &mut animation_player { if keyboard_input.just_pressed(KeyCode::Space) { if player.all_paused() { player.resume_all(); } else { player.pause_all(); } } if keyboard_input.just_pressed(KeyCode::ArrowUp) { player.adjust_speeds(1.25); } if keyboard_input.just_pressed(KeyCode::ArrowDown) { player.adjust_speeds(0.8); } if keyboard_input.just_pressed(KeyCode::ArrowLeft) { player.seek_all_by(-0.1); } if keyboard_input.just_pressed(KeyCode::ArrowRight) { player.seek_all_by(0.1); } if keyboard_input.just_pressed(KeyCode::Enter) { transitions .play( &mut player, animations.node_indices[*current_animation], Duration::from_millis(250), ) .repeat(); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/stress_tests/many_cubes.rs
examples/stress_tests/many_cubes.rs
//! Simple benchmark to test per-entity draw overhead. //! //! To measure performance realistically, be sure to run this in release mode. //! `cargo run --example many_cubes --release` //! //! By default, this arranges the meshes in a spherical pattern that //! distributes the meshes evenly. //! //! See `cargo run --example many_cubes --release -- --help` for more options. use std::{f64::consts::PI, str::FromStr}; use argh::FromArgs; use bevy::{ asset::RenderAssetUsages, camera::visibility::{NoCpuCulling, NoFrustumCulling}, diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, light::NotShadowCaster, math::{ops::cbrt, DVec2, DVec3}, prelude::*, render::{ batching::NoAutomaticBatching, render_resource::{Extent3d, TextureDimension, TextureFormat}, view::NoIndirectDrawing, }, window::{PresentMode, WindowResolution}, winit::{UpdateMode, WinitSettings}, }; use rand::{seq::IndexedRandom, Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; #[derive(FromArgs, Resource)] /// `many_cubes` stress test struct Args { /// how the cube instances should be positioned. #[argh(option, default = "Layout::Sphere")] layout: Layout, /// whether to step the camera animation by a fixed amount such that each frame is the same across runs. #[argh(switch)] benchmark: bool, /// whether to vary the material data in each instance. #[argh(switch)] vary_material_data_per_instance: bool, /// the number of different textures from which to randomly select the material base color. 0 means no textures. #[argh(option, default = "0")] material_texture_count: usize, /// the number of different meshes from which to randomly select. Clamped to at least 1. #[argh(option, default = "1")] mesh_count: usize, /// whether to disable all frustum culling. Stresses queuing and batching as all mesh material entities in the scene are always drawn. #[argh(switch)] no_frustum_culling: bool, /// whether to disable automatic batching. Skips batching resulting in heavy stress on render pass draw command encoding. #[argh(switch)] no_automatic_batching: bool, /// whether to disable indirect drawing. #[argh(switch)] no_indirect_drawing: bool, /// whether to disable CPU culling. #[argh(switch)] no_cpu_culling: bool, /// whether to enable directional light cascaded shadow mapping. #[argh(switch)] shadows: bool, /// whether to continuously rotate individual cubes. #[argh(switch)] rotate_cubes: bool, /// animate the cube materials by updating the material from the cpu each frame #[argh(switch)] animate_materials: bool, } #[derive(Default, Clone, PartialEq)] enum Layout { Cube, #[default] Sphere, Dense, } impl FromStr for Layout { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "cube" => Ok(Self::Cube), "sphere" => Ok(Self::Sphere), "dense" => Ok(Self::Dense), _ => Err(format!( "Unknown layout value: '{s}', valid options: 'cube', 'sphere', 'dense'" )), } } } fn main() { // `from_env` panics on the web #[cfg(not(target_arch = "wasm32"))] let args: Args = argh::from_env(); #[cfg(target_arch = "wasm32")] let args = Args::from_args(&[], &[]).unwrap(); let mut app = App::new(); app.add_plugins(( DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { present_mode: PresentMode::AutoNoVsync, resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0), ..default() }), ..default() }), FrameTimeDiagnosticsPlugin::default(), LogDiagnosticsPlugin::default(), )) .insert_resource(WinitSettings { focused_mode: UpdateMode::Continuous, unfocused_mode: UpdateMode::Continuous, }) .add_systems(Startup, setup) .add_systems(Update, print_mesh_count); if args.layout != Layout::Dense { app.add_systems(Update, move_camera); } if args.rotate_cubes { app.add_systems(Update, rotate_cubes); } if args.animate_materials { app.add_systems(Update, update_materials); } app.insert_resource(args).run(); } const WIDTH: usize = 200; const HEIGHT: usize = 200; fn setup( mut commands: Commands, args: Res<Args>, mesh_assets: ResMut<Assets<Mesh>>, material_assets: ResMut<Assets<StandardMaterial>>, images: ResMut<Assets<Image>>, ) { warn!(include_str!("warning_string.txt")); let args = args.into_inner(); let images = images.into_inner(); let material_assets = material_assets.into_inner(); let mesh_assets = mesh_assets.into_inner(); let meshes = init_meshes(args, mesh_assets); let material_textures = init_textures(args, images); let materials = init_materials(args, &material_textures, material_assets); // We're seeding the PRNG here to make this example deterministic for testing purposes. // This isn't strictly required in practical use unless you need your app to be deterministic. let mut material_rng = ChaCha8Rng::seed_from_u64(42); match args.layout { Layout::Sphere => { // NOTE: This pattern is good for testing performance of culling as it provides roughly // the same number of visible meshes regardless of the viewing angle. const N_POINTS: usize = WIDTH * HEIGHT * 4; // NOTE: f64 is used to avoid precision issues that produce visual artifacts in the distribution let radius = WIDTH as f64 * 2.5; let golden_ratio = 0.5f64 * (1.0f64 + 5.0f64.sqrt()); for i in 0..N_POINTS { let spherical_polar_theta_phi = fibonacci_spiral_on_sphere(golden_ratio, i, N_POINTS); let unit_sphere_p = spherical_polar_to_cartesian(spherical_polar_theta_phi); let (mesh, transform) = meshes.choose(&mut material_rng).unwrap(); commands .spawn(( Mesh3d(mesh.clone()), MeshMaterial3d(materials.choose(&mut material_rng).unwrap().clone()), Transform::from_translation((radius * unit_sphere_p).as_vec3()) .looking_at(Vec3::ZERO, Vec3::Y) .mul_transform(*transform), )) .insert_if(NoFrustumCulling, || args.no_frustum_culling) .insert_if(NoAutomaticBatching, || args.no_automatic_batching); } // camera let mut camera = commands.spawn(Camera3d::default()); if args.no_indirect_drawing { camera.insert(NoIndirectDrawing); } if args.no_cpu_culling { camera.insert(NoCpuCulling); } // Inside-out box around the meshes onto which shadows are cast (though you cannot see them...) commands.spawn(( Mesh3d(mesh_assets.add(Cuboid::from_size(Vec3::splat(radius as f32 * 2.2)))), MeshMaterial3d(material_assets.add(StandardMaterial::from(Color::WHITE))), Transform::from_scale(-Vec3::ONE), NotShadowCaster, )); } Layout::Cube => { // NOTE: This pattern is good for demonstrating that frustum culling is working correctly // as the number of visible meshes rises and falls depending on the viewing angle. let scale = 2.5; for x in 0..WIDTH { for y in 0..HEIGHT { // introduce spaces to break any kind of moiré pattern if x % 10 == 0 || y % 10 == 0 { continue; } // cube commands.spawn(( Mesh3d(meshes.choose(&mut material_rng).unwrap().0.clone()), MeshMaterial3d(materials.choose(&mut material_rng).unwrap().clone()), Transform::from_xyz((x as f32) * scale, (y as f32) * scale, 0.0), )); commands.spawn(( Mesh3d(meshes.choose(&mut material_rng).unwrap().0.clone()), MeshMaterial3d(materials.choose(&mut material_rng).unwrap().clone()), Transform::from_xyz( (x as f32) * scale, HEIGHT as f32 * scale, (y as f32) * scale, ), )); commands.spawn(( Mesh3d(meshes.choose(&mut material_rng).unwrap().0.clone()), MeshMaterial3d(materials.choose(&mut material_rng).unwrap().clone()), Transform::from_xyz((x as f32) * scale, 0.0, (y as f32) * scale), )); commands.spawn(( Mesh3d(meshes.choose(&mut material_rng).unwrap().0.clone()), MeshMaterial3d(materials.choose(&mut material_rng).unwrap().clone()), Transform::from_xyz(0.0, (x as f32) * scale, (y as f32) * scale), )); } } // camera let center = 0.5 * scale * Vec3::new(WIDTH as f32, HEIGHT as f32, WIDTH as f32); commands.spawn((Camera3d::default(), Transform::from_translation(center))); // Inside-out box around the meshes onto which shadows are cast (though you cannot see them...) commands.spawn(( Mesh3d(mesh_assets.add(Cuboid::from_size(2.0 * 1.1 * center))), MeshMaterial3d(material_assets.add(StandardMaterial::from(Color::WHITE))), Transform::from_scale(-Vec3::ONE).with_translation(center), NotShadowCaster, )); } Layout::Dense => { // NOTE: This pattern is good for demonstrating a dense configuration of cubes // overlapping each other, all within the camera frustum. let count = WIDTH * HEIGHT * 2; let size = cbrt(count as f32).round(); let gap = 1.25; let cubes = (0..count).map(move |i| { let x = i as f32 % size; let y = (i as f32 / size) % size; let z = i as f32 / (size * size); let pos = Vec3::new(x * gap, y * gap, z * gap); ( Mesh3d(meshes.choose(&mut material_rng).unwrap().0.clone()), MeshMaterial3d(materials.choose(&mut material_rng).unwrap().clone()), Transform::from_translation(pos), ) }); // camera commands.spawn(( Camera3d::default(), Transform::from_xyz(100.0, 90.0, 100.0) .looking_at(Vec3::new(0.0, -10.0, 0.0), Vec3::Y), )); commands.spawn_batch(cubes); } } commands.spawn(( DirectionalLight { shadows_enabled: args.shadows, ..default() }, Transform::IDENTITY.looking_at(Vec3::new(0.0, -1.0, -1.0), Vec3::Y), )); } fn init_textures(args: &Args, images: &mut Assets<Image>) -> Vec<Handle<Image>> { // We're seeding the PRNG here to make this example deterministic for testing purposes. // This isn't strictly required in practical use unless you need your app to be deterministic. let mut color_rng = ChaCha8Rng::seed_from_u64(42); let color_bytes: Vec<u8> = (0..(args.material_texture_count * 4)) .map(|i| { if (i % 4) == 3 { 255 } else { color_rng.random() } }) .collect(); color_bytes .chunks(4) .map(|pixel| { images.add(Image::new_fill( Extent3d::default(), TextureDimension::D2, pixel, TextureFormat::Rgba8UnormSrgb, RenderAssetUsages::RENDER_WORLD, )) }) .collect() } fn init_materials( args: &Args, textures: &[Handle<Image>], assets: &mut Assets<StandardMaterial>, ) -> Vec<Handle<StandardMaterial>> { let capacity = if args.vary_material_data_per_instance { match args.layout { Layout::Cube => (WIDTH - WIDTH / 10) * (HEIGHT - HEIGHT / 10), Layout::Sphere => WIDTH * HEIGHT * 4, Layout::Dense => WIDTH * HEIGHT * 2, } } else { args.material_texture_count } .max(1); let mut materials = Vec::with_capacity(capacity); materials.push(assets.add(StandardMaterial { base_color: Color::WHITE, base_color_texture: textures.first().cloned(), ..default() })); // We're seeding the PRNG here to make this example deterministic for testing purposes. // This isn't strictly required in practical use unless you need your app to be deterministic. let mut color_rng = ChaCha8Rng::seed_from_u64(42); let mut texture_rng = ChaCha8Rng::seed_from_u64(42); materials.extend( std::iter::repeat_with(|| { assets.add(StandardMaterial { base_color: Color::srgb_u8( color_rng.random(), color_rng.random(), color_rng.random(), ), base_color_texture: textures.choose(&mut texture_rng).cloned(), ..default() }) }) .take(capacity - materials.len()), ); materials } fn init_meshes(args: &Args, assets: &mut Assets<Mesh>) -> Vec<(Handle<Mesh>, Transform)> { let capacity = args.mesh_count.max(1); // We're seeding the PRNG here to make this example deterministic for testing purposes. // This isn't strictly required in practical use unless you need your app to be deterministic. let mut radius_rng = ChaCha8Rng::seed_from_u64(42); let mut variant = 0; std::iter::repeat_with(|| { let radius = radius_rng.random_range(0.25f32..=0.75f32); let (handle, transform) = match variant % 15 { 0 => ( assets.add(Cuboid { half_size: Vec3::splat(radius), }), Transform::IDENTITY, ), 1 => ( assets.add(Capsule3d { radius, half_length: radius, }), Transform::IDENTITY, ), 2 => ( assets.add(Circle { radius }), Transform::IDENTITY.looking_at(Vec3::Z, Vec3::Y), ), 3 => { let mut vertices = [Vec2::ZERO; 3]; let dtheta = std::f32::consts::TAU / 3.0; for (i, vertex) in vertices.iter_mut().enumerate() { let (s, c) = ops::sin_cos(i as f32 * dtheta); *vertex = Vec2::new(c, s) * radius; } ( assets.add(Triangle2d { vertices }), Transform::IDENTITY.looking_at(Vec3::Z, Vec3::Y), ) } 4 => ( assets.add(Rectangle { half_size: Vec2::splat(radius), }), Transform::IDENTITY.looking_at(Vec3::Z, Vec3::Y), ), v if (5..=8).contains(&v) => ( assets.add(RegularPolygon { circumcircle: Circle { radius }, sides: v, }), Transform::IDENTITY.looking_at(Vec3::Z, Vec3::Y), ), 9 => ( assets.add(Cylinder { radius, half_height: radius, }), Transform::IDENTITY, ), 10 => ( assets.add(Ellipse { half_size: Vec2::new(radius, 0.5 * radius), }), Transform::IDENTITY.looking_at(Vec3::Z, Vec3::Y), ), 11 => ( assets.add( Plane3d { normal: Dir3::NEG_Z, half_size: Vec2::splat(0.5), } .mesh() .size(radius, radius), ), Transform::IDENTITY, ), 12 => (assets.add(Sphere { radius }), Transform::IDENTITY), 13 => ( assets.add(Torus { minor_radius: 0.5 * radius, major_radius: radius, }), Transform::IDENTITY.looking_at(Vec3::Y, Vec3::Y), ), 14 => ( assets.add(Capsule2d { radius, half_length: radius, }), Transform::IDENTITY.looking_at(Vec3::Z, Vec3::Y), ), _ => unreachable!(), }; variant += 1; (handle, transform) }) .take(capacity) .collect() } // NOTE: This epsilon value is apparently optimal for optimizing for the average // nearest-neighbor distance. See: // http://extremelearning.com.au/how-to-evenly-distribute-points-on-a-sphere-more-effectively-than-the-canonical-fibonacci-lattice/ // for details. const EPSILON: f64 = 0.36; fn fibonacci_spiral_on_sphere(golden_ratio: f64, i: usize, n: usize) -> DVec2 { DVec2::new( PI * 2. * (i as f64 / golden_ratio), f64::acos(1.0 - 2.0 * (i as f64 + EPSILON) / (n as f64 - 1.0 + 2.0 * EPSILON)), ) } fn spherical_polar_to_cartesian(p: DVec2) -> DVec3 { let (sin_theta, cos_theta) = p.x.sin_cos(); let (sin_phi, cos_phi) = p.y.sin_cos(); DVec3::new(cos_theta * sin_phi, sin_theta * sin_phi, cos_phi) } // System for rotating the camera fn move_camera( time: Res<Time>, args: Res<Args>, mut camera_transform: Single<&mut Transform, With<Camera>>, ) { let delta = 0.15 * if args.benchmark { 1.0 / 60.0 } else { time.delta_secs() }; camera_transform.rotate_z(delta); camera_transform.rotate_x(delta); } // System for printing the number of meshes on every tick of the timer fn print_mesh_count( time: Res<Time>, mut timer: Local<PrintingTimer>, sprites: Query<(&Mesh3d, &ViewVisibility)>, ) { timer.tick(time.delta()); if timer.just_finished() { info!( "Meshes: {} - Visible Meshes {}", sprites.iter().len(), sprites.iter().filter(|(_, vis)| vis.get()).count(), ); } } #[derive(Deref, DerefMut)] struct PrintingTimer(Timer); impl Default for PrintingTimer { fn default() -> Self { Self(Timer::from_seconds(1.0, TimerMode::Repeating)) } } fn update_materials(mut materials: ResMut<Assets<StandardMaterial>>, time: Res<Time>) { let elapsed = time.elapsed_secs(); for (i, (_, material)) in materials.iter_mut().enumerate() { let hue = (elapsed + i as f32 * 0.005).rem_euclid(1.0); // This is much faster than using base_color.set_hue(hue), and in a tight loop it shows. let color = fast_hue_to_rgb(hue); material.base_color = Color::linear_rgb(color.x, color.y, color.z); } } fn rotate_cubes( mut query: Query<&mut Transform, (With<Mesh3d>, Without<NotShadowCaster>)>, time: Res<Time>, ) { query.par_iter_mut().for_each(|mut transform| { transform.rotate_y(10.0 * time.delta_secs()); }); } #[inline] fn fast_hue_to_rgb(hue: f32) -> Vec3 { (hue * 6.0 - vec3(3.0, 2.0, 4.0)).abs() * vec3(1.0, -1.0, -1.0) + vec3(-1.0, 2.0, 2.0) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/stress_tests/many_lights.rs
examples/stress_tests/many_lights.rs
//! Simple benchmark to test rendering many point lights. //! Run with `WGPU_SETTINGS_PRIO=webgl2` to restrict to uniform buffers and max 256 lights. use std::f64::consts::PI; use bevy::{ camera::ScalingMode, color::palettes::css::DEEP_PINK, diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, math::{DVec2, DVec3}, pbr::{ExtractedPointLight, GlobalClusterableObjectMeta}, prelude::*, render::{Render, RenderApp, RenderSystems}, window::{PresentMode, WindowResolution}, winit::WinitSettings, }; use rand::{rng, Rng}; fn main() { App::new() .add_plugins(( DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0), title: "many_lights".into(), present_mode: PresentMode::AutoNoVsync, ..default() }), ..default() }), FrameTimeDiagnosticsPlugin::default(), LogDiagnosticsPlugin::default(), LogVisibleLights, )) .insert_resource(WinitSettings::continuous()) .add_systems(Startup, setup) .add_systems(Update, (move_camera, print_light_count)) .run(); } fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { warn!(include_str!("warning_string.txt")); const LIGHT_RADIUS: f32 = 0.3; const LIGHT_INTENSITY: f32 = 1000.0; const RADIUS: f32 = 50.0; const N_LIGHTS: usize = 100_000; commands.spawn(( Mesh3d(meshes.add(Sphere::new(RADIUS).mesh().ico(9).unwrap())), MeshMaterial3d(materials.add(Color::WHITE)), Transform::from_scale(Vec3::NEG_ONE), )); let mesh = meshes.add(Cuboid::default()); let material = materials.add(StandardMaterial { base_color: DEEP_PINK.into(), ..default() }); // NOTE: This pattern is good for testing performance of culling as it provides roughly // the same number of visible meshes regardless of the viewing angle. // NOTE: f64 is used to avoid precision issues that produce visual artifacts in the distribution let golden_ratio = 0.5f64 * (1.0f64 + 5.0f64.sqrt()); // Spawn N_LIGHTS many lights commands.spawn_batch((0..N_LIGHTS).map(move |i| { let mut rng = rng(); let spherical_polar_theta_phi = fibonacci_spiral_on_sphere(golden_ratio, i, N_LIGHTS); let unit_sphere_p = spherical_polar_to_cartesian(spherical_polar_theta_phi); ( PointLight { range: LIGHT_RADIUS, intensity: LIGHT_INTENSITY, color: Color::hsl(rng.random_range(0.0..360.0), 1.0, 0.5), ..default() }, Transform::from_translation((RADIUS as f64 * unit_sphere_p).as_vec3()), ) })); // camera match std::env::args().nth(1).as_deref() { Some("orthographic") => commands.spawn(( Camera3d::default(), Projection::from(OrthographicProjection { scaling_mode: ScalingMode::FixedHorizontal { viewport_width: 20.0, }, ..OrthographicProjection::default_3d() }), )), _ => commands.spawn(Camera3d::default()), }; // add one cube, the only one with strong handles // also serves as a reference point during rotation commands.spawn(( Mesh3d(mesh), MeshMaterial3d(material), Transform { translation: Vec3::new(0.0, RADIUS, 0.0), scale: Vec3::splat(5.0), ..default() }, )); } // NOTE: This epsilon value is apparently optimal for optimizing for the average // nearest-neighbor distance. See: // http://extremelearning.com.au/how-to-evenly-distribute-points-on-a-sphere-more-effectively-than-the-canonical-fibonacci-lattice/ // for details. const EPSILON: f64 = 0.36; fn fibonacci_spiral_on_sphere(golden_ratio: f64, i: usize, n: usize) -> DVec2 { DVec2::new( PI * 2. * (i as f64 / golden_ratio), ops::acos((1.0 - 2.0 * (i as f64 + EPSILON) / (n as f64 - 1.0 + 2.0 * EPSILON)) as f32) as f64, ) } fn spherical_polar_to_cartesian(p: DVec2) -> DVec3 { let (sin_theta, cos_theta) = p.x.sin_cos(); let (sin_phi, cos_phi) = p.y.sin_cos(); DVec3::new(cos_theta * sin_phi, sin_theta * sin_phi, cos_phi) } // System for rotating the camera fn move_camera(time: Res<Time>, mut camera_transform: Single<&mut Transform, With<Camera>>) { let delta = time.delta_secs() * 0.15; camera_transform.rotate_z(delta); camera_transform.rotate_x(delta); } // System for printing the number of meshes on every tick of the timer fn print_light_count(time: Res<Time>, mut timer: Local<PrintingTimer>, lights: Query<&PointLight>) { timer.0.tick(time.delta()); if timer.0.just_finished() { info!("Lights: {}", lights.iter().len()); } } struct LogVisibleLights; impl Plugin for LogVisibleLights { fn build(&self, app: &mut App) { let Some(render_app) = app.get_sub_app_mut(RenderApp) else { return; }; render_app.add_systems( Render, print_visible_light_count.in_set(RenderSystems::Prepare), ); } } // System for printing the number of meshes on every tick of the timer fn print_visible_light_count( time: Res<Time>, mut timer: Local<PrintingTimer>, visible: Query<&ExtractedPointLight>, global_light_meta: Res<GlobalClusterableObjectMeta>, ) { timer.0.tick(time.delta()); if timer.0.just_finished() { info!( "Visible Lights: {}, Rendered Lights: {}", visible.iter().len(), global_light_meta.entity_to_index.len() ); } } struct PrintingTimer(Timer); impl Default for PrintingTimer { fn default() -> Self { Self(Timer::from_seconds(1.0, TimerMode::Repeating)) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/app/log_layers_ecs.rs
examples/app/log_layers_ecs.rs
//! This example illustrates how to transfer log events from the [`Layer`] to Bevy's ECS. //! //! The way we will do this is via a [`mpsc`] channel. [`mpsc`] channels allow 2 unrelated //! parts of the program to communicate (in this case, [`Layer`]s and Bevy's ECS). //! //! Inside the `custom_layer` function we will create a [`mpsc::Sender`] and a [`mpsc::Receiver`] from a //! [`mpsc::channel`]. The [`Sender`](mpsc::Sender) will go into the `AdvancedLayer` and the [`Receiver`](mpsc::Receiver) will //! go into a non-send resource called `LogEvents` (It has to be non-send because [`Receiver`](mpsc::Receiver) is [`!Sync`](Sync)). //! From there we will use [`transfer_log_messages`] to transfer log messages from [`CapturedLogMessages`] to an ECS message called [`LogMessage`]. //! //! Finally, after all that we can access the [`LogMessage`] message from our systems and use it. //! In this example we build a simple log viewer. use std::sync::mpsc; use bevy::{ log::{ tracing::{self, Subscriber}, tracing_subscriber::{self, Layer}, BoxedLayer, Level, }, prelude::*, }; fn main() { App::new() .add_plugins(DefaultPlugins.set(bevy::log::LogPlugin { // Show logs all the way up to the trace level, but only for logs // produced by this example. level: Level::TRACE, filter: "warn,log_layers_ecs=trace".to_string(), custom_layer, ..default() })) .add_systems(Startup, (log_system, setup)) .add_systems(Update, print_logs) .run(); } /// A basic message. This is what we will be sending from the [`CaptureLayer`] to [`CapturedLogMessages`] non-send resource. #[derive(Debug, Message)] struct LogMessage { message: String, level: Level, } /// This non-send resource temporarily stores [`LogMessage`]s before they are /// written to [`Messages<LogEvent>`] by [`transfer_log_messages`]. #[derive(Deref, DerefMut)] struct CapturedLogMessages(mpsc::Receiver<LogMessage>); /// Transfers information from the [`CapturedLogMessages`] resource to [`Messages<LogEvent>`](LogMessage). fn transfer_log_messages( receiver: NonSend<CapturedLogMessages>, mut message_writer: MessageWriter<LogMessage>, ) { // Make sure to use `try_iter()` and not `iter()` to prevent blocking. message_writer.write_batch(receiver.try_iter()); } /// This is the [`Layer`] that we will use to capture log messages and then send them to Bevy's /// ECS via its [`mpsc::Sender`]. struct CaptureLayer { sender: mpsc::Sender<LogMessage>, } impl<S: Subscriber> Layer<S> for CaptureLayer { fn on_event( &self, event: &tracing::Event<'_>, _ctx: tracing_subscriber::layer::Context<'_, S>, ) { // In order to obtain the log message, we have to create a struct that implements // Visit and holds a reference to our string. Then we use the `record` method and // the struct to modify the reference to hold the message string. let mut message = None; event.record(&mut CaptureLayerVisitor(&mut message)); if let Some(message) = message { let metadata = event.metadata(); self.sender .send(LogMessage { message, level: *metadata.level(), }) .expect("LogEvents resource no longer exists!"); } } } /// A [`Visit`](tracing::field::Visit)or that records log messages that are transferred to [`CaptureLayer`]. struct CaptureLayerVisitor<'a>(&'a mut Option<String>); impl tracing::field::Visit for CaptureLayerVisitor<'_> { fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) { // This if statement filters out unneeded events sometimes show up if field.name() == "message" { *self.0 = Some(format!("{value:?}")); } } } fn custom_layer(app: &mut App) -> Option<BoxedLayer> { let (sender, receiver) = mpsc::channel(); let layer = CaptureLayer { sender }; let resource = CapturedLogMessages(receiver); app.insert_non_send_resource(resource); app.add_message::<LogMessage>(); app.add_systems(Update, transfer_log_messages); Some(layer.boxed()) } fn log_system() { // Here is how you write new logs at each "log level" (in "most important" to // "least important" order) error!("Something failed"); warn!("Something bad happened that isn't a failure, but thats worth calling out"); info!("Helpful information that is worth printing by default"); debug!("Helpful for debugging"); trace!("Very noisy"); } #[derive(Component)] struct LogViewerRoot; fn setup(mut commands: Commands) { commands.spawn(Camera2d); commands.spawn(( Node { width: vw(100), height: vh(100), flex_direction: FlexDirection::Column, padding: UiRect::all(px(12)), ..default() }, LogViewerRoot, )); } // This is how we can read our LogMessages. // In this example we are reading the LogMessages and inserting them as text into our log viewer. fn print_logs( mut log_message_reader: MessageReader<LogMessage>, mut commands: Commands, log_viewer_root: Single<Entity, With<LogViewerRoot>>, ) { let root_entity = *log_viewer_root; commands.entity(root_entity).with_children(|child| { for log_message in log_message_reader.read() { child.spawn(( Text::default(), children![ ( TextSpan::new(format!("{:5} ", log_message.level)), TextColor(level_color(&log_message.level)), ), TextSpan::new(&log_message.message), ], )); } }); } fn level_color(level: &Level) -> Color { use bevy::color::palettes::tailwind::*; Color::from(match *level { Level::WARN => ORANGE_400, Level::ERROR => RED_400, Level::INFO => GREEN_400, Level::TRACE => PURPLE_400, Level::DEBUG => BLUE_400, }) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/app/thread_pool_resources.rs
examples/app/thread_pool_resources.rs
//! This example illustrates how to customize the thread pool used internally (e.g. to only use a //! certain number of threads). use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins.set(TaskPoolPlugin { task_pool_options: TaskPoolOptions::with_num_threads(4), })) .run(); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/app/empty_defaults.rs
examples/app/empty_defaults.rs
//! An empty application with default plugins. use bevy::prelude::*; fn main() { App::new().add_plugins(DefaultPlugins).run(); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/app/custom_loop.rs
examples/app/custom_loop.rs
//! This example demonstrates you can create a custom runner (to update an app manually). It reads //! lines from stdin and prints them from within the ecs. use bevy::{app::AppExit, prelude::*}; use std::io; #[derive(Resource)] struct Input(String); fn my_runner(mut app: App) -> AppExit { // Finalize plugin building, including running any necessary clean-up. // This is normally completed by the default runner. app.finish(); app.cleanup(); println!("Type stuff into the console"); for line in io::stdin().lines() { { let mut input = app.world_mut().resource_mut::<Input>(); input.0 = line.unwrap(); } app.update(); if let Some(exit) = app.should_exit() { return exit; } } AppExit::Success } fn print_system(input: Res<Input>) { println!("You typed: {}", input.0); } fn exit_system(input: Res<Input>, mut app_exit_reader: MessageWriter<AppExit>) { if input.0 == "exit" { app_exit_reader.write(AppExit::Success); } } // AppExit implements `Termination` so we can return it from main. fn main() -> AppExit { App::new() .insert_resource(Input(String::new())) .set_runner(my_runner) .add_systems(Update, (print_system, exit_system)) .run() }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/app/headless_renderer.rs
examples/app/headless_renderer.rs
//! This example illustrates how to make a headless renderer. //! Derived from: <https://sotrh.github.io/learn-wgpu/showcase/windowless/#a-triangle-without-a-window> //! It follows these steps: //! //! 1. Render from camera to gpu-image render target //! 2. Copy from gpu image to buffer using `ImageCopyDriver` node in `RenderGraph` //! 3. Copy from buffer to channel using `receive_image_from_buffer` after `RenderSystems::Render` //! 4. Save from channel to random named file using `scene::update` at `PostUpdate` in `MainWorld` //! 5. Exit if `single_image` setting is set //! //! If your goal is to capture a single “screenshot” as opposed to every single rendered frame //! without gaps, it is simpler to use [`bevy::render::view::window::screenshot::Screenshot`] //! than this approach. use bevy::{ app::{AppExit, ScheduleRunnerPlugin}, camera::RenderTarget, core_pipeline::tonemapping::Tonemapping, image::TextureFormatPixelInfo, prelude::*, render::{ render_asset::RenderAssets, render_graph::{self, NodeRunError, RenderGraph, RenderGraphContext, RenderLabel}, render_resource::{ Buffer, BufferDescriptor, BufferUsages, CommandEncoderDescriptor, Extent3d, MapMode, PollType, TexelCopyBufferInfo, TexelCopyBufferLayout, TextureFormat, TextureUsages, }, renderer::{RenderContext, RenderDevice, RenderQueue}, Extract, Render, RenderApp, RenderSystems, }, window::ExitCondition, winit::WinitPlugin, }; use crossbeam_channel::{Receiver, Sender}; use std::{ ops::{Deref, DerefMut}, path::PathBuf, sync::{ atomic::{AtomicBool, Ordering}, Arc, }, time::Duration, }; // To communicate between the main world and the render world we need a channel. // Since the main world and render world run in parallel, there will always be a frame of latency // between the data sent from the render world and the data received in the main world // // frame n => render world sends data through the channel at the end of the frame // frame n + 1 => main world receives the data // // Receiver and Sender are kept in resources because there is single camera and single target // That's why there is single images role, if you want to differentiate images // from different cameras, you should keep Receiver in ImageCopier and Sender in ImageToSave // or send some id with data /// This will receive asynchronously any data sent from the render world #[derive(Resource, Deref)] struct MainWorldReceiver(Receiver<Vec<u8>>); /// This will send asynchronously any data to the main world #[derive(Resource, Deref)] struct RenderWorldSender(Sender<Vec<u8>>); // Parameters of resulting image struct AppConfig { width: u32, height: u32, single_image: bool, } fn main() { let config = AppConfig { width: 1920, height: 1080, single_image: true, }; // setup frame capture App::new() .insert_resource(SceneController::new( config.width, config.height, config.single_image, )) .insert_resource(ClearColor(Color::srgb_u8(0, 0, 0))) .add_plugins( DefaultPlugins .set(ImagePlugin::default_nearest()) // Not strictly necessary, as the inclusion of ScheduleRunnerPlugin below // replaces the bevy_winit app runner and so a window is never created. .set(WindowPlugin { primary_window: None, // Don’t automatically exit due to having no windows. // Instead, the code in `update()` will explicitly produce an `AppExit` event. exit_condition: ExitCondition::DontExit, ..default() }) // WinitPlugin will panic in environments without a display server. .disable::<WinitPlugin>(), ) .add_plugins(ImageCopyPlugin) // headless frame capture .add_plugins(CaptureFramePlugin) // ScheduleRunnerPlugin provides an alternative to the default bevy_winit app runner, which // manages the loop without creating a window. .add_plugins(ScheduleRunnerPlugin::run_loop( // Run 60 times per second. Duration::from_secs_f64(1.0 / 60.0), )) .init_resource::<SceneController>() .add_systems(Startup, setup) .run(); } /// Capture image settings and state #[derive(Debug, Default, Resource)] struct SceneController { state: SceneState, name: String, width: u32, height: u32, single_image: bool, } impl SceneController { pub fn new(width: u32, height: u32, single_image: bool) -> SceneController { SceneController { state: SceneState::BuildScene, name: String::from(""), width, height, single_image, } } } /// Capture image state #[derive(Debug, Default)] enum SceneState { #[default] // State before any rendering BuildScene, // Rendering state, stores the number of frames remaining before saving the image Render(u32), } fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, mut images: ResMut<Assets<Image>>, mut scene_controller: ResMut<SceneController>, render_device: Res<RenderDevice>, ) { let render_target = setup_render_target( &mut commands, &mut images, &render_device, &mut scene_controller, // pre_roll_frames should be big enough for full scene render, // but the bigger it is, the longer example will run. // To visualize stages of scene rendering change this param to 0 // and change AppConfig::single_image to false in main // Stages are: // 1. Transparent image // 2. Few black box images // 3. Fully rendered scene images // Exact number depends on device speed, device load and scene size 40, "main_scene".into(), ); // Scene example for non black box picture // circular base commands.spawn(( Mesh3d(meshes.add(Circle::new(4.0))), MeshMaterial3d(materials.add(Color::WHITE)), Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)), )); // cube commands.spawn(( Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))), MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))), Transform::from_xyz(0.0, 0.5, 0.0), )); // light commands.spawn(( PointLight { shadows_enabled: true, ..default() }, Transform::from_xyz(4.0, 8.0, 4.0), )); commands.spawn(( Camera3d::default(), render_target, Tonemapping::None, Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y), )); } /// Plugin for Render world part of work pub struct ImageCopyPlugin; impl Plugin for ImageCopyPlugin { fn build(&self, app: &mut App) { let (s, r) = crossbeam_channel::unbounded(); let render_app = app .insert_resource(MainWorldReceiver(r)) .sub_app_mut(RenderApp); let mut graph = render_app.world_mut().resource_mut::<RenderGraph>(); graph.add_node(ImageCopy, ImageCopyDriver); graph.add_node_edge(bevy::render::graph::CameraDriverLabel, ImageCopy); render_app .insert_resource(RenderWorldSender(s)) // Make ImageCopiers accessible in RenderWorld system and plugin .add_systems(ExtractSchedule, image_copy_extract) // Receives image data from buffer to channel // so we need to run it after the render graph is done .add_systems( Render, receive_image_from_buffer.after(RenderSystems::Render), ); } } /// Setups render target and cpu image for saving, changes scene state into render mode fn setup_render_target( commands: &mut Commands, images: &mut ResMut<Assets<Image>>, render_device: &Res<RenderDevice>, scene_controller: &mut ResMut<SceneController>, pre_roll_frames: u32, scene_name: String, ) -> RenderTarget { let size = Extent3d { width: scene_controller.width, height: scene_controller.height, ..Default::default() }; // This is the texture that will be rendered to. let mut render_target_image = Image::new_target_texture(size.width, size.height, TextureFormat::bevy_default(), None); render_target_image.texture_descriptor.usage |= TextureUsages::COPY_SRC; let render_target_image_handle = images.add(render_target_image); // This is the texture that will be copied to. let cpu_image = Image::new_target_texture(size.width, size.height, TextureFormat::bevy_default(), None); let cpu_image_handle = images.add(cpu_image); commands.spawn(ImageCopier::new( render_target_image_handle.clone(), size, render_device, )); commands.spawn(ImageToSave(cpu_image_handle)); scene_controller.state = SceneState::Render(pre_roll_frames); scene_controller.name = scene_name; RenderTarget::Image(render_target_image_handle.into()) } /// Setups image saver pub struct CaptureFramePlugin; impl Plugin for CaptureFramePlugin { fn build(&self, app: &mut App) { info!("Adding CaptureFramePlugin"); app.add_systems(PostUpdate, update); } } /// `ImageCopier` aggregator in `RenderWorld` #[derive(Clone, Default, Resource, Deref, DerefMut)] struct ImageCopiers(pub Vec<ImageCopier>); /// Used by `ImageCopyDriver` for copying from render target to buffer #[derive(Clone, Component)] struct ImageCopier { buffer: Buffer, enabled: Arc<AtomicBool>, src_image: Handle<Image>, } impl ImageCopier { pub fn new( src_image: Handle<Image>, size: Extent3d, render_device: &RenderDevice, ) -> ImageCopier { let padded_bytes_per_row = RenderDevice::align_copy_bytes_per_row((size.width) as usize) * 4; let cpu_buffer = render_device.create_buffer(&BufferDescriptor { label: None, size: padded_bytes_per_row as u64 * size.height as u64, usage: BufferUsages::MAP_READ | BufferUsages::COPY_DST, mapped_at_creation: false, }); ImageCopier { buffer: cpu_buffer, src_image, enabled: Arc::new(AtomicBool::new(true)), } } pub fn enabled(&self) -> bool { self.enabled.load(Ordering::Relaxed) } } /// Extracting `ImageCopier`s into render world, because `ImageCopyDriver` accesses them fn image_copy_extract(mut commands: Commands, image_copiers: Extract<Query<&ImageCopier>>) { commands.insert_resource(ImageCopiers( image_copiers.iter().cloned().collect::<Vec<ImageCopier>>(), )); } /// `RenderGraph` label for `ImageCopyDriver` #[derive(Debug, PartialEq, Eq, Clone, Hash, RenderLabel)] struct ImageCopy; /// `RenderGraph` node #[derive(Default)] struct ImageCopyDriver; // Copies image content from render target to buffer impl render_graph::Node for ImageCopyDriver { fn run( &self, _graph: &mut RenderGraphContext, render_context: &mut RenderContext, world: &World, ) -> Result<(), NodeRunError> { let image_copiers = world.get_resource::<ImageCopiers>().unwrap(); let gpu_images = world .get_resource::<RenderAssets<bevy::render::texture::GpuImage>>() .unwrap(); for image_copier in image_copiers.iter() { if !image_copier.enabled() { continue; } let src_image = gpu_images.get(&image_copier.src_image).unwrap(); let mut encoder = render_context .render_device() .create_command_encoder(&CommandEncoderDescriptor::default()); let block_dimensions = src_image.texture_format.block_dimensions(); let block_size = src_image.texture_format.block_copy_size(None).unwrap(); // Calculating correct size of image row because // copy_texture_to_buffer can copy image only by rows aligned wgpu::COPY_BYTES_PER_ROW_ALIGNMENT // That's why image in buffer can be little bit wider // This should be taken into account at copy from buffer stage let padded_bytes_per_row = RenderDevice::align_copy_bytes_per_row( (src_image.size.width as usize / block_dimensions.0 as usize) * block_size as usize, ); encoder.copy_texture_to_buffer( src_image.texture.as_image_copy(), TexelCopyBufferInfo { buffer: &image_copier.buffer, layout: TexelCopyBufferLayout { offset: 0, bytes_per_row: Some( std::num::NonZero::<u32>::new(padded_bytes_per_row as u32) .unwrap() .into(), ), rows_per_image: None, }, }, src_image.size, ); let render_queue = world.get_resource::<RenderQueue>().unwrap(); render_queue.submit(std::iter::once(encoder.finish())); } Ok(()) } } /// runs in render world after Render stage to send image from buffer via channel (receiver is in main world) fn receive_image_from_buffer( image_copiers: Res<ImageCopiers>, render_device: Res<RenderDevice>, sender: Res<RenderWorldSender>, ) { for image_copier in image_copiers.0.iter() { if !image_copier.enabled() { continue; } // Finally time to get our data back from the gpu. // First we get a buffer slice which represents a chunk of the buffer (which we // can't access yet). // We want the whole thing so use unbounded range. let buffer_slice = image_copier.buffer.slice(..); // Now things get complicated. WebGPU, for safety reasons, only allows either the GPU // or CPU to access a buffer's contents at a time. We need to "map" the buffer which means // flipping ownership of the buffer over to the CPU and making access legal. We do this // with `BufferSlice::map_async`. // // The problem is that map_async is not an async function so we can't await it. What // we need to do instead is pass in a closure that will be executed when the slice is // either mapped or the mapping has failed. // // The problem with this is that we don't have a reliable way to wait in the main // code for the buffer to be mapped and even worse, calling get_mapped_range or // get_mapped_range_mut prematurely will cause a panic, not return an error. // // Using channels solves this as awaiting the receiving of a message from // the passed closure will force the outside code to wait. It also doesn't hurt // if the closure finishes before the outside code catches up as the message is // buffered and receiving will just pick that up. // // It may also be worth noting that although on native, the usage of asynchronous // channels is wholly unnecessary, for the sake of portability to Wasm // we'll use async channels that work on both native and Wasm. let (s, r) = crossbeam_channel::bounded(1); // Maps the buffer so it can be read on the cpu buffer_slice.map_async(MapMode::Read, move |r| match r { // This will execute once the gpu is ready, so after the call to poll() Ok(r) => s.send(r).expect("Failed to send map update"), Err(err) => panic!("Failed to map buffer {err}"), }); // In order for the mapping to be completed, one of three things must happen. // One of those can be calling `Device::poll`. This isn't necessary on the web as devices // are polled automatically but natively, we need to make sure this happens manually. // `Maintain::Wait` will cause the thread to wait on native but not on WebGpu. // This blocks until the gpu is done executing everything render_device .poll(PollType::wait_indefinitely()) .expect("Failed to poll device for map async"); // This blocks until the buffer is mapped r.recv().expect("Failed to receive the map_async message"); // This could fail on app exit, if Main world clears resources (including receiver) while Render world still renders let _ = sender.send(buffer_slice.get_mapped_range().to_vec()); // We need to make sure all `BufferView`'s are dropped before we do what we're about // to do. // Unmap so that we can copy to the staging buffer in the next iteration. image_copier.buffer.unmap(); } } /// CPU-side image for saving #[derive(Component, Deref, DerefMut)] struct ImageToSave(Handle<Image>); // Takes from channel image content sent from render world and saves it to disk fn update( images_to_save: Query<&ImageToSave>, receiver: Res<MainWorldReceiver>, mut images: ResMut<Assets<Image>>, mut scene_controller: ResMut<SceneController>, mut app_exit_writer: MessageWriter<AppExit>, mut file_number: Local<u32>, ) { if let SceneState::Render(n) = scene_controller.state { if n < 1 { // We don't want to block the main world on this, // so we use try_recv which attempts to receive without blocking let mut image_data = Vec::new(); while let Ok(data) = receiver.try_recv() { // image generation could be faster than saving to fs, // that's why use only last of them image_data = data; } if !image_data.is_empty() { for image in images_to_save.iter() { // Fill correct data from channel to image let img_bytes = images.get_mut(image.id()).unwrap(); // We need to ensure that this works regardless of the image dimensions // If the image became wider when copying from the texture to the buffer, // then the data is reduced to its original size when copying from the buffer to the image. let row_bytes = img_bytes.width() as usize * img_bytes.texture_descriptor.format.pixel_size().unwrap(); let aligned_row_bytes = RenderDevice::align_copy_bytes_per_row(row_bytes); if row_bytes == aligned_row_bytes { img_bytes.data.as_mut().unwrap().clone_from(&image_data); } else { // shrink data to original image size img_bytes.data = Some( image_data .chunks(aligned_row_bytes) .take(img_bytes.height() as usize) .flat_map(|row| &row[..row_bytes.min(row.len())]) .cloned() .collect(), ); } // Create RGBA Image Buffer let img = match img_bytes.clone().try_into_dynamic() { Ok(img) => img.to_rgba8(), Err(e) => panic!("Failed to create image buffer {e:?}"), }; // Prepare directory for images, test_images in bevy folder is used here for example // You should choose the path depending on your needs let images_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("test_images"); info!("Saving image to: {images_dir:?}"); std::fs::create_dir_all(&images_dir).unwrap(); // Choose filename starting from 000.png let image_path = images_dir.join(format!("{:03}.png", file_number.deref())); *file_number.deref_mut() += 1; // Finally saving image to file, this heavy blocking operation is kept here // for example simplicity, but in real app you should move it to a separate task if let Err(e) = img.save(image_path) { panic!("Failed to save image: {e}"); }; } if scene_controller.single_image { app_exit_writer.write(AppExit::Success); } } } else { // clears channel for skipped frames while receiver.try_recv().is_ok() {} scene_controller.state = SceneState::Render(n - 1); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/app/log_layers.rs
examples/app/log_layers.rs
//! This example illustrates how to add custom log layers in bevy. use bevy::{ log::{ tracing::{self, Subscriber}, tracing_subscriber::{field::MakeExt, Layer}, BoxedFmtLayer, BoxedLayer, }, prelude::*, }; struct CustomLayer; impl<S: Subscriber> Layer<S> for CustomLayer { fn on_event( &self, event: &tracing::Event<'_>, _ctx: bevy::log::tracing_subscriber::layer::Context<'_, S>, ) { println!("Got event!"); println!(" level={}", event.metadata().level()); println!(" target={}", event.metadata().target()); println!(" name={}", event.metadata().name()); } } // We don't need App for this example, as we are just printing log information. // For an example that uses App, see log_layers_ecs. fn custom_layer(_app: &mut App) -> Option<BoxedLayer> { // You can provide multiple layers like this, since Vec<Layer> is also a layer: Some(Box::new(vec![ bevy::log::tracing_subscriber::fmt::layer() .with_file(true) .boxed(), CustomLayer.boxed(), ])) } // While `custom_layer` allows you to add _additional_ layers, it won't allow you to override the // default `tracing_subscriber::fmt::Layer` added by `LogPlugin`. To do that, you can use the // `fmt_layer` option. // // In this example, we're disabling the timestamp in the log output and enabling the alternative debugging format. // This formatting inserts newlines into logs that use the debug sigil (`?`) like `info!(foo=?bar)` fn fmt_layer(_app: &mut App) -> Option<BoxedFmtLayer> { Some(Box::new( bevy::log::tracing_subscriber::fmt::Layer::default() .without_time() .map_fmt_fields(MakeExt::debug_alt) .with_writer(std::io::stderr), )) } fn main() { App::new() .add_plugins(DefaultPlugins.set(bevy::log::LogPlugin { custom_layer, fmt_layer, ..default() })) .add_systems(Update, log_system) .run(); } fn log_system() { // here is how you write new logs at each "log level" (in "most important" to // "least important" order) error!("something failed"); warn!("something bad happened that isn't a failure, but thats worth calling out"); info!("helpful information that is worth printing by default"); let secret_message = "Bevy"; info!(?secret_message, "Here's a log that uses the debug sigil"); debug!("helpful for debugging"); trace!("very noisy"); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/app/plugin_group.rs
examples/app/plugin_group.rs
//! Demonstrates the creation and registration of a custom plugin group. //! [`PluginGroup`]s are a way to group sets of plugins that should be registered together. use bevy::{app::PluginGroupBuilder, prelude::*}; fn main() { App::new() .add_plugins(( // Two PluginGroups that are included with bevy are DefaultPlugins and MinimalPlugins DefaultPlugins, // Adding a plugin group adds all plugins in the group by default HelloWorldPlugins, )) // You can also modify a PluginGroup (such as disabling plugins) like this: // .add_plugins( // HelloWorldPlugins // .build() // .disable::<PrintWorldPlugin>() // .add_before::<PrintHelloPlugin>( // bevy::diagnostic::LogDiagnosticsPlugin::default(), // ), // ) .run(); } /// A group of plugins that produce the "hello world" behavior pub struct HelloWorldPlugins; impl PluginGroup for HelloWorldPlugins { fn build(self) -> PluginGroupBuilder { PluginGroupBuilder::start::<Self>() .add(PrintHelloPlugin) .add(PrintWorldPlugin) } } struct PrintHelloPlugin; impl Plugin for PrintHelloPlugin { fn build(&self, app: &mut App) { app.add_systems(Update, print_hello_system); } } fn print_hello_system() { info!("hello"); } struct PrintWorldPlugin; impl Plugin for PrintWorldPlugin { fn build(&self, app: &mut App) { app.add_systems(Update, print_world_system); } } fn print_world_system() { info!("world"); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/app/empty.rs
examples/app/empty.rs
//! An empty application (does nothing) use bevy::prelude::*; fn main() { App::new().run(); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/app/headless.rs
examples/app/headless.rs
//! This example shows how to configure the `ScheduleRunnerPlugin` to run your //! application without windowing. You can completely remove rendering / windowing //! Plugin code from bevy by making your import look like this in your Cargo.toml. //! //! ```toml //! [dependencies] //! bevy = { version = "*", default-features = false } //! # replace "*" with the most recent version of bevy //! ``` //! //! And then enabling the features you need. //! See the full list: <https://docs.rs/bevy/latest/bevy/#cargo-features> use bevy::{app::ScheduleRunnerPlugin, log::LogPlugin, prelude::*}; use core::time::Duration; fn main() { if cfg!(feature = "bevy_window") { println!("This example is running with the bevy_window feature enabled and will not run headless."); println!("Disable the default features and rerun the example to run headless."); println!("To do so, run:"); println!(); println!(" cargo run --example headless --no-default-features --features bevy_log"); return; } // This app runs once App::new() .add_plugins(DefaultPlugins.set(ScheduleRunnerPlugin::run_once())) .add_systems(Update, hello_world_system) .run(); // This app loops forever at 60 fps App::new() .add_plugins( DefaultPlugins .set(ScheduleRunnerPlugin::run_loop(Duration::from_secs_f64( 1.0 / 60.0, ))) // The log and ctrl+c plugin can only be registered once globally, // which means we need to disable it here, because it was already registered with the // app that runs once. .disable::<LogPlugin>(), ) .add_systems(Update, counter) .run(); } fn hello_world_system() { println!("hello world"); } fn counter(mut state: Local<CounterState>) { if state.count.is_multiple_of(60) { println!("{}", state.count); } state.count += 1; } #[derive(Default)] struct CounterState { count: u32, }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/app/without_winit.rs
examples/app/without_winit.rs
//! Create an application without winit (runs single time, no event loop). use bevy::{prelude::*, winit::WinitPlugin}; fn main() { App::new() .add_plugins(DefaultPlugins.build().disable::<WinitPlugin>()) .add_systems(Update, setup_system) .run(); } fn setup_system(mut commands: Commands) { commands.spawn(Camera3d::default()); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/app/drag_and_drop.rs
examples/app/drag_and_drop.rs
//! An example that shows how to handle drag and drop of files in an app. use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Update, file_drag_and_drop_system) .run(); } fn file_drag_and_drop_system(mut drag_and_drop_reader: MessageReader<FileDragAndDrop>) { for drag_and_drop in drag_and_drop_reader.read() { info!("{:?}", drag_and_drop); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/app/logs.rs
examples/app/logs.rs
//! This example illustrates how to use logs in bevy. use bevy::{log::once, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins.set(bevy::log::LogPlugin { // Uncomment this to override the default log settings: // level: bevy::log::Level::TRACE, // filter: "wgpu=warn,bevy_ecs=info".to_string(), ..default() })) .add_systems(Startup, setup) .add_systems(Update, log_system) .add_systems(Update, log_once_system) .add_systems(Update, panic_on_p) .run(); } fn setup(mut commands: Commands) { commands.spawn(Camera2d); commands.spawn(( Text::new("Press P to panic"), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, )); } fn panic_on_p(keys: Res<ButtonInput<KeyCode>>) { if keys.just_pressed(KeyCode::KeyP) { panic!("P pressed, panicking"); } } fn log_system() { // here is how you write new logs at each "log level" (in "least important" to "most important" // order) trace!("very noisy"); debug!("helpful for debugging"); info!("helpful information that is worth printing by default"); warn!("something bad happened that isn't a failure, but thats worth calling out"); error!("something failed"); // by default, trace and debug logs are ignored because they are "noisy" // you can control what level is logged by setting up the LogPlugin // alternatively you can set the log level via the RUST_LOG=LEVEL environment variable // ex: RUST_LOG=trace, RUST_LOG=info,bevy_ecs=warn // the format used here is super flexible. check out this documentation for more info: // https://docs.rs/tracing-subscriber/*/tracing_subscriber/filter/struct.EnvFilter.html } fn log_once_system() { // The 'once' variants of each log level are useful when a system is called every frame, // but we still wish to inform the user only once. In other words, use these to prevent spam :) trace_once!("one time noisy message"); debug_once!("one time debug message"); info_once!("some info which is printed only once"); warn_once!("some warning we wish to call out only once"); error_once!("some error we wish to report only once"); for i in 0..10 { info_once!("logs once per call site, so this works just fine: {}", i); } // you can also use the `once!` macro directly, // in situations where you want to do something expensive only once // within the context of a continuous system. once!({ info!("doing expensive things"); let mut a: u64 = 0; for i in 0..100000000 { a += i; } info!("result of some expensive one time calculation: {}", a); }); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/app/no_renderer.rs
examples/app/no_renderer.rs
//! An application that runs with default plugins and displays an empty //! window, but without an actual renderer. //! This can be very useful for integration tests or CI. //! //! See also the `headless` example which does not display a window. use bevy::{ prelude::*, render::{settings::WgpuSettings, RenderPlugin}, }; fn main() { App::new() .add_plugins( DefaultPlugins.set(RenderPlugin { render_creation: WgpuSettings { backends: None, ..default() } .into(), ..default() }), ) .run(); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/app/return_after_run.rs
examples/app/return_after_run.rs
//! Shows how to return to the calling function after a windowed Bevy app has exited. //! //! In windowed *Bevy* applications, executing code below a call to `App::run()` is //! not recommended because: //! - `App::run()` will never return on iOS and Web. //! - It is not possible to recreate a window after the event loop has been terminated. use bevy::prelude::*; fn main() { println!("Running Bevy App"); App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "Close the window to return to the main function".into(), ..default() }), ..default() })) .add_systems(Update, system) .run(); println!("Bevy App has exited. We are back in our main function."); } fn system() { info!("Logging from Bevy App"); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/app/plugin.rs
examples/app/plugin.rs
//! Demonstrates the creation and registration of a custom plugin. //! //! Plugins are the foundation of Bevy. They are scoped sets of components, resources, and systems //! that provide a specific piece of functionality (generally the smaller the scope, the better). //! This example illustrates how to create a simple plugin that prints out a message. use bevy::prelude::*; use core::time::Duration; fn main() { App::new() // plugins are registered as part of the "app building" process .add_plugins(( DefaultPlugins, PrintMessagePlugin { wait_duration: Duration::from_secs(1), message: "This is an example plugin".to_string(), }, )) .run(); } // This "print message plugin" prints a `message` every `wait_duration` struct PrintMessagePlugin { // Put your plugin configuration here wait_duration: Duration, message: String, } impl Plugin for PrintMessagePlugin { // this is where we set up our plugin fn build(&self, app: &mut App) { let state = PrintMessageState { message: self.message.clone(), timer: Timer::new(self.wait_duration, TimerMode::Repeating), }; app.insert_resource(state) .add_systems(Update, print_message_system); } } #[derive(Resource)] struct PrintMessageState { message: String, timer: Timer, } fn print_message_system(mut state: ResMut<PrintMessageState>, time: Res<Time>) { if state.timer.tick(time.delta()).is_finished() { info!("{}", state.message); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/tonemapping.rs
examples/3d/tonemapping.rs
//! This examples compares Tonemapping options use bevy::{ asset::UnapprovedPathMode, core_pipeline::tonemapping::Tonemapping, light::CascadeShadowConfigBuilder, platform::collections::HashMap, prelude::*, reflect::TypePath, render::{ render_resource::AsBindGroup, view::{ColorGrading, ColorGradingGlobal, ColorGradingSection, Hdr}, }, shader::ShaderRef, }; use std::f32::consts::PI; /// This example uses a shader source file from the assets subdirectory const SHADER_ASSET_PATH: &str = "shaders/tonemapping_test_patterns.wgsl"; fn main() { App::new() .add_plugins(( DefaultPlugins.set(AssetPlugin { // We enable loading assets from arbitrary filesystem paths as this example allows // drag and dropping a local image for color grading unapproved_path_mode: UnapprovedPathMode::Allow, ..default() }), MaterialPlugin::<ColorGradientMaterial>::default(), )) .insert_resource(CameraTransform( Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y), )) .init_resource::<PerMethodSettings>() .insert_resource(CurrentScene(1)) .insert_resource(SelectedParameter { value: 0, max: 4 }) .add_systems( Startup, ( setup, setup_basic_scene, setup_color_gradient_scene, setup_image_viewer_scene, ), ) .add_systems( Update, ( drag_drop_image, resize_image, toggle_scene, toggle_tonemapping_method, update_color_grading_settings, update_ui, ), ) .run(); } fn setup( mut commands: Commands, asset_server: Res<AssetServer>, camera_transform: Res<CameraTransform>, ) { // camera commands.spawn(( Camera3d::default(), Hdr, camera_transform.0, DistanceFog { color: Color::srgb_u8(43, 44, 47), falloff: FogFalloff::Linear { start: 1.0, end: 8.0, }, ..default() }, EnvironmentMapLight { diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"), specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"), intensity: 2000.0, ..default() }, )); // ui commands.spawn(( Text::default(), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, )); } fn setup_basic_scene(mut commands: Commands, asset_server: Res<AssetServer>) { // Main scene commands.spawn(( SceneRoot(asset_server.load( GltfAssetLabel::Scene(0).from_asset("models/TonemappingTest/TonemappingTest.gltf"), )), SceneNumber(1), )); // Flight Helmet commands.spawn(( SceneRoot( asset_server .load(GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf")), ), Transform::from_xyz(0.5, 0.0, -0.5).with_rotation(Quat::from_rotation_y(-0.15 * PI)), SceneNumber(1), )); // light commands.spawn(( DirectionalLight { illuminance: 15_000., shadows_enabled: true, ..default() }, Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, PI * -0.15, PI * -0.15)), CascadeShadowConfigBuilder { maximum_distance: 3.0, first_cascade_far_bound: 0.9, ..default() } .build(), SceneNumber(1), )); } fn setup_color_gradient_scene( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorGradientMaterial>>, camera_transform: Res<CameraTransform>, ) { let mut transform = camera_transform.0; transform.translation += *transform.forward(); commands.spawn(( Mesh3d(meshes.add(Rectangle::new(0.7, 0.7))), MeshMaterial3d(materials.add(ColorGradientMaterial {})), transform, Visibility::Hidden, SceneNumber(2), )); } fn setup_image_viewer_scene( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, camera_transform: Res<CameraTransform>, ) { let mut transform = camera_transform.0; transform.translation += *transform.forward(); // exr/hdr viewer (exr requires enabling bevy feature) commands.spawn(( Mesh3d(meshes.add(Rectangle::default())), MeshMaterial3d(materials.add(StandardMaterial { base_color_texture: None, unlit: true, ..default() })), transform, Visibility::Hidden, SceneNumber(3), HDRViewer, )); commands.spawn(( Text::new("Drag and drop an HDR or EXR file"), TextFont { font_size: 36.0, ..default() }, TextColor(Color::BLACK), TextLayout::new_with_justify(Justify::Center), Node { align_self: AlignSelf::Center, margin: UiRect::all(auto()), ..default() }, SceneNumber(3), Visibility::Hidden, )); } // ---------------------------------------------------------------------------- fn drag_drop_image( image_mat: Query<&MeshMaterial3d<StandardMaterial>, With<HDRViewer>>, text: Query<Entity, (With<Text>, With<SceneNumber>)>, mut materials: ResMut<Assets<StandardMaterial>>, mut drag_and_drop_reader: MessageReader<FileDragAndDrop>, asset_server: Res<AssetServer>, mut commands: Commands, ) { let Some(new_image) = drag_and_drop_reader.read().find_map(|e| match e { FileDragAndDrop::DroppedFile { path_buf, .. } => { Some(asset_server.load(path_buf.to_string_lossy().to_string())) } _ => None, }) else { return; }; for mat_h in &image_mat { if let Some(mat) = materials.get_mut(mat_h) { mat.base_color_texture = Some(new_image.clone()); // Despawn the image viewer instructions if let Ok(text_entity) = text.single() { commands.entity(text_entity).despawn(); } } } } fn resize_image( image_mesh: Query<(&MeshMaterial3d<StandardMaterial>, &Mesh3d), With<HDRViewer>>, materials: Res<Assets<StandardMaterial>>, mut meshes: ResMut<Assets<Mesh>>, images: Res<Assets<Image>>, mut image_event_reader: MessageReader<AssetEvent<Image>>, ) { for event in image_event_reader.read() { let (AssetEvent::Added { id } | AssetEvent::Modified { id }) = event else { continue; }; for (mat_h, mesh_h) in &image_mesh { let Some(mat) = materials.get(mat_h) else { continue; }; let Some(ref base_color_texture) = mat.base_color_texture else { continue; }; if *id != base_color_texture.id() { continue; }; let Some(image_changed) = images.get(*id) else { continue; }; let size = image_changed.size_f32().normalize_or_zero() * 1.4; // Resize Mesh let quad = Mesh::from(Rectangle::from_size(size)); meshes.insert(mesh_h, quad).unwrap(); } } } fn toggle_scene( keys: Res<ButtonInput<KeyCode>>, mut query: Query<(&mut Visibility, &SceneNumber)>, mut current_scene: ResMut<CurrentScene>, ) { let mut pressed = None; if keys.just_pressed(KeyCode::KeyQ) { pressed = Some(1); } else if keys.just_pressed(KeyCode::KeyW) { pressed = Some(2); } else if keys.just_pressed(KeyCode::KeyE) { pressed = Some(3); } if let Some(pressed) = pressed { current_scene.0 = pressed; for (mut visibility, scene) in query.iter_mut() { if scene.0 == pressed { *visibility = Visibility::Visible; } else { *visibility = Visibility::Hidden; } } } } fn toggle_tonemapping_method( keys: Res<ButtonInput<KeyCode>>, mut tonemapping: Single<&mut Tonemapping>, mut color_grading: Single<&mut ColorGrading>, per_method_settings: Res<PerMethodSettings>, ) { if keys.just_pressed(KeyCode::Digit1) { **tonemapping = Tonemapping::None; } else if keys.just_pressed(KeyCode::Digit2) { **tonemapping = Tonemapping::Reinhard; } else if keys.just_pressed(KeyCode::Digit3) { **tonemapping = Tonemapping::ReinhardLuminance; } else if keys.just_pressed(KeyCode::Digit4) { **tonemapping = Tonemapping::AcesFitted; } else if keys.just_pressed(KeyCode::Digit5) { **tonemapping = Tonemapping::AgX; } else if keys.just_pressed(KeyCode::Digit6) { **tonemapping = Tonemapping::SomewhatBoringDisplayTransform; } else if keys.just_pressed(KeyCode::Digit7) { **tonemapping = Tonemapping::TonyMcMapface; } else if keys.just_pressed(KeyCode::Digit8) { **tonemapping = Tonemapping::BlenderFilmic; } **color_grading = (*per_method_settings .settings .get::<Tonemapping>(&tonemapping) .as_ref() .unwrap()) .clone(); } #[derive(Resource)] struct SelectedParameter { value: i32, max: i32, } impl SelectedParameter { fn next(&mut self) { self.value = (self.value + 1).rem_euclid(self.max); } fn prev(&mut self) { self.value = (self.value - 1).rem_euclid(self.max); } } fn update_color_grading_settings( keys: Res<ButtonInput<KeyCode>>, time: Res<Time>, mut per_method_settings: ResMut<PerMethodSettings>, tonemapping: Single<&Tonemapping>, current_scene: Res<CurrentScene>, mut selected_parameter: ResMut<SelectedParameter>, ) { let color_grading = per_method_settings.settings.get_mut(*tonemapping).unwrap(); let mut dt = time.delta_secs() * 0.25; if keys.pressed(KeyCode::ArrowLeft) { dt = -dt; } if keys.just_pressed(KeyCode::ArrowDown) { selected_parameter.next(); } if keys.just_pressed(KeyCode::ArrowUp) { selected_parameter.prev(); } if keys.pressed(KeyCode::ArrowLeft) || keys.pressed(KeyCode::ArrowRight) { match selected_parameter.value { 0 => { color_grading.global.exposure += dt; } 1 => { color_grading .all_sections_mut() .for_each(|section| section.gamma += dt); } 2 => { color_grading .all_sections_mut() .for_each(|section| section.saturation += dt); } 3 => { color_grading.global.post_saturation += dt; } _ => {} } } if keys.just_pressed(KeyCode::Space) { for (_, grading) in per_method_settings.settings.iter_mut() { *grading = ColorGrading::default(); } } if keys.just_pressed(KeyCode::Enter) && current_scene.0 == 1 { for (mapper, grading) in per_method_settings.settings.iter_mut() { *grading = PerMethodSettings::basic_scene_recommendation(*mapper); } } } fn update_ui( mut text_query: Single<&mut Text, Without<SceneNumber>>, settings: Single<(&Tonemapping, &ColorGrading)>, current_scene: Res<CurrentScene>, selected_parameter: Res<SelectedParameter>, mut hide_ui: Local<bool>, keys: Res<ButtonInput<KeyCode>>, ) { if keys.just_pressed(KeyCode::KeyH) { *hide_ui = !*hide_ui; } if *hide_ui { if !text_query.is_empty() { // single_mut() always triggers change detection, // so only access if text actually needs changing text_query.clear(); } return; } let (tonemapping, color_grading) = *settings; let tonemapping = *tonemapping; let mut text = String::with_capacity(text_query.len()); let scn = current_scene.0; text.push_str("(H) Hide UI\n\n"); text.push_str("Test Scene: \n"); text.push_str(&format!( "(Q) {} Basic Scene\n", if scn == 1 { ">" } else { "" } )); text.push_str(&format!( "(W) {} Color Sweep\n", if scn == 2 { ">" } else { "" } )); text.push_str(&format!( "(E) {} Image Viewer\n", if scn == 3 { ">" } else { "" } )); text.push_str("\n\nTonemapping Method:\n"); text.push_str(&format!( "(1) {} Disabled\n", if tonemapping == Tonemapping::None { ">" } else { "" } )); text.push_str(&format!( "(2) {} Reinhard\n", if tonemapping == Tonemapping::Reinhard { "> " } else { "" } )); text.push_str(&format!( "(3) {} Reinhard Luminance\n", if tonemapping == Tonemapping::ReinhardLuminance { ">" } else { "" } )); text.push_str(&format!( "(4) {} ACES Fitted\n", if tonemapping == Tonemapping::AcesFitted { ">" } else { "" } )); text.push_str(&format!( "(5) {} AgX\n", if tonemapping == Tonemapping::AgX { ">" } else { "" } )); text.push_str(&format!( "(6) {} SomewhatBoringDisplayTransform\n", if tonemapping == Tonemapping::SomewhatBoringDisplayTransform { ">" } else { "" } )); text.push_str(&format!( "(7) {} TonyMcMapface\n", if tonemapping == Tonemapping::TonyMcMapface { ">" } else { "" } )); text.push_str(&format!( "(8) {} Blender Filmic\n", if tonemapping == Tonemapping::BlenderFilmic { ">" } else { "" } )); text.push_str("\n\nColor Grading:\n"); text.push_str("(arrow keys)\n"); if selected_parameter.value == 0 { text.push_str("> "); } text.push_str(&format!("Exposure: {:.2}\n", color_grading.global.exposure)); if selected_parameter.value == 1 { text.push_str("> "); } text.push_str(&format!("Gamma: {:.2}\n", color_grading.shadows.gamma)); if selected_parameter.value == 2 { text.push_str("> "); } text.push_str(&format!( "PreSaturation: {:.2}\n", color_grading.shadows.saturation )); if selected_parameter.value == 3 { text.push_str("> "); } text.push_str(&format!( "PostSaturation: {:.2}\n", color_grading.global.post_saturation )); text.push_str("(Space) Reset all to default\n"); if current_scene.0 == 1 { text.push_str("(Enter) Reset all to scene recommendation\n"); } if text != text_query.as_str() { // single_mut() always triggers change detection, // so only access if text actually changed text_query.0 = text; } } // ---------------------------------------------------------------------------- #[derive(Resource)] struct PerMethodSettings { settings: HashMap<Tonemapping, ColorGrading>, } impl PerMethodSettings { fn basic_scene_recommendation(method: Tonemapping) -> ColorGrading { match method { Tonemapping::Reinhard | Tonemapping::ReinhardLuminance => ColorGrading { global: ColorGradingGlobal { exposure: 0.5, ..default() }, ..default() }, Tonemapping::AcesFitted => ColorGrading { global: ColorGradingGlobal { exposure: 0.35, ..default() }, ..default() }, Tonemapping::AgX => ColorGrading::with_identical_sections( ColorGradingGlobal { exposure: -0.2, post_saturation: 1.1, ..default() }, ColorGradingSection { saturation: 1.1, ..default() }, ), _ => ColorGrading::default(), } } } impl Default for PerMethodSettings { fn default() -> Self { let mut settings = <HashMap<_, _>>::default(); for method in [ Tonemapping::None, Tonemapping::Reinhard, Tonemapping::ReinhardLuminance, Tonemapping::AcesFitted, Tonemapping::AgX, Tonemapping::SomewhatBoringDisplayTransform, Tonemapping::TonyMcMapface, Tonemapping::BlenderFilmic, ] { settings.insert( method, PerMethodSettings::basic_scene_recommendation(method), ); } Self { settings } } } impl Material for ColorGradientMaterial { fn fragment_shader() -> ShaderRef { SHADER_ASSET_PATH.into() } } #[derive(Asset, TypePath, AsBindGroup, Debug, Clone)] struct ColorGradientMaterial {} #[derive(Resource)] struct CameraTransform(Transform); #[derive(Resource)] struct CurrentScene(u32); #[derive(Component)] struct SceneNumber(u32); #[derive(Component)] struct HDRViewer;
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/scrolling_fog.rs
examples/3d/scrolling_fog.rs
//! Showcases a `FogVolume`'s density texture being scrolled over time to create //! the effect of fog moving in the wind. //! //! The density texture is a repeating 3d noise texture and the `density_texture_offset` //! is moved every frame to achieve this. //! //! The example also utilizes the jitter option of `VolumetricFog` in tandem //! with temporal anti-aliasing to improve the visual quality of the effect. //! //! The camera is looking at a pillar with the sun peaking behind it. The light //! interactions change based on the density of the fog. use bevy::{ anti_alias::taa::TemporalAntiAliasing, image::{ ImageAddressMode, ImageFilterMode, ImageLoaderSettings, ImageSampler, ImageSamplerDescriptor, }, light::{DirectionalLightShadowMap, FogVolume, VolumetricFog, VolumetricLight}, post_process::bloom::Bloom, prelude::*, }; /// Initializes the example. fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "Bevy Scrolling Fog".into(), ..default() }), ..default() })) .insert_resource(DirectionalLightShadowMap { size: 4096 }) .add_systems(Startup, setup) .add_systems(Update, scroll_fog) .run(); } /// Spawns all entities into the scene. fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, assets: Res<AssetServer>, ) { // Spawn camera with temporal anti-aliasing and a VolumetricFog configuration. commands.spawn(( Camera3d::default(), Transform::from_xyz(0.0, 2.0, 0.0).looking_at(Vec3::new(-5.0, 3.5, -6.0), Vec3::Y), Msaa::Off, TemporalAntiAliasing::default(), Bloom::default(), VolumetricFog { ambient_intensity: 0.0, jitter: 0.5, ..default() }, )); // Spawn a directional light shining at the camera with the VolumetricLight component. commands.spawn(( DirectionalLight { shadows_enabled: true, ..default() }, Transform::from_xyz(-5.0, 5.0, -7.0).looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y), VolumetricLight, )); // Spawn ground mesh. commands.spawn(( Mesh3d(meshes.add(Cuboid::new(64.0, 1.0, 64.0))), MeshMaterial3d(materials.add(StandardMaterial { base_color: Color::BLACK, perceptual_roughness: 1.0, ..default() })), Transform::from_xyz(0.0, -0.5, 0.0), )); // Spawn pillar standing between the camera and the sun. commands.spawn(( Mesh3d(meshes.add(Cuboid::new(2.0, 9.0, 2.0))), MeshMaterial3d(materials.add(Color::BLACK)), Transform::from_xyz(-10.0, 4.5, -11.0), )); // Load a repeating 3d noise texture. Make sure to set ImageAddressMode to Repeat // so that the texture wraps around as the density texture offset is moved along. // Also set ImageFilterMode to Linear so that the fog isn't pixelated. let noise_texture = assets.load_with_settings("volumes/fog_noise.ktx2", |settings: &mut _| { *settings = ImageLoaderSettings { sampler: ImageSampler::Descriptor(ImageSamplerDescriptor { address_mode_u: ImageAddressMode::Repeat, address_mode_v: ImageAddressMode::Repeat, address_mode_w: ImageAddressMode::Repeat, mag_filter: ImageFilterMode::Linear, min_filter: ImageFilterMode::Linear, mipmap_filter: ImageFilterMode::Linear, ..default() }), ..default() } }); // Spawn a FogVolume and use the repeating noise texture as its density texture. commands.spawn(( Transform::from_xyz(0.0, 32.0, 0.0).with_scale(Vec3::splat(64.0)), FogVolume { density_texture: Some(noise_texture), density_factor: 0.05, ..default() }, )); } /// Moves fog density texture offset every frame. fn scroll_fog(time: Res<Time>, mut query: Query<&mut FogVolume>) { for mut fog_volume in query.iter_mut() { fog_volume.density_texture_offset += Vec3::new(0.0, 0.0, 0.04) * time.delta_secs(); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/visibility_range.rs
examples/3d/visibility_range.rs
//! Demonstrates visibility ranges, also known as HLODs. use std::f32::consts::PI; use bevy::{ camera::visibility::VisibilityRange, core_pipeline::prepass::{DepthPrepass, NormalPrepass}, input::mouse::MouseWheel, light::{light_consts::lux::FULL_DAYLIGHT, CascadeShadowConfigBuilder}, math::vec3, prelude::*, }; // Where the camera is focused. const CAMERA_FOCAL_POINT: Vec3 = vec3(0.0, 0.3, 0.0); // Speed in units per frame. const CAMERA_KEYBOARD_ZOOM_SPEED: f32 = 0.05; // Speed in radians per frame. const CAMERA_KEYBOARD_PAN_SPEED: f32 = 0.01; // Speed in units per frame. const CAMERA_MOUSE_MOVEMENT_SPEED: f32 = 0.25; // The minimum distance that the camera is allowed to be from the model. const MIN_ZOOM_DISTANCE: f32 = 0.5; // The visibility ranges for high-poly and low-poly models respectively, when // both models are being shown. static NORMAL_VISIBILITY_RANGE_HIGH_POLY: VisibilityRange = VisibilityRange { start_margin: 0.0..0.0, end_margin: 3.0..4.0, use_aabb: false, }; static NORMAL_VISIBILITY_RANGE_LOW_POLY: VisibilityRange = VisibilityRange { start_margin: 3.0..4.0, end_margin: 8.0..9.0, use_aabb: false, }; // A visibility model that we use to always show a model (until the camera is so // far zoomed out that it's culled entirely). static SINGLE_MODEL_VISIBILITY_RANGE: VisibilityRange = VisibilityRange { start_margin: 0.0..0.0, end_margin: 8.0..9.0, use_aabb: false, }; // A visibility range that we use to completely hide a model. static INVISIBLE_VISIBILITY_RANGE: VisibilityRange = VisibilityRange { start_margin: 0.0..0.0, end_margin: 0.0..0.0, use_aabb: false, }; // Allows us to identify the main model. #[derive(Component, Debug, Clone, Copy, PartialEq)] enum MainModel { // The high-poly version. HighPoly, // The low-poly version. LowPoly, } // The current mode. #[derive(Default, Resource)] struct AppStatus { // Whether to show only one model. show_one_model_only: Option<MainModel>, // Whether to enable the prepass. prepass: bool, } // Sets up the app. fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "Bevy Visibility Range Example".into(), ..default() }), ..default() })) .init_resource::<AppStatus>() .add_systems(Startup, setup) .add_systems( Update, ( move_camera, set_visibility_ranges, update_help_text, update_mode, toggle_prepass, ), ) .run(); } // Set up a simple 3D scene. Load the two meshes. fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, asset_server: Res<AssetServer>, app_status: Res<AppStatus>, ) { // Spawn a plane. commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(50.0, 50.0))), MeshMaterial3d(materials.add(Color::srgb(0.1, 0.2, 0.1))), )); // Spawn the two HLODs. commands.spawn(( SceneRoot( asset_server .load(GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf")), ), MainModel::HighPoly, )); commands.spawn(( SceneRoot( asset_server.load( GltfAssetLabel::Scene(0) .from_asset("models/FlightHelmetLowPoly/FlightHelmetLowPoly.gltf"), ), ), MainModel::LowPoly, )); // Spawn a light. commands.spawn(( DirectionalLight { illuminance: FULL_DAYLIGHT, shadows_enabled: true, ..default() }, Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, PI * -0.15, PI * -0.15)), CascadeShadowConfigBuilder { maximum_distance: 30.0, first_cascade_far_bound: 0.9, ..default() } .build(), )); // Spawn a camera. commands .spawn(( Camera3d::default(), Transform::from_xyz(0.7, 0.7, 1.0).looking_at(CAMERA_FOCAL_POINT, Vec3::Y), )) .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: 150.0, ..default() }); // Create the text. commands.spawn(( app_status.create_text(), Node { position_type: PositionType::Absolute, bottom: px(12), left: px(12), ..default() }, )); } // We need to add the `VisibilityRange` components manually, as glTF currently // has no way to specify visibility ranges. This system watches for new meshes, // determines which `Scene` they're under, and adds the `VisibilityRange` // component as appropriate. fn set_visibility_ranges( mut commands: Commands, mut new_meshes: Query<Entity, Added<Mesh3d>>, children: Query<(Option<&ChildOf>, Option<&MainModel>)>, ) { // Loop over each newly-added mesh. for new_mesh in new_meshes.iter_mut() { // Search for the nearest ancestor `MainModel` component. let (mut current, mut main_model) = (new_mesh, None); while let Ok((child_of, maybe_main_model)) = children.get(current) { if let Some(model) = maybe_main_model { main_model = Some(model); break; } match child_of { Some(child_of) => current = child_of.parent(), None => break, } } // Add the `VisibilityRange` component. match main_model { Some(MainModel::HighPoly) => { commands .entity(new_mesh) .insert(NORMAL_VISIBILITY_RANGE_HIGH_POLY.clone()) .insert(MainModel::HighPoly); } Some(MainModel::LowPoly) => { commands .entity(new_mesh) .insert(NORMAL_VISIBILITY_RANGE_LOW_POLY.clone()) .insert(MainModel::LowPoly); } None => {} } } } // Process the movement controls. fn move_camera( keyboard_input: Res<ButtonInput<KeyCode>>, mut mouse_wheel_reader: MessageReader<MouseWheel>, mut cameras: Query<&mut Transform, With<Camera3d>>, ) { let (mut zoom_delta, mut theta_delta) = (0.0, 0.0); // Process zoom in and out via the keyboard. if keyboard_input.pressed(KeyCode::KeyW) || keyboard_input.pressed(KeyCode::ArrowUp) { zoom_delta -= CAMERA_KEYBOARD_ZOOM_SPEED; } else if keyboard_input.pressed(KeyCode::KeyS) || keyboard_input.pressed(KeyCode::ArrowDown) { zoom_delta += CAMERA_KEYBOARD_ZOOM_SPEED; } // Process left and right pan via the keyboard. if keyboard_input.pressed(KeyCode::KeyA) || keyboard_input.pressed(KeyCode::ArrowLeft) { theta_delta -= CAMERA_KEYBOARD_PAN_SPEED; } else if keyboard_input.pressed(KeyCode::KeyD) || keyboard_input.pressed(KeyCode::ArrowRight) { theta_delta += CAMERA_KEYBOARD_PAN_SPEED; } // Process zoom in and out via the mouse wheel. for mouse_wheel in mouse_wheel_reader.read() { zoom_delta -= mouse_wheel.y * CAMERA_MOUSE_MOVEMENT_SPEED; } // Update the camera transform. for transform in cameras.iter_mut() { let transform = transform.into_inner(); let direction = transform.translation.normalize_or_zero(); let magnitude = transform.translation.length(); let new_direction = Mat3::from_rotation_y(theta_delta) * direction; let new_magnitude = (magnitude + zoom_delta).max(MIN_ZOOM_DISTANCE); transform.translation = new_direction * new_magnitude; transform.look_at(CAMERA_FOCAL_POINT, Vec3::Y); } } // Toggles modes if the user requests. fn update_mode( mut meshes: Query<(&mut VisibilityRange, &MainModel)>, keyboard_input: Res<ButtonInput<KeyCode>>, mut app_status: ResMut<AppStatus>, ) { // Toggle the mode as requested. if keyboard_input.just_pressed(KeyCode::Digit1) || keyboard_input.just_pressed(KeyCode::Numpad1) { app_status.show_one_model_only = None; } else if keyboard_input.just_pressed(KeyCode::Digit2) || keyboard_input.just_pressed(KeyCode::Numpad2) { app_status.show_one_model_only = Some(MainModel::HighPoly); } else if keyboard_input.just_pressed(KeyCode::Digit3) || keyboard_input.just_pressed(KeyCode::Numpad3) { app_status.show_one_model_only = Some(MainModel::LowPoly); } else { return; } // Update the visibility ranges as appropriate. for (mut visibility_range, main_model) in meshes.iter_mut() { *visibility_range = match (main_model, app_status.show_one_model_only) { (&MainModel::HighPoly, Some(MainModel::LowPoly)) | (&MainModel::LowPoly, Some(MainModel::HighPoly)) => { INVISIBLE_VISIBILITY_RANGE.clone() } (&MainModel::HighPoly, Some(MainModel::HighPoly)) | (&MainModel::LowPoly, Some(MainModel::LowPoly)) => { SINGLE_MODEL_VISIBILITY_RANGE.clone() } (&MainModel::HighPoly, None) => NORMAL_VISIBILITY_RANGE_HIGH_POLY.clone(), (&MainModel::LowPoly, None) => NORMAL_VISIBILITY_RANGE_LOW_POLY.clone(), } } } // Toggles the prepass if the user requests. fn toggle_prepass( mut commands: Commands, cameras: Query<Entity, With<Camera3d>>, keyboard_input: Res<ButtonInput<KeyCode>>, mut app_status: ResMut<AppStatus>, ) { if !keyboard_input.just_pressed(KeyCode::Space) { return; } app_status.prepass = !app_status.prepass; for camera in cameras.iter() { if app_status.prepass { commands .entity(camera) .insert(DepthPrepass) .insert(NormalPrepass); } else { commands .entity(camera) .remove::<DepthPrepass>() .remove::<NormalPrepass>(); } } } // A system that updates the help text. 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_text(); } } impl AppStatus { // Creates and returns help text reflecting the app status. fn create_text(&self) -> Text { format!( "\ {} (1) Switch from high-poly to low-poly based on camera distance {} (2) Show only the high-poly model {} (3) Show only the low-poly model Press 1, 2, or 3 to switch which model is shown Press WASD or use the mouse wheel to move the camera Press Space to {} the prepass", if self.show_one_model_only.is_none() { '>' } else { ' ' }, if self.show_one_model_only == Some(MainModel::HighPoly) { '>' } else { ' ' }, if self.show_one_model_only == Some(MainModel::LowPoly) { '>' } else { ' ' }, if self.prepass { "disable" } else { "enable" } ) .into() } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/generate_custom_mesh.rs
examples/3d/generate_custom_mesh.rs
//! This example demonstrates how to create a custom mesh, //! assign a custom UV mapping for a custom texture, //! and how to change the UV mapping at run-time. use bevy::{ asset::RenderAssetUsages, mesh::{Indices, VertexAttributeValues}, prelude::*, render::render_resource::PrimitiveTopology, }; // Define a "marker" component to mark the custom mesh. Marker components are often used in Bevy for // filtering entities in queries with `With`, they're usually not queried directly since they don't // contain information within them. #[derive(Component)] struct CustomUV; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, input_handler) .run(); } fn setup( mut commands: Commands, asset_server: Res<AssetServer>, mut materials: ResMut<Assets<StandardMaterial>>, mut meshes: ResMut<Assets<Mesh>>, ) { // Import the custom texture. let custom_texture_handle: Handle<Image> = asset_server.load("textures/array_texture.png"); // Create and save a handle to the mesh. let cube_mesh_handle: Handle<Mesh> = meshes.add(create_cube_mesh()); // Render the mesh with the custom texture, and add the marker. commands.spawn(( Mesh3d(cube_mesh_handle), MeshMaterial3d(materials.add(StandardMaterial { base_color_texture: Some(custom_texture_handle), ..default() })), CustomUV, )); // Transform for the camera and lighting, looking at (0,0,0) (the position of the mesh). let camera_and_light_transform = Transform::from_xyz(1.8, 1.8, 1.8).looking_at(Vec3::ZERO, Vec3::Y); // Camera in 3D space. commands.spawn((Camera3d::default(), camera_and_light_transform)); // Light up the scene. commands.spawn((PointLight::default(), camera_and_light_transform)); // Text to describe the controls. commands.spawn(( Text::new("Controls:\nSpace: Change UVs\nX/Y/Z: Rotate\nR: Reset orientation"), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, )); } // System to receive input from the user, // check out examples/input/ for more examples about user input. fn input_handler( keyboard_input: Res<ButtonInput<KeyCode>>, mesh_query: Query<&Mesh3d, With<CustomUV>>, mut meshes: ResMut<Assets<Mesh>>, mut query: Query<&mut Transform, With<CustomUV>>, time: Res<Time>, ) { if keyboard_input.just_pressed(KeyCode::Space) { let mesh_handle = mesh_query.single().expect("Query not successful"); let mesh = meshes.get_mut(mesh_handle).unwrap(); toggle_texture(mesh); } if keyboard_input.pressed(KeyCode::KeyX) { for mut transform in &mut query { transform.rotate_x(time.delta_secs() / 1.2); } } if keyboard_input.pressed(KeyCode::KeyY) { for mut transform in &mut query { transform.rotate_y(time.delta_secs() / 1.2); } } if keyboard_input.pressed(KeyCode::KeyZ) { for mut transform in &mut query { transform.rotate_z(time.delta_secs() / 1.2); } } if keyboard_input.pressed(KeyCode::KeyR) { for mut transform in &mut query { transform.look_to(Vec3::NEG_Z, Vec3::Y); } } } #[rustfmt::skip] fn create_cube_mesh() -> Mesh { // Keep the mesh data accessible in future frames to be able to mutate it in toggle_texture. Mesh::new(PrimitiveTopology::TriangleList, RenderAssetUsages::MAIN_WORLD | RenderAssetUsages::RENDER_WORLD) .with_inserted_attribute( Mesh::ATTRIBUTE_POSITION, // Each array is an [x, y, z] coordinate in local space. // The camera coordinate space is right-handed x-right, y-up, z-back. This means "forward" is -Z. // Meshes always rotate around their local [0, 0, 0] when a rotation is applied to their Transform. // By centering our mesh around the origin, rotating the mesh preserves its center of mass. vec![ // top (facing towards +y) [-0.5, 0.5, -0.5], // vertex with index 0 [0.5, 0.5, -0.5], // vertex with index 1 [0.5, 0.5, 0.5], // etc. until 23 [-0.5, 0.5, 0.5], // bottom (-y) [-0.5, -0.5, -0.5], [0.5, -0.5, -0.5], [0.5, -0.5, 0.5], [-0.5, -0.5, 0.5], // right (+x) [0.5, -0.5, -0.5], [0.5, -0.5, 0.5], [0.5, 0.5, 0.5], // This vertex is at the same position as vertex with index 2, but they'll have different UV and normal [0.5, 0.5, -0.5], // left (-x) [-0.5, -0.5, -0.5], [-0.5, -0.5, 0.5], [-0.5, 0.5, 0.5], [-0.5, 0.5, -0.5], // back (+z) [-0.5, -0.5, 0.5], [-0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [0.5, -0.5, 0.5], // forward (-z) [-0.5, -0.5, -0.5], [-0.5, 0.5, -0.5], [0.5, 0.5, -0.5], [0.5, -0.5, -0.5], ], ) // Set-up UV coordinates to point to the upper (V < 0.5), "dirt+grass" part of the texture. // Take a look at the custom image (assets/textures/array_texture.png) // so the UV coords will make more sense // Note: (0.0, 0.0) = Top-Left in UV mapping, (1.0, 1.0) = Bottom-Right in UV mapping .with_inserted_attribute( Mesh::ATTRIBUTE_UV_0, vec![ // Assigning the UV coords for the top side. [0.0, 0.2], [0.0, 0.0], [1.0, 0.0], [1.0, 0.2], // Assigning the UV coords for the bottom side. [0.0, 0.45], [0.0, 0.25], [1.0, 0.25], [1.0, 0.45], // Assigning the UV coords for the right side. [1.0, 0.45], [0.0, 0.45], [0.0, 0.2], [1.0, 0.2], // Assigning the UV coords for the left side. [1.0, 0.45], [0.0, 0.45], [0.0, 0.2], [1.0, 0.2], // Assigning the UV coords for the back side. [0.0, 0.45], [0.0, 0.2], [1.0, 0.2], [1.0, 0.45], // Assigning the UV coords for the forward side. [0.0, 0.45], [0.0, 0.2], [1.0, 0.2], [1.0, 0.45], ], ) // For meshes with flat shading, normals are orthogonal (pointing out) from the direction of // the surface. // Normals are required for correct lighting calculations. // Each array represents a normalized vector, which length should be equal to 1.0. .with_inserted_attribute( Mesh::ATTRIBUTE_NORMAL, vec![ // Normals for the top side (towards +y) [0.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 1.0, 0.0], // Normals for the bottom side (towards -y) [0.0, -1.0, 0.0], [0.0, -1.0, 0.0], [0.0, -1.0, 0.0], [0.0, -1.0, 0.0], // Normals for the right side (towards +x) [1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0], // Normals for the left side (towards -x) [-1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], // Normals for the back side (towards +z) [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], // Normals for the forward side (towards -z) [0.0, 0.0, -1.0], [0.0, 0.0, -1.0], [0.0, 0.0, -1.0], [0.0, 0.0, -1.0], ], ) // Create the triangles out of the 24 vertices we created. // To construct a square, we need 2 triangles, therefore 12 triangles in total. // To construct a triangle, we need the indices of its 3 defined vertices, adding them one // by one, in a counter-clockwise order (relative to the position of the viewer, the order // should appear counter-clockwise from the front of the triangle, in this case from outside the cube). // Read more about how to correctly build a mesh manually in the Bevy documentation of a Mesh, // further examples and the implementation of the built-in shapes. // // The first two defined triangles look like this (marked with the vertex indices, // and the axis), when looking down at the top (+y) of the cube: // -Z // ^ // 0---1 // | /| // | / | -> +X // |/ | // 3---2 // // The right face's (+x) triangles look like this, seen from the outside of the cube. // +Y // ^ // 10--11 // | /| // | / | -> -Z // |/ | // 9---8 // // The back face's (+z) triangles look like this, seen from the outside of the cube. // +Y // ^ // 17--18 // |\ | // | \ | -> +X // | \| // 16--19 .with_inserted_indices(Indices::U32(vec![ 0,3,1 , 1,3,2, // triangles making up the top (+y) facing side. 4,5,7 , 5,6,7, // bottom (-y) 8,11,9 , 9,11,10, // right (+x) 12,13,15 , 13,14,15, // left (-x) 16,19,17 , 17,19,18, // back (+z) 20,21,23 , 21,22,23, // forward (-z) ])) } // Function that changes the UV mapping of the mesh, to apply the other texture. fn toggle_texture(mesh_to_change: &mut Mesh) { // Get a mutable reference to the values of the UV attribute, so we can iterate over it. let uv_attribute = mesh_to_change.attribute_mut(Mesh::ATTRIBUTE_UV_0).unwrap(); // The format of the UV coordinates should be Float32x2. let VertexAttributeValues::Float32x2(uv_attribute) = uv_attribute else { panic!("Unexpected vertex format, expected Float32x2."); }; // Iterate over the UV coordinates, and change them as we want. for uv_coord in uv_attribute.iter_mut() { // If the UV coordinate points to the upper, "dirt+grass" part of the texture... if (uv_coord[1] + 0.5) < 1.0 { // ... point to the equivalent lower, "sand+water" part instead, uv_coord[1] += 0.5; } else { // else, point back to the upper, "dirt+grass" part. uv_coord[1] -= 0.5; } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/rotate_environment_map.rs
examples/3d/rotate_environment_map.rs
//! Demonstrates how to rotate the skybox and the environment map simultaneously. use std::f32::consts::PI; use bevy::{ color::palettes::css::{GOLD, WHITE}, core_pipeline::{tonemapping::Tonemapping::AcesFitted, Skybox}, image::ImageLoaderSettings, prelude::*, render::view::Hdr, }; /// Entry point. pub fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, rotate_skybox_and_environment_map) .run(); } /// Initializes the scene. fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, asset_server: Res<AssetServer>, ) { let sphere_mesh = create_sphere_mesh(&mut meshes); spawn_sphere(&mut commands, &mut materials, &asset_server, &sphere_mesh); spawn_light(&mut commands); spawn_camera(&mut commands, &asset_server); } /// Rotate the skybox and the environment map per frame. fn rotate_skybox_and_environment_map( mut environments: Query<(&mut Skybox, &mut EnvironmentMapLight)>, time: Res<Time>, ) { let now = time.elapsed_secs(); let rotation = Quat::from_rotation_y(0.2 * now); for (mut skybox, mut environment_map) in environments.iter_mut() { skybox.rotation = rotation; environment_map.rotation = rotation; } } /// Generates a sphere. fn create_sphere_mesh(meshes: &mut Assets<Mesh>) -> Handle<Mesh> { // We're going to use normal maps, so make sure we've generated tangents, or // else the normal maps won't show up. let mut sphere_mesh = Sphere::new(1.0).mesh().build(); sphere_mesh .generate_tangents() .expect("Failed to generate tangents"); meshes.add(sphere_mesh) } /// Spawn a regular object with a clearcoat layer. This looks like car paint. fn spawn_sphere( commands: &mut Commands, materials: &mut Assets<StandardMaterial>, asset_server: &AssetServer, sphere_mesh: &Handle<Mesh>, ) { commands.spawn(( Mesh3d(sphere_mesh.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(0.0, 0.0, 0.0).with_scale(Vec3::splat(1.25)), )); } /// Spawns a light. fn spawn_light(commands: &mut Commands) { commands.spawn(PointLight { color: WHITE.into(), intensity: 100000.0, ..default() }); } /// Spawns a camera with associated skybox and environment map. 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() }); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/transparency_3d.rs
examples/3d/transparency_3d.rs
//! Demonstrates how to use transparency in 3D. //! Shows the effects of different blend modes. //! The `fade_transparency` system smoothly changes the transparency over time. use bevy::{math::ops, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, fade_transparency) .run(); } fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // Opaque plane, uses `alpha_mode: Opaque` by default commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(6.0, 6.0))), MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))), )); // Transparent sphere, uses `alpha_mode: Mask(f32)` commands.spawn(( Mesh3d(meshes.add(Sphere::new(0.5).mesh().ico(3).unwrap())), MeshMaterial3d(materials.add(StandardMaterial { // Alpha channel of the color controls transparency. // We set it to 0.0 here, because it will be changed over time in the // `fade_transparency` function. // Note that the transparency has no effect on the objects shadow. base_color: Color::srgba(0.2, 0.7, 0.1, 0.0), // Mask sets a cutoff for transparency. Alpha values below are fully transparent, // alpha values above are fully opaque. alpha_mode: AlphaMode::Mask(0.5), ..default() })), Transform::from_xyz(1.0, 0.5, -1.5), )); // Transparent unlit sphere, uses `alpha_mode: Mask(f32)` commands.spawn(( Mesh3d(meshes.add(Sphere::new(0.5).mesh().ico(3).unwrap())), MeshMaterial3d(materials.add(StandardMaterial { base_color: Color::srgba(0.2, 0.7, 0.1, 0.0), alpha_mode: AlphaMode::Mask(0.5), unlit: true, ..default() })), Transform::from_xyz(-1.0, 0.5, -1.5), )); // Transparent cube, uses `alpha_mode: Blend` commands.spawn(( Mesh3d(meshes.add(Cuboid::default())), // Notice how there is no need to set the `alpha_mode` explicitly here. // When converting a color to a material using `into()`, the alpha mode is // automatically set to `Blend` if the alpha channel is anything lower than 1.0. MeshMaterial3d(materials.add(Color::srgba(0.5, 0.5, 1.0, 0.0))), Transform::from_xyz(0.0, 0.5, 0.0), )); // Transparent cube, uses `alpha_mode: AlphaToCoverage` commands.spawn(( Mesh3d(meshes.add(Cuboid::default())), MeshMaterial3d(materials.add(StandardMaterial { base_color: Color::srgba(0.5, 1.0, 0.5, 0.0), alpha_mode: AlphaMode::AlphaToCoverage, ..default() })), Transform::from_xyz(-1.5, 0.5, 0.0), )); // Opaque sphere commands.spawn(( Mesh3d(meshes.add(Sphere::new(0.5).mesh().ico(3).unwrap())), MeshMaterial3d(materials.add(Color::srgb(0.7, 0.2, 0.1))), Transform::from_xyz(0.0, 0.5, -1.5), )); // Light commands.spawn(( PointLight { shadows_enabled: true, ..default() }, Transform::from_xyz(4.0, 8.0, 4.0), )); // Camera commands.spawn(( Camera3d::default(), Transform::from_xyz(-2.0, 3.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y), )); } /// Fades the alpha channel of all materials between 0 and 1 over time. /// Each blend mode responds differently to this: /// - [`Opaque`](AlphaMode::Opaque): Ignores alpha channel altogether, these materials stay completely opaque. /// - [`Mask(f32)`](AlphaMode::Mask): Object appears when the alpha value goes above the mask's threshold, disappears /// when the alpha value goes back below the threshold. /// - [`Blend`](AlphaMode::Blend): Object fades in and out smoothly. /// - [`AlphaToCoverage`](AlphaMode::AlphaToCoverage): Object fades in and out /// in steps corresponding to the number of multisample antialiasing (MSAA) /// samples in use. For example, assuming 8xMSAA, the object will be /// completely opaque, then will be 7/8 opaque (1/8 transparent), then will be /// 6/8 opaque, then 5/8, etc. pub fn fade_transparency(time: Res<Time>, mut materials: ResMut<Assets<StandardMaterial>>) { let alpha = (ops::sin(time.elapsed_secs()) / 2.0) + 0.5; for (_, material) in materials.iter_mut() { material.base_color.set_alpha(alpha); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/volumetric_fog.rs
examples/3d/volumetric_fog.rs
//! Demonstrates volumetric fog and lighting (light shafts or god rays). //! Note: On Wasm, this example only runs on WebGPU use bevy::{ color::palettes::css::RED, core_pipeline::{tonemapping::Tonemapping, Skybox}, light::{FogVolume, VolumetricFog, VolumetricLight}, math::vec3, post_process::bloom::Bloom, prelude::*, }; const DIRECTIONAL_LIGHT_MOVEMENT_SPEED: f32 = 0.02; /// The current settings that the user has chosen. #[derive(Resource)] struct AppSettings { /// Whether volumetric spot light is on. volumetric_spotlight: bool, /// Whether volumetric point light is on. volumetric_pointlight: bool, } impl Default for AppSettings { fn default() -> Self { Self { volumetric_spotlight: true, volumetric_pointlight: true, } } } // Define a struct to store parameters for the point light's movement. #[derive(Component)] struct MoveBackAndForthHorizontally { min_x: f32, max_x: f32, speed: f32, } fn main() { App::new() .add_plugins(DefaultPlugins) .insert_resource(ClearColor(Color::Srgba(Srgba { red: 0.02, green: 0.02, blue: 0.02, alpha: 1.0, }))) .insert_resource(GlobalAmbientLight::NONE) .init_resource::<AppSettings>() .add_systems(Startup, setup) .add_systems(Update, tweak_scene) .add_systems(Update, (move_directional_light, move_point_light)) .add_systems(Update, adjust_app_settings) .run(); } /// Initializes the scene. fn setup(mut commands: Commands, asset_server: Res<AssetServer>, app_settings: Res<AppSettings>) { // Spawn the glTF scene. commands.spawn(SceneRoot(asset_server.load( GltfAssetLabel::Scene(0).from_asset("models/VolumetricFogExample/VolumetricFogExample.glb"), ))); // Spawn the camera. commands .spawn(( Camera3d::default(), Transform::from_xyz(-1.7, 1.5, 4.5).looking_at(vec3(-1.5, 1.7, 3.5), Vec3::Y), Tonemapping::TonyMcMapface, Bloom::default(), )) .insert(Skybox { image: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"), brightness: 1000.0, ..default() }) .insert(VolumetricFog { // This value is explicitly set to 0 since we have no environment map light ambient_intensity: 0.0, ..default() }); // Add the point light commands.spawn(( Transform::from_xyz(-0.4, 1.9, 1.0), PointLight { shadows_enabled: true, range: 150.0, color: RED.into(), intensity: 10_000.0, ..default() }, VolumetricLight, MoveBackAndForthHorizontally { min_x: -1.93, max_x: -0.4, speed: -0.2, }, )); // Add the spot light commands.spawn(( Transform::from_xyz(-1.8, 3.9, -2.7).looking_at(Vec3::ZERO, Vec3::Y), SpotLight { intensity: 50_000.0, // lumens color: Color::WHITE, shadows_enabled: true, inner_angle: 0.76, outer_angle: 0.94, ..default() }, VolumetricLight, )); // Add the fog volume. commands.spawn(( FogVolume::default(), Transform::from_scale(Vec3::splat(35.0)), )); // Add the help text. commands.spawn(( create_text(&app_settings), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, )); } fn create_text(app_settings: &AppSettings) -> Text { format!( "{}\n{}\n{}", "Press WASD or the arrow keys to change the direction of the directional light", if app_settings.volumetric_pointlight { "Press P to turn volumetric point light off" } else { "Press P to turn volumetric point light on" }, if app_settings.volumetric_spotlight { "Press L to turn volumetric spot light off" } else { "Press L to turn volumetric spot light on" } ) .into() } /// A system that makes directional lights in the glTF scene into volumetric /// lights with shadows. fn tweak_scene( mut commands: Commands, mut lights: Query<(Entity, &mut DirectionalLight), Changed<DirectionalLight>>, ) { for (light, mut directional_light) in lights.iter_mut() { // Shadows are needed for volumetric lights to work. directional_light.shadows_enabled = true; commands.entity(light).insert(VolumetricLight); } } /// Processes user requests to move the directional light. fn move_directional_light( input: Res<ButtonInput<KeyCode>>, mut directional_lights: Query<&mut Transform, With<DirectionalLight>>, ) { let mut delta_theta = Vec2::ZERO; if input.pressed(KeyCode::KeyW) || input.pressed(KeyCode::ArrowUp) { delta_theta.y += DIRECTIONAL_LIGHT_MOVEMENT_SPEED; } if input.pressed(KeyCode::KeyS) || input.pressed(KeyCode::ArrowDown) { delta_theta.y -= DIRECTIONAL_LIGHT_MOVEMENT_SPEED; } if input.pressed(KeyCode::KeyA) || input.pressed(KeyCode::ArrowLeft) { delta_theta.x += DIRECTIONAL_LIGHT_MOVEMENT_SPEED; } if input.pressed(KeyCode::KeyD) || input.pressed(KeyCode::ArrowRight) { delta_theta.x -= DIRECTIONAL_LIGHT_MOVEMENT_SPEED; } if delta_theta == Vec2::ZERO { return; } let delta_quat = Quat::from_euler(EulerRot::XZY, delta_theta.y, 0.0, delta_theta.x); for mut transform in directional_lights.iter_mut() { transform.rotate(delta_quat); } } // Toggle point light movement between left and right. fn move_point_light( timer: Res<Time>, mut objects: Query<(&mut Transform, &mut MoveBackAndForthHorizontally)>, ) { for (mut transform, mut move_data) in objects.iter_mut() { let mut translation = transform.translation; let mut need_toggle = false; translation.x += move_data.speed * timer.delta_secs(); if translation.x > move_data.max_x { translation.x = move_data.max_x; need_toggle = true; } else if translation.x < move_data.min_x { translation.x = move_data.min_x; need_toggle = true; } if need_toggle { move_data.speed = -move_data.speed; } transform.translation = translation; } } // Adjusts app settings per user input. fn adjust_app_settings( mut commands: Commands, keyboard_input: Res<ButtonInput<KeyCode>>, mut app_settings: ResMut<AppSettings>, mut point_lights: Query<Entity, With<PointLight>>, mut spot_lights: Query<Entity, With<SpotLight>>, mut text: Query<&mut Text>, ) { // If there are no changes, we're going to bail for efficiency. Record that // here. let mut any_changes = false; // If the user pressed P, toggle volumetric state of the point light. if keyboard_input.just_pressed(KeyCode::KeyP) { app_settings.volumetric_pointlight = !app_settings.volumetric_pointlight; any_changes = true; } // If the user pressed L, toggle volumetric state of the spot light. if keyboard_input.just_pressed(KeyCode::KeyL) { app_settings.volumetric_spotlight = !app_settings.volumetric_spotlight; any_changes = true; } // If there were no changes, bail out. if !any_changes { return; } // Update volumetric settings. for point_light in point_lights.iter_mut() { if app_settings.volumetric_pointlight { commands.entity(point_light).insert(VolumetricLight); } else { commands.entity(point_light).remove::<VolumetricLight>(); } } for spot_light in spot_lights.iter_mut() { if app_settings.volumetric_spotlight { commands.entity(spot_light).insert(VolumetricLight); } else { commands.entity(spot_light).remove::<VolumetricLight>(); } } // Update the help text. for mut text in text.iter_mut() { *text = create_text(&app_settings); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/light_textures.rs
examples/3d/light_textures.rs
//! Demonstrates light textures, which modulate light sources. use std::f32::consts::{FRAC_PI_2, FRAC_PI_3, FRAC_PI_4, PI}; use std::fmt::{self, Formatter}; use bevy::{ camera::primitives::CubemapLayout, color::palettes::css::{SILVER, YELLOW}, input::mouse::AccumulatedMouseMotion, light::{DirectionalLightTexture, NotShadowCaster, PointLightTexture, SpotLightTexture}, pbr::decal, prelude::*, render::renderer::{RenderAdapter, RenderDevice}, window::{CursorIcon, SystemCursorIcon}, }; use light_consts::lux::{AMBIENT_DAYLIGHT, CLEAR_SUNRISE}; use ops::{acos, cos, sin}; use widgets::{ WidgetClickEvent, WidgetClickSender, BUTTON_BORDER, BUTTON_BORDER_COLOR, BUTTON_BORDER_RADIUS_SIZE, BUTTON_PADDING, }; #[path = "../helpers/widgets.rs"] mod widgets; /// The speed at which the cube rotates, in radians per frame. const CUBE_ROTATION_SPEED: f32 = 0.02; /// The speed at which the selection can be moved, in spherical coordinate /// radians per mouse unit. const MOVE_SPEED: f32 = 0.008; /// The speed at which the selection can be scaled, in reciprocal mouse units. const SCALE_SPEED: f32 = 0.05; /// The speed at which the selection can be scaled, in radians per mouse unit. const ROLL_SPEED: f32 = 0.01; /// Various settings for the demo. #[derive(Resource, Default)] struct AppStatus { /// The object that will be moved, scaled, or rotated when the mouse is /// dragged. selection: Selection, /// What happens when the mouse is dragged: one of a move, rotate, or scale /// operation. drag_mode: DragMode, } /// The object that will be moved, scaled, or rotated when the mouse is dragged. #[derive(Clone, Copy, Component, Default, PartialEq)] enum Selection { /// The camera. /// /// The camera can only be moved, not scaled or rotated. #[default] Camera, /// The spotlight, which uses a torch-like light texture SpotLight, /// The point light, which uses a light texture cubemap constructed from the faces mesh PointLight, /// The directional light, which uses a caustic-like texture DirectionalLight, } impl fmt::Display for Selection { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match *self { Selection::Camera => f.write_str("camera"), Selection::SpotLight => f.write_str("spotlight"), Selection::PointLight => f.write_str("point light"), Selection::DirectionalLight => f.write_str("directional light"), } } } /// What happens when the mouse is dragged: one of a move, rotate, or scale /// operation. #[derive(Clone, Copy, Component, Default, PartialEq, Debug)] enum DragMode { /// The mouse moves the current selection. #[default] Move, /// The mouse scales the current selection. /// /// This only applies to decals, not cameras. Scale, /// The mouse rotates the current selection around its local Z axis. /// /// This only applies to decals, not cameras. Roll, } impl fmt::Display for DragMode { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match *self { DragMode::Move => f.write_str("move"), DragMode::Scale => f.write_str("scale"), DragMode::Roll => f.write_str("roll"), } } } /// A marker component for the help text in the top left corner of the window. #[derive(Clone, Copy, Component)] struct HelpText; /// Entry point. fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "Bevy Light Textures Example".into(), ..default() }), ..default() })) .init_resource::<AppStatus>() .add_message::<WidgetClickEvent<Selection>>() .add_message::<WidgetClickEvent<Visibility>>() .add_systems(Startup, setup) .add_systems(Update, draw_gizmos) .add_systems(Update, rotate_cube) .add_systems(Update, hide_shadows) .add_systems(Update, widgets::handle_ui_interactions::<Selection>) .add_systems(Update, widgets::handle_ui_interactions::<Visibility>) .add_systems( Update, (handle_selection_change, update_radio_buttons) .after(widgets::handle_ui_interactions::<Selection>) .after(widgets::handle_ui_interactions::<Visibility>), ) .add_systems(Update, toggle_visibility) .add_systems(Update, update_directional_light) .add_systems(Update, process_move_input) .add_systems(Update, process_scale_input) .add_systems(Update, process_roll_input) .add_systems(Update, switch_drag_mode) .add_systems(Update, update_help_text) .add_systems(Update, update_button_visibility) .run(); } /// Creates the scene. fn setup( mut commands: Commands, asset_server: Res<AssetServer>, app_status: Res<AppStatus>, render_device: Res<RenderDevice>, render_adapter: Res<RenderAdapter>, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // Error out if clustered decals (and so light textures) aren't supported on the current platform. if !decal::clustered::clustered_decals_are_usable(&render_device, &render_adapter) { error!("Light textures aren't usable on this platform."); commands.write_message(AppExit::error()); } spawn_cubes(&mut commands, &mut meshes, &mut materials); spawn_camera(&mut commands); spawn_light(&mut commands, &asset_server); spawn_buttons(&mut commands); spawn_help_text(&mut commands, &app_status); spawn_light_textures(&mut commands, &asset_server, &mut meshes, &mut materials); } #[derive(Component)] struct Rotate; /// Spawns the cube onto which the decals are projected. fn spawn_cubes( commands: &mut Commands, meshes: &mut Assets<Mesh>, materials: &mut Assets<StandardMaterial>, ) { // 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(StandardMaterial { base_color: SILVER.into(), ..default() })), transform, Rotate, )); commands.spawn(( Mesh3d(meshes.add(Cuboid::new(-13.0, -13.0, -13.0))), MeshMaterial3d(materials.add(StandardMaterial { base_color: SILVER.into(), ..default() })), transform, )); } /// Spawns the directional light. fn spawn_light(commands: &mut Commands, asset_server: &AssetServer) { commands.spawn(( Visibility::Hidden, Transform::from_xyz(8.0, 8.0, 4.0).looking_at(Vec3::ZERO, Vec3::Y), Selection::DirectionalLight, children![( DirectionalLight { illuminance: AMBIENT_DAYLIGHT, ..default() }, DirectionalLightTexture { image: asset_server.load("lightmaps/caustic_directional_texture.png"), tiled: true, }, Visibility::Visible, )], )); } /// Spawns the camera. fn spawn_camera(commands: &mut Commands) { commands .spawn(Camera3d::default()) .insert(Transform::from_xyz(0.0, 2.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y)) // Tag the camera with `Selection::Camera`. .insert(Selection::Camera); } fn spawn_light_textures( commands: &mut Commands, asset_server: &AssetServer, meshes: &mut Assets<Mesh>, materials: &mut Assets<StandardMaterial>, ) { commands.spawn(( SpotLight { color: Color::srgb(1.0, 1.0, 0.8), intensity: 10e6, outer_angle: 0.25, inner_angle: 0.25, shadows_enabled: true, ..default() }, Transform::from_translation(Vec3::new(6.0, 1.0, 2.0)).looking_at(Vec3::ZERO, Vec3::Y), SpotLightTexture { image: asset_server.load("lightmaps/torch_spotlight_texture.png"), }, Visibility::Inherited, Selection::SpotLight, )); commands.spawn(( Visibility::Hidden, Transform::from_translation(Vec3::new(0.0, 1.8, 0.01)).with_scale(Vec3::splat(0.1)), Selection::PointLight, children![ SceneRoot( asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/Faces/faces.glb")), ), ( Mesh3d(meshes.add(Sphere::new(1.0))), MeshMaterial3d(materials.add(StandardMaterial { emissive: Color::srgb(0.0, 0.0, 300.0).to_linear(), ..default() })), ), ( PointLight { color: Color::srgb(0.0, 0.0, 1.0), intensity: 1e6, shadows_enabled: true, ..default() }, PointLightTexture { image: asset_server.load("lightmaps/faces_pointlight_texture_blurred.png"), cubemap_layout: CubemapLayout::CrossVertical, }, ) ], )); } /// Spawns the buttons at the bottom of the screen. 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(), children![widgets::option_buttons( "Drag to Move", &[ (Selection::Camera, "Camera"), (Selection::SpotLight, "Spotlight"), (Selection::PointLight, "Point Light"), (Selection::DirectionalLight, "Directional Light"), ], )], )); // 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: px(10), bottom: px(10), column_gap: px(6), ..default() }, children![ widgets::option_buttons( "", &[ (Visibility::Inherited, "Show"), (Visibility::Hidden, "Hide"), ], ), (drag_button("Scale"), DragMode::Scale), (drag_button("Roll"), DragMode::Roll), ], )); } /// Spawns a button that the user can drag to change a parameter. fn drag_button(label: &str) -> impl Bundle { ( Node { border: BUTTON_BORDER, justify_content: JustifyContent::Center, align_items: AlignItems::Center, padding: BUTTON_PADDING, border_radius: BorderRadius::all(BUTTON_BORDER_RADIUS_SIZE), ..default() }, Button, BackgroundColor(Color::BLACK), BUTTON_BORDER_COLOR, children![widgets::ui_text(label, Color::WHITE),], ) } /// Spawns the help text at the top of the screen. 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: px(12), left: px(12), ..default() }, HelpText, )); } /// Draws the outlines that show the bounds of the spotlight. fn draw_gizmos(mut gizmos: Gizmos, spotlight: Query<(&GlobalTransform, &SpotLight, &Visibility)>) { if let Ok((global_transform, spotlight, visibility)) = spotlight.single() && visibility != Visibility::Hidden { gizmos.primitive_3d( &Cone::new(7.0 * spotlight.outer_angle, 7.0), Isometry3d { rotation: global_transform.rotation() * Quat::from_rotation_x(FRAC_PI_2), translation: global_transform.translation_vec3a() * 0.5, }, YELLOW, ); } } /// Rotates the cube a bit every frame. fn rotate_cube(mut meshes: Query<&mut Transform, With<Rotate>>) { for mut transform in &mut meshes { transform.rotate_y(CUBE_ROTATION_SPEED); } } /// Hide shadows on all meshes except the main cube fn hide_shadows( mut commands: Commands, meshes: Query<Entity, (With<Mesh3d>, Without<NotShadowCaster>, Without<Rotate>)>, ) { for ent in &meshes { commands.entity(ent).insert(NotShadowCaster); } } /// Updates the state of the radio buttons when the user clicks on one. fn update_radio_buttons( mut widgets: Query<( Entity, Option<&mut BackgroundColor>, Has<Text>, &WidgetClickSender<Selection>, )>, app_status: Res<AppStatus>, mut writer: TextUiWriter, visible: Query<(&Visibility, &Selection)>, mut visibility_widgets: Query< ( Entity, Option<&mut BackgroundColor>, Has<Text>, &WidgetClickSender<Visibility>, ), Without<WidgetClickSender<Selection>>, >, ) { for (entity, maybe_bg_color, has_text, sender) in &mut widgets { let selected = app_status.selection == **sender; if let Some(mut bg_color) = maybe_bg_color { widgets::update_ui_radio_button(&mut bg_color, selected); } if has_text { widgets::update_ui_radio_button_text(entity, &mut writer, selected); } } let visibility = visible .iter() .filter(|(_, selection)| **selection == app_status.selection) .map(|(visibility, _)| *visibility) .next() .unwrap_or_default(); for (entity, maybe_bg_color, has_text, sender) in &mut visibility_widgets { if let Some(mut bg_color) = maybe_bg_color { widgets::update_ui_radio_button(&mut bg_color, **sender == visibility); } if has_text { widgets::update_ui_radio_button_text(entity, &mut writer, **sender == visibility); } } } /// Changes the selection when the user clicks a radio button. fn handle_selection_change( mut events: MessageReader<WidgetClickEvent<Selection>>, mut app_status: ResMut<AppStatus>, ) { for event in events.read() { app_status.selection = **event; } } fn toggle_visibility( mut events: MessageReader<WidgetClickEvent<Visibility>>, app_status: Res<AppStatus>, mut visibility: Query<(&mut Visibility, &Selection)>, ) { if let Some(vis) = events.read().last() { for (mut visibility, selection) in visibility.iter_mut() { if selection == &app_status.selection { *visibility = **vis; } } } } /// Process a drag event that moves the selected object. fn process_move_input( mut selections: Query<(&mut Transform, &Selection)>, mouse_buttons: Res<ButtonInput<MouseButton>>, mouse_motion: Res<AccumulatedMouseMotion>, app_status: Res<AppStatus>, ) { // Only process drags when movement is selected. if !mouse_buttons.pressed(MouseButton::Left) || app_status.drag_mode != DragMode::Move { return; } for (mut transform, selection) in &mut selections { if app_status.selection != *selection { continue; } // use simple movement for the point light if *selection == Selection::PointLight { transform.translation += (mouse_motion.delta * Vec2::new(1.0, -1.0) * MOVE_SPEED).extend(0.0); return; } let position = transform.translation; // Convert to spherical coordinates. let radius = position.length(); let mut theta = acos(position.y / radius); let mut phi = position.z.signum() * acos(position.x * position.xz().length_recip()); // Camera movement is the inverse of object movement. let (phi_factor, theta_factor) = match *selection { Selection::Camera => (1.0, -1.0), _ => (-1.0, 1.0), }; // Adjust the spherical coordinates. Clamp the inclination to (0, π). phi += phi_factor * mouse_motion.delta.x * MOVE_SPEED; theta = f32::clamp( theta + theta_factor * mouse_motion.delta.y * MOVE_SPEED, 0.001, PI - 0.001, ); // Convert spherical coordinates back to Cartesian coordinates. transform.translation = radius * vec3(sin(theta) * cos(phi), cos(theta), sin(theta) * sin(phi)); // Look at the center, but preserve the previous roll angle. let roll = transform.rotation.to_euler(EulerRot::YXZ).2; transform.look_at(Vec3::ZERO, Vec3::Y); let (yaw, pitch, _) = transform.rotation.to_euler(EulerRot::YXZ); transform.rotation = Quat::from_euler(EulerRot::YXZ, yaw, pitch, roll); } } /// Processes a drag event that scales the selected target. fn process_scale_input( mut scale_selections: Query<(&mut Transform, &Selection)>, mut spotlight_selections: Query<(&mut SpotLight, &Selection)>, mouse_buttons: Res<ButtonInput<MouseButton>>, mouse_motion: Res<AccumulatedMouseMotion>, app_status: Res<AppStatus>, ) { // Only process drags when the scaling operation is selected. if !mouse_buttons.pressed(MouseButton::Left) || app_status.drag_mode != DragMode::Scale { return; } for (mut transform, selection) in &mut scale_selections { if app_status.selection == *selection { transform.scale = (transform.scale * (1.0 + mouse_motion.delta.x * SCALE_SPEED)) .clamp(Vec3::splat(0.01), Vec3::splat(5.0)); } } for (mut spotlight, selection) in &mut spotlight_selections { if app_status.selection == *selection { spotlight.outer_angle = (spotlight.outer_angle * (1.0 + mouse_motion.delta.x * SCALE_SPEED)) .clamp(0.01, FRAC_PI_4); spotlight.inner_angle = spotlight.outer_angle; } } } /// Processes a drag event that rotates the selected target along its local Z /// axis. fn process_roll_input( mut selections: Query<(&mut Transform, &Selection)>, mouse_buttons: Res<ButtonInput<MouseButton>>, mouse_motion: Res<AccumulatedMouseMotion>, app_status: Res<AppStatus>, ) { // Only process drags when the rolling operation is selected. if !mouse_buttons.pressed(MouseButton::Left) || app_status.drag_mode != DragMode::Roll { return; } for (mut transform, selection) in &mut selections { if app_status.selection != *selection { continue; } let (yaw, pitch, mut roll) = transform.rotation.to_euler(EulerRot::YXZ); roll += mouse_motion.delta.x * ROLL_SPEED; transform.rotation = Quat::from_euler(EulerRot::YXZ, yaw, pitch, roll); } } /// Creates the help string at the top left of the screen. fn create_help_string(app_status: &AppStatus) -> String { format!( "Click and drag to {} {}", app_status.drag_mode, app_status.selection ) } /// Changes the drag mode when the user hovers over the "Scale" and "Roll" /// buttons in the lower right. /// /// If the user is hovering over no such button, this system changes the drag /// mode back to its default value of [`DragMode::Move`]. fn switch_drag_mode( mut commands: Commands, mut interactions: Query<(&Interaction, &DragMode)>, mut windows: Query<Entity, With<Window>>, mouse_buttons: Res<ButtonInput<MouseButton>>, mut app_status: ResMut<AppStatus>, ) { if mouse_buttons.pressed(MouseButton::Left) { return; } for (interaction, drag_mode) in &mut interactions { if *interaction != Interaction::Hovered { continue; } app_status.drag_mode = *drag_mode; // Set the cursor to provide the user with a nice visual hint. for window in &mut windows { commands .entity(window) .insert(CursorIcon::from(SystemCursorIcon::EwResize)); } return; } app_status.drag_mode = DragMode::Move; for window in &mut windows { commands.entity(window).remove::<CursorIcon>(); } } /// Updates the help text in the top left of the screen to reflect the current /// selection and drag mode. fn update_help_text(mut help_text: Query<&mut Text, With<HelpText>>, app_status: Res<AppStatus>) { for mut text in &mut help_text { text.0 = create_help_string(&app_status); } } /// Updates the visibility of the drag mode buttons so that they aren't visible /// if the camera is selected. fn update_button_visibility( mut nodes: Query<&mut Visibility, Or<(With<DragMode>, With<WidgetClickSender<Visibility>>)>>, app_status: Res<AppStatus>, ) { for mut visibility in &mut nodes { *visibility = match app_status.selection { Selection::Camera => Visibility::Hidden, _ => Visibility::Visible, }; } } fn update_directional_light( mut commands: Commands, asset_server: Res<AssetServer>, selections: Query<(&Selection, &Visibility)>, mut light: Query<( Entity, &mut DirectionalLight, Option<&DirectionalLightTexture>, )>, ) { let directional_visible = selections .iter() .filter(|(selection, _)| **selection == Selection::DirectionalLight) .any(|(_, visibility)| visibility != Visibility::Hidden); let any_texture_light_visible = selections .iter() .filter(|(selection, _)| { **selection == Selection::PointLight || **selection == Selection::SpotLight }) .any(|(_, visibility)| visibility != Visibility::Hidden); let (entity, mut light, maybe_texture) = light .single_mut() .expect("there should be a single directional light"); if directional_visible { light.illuminance = AMBIENT_DAYLIGHT; if maybe_texture.is_none() { commands.entity(entity).insert(DirectionalLightTexture { image: asset_server.load("lightmaps/caustic_directional_texture.png"), tiled: true, }); } } else if any_texture_light_visible { light.illuminance = CLEAR_SUNRISE; if maybe_texture.is_some() { commands.entity(entity).remove::<DirectionalLightTexture>(); } } else { light.illuminance = AMBIENT_DAYLIGHT; if maybe_texture.is_some() { commands.entity(entity).remove::<DirectionalLightTexture>(); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/mixed_lighting.rs
examples/3d/mixed_lighting.rs
//! Demonstrates how to combine baked and dynamic lighting. use bevy::{ gltf::GltfMeshName, pbr::Lightmap, picking::{backend::HitData, pointer::PointerInteraction}, prelude::*, scene::SceneInstanceReady, }; use crate::widgets::{RadioButton, RadioButtonText, WidgetClickEvent, WidgetClickSender}; #[path = "../helpers/widgets.rs"] mod widgets; /// How bright the lightmaps are. const LIGHTMAP_EXPOSURE: f32 = 600.0; /// How far above the ground the sphere's origin is when moved, in scene units. const SPHERE_OFFSET: f32 = 0.2; /// The settings that the user has currently chosen for the app. #[derive(Clone, Default, Resource)] struct AppStatus { /// The lighting mode that the user currently has set: baked, mixed, or /// real-time. lighting_mode: LightingMode, } /// The type of lighting to use in the scene. #[derive(Clone, Copy, PartialEq, Default)] enum LightingMode { /// All light is computed ahead of time; no lighting takes place at runtime. /// /// In this mode, the sphere can't be moved, as the light shining on it was /// precomputed. On the plus side, the sphere has indirect lighting in this /// mode, as the red hue on the bottom of the sphere demonstrates. Baked, /// All light for the static objects is computed ahead of time, but the /// light for the dynamic sphere is computed at runtime. /// /// In this mode, the sphere can be moved, and the light will be computed /// for it as you do so. The sphere loses indirect illumination; notice the /// lack of a red hue at the base of the sphere. However, the rest of the /// scene has indirect illumination. Note also that the sphere doesn't cast /// a shadow on the static objects in this mode, because shadows are part of /// the lighting computation. MixedDirect, /// Indirect light for the static objects is computed ahead of time, and /// direct light for all objects is computed at runtime. /// /// In this mode, the sphere can be moved, and the light will be computed /// for it as you do so. The sphere loses indirect illumination; notice the /// lack of a red hue at the base of the sphere. However, the rest of the /// scene has indirect illumination. The sphere does cast a shadow on /// objects in this mode, because the direct light for all objects is being /// computed dynamically. #[default] MixedIndirect, /// Light is computed at runtime for all objects. /// /// In this mode, no lightmaps are used at all. All objects are dynamically /// lit, which provides maximum flexibility. However, the downside is that /// global illumination is lost; note that the base of the sphere isn't red /// as it is in baked mode. RealTime, } /// A message that's written whenever the user changes the lighting mode. /// /// This is also written when the scene loads for the first time. #[derive(Clone, Copy, Default, Message)] struct LightingModeChanged; #[derive(Clone, Copy, Component, Debug)] struct HelpText; /// The name of every static object in the scene that has a lightmap, as well as /// the UV rect of its lightmap. /// /// Storing this as an array and doing a linear search through it is rather /// inefficient, but we do it anyway for clarity's sake. static LIGHTMAPS: [(&str, Rect); 5] = [ ( "Plane", uv_rect_opengl(Vec2::splat(0.026), Vec2::splat(0.710)), ), ( "SheenChair_fabric", uv_rect_opengl(vec2(0.7864, 0.02377), vec2(0.1910, 0.1912)), ), ( "SheenChair_label", uv_rect_opengl(vec2(0.275, -0.016), vec2(0.858, 0.486)), ), ( "SheenChair_metal", uv_rect_opengl(vec2(0.998, 0.506), vec2(-0.029, -0.067)), ), ( "SheenChair_wood", uv_rect_opengl(vec2(0.787, 0.257), vec2(0.179, 0.177)), ), ]; static SPHERE_UV_RECT: Rect = uv_rect_opengl(vec2(0.788, 0.484), Vec2::splat(0.062)); /// The initial position of the sphere. /// /// When the user sets the light mode to [`LightingMode::Baked`], we reset the /// position to this point. const INITIAL_SPHERE_POSITION: Vec3 = vec3(0.0, 0.5233223, 0.0); fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "Bevy Mixed Lighting Example".into(), ..default() }), ..default() })) .add_plugins(MeshPickingPlugin) .insert_resource(GlobalAmbientLight { color: ClearColor::default().0, brightness: 10000.0, affects_lightmapped_meshes: true, }) .init_resource::<AppStatus>() .add_message::<WidgetClickEvent<LightingMode>>() .add_message::<LightingModeChanged>() .add_systems(Startup, setup) .add_systems(Update, update_lightmaps) .add_systems(Update, update_directional_light) .add_systems(Update, make_sphere_nonpickable) .add_systems(Update, update_radio_buttons) .add_systems(Update, handle_lighting_mode_change) .add_systems(Update, widgets::handle_ui_interactions::<LightingMode>) .add_systems(Update, reset_sphere_position) .add_systems(Update, move_sphere) .add_systems(Update, adjust_help_text) .run(); } /// Creates the scene. fn setup(mut commands: Commands, asset_server: Res<AssetServer>, app_status: Res<AppStatus>) { spawn_camera(&mut commands); spawn_scene(&mut commands, &asset_server); spawn_buttons(&mut commands); spawn_help_text(&mut commands, &app_status); } /// Spawns the 3D camera. fn spawn_camera(commands: &mut Commands) { commands .spawn(Camera3d::default()) .insert(Transform::from_xyz(-0.7, 0.7, 1.0).looking_at(vec3(0.0, 0.3, 0.0), Vec3::Y)); } /// Spawns the scene. /// /// The scene is loaded from a glTF file. 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_changed_writer: MessageWriter<LightingModeChanged>| { // When the scene loads, send a `LightingModeChanged` event so // that we set up the lightmaps. lighting_mode_changed_writer.write(LightingModeChanged); }, ); } /// Spawns the buttons that allow the user to change the lighting mode. fn spawn_buttons(commands: &mut Commands) { commands.spawn(( widgets::main_ui_node(), children![widgets::option_buttons( "Lighting", &[ (LightingMode::Baked, "Baked"), (LightingMode::MixedDirect, "Mixed (Direct)"), (LightingMode::MixedIndirect, "Mixed (Indirect)"), (LightingMode::RealTime, "Real-Time"), ], )], )); } /// Spawns the help text at the top of the window. fn spawn_help_text(commands: &mut Commands, app_status: &AppStatus) { commands.spawn(( create_help_text(app_status), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, HelpText, )); } /// 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. 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_changed_reader: MessageReader<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_changed_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>(); } } } } } /// 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. 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), } } /// Ensures that clicking on the scene to move the sphere doesn't result in a /// hit on the sphere itself. 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); } } } /// Updates the directional light settings as necessary when the lighting mode /// changes. fn update_directional_light( mut lights: Query<&mut DirectionalLight>, mut lighting_mode_changed_reader: MessageReader<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_changed_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 state of the selection widgets at the bottom of the window when /// the lighting mode changes. 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); } } } /// Handles clicks on the widgets at the bottom of the screen and fires /// [`LightingModeChanged`] events. fn handle_lighting_mode_change( mut widget_click_event_reader: MessageReader<WidgetClickEvent<LightingMode>>, mut lighting_mode_changed_writer: MessageWriter<LightingModeChanged>, mut app_status: ResMut<AppStatus>, ) { for event in widget_click_event_reader.read() { app_status.lighting_mode = **event; lighting_mode_changed_writer.write(LightingModeChanged); } } /// 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. fn reset_sphere_position( mut objects: Query<(&Name, &mut Transform)>, mut lighting_mode_changed_reader: MessageReader<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_changed_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; } } } /// 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. 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); } } } /// Changes the help text at the top of the screen when the lighting mode /// changes. fn adjust_help_text( mut commands: Commands, help_texts: Query<Entity, With<HelpText>>, app_status: Res<AppStatus>, mut lighting_mode_changed_reader: MessageReader<LightingModeChanged>, ) { if lighting_mode_changed_reader.read().next().is_none() { return; } for help_text in &help_texts { commands .entity(help_text) .insert(create_help_text(&app_status)); } } /// Returns appropriate text to display at the top of the screen. 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", ), } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/animated_material.rs
examples/3d/animated_material.rs
//! Shows how to animate material properties use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, animate_materials) .run(); } fn setup( mut commands: Commands, asset_server: Res<AssetServer>, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { commands.spawn(( Camera3d::default(), Transform::from_xyz(3.0, 1.0, 3.0).looking_at(Vec3::new(0.0, -0.5, 0.0), Vec3::Y), 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: 2_000.0, ..default() }, )); let cube = meshes.add(Cuboid::new(0.5, 0.5, 0.5)); const GOLDEN_ANGLE: f32 = 137.507_77; let mut hsla = Hsla::hsl(0.0, 1.0, 0.5); for x in -1..2 { for z in -1..2 { commands.spawn(( Mesh3d(cube.clone()), MeshMaterial3d(materials.add(Color::from(hsla))), Transform::from_translation(Vec3::new(x as f32, 0.0, z as f32)), )); hsla = hsla.rotate_hue(GOLDEN_ANGLE); } } } fn animate_materials( material_handles: Query<&MeshMaterial3d<StandardMaterial>>, time: Res<Time>, mut materials: ResMut<Assets<StandardMaterial>>, ) { for material_handle in material_handles.iter() { if let Some(material) = materials.get_mut(material_handle) && let Color::Hsla(ref mut hsla) = material.base_color { *hsla = hsla.rotate_hue(time.delta_secs() * 100.0); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/deferred_rendering.rs
examples/3d/deferred_rendering.rs
//! This example compares Forward, Forward + Prepass, and Deferred rendering. use std::f32::consts::*; use bevy::{ anti_alias::fxaa::Fxaa, core_pipeline::prepass::{DeferredPrepass, DepthPrepass, MotionVectorPrepass, NormalPrepass}, image::ImageLoaderSettings, light::{ CascadeShadowConfigBuilder, DirectionalLightShadowMap, NotShadowCaster, NotShadowReceiver, }, math::ops, pbr::{DefaultOpaqueRendererMethod, OpaqueRendererMethod}, prelude::*, }; fn main() { App::new() .insert_resource(DefaultOpaqueRendererMethod::deferred()) .insert_resource(DirectionalLightShadowMap { size: 4096 }) .add_plugins(DefaultPlugins) .insert_resource(Pause(true)) .add_systems(Startup, (setup, setup_parallax)) .add_systems(Update, (animate_light_direction, switch_mode, spin)) .run(); } fn setup( mut commands: Commands, asset_server: Res<AssetServer>, mut materials: ResMut<Assets<StandardMaterial>>, mut meshes: ResMut<Assets<Mesh>>, ) { commands.spawn(( Camera3d::default(), Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y), // MSAA needs to be off for Deferred rendering Msaa::Off, DistanceFog { color: Color::srgb_u8(43, 44, 47), falloff: FogFalloff::Linear { start: 1.0, end: 8.0, }, ..default() }, EnvironmentMapLight { diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"), specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"), intensity: 2000.0, ..default() }, DepthPrepass, MotionVectorPrepass, DeferredPrepass, Fxaa::default(), )); commands.spawn(( DirectionalLight { illuminance: 15_000., shadows_enabled: true, ..default() }, CascadeShadowConfigBuilder { num_cascades: 3, maximum_distance: 10.0, ..default() } .build(), Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 0.0, -FRAC_PI_4)), )); // FlightHelmet let helmet_scene = asset_server .load(GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf")); commands.spawn(SceneRoot(helmet_scene.clone())); commands.spawn(( SceneRoot(helmet_scene), Transform::from_xyz(-4.0, 0.0, -3.0), )); let mut forward_mat: StandardMaterial = Color::srgb(0.1, 0.2, 0.1).into(); forward_mat.opaque_render_method = OpaqueRendererMethod::Forward; let forward_mat_h = materials.add(forward_mat); // Plane commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(50.0, 50.0))), MeshMaterial3d(forward_mat_h.clone()), )); let cube_h = meshes.add(Cuboid::new(0.1, 0.1, 0.1)); let sphere_h = meshes.add(Sphere::new(0.125).mesh().uv(32, 18)); // Cubes commands.spawn(( Mesh3d(cube_h.clone()), MeshMaterial3d(forward_mat_h.clone()), Transform::from_xyz(-0.3, 0.5, -0.2), )); commands.spawn(( Mesh3d(cube_h), MeshMaterial3d(forward_mat_h), Transform::from_xyz(0.2, 0.5, 0.2), )); let sphere_color = Color::srgb(10.0, 4.0, 1.0); let sphere_pos = Transform::from_xyz(0.4, 0.5, -0.8); // Emissive sphere let mut unlit_mat: StandardMaterial = sphere_color.into(); unlit_mat.unlit = true; commands.spawn(( Mesh3d(sphere_h.clone()), MeshMaterial3d(materials.add(unlit_mat)), sphere_pos, NotShadowCaster, )); // Light commands.spawn(( PointLight { intensity: 800.0, radius: 0.125, shadows_enabled: true, color: sphere_color, ..default() }, sphere_pos, )); // Spheres for i in 0..6 { let j = i % 3; let s_val = if i < 3 { 0.0 } else { 0.2 }; let material = if j == 0 { materials.add(StandardMaterial { base_color: Color::srgb(s_val, s_val, 1.0), perceptual_roughness: 0.089, metallic: 0.0, ..default() }) } else if j == 1 { materials.add(StandardMaterial { base_color: Color::srgb(s_val, 1.0, s_val), perceptual_roughness: 0.089, metallic: 0.0, ..default() }) } else { materials.add(StandardMaterial { base_color: Color::srgb(1.0, s_val, s_val), perceptual_roughness: 0.089, metallic: 0.0, ..default() }) }; commands.spawn(( Mesh3d(sphere_h.clone()), MeshMaterial3d(material), Transform::from_xyz( j as f32 * 0.25 + if i < 3 { -0.15 } else { 0.15 } - 0.4, 0.125, -j as f32 * 0.25 + if i < 3 { -0.15 } else { 0.15 } + 0.4, ), )); } // sky commands.spawn(( Mesh3d(meshes.add(Cuboid::new(2.0, 1.0, 1.0))), MeshMaterial3d(materials.add(StandardMaterial { base_color: Srgba::hex("888888").unwrap().into(), unlit: true, cull_mode: None, ..default() })), Transform::from_scale(Vec3::splat(1_000_000.0)), NotShadowCaster, NotShadowReceiver, )); // Example instructions commands.spawn(( Text::default(), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, )); } #[derive(Resource)] struct Pause(bool); fn animate_light_direction( time: Res<Time>, mut query: Query<&mut Transform, With<DirectionalLight>>, pause: Res<Pause>, ) { if pause.0 { return; } for mut transform in &mut query { transform.rotate_y(time.delta_secs() * PI / 5.0); } } fn setup_parallax( mut commands: Commands, mut materials: ResMut<Assets<StandardMaterial>>, mut meshes: ResMut<Assets<Mesh>>, asset_server: Res<AssetServer>, ) { // The normal map. Note that to generate it in the GIMP image editor, you should // open the depth map, and do Filters → Generic → Normal Map // You should enable the "flip X" checkbox. let normal_handle = asset_server.load_with_settings( "textures/parallax_example/cube_normal.png", // The normal map texture is in linear color space. Lighting won't look correct // if `is_srgb` is `true`, which is the default. |settings: &mut ImageLoaderSettings| settings.is_srgb = false, ); let mut cube = Mesh::from(Cuboid::new(0.15, 0.15, 0.15)); // NOTE: for normal maps and depth maps to work, the mesh // needs tangents generated. cube.generate_tangents().unwrap(); let parallax_material = materials.add(StandardMaterial { perceptual_roughness: 0.4, base_color_texture: Some(asset_server.load("textures/parallax_example/cube_color.png")), normal_map_texture: Some(normal_handle), // The depth map is a grayscale texture where black is the highest level and // white the lowest. depth_map: Some(asset_server.load("textures/parallax_example/cube_depth.png")), parallax_depth_scale: 0.09, parallax_mapping_method: ParallaxMappingMethod::Relief { max_steps: 4 }, max_parallax_layer_count: ops::exp2(5.0f32), ..default() }); commands.spawn(( Mesh3d(meshes.add(cube)), MeshMaterial3d(parallax_material), Transform::from_xyz(0.4, 0.2, -0.8), Spin { speed: 0.3 }, )); } #[derive(Component)] struct Spin { speed: f32, } fn spin(time: Res<Time>, mut query: Query<(&mut Transform, &Spin)>, pause: Res<Pause>) { if pause.0 { return; } for (mut transform, spin) in query.iter_mut() { transform.rotate_local_y(spin.speed * time.delta_secs()); transform.rotate_local_x(spin.speed * time.delta_secs()); transform.rotate_local_z(-spin.speed * time.delta_secs()); } } #[derive(Resource, Default)] enum DefaultRenderMode { #[default] Deferred, Forward, ForwardPrepass, } fn switch_mode( mut text: Single<&mut Text>, mut commands: Commands, keys: Res<ButtonInput<KeyCode>>, mut default_opaque_renderer_method: ResMut<DefaultOpaqueRendererMethod>, mut materials: ResMut<Assets<StandardMaterial>>, cameras: Query<Entity, With<Camera>>, mut pause: ResMut<Pause>, mut hide_ui: Local<bool>, mut mode: Local<DefaultRenderMode>, ) { text.clear(); if keys.just_pressed(KeyCode::Space) { pause.0 = !pause.0; } if keys.just_pressed(KeyCode::Digit1) { *mode = DefaultRenderMode::Deferred; default_opaque_renderer_method.set_to_deferred(); println!("DefaultOpaqueRendererMethod: Deferred"); for _ in materials.iter_mut() {} for camera in &cameras { commands.entity(camera).remove::<NormalPrepass>(); commands.entity(camera).insert(DepthPrepass); commands.entity(camera).insert(MotionVectorPrepass); commands.entity(camera).insert(DeferredPrepass); } } if keys.just_pressed(KeyCode::Digit2) { *mode = DefaultRenderMode::Forward; default_opaque_renderer_method.set_to_forward(); println!("DefaultOpaqueRendererMethod: Forward"); for _ in materials.iter_mut() {} for camera in &cameras { commands.entity(camera).remove::<NormalPrepass>(); commands.entity(camera).remove::<DepthPrepass>(); commands.entity(camera).remove::<MotionVectorPrepass>(); commands.entity(camera).remove::<DeferredPrepass>(); } } if keys.just_pressed(KeyCode::Digit3) { *mode = DefaultRenderMode::ForwardPrepass; default_opaque_renderer_method.set_to_forward(); println!("DefaultOpaqueRendererMethod: Forward + Prepass"); for _ in materials.iter_mut() {} for camera in &cameras { commands.entity(camera).insert(NormalPrepass); commands.entity(camera).insert(DepthPrepass); commands.entity(camera).insert(MotionVectorPrepass); commands.entity(camera).remove::<DeferredPrepass>(); } } if keys.just_pressed(KeyCode::KeyH) { *hide_ui = !*hide_ui; } if !*hide_ui { text.push_str("(H) Hide UI\n"); text.push_str("(Space) Play/Pause\n\n"); text.push_str("Rendering Method:\n"); text.push_str(&format!( "(1) {} Deferred\n", if let DefaultRenderMode::Deferred = *mode { ">" } else { "" } )); text.push_str(&format!( "(2) {} Forward\n", if let DefaultRenderMode::Forward = *mode { ">" } else { "" } )); text.push_str(&format!( "(3) {} Forward + Prepass\n", if let DefaultRenderMode::ForwardPrepass = *mode { ">" } else { "" } )); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/atmospheric_fog.rs
examples/3d/atmospheric_fog.rs
//! This example showcases atmospheric fog //! //! ## Controls //! //! | Key Binding | Action | //! |:-------------------|:---------------------------------------| //! | `Spacebar` | Toggle Atmospheric Fog | //! | `S` | Toggle Directional Light Fog Influence | use bevy::{ light::{CascadeShadowConfigBuilder, NotShadowCaster}, prelude::*, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems( Startup, (setup_camera_fog, setup_terrain_scene, setup_instructions), ) .add_systems(Update, toggle_system) .run(); } fn setup_camera_fog(mut commands: Commands) { commands.spawn(( Camera3d::default(), Transform::from_xyz(-1.0, 0.1, 1.0).looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y), DistanceFog { color: Color::srgba(0.35, 0.48, 0.66, 1.0), directional_light_color: Color::srgba(1.0, 0.95, 0.85, 0.5), directional_light_exponent: 30.0, falloff: FogFalloff::from_visibility_colors( 15.0, // distance in world units up to which objects retain visibility (>= 5% contrast) Color::srgb(0.35, 0.5, 0.66), // atmospheric extinction color (after light is lost due to absorption by atmospheric particles) Color::srgb(0.8, 0.844, 1.0), // atmospheric inscattering color (light gained due to scattering from the sun) ), }, )); } fn setup_terrain_scene( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, asset_server: Res<AssetServer>, ) { // Configure a properly scaled cascade shadow map for this scene (defaults are too large, mesh units are in km) let cascade_shadow_config = CascadeShadowConfigBuilder { first_cascade_far_bound: 0.3, maximum_distance: 3.0, ..default() } .build(); // Sun commands.spawn(( DirectionalLight { color: Color::srgb(0.98, 0.95, 0.82), shadows_enabled: true, ..default() }, Transform::from_xyz(0.0, 0.0, 0.0).looking_at(Vec3::new(-0.15, -0.05, 0.25), Vec3::Y), cascade_shadow_config, )); // Terrain commands.spawn(SceneRoot(asset_server.load( GltfAssetLabel::Scene(0).from_asset("models/terrain/Mountains.gltf"), ))); // Sky commands.spawn(( Mesh3d(meshes.add(Cuboid::new(2.0, 1.0, 1.0))), MeshMaterial3d(materials.add(StandardMaterial { base_color: Srgba::hex("888888").unwrap().into(), unlit: true, cull_mode: None, ..default() })), Transform::from_scale(Vec3::splat(20.0)), NotShadowCaster, )); } fn setup_instructions(mut commands: Commands) { commands.spawn((Text::new("Press Spacebar to Toggle Atmospheric Fog.\nPress S to Toggle Directional Light Fog Influence."), Node { position_type: PositionType::Absolute, bottom: px(12), left: px(12), ..default() }) ); } fn toggle_system(keycode: Res<ButtonInput<KeyCode>>, mut fog: Single<&mut DistanceFog>) { if keycode.just_pressed(KeyCode::Space) { let a = fog.color.alpha(); fog.color.set_alpha(1.0 - a); } if keycode.just_pressed(KeyCode::KeyS) { let a = fog.directional_light_color.alpha(); fog.directional_light_color.set_alpha(0.5 - a); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/mesh_ray_cast.rs
examples/3d/mesh_ray_cast.rs
//! Demonstrates how to use the [`MeshRayCast`] system parameter to chain multiple ray casts //! and bounce off of surfaces. use std::f32::consts::{FRAC_PI_2, PI}; use bevy::{ color::palettes::css, core_pipeline::tonemapping::Tonemapping, math::vec3, picking::backend::ray::RayMap, post_process::bloom::Bloom, prelude::*, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, bouncing_raycast) .insert_resource(ClearColor(Color::BLACK)) .run(); } const MAX_BOUNCES: usize = 64; const LASER_SPEED: f32 = 0.03; fn bouncing_raycast( mut ray_cast: MeshRayCast, mut gizmos: Gizmos, time: Res<Time>, // The ray map stores rays cast by the cursor ray_map: Res<RayMap>, ) { // Cast an automatically moving ray and bounce it off of surfaces let t = ops::cos((time.elapsed_secs() - 4.0).max(0.0) * LASER_SPEED) * PI; let ray_pos = Vec3::new(ops::sin(t), ops::cos(3.0 * t) * 0.5, ops::cos(t)) * 0.5; let ray_dir = Dir3::new(-ray_pos).unwrap(); let ray = Ray3d::new(ray_pos, ray_dir); gizmos.sphere(ray_pos, 0.1, Color::WHITE); bounce_ray(ray, &mut ray_cast, &mut gizmos, Color::from(css::RED)); // Cast a ray from the cursor and bounce it off of surfaces for (_, ray) in ray_map.iter() { bounce_ray(*ray, &mut ray_cast, &mut gizmos, Color::from(css::GREEN)); } } // Bounces a ray off of surfaces `MAX_BOUNCES` times. fn bounce_ray(mut ray: Ray3d, ray_cast: &mut MeshRayCast, gizmos: &mut Gizmos, color: Color) { let mut intersections = Vec::with_capacity(MAX_BOUNCES + 1); intersections.push((ray.origin, Color::srgb(30.0, 0.0, 0.0))); for i in 0..MAX_BOUNCES { // Cast the ray and get the first hit let Some((_, hit)) = ray_cast .cast_ray(ray, &MeshRayCastSettings::default()) .first() else { break; }; // Draw the point of intersection and add it to the list let brightness = 1.0 + 10.0 * (1.0 - i as f32 / MAX_BOUNCES as f32); intersections.push((hit.point, Color::BLACK.mix(&color, brightness))); gizmos.sphere(hit.point, 0.005, Color::BLACK.mix(&color, brightness * 2.0)); // Reflect the ray off of the surface ray.direction = Dir3::new(ray.direction.reflect(hit.normal)).unwrap(); ray.origin = hit.point + ray.direction * 1e-6; } gizmos.linestrip_gradient(intersections); } // Set up a simple 3D scene fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // Make a box of planes facing inward so the laser gets trapped inside let plane_mesh = meshes.add(Plane3d::default()); let plane_material = materials.add(Color::from(css::GRAY).with_alpha(0.01)); let create_plane = move |translation, rotation| { ( Transform::from_translation(translation) .with_rotation(Quat::from_scaled_axis(rotation)), Mesh3d(plane_mesh.clone()), MeshMaterial3d(plane_material.clone()), ) }; commands.spawn(create_plane(vec3(0.0, 0.5, 0.0), Vec3::X * PI)); commands.spawn(create_plane(vec3(0.0, -0.5, 0.0), Vec3::ZERO)); commands.spawn(create_plane(vec3(0.5, 0.0, 0.0), Vec3::Z * FRAC_PI_2)); commands.spawn(create_plane(vec3(-0.5, 0.0, 0.0), Vec3::Z * -FRAC_PI_2)); commands.spawn(create_plane(vec3(0.0, 0.0, 0.5), Vec3::X * -FRAC_PI_2)); commands.spawn(create_plane(vec3(0.0, 0.0, -0.5), Vec3::X * FRAC_PI_2)); // Light commands.spawn(( DirectionalLight::default(), Transform::from_rotation(Quat::from_euler(EulerRot::XYZ, -0.1, 0.2, 0.0)), )); // Camera commands.spawn(( Camera3d::default(), Transform::from_xyz(1.5, 1.5, 1.5).looking_at(Vec3::ZERO, Vec3::Y), Tonemapping::TonyMcMapface, Bloom::default(), )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/meshlet.rs
examples/3d/meshlet.rs
//! Meshlet rendering for dense high-poly scenes (experimental). // Note: This example showcases the meshlet API, but is not the type of scene that would benefit from using meshlets. use bevy::{ camera_controller::free_camera::{FreeCamera, FreeCameraPlugin}, light::{CascadeShadowConfigBuilder, DirectionalLightShadowMap}, pbr::experimental::meshlet::{MeshletMesh3d, MeshletPlugin}, prelude::*, render::render_resource::AsBindGroup, }; use std::f32::consts::PI; const ASSET_URL: &str = "https://github.com/bevyengine/bevy_asset_files/raw/6dccaef517bde74d1969734703709aead7211dbc/meshlet/bunny.meshlet_mesh"; fn main() { App::new() .insert_resource(DirectionalLightShadowMap { size: 4096 }) .add_plugins(( DefaultPlugins, MeshletPlugin { cluster_buffer_slots: 1 << 14, }, MaterialPlugin::<MeshletDebugMaterial>::default(), FreeCameraPlugin, )) .add_systems(Startup, setup) .run(); } fn setup( mut commands: Commands, asset_server: Res<AssetServer>, mut standard_materials: ResMut<Assets<StandardMaterial>>, mut debug_materials: ResMut<Assets<MeshletDebugMaterial>>, mut meshes: ResMut<Assets<Mesh>>, ) { commands.spawn(( Camera3d::default(), Transform::from_translation(Vec3::new(1.8, 0.4, -0.1)).looking_at(Vec3::ZERO, Vec3::Y), Msaa::Off, EnvironmentMapLight { diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"), specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"), intensity: 150.0, ..default() }, FreeCamera::default(), )); commands.spawn(( DirectionalLight { illuminance: light_consts::lux::FULL_DAYLIGHT, shadows_enabled: true, ..default() }, CascadeShadowConfigBuilder { num_cascades: 1, maximum_distance: 15.0, ..default() } .build(), Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, PI * -0.15, PI * -0.15)), )); // A custom file format storing a [`bevy_mesh::Mesh`] // that has been converted to a [`bevy_pbr::meshlet::MeshletMesh`] // using [`bevy_pbr::meshlet::MeshletMesh::from_mesh`], which is // a function only available when the `meshlet_processor` cargo feature is enabled. let meshlet_mesh_handle = asset_server.load(ASSET_URL); let debug_material = debug_materials.add(MeshletDebugMaterial::default()); for x in -2..=2 { commands.spawn(( MeshletMesh3d(meshlet_mesh_handle.clone()), MeshMaterial3d(standard_materials.add(StandardMaterial { base_color: match x { -2 => Srgba::hex("#dc2626").unwrap().into(), -1 => Srgba::hex("#ea580c").unwrap().into(), 0 => Srgba::hex("#facc15").unwrap().into(), 1 => Srgba::hex("#16a34a").unwrap().into(), 2 => Srgba::hex("#0284c7").unwrap().into(), _ => unreachable!(), }, perceptual_roughness: (x + 2) as f32 / 4.0, ..default() })), Transform::default() .with_scale(Vec3::splat(0.2)) .with_translation(Vec3::new(x as f32 / 2.0, 0.0, -0.3)), )); } for x in -2..=2 { commands.spawn(( MeshletMesh3d(meshlet_mesh_handle.clone()), MeshMaterial3d(debug_material.clone()), Transform::default() .with_scale(Vec3::splat(0.2)) .with_rotation(Quat::from_rotation_y(PI)) .with_translation(Vec3::new(x as f32 / 2.0, 0.0, 0.3)), )); } commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(5.0, 5.0))), MeshMaterial3d(standard_materials.add(StandardMaterial { base_color: Color::WHITE, perceptual_roughness: 1.0, ..default() })), )); } #[derive(Asset, TypePath, AsBindGroup, Clone, Default)] struct MeshletDebugMaterial { _dummy: (), } impl Material for MeshletDebugMaterial {}
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/anisotropy.rs
examples/3d/anisotropy.rs
//! Demonstrates anisotropy with the glTF sample barn lamp model. use std::fmt::Display; use bevy::{ color::palettes::{self, css::WHITE}, core_pipeline::Skybox, math::vec3, prelude::*, time::Stopwatch, }; /// The initial position of the camera. const CAMERA_INITIAL_POSITION: Vec3 = vec3(-0.4, 0.0, 0.0); /// The current settings of the app, as chosen by the user. #[derive(Resource)] struct AppStatus { /// Which type of light is in the scene. light_mode: LightMode, /// Whether anisotropy is enabled. anisotropy_enabled: bool, /// Which mesh is visible visible_scene: Scene, } /// Which type of light we're using: a directional light, a point light, or an /// environment map. #[derive(Clone, Copy, PartialEq, Default)] enum LightMode { /// A rotating directional light. #[default] Directional, /// A rotating point light. Point, /// An environment map (image-based lighting, including skybox). EnvironmentMap, } /// A component that stores the version of the material with anisotropy and the /// version of the material without it. /// /// This is placed on each mesh with a material. It exists so that the /// appropriate system can replace the materials when the user presses Enter to /// turn anisotropy on and off. #[derive(Component)] struct MaterialVariants { /// The version of the material in the glTF file, with anisotropy. anisotropic: Handle<StandardMaterial>, /// The version of the material with anisotropy removed. isotropic: Handle<StandardMaterial>, } #[derive(Default, Clone, Copy, PartialEq, Eq, Component)] enum Scene { #[default] BarnLamp, Sphere, } impl Scene { fn next(&self) -> Self { match self { Self::BarnLamp => Self::Sphere, Self::Sphere => Self::BarnLamp, } } } impl Display for Scene { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let scene_name = match self { Self::BarnLamp => "Barn Lamp", Self::Sphere => "Sphere", }; write!(f, "{scene_name}") } } /// The application entry point. fn main() { App::new() .init_resource::<AppStatus>() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "Bevy Anisotropy Example".into(), ..default() }), ..default() })) .add_systems(Startup, setup) .add_systems(Update, create_material_variants) .add_systems(Update, animate_light) .add_systems(Update, rotate_camera) .add_systems(Update, (handle_input, update_help_text).chain()) .run(); } /// Creates the initial scene. fn setup(mut commands: Commands, asset_server: Res<AssetServer>, app_status: Res<AppStatus>) { commands.spawn(( Camera3d::default(), Transform::from_translation(CAMERA_INITIAL_POSITION).looking_at(Vec3::ZERO, Vec3::Y), )); spawn_directional_light(&mut commands); commands.spawn(( SceneRoot(asset_server.load("models/AnisotropyBarnLamp/AnisotropyBarnLamp.gltf#Scene0")), Transform::from_xyz(0.0, 0.07, -0.13), Scene::BarnLamp, )); commands.spawn(( Mesh3d( asset_server.add( Mesh::from(Sphere::new(0.1)) .with_generated_tangents() .unwrap(), ), ), MeshMaterial3d(asset_server.add(StandardMaterial { base_color: palettes::tailwind::GRAY_300.into(), anisotropy_rotation: 0.5, anisotropy_strength: 1., ..default() })), Scene::Sphere, Visibility::Hidden, )); spawn_text(&mut commands, &app_status); } /// Spawns the help text. fn spawn_text(commands: &mut Commands, app_status: &AppStatus) { commands.spawn(( app_status.create_help_text(), Node { position_type: PositionType::Absolute, bottom: px(12), left: px(12), ..default() }, )); } /// For each material, creates a version with the anisotropy removed. /// /// This allows the user to press Enter to toggle anisotropy on and off. 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 }), }); } } /// A system that animates the light every frame, if there is one. 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 rotates the camera if the environment map is enabled. 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); } } /// Handles requests from the user to change the lighting or toggle anisotropy. 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; } } } /// A system that updates the help text based on the current app status. 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(); } } /// Adds the skybox and environment map to the scene. 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() }); } /// Spawns a rotating directional light. fn spawn_directional_light(commands: &mut Commands) { commands.spawn(DirectionalLight { color: WHITE.into(), illuminance: 3000.0, ..default() }); } /// Spawns a rotating point light. fn spawn_point_light(commands: &mut Commands) { commands.spawn(PointLight { color: WHITE.into(), intensity: 200000.0, ..default() }); } impl AppStatus { /// Creates the help text as appropriate for the current app status. 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!("{material_variant_help_text}\n{light_help_text}\n{mesh_help_text}",).into() } } impl Default for AppStatus { fn default() -> Self { Self { light_mode: default(), anisotropy_enabled: true, visible_scene: default(), } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/texture.rs
examples/3d/texture.rs
//! This example shows various ways to configure texture materials in 3D. use std::f32::consts::PI; use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } /// sets up a scene with textured entities fn setup( mut commands: Commands, asset_server: Res<AssetServer>, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // load a texture and retrieve its aspect ratio let texture_handle = asset_server.load("branding/bevy_logo_dark_big.png"); let aspect = 0.25; // create a new quad mesh. this is what we will apply the texture to let quad_width = 8.0; let quad_handle = meshes.add(Rectangle::new(quad_width, quad_width * aspect)); // this material renders the texture normally let material_handle = materials.add(StandardMaterial { base_color_texture: Some(texture_handle.clone()), alpha_mode: AlphaMode::Blend, unlit: true, ..default() }); // this material modulates the texture to make it red (and slightly transparent) let red_material_handle = materials.add(StandardMaterial { base_color: Color::srgba(1.0, 0.0, 0.0, 0.5), base_color_texture: Some(texture_handle.clone()), alpha_mode: AlphaMode::Blend, unlit: true, ..default() }); // and lets make this one blue! (and also slightly transparent) let blue_material_handle = materials.add(StandardMaterial { base_color: Color::srgba(0.0, 0.0, 1.0, 0.5), base_color_texture: Some(texture_handle), alpha_mode: AlphaMode::Blend, unlit: true, ..default() }); // textured quad - normal commands.spawn(( Mesh3d(quad_handle.clone()), MeshMaterial3d(material_handle), Transform::from_xyz(0.0, 0.0, 1.5).with_rotation(Quat::from_rotation_x(-PI / 5.0)), )); // textured quad - modulated commands.spawn(( Mesh3d(quad_handle.clone()), MeshMaterial3d(red_material_handle), Transform::from_rotation(Quat::from_rotation_x(-PI / 5.0)), )); // textured quad - modulated commands.spawn(( Mesh3d(quad_handle), MeshMaterial3d(blue_material_handle), Transform::from_xyz(0.0, 0.0, -1.5).with_rotation(Quat::from_rotation_x(-PI / 5.0)), )); // camera commands.spawn(( Camera3d::default(), Transform::from_xyz(3.0, 5.0, 8.0).looking_at(Vec3::ZERO, Vec3::Y), )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/solari.rs
examples/3d/solari.rs
//! Demonstrates realtime dynamic raytraced lighting using Bevy Solari. use argh::FromArgs; use bevy::{ camera::CameraMainTextureUsages, camera_controller::free_camera::{FreeCamera, FreeCameraPlugin}, diagnostic::{Diagnostic, DiagnosticPath, DiagnosticsStore}, gltf::GltfMaterialName, image::{ImageAddressMode, ImageLoaderSettings}, mesh::VertexAttributeValues, post_process::bloom::Bloom, prelude::*, render::{diagnostic::RenderDiagnosticsPlugin, render_resource::TextureUsages}, scene::SceneInstanceReady, solari::{ pathtracer::{Pathtracer, PathtracingPlugin}, prelude::{RaytracingMesh3d, SolariLighting, SolariPlugins}, }, }; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; use std::f32::consts::PI; #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] use bevy::anti_alias::dlss::{ Dlss, DlssProjectId, DlssRayReconstructionFeature, DlssRayReconstructionSupported, }; /// `bevy_solari` demo. #[derive(FromArgs, Resource, Clone, Copy)] struct Args { /// use the reference pathtracer instead of the realtime lighting system. #[argh(switch)] pathtracer: Option<bool>, /// stress test a scene with many lights. #[argh(switch)] many_lights: Option<bool>, } fn main() { let args: Args = argh::from_env(); let mut app = App::new(); #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] app.insert_resource(DlssProjectId(bevy_asset::uuid::uuid!( "5417916c-0291-4e3f-8f65-326c1858ab96" // Don't copy paste this - generate your own UUID! ))); app.add_plugins(( DefaultPlugins, SolariPlugins, FreeCameraPlugin, RenderDiagnosticsPlugin, )) .insert_resource(args); if args.many_lights == Some(true) { app.add_systems(Startup, setup_many_lights); } else { app.add_systems(Startup, setup_pica_pica); } if args.pathtracer == Some(true) { app.add_plugins(PathtracingPlugin); } else { if args.many_lights != Some(true) { app.add_systems(Update, (pause_scene, toggle_lights, patrol_path)) .add_systems(PostUpdate, update_control_text); } app.add_systems(PostUpdate, update_performance_text); } app.run(); } fn setup_pica_pica( mut commands: Commands, asset_server: Res<AssetServer>, args: Res<Args>, #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] dlss_rr_supported: Option< Res<DlssRayReconstructionSupported>, >, ) { commands .spawn(( SceneRoot( asset_server.load( GltfAssetLabel::Scene(0) .from_asset("https://github.com/bevyengine/bevy_asset_files/raw/2a5950295a8b6d9d051d59c0df69e87abcda58c3/pica_pica/mini_diorama_01.glb") ), ), Transform::from_scale(Vec3::splat(10.0)), )) .observe(add_raytracing_meshes_on_scene_load); commands .spawn(( SceneRoot(asset_server.load( GltfAssetLabel::Scene(0).from_asset("https://github.com/bevyengine/bevy_asset_files/raw/2a5950295a8b6d9d051d59c0df69e87abcda58c3/pica_pica/robot_01.glb") )), Transform::from_scale(Vec3::splat(2.0)) .with_translation(Vec3::new(-2.0, 0.05, -2.1)) .with_rotation(Quat::from_rotation_y(PI / 2.0)), PatrolPath { path: vec![ (Vec3::new(-2.0, 0.05, -2.1), Quat::from_rotation_y(PI / 2.0)), (Vec3::new(2.2, 0.05, -2.1), Quat::from_rotation_y(0.0)), ( Vec3::new(2.2, 0.05, 2.1), Quat::from_rotation_y(3.0 * PI / 2.0), ), (Vec3::new(-2.0, 0.05, 2.1), Quat::from_rotation_y(PI)), ], i: 0, }, )) .observe(add_raytracing_meshes_on_scene_load); commands.spawn(( DirectionalLight { illuminance: light_consts::lux::FULL_DAYLIGHT, shadows_enabled: false, // Solari replaces shadow mapping ..default() }, Transform::from_rotation(Quat::from_xyzw( -0.13334629, -0.86597735, -0.3586996, 0.3219264, )), )); let mut camera = commands.spawn(( Camera3d::default(), Camera { clear_color: ClearColorConfig::Custom(Color::BLACK), ..default() }, FreeCamera { walk_speed: 3.0, run_speed: 10.0, ..Default::default() }, Transform::from_translation(Vec3::new(0.219417, 2.5764852, 6.9718704)).with_rotation( Quat::from_xyzw(-0.1466768, 0.013738206, 0.002037309, 0.989087), ), // Msaa::Off and CameraMainTextureUsages with STORAGE_BINDING are required for Solari CameraMainTextureUsages::default().with(TextureUsages::STORAGE_BINDING), Msaa::Off, )); if args.pathtracer == Some(true) { camera.insert(Pathtracer::default()); } else { camera.insert(SolariLighting::default()); } // Using DLSS Ray Reconstruction for denoising (and cheaper rendering via upscaling) is _highly_ recommended when using Solari #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] if dlss_rr_supported.is_some() { camera.insert(Dlss::<DlssRayReconstructionFeature> { perf_quality_mode: Default::default(), reset: Default::default(), _phantom_data: Default::default(), }); } commands.spawn(( ControlText, Text::default(), Node { position_type: PositionType::Absolute, bottom: px(12.0), left: px(12.0), ..default() }, )); commands.spawn(( Node { position_type: PositionType::Absolute, right: px(0.0), padding: px(4.0).all(), border_radius: BorderRadius::bottom_left(px(4.0)), ..default() }, BackgroundColor(Color::srgba(0.10, 0.10, 0.10, 0.8)), children![( PerformanceText, Text::default(), TextFont { font_size: 8.0, ..default() }, )], )); } fn setup_many_lights( mut commands: Commands, asset_server: Res<AssetServer>, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, args: Res<Args>, #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] dlss_rr_supported: Option< Res<DlssRayReconstructionSupported>, >, ) { let mut rng = ChaCha8Rng::seed_from_u64(42); let mut plane_mesh = Plane3d::default() .mesh() .size(40.0, 40.0) .build() .with_generated_tangents() .unwrap(); match plane_mesh.attribute_mut(Mesh::ATTRIBUTE_UV_0).unwrap() { VertexAttributeValues::Float32x2(items) => { items.iter_mut().flatten().for_each(|x| *x *= 3.0); } _ => unreachable!(), } let plane_mesh = meshes.add(plane_mesh); let cube_mesh = meshes.add( Cuboid::default() .mesh() .build() .with_generated_tangents() .unwrap(), ); let sphere_mesh = meshes.add( Sphere::default() .mesh() .build() .with_generated_tangents() .unwrap(), ); commands .spawn(( RaytracingMesh3d(plane_mesh.clone()), MeshMaterial3d(materials.add(StandardMaterial { base_color_texture: Some( asset_server.load_with_settings::<Image, ImageLoaderSettings>( "textures/uv_checker_bw.png", |settings| { settings .sampler .get_or_init_descriptor() .set_address_mode(ImageAddressMode::Repeat); }, ), ), perceptual_roughness: 0.0, ..default() })), )) .insert_if(Mesh3d(plane_mesh), || args.pathtracer != Some(true)); for _ in 0..200 { commands .spawn(( RaytracingMesh3d(cube_mesh.clone()), MeshMaterial3d(materials.add(StandardMaterial { base_color: Color::srgb(rng.random(), rng.random(), rng.random()), perceptual_roughness: rng.random(), ..default() })), Transform::default() .with_scale(Vec3 { x: rng.random_range(0.2..=2.0), y: rng.random_range(0.2..=2.0), z: rng.random_range(0.2..=2.0), }) .with_translation(Vec3::new( rng.random_range(-18.0..=18.0), 0.2, rng.random_range(-18.0..=18.0), )), )) .insert_if(Mesh3d(cube_mesh.clone()), || args.pathtracer != Some(true)); } for _ in 0..100 { commands .spawn(( RaytracingMesh3d(sphere_mesh.clone()), MeshMaterial3d( materials.add(StandardMaterial { emissive: Color::linear_rgb( rng.random::<f32>() * 20000.0, rng.random::<f32>() * 20000.0, rng.random::<f32>() * 20000.0, ) .into(), ..default() }), ), Transform::default().with_translation(Vec3::new( rng.random_range(-18.0..=18.0), rng.random_range(6.0..=9.0), rng.random_range(-18.0..=18.0), )), )) .insert_if(Mesh3d(sphere_mesh.clone()), || { args.pathtracer != Some(true) }); } let mut camera = commands.spawn(( Camera3d::default(), Camera { clear_color: ClearColorConfig::Custom(Color::BLACK), ..default() }, FreeCamera { walk_speed: 3.0, run_speed: 10.0, ..Default::default() }, Transform::from_translation(Vec3::new(0.0919233, 7.5015035, 28.449198)).with_rotation( Quat::from_xyzw(-0.18394549, 0.0019948867, 0.0003733214, 0.98293436), ), // Msaa::Off and CameraMainTextureUsages with STORAGE_BINDING are required for Solari CameraMainTextureUsages::default().with(TextureUsages::STORAGE_BINDING), Msaa::Off, Bloom { intensity: 0.1, ..Bloom::NATURAL }, )); if args.pathtracer == Some(true) { camera.insert(Pathtracer::default()); } else { camera.insert(SolariLighting::default()); } // Using DLSS Ray Reconstruction for denoising (and cheaper rendering via upscaling) is _highly_ recommended when using Solari #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] if dlss_rr_supported.is_some() { camera.insert(Dlss::<DlssRayReconstructionFeature> { perf_quality_mode: Default::default(), reset: Default::default(), _phantom_data: Default::default(), }); } commands.spawn(( Node { position_type: PositionType::Absolute, right: px(0.0), padding: px(4.0).all(), border_radius: BorderRadius::bottom_left(px(4.0)), ..default() }, BackgroundColor(Color::srgba(0.10, 0.10, 0.10, 0.8)), children![( PerformanceText, Text::default(), TextFont { font_size: 8.0, ..default() }, )], )); } fn add_raytracing_meshes_on_scene_load( scene_ready: On<SceneInstanceReady>, children: Query<&Children>, mesh_query: Query<( &Mesh3d, &MeshMaterial3d<StandardMaterial>, Option<&GltfMaterialName>, )>, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, mut commands: Commands, args: Res<Args>, ) { for descendant in children.iter_descendants(scene_ready.entity) { if let Ok((Mesh3d(mesh_handle), MeshMaterial3d(material_handle), material_name)) = mesh_query.get(descendant) { // Add raytracing mesh component commands .entity(descendant) .insert(RaytracingMesh3d(mesh_handle.clone())); // Ensure meshes are Solari compatible let mesh = meshes.get_mut(mesh_handle).unwrap(); if !mesh.contains_attribute(Mesh::ATTRIBUTE_UV_0) { let vertex_count = mesh.count_vertices(); mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, vec![[0.0, 0.0]; vertex_count]); mesh.insert_attribute( Mesh::ATTRIBUTE_TANGENT, vec![[0.0, 0.0, 0.0, 0.0]; vertex_count], ); } if !mesh.contains_attribute(Mesh::ATTRIBUTE_TANGENT) { mesh.generate_tangents().unwrap(); } if mesh.contains_attribute(Mesh::ATTRIBUTE_UV_1) { mesh.remove_attribute(Mesh::ATTRIBUTE_UV_1); } // Prevent rasterization if using pathtracer if args.pathtracer == Some(true) { commands.entity(descendant).remove::<Mesh3d>(); } // Adjust scene materials to better demo Solari features if material_name.map(|s| s.0.as_str()) == Some("material") { let material = materials.get_mut(material_handle).unwrap(); material.emissive = LinearRgba::BLACK; } if material_name.map(|s| s.0.as_str()) == Some("Lights") { let material = materials.get_mut(material_handle).unwrap(); material.emissive = LinearRgba::from(Color::srgb(0.941, 0.714, 0.043)) * 1_000_000.0; material.alpha_mode = AlphaMode::Opaque; material.specular_transmission = 0.0; commands.insert_resource(RobotLightMaterial(material_handle.clone())); } if material_name.map(|s| s.0.as_str()) == Some("Glass_Dark_01") { let material = materials.get_mut(material_handle).unwrap(); material.alpha_mode = AlphaMode::Opaque; material.specular_transmission = 0.0; } } } } fn pause_scene(mut time: ResMut<Time<Virtual>>, key_input: Res<ButtonInput<KeyCode>>) { if key_input.just_pressed(KeyCode::Space) { time.toggle(); } } #[derive(Resource)] struct RobotLightMaterial(Handle<StandardMaterial>); fn toggle_lights( key_input: Res<ButtonInput<KeyCode>>, robot_light_material: Option<Res<RobotLightMaterial>>, mut materials: ResMut<Assets<StandardMaterial>>, directional_light: Query<Entity, With<DirectionalLight>>, mut commands: Commands, ) { if key_input.just_pressed(KeyCode::Digit1) { if let Ok(directional_light) = directional_light.single() { commands.entity(directional_light).despawn(); } else { commands.spawn(( DirectionalLight { illuminance: light_consts::lux::FULL_DAYLIGHT, shadows_enabled: false, // Solari replaces shadow mapping ..default() }, Transform::from_rotation(Quat::from_xyzw( -0.13334629, -0.86597735, -0.3586996, 0.3219264, )), )); } } if key_input.just_pressed(KeyCode::Digit2) && let Some(robot_light_material) = robot_light_material { let material = materials.get_mut(&robot_light_material.0).unwrap(); if material.emissive == LinearRgba::BLACK { material.emissive = LinearRgba::from(Color::srgb(0.941, 0.714, 0.043)) * 1_000_000.0; } else { material.emissive = LinearRgba::BLACK; } } } #[derive(Component)] struct PatrolPath { path: Vec<(Vec3, Quat)>, i: usize, } fn patrol_path(mut query: Query<(&mut PatrolPath, &mut Transform)>, time: Res<Time<Virtual>>) { for (mut path, mut transform) in query.iter_mut() { let (mut target_position, mut target_rotation) = path.path[path.i]; let mut distance_to_target = transform.translation.distance(target_position); if distance_to_target < 0.01 { transform.translation = target_position; transform.rotation = target_rotation; path.i = (path.i + 1) % path.path.len(); (target_position, target_rotation) = path.path[path.i]; distance_to_target = transform.translation.distance(target_position); } let direction = (target_position - transform.translation).normalize(); let movement = direction * time.delta_secs(); if movement.length() > distance_to_target { transform.translation = target_position; transform.rotation = target_rotation; } else { transform.translation += movement; } } } #[derive(Component)] struct ControlText; fn update_control_text( mut text: Single<&mut Text, With<ControlText>>, robot_light_material: Option<Res<RobotLightMaterial>>, materials: Res<Assets<StandardMaterial>>, directional_light: Query<Entity, With<DirectionalLight>>, time: Res<Time<Virtual>>, #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] dlss_rr_supported: Option< Res<DlssRayReconstructionSupported>, >, ) { text.0.clear(); if time.is_paused() { text.0.push_str("(Space): Resume"); } else { text.0.push_str("(Space): Pause"); } if directional_light.single().is_ok() { text.0.push_str("\n(1): Disable directional light"); } else { text.0.push_str("\n(1): Enable directional light"); } match robot_light_material.and_then(|m| materials.get(&m.0)) { Some(robot_light_material) if robot_light_material.emissive != LinearRgba::BLACK => { text.0.push_str("\n(2): Disable robot emissive light"); } _ => { text.0.push_str("\n(2): Enable robot emissive light"); } } #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] if dlss_rr_supported.is_some() { text.0 .push_str("\nDenoising: DLSS Ray Reconstruction enabled"); } else { text.0 .push_str("\nDenoising: DLSS Ray Reconstruction not supported"); } #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))] text.0 .push_str("\nDenoising: App not compiled with DLSS support"); } #[derive(Component)] struct PerformanceText; fn update_performance_text( mut text: Single<&mut Text, With<PerformanceText>>, diagnostics: Res<DiagnosticsStore>, ) { text.0.clear(); let mut total = 0.0; let mut add_diagnostic = |name: &str, path: &'static str| { let path = DiagnosticPath::new(path); if let Some(average) = diagnostics.get(&path).and_then(Diagnostic::average) { text.push_str(&format!("{name:17} {average:.2} ms\n")); total += average; } }; (add_diagnostic)( "Light tiles", "render/solari_lighting/presample_light_tiles/elapsed_gpu", ); (add_diagnostic)( "World cache", "render/solari_lighting/world_cache/elapsed_gpu", ); (add_diagnostic)( "Direct lighting", "render/solari_lighting/direct_lighting/elapsed_gpu", ); (add_diagnostic)( "Diffuse indirect", "render/solari_lighting/diffuse_indirect_lighting/elapsed_gpu", ); (add_diagnostic)( "Specular indirect", "render/solari_lighting/specular_indirect_lighting/elapsed_gpu", ); text.push_str(&format!("{:17} TODO\n", "DLSS-RR")); text.push_str(&format!("\n{:17} {total:.2} ms", "Total")); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/pbr.rs
examples/3d/pbr.rs
//! This example shows how to configure Physically Based Rendering (PBR) parameters. use bevy::camera::ScalingMode; use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, environment_map_load_finish) .run(); } /// set up a simple 3D scene fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, asset_server: Res<AssetServer>, ) { let sphere_mesh = meshes.add(Sphere::new(0.45)); // add entities to the world for y in -2..=2 { for x in -5..=5 { let x01 = (x + 5) as f32 / 10.0; let y01 = (y + 2) as f32 / 4.0; // sphere commands.spawn(( Mesh3d(sphere_mesh.clone()), MeshMaterial3d(materials.add(StandardMaterial { base_color: Srgba::hex("#ffd891").unwrap().into(), // vary key PBR parameters on a grid of spheres to show the effect metallic: y01, perceptual_roughness: x01, ..default() })), Transform::from_xyz(x as f32, y as f32 + 0.5, 0.0), )); } } // unlit sphere commands.spawn(( Mesh3d(sphere_mesh), MeshMaterial3d(materials.add(StandardMaterial { base_color: Srgba::hex("#ffd891").unwrap().into(), // vary key PBR parameters on a grid of spheres to show the effect unlit: true, ..default() })), Transform::from_xyz(-5.0, -2.5, 0.0), )); commands.spawn(( DirectionalLight { illuminance: 1_500., ..default() }, Transform::from_xyz(50.0, 50.0, 50.0).looking_at(Vec3::ZERO, Vec3::Y), )); // labels commands.spawn(( Text::new("Perceptual Roughness"), TextFont { font_size: 30.0, ..default() }, Node { position_type: PositionType::Absolute, top: px(20), left: px(100), ..default() }, )); commands.spawn(( Text::new("Metallic"), TextFont { font_size: 30.0, ..default() }, Node { position_type: PositionType::Absolute, top: px(130), right: Val::ZERO, ..default() }, UiTransform { rotation: Rot2::degrees(90.), ..default() }, )); commands.spawn(( Text::new("Loading Environment Map..."), TextFont { font_size: 30.0, ..default() }, Node { position_type: PositionType::Absolute, bottom: px(20), right: px(20), ..default() }, EnvironmentMapLabel, )); // camera commands.spawn(( Camera3d::default(), Transform::from_xyz(0.0, 0.0, 8.0).looking_at(Vec3::default(), Vec3::Y), Projection::from(OrthographicProjection { scale: 0.01, scaling_mode: ScalingMode::WindowSize, ..OrthographicProjection::default_3d() }), 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: 900.0, ..default() }, )); } fn environment_map_load_finish( mut commands: Commands, asset_server: Res<AssetServer>, environment_map: Single<&EnvironmentMapLight>, label_entity: Option<Single<Entity, With<EnvironmentMapLabel>>>, ) { if asset_server .load_state(&environment_map.diffuse_map) .is_loaded() && asset_server .load_state(&environment_map.specular_map) .is_loaded() { // Do not attempt to remove `label_entity` if it has already been removed. if let Some(label_entity) = label_entity { commands.entity(*label_entity).despawn(); } } } #[derive(Component)] struct EnvironmentMapLabel;
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/mirror.rs
examples/3d/mirror.rs
//! Demonstrates how to create a mirror with a second camera. use std::f32::consts::FRAC_PI_2; use crate::widgets::{RadioButton, WidgetClickEvent, WidgetClickSender}; use bevy::camera::RenderTarget; use bevy::{ asset::RenderAssetUsages, color::palettes::css::GREEN, input::mouse::AccumulatedMouseMotion, math::{reflection_matrix, uvec2, vec3}, pbr::{ExtendedMaterial, MaterialExtension}, prelude::*, render::render_resource::{ AsBindGroup, Extent3d, TextureDimension, TextureFormat, TextureUsages, }, shader::ShaderRef, window::{PrimaryWindow, WindowResized}, }; #[path = "../helpers/widgets.rs"] mod widgets; /// A resource that stores a handle to the image that contains the rendered /// mirror world. #[derive(Resource)] struct MirrorImage(Handle<Image>); /// A marker component for the camera that renders the mirror world. #[derive(Component)] struct MirrorCamera; /// A marker component for the mirror mesh itself. #[derive(Component)] struct Mirror; /// The dummy material extension that we use for the mirror surface. /// /// This shader samples its emissive texture at the screen space position of /// each fragment rather than at the UVs. Effectively, this uses a PBR shader as /// a mask that copies a portion of the emissive texture to the screen, all in /// screen space. /// /// We use [`ExtendedMaterial`], as that's the easiest way to implement custom /// shaders that modify the built-in [`StandardMaterial`]. We don't require any /// extra data to be passed to the shader beyond the [`StandardMaterial`] PBR /// fields, but currently Bevy requires at least one field to be present in the /// extended material, so we simply have an unused field. #[derive(Clone, AsBindGroup, Asset, Reflect)] struct ScreenSpaceTextureExtension { /// An unused value that we have just to satisfy [`ExtendedMaterial`] /// requirements. #[uniform(100)] dummy: f32, } impl MaterialExtension for ScreenSpaceTextureExtension { fn fragment_shader() -> ShaderRef { "shaders/screen_space_texture_material.wgsl".into() } } /// The action that will be performed when the user drags the mouse: either /// moving the camera or moving the rigged model. #[derive(Clone, Copy, PartialEq, Default)] enum DragAction { /// Dragging will move the camera. #[default] MoveCamera, /// Dragging will move the animated fox. MoveFox, } /// The settings that the user has currently chosen. /// /// Currently, this just consists of the [`DragAction`]. #[derive(Resource, Default)] struct AppStatus { /// The action that will be performed when the user drags the mouse: either /// moving the camera or moving the rigged model. drag_action: DragAction, } /// A marker component for the help text at the top of the screen. #[derive(Clone, Copy, Component)] struct HelpText; /// The coordinates that the camera looks at. const CAMERA_TARGET: Vec3 = vec3(-25.0, 20.0, 0.0); /// The camera stays this distance in meters from the camera target. const CAMERA_ORBIT_DISTANCE: f32 = 500.0; /// The speed at which the user can move the camera vertically, in radians per /// mouse input unit. const CAMERA_PITCH_SPEED: f32 = 0.003; /// The speed at which the user can move the camera horizontally, in radians per /// mouse input unit. const CAMERA_YAW_SPEED: f32 = 0.004; // Limiting pitch stops some unexpected rotation past 90° up or down. const CAMERA_PITCH_LIMIT: f32 = FRAC_PI_2 - 0.01; /// The angle that the mirror faces. /// /// The mirror is rotated across the X axis in this many radians. const MIRROR_ROTATION_ANGLE: f32 = -FRAC_PI_2; const MIRROR_POSITION: Vec3 = vec3(-25.0, 75.0, 0.0); /// The path to the animated fox model. static FOX_ASSET_PATH: &str = "models/animated/Fox.glb"; /// The app entry point. fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "Bevy Mirror Example".into(), ..default() }), ..default() })) .add_plugins(MaterialPlugin::< ExtendedMaterial<StandardMaterial, ScreenSpaceTextureExtension>, >::default()) .init_resource::<AppStatus>() .add_message::<WidgetClickEvent<DragAction>>() .add_systems(Startup, setup) .add_systems(Update, handle_window_resize_messages) .add_systems(Update, (move_camera_on_mouse_down, move_fox_on_mouse_down)) .add_systems(Update, widgets::handle_ui_interactions::<DragAction>) .add_systems( Update, (handle_mouse_action_change, update_radio_buttons) .after(widgets::handle_ui_interactions::<DragAction>), ) .add_systems( Update, update_mirror_camera_on_main_camera_transform_change.after(move_camera_on_mouse_down), ) .add_systems(Update, play_fox_animation) .add_systems(Update, update_help_text) .run(); } /// A startup system that spawns the scene and sets up the mirror render target. fn setup( mut commands: Commands, windows_query: Query<&Window>, asset_server: Res<AssetServer>, mut meshes: ResMut<Assets<Mesh>>, mut standard_materials: ResMut<Assets<StandardMaterial>>, mut screen_space_texture_materials: ResMut< Assets<ExtendedMaterial<StandardMaterial, ScreenSpaceTextureExtension>>, >, mut images: ResMut<Assets<Image>>, app_status: Res<AppStatus>, ) { // Spawn the main camera. let camera_projection = PerspectiveProjection::default(); let camera_transform = spawn_main_camera(&mut commands, &camera_projection); // Spawn the light. spawn_light(&mut commands); // Spawn the objects reflected in the mirror. spawn_ground_plane(&mut commands, &mut meshes, &mut standard_materials); spawn_fox(&mut commands, &asset_server); // Spawn the mirror and associated camera. let mirror_render_target_image = create_mirror_texture_resource(&mut commands, &windows_query, &mut images); let mirror_transform = spawn_mirror( &mut commands, &mut meshes, &mut screen_space_texture_materials, mirror_render_target_image.clone(), ); spawn_mirror_camera( &mut commands, &camera_transform, &camera_projection, &mirror_transform, mirror_render_target_image, ); // Spawn the UI. spawn_buttons(&mut commands); spawn_help_text(&mut commands, &app_status); } /// Spawns the main camera (not the mirror camera). fn spawn_main_camera( commands: &mut Commands, camera_projection: &PerspectiveProjection, ) -> Transform { let camera_transform = Transform::from_translation( vec3(-2.0, 1.0, -2.0).normalize_or_zero() * CAMERA_ORBIT_DISTANCE, ) .looking_at(CAMERA_TARGET, Vec3::Y); commands.spawn(( Camera3d::default(), camera_transform, Projection::Perspective(camera_projection.clone()), )); camera_transform } /// Spawns a directional light to illuminate the scene. fn spawn_light(commands: &mut Commands) { commands.spawn(( DirectionalLight { illuminance: 5000.0, ..default() }, Transform::from_xyz(-85.0, 16.0, -200.0).looking_at(vec3(-50.0, 0.0, 100.0), Vec3::Y), )); } /// Spawns the circular ground plane object. fn spawn_ground_plane( commands: &mut Commands, meshes: &mut Assets<Mesh>, standard_materials: &mut Assets<StandardMaterial>, ) { commands.spawn(( Mesh3d(meshes.add(Circle::new(200.0))), MeshMaterial3d(standard_materials.add(Color::from(GREEN))), Transform::from_rotation(Quat::from_rotation_x(-FRAC_PI_2)) .with_translation(vec3(-25.0, 0.0, 0.0)), )); } /// Creates the initial image that the mirror camera will render the mirror /// world to. fn create_mirror_texture_resource( commands: &mut Commands, windows_query: &Query<&Window>, images: &mut Assets<Image>, ) -> Handle<Image> { let window = windows_query.iter().next().expect("No window found"); let window_size = uvec2(window.physical_width(), window.physical_height()); let image = create_mirror_texture_image(images, window_size); commands.insert_resource(MirrorImage(image.clone())); image } /// Spawns the camera that renders the mirror world. fn spawn_mirror_camera( commands: &mut Commands, camera_transform: &Transform, camera_projection: &PerspectiveProjection, mirror_transform: &Transform, mirror_render_target: Handle<Image>, ) { let (mirror_camera_transform, mirror_camera_projection) = calculate_mirror_camera_transform_and_projection( camera_transform, camera_projection, mirror_transform, ); commands.spawn(( Camera3d::default(), Camera { order: -1, // Reflecting the model across the mirror will flip the winding of // all the polygons. Therefore, in order to properly backface cull, // we need to turn on `invert_culling`. invert_culling: true, ..default() }, RenderTarget::Image(mirror_render_target.clone().into()), mirror_camera_transform, Projection::Perspective(mirror_camera_projection), MirrorCamera, )); } /// Spawns the animated fox. /// /// Note that this doesn't play the animation; that's handled in /// [`play_fox_animation`]. fn spawn_fox(commands: &mut Commands, asset_server: &AssetServer) { commands.spawn(( SceneRoot(asset_server.load(GltfAssetLabel::Scene(0).from_asset(FOX_ASSET_PATH))), Transform::from_xyz(-50.0, 0.0, -100.0), )); } /// Spawns the mirror plane mesh and returns its transform. fn spawn_mirror( commands: &mut Commands, meshes: &mut Assets<Mesh>, screen_space_texture_materials: &mut Assets< ExtendedMaterial<StandardMaterial, ScreenSpaceTextureExtension>, >, mirror_render_target: Handle<Image>, ) -> Transform { let mirror_transform = Transform::from_scale(vec3(300.0, 1.0, 150.0)) .with_rotation(Quat::from_rotation_x(MIRROR_ROTATION_ANGLE)) .with_translation(MIRROR_POSITION); commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(1.0, 1.0))), MeshMaterial3d(screen_space_texture_materials.add(ExtendedMaterial { base: StandardMaterial { base_color: Color::BLACK, emissive: Color::WHITE.into(), emissive_texture: Some(mirror_render_target), perceptual_roughness: 0.0, metallic: 1.0, ..default() }, extension: ScreenSpaceTextureExtension { dummy: 0.0 }, })), mirror_transform, Mirror, )); mirror_transform } /// Spawns the buttons at the bottom of the screen. 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(), children![widgets::option_buttons( "Drag Action", &[ (DragAction::MoveCamera, "Move Camera"), (DragAction::MoveFox, "Move Fox"), ], )], )); } /// Given the transform and projection of the main camera, returns an /// appropriate transform and projection for the mirror camera. fn calculate_mirror_camera_transform_and_projection( main_camera_transform: &Transform, main_camera_projection: &PerspectiveProjection, mirror_transform: &Transform, ) -> (Transform, PerspectiveProjection) { // Calculate the reflection matrix (a.k.a. Householder matrix) that will // reflect the scene across the mirror plane. // // Note that you must calculate this in *matrix* form and only *afterward* // convert to a `Transform` instead of composing `Transform`s. This is // because the reflection matrix has non-uniform scale, and composing // transforms can't always handle composition of matrices with non-uniform // scales. let mirror_camera_transform = Transform::from_matrix( Mat4::from_mat3a(reflection_matrix(Vec3::NEG_Z)) * main_camera_transform.to_matrix(), ); // Compute the distance from the camera to the mirror plane. This will be // used to calculate the distance to the near clip plane for the mirror // world. let distance_from_camera_to_mirror = InfinitePlane3d::new(mirror_transform.rotation * Vec3::Y) .signed_distance( Isometry3d::IDENTITY, mirror_transform.translation - main_camera_transform.translation, ); // Compute the normal of the mirror plane in view space. let view_from_world = main_camera_transform.compute_affine().matrix3.inverse(); let mirror_projection_plane_normal = (view_from_world * (mirror_transform.rotation * Vec3::NEG_Y)).normalize(); // Compute the final projection. It should match the main camera projection, // except that `near` and `near_normal` should be set to the updated near // plane and near normal plane as above. let mirror_camera_projection = PerspectiveProjection { near_clip_plane: mirror_projection_plane_normal.extend(distance_from_camera_to_mirror), ..*main_camera_projection }; (mirror_camera_transform, mirror_camera_projection) } /// A system that resizes the render target image when the user resizes the window. /// /// Since the image that stores the rendered mirror world has the same physical /// size as the window, we need to reallocate it and reattach it to the mirror /// material whenever the window size changes. fn handle_window_resize_messages( windows_query: Query<&Window>, mut mirror_cameras_query: Query<&mut RenderTarget, With<MirrorCamera>>, mut images: ResMut<Assets<Image>>, mut mirror_image: ResMut<MirrorImage>, mut screen_space_texture_materials: ResMut< Assets<ExtendedMaterial<StandardMaterial, ScreenSpaceTextureExtension>>, >, mut resize_messages: MessageReader<WindowResized>, ) { // We run at most once, regardless of the number of window resize messages // there were this frame. let Some(resize_message) = resize_messages.read().next() else { return; }; let Ok(window) = windows_query.get(resize_message.window) else { return; }; let window_size = uvec2(window.physical_width(), window.physical_height()); let image = create_mirror_texture_image(&mut images, window_size); images.remove(mirror_image.0.id()); mirror_image.0 = image.clone(); for mut target in mirror_cameras_query.iter_mut() { *target = image.clone().into(); } for (_, material) in screen_space_texture_materials.iter_mut() { material.base.emissive_texture = Some(image.clone()); } } /// Creates the image that will be used to store the reflected scene. fn create_mirror_texture_image(images: &mut Assets<Image>, window_size: UVec2) -> Handle<Image> { let mirror_image_extent = Extent3d { width: window_size.x, height: window_size.y, depth_or_array_layers: 1, }; let mut image = Image::new_uninit( mirror_image_extent, TextureDimension::D2, TextureFormat::Bgra8UnormSrgb, RenderAssetUsages::MAIN_WORLD | RenderAssetUsages::RENDER_WORLD, ); image.texture_descriptor.usage |= TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST | TextureUsages::RENDER_ATTACHMENT; images.add(image) } // Moves the fox when the user moves the mouse with the left button down. fn move_fox_on_mouse_down( mut scene_roots_query: Query<&mut Transform, With<SceneRoot>>, windows_query: Query<&Window, With<PrimaryWindow>>, cameras_query: Query<(&Camera, &GlobalTransform)>, interactions_query: Query<&Interaction, With<RadioButton>>, buttons: Res<ButtonInput<MouseButton>>, app_status: Res<AppStatus>, ) { // Only process the mouse motion if the left mouse button is pressed, the // mouse action is set to move the fox, and the pointer isn't over a UI // widget. if app_status.drag_action != DragAction::MoveFox || !buttons.pressed(MouseButton::Left) || interactions_query .iter() .any(|interaction| *interaction != Interaction::None) { return; } // Find out where the user clicked the mouse. let Some(mouse_position) = windows_query .iter() .next() .and_then(Window::cursor_position) else { return; }; // Grab the camera. let Some((camera, camera_transform)) = cameras_query.iter().next() else { return; }; // Figure out where the user clicked on the plane. let Ok(ray) = camera.viewport_to_world(camera_transform, mouse_position) else { return; }; let Some(ray_distance) = ray.intersect_plane(Vec3::ZERO, InfinitePlane3d::new(Vec3::Y)) else { return; }; let plane_intersection = ray.origin + ray.direction.normalize() * ray_distance; // Move the fox. for mut transform in scene_roots_query.iter_mut() { transform.translation = transform.translation.with_xz(plane_intersection.xz()); } } /// A system that changes the drag action when the user clicks on one of the /// radio buttons. fn handle_mouse_action_change( mut app_status: ResMut<AppStatus>, mut messages: MessageReader<WidgetClickEvent<DragAction>>, ) { for message in messages.read() { app_status.drag_action = **message; } } /// A system that updates the radio buttons at the bottom of the screen to /// reflect the current drag action. fn update_radio_buttons( mut widgets_query: Query<( Entity, Option<&mut BackgroundColor>, Has<Text>, &WidgetClickSender<DragAction>, )>, app_status: Res<AppStatus>, mut text_ui_writer: TextUiWriter, ) { for (entity, maybe_bg_color, has_text, sender) in &mut widgets_query { let selected = app_status.drag_action == **sender; if let Some(mut bg_color) = maybe_bg_color { widgets::update_ui_radio_button(&mut bg_color, selected); } if has_text { widgets::update_ui_radio_button_text(entity, &mut text_ui_writer, selected); } } } /// A system that processes user mouse actions that move the camera. /// /// This is mostly copied from `examples/camera/camera_orbit.rs`. fn move_camera_on_mouse_down( mut main_cameras_query: Query<&mut Transform, (With<Camera>, Without<MirrorCamera>)>, interactions_query: Query<&Interaction, With<RadioButton>>, mouse_buttons: Res<ButtonInput<MouseButton>>, mouse_motion: Res<AccumulatedMouseMotion>, app_status: Res<AppStatus>, ) { // Only process the mouse motion if the left mouse button is pressed, the // mouse action is set to move the fox, and the pointer isn't over a UI // widget. if app_status.drag_action != DragAction::MoveCamera || !mouse_buttons.pressed(MouseButton::Left) || interactions_query .iter() .any(|interaction| *interaction != Interaction::None) { return; } let delta = mouse_motion.delta; // Mouse motion is one of the few inputs that should not be multiplied by delta time, // as we are already receiving the full movement since the last frame was rendered. Multiplying // by delta time here would make the movement slower that it should be. let delta_pitch = delta.y * CAMERA_PITCH_SPEED; let delta_yaw = delta.x * CAMERA_YAW_SPEED; for mut main_camera_transform in &mut main_cameras_query { // Obtain the existing pitch and yaw values from the transform. let (yaw, pitch, _) = main_camera_transform.rotation.to_euler(EulerRot::YXZ); // Establish the new yaw and pitch, preventing the pitch value from exceeding our limits. let pitch = (pitch + delta_pitch).clamp(-CAMERA_PITCH_LIMIT, CAMERA_PITCH_LIMIT); let yaw = yaw + delta_yaw; main_camera_transform.rotation = Quat::from_euler(EulerRot::YXZ, yaw, pitch, 0.0); // Adjust the translation to maintain the correct orientation toward the orbit target. // In our example it's a static target, but this could easily be customized. let target = Vec3::ZERO; main_camera_transform.translation = target - main_camera_transform.forward() * CAMERA_ORBIT_DISTANCE; } } /// Updates the position, rotation, and projection of the mirror camera when the /// main camera is moved. /// /// When the main camera is moved, the mirror camera must be moved to match it. /// The *projection* on the mirror camera must also be altered, because the /// projection takes the view-space rotation of and distance to the mirror into /// account. fn update_mirror_camera_on_main_camera_transform_change( main_cameras_query: Query< (&Transform, &Projection), (Changed<Transform>, With<Camera>, Without<MirrorCamera>), >, mut mirror_cameras_query: Query< (&mut Transform, &mut Projection), (With<Camera>, With<MirrorCamera>, Without<Mirror>), >, mirrors_query: Query<&Transform, (Without<MirrorCamera>, With<Mirror>)>, ) { let Some((main_camera_transform, Projection::Perspective(main_camera_projection))) = main_cameras_query.iter().next() else { return; }; let Some(mirror_transform) = mirrors_query.iter().next() else { return; }; // Here we need the transforms of both the camera and the mirror in order to // properly calculate the new projection. let (new_mirror_camera_transform, new_mirror_camera_projection) = calculate_mirror_camera_transform_and_projection( main_camera_transform, main_camera_projection, mirror_transform, ); for (mut mirror_camera_transform, mut mirror_camera_projection) in &mut mirror_cameras_query { *mirror_camera_transform = new_mirror_camera_transform; *mirror_camera_projection = Projection::Perspective(new_mirror_camera_projection.clone()); } } /// Plays the initial animation on the fox model. fn play_fox_animation( mut commands: Commands, mut animation_players_query: Query< (Entity, &mut AnimationPlayer), Without<AnimationGraphHandle>, >, asset_server: Res<AssetServer>, mut animation_graphs: ResMut<Assets<AnimationGraph>>, ) { // Only pick up animation players that don't already have an animation graph // handle. // This ensures that we only start playing the animation once. if animation_players_query.is_empty() { return; } let fox_animation = asset_server.load(GltfAssetLabel::Animation(0).from_asset(FOX_ASSET_PATH)); let (fox_animation_graph, fox_animation_node) = AnimationGraph::from_clip(fox_animation.clone()); let fox_animation_graph = animation_graphs.add(fox_animation_graph); for (entity, mut animation_player) in animation_players_query.iter_mut() { commands .entity(entity) .insert(AnimationGraphHandle(fox_animation_graph.clone())); animation_player.play(fox_animation_node).repeat(); } } /// Spawns the help text at the top of the screen. 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: px(12), left: px(12), ..default() }, HelpText, )); } /// Creates the help string at the top left of the screen. fn create_help_string(app_status: &AppStatus) -> String { format!( "Click and drag to move the {}", match app_status.drag_action { DragAction::MoveCamera => "camera", DragAction::MoveFox => "fox", } ) } /// Updates the help text in the top left of the screen to reflect the current /// drag mode. fn update_help_text(mut help_text: Query<&mut Text, With<HelpText>>, app_status: Res<AppStatus>) { for mut text in &mut help_text { text.0 = create_help_string(&app_status); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/auto_exposure.rs
examples/3d/auto_exposure.rs
//! This example showcases auto exposure, //! which automatically (but not instantly) adjusts the brightness of the scene in a way that mimics the function of the human eye. //! Auto exposure requires compute shader capabilities, so it's not available on WebGL. //! //! ## Controls //! //! | Key Binding | Action | //! |:-------------------|:---------------------------------------| //! | `Left` / `Right` | Rotate Camera | //! | `C` | Toggle Compensation Curve | //! | `M` | Toggle Metering Mask | //! | `V` | Visualize Metering Mask | use bevy::{ core_pipeline::Skybox, math::{cubic_splines::LinearSpline, primitives::Plane3d, vec2}, post_process::auto_exposure::{ AutoExposure, AutoExposureCompensationCurve, AutoExposurePlugin, }, prelude::*, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugins(AutoExposurePlugin) .add_systems(Startup, setup) .add_systems(Update, example_control_system) .run(); } fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, mut compensation_curves: ResMut<Assets<AutoExposureCompensationCurve>>, asset_server: Res<AssetServer>, ) { let metering_mask = asset_server.load("textures/basic_metering_mask.png"); commands.spawn(( Camera3d::default(), Transform::from_xyz(1.0, 0.0, 0.0).looking_at(Vec3::ZERO, Vec3::Y), AutoExposure { metering_mask: metering_mask.clone(), ..default() }, Skybox { image: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"), brightness: light_consts::lux::DIRECT_SUNLIGHT, ..default() }, )); commands.insert_resource(ExampleResources { basic_compensation_curve: compensation_curves.add( AutoExposureCompensationCurve::from_curve(LinearSpline::new([ vec2(-4.0, -2.0), vec2(0.0, 0.0), vec2(2.0, 0.0), vec2(4.0, 2.0), ])) .unwrap(), ), basic_metering_mask: metering_mask.clone(), }); let plane = meshes.add(Mesh::from( Plane3d { normal: -Dir3::Z, half_size: Vec2::new(2.0, 0.5), } .mesh(), )); // Build a dimly lit box around the camera, with a slot to see the bright skybox. for level in -1..=1 { for side in [-Vec3::X, Vec3::X, -Vec3::Z, Vec3::Z] { if level == 0 && Vec3::Z == side { continue; } let height = Vec3::Y * level as f32; commands.spawn(( Mesh3d(plane.clone()), MeshMaterial3d(materials.add(StandardMaterial { base_color: Color::srgb( 0.5 + side.x * 0.5, 0.75 - level as f32 * 0.25, 0.5 + side.z * 0.5, ), ..default() })), Transform::from_translation(side * 2.0 + height).looking_at(height, Vec3::Y), )); } } commands.insert_resource(GlobalAmbientLight { color: Color::WHITE, brightness: 0.0, ..default() }); commands.spawn(( PointLight { intensity: 2000.0, ..default() }, Transform::from_xyz(0.0, 0.0, 0.0), )); commands.spawn(( ImageNode { image: metering_mask, ..default() }, Node { width: percent(100), height: percent(100), ..default() }, )); let text_font = TextFont::default(); commands.spawn((Text::new("Left / Right - Rotate Camera\nC - Toggle Compensation Curve\nM - Toggle Metering Mask\nV - Visualize Metering Mask"), text_font.clone(), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }) ); commands.spawn(( Text::default(), text_font, Node { position_type: PositionType::Absolute, top: px(12), right: px(12), ..default() }, ExampleDisplay, )); } #[derive(Component)] struct ExampleDisplay; #[derive(Resource)] struct ExampleResources { basic_compensation_curve: Handle<AutoExposureCompensationCurve>, basic_metering_mask: Handle<Image>, } fn example_control_system( camera: Single<(&mut Transform, &mut AutoExposure), With<Camera3d>>, mut display: Single<&mut Text, With<ExampleDisplay>>, mut mask_image: Single<&mut Node, With<ImageNode>>, time: Res<Time>, input: Res<ButtonInput<KeyCode>>, resources: Res<ExampleResources>, ) { let (mut camera_transform, mut auto_exposure) = camera.into_inner(); let rotation = if input.pressed(KeyCode::ArrowLeft) { time.delta_secs() } else if input.pressed(KeyCode::ArrowRight) { -time.delta_secs() } else { 0.0 }; camera_transform.rotate_around(Vec3::ZERO, Quat::from_rotation_y(rotation)); if input.just_pressed(KeyCode::KeyC) { auto_exposure.compensation_curve = if auto_exposure.compensation_curve == resources.basic_compensation_curve { Handle::default() } else { resources.basic_compensation_curve.clone() }; } if input.just_pressed(KeyCode::KeyM) { auto_exposure.metering_mask = if auto_exposure.metering_mask == resources.basic_metering_mask { Handle::default() } else { resources.basic_metering_mask.clone() }; } mask_image.display = if input.pressed(KeyCode::KeyV) { Display::Flex } else { Display::None }; display.0 = format!( "Compensation Curve: {}\nMetering Mask: {}", if auto_exposure.compensation_curve == resources.basic_compensation_curve { "Enabled" } else { "Disabled" }, if auto_exposure.metering_mask == resources.basic_metering_mask { "Enabled" } else { "Disabled" }, ); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/two_passes.rs
examples/3d/two_passes.rs
//! Renders two 3d passes to the same window from different perspectives. use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } /// Set up a simple 3D scene fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // Plane commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(5.0, 5.0))), MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))), )); // Cube commands.spawn(( Mesh3d(meshes.add(Cuboid::default())), MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))), Transform::from_xyz(0.0, 0.5, 0.0), )); // Light commands.spawn(( PointLight { shadows_enabled: true, ..default() }, Transform::from_xyz(4.0, 8.0, 4.0), )); // Camera commands.spawn(( Camera3d::default(), Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y), )); // camera commands.spawn(( Camera3d::default(), Camera { // renders after / on top of the main camera order: 1, clear_color: ClearColorConfig::None, ..default() }, Transform::from_xyz(10.0, 10., -5.0).looking_at(Vec3::ZERO, Vec3::Y), )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/blend_modes.rs
examples/3d/blend_modes.rs
//! This example showcases different blend modes. //! //! ## Controls //! //! | Key Binding | Action | //! |:-------------------|:------------------------------------| //! | `Up` / `Down` | Increase / Decrease Alpha | //! | `Left` / `Right` | Rotate Camera | //! | `H` | Toggle HDR | //! | `Spacebar` | Toggle Unlit | //! | `C` | Randomize Colors | use bevy::{color::palettes::css::ORANGE, prelude::*, render::view::Hdr}; use rand::random; fn main() { let mut app = App::new(); app.add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, example_control_system); app.run(); } /// set up a simple 3D scene fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, asset_server: Res<AssetServer>, ) { let base_color = Color::srgb(0.9, 0.2, 0.3); let icosphere_mesh = meshes.add(Sphere::new(0.9).mesh().ico(7).unwrap()); // Opaque let opaque = commands .spawn(( Mesh3d(icosphere_mesh.clone()), MeshMaterial3d(materials.add(StandardMaterial { base_color, alpha_mode: AlphaMode::Opaque, ..default() })), Transform::from_xyz(-4.0, 0.0, 0.0), ExampleControls { unlit: true, color: true, }, )) .id(); // Blend let blend = commands .spawn(( Mesh3d(icosphere_mesh.clone()), MeshMaterial3d(materials.add(StandardMaterial { base_color, alpha_mode: AlphaMode::Blend, ..default() })), Transform::from_xyz(-2.0, 0.0, 0.0), ExampleControls { unlit: true, color: true, }, )) .id(); // Premultiplied let premultiplied = commands .spawn(( Mesh3d(icosphere_mesh.clone()), MeshMaterial3d(materials.add(StandardMaterial { base_color, alpha_mode: AlphaMode::Premultiplied, ..default() })), Transform::from_xyz(0.0, 0.0, 0.0), ExampleControls { unlit: true, color: true, }, )) .id(); // Add let add = commands .spawn(( Mesh3d(icosphere_mesh.clone()), MeshMaterial3d(materials.add(StandardMaterial { base_color, alpha_mode: AlphaMode::Add, ..default() })), Transform::from_xyz(2.0, 0.0, 0.0), ExampleControls { unlit: true, color: true, }, )) .id(); // Multiply let multiply = commands .spawn(( Mesh3d(icosphere_mesh), MeshMaterial3d(materials.add(StandardMaterial { base_color, alpha_mode: AlphaMode::Multiply, ..default() })), Transform::from_xyz(4.0, 0.0, 0.0), ExampleControls { unlit: true, color: true, }, )) .id(); // Chessboard Plane let black_material = materials.add(Color::BLACK); let white_material = materials.add(Color::WHITE); let plane_mesh = meshes.add(Plane3d::default().mesh().size(2.0, 2.0)); for x in -3..4 { for z in -3..4 { commands.spawn(( Mesh3d(plane_mesh.clone()), MeshMaterial3d(if (x + z) % 2 == 0 { black_material.clone() } else { white_material.clone() }), Transform::from_xyz(x as f32 * 2.0, -1.0, z as f32 * 2.0), ExampleControls { unlit: false, color: true, }, )); } } // Light commands.spawn((PointLight::default(), Transform::from_xyz(4.0, 8.0, 4.0))); // Camera commands.spawn(( Camera3d::default(), Transform::from_xyz(0.0, 2.5, 10.0).looking_at(Vec3::ZERO, Vec3::Y), Hdr, // Unfortunately, MSAA and HDR are not supported simultaneously under WebGL. // Since this example uses HDR, we must disable MSAA for Wasm builds, at least // until WebGPU is ready and no longer behind a feature flag in Web browsers. #[cfg(target_arch = "wasm32")] Msaa::Off, )); // Controls Text // We need the full version of this font so we can use box drawing characters. let text_style = TextFont { font: asset_server.load("fonts/FiraMono-Medium.ttf").into(), ..default() }; let label_text_style = (text_style.clone(), TextColor(ORANGE.into())); commands.spawn((Text::new("Up / Down — Increase / Decrease Alpha\nLeft / Right — Rotate Camera\nH - Toggle HDR\nSpacebar — Toggle Unlit\nC — Randomize Colors"), text_style.clone(), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }) ); commands.spawn(( Text::default(), text_style, Node { position_type: PositionType::Absolute, top: px(12), right: px(12), ..default() }, ExampleDisplay, )); let mut label = |entity: Entity, label: &str| { commands.spawn(( Node { position_type: PositionType::Absolute, ..default() }, ExampleLabel { entity }, children![( Text::new(label), label_text_style.clone(), Node { position_type: PositionType::Absolute, bottom: Val::ZERO, ..default() }, TextLayout::default().with_no_wrap(), )], )); }; label(opaque, "┌─ Opaque\n│\n│\n│\n│"); label(blend, "┌─ Blend\n│\n│\n│"); label(premultiplied, "┌─ Premultiplied\n│\n│"); label(add, "┌─ Add\n│"); label(multiply, "┌─ Multiply"); } #[derive(Component)] struct ExampleControls { unlit: bool, color: bool, } #[derive(Component)] struct ExampleLabel { entity: Entity, } struct ExampleState { alpha: f32, unlit: bool, } #[derive(Component)] struct ExampleDisplay; impl Default for ExampleState { fn default() -> Self { ExampleState { alpha: 0.9, unlit: false, } } } fn example_control_system( mut materials: ResMut<Assets<StandardMaterial>>, controllable: Query<(&MeshMaterial3d<StandardMaterial>, &ExampleControls)>, camera: Single< ( Entity, &mut Camera, &mut Transform, &GlobalTransform, Has<Hdr>, ), With<Camera3d>, >, mut labels: Query<(&mut Node, &ExampleLabel)>, mut display: Single<&mut Text, With<ExampleDisplay>>, labeled: Query<&GlobalTransform>, mut state: Local<ExampleState>, time: Res<Time>, input: Res<ButtonInput<KeyCode>>, mut commands: Commands, ) { if input.pressed(KeyCode::ArrowUp) { state.alpha = (state.alpha + time.delta_secs()).min(1.0); } else if input.pressed(KeyCode::ArrowDown) { state.alpha = (state.alpha - time.delta_secs()).max(0.0); } if input.just_pressed(KeyCode::Space) { state.unlit = !state.unlit; } let randomize_colors = input.just_pressed(KeyCode::KeyC); for (material_handle, controls) in &controllable { let material = materials.get_mut(material_handle).unwrap(); if controls.color && randomize_colors { material.base_color = Srgba { red: random(), green: random(), blue: random(), alpha: state.alpha, } .into(); } else { material.base_color.set_alpha(state.alpha); } if controls.unlit { material.unlit = state.unlit; } } let (entity, camera, mut camera_transform, camera_global_transform, hdr) = camera.into_inner(); if input.just_pressed(KeyCode::KeyH) { if hdr { commands.entity(entity).remove::<Hdr>(); } else { commands.entity(entity).insert(Hdr); } } let rotation = if input.pressed(KeyCode::ArrowLeft) { time.delta_secs() } else if input.pressed(KeyCode::ArrowRight) { -time.delta_secs() } else { 0.0 }; camera_transform.rotate_around(Vec3::ZERO, Quat::from_rotation_y(rotation)); for (mut node, label) in &mut labels { let world_position = labeled.get(label.entity).unwrap().translation() + Vec3::Y; let viewport_position = camera .world_to_viewport(camera_global_transform, world_position) .unwrap(); node.top = px(viewport_position.y); node.left = px(viewport_position.x); } display.0 = format!( " HDR: {}\nAlpha: {:.2}", if hdr { "ON " } else { "OFF" }, state.alpha ); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/post_processing.rs
examples/3d/post_processing.rs
//! Demonstrates Bevy's built-in postprocessing features. //! //! Currently, this simply consists of chromatic aberration. use std::f32::consts::PI; use bevy::{ light::CascadeShadowConfigBuilder, post_process::effect_stack::ChromaticAberration, prelude::*, render::view::Hdr, }; /// The number of units per frame to add to or subtract from intensity when the /// arrow keys are held. const CHROMATIC_ABERRATION_INTENSITY_ADJUSTMENT_SPEED: f32 = 0.002; /// The maximum supported chromatic aberration intensity level. const MAX_CHROMATIC_ABERRATION_INTENSITY: f32 = 0.4; /// The settings that the user can control. #[derive(Resource)] struct AppSettings { /// The intensity of the chromatic aberration effect. chromatic_aberration_intensity: f32, } /// The entry point. fn main() { App::new() .init_resource::<AppSettings>() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "Bevy Chromatic Aberration Example".into(), ..default() }), ..default() })) .add_systems(Startup, setup) .add_systems(Update, handle_keyboard_input) .add_systems( Update, (update_chromatic_aberration_settings, update_help_text) .run_if(resource_changed::<AppSettings>) .after(handle_keyboard_input), ) .run(); } /// Creates the example scene and spawns the UI. fn setup(mut commands: Commands, asset_server: Res<AssetServer>, app_settings: Res<AppSettings>) { // Spawn the camera. spawn_camera(&mut commands, &asset_server); // Create the scene. spawn_scene(&mut commands, &asset_server); // Spawn the help text. spawn_text(&mut commands, &app_settings); } /// Spawns the camera, including the [`ChromaticAberration`] component. fn spawn_camera(commands: &mut Commands, asset_server: &AssetServer) { commands.spawn(( Camera3d::default(), Hdr, Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y), DistanceFog { color: Color::srgb_u8(43, 44, 47), falloff: FogFalloff::Linear { start: 1.0, end: 8.0, }, ..default() }, EnvironmentMapLight { diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"), specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"), intensity: 2000.0, ..default() }, // Include the `ChromaticAberration` component. ChromaticAberration::default(), )); } /// Spawns the scene. /// /// This is just the tonemapping test scene, chosen for the fact that it uses a /// variety of colors. fn spawn_scene(commands: &mut Commands, asset_server: &AssetServer) { // Spawn the main scene. commands.spawn(SceneRoot(asset_server.load( GltfAssetLabel::Scene(0).from_asset("models/TonemappingTest/TonemappingTest.gltf"), ))); // Spawn the flight helmet. commands.spawn(( SceneRoot( asset_server .load(GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf")), ), Transform::from_xyz(0.5, 0.0, -0.5).with_rotation(Quat::from_rotation_y(-0.15 * PI)), )); // Spawn the light. commands.spawn(( DirectionalLight { illuminance: 15000.0, shadows_enabled: true, ..default() }, Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, PI * -0.15, PI * -0.15)), CascadeShadowConfigBuilder { maximum_distance: 3.0, first_cascade_far_bound: 0.9, ..default() } .build(), )); } /// Spawns the help text at the bottom of the screen. fn spawn_text(commands: &mut Commands, app_settings: &AppSettings) { commands.spawn(( create_help_text(app_settings), Node { position_type: PositionType::Absolute, bottom: px(12), left: px(12), ..default() }, )); } impl Default for AppSettings { fn default() -> Self { Self { chromatic_aberration_intensity: ChromaticAberration::default().intensity, } } } /// Creates help text at the bottom of the screen. fn create_help_text(app_settings: &AppSettings) -> Text { format!( "Chromatic aberration intensity: {:.2} (Press Left or Right to change)", app_settings.chromatic_aberration_intensity ) .into() } /// Handles requests from the user to change the chromatic aberration intensity. fn handle_keyboard_input(mut app_settings: ResMut<AppSettings>, input: Res<ButtonInput<KeyCode>>) { let mut delta = 0.0; if input.pressed(KeyCode::ArrowLeft) { delta -= CHROMATIC_ABERRATION_INTENSITY_ADJUSTMENT_SPEED; } else if input.pressed(KeyCode::ArrowRight) { delta += CHROMATIC_ABERRATION_INTENSITY_ADJUSTMENT_SPEED; } // If no arrow key was pressed, just bail out. if delta == 0.0 { return; } app_settings.chromatic_aberration_intensity = (app_settings.chromatic_aberration_intensity + delta) .clamp(0.0, MAX_CHROMATIC_ABERRATION_INTENSITY); } /// Updates the [`ChromaticAberration`] settings per the [`AppSettings`]. fn update_chromatic_aberration_settings( mut chromatic_aberration: Query<&mut ChromaticAberration>, app_settings: Res<AppSettings>, ) { let intensity = app_settings.chromatic_aberration_intensity; // Pick a reasonable maximum sample size for the intensity to avoid an // artifact whereby the individual samples appear instead of producing // smooth streaks of color. // // Don't take this formula too seriously; it hasn't been heavily tuned. let max_samples = ((intensity - 0.02) / (0.20 - 0.02) * 56.0 + 8.0) .clamp(8.0, 64.0) .round() as u32; for mut chromatic_aberration in &mut chromatic_aberration { chromatic_aberration.intensity = intensity; chromatic_aberration.max_samples = max_samples; } } /// Updates the help text at the bottom of the screen to reflect the current /// [`AppSettings`]. fn update_help_text(mut text: Query<&mut Text>, app_settings: Res<AppSettings>) { for mut text in text.iter_mut() { *text = create_help_text(&app_settings); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/shadow_biases.rs
examples/3d/shadow_biases.rs
//! Demonstrates how shadow biases affect shadows in a 3d scene. use bevy::{ camera_controller::free_camera::{FreeCamera, FreeCameraPlugin}, light::ShadowFilteringMethod, prelude::*, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugins(FreeCameraPlugin) .add_systems(Startup, setup) .add_systems( Update, ( cycle_filter_methods, adjust_light_position, adjust_point_light_biases, toggle_light, adjust_directional_light_biases, ), ) .run(); } #[derive(Component)] struct Lights; /// set up a 3D scene to test shadow biases and perspective projections fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { let spawn_plane_depth = 300.0f32; let spawn_height = 2.0; let sphere_radius = 0.25; let white_handle = materials.add(StandardMaterial { base_color: Color::WHITE, perceptual_roughness: 1.0, ..default() }); let sphere_handle = meshes.add(Sphere::new(sphere_radius)); let light_transform = Transform::from_xyz(5.0, 5.0, 0.0).looking_at(Vec3::ZERO, Vec3::Y); commands.spawn(( light_transform, Visibility::default(), Lights, children![ (PointLight { intensity: 0.0, range: spawn_plane_depth, color: Color::WHITE, shadows_enabled: true, ..default() }), (DirectionalLight { shadows_enabled: true, ..default() }) ], )); // camera commands.spawn(( Camera3d::default(), Transform::from_xyz(-1.0, 1.0, 1.0).looking_at(Vec3::new(-1.0, 1.0, 0.0), Vec3::Y), FreeCamera::default(), ShadowFilteringMethod::Hardware2x2, )); for z_i32 in (-spawn_plane_depth as i32..=0).step_by(2) { commands.spawn(( Mesh3d(sphere_handle.clone()), MeshMaterial3d(white_handle.clone()), Transform::from_xyz( 0.0, if z_i32 % 4 == 0 { spawn_height } else { sphere_radius }, z_i32 as f32, ), )); } // ground plane let plane_size = 2.0 * spawn_plane_depth; commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(plane_size, plane_size))), MeshMaterial3d(white_handle), )); commands.spawn(( Node { position_type: PositionType::Absolute, padding: UiRect::all(px(5)), ..default() }, BackgroundColor(Color::BLACK.with_alpha(0.75)), GlobalZIndex(i32::MAX), children![( Text::default(), children![ (TextSpan::new("Controls:\n")), (TextSpan::new("R / Z - reset biases to default / zero\n")), (TextSpan::new("L - switch between directional and point lights [",)), (TextSpan::new("DirectionalLight")), (TextSpan::new("]\n")), (TextSpan::new("F - switch directional light filter methods [",)), (TextSpan::new("Hardware2x2")), (TextSpan::new("]\n")), (TextSpan::new("1/2 - change point light depth bias [")), (TextSpan::new("0.00")), (TextSpan::new("]\n")), (TextSpan::new("3/4 - change point light normal bias [")), (TextSpan::new("0.0")), (TextSpan::new("]\n")), (TextSpan::new("5/6 - change direction light depth bias [")), (TextSpan::new("0.00")), (TextSpan::new("]\n")), (TextSpan::new("7/8 - change direction light normal bias [",)), (TextSpan::new("0.0")), (TextSpan::new("]\n")), (TextSpan::new( "left/right/up/down/pgup/pgdown - adjust light position (looking at 0,0,0) [", )), (TextSpan(format!("{:.1},", light_transform.translation.x))), (TextSpan(format!(" {:.1},", light_transform.translation.y))), (TextSpan(format!(" {:.1}", light_transform.translation.z))), (TextSpan::new("]\n")), ] )], )); } fn toggle_light( input: Res<ButtonInput<KeyCode>>, mut point_lights: Query<&mut PointLight>, mut directional_lights: Query<&mut DirectionalLight>, example_text: Single<Entity, With<Text>>, mut writer: TextUiWriter, ) { if input.just_pressed(KeyCode::KeyL) { for mut light in &mut point_lights { light.intensity = if light.intensity == 0.0 { *writer.text(*example_text, 4) = "PointLight".to_string(); light_consts::lumens::VERY_LARGE_CINEMA_LIGHT } else { 0.0 }; } for mut light in &mut directional_lights { light.illuminance = if light.illuminance == 0.0 { *writer.text(*example_text, 4) = "DirectionalLight".to_string(); light_consts::lux::AMBIENT_DAYLIGHT } else { 0.0 }; } } } fn adjust_light_position( input: Res<ButtonInput<KeyCode>>, mut lights: Query<&mut Transform, With<Lights>>, example_text: Single<Entity, With<Text>>, mut writer: TextUiWriter, ) { let mut offset = Vec3::ZERO; if input.just_pressed(KeyCode::ArrowLeft) { offset.x -= 1.0; } if input.just_pressed(KeyCode::ArrowRight) { offset.x += 1.0; } if input.just_pressed(KeyCode::ArrowUp) { offset.z -= 1.0; } if input.just_pressed(KeyCode::ArrowDown) { offset.z += 1.0; } if input.just_pressed(KeyCode::PageDown) { offset.y -= 1.0; } if input.just_pressed(KeyCode::PageUp) { offset.y += 1.0; } if offset != Vec3::ZERO { let example_text = *example_text; for mut light in &mut lights { light.translation += offset; light.look_at(Vec3::ZERO, Vec3::Y); *writer.text(example_text, 22) = format!("{:.1},", light.translation.x); *writer.text(example_text, 23) = format!(" {:.1},", light.translation.y); *writer.text(example_text, 24) = format!(" {:.1}", light.translation.z); } } } fn cycle_filter_methods( input: Res<ButtonInput<KeyCode>>, mut filter_methods: Query<&mut ShadowFilteringMethod>, example_text: Single<Entity, With<Text>>, mut writer: TextUiWriter, ) { if input.just_pressed(KeyCode::KeyF) { for mut filter_method in &mut filter_methods { let filter_method_string; *filter_method = match *filter_method { ShadowFilteringMethod::Hardware2x2 => { filter_method_string = "Gaussian".to_string(); ShadowFilteringMethod::Gaussian } ShadowFilteringMethod::Gaussian => { filter_method_string = "Temporal".to_string(); ShadowFilteringMethod::Temporal } ShadowFilteringMethod::Temporal => { filter_method_string = "Hardware2x2".to_string(); ShadowFilteringMethod::Hardware2x2 } }; *writer.text(*example_text, 7) = filter_method_string; } } } fn adjust_point_light_biases( input: Res<ButtonInput<KeyCode>>, mut query: Query<&mut PointLight>, example_text: Single<Entity, With<Text>>, mut writer: TextUiWriter, ) { let depth_bias_step_size = 0.01; let normal_bias_step_size = 0.1; for mut light in &mut query { if input.just_pressed(KeyCode::Digit1) { light.shadow_depth_bias -= depth_bias_step_size; } if input.just_pressed(KeyCode::Digit2) { light.shadow_depth_bias += depth_bias_step_size; } if input.just_pressed(KeyCode::Digit3) { light.shadow_normal_bias -= normal_bias_step_size; } if input.just_pressed(KeyCode::Digit4) { light.shadow_normal_bias += normal_bias_step_size; } if input.just_pressed(KeyCode::KeyR) { light.shadow_depth_bias = PointLight::DEFAULT_SHADOW_DEPTH_BIAS; light.shadow_normal_bias = PointLight::DEFAULT_SHADOW_NORMAL_BIAS; } if input.just_pressed(KeyCode::KeyZ) { light.shadow_depth_bias = 0.0; light.shadow_normal_bias = 0.0; } *writer.text(*example_text, 10) = format!("{:.2}", light.shadow_depth_bias); *writer.text(*example_text, 13) = format!("{:.1}", light.shadow_normal_bias); } } fn adjust_directional_light_biases( input: Res<ButtonInput<KeyCode>>, mut query: Query<&mut DirectionalLight>, example_text: Single<Entity, With<Text>>, mut writer: TextUiWriter, ) { let depth_bias_step_size = 0.01; let normal_bias_step_size = 0.1; for mut light in &mut query { if input.just_pressed(KeyCode::Digit5) { light.shadow_depth_bias -= depth_bias_step_size; } if input.just_pressed(KeyCode::Digit6) { light.shadow_depth_bias += depth_bias_step_size; } if input.just_pressed(KeyCode::Digit7) { light.shadow_normal_bias -= normal_bias_step_size; } if input.just_pressed(KeyCode::Digit8) { light.shadow_normal_bias += normal_bias_step_size; } if input.just_pressed(KeyCode::KeyR) { light.shadow_depth_bias = DirectionalLight::DEFAULT_SHADOW_DEPTH_BIAS; light.shadow_normal_bias = DirectionalLight::DEFAULT_SHADOW_NORMAL_BIAS; } if input.just_pressed(KeyCode::KeyZ) { light.shadow_depth_bias = 0.0; light.shadow_normal_bias = 0.0; } *writer.text(*example_text, 16) = format!("{:.2}", light.shadow_depth_bias); *writer.text(*example_text, 19) = format!("{:.1}", light.shadow_normal_bias); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/decal.rs
examples/3d/decal.rs
//! Decal rendering. //! Note: On Wasm, this example only runs on WebGPU use bevy::{ anti_alias::fxaa::Fxaa, camera_controller::free_camera::{FreeCamera, FreeCameraPlugin}, core_pipeline::prepass::DepthPrepass, pbr::decal::{ForwardDecal, ForwardDecalMaterial, ForwardDecalMaterialExt}, prelude::*, }; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; fn main() { App::new() .add_plugins((DefaultPlugins, FreeCameraPlugin)) .add_systems(Startup, setup) .run(); } fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut standard_materials: ResMut<Assets<StandardMaterial>>, mut decal_standard_materials: ResMut<Assets<ForwardDecalMaterial<StandardMaterial>>>, asset_server: Res<AssetServer>, ) { // Spawn the forward decal commands.spawn(( Name::new("Decal"), ForwardDecal, MeshMaterial3d(decal_standard_materials.add(ForwardDecalMaterial { base: StandardMaterial { base_color_texture: Some(asset_server.load("textures/uv_checker_bw.png")), ..default() }, extension: ForwardDecalMaterialExt { depth_fade_factor: 1.0, }, })), Transform::from_scale(Vec3::splat(4.0)), )); commands.spawn(( Name::new("Camera"), Camera3d::default(), FreeCamera::default(), // Must enable the depth prepass to render forward decals DepthPrepass, // Must disable MSAA to use decals on WebGPU Msaa::Off, // FXAA is a fine alternative to MSAA for anti-aliasing Fxaa::default(), Transform::from_xyz(2.0, 9.5, 2.5).looking_at(Vec3::ZERO, Vec3::Y), )); let white_material = standard_materials.add(Color::WHITE); commands.spawn(( Name::new("Floor"), Mesh3d(meshes.add(Rectangle::from_length(10.0))), MeshMaterial3d(white_material.clone()), Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)), )); // Spawn a few cube with random rotations to showcase how the decals behave with non-flat geometry let num_obs = 10; let mut rng = ChaCha8Rng::seed_from_u64(19878367467713); for i in 0..num_obs { for j in 0..num_obs { let rotation_axis: [f32; 3] = rng.random(); let rotation_vec: Vec3 = rotation_axis.into(); let rotation: u32 = rng.random_range(0..360); let transform = Transform::from_xyz( (-num_obs + 1) as f32 / 2.0 + i as f32, -0.2, (-num_obs + 1) as f32 / 2.0 + j as f32, ) .with_rotation(Quat::from_axis_angle( rotation_vec.normalize_or_zero(), (rotation as f32).to_radians(), )); commands.spawn(( Mesh3d(meshes.add(Cuboid::from_length(0.6))), MeshMaterial3d(white_material.clone()), transform, )); } } commands.spawn(( Name::new("Light"), PointLight { shadows_enabled: true, ..default() }, Transform::from_xyz(4.0, 8.0, 4.0), )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/spherical_area_lights.rs
examples/3d/spherical_area_lights.rs
//! Demonstrates how lighting is affected by different radius of point lights. use bevy::prelude::*; fn main() { App::new() .insert_resource(GlobalAmbientLight { brightness: 60.0, ..default() }) .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // camera commands.spawn(( Camera3d::default(), Transform::from_xyz(0.2, 1.5, 2.5).looking_at(Vec3::ZERO, Vec3::Y), )); // plane commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(100.0, 100.0))), MeshMaterial3d(materials.add(StandardMaterial { base_color: Color::srgb(0.2, 0.2, 0.2), perceptual_roughness: 0.08, ..default() })), )); const COUNT: usize = 6; let position_range = -2.0..2.0; let radius_range = 0.0..0.4; let pos_len = position_range.end - position_range.start; let radius_len = radius_range.end - radius_range.start; let mesh = meshes.add(Sphere::new(1.0).mesh().uv(120, 64)); for i in 0..COUNT { let percent = i as f32 / COUNT as f32; let radius = radius_range.start + percent * radius_len; // sphere light commands .spawn(( Mesh3d(mesh.clone()), MeshMaterial3d(materials.add(StandardMaterial { base_color: Color::srgb(0.5, 0.5, 1.0), unlit: true, ..default() })), Transform::from_xyz(position_range.start + percent * pos_len, 0.3, 0.0) .with_scale(Vec3::splat(radius)), )) .with_child(PointLight { radius, color: Color::srgb(0.2, 0.2, 1.0), ..default() }); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/pcss.rs
examples/3d/pcss.rs
//! Demonstrates percentage-closer soft shadows (PCSS). use std::f32::consts::PI; use bevy::{ anti_alias::taa::TemporalAntiAliasing, camera::{ primitives::{CubemapFrusta, Frustum}, visibility::{CubemapVisibleEntities, VisibleMeshEntities}, }, core_pipeline::{ prepass::{DepthPrepass, MotionVectorPrepass}, Skybox, }, light::ShadowFilteringMethod, math::vec3, prelude::*, render::camera::TemporalJitter, }; use crate::widgets::{RadioButton, RadioButtonText, WidgetClickEvent, WidgetClickSender}; #[path = "../helpers/widgets.rs"] mod widgets; /// The size of the light, which affects the size of the penumbras. const LIGHT_RADIUS: f32 = 10.0; /// The intensity of the point and spot lights. const POINT_LIGHT_INTENSITY: f32 = 1_000_000_000.0; /// The range in meters of the point and spot lights. const POINT_LIGHT_RANGE: f32 = 110.0; /// The depth bias for directional and spot lights. This value is set higher /// than the default to avoid shadow acne. const DIRECTIONAL_SHADOW_DEPTH_BIAS: f32 = 0.20; /// The depth bias for point lights. This value is set higher than the default to /// avoid shadow acne. /// /// Unfortunately, there is a bit of Peter Panning with this value, because of /// the distance and angle of the light. This can't be helped in this scene /// without increasing the shadow map size beyond reasonable limits. const POINT_SHADOW_DEPTH_BIAS: f32 = 0.35; /// The near Z value for the shadow map, in meters. This is set higher than the /// default in order to achieve greater resolution in the shadow map for point /// and spot lights. const SHADOW_MAP_NEAR_Z: f32 = 50.0; /// The current application settings (light type, shadow filter, and the status /// of PCSS). #[derive(Resource)] struct AppStatus { /// The type of light presently in the scene: either directional or point. light_type: LightType, /// The type of shadow filter: Gaussian or temporal. shadow_filter: ShadowFilter, /// Whether soft shadows are enabled. soft_shadows: bool, } impl Default for AppStatus { fn default() -> Self { Self { light_type: default(), shadow_filter: default(), soft_shadows: true, } } } /// The type of light presently in the scene: directional, point, or spot. #[derive(Clone, Copy, Default, PartialEq)] enum LightType { /// A directional light, with a cascaded shadow map. #[default] Directional, /// A point light, with a cube shadow map. Point, /// A spot light, with a cube shadow map. Spot, } /// The type of shadow filter. /// /// Generally, `Gaussian` is preferred when temporal antialiasing isn't in use, /// while `Temporal` is preferred when TAA is in use. In this example, this /// setting also turns TAA on and off. #[derive(Clone, Copy, Default, PartialEq)] enum ShadowFilter { /// The non-temporal Gaussian filter (Castano '13 for directional lights, an /// analogous alternative for point and spot lights). #[default] NonTemporal, /// The temporal Gaussian filter (Jimenez '14 for directional lights, an /// analogous alternative for point and spot lights). Temporal, } /// Each example setting that can be toggled in the UI. #[derive(Clone, Copy, PartialEq)] enum AppSetting { /// The type of light presently in the scene: directional, point, or spot. LightType(LightType), /// The type of shadow filter. ShadowFilter(ShadowFilter), /// Whether PCSS is enabled or disabled. SoftShadows(bool), } /// The example application entry point. fn main() { App::new() .init_resource::<AppStatus>() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "Bevy Percentage Closer Soft Shadows Example".into(), ..default() }), ..default() })) .add_message::<WidgetClickEvent<AppSetting>>() .add_systems(Startup, setup) .add_systems(Update, widgets::handle_ui_interactions::<AppSetting>) .add_systems( Update, update_radio_buttons.after(widgets::handle_ui_interactions::<AppSetting>), ) .add_systems( Update, ( handle_light_type_change, handle_shadow_filter_change, handle_pcss_toggle, ) .after(widgets::handle_ui_interactions::<AppSetting>), ) .run(); } /// Creates all the objects in the scene. fn setup(mut commands: Commands, asset_server: Res<AssetServer>, app_status: Res<AppStatus>) { spawn_camera(&mut commands, &asset_server); spawn_light(&mut commands, &app_status); spawn_gltf_scene(&mut commands, &asset_server); spawn_buttons(&mut commands); } /// Spawns the camera, with the initial shadow filtering method. fn spawn_camera(commands: &mut Commands, asset_server: &AssetServer) { commands .spawn(( Camera3d::default(), Transform::from_xyz(-12.912 * 0.7, 4.466 * 0.7, -10.624 * 0.7).with_rotation( Quat::from_euler(EulerRot::YXZ, -134.76 / 180.0 * PI, -0.175, 0.0), ), )) .insert(ShadowFilteringMethod::Gaussian) // `TemporalJitter` is needed for TAA. Note that it does nothing without // `TemporalAntiAliasSettings`. .insert(TemporalJitter::default()) // We want MSAA off for TAA to work properly. .insert(Msaa::Off) // The depth prepass is needed for TAA. .insert(DepthPrepass) // The motion vector prepass is needed for TAA. .insert(MotionVectorPrepass) // Add a nice skybox. .insert(Skybox { image: asset_server.load("environment_maps/sky_skybox.ktx2"), brightness: 500.0, rotation: Quat::IDENTITY, }); } /// Spawns the initial light. fn spawn_light(commands: &mut Commands, app_status: &AppStatus) { // Because this light can become a directional light, point light, or spot // light depending on the settings, we add the union of the components // necessary for this light to behave as all three of those. commands .spawn(( create_directional_light(app_status), Transform::from_rotation(Quat::from_array([ 0.6539259, -0.34646285, 0.36505926, -0.5648683, ])) .with_translation(vec3(57.693, 34.334, -6.422)), )) // These two are needed for point lights. .insert(CubemapVisibleEntities::default()) .insert(CubemapFrusta::default()) // These two are needed for spot lights. .insert(VisibleMeshEntities::default()) .insert(Frustum::default()); } /// Loads and spawns the glTF palm tree scene. fn spawn_gltf_scene(commands: &mut Commands, asset_server: &AssetServer) { commands.spawn(SceneRoot( asset_server.load("models/PalmTree/PalmTree.gltf#Scene0"), )); } /// Spawns all the buttons at the bottom of the screen. fn spawn_buttons(commands: &mut Commands) { commands.spawn(( widgets::main_ui_node(), children![ widgets::option_buttons( "Light Type", &[ (AppSetting::LightType(LightType::Directional), "Directional"), (AppSetting::LightType(LightType::Point), "Point"), (AppSetting::LightType(LightType::Spot), "Spot"), ], ), widgets::option_buttons( "Shadow Filter", &[ (AppSetting::ShadowFilter(ShadowFilter::Temporal), "Temporal"), ( AppSetting::ShadowFilter(ShadowFilter::NonTemporal), "Non-Temporal", ), ], ), widgets::option_buttons( "Soft Shadows", &[ (AppSetting::SoftShadows(true), "On"), (AppSetting::SoftShadows(false), "Off"), ], ), ], )); } /// Updates the style of the radio buttons that enable and disable soft shadows /// to reflect whether PCSS is enabled. fn update_radio_buttons( mut widgets: Query< ( Entity, Option<&mut BackgroundColor>, Has<Text>, &WidgetClickSender<AppSetting>, ), Or<(With<RadioButton>, With<RadioButtonText>)>, >, app_status: Res<AppStatus>, mut writer: TextUiWriter, ) { for (entity, image, has_text, sender) in widgets.iter_mut() { let selected = match **sender { AppSetting::LightType(light_type) => light_type == app_status.light_type, AppSetting::ShadowFilter(shadow_filter) => shadow_filter == app_status.shadow_filter, AppSetting::SoftShadows(soft_shadows) => soft_shadows == app_status.soft_shadows, }; 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); } } } /// Handles requests from the user to change the type of light. fn handle_light_type_change( mut commands: Commands, mut lights: Query<Entity, Or<(With<DirectionalLight>, With<PointLight>, With<SpotLight>)>>, mut events: MessageReader<WidgetClickEvent<AppSetting>>, mut app_status: ResMut<AppStatus>, ) { for event in events.read() { let AppSetting::LightType(light_type) = **event else { continue; }; app_status.light_type = light_type; for light in lights.iter_mut() { let mut light_commands = commands.entity(light); light_commands .remove::<DirectionalLight>() .remove::<PointLight>() .remove::<SpotLight>(); match light_type { LightType::Point => { light_commands.insert(create_point_light(&app_status)); } LightType::Spot => { light_commands.insert(create_spot_light(&app_status)); } LightType::Directional => { light_commands.insert(create_directional_light(&app_status)); } } } } } /// Handles requests from the user to change the shadow filter method. /// /// This system is also responsible for enabling and disabling TAA as /// appropriate. fn handle_shadow_filter_change( mut commands: Commands, mut cameras: Query<(Entity, &mut ShadowFilteringMethod)>, mut events: MessageReader<WidgetClickEvent<AppSetting>>, mut app_status: ResMut<AppStatus>, ) { for event in events.read() { let AppSetting::ShadowFilter(shadow_filter) = **event else { continue; }; app_status.shadow_filter = shadow_filter; for (camera, mut shadow_filtering_method) in cameras.iter_mut() { match shadow_filter { ShadowFilter::NonTemporal => { *shadow_filtering_method = ShadowFilteringMethod::Gaussian; commands.entity(camera).remove::<TemporalAntiAliasing>(); } ShadowFilter::Temporal => { *shadow_filtering_method = ShadowFilteringMethod::Temporal; commands .entity(camera) .insert(TemporalAntiAliasing::default()); } } } } } /// Handles requests from the user to toggle soft shadows on and off. fn handle_pcss_toggle( mut lights: Query<AnyOf<(&mut DirectionalLight, &mut PointLight, &mut SpotLight)>>, mut events: MessageReader<WidgetClickEvent<AppSetting>>, mut app_status: ResMut<AppStatus>, ) { for event in events.read() { let AppSetting::SoftShadows(value) = **event else { continue; }; app_status.soft_shadows = value; // Recreating the lights is the simplest way to toggle soft shadows. for (directional_light, point_light, spot_light) in lights.iter_mut() { if let Some(mut directional_light) = directional_light { *directional_light = create_directional_light(&app_status); } if let Some(mut point_light) = point_light { *point_light = create_point_light(&app_status); } if let Some(mut spot_light) = spot_light { *spot_light = create_spot_light(&app_status); } } } } /// Creates the [`DirectionalLight`] component with the appropriate settings. fn create_directional_light(app_status: &AppStatus) -> DirectionalLight { DirectionalLight { shadows_enabled: true, soft_shadow_size: if app_status.soft_shadows { Some(LIGHT_RADIUS) } else { None }, shadow_depth_bias: DIRECTIONAL_SHADOW_DEPTH_BIAS, ..default() } } /// Creates the [`PointLight`] component with the appropriate settings. fn create_point_light(app_status: &AppStatus) -> PointLight { PointLight { intensity: POINT_LIGHT_INTENSITY, range: POINT_LIGHT_RANGE, shadows_enabled: true, radius: LIGHT_RADIUS, soft_shadows_enabled: app_status.soft_shadows, shadow_depth_bias: POINT_SHADOW_DEPTH_BIAS, shadow_map_near_z: SHADOW_MAP_NEAR_Z, ..default() } } /// Creates the [`SpotLight`] component with the appropriate settings. fn create_spot_light(app_status: &AppStatus) -> SpotLight { SpotLight { intensity: POINT_LIGHT_INTENSITY, range: POINT_LIGHT_RANGE, radius: LIGHT_RADIUS, shadows_enabled: true, soft_shadows_enabled: app_status.soft_shadows, shadow_depth_bias: DIRECTIONAL_SHADOW_DEPTH_BIAS, shadow_map_near_z: SHADOW_MAP_NEAR_Z, ..default() } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/vertex_colors.rs
examples/3d/vertex_colors.rs
//! Illustrates the use of vertex colors. use bevy::{mesh::VertexAttributeValues, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } /// set up a simple 3D scene fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // plane commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(5.0, 5.0))), MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))), )); // cube // Assign vertex colors based on vertex positions let mut colorful_cube = Mesh::from(Cuboid::default()); if let Some(VertexAttributeValues::Float32x3(positions)) = colorful_cube.attribute(Mesh::ATTRIBUTE_POSITION) { let colors: Vec<[f32; 4]> = positions .iter() .map(|[r, g, b]| [(1. - *r) / 2., (1. - *g) / 2., (1. - *b) / 2., 1.]) .collect(); colorful_cube.insert_attribute(Mesh::ATTRIBUTE_COLOR, colors); } commands.spawn(( Mesh3d(meshes.add(colorful_cube)), // This is the default color, but note that vertex colors are // multiplied by the base color, so you'll likely want this to be // white if using vertex colors. MeshMaterial3d(materials.add(Color::srgb(1., 1., 1.))), Transform::from_xyz(0.0, 0.5, 0.0), )); // Light commands.spawn(( PointLight { shadows_enabled: true, ..default() }, Transform::from_xyz(4.0, 5.0, 4.0).looking_at(Vec3::ZERO, Vec3::Y), )); // Camera commands.spawn(( Camera3d::default(), Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y), )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/anti_aliasing.rs
examples/3d/anti_aliasing.rs
//! Compares different anti-aliasing techniques supported by Bevy. use std::{f32::consts::PI, fmt::Write}; use bevy::{ anti_alias::{ contrast_adaptive_sharpening::ContrastAdaptiveSharpening, fxaa::{Fxaa, Sensitivity}, smaa::{Smaa, SmaaPreset}, taa::TemporalAntiAliasing, }, asset::RenderAssetUsages, core_pipeline::prepass::{DepthPrepass, MotionVectorPrepass}, image::{ImageSampler, ImageSamplerDescriptor}, light::CascadeShadowConfigBuilder, prelude::*, render::{ camera::{MipBias, TemporalJitter}, render_resource::{Extent3d, TextureDimension, TextureFormat}, view::Hdr, }, }; #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] use bevy::anti_alias::dlss::{ Dlss, DlssPerfQualityMode, DlssProjectId, DlssSuperResolutionSupported, }; fn main() { let mut app = App::new(); #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] app.insert_resource(DlssProjectId(bevy_asset::uuid::uuid!( "5417916c-0291-4e3f-8f65-326c1858ab96" // Don't copy paste this - generate your own UUID! ))); app.add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems( Update, (modify_aa, modify_sharpening, modify_projection, update_ui), ); app.run(); } type TaaComponents = ( TemporalAntiAliasing, TemporalJitter, MipBias, DepthPrepass, MotionVectorPrepass, ); #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] type DlssComponents = ( Dlss, TemporalJitter, MipBias, DepthPrepass, MotionVectorPrepass, ); #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))] type DlssComponents = (); fn modify_aa( keys: Res<ButtonInput<KeyCode>>, #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] camera: Single< ( Entity, Option<&mut Fxaa>, Option<&mut Smaa>, Option<&TemporalAntiAliasing>, &mut Msaa, Option<&mut Dlss>, ), With<Camera>, >, #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))] camera: Single< ( Entity, Option<&mut Fxaa>, Option<&mut Smaa>, Option<&TemporalAntiAliasing>, &mut Msaa, ), With<Camera>, >, #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] dlss_supported: Option< Res<DlssSuperResolutionSupported>, >, mut commands: Commands, ) { #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] let (camera_entity, fxaa, smaa, taa, mut msaa, dlss) = camera.into_inner(); #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))] let (camera_entity, fxaa, smaa, taa, mut msaa) = camera.into_inner(); let mut camera = commands.entity(camera_entity); // No AA if keys.just_pressed(KeyCode::Digit1) { *msaa = Msaa::Off; camera .remove::<Fxaa>() .remove::<Smaa>() .remove::<TaaComponents>() .remove::<DlssComponents>(); } // MSAA if keys.just_pressed(KeyCode::Digit2) && *msaa == Msaa::Off { camera .remove::<Fxaa>() .remove::<Smaa>() .remove::<TaaComponents>() .remove::<DlssComponents>(); *msaa = Msaa::Sample4; } // MSAA Sample Count if *msaa != Msaa::Off { if keys.just_pressed(KeyCode::KeyQ) { *msaa = Msaa::Sample2; } if keys.just_pressed(KeyCode::KeyW) { *msaa = Msaa::Sample4; } if keys.just_pressed(KeyCode::KeyE) { *msaa = Msaa::Sample8; } } // FXAA if keys.just_pressed(KeyCode::Digit3) && fxaa.is_none() { *msaa = Msaa::Off; camera .remove::<Smaa>() .remove::<TaaComponents>() .remove::<DlssComponents>() .insert(Fxaa::default()); } // FXAA Settings if let Some(mut fxaa) = fxaa { if keys.just_pressed(KeyCode::KeyQ) { fxaa.edge_threshold = Sensitivity::Low; fxaa.edge_threshold_min = Sensitivity::Low; } if keys.just_pressed(KeyCode::KeyW) { fxaa.edge_threshold = Sensitivity::Medium; fxaa.edge_threshold_min = Sensitivity::Medium; } if keys.just_pressed(KeyCode::KeyE) { fxaa.edge_threshold = Sensitivity::High; fxaa.edge_threshold_min = Sensitivity::High; } if keys.just_pressed(KeyCode::KeyR) { fxaa.edge_threshold = Sensitivity::Ultra; fxaa.edge_threshold_min = Sensitivity::Ultra; } if keys.just_pressed(KeyCode::KeyT) { fxaa.edge_threshold = Sensitivity::Extreme; fxaa.edge_threshold_min = Sensitivity::Extreme; } } // SMAA if keys.just_pressed(KeyCode::Digit4) && smaa.is_none() { *msaa = Msaa::Off; camera .remove::<Fxaa>() .remove::<TaaComponents>() .remove::<DlssComponents>() .insert(Smaa::default()); } // SMAA Settings if let Some(mut smaa) = smaa { if keys.just_pressed(KeyCode::KeyQ) { smaa.preset = SmaaPreset::Low; } if keys.just_pressed(KeyCode::KeyW) { smaa.preset = SmaaPreset::Medium; } if keys.just_pressed(KeyCode::KeyE) { smaa.preset = SmaaPreset::High; } if keys.just_pressed(KeyCode::KeyR) { smaa.preset = SmaaPreset::Ultra; } } // TAA if keys.just_pressed(KeyCode::Digit5) && taa.is_none() { *msaa = Msaa::Off; camera .remove::<Fxaa>() .remove::<Smaa>() .remove::<DlssComponents>() .insert(TemporalAntiAliasing::default()); } // DLSS #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] if keys.just_pressed(KeyCode::Digit6) && dlss.is_none() && dlss_supported.is_some() { *msaa = Msaa::Off; camera .remove::<Fxaa>() .remove::<Smaa>() .remove::<TaaComponents>() .insert(Dlss::default()); } // DLSS Settings #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] if let Some(mut dlss) = dlss { if keys.just_pressed(KeyCode::KeyZ) { dlss.perf_quality_mode = DlssPerfQualityMode::Auto; } if keys.just_pressed(KeyCode::KeyX) { dlss.perf_quality_mode = DlssPerfQualityMode::UltraPerformance; } if keys.just_pressed(KeyCode::KeyC) { dlss.perf_quality_mode = DlssPerfQualityMode::Performance; } if keys.just_pressed(KeyCode::KeyV) { dlss.perf_quality_mode = DlssPerfQualityMode::Balanced; } if keys.just_pressed(KeyCode::KeyB) { dlss.perf_quality_mode = DlssPerfQualityMode::Quality; } if keys.just_pressed(KeyCode::KeyN) { dlss.perf_quality_mode = DlssPerfQualityMode::Dlaa; } } } fn modify_sharpening( keys: Res<ButtonInput<KeyCode>>, mut query: Query<&mut ContrastAdaptiveSharpening>, ) { for mut cas in &mut query { if keys.just_pressed(KeyCode::Digit0) { cas.enabled = !cas.enabled; } if cas.enabled { if keys.just_pressed(KeyCode::Minus) { cas.sharpening_strength -= 0.1; cas.sharpening_strength = cas.sharpening_strength.clamp(0.0, 1.0); } if keys.just_pressed(KeyCode::Equal) { cas.sharpening_strength += 0.1; cas.sharpening_strength = cas.sharpening_strength.clamp(0.0, 1.0); } if keys.just_pressed(KeyCode::KeyD) { cas.denoise = !cas.denoise; } } } } fn modify_projection(keys: Res<ButtonInput<KeyCode>>, mut query: Query<&mut Projection>) { for mut projection in &mut query { if keys.just_pressed(KeyCode::KeyO) { match *projection { Projection::Perspective(_) => { *projection = Projection::Orthographic(OrthographicProjection { scale: 0.002, ..OrthographicProjection::default_3d() }); } _ => { *projection = Projection::Perspective(PerspectiveProjection::default()); } } } } } fn update_ui( #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] camera: Single< ( &Projection, Option<&Fxaa>, Option<&Smaa>, Option<&TemporalAntiAliasing>, &ContrastAdaptiveSharpening, &Msaa, Option<&Dlss>, ), With<Camera>, >, #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))] camera: Single< ( &Projection, Option<&Fxaa>, Option<&Smaa>, Option<&TemporalAntiAliasing>, &ContrastAdaptiveSharpening, &Msaa, ), With<Camera>, >, mut ui: Single<&mut Text>, #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] dlss_supported: Option< Res<DlssSuperResolutionSupported>, >, ) { #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] let (projection, fxaa, smaa, taa, cas, msaa, dlss) = *camera; #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))] let (projection, fxaa, smaa, taa, cas, msaa) = *camera; let ui = &mut ui.0; *ui = "Antialias Method\n".to_string(); #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] let dlss_none = dlss.is_none(); #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))] let dlss_none = true; draw_selectable_menu_item( ui, "No AA", '1', *msaa == Msaa::Off && fxaa.is_none() && taa.is_none() && smaa.is_none() && dlss_none, ); draw_selectable_menu_item(ui, "MSAA", '2', *msaa != Msaa::Off); draw_selectable_menu_item(ui, "FXAA", '3', fxaa.is_some()); draw_selectable_menu_item(ui, "SMAA", '4', smaa.is_some()); draw_selectable_menu_item(ui, "TAA", '5', taa.is_some()); #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] if dlss_supported.is_some() { draw_selectable_menu_item(ui, "DLSS", '6', dlss.is_some()); } if *msaa != Msaa::Off { ui.push_str("\n----------\n\nSample Count\n"); draw_selectable_menu_item(ui, "2", 'Q', *msaa == Msaa::Sample2); draw_selectable_menu_item(ui, "4", 'W', *msaa == Msaa::Sample4); draw_selectable_menu_item(ui, "8", 'E', *msaa == Msaa::Sample8); } if let Some(fxaa) = fxaa { ui.push_str("\n----------\n\nSensitivity\n"); draw_selectable_menu_item(ui, "Low", 'Q', fxaa.edge_threshold == Sensitivity::Low); draw_selectable_menu_item( ui, "Medium", 'W', fxaa.edge_threshold == Sensitivity::Medium, ); draw_selectable_menu_item(ui, "High", 'E', fxaa.edge_threshold == Sensitivity::High); draw_selectable_menu_item(ui, "Ultra", 'R', fxaa.edge_threshold == Sensitivity::Ultra); draw_selectable_menu_item( ui, "Extreme", 'T', fxaa.edge_threshold == Sensitivity::Extreme, ); } if let Some(smaa) = smaa { ui.push_str("\n----------\n\nQuality\n"); draw_selectable_menu_item(ui, "Low", 'Q', smaa.preset == SmaaPreset::Low); draw_selectable_menu_item(ui, "Medium", 'W', smaa.preset == SmaaPreset::Medium); draw_selectable_menu_item(ui, "High", 'E', smaa.preset == SmaaPreset::High); draw_selectable_menu_item(ui, "Ultra", 'R', smaa.preset == SmaaPreset::Ultra); } #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] if let Some(dlss) = dlss { let pqm = dlss.perf_quality_mode; ui.push_str("\n----------\n\nQuality\n"); draw_selectable_menu_item(ui, "Auto", 'Z', pqm == DlssPerfQualityMode::Auto); draw_selectable_menu_item( ui, "UltraPerformance", 'X', pqm == DlssPerfQualityMode::UltraPerformance, ); draw_selectable_menu_item( ui, "Performance", 'C', pqm == DlssPerfQualityMode::Performance, ); draw_selectable_menu_item(ui, "Balanced", 'V', pqm == DlssPerfQualityMode::Balanced); draw_selectable_menu_item(ui, "Quality", 'B', pqm == DlssPerfQualityMode::Quality); draw_selectable_menu_item(ui, "DLAA", 'N', pqm == DlssPerfQualityMode::Dlaa); } ui.push_str("\n----------\n\n"); draw_selectable_menu_item(ui, "Sharpening", '0', cas.enabled); if cas.enabled { ui.push_str(&format!("(-/+) Strength: {:.1}\n", cas.sharpening_strength)); draw_selectable_menu_item(ui, "Denoising", 'D', cas.denoise); } ui.push_str("\n----------\n\n"); draw_selectable_menu_item( ui, "Orthographic", 'O', matches!(projection, Projection::Orthographic(_)), ); } /// Set up a simple 3D scene fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, mut images: ResMut<Assets<Image>>, asset_server: Res<AssetServer>, ) { // Plane commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(20.0, 20.0))), MeshMaterial3d(materials.add(Color::srgb(0.1, 0.2, 0.1))), )); let cube_material = materials.add(StandardMaterial { base_color_texture: Some(images.add(uv_debug_texture())), ..default() }); // Cubes for i in 0..5 { commands.spawn(( Mesh3d(meshes.add(Cuboid::new(0.25, 0.25, 0.25))), MeshMaterial3d(cube_material.clone()), Transform::from_xyz(i as f32 * 0.25 - 1.0, 0.125, -i as f32 * 0.5), )); } // Flight Helmet commands.spawn(SceneRoot(asset_server.load( GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf"), ))); // Light commands.spawn(( DirectionalLight { illuminance: light_consts::lux::FULL_DAYLIGHT, shadows_enabled: true, ..default() }, Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, PI * -0.15, PI * -0.15)), CascadeShadowConfigBuilder { maximum_distance: 3.0, first_cascade_far_bound: 0.9, ..default() } .build(), )); // Camera commands.spawn(( Camera3d::default(), Hdr, Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y), ContrastAdaptiveSharpening { enabled: false, ..default() }, EnvironmentMapLight { diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"), specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"), intensity: 150.0, ..default() }, DistanceFog { color: Color::srgba_u8(43, 44, 47, 255), falloff: FogFalloff::Linear { start: 1.0, end: 4.0, }, ..default() }, )); // example instructions commands.spawn(( Text::default(), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, )); } /// Writes a simple menu item that can be on or off. 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}"); } /// Creates a colorful test pattern fn uv_debug_texture() -> Image { const TEXTURE_SIZE: usize = 8; let mut palette: [u8; 32] = [ 255, 102, 159, 255, 255, 159, 102, 255, 236, 255, 102, 255, 121, 255, 102, 255, 102, 255, 198, 255, 102, 198, 255, 255, 121, 102, 255, 255, 236, 102, 255, 255, ]; let mut texture_data = [0; TEXTURE_SIZE * TEXTURE_SIZE * 4]; for y in 0..TEXTURE_SIZE { let offset = TEXTURE_SIZE * y * 4; texture_data[offset..(offset + TEXTURE_SIZE * 4)].copy_from_slice(&palette); palette.rotate_right(4); } let mut img = Image::new_fill( Extent3d { width: TEXTURE_SIZE as u32, height: TEXTURE_SIZE as u32, depth_or_array_layers: 1, }, TextureDimension::D2, &texture_data, TextureFormat::Rgba8UnormSrgb, RenderAssetUsages::RENDER_WORLD, ); img.sampler = ImageSampler::Descriptor(ImageSamplerDescriptor::default()); img }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/spotlight.rs
examples/3d/spotlight.rs
//! Illustrates spot lights. use std::f32::consts::*; use bevy::{ color::palettes::basic::{MAROON, RED}, light::NotShadowCaster, math::ops, prelude::*, render::view::Hdr, }; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; const INSTRUCTIONS: &str = "\ Controls -------- Horizontal Movement: WASD Vertical Movement: Space and Shift Rotate Camera: Left and Right Arrows"; fn main() { App::new() .insert_resource(GlobalAmbientLight { brightness: 20.0, ..default() }) .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, (light_sway, movement, rotation)) .run(); } #[derive(Component)] struct Movable; /// set up a simple 3D scene fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // ground plane commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(100.0, 100.0))), MeshMaterial3d(materials.add(Color::WHITE)), Movable, )); // cubes // We're seeding the PRNG here to make this example deterministic for testing purposes. // This isn't strictly required in practical use unless you need your app to be deterministic. let mut rng = ChaCha8Rng::seed_from_u64(19878367467713); let cube_mesh = meshes.add(Cuboid::new(0.5, 0.5, 0.5)); let blue = materials.add(Color::srgb_u8(124, 144, 255)); commands.spawn_batch( std::iter::repeat_with(move || { let x = rng.random_range(-5.0..5.0); let y = rng.random_range(0.0..3.0); let z = rng.random_range(-5.0..5.0); ( Mesh3d(cube_mesh.clone()), MeshMaterial3d(blue.clone()), Transform::from_xyz(x, y, z), Movable, ) }) .take(40), ); let sphere_mesh = meshes.add(Sphere::new(0.05).mesh().uv(32, 18)); let sphere_mesh_direction = meshes.add(Sphere::new(0.1).mesh().uv(32, 18)); let red_emissive = materials.add(StandardMaterial { base_color: RED.into(), emissive: LinearRgba::new(1.0, 0.0, 0.0, 0.0), ..default() }); let maroon_emissive = materials.add(StandardMaterial { base_color: MAROON.into(), emissive: LinearRgba::new(0.369, 0.0, 0.0, 0.0), ..default() }); for x in 0..4 { for z in 0..4 { let x = x as f32 - 2.0; let z = z as f32 - 2.0; // red spot_light commands.spawn(( SpotLight { intensity: 40_000.0, // lumens color: Color::WHITE, shadows_enabled: true, inner_angle: PI / 4.0 * 0.85, outer_angle: PI / 4.0, ..default() }, Transform::from_xyz(1.0 + x, 2.0, z) .looking_at(Vec3::new(1.0 + x, 0.0, z), Vec3::X), children![ ( Mesh3d(sphere_mesh.clone()), MeshMaterial3d(red_emissive.clone()), ), ( Mesh3d(sphere_mesh_direction.clone()), MeshMaterial3d(maroon_emissive.clone()), Transform::from_translation(Vec3::Z * -0.1), NotShadowCaster, ) ], )); } } // camera commands.spawn(( Camera3d::default(), Hdr, Transform::from_xyz(-4.0, 5.0, 10.0).looking_at(Vec3::ZERO, Vec3::Y), )); commands.spawn(( Text::new(INSTRUCTIONS), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, )); } fn light_sway(time: Res<Time>, mut query: Query<(&mut Transform, &mut SpotLight)>) { for (mut transform, mut angles) in query.iter_mut() { transform.rotation = Quat::from_euler( EulerRot::XYZ, -FRAC_PI_2 + ops::sin(time.elapsed_secs() * 0.67 * 3.0) * 0.5, ops::sin(time.elapsed_secs() * 3.0) * 0.5, 0.0, ); let angle = (ops::sin(time.elapsed_secs() * 1.2) + 1.0) * (FRAC_PI_4 - 0.1); angles.inner_angle = angle * 0.8; angles.outer_angle = angle; } } fn movement( input: Res<ButtonInput<KeyCode>>, time: Res<Time>, mut query: Query<&mut Transform, With<Movable>>, ) { // Calculate translation to move the cubes and ground plane let mut translation = Vec3::ZERO; // Horizontal forward and backward movement if input.pressed(KeyCode::KeyW) { translation.z += 1.0; } else if input.pressed(KeyCode::KeyS) { translation.z -= 1.0; } // Horizontal left and right movement if input.pressed(KeyCode::KeyA) { translation.x += 1.0; } else if input.pressed(KeyCode::KeyD) { translation.x -= 1.0; } // Vertical movement if input.pressed(KeyCode::ShiftLeft) { translation.y += 1.0; } else if input.pressed(KeyCode::Space) { translation.y -= 1.0; } translation *= 2.0 * time.delta_secs(); // Apply translation for mut transform in &mut query { transform.translation += translation; } } fn rotation( mut transform: Single<&mut Transform, With<Camera>>, input: Res<ButtonInput<KeyCode>>, time: Res<Time>, ) { let delta = time.delta_secs(); if input.pressed(KeyCode::ArrowLeft) { transform.rotate_around(Vec3::ZERO, Quat::from_rotation_y(delta)); } else if input.pressed(KeyCode::ArrowRight) { transform.rotate_around(Vec3::ZERO, Quat::from_rotation_y(-delta)); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/fog_volumes.rs
examples/3d/fog_volumes.rs
//! Demonstrates fog volumes with voxel density textures. //! //! We render the Stanford bunny as a fog volume. Parts of the bunny become //! lighter and darker as the camera rotates. This is physically-accurate //! behavior that results from the scattering and absorption of the directional //! light. use bevy::{ light::{FogVolume, VolumetricFog, VolumetricLight}, math::vec3, prelude::*, render::view::Hdr, }; /// Entry point. fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "Bevy Fog Volumes Example".into(), ..default() }), ..default() })) .insert_resource(GlobalAmbientLight::NONE) .add_systems(Startup, setup) .add_systems(Update, rotate_camera) .run(); } /// Spawns all the objects in the scene. 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() }, )); } /// Rotates the camera a bit every frame. 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); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/ssao.rs
examples/3d/ssao.rs
//! A scene showcasing screen space ambient occlusion. use bevy::{ anti_alias::taa::TemporalAntiAliasing, math::ops, pbr::{ScreenSpaceAmbientOcclusion, ScreenSpaceAmbientOcclusionQualityLevel}, prelude::*, render::{camera::TemporalJitter, view::Hdr}, }; use std::f32::consts::PI; fn main() { App::new() .insert_resource(GlobalAmbientLight { brightness: 1000., ..default() }) .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, update) .run(); } fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { commands.spawn(( Camera3d::default(), Transform::from_xyz(-2.0, 2.0, -2.0).looking_at(Vec3::ZERO, Vec3::Y), Hdr, Msaa::Off, ScreenSpaceAmbientOcclusion::default(), TemporalAntiAliasing::default(), )); let material = materials.add(StandardMaterial { base_color: Color::srgb(0.5, 0.5, 0.5), perceptual_roughness: 1.0, reflectance: 0.0, ..default() }); commands.spawn(( Mesh3d(meshes.add(Cuboid::default())), MeshMaterial3d(material.clone()), Transform::from_xyz(0.0, 0.0, 1.0), )); commands.spawn(( Mesh3d(meshes.add(Cuboid::default())), MeshMaterial3d(material.clone()), Transform::from_xyz(0.0, -1.0, 0.0), )); commands.spawn(( Mesh3d(meshes.add(Cuboid::default())), MeshMaterial3d(material), Transform::from_xyz(1.0, 0.0, 0.0), )); commands.spawn(( Mesh3d(meshes.add(Sphere::new(0.4).mesh().uv(72, 36))), MeshMaterial3d(materials.add(StandardMaterial { base_color: Color::srgb(0.4, 0.4, 0.4), perceptual_roughness: 1.0, reflectance: 0.0, ..default() })), SphereMarker, )); commands.spawn(( DirectionalLight { shadows_enabled: true, ..default() }, Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, PI * -0.15, PI * -0.15)), )); commands.spawn(( Text::default(), Node { position_type: PositionType::Absolute, bottom: px(12), left: px(12), ..default() }, )); } fn update( camera: Single< ( Entity, Option<&ScreenSpaceAmbientOcclusion>, Option<&TemporalJitter>, ), With<Camera>, >, mut text: Single<&mut Text>, mut sphere: Single<&mut Transform, With<SphereMarker>>, mut commands: Commands, keycode: Res<ButtonInput<KeyCode>>, time: Res<Time>, ) { sphere.translation.y = ops::sin(time.elapsed_secs() / 1.7) * 0.7; let (camera_entity, ssao, temporal_jitter) = *camera; let current_ssao = ssao.cloned().unwrap_or_default(); let mut commands = commands.entity(camera_entity); commands .insert_if( ScreenSpaceAmbientOcclusion { quality_level: ScreenSpaceAmbientOcclusionQualityLevel::Low, ..current_ssao }, || keycode.just_pressed(KeyCode::Digit2), ) .insert_if( ScreenSpaceAmbientOcclusion { quality_level: ScreenSpaceAmbientOcclusionQualityLevel::Medium, ..current_ssao }, || keycode.just_pressed(KeyCode::Digit3), ) .insert_if( ScreenSpaceAmbientOcclusion { quality_level: ScreenSpaceAmbientOcclusionQualityLevel::High, ..current_ssao }, || keycode.just_pressed(KeyCode::Digit4), ) .insert_if( ScreenSpaceAmbientOcclusion { quality_level: ScreenSpaceAmbientOcclusionQualityLevel::Ultra, ..current_ssao }, || keycode.just_pressed(KeyCode::Digit5), ) .insert_if( ScreenSpaceAmbientOcclusion { constant_object_thickness: (current_ssao.constant_object_thickness * 2.0).min(4.0), ..current_ssao }, || keycode.just_pressed(KeyCode::ArrowUp), ) .insert_if( ScreenSpaceAmbientOcclusion { constant_object_thickness: (current_ssao.constant_object_thickness * 0.5) .max(0.0625), ..current_ssao }, || keycode.just_pressed(KeyCode::ArrowDown), ); if keycode.just_pressed(KeyCode::Digit1) { commands.remove::<ScreenSpaceAmbientOcclusion>(); } if keycode.just_pressed(KeyCode::Space) { if temporal_jitter.is_some() { commands.remove::<TemporalJitter>(); } else { commands.insert(TemporalJitter::default()); } } text.clear(); let (o, l, m, h, u) = match ssao.map(|s| s.quality_level) { None => ("*", "", "", "", ""), Some(ScreenSpaceAmbientOcclusionQualityLevel::Low) => ("", "*", "", "", ""), Some(ScreenSpaceAmbientOcclusionQualityLevel::Medium) => ("", "", "*", "", ""), Some(ScreenSpaceAmbientOcclusionQualityLevel::High) => ("", "", "", "*", ""), Some(ScreenSpaceAmbientOcclusionQualityLevel::Ultra) => ("", "", "", "", "*"), _ => unreachable!(), }; if let Some(thickness) = ssao.map(|s| s.constant_object_thickness) { text.push_str(&format!( "Constant object thickness: {thickness} (Up/Down)\n\n" )); } text.push_str("SSAO Quality:\n"); text.push_str(&format!("(1) {o}Off{o}\n")); text.push_str(&format!("(2) {l}Low{l}\n")); text.push_str(&format!("(3) {m}Medium{m}\n")); text.push_str(&format!("(4) {h}High{h}\n")); text.push_str(&format!("(5) {u}Ultra{u}\n\n")); text.push_str("Temporal Antialiasing:\n"); text.push_str(match temporal_jitter { Some(_) => "(Space) Enabled", None => "(Space) Disabled", }); } #[derive(Component)] struct SphereMarker;
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/parallax_mapping.rs
examples/3d/parallax_mapping.rs
//! A simple 3D scene with a spinning cube with a normal map and depth map to demonstrate parallax mapping. //! Press left mouse button to cycle through different views. use std::fmt; use bevy::{image::ImageLoaderSettings, math::ops, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems( Update, ( spin, move_camera, update_parallax_depth_scale, update_parallax_layers, switch_method, ), ) .run(); } #[derive(Component)] struct Spin { speed: f32, } /// The camera, used to move camera on click. #[derive(Component)] struct FreeCameraController; const DEPTH_CHANGE_RATE: f32 = 0.1; const DEPTH_UPDATE_STEP: f32 = 0.03; const MAX_DEPTH: f32 = 0.3; struct TargetDepth(f32); impl Default for TargetDepth { fn default() -> Self { TargetDepth(0.09) } } struct TargetLayers(f32); impl Default for TargetLayers { fn default() -> Self { TargetLayers(5.0) } } struct CurrentMethod(ParallaxMappingMethod); impl Default for CurrentMethod { fn default() -> Self { CurrentMethod(ParallaxMappingMethod::Relief { max_steps: 4 }) } } impl fmt::Display for CurrentMethod { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.0 { ParallaxMappingMethod::Occlusion => write!(f, "Parallax Occlusion Mapping"), ParallaxMappingMethod::Relief { max_steps } => { write!(f, "Relief Mapping with {max_steps} steps") } } } } impl CurrentMethod { fn next_method(&mut self) { use ParallaxMappingMethod::*; self.0 = match self.0 { Occlusion => Relief { max_steps: 2 }, Relief { max_steps } if max_steps < 3 => Relief { max_steps: 4 }, Relief { max_steps } if max_steps < 5 => Relief { max_steps: 8 }, Relief { .. } => Occlusion, } } } fn update_parallax_depth_scale( input: Res<ButtonInput<KeyCode>>, mut materials: ResMut<Assets<StandardMaterial>>, mut target_depth: Local<TargetDepth>, mut depth_update: Local<bool>, mut writer: TextUiWriter, text: Single<Entity, With<Text>>, ) { if input.just_pressed(KeyCode::Digit1) { target_depth.0 -= DEPTH_UPDATE_STEP; target_depth.0 = target_depth.0.max(0.0); *depth_update = true; } if input.just_pressed(KeyCode::Digit2) { target_depth.0 += DEPTH_UPDATE_STEP; target_depth.0 = target_depth.0.min(MAX_DEPTH); *depth_update = true; } if *depth_update { for (_, mat) in materials.iter_mut() { let current_depth = mat.parallax_depth_scale; let new_depth = current_depth.lerp(target_depth.0, DEPTH_CHANGE_RATE); mat.parallax_depth_scale = new_depth; *writer.text(*text, 1) = format!("Parallax depth scale: {new_depth:.5}\n"); if (new_depth - current_depth).abs() <= 0.000000001 { *depth_update = false; } } } } fn switch_method( input: Res<ButtonInput<KeyCode>>, mut materials: ResMut<Assets<StandardMaterial>>, text: Single<Entity, With<Text>>, mut writer: TextUiWriter, mut current: Local<CurrentMethod>, ) { if input.just_pressed(KeyCode::Space) { current.next_method(); } else { return; } let text_entity = *text; *writer.text(text_entity, 3) = format!("Method: {}\n", *current); for (_, mat) in materials.iter_mut() { mat.parallax_mapping_method = current.0; } } fn update_parallax_layers( input: Res<ButtonInput<KeyCode>>, mut materials: ResMut<Assets<StandardMaterial>>, mut target_layers: Local<TargetLayers>, text: Single<Entity, With<Text>>, mut writer: TextUiWriter, ) { if input.just_pressed(KeyCode::Digit3) { target_layers.0 -= 1.0; target_layers.0 = target_layers.0.max(0.0); } else if input.just_pressed(KeyCode::Digit4) { target_layers.0 += 1.0; } else { return; } let layer_count = ops::exp2(target_layers.0); let text_entity = *text; *writer.text(text_entity, 2) = format!("Layers: {layer_count:.0}\n"); for (_, mat) in materials.iter_mut() { mat.max_parallax_layer_count = layer_count; } } fn spin(time: Res<Time>, mut query: Query<(&mut Transform, &Spin)>) { for (mut transform, spin) in query.iter_mut() { transform.rotate_local_y(spin.speed * time.delta_secs()); transform.rotate_local_x(spin.speed * time.delta_secs()); transform.rotate_local_z(-spin.speed * time.delta_secs()); } } // Camera positions to cycle through when left-clicking. const CAMERA_POSITIONS: &[Transform] = &[ Transform { translation: Vec3::new(1.5, 1.5, 1.5), rotation: Quat::from_xyzw(-0.279, 0.364, 0.115, 0.880), scale: Vec3::ONE, }, Transform { translation: Vec3::new(2.4, 0.0, 0.2), rotation: Quat::from_xyzw(0.094, 0.676, 0.116, 0.721), scale: Vec3::ONE, }, Transform { translation: Vec3::new(2.4, 2.6, -4.3), rotation: Quat::from_xyzw(0.170, 0.908, 0.308, 0.225), scale: Vec3::ONE, }, Transform { translation: Vec3::new(-1.0, 0.8, -1.2), rotation: Quat::from_xyzw(-0.004, 0.909, 0.247, -0.335), scale: Vec3::ONE, }, ]; fn move_camera( mut camera: Single<&mut Transform, With<FreeCameraController>>, mut current_view: Local<usize>, button: Res<ButtonInput<MouseButton>>, ) { if button.just_pressed(MouseButton::Left) { *current_view = (*current_view + 1) % CAMERA_POSITIONS.len(); } let target = CAMERA_POSITIONS[*current_view]; camera.translation = camera.translation.lerp(target.translation, 0.2); camera.rotation = camera.rotation.slerp(target.rotation, 0.2); } fn setup( mut commands: Commands, mut materials: ResMut<Assets<StandardMaterial>>, mut meshes: ResMut<Assets<Mesh>>, asset_server: Res<AssetServer>, ) { // The normal map. Note that to generate it in the GIMP image editor, you should // open the depth map, and do Filters → Generic → Normal Map // You should enable the "flip X" checkbox. let normal_handle = asset_server.load_with_settings( "textures/parallax_example/cube_normal.png", // The normal map texture is in linear color space. Lighting won't look correct // if `is_srgb` is `true`, which is the default. |settings: &mut ImageLoaderSettings| settings.is_srgb = false, ); // Camera commands.spawn(( Camera3d::default(), Transform::from_xyz(1.5, 1.5, 1.5).looking_at(Vec3::ZERO, Vec3::Y), FreeCameraController, )); // represent the light source as a sphere let mesh = meshes.add(Sphere::new(0.05).mesh().ico(3).unwrap()); // light commands.spawn(( PointLight { shadows_enabled: true, ..default() }, Transform::from_xyz(2.0, 1.0, -1.1), children![(Mesh3d(mesh), MeshMaterial3d(materials.add(Color::WHITE)))], )); // Plane commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(10.0, 10.0))), MeshMaterial3d(materials.add(StandardMaterial { // standard material derived from dark green, but // with roughness and reflectance set. perceptual_roughness: 0.45, reflectance: 0.18, ..Color::srgb_u8(0, 80, 0).into() })), Transform::from_xyz(0.0, -1.0, 0.0), )); let parallax_depth_scale = TargetDepth::default().0; let max_parallax_layer_count = ops::exp2(TargetLayers::default().0); let parallax_mapping_method = CurrentMethod::default(); let parallax_material = materials.add(StandardMaterial { perceptual_roughness: 0.4, base_color_texture: Some(asset_server.load("textures/parallax_example/cube_color.png")), normal_map_texture: Some(normal_handle), // The depth map is a grayscale texture where black is the highest level and // white the lowest. depth_map: Some(asset_server.load("textures/parallax_example/cube_depth.png")), parallax_depth_scale, parallax_mapping_method: parallax_mapping_method.0, max_parallax_layer_count, ..default() }); commands.spawn(( Mesh3d( meshes.add( // NOTE: for normal maps and depth maps to work, the mesh // needs tangents generated. Mesh::from(Cuboid::default()) .with_generated_tangents() .unwrap(), ), ), MeshMaterial3d(parallax_material.clone()), Spin { speed: 0.3 }, )); let background_cube = meshes.add( Mesh::from(Cuboid::new(40.0, 40.0, 40.0)) .with_generated_tangents() .unwrap(), ); let background_cube_bundle = |translation| { ( Mesh3d(background_cube.clone()), MeshMaterial3d(parallax_material.clone()), Transform::from_translation(translation), Spin { speed: -0.1 }, ) }; commands.spawn(background_cube_bundle(Vec3::new(45., 0., 0.))); commands.spawn(background_cube_bundle(Vec3::new(-45., 0., 0.))); commands.spawn(background_cube_bundle(Vec3::new(0., 0., 45.))); commands.spawn(background_cube_bundle(Vec3::new(0., 0., -45.))); // example instructions commands.spawn(( Text::default(), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, children![ (TextSpan(format!("Parallax depth scale: {parallax_depth_scale:.5}\n"))), (TextSpan(format!("Layers: {max_parallax_layer_count:.0}\n"))), (TextSpan(format!("{parallax_mapping_method}\n"))), (TextSpan::new("\n\n")), (TextSpan::new("Controls:\n")), (TextSpan::new("Left click - Change view angle\n")), (TextSpan::new("1/2 - Decrease/Increase parallax depth scale\n",)), (TextSpan::new("3/4 - Decrease/Increase layer count\n")), (TextSpan::new("Space - Switch parallaxing algorithm\n")), ], )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/order_independent_transparency.rs
examples/3d/order_independent_transparency.rs
//! A simple 3D scene showing how alpha blending can break and how order independent transparency (OIT) can fix it. //! //! See [`OrderIndependentTransparencyPlugin`] for the trade-offs of using OIT. //! //! [`OrderIndependentTransparencyPlugin`]: bevy::core_pipeline::oit::OrderIndependentTransparencyPlugin use bevy::{ camera::visibility::RenderLayers, color::palettes::css::{BLUE, GREEN, RED}, core_pipeline::oit::OrderIndependentTransparencySettings, prelude::*, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, (toggle_oit, cycle_scenes)) .run(); } /// set up a simple 3D scene fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // camera commands.spawn(( Camera3d::default(), Transform::from_xyz(0.0, 0.0, 10.0).looking_at(Vec3::ZERO, Vec3::Y), // Add this component to this camera to render transparent meshes using OIT OrderIndependentTransparencySettings::default(), RenderLayers::layer(1), // Msaa currently doesn't work with OIT Msaa::Off, )); // light commands.spawn(( PointLight { shadows_enabled: false, ..default() }, Transform::from_xyz(4.0, 8.0, 4.0), RenderLayers::layer(1), )); // spawn help text commands.spawn(( Text::default(), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, RenderLayers::layer(1), children![ TextSpan::new("Press T to toggle OIT\n"), TextSpan::new("OIT Enabled"), TextSpan::new("\nPress C to cycle test scenes"), ], )); // spawn default scene spawn_spheres(&mut commands, &mut meshes, &mut materials); } fn toggle_oit( mut commands: Commands, text: Single<Entity, With<Text>>, keyboard_input: Res<ButtonInput<KeyCode>>, q: Single<(Entity, Has<OrderIndependentTransparencySettings>), With<Camera3d>>, mut text_writer: TextUiWriter, ) { if keyboard_input.just_pressed(KeyCode::KeyT) { let (e, has_oit) = *q; *text_writer.text(*text, 2) = if has_oit { // Removing the component will completely disable OIT for this camera commands .entity(e) .remove::<OrderIndependentTransparencySettings>(); "OIT disabled".to_string() } else { // Adding the component to the camera will render any transparent meshes // with OIT instead of alpha blending commands .entity(e) .insert(OrderIndependentTransparencySettings::default()); "OIT enabled".to_string() }; } } fn cycle_scenes( mut commands: Commands, keyboard_input: Res<ButtonInput<KeyCode>>, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, q: Query<Entity, With<Mesh3d>>, mut scene_id: Local<usize>, ) { if keyboard_input.just_pressed(KeyCode::KeyC) { // despawn current scene for e in &q { commands.entity(e).despawn(); } // increment scene_id *scene_id = (*scene_id + 1) % 2; // spawn next scene match *scene_id { 0 => spawn_spheres(&mut commands, &mut meshes, &mut materials), 1 => spawn_occlusion_test(&mut commands, &mut meshes, &mut materials), _ => unreachable!(), } } } /// Spawns 3 overlapping spheres /// Technically, when using `alpha_to_coverage` with MSAA this particular example wouldn't break, /// but it breaks when disabling MSAA and is enough to show the difference between OIT enabled vs disabled. fn spawn_spheres( commands: &mut Commands, meshes: &mut Assets<Mesh>, materials: &mut Assets<StandardMaterial>, ) { let pos_a = Vec3::new(-1.0, 0.75, 0.0); let pos_b = Vec3::new(0.0, -0.75, 0.0); let pos_c = Vec3::new(1.0, 0.75, 0.0); let offset = Vec3::new(0.0, 0.0, 0.0); let sphere_handle = meshes.add(Sphere::new(2.0).mesh()); let alpha = 0.25; let render_layers = RenderLayers::layer(1); commands.spawn(( Mesh3d(sphere_handle.clone()), MeshMaterial3d(materials.add(StandardMaterial { base_color: RED.with_alpha(alpha).into(), alpha_mode: AlphaMode::Blend, ..default() })), Transform::from_translation(pos_a + offset), render_layers.clone(), )); commands.spawn(( Mesh3d(sphere_handle.clone()), MeshMaterial3d(materials.add(StandardMaterial { base_color: GREEN.with_alpha(alpha).into(), alpha_mode: AlphaMode::Blend, ..default() })), Transform::from_translation(pos_b + offset), render_layers.clone(), )); commands.spawn(( Mesh3d(sphere_handle.clone()), MeshMaterial3d(materials.add(StandardMaterial { base_color: BLUE.with_alpha(alpha).into(), alpha_mode: AlphaMode::Blend, ..default() })), Transform::from_translation(pos_c + offset), render_layers.clone(), )); } /// Spawn a combination of opaque cubes and transparent spheres. /// This is useful to make sure transparent meshes drawn with OIT /// are properly occluded by opaque meshes. fn spawn_occlusion_test( commands: &mut Commands, meshes: &mut Assets<Mesh>, materials: &mut Assets<StandardMaterial>, ) { let sphere_handle = meshes.add(Sphere::new(1.0).mesh()); let cube_handle = meshes.add(Cuboid::from_size(Vec3::ONE).mesh()); let cube_material = materials.add(Color::srgb(0.8, 0.7, 0.6)); let render_layers = RenderLayers::layer(1); // front let x = -2.5; commands.spawn(( Mesh3d(cube_handle.clone()), MeshMaterial3d(cube_material.clone()), Transform::from_xyz(x, 0.0, 2.0), render_layers.clone(), )); commands.spawn(( Mesh3d(sphere_handle.clone()), MeshMaterial3d(materials.add(StandardMaterial { base_color: RED.with_alpha(0.5).into(), alpha_mode: AlphaMode::Blend, ..default() })), Transform::from_xyz(x, 0., 0.), render_layers.clone(), )); // intersection commands.spawn(( Mesh3d(cube_handle.clone()), MeshMaterial3d(cube_material.clone()), Transform::from_xyz(x, 0.0, 1.0), render_layers.clone(), )); commands.spawn(( Mesh3d(sphere_handle.clone()), MeshMaterial3d(materials.add(StandardMaterial { base_color: RED.with_alpha(0.5).into(), alpha_mode: AlphaMode::Blend, ..default() })), Transform::from_xyz(0., 0., 0.), render_layers.clone(), )); // back let x = 2.5; commands.spawn(( Mesh3d(cube_handle.clone()), MeshMaterial3d(cube_material.clone()), Transform::from_xyz(x, 0.0, -2.0), render_layers.clone(), )); commands.spawn(( Mesh3d(sphere_handle.clone()), MeshMaterial3d(materials.add(StandardMaterial { base_color: RED.with_alpha(0.5).into(), alpha_mode: AlphaMode::Blend, ..default() })), Transform::from_xyz(x, 0., 0.), render_layers.clone(), )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/camera_sub_view.rs
examples/3d/camera_sub_view.rs
//! Demonstrates different sub view effects. //! //! A sub view is essentially a smaller section of a larger viewport. Some use //! cases include: //! - Split one image across multiple cameras, for use in a multimonitor setups //! - Magnify a section of the image, by rendering a small sub view in another //! camera //! - Rapidly change the sub view offset to get a screen shake effect use bevy::{ camera::{ScalingMode, SubCameraView, Viewport}, prelude::*, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, (move_camera_view, resize_viewports)) .run(); } #[derive(Debug, Component)] struct MovingCameraMarker; /// Set up a simple 3D scene fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { let transform = Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y); // Plane commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(5.0, 5.0))), MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))), )); // Cube commands.spawn(( Mesh3d(meshes.add(Cuboid::default())), MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))), Transform::from_xyz(0.0, 0.5, 0.0), )); // Light commands.spawn(( PointLight { shadows_enabled: true, ..default() }, Transform::from_xyz(4.0, 8.0, 4.0), )); // Main perspective camera: // // The main perspective image to use as a comparison for the sub views. commands.spawn(( Camera3d::default(), Camera::default(), ExampleViewports::PerspectiveMain, transform, )); // Perspective camera right half: // // For this camera, the projection is perspective, and `size` is half the // width of the `full_size`, while the x value of `offset` is set to half // the value of the full width, causing the right half of the image to be // shown. Since the viewport has an aspect ratio of 1x1 and the sub view has // an aspect ratio of 1x2, the image appears stretched along the horizontal // axis. commands.spawn(( Camera3d::default(), Camera { sub_camera_view: Some(SubCameraView { // The values of `full_size` and `size` do not have to be the // exact values of your physical viewport. The important part is // the ratio between them. full_size: UVec2::new(10, 10), // The `offset` is also relative to the values in `full_size` // and `size` offset: Vec2::new(5.0, 0.0), size: UVec2::new(5, 10), }), order: 1, ..default() }, ExampleViewports::PerspectiveStretched, transform, )); // Perspective camera moving: // // For this camera, the projection is perspective, and the offset is updated // continuously in 150 units per second in `move_camera_view`. Since the // `full_size` is 500x500, the image should appear to be moving across the // full image once every 3.3 seconds. `size` is a fifth of the size of // `full_size`, so the image will appear zoomed in. commands.spawn(( Camera3d::default(), Camera { sub_camera_view: Some(SubCameraView { full_size: UVec2::new(500, 500), offset: Vec2::ZERO, size: UVec2::new(100, 100), }), order: 2, ..default() }, transform, ExampleViewports::PerspectiveMoving, MovingCameraMarker, )); // Perspective camera different aspect ratio: // // For this camera, the projection is perspective, and the aspect ratio of // the sub view (2x1) is different to the aspect ratio of the full view // (2x2). The aspect ratio of the sub view matches the aspect ratio of // the viewport and should show an unstretched image of the top half of the // full perspective image. commands.spawn(( Camera3d::default(), Camera { sub_camera_view: Some(SubCameraView { full_size: UVec2::new(800, 800), offset: Vec2::ZERO, size: UVec2::new(800, 400), }), order: 3, ..default() }, ExampleViewports::PerspectiveControl, transform, )); // Main orthographic camera: // // The main orthographic image to use as a comparison for the sub views. commands.spawn(( Camera3d::default(), Projection::from(OrthographicProjection { scaling_mode: ScalingMode::FixedVertical { viewport_height: 6.0, }, ..OrthographicProjection::default_3d() }), Camera { order: 4, ..default() }, ExampleViewports::OrthographicMain, transform, )); // Orthographic camera left half: // // For this camera, the projection is orthographic, and `size` is half the // width of the `full_size`, causing the left half of the image to be shown. // Since the viewport has an aspect ratio of 1x1 and the sub view has an // aspect ratio of 1x2, the image appears stretched along the horizontal axis. commands.spawn(( Camera3d::default(), Projection::from(OrthographicProjection { scaling_mode: ScalingMode::FixedVertical { viewport_height: 6.0, }, ..OrthographicProjection::default_3d() }), Camera { sub_camera_view: Some(SubCameraView { full_size: UVec2::new(2, 2), offset: Vec2::ZERO, size: UVec2::new(1, 2), }), order: 5, ..default() }, ExampleViewports::OrthographicStretched, transform, )); // Orthographic camera moving: // // For this camera, the projection is orthographic, and the offset is // updated continuously in 150 units per second in `move_camera_view`. Since // the `full_size` is 500x500, the image should appear to be moving across // the full image once every 3.3 seconds. `size` is a fifth of the size of // `full_size`, so the image will appear zoomed in. commands.spawn(( Camera3d::default(), Projection::from(OrthographicProjection { scaling_mode: ScalingMode::FixedVertical { viewport_height: 6.0, }, ..OrthographicProjection::default_3d() }), Camera { sub_camera_view: Some(SubCameraView { full_size: UVec2::new(500, 500), offset: Vec2::ZERO, size: UVec2::new(100, 100), }), order: 6, ..default() }, transform, ExampleViewports::OrthographicMoving, MovingCameraMarker, )); // Orthographic camera different aspect ratio: // // For this camera, the projection is orthographic, and the aspect ratio of // the sub view (2x1) is different to the aspect ratio of the full view // (2x2). The aspect ratio of the sub view matches the aspect ratio of // the viewport and should show an unstretched image of the top half of the // full orthographic image. commands.spawn(( Camera3d::default(), Projection::from(OrthographicProjection { scaling_mode: ScalingMode::FixedVertical { viewport_height: 6.0, }, ..OrthographicProjection::default_3d() }), Camera { sub_camera_view: Some(SubCameraView { full_size: UVec2::new(200, 200), offset: Vec2::ZERO, size: UVec2::new(200, 100), }), order: 7, ..default() }, ExampleViewports::OrthographicControl, transform, )); } fn move_camera_view( mut movable_camera_query: Query<&mut Camera, With<MovingCameraMarker>>, time: Res<Time>, ) { for mut camera in movable_camera_query.iter_mut() { if let Some(sub_view) = &mut camera.sub_camera_view { sub_view.offset.x = (time.elapsed_secs() * 150.) % 450.0 - 50.0; sub_view.offset.y = sub_view.offset.x; } } } // To ensure viewports remain the same at any window size fn resize_viewports( window: Single<&Window, With<bevy::window::PrimaryWindow>>, mut viewports: Query<(&mut Camera, &ExampleViewports)>, ) { let window_size = window.physical_size(); let small_height = window_size.y / 5; let small_width = window_size.x / 8; let large_height = small_height * 4; let large_width = small_width * 4; let large_size = UVec2::new(large_width, large_height); // Enforce the aspect ratio of the small viewports to ensure the images // appear unstretched let small_dim = small_height.min(small_width); let small_size = UVec2::new(small_dim, small_dim); let small_wide_size = UVec2::new(small_dim * 2, small_dim); for (mut camera, example_viewport) in viewports.iter_mut() { if camera.viewport.is_none() { camera.viewport = Some(Viewport::default()); }; let Some(viewport) = &mut camera.viewport else { continue; }; let (size, position) = match example_viewport { ExampleViewports::PerspectiveMain => (large_size, UVec2::new(0, small_height)), ExampleViewports::PerspectiveStretched => (small_size, UVec2::ZERO), ExampleViewports::PerspectiveMoving => (small_size, UVec2::new(small_width, 0)), ExampleViewports::PerspectiveControl => { (small_wide_size, UVec2::new(small_width * 2, 0)) } ExampleViewports::OrthographicMain => { (large_size, UVec2::new(large_width, small_height)) } ExampleViewports::OrthographicStretched => (small_size, UVec2::new(small_width * 4, 0)), ExampleViewports::OrthographicMoving => (small_size, UVec2::new(small_width * 5, 0)), ExampleViewports::OrthographicControl => { (small_wide_size, UVec2::new(small_width * 6, 0)) } }; viewport.physical_size = size; viewport.physical_position = position; } } #[derive(Component)] enum ExampleViewports { PerspectiveMain, PerspectiveStretched, PerspectiveMoving, PerspectiveControl, OrthographicMain, OrthographicStretched, OrthographicMoving, OrthographicControl, }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/bloom_3d.rs
examples/3d/bloom_3d.rs
//! Illustrates bloom post-processing using HDR and emissive materials. use bevy::{ core_pipeline::tonemapping::Tonemapping, math::ops, post_process::bloom::{Bloom, BloomCompositeMode}, prelude::*, }; use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup_scene) .add_systems(Update, (update_bloom_settings, bounce_spheres)) .run(); } fn setup_scene( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { commands.spawn(( Camera3d::default(), Camera { clear_color: ClearColorConfig::Custom(Color::BLACK), ..default() }, Tonemapping::TonyMcMapface, // 1. Using a tonemapper that desaturates to white is recommended Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y), Bloom::NATURAL, // 2. Enable bloom for the camera )); let material_emissive1 = materials.add(StandardMaterial { emissive: LinearRgba::rgb(0.0, 0.0, 150.0), // 3. Put something bright in a dark environment to see the effect ..default() }); let material_emissive2 = materials.add(StandardMaterial { emissive: LinearRgba::rgb(1000.0, 1000.0, 1000.0), ..default() }); let material_emissive3 = materials.add(StandardMaterial { emissive: LinearRgba::rgb(50.0, 0.0, 0.0), ..default() }); let material_non_emissive = materials.add(StandardMaterial { base_color: Color::BLACK, ..default() }); let mesh = meshes.add(Sphere::new(0.4).mesh().ico(5).unwrap()); for x in -5..5 { for z in -5..5 { // This generates a pseudo-random integer between `[0, 6)`, but deterministically so // the same spheres are always the same colors. let mut hasher = DefaultHasher::new(); (x, z).hash(&mut hasher); let rand = (hasher.finish() + 3) % 6; let (material, scale) = match rand { 0 => (material_emissive1.clone(), 0.5), 1 => (material_emissive2.clone(), 0.1), 2 => (material_emissive3.clone(), 1.0), 3..=5 => (material_non_emissive.clone(), 1.5), _ => unreachable!(), }; commands.spawn(( Mesh3d(mesh.clone()), MeshMaterial3d(material), Transform::from_xyz(x as f32 * 2.0, 0.0, z as f32 * 2.0) .with_scale(Vec3::splat(scale)), Bouncing, )); } } // example instructions commands.spawn(( Text::default(), Node { position_type: PositionType::Absolute, bottom: px(12), left: px(12), ..default() }, )); } // ------------------------------------------------------------------------------------------------ fn update_bloom_settings( camera: Single<(Entity, Option<&mut Bloom>), With<Camera>>, mut text: Single<&mut Text>, mut commands: Commands, keycode: Res<ButtonInput<KeyCode>>, time: Res<Time>, ) { let bloom = camera.into_inner(); match bloom { (entity, Some(mut bloom)) => { text.0 = "Bloom (Toggle: Space)\n".to_string(); text.push_str(&format!("(Q/A) Intensity: {:.2}\n", bloom.intensity)); text.push_str(&format!( "(W/S) Low-frequency boost: {:.2}\n", bloom.low_frequency_boost )); text.push_str(&format!( "(E/D) Low-frequency boost curvature: {:.2}\n", bloom.low_frequency_boost_curvature )); text.push_str(&format!( "(R/F) High-pass frequency: {:.2}\n", bloom.high_pass_frequency )); text.push_str(&format!( "(T/G) Mode: {}\n", match bloom.composite_mode { BloomCompositeMode::EnergyConserving => "Energy-conserving", BloomCompositeMode::Additive => "Additive", } )); text.push_str(&format!( "(Y/H) Threshold: {:.2}\n", bloom.prefilter.threshold )); text.push_str(&format!( "(U/J) Threshold softness: {:.2}\n", bloom.prefilter.threshold_softness )); text.push_str(&format!("(I/K) Horizontal Scale: {:.2}\n", bloom.scale.x)); if keycode.just_pressed(KeyCode::Space) { commands.entity(entity).remove::<Bloom>(); } let dt = time.delta_secs(); if keycode.pressed(KeyCode::KeyA) { bloom.intensity -= dt / 10.0; } if keycode.pressed(KeyCode::KeyQ) { bloom.intensity += dt / 10.0; } bloom.intensity = bloom.intensity.clamp(0.0, 1.0); if keycode.pressed(KeyCode::KeyS) { bloom.low_frequency_boost -= dt / 10.0; } if keycode.pressed(KeyCode::KeyW) { bloom.low_frequency_boost += dt / 10.0; } bloom.low_frequency_boost = bloom.low_frequency_boost.clamp(0.0, 1.0); if keycode.pressed(KeyCode::KeyD) { bloom.low_frequency_boost_curvature -= dt / 10.0; } if keycode.pressed(KeyCode::KeyE) { bloom.low_frequency_boost_curvature += dt / 10.0; } bloom.low_frequency_boost_curvature = bloom.low_frequency_boost_curvature.clamp(0.0, 1.0); if keycode.pressed(KeyCode::KeyF) { bloom.high_pass_frequency -= dt / 10.0; } if keycode.pressed(KeyCode::KeyR) { bloom.high_pass_frequency += dt / 10.0; } bloom.high_pass_frequency = bloom.high_pass_frequency.clamp(0.0, 1.0); if keycode.pressed(KeyCode::KeyG) { bloom.composite_mode = BloomCompositeMode::Additive; } if keycode.pressed(KeyCode::KeyT) { bloom.composite_mode = BloomCompositeMode::EnergyConserving; } if keycode.pressed(KeyCode::KeyH) { bloom.prefilter.threshold -= dt; } if keycode.pressed(KeyCode::KeyY) { bloom.prefilter.threshold += dt; } bloom.prefilter.threshold = bloom.prefilter.threshold.max(0.0); if keycode.pressed(KeyCode::KeyJ) { bloom.prefilter.threshold_softness -= dt / 10.0; } if keycode.pressed(KeyCode::KeyU) { bloom.prefilter.threshold_softness += dt / 10.0; } bloom.prefilter.threshold_softness = bloom.prefilter.threshold_softness.clamp(0.0, 1.0); if keycode.pressed(KeyCode::KeyK) { bloom.scale.x -= dt * 2.0; } if keycode.pressed(KeyCode::KeyI) { bloom.scale.x += dt * 2.0; } bloom.scale.x = bloom.scale.x.clamp(0.0, 8.0); } (entity, None) => { text.0 = "Bloom: Off (Toggle: Space)".to_string(); if keycode.just_pressed(KeyCode::Space) { commands.entity(entity).insert(Bloom::NATURAL); } } } } #[derive(Component)] struct Bouncing; fn bounce_spheres(time: Res<Time>, mut query: Query<&mut Transform, With<Bouncing>>) { for mut transform in query.iter_mut() { transform.translation.y = ops::sin(transform.translation.x + transform.translation.z + time.elapsed_secs()); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/lighting.rs
examples/3d/lighting.rs
//! Illustrates different lights of various types and colors, some static, some moving over //! a simple scene. use std::f32::consts::PI; use bevy::{ camera::{Exposure, PhysicalCameraParameters}, color::palettes::css::*, light::CascadeShadowConfigBuilder, prelude::*, }; fn main() { App::new() .add_plugins(DefaultPlugins) .insert_resource(Parameters(PhysicalCameraParameters { aperture_f_stops: 1.0, shutter_speed_s: 1.0 / 125.0, sensitivity_iso: 100.0, sensor_height: 0.01866, })) .add_systems(Startup, setup) .add_systems( Update, ( update_exposure, toggle_ambient_light, movement, animate_light_direction, ), ) .run(); } #[derive(Resource, Default, Deref, DerefMut)] struct Parameters(PhysicalCameraParameters); #[derive(Component)] struct Movable; /// set up a simple 3D scene fn setup( parameters: Res<Parameters>, mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, asset_server: Res<AssetServer>, ) { // ground plane commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(10.0, 10.0))), MeshMaterial3d(materials.add(StandardMaterial { base_color: Color::WHITE, perceptual_roughness: 1.0, ..default() })), )); // left wall let mut transform = Transform::from_xyz(2.5, 2.5, 0.0); transform.rotate_z(PI / 2.); commands.spawn(( Mesh3d(meshes.add(Cuboid::new(5.0, 0.15, 5.0))), MeshMaterial3d(materials.add(StandardMaterial { base_color: INDIGO.into(), perceptual_roughness: 1.0, ..default() })), transform, )); // back (right) wall let mut transform = Transform::from_xyz(0.0, 2.5, -2.5); transform.rotate_x(PI / 2.); commands.spawn(( Mesh3d(meshes.add(Cuboid::new(5.0, 0.15, 5.0))), MeshMaterial3d(materials.add(StandardMaterial { base_color: INDIGO.into(), perceptual_roughness: 1.0, ..default() })), transform, )); // Bevy logo to demonstrate alpha mask shadows let mut transform = Transform::from_xyz(-2.2, 0.5, 1.0); transform.rotate_y(PI / 8.); commands.spawn(( Mesh3d(meshes.add(Rectangle::new(2.0, 0.5))), MeshMaterial3d(materials.add(StandardMaterial { base_color_texture: Some(asset_server.load("branding/bevy_logo_light.png")), perceptual_roughness: 1.0, alpha_mode: AlphaMode::Mask(0.5), cull_mode: None, ..default() })), transform, Movable, )); // cube commands.spawn(( Mesh3d(meshes.add(Cuboid::default())), MeshMaterial3d(materials.add(StandardMaterial { base_color: DEEP_PINK.into(), ..default() })), Transform::from_xyz(0.0, 0.5, 0.0), Movable, )); // sphere commands.spawn(( Mesh3d(meshes.add(Sphere::new(0.5).mesh().uv(32, 18))), MeshMaterial3d(materials.add(StandardMaterial { base_color: LIMEGREEN.into(), ..default() })), Transform::from_xyz(1.5, 1.0, 1.5), Movable, )); // ambient light // ambient lights' brightnesses are measured in candela per meter square, calculable as (color * brightness) commands.insert_resource(GlobalAmbientLight { color: ORANGE_RED.into(), brightness: 200.0, ..default() }); // red point light commands.spawn(( PointLight { intensity: 100_000.0, color: RED.into(), shadows_enabled: true, ..default() }, Transform::from_xyz(1.0, 2.0, 0.0), children![( Mesh3d(meshes.add(Sphere::new(0.1).mesh().uv(32, 18))), MeshMaterial3d(materials.add(StandardMaterial { base_color: RED.into(), emissive: LinearRgba::new(4.0, 0.0, 0.0, 0.0), ..default() })), )], )); // green spot light commands.spawn(( SpotLight { intensity: 100_000.0, color: LIME.into(), shadows_enabled: true, inner_angle: 0.6, outer_angle: 0.8, ..default() }, Transform::from_xyz(-1.0, 2.0, 0.0).looking_at(Vec3::new(-1.0, 0.0, 0.0), Vec3::Z), children![( Mesh3d(meshes.add(Capsule3d::new(0.1, 0.125))), MeshMaterial3d(materials.add(StandardMaterial { base_color: LIME.into(), emissive: LinearRgba::new(0.0, 4.0, 0.0, 0.0), ..default() })), Transform::from_rotation(Quat::from_rotation_x(PI / 2.0)), )], )); // blue point light commands.spawn(( PointLight { intensity: 100_000.0, color: BLUE.into(), shadows_enabled: true, ..default() }, Transform::from_xyz(0.0, 4.0, 0.0), children![( Mesh3d(meshes.add(Sphere::new(0.1).mesh().uv(32, 18))), MeshMaterial3d(materials.add(StandardMaterial { base_color: BLUE.into(), emissive: LinearRgba::new(0.0, 0.0, 713.0, 0.0), ..default() })), )], )); // directional 'sun' light commands.spawn(( DirectionalLight { illuminance: light_consts::lux::OVERCAST_DAY, shadows_enabled: true, ..default() }, Transform { translation: Vec3::new(0.0, 2.0, 0.0), rotation: Quat::from_rotation_x(-PI / 4.), ..default() }, // The default cascade config is designed to handle large scenes. // As this example has a much smaller world, we can tighten the shadow // bounds for better visual quality. CascadeShadowConfigBuilder { first_cascade_far_bound: 4.0, maximum_distance: 10.0, ..default() } .build(), )); // example instructions commands.spawn(( Text::default(), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, children![ TextSpan::new("Ambient light is on\n"), TextSpan(format!("Aperture: f/{:.0}\n", parameters.aperture_f_stops,)), TextSpan(format!( "Shutter speed: 1/{:.0}s\n", 1.0 / parameters.shutter_speed_s )), TextSpan(format!( "Sensitivity: ISO {:.0}\n", parameters.sensitivity_iso )), TextSpan::new("\n\n"), TextSpan::new("Controls\n"), TextSpan::new("---------------\n"), TextSpan::new("Arrow keys - Move objects\n"), TextSpan::new("Space - Toggle ambient light\n"), TextSpan::new("1/2 - Decrease/Increase aperture\n"), TextSpan::new("3/4 - Decrease/Increase shutter speed\n"), TextSpan::new("5/6 - Decrease/Increase sensitivity\n"), TextSpan::new("R - Reset exposure"), ], )); // camera commands.spawn(( Camera3d::default(), Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y), Exposure::from_physical_camera(**parameters), )); } fn update_exposure( key_input: Res<ButtonInput<KeyCode>>, mut parameters: ResMut<Parameters>, mut exposure: Single<&mut Exposure>, text: Single<Entity, With<Text>>, mut writer: TextUiWriter, ) { // TODO: Clamp values to a reasonable range let entity = *text; if key_input.just_pressed(KeyCode::Digit2) { parameters.aperture_f_stops *= 2.0; } else if key_input.just_pressed(KeyCode::Digit1) { parameters.aperture_f_stops *= 0.5; } if key_input.just_pressed(KeyCode::Digit4) { parameters.shutter_speed_s *= 2.0; } else if key_input.just_pressed(KeyCode::Digit3) { parameters.shutter_speed_s *= 0.5; } if key_input.just_pressed(KeyCode::Digit6) { parameters.sensitivity_iso += 100.0; } else if key_input.just_pressed(KeyCode::Digit5) { parameters.sensitivity_iso -= 100.0; } if key_input.just_pressed(KeyCode::KeyR) { *parameters = Parameters::default(); } *writer.text(entity, 2) = format!("Aperture: f/{:.0}\n", parameters.aperture_f_stops); *writer.text(entity, 3) = format!( "Shutter speed: 1/{:.0}s\n", 1.0 / parameters.shutter_speed_s ); *writer.text(entity, 4) = format!("Sensitivity: ISO {:.0}\n", parameters.sensitivity_iso); **exposure = Exposure::from_physical_camera(**parameters); } fn toggle_ambient_light( key_input: Res<ButtonInput<KeyCode>>, mut ambient_light: ResMut<GlobalAmbientLight>, text: Single<Entity, With<Text>>, mut writer: TextUiWriter, ) { if key_input.just_pressed(KeyCode::Space) { if ambient_light.brightness > 1. { ambient_light.brightness = 0.; } else { ambient_light.brightness = 200.; } let entity = *text; let ambient_light_state_text: &str = match ambient_light.brightness { 0. => "off", _ => "on", }; *writer.text(entity, 1) = format!("Ambient light is {ambient_light_state_text}\n"); } } fn animate_light_direction( time: Res<Time>, mut query: Query<&mut Transform, With<DirectionalLight>>, ) { for mut transform in &mut query { transform.rotate_y(time.delta_secs() * 0.5); } } fn movement( input: Res<ButtonInput<KeyCode>>, time: Res<Time>, mut query: Query<&mut Transform, With<Movable>>, ) { for mut transform in &mut query { let mut direction = Vec3::ZERO; if input.pressed(KeyCode::ArrowUp) { direction.y += 1.0; } if input.pressed(KeyCode::ArrowDown) { direction.y -= 1.0; } if input.pressed(KeyCode::ArrowLeft) { direction.x -= 1.0; } if input.pressed(KeyCode::ArrowRight) { direction.x += 1.0; } transform.translation += time.delta_secs() * 2.0 * direction; } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/clearcoat.rs
examples/3d/clearcoat.rs
//! Demonstrates the clearcoat PBR feature. //! //! Clearcoat is a separate material layer that represents a thin translucent //! layer over a material. Examples include (from the Filament spec [1]) car paint, //! soda cans, and lacquered wood. //! //! In glTF, clearcoat is supported via the `KHR_materials_clearcoat` [2] //! extension. This extension is well supported by tools; in particular, //! Blender's glTF exporter maps the clearcoat feature of its Principled BSDF //! node to this extension, allowing it to appear in Bevy. //! //! This Bevy example is inspired by the corresponding three.js example [3]. //! //! [1]: https://google.github.io/filament/Filament.html#materialsystem/clearcoatmodel //! //! [2]: https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_clearcoat/README.md //! //! [3]: https://threejs.org/examples/webgl_materials_physical_clearcoat.html use std::f32::consts::PI; use bevy::{ color::palettes::css::{BLUE, GOLD, WHITE}, core_pipeline::{tonemapping::Tonemapping::AcesFitted, Skybox}, image::ImageLoaderSettings, math::vec3, prelude::*, render::view::Hdr, }; /// The size of each sphere. const SPHERE_SCALE: f32 = 0.9; /// The speed at which the spheres rotate, in radians per second. const SPHERE_ROTATION_SPEED: f32 = 0.8; /// Which type of light we're using: a point light or a directional light. #[derive(Clone, Copy, PartialEq, Resource, Default)] enum LightMode { #[default] Point, Directional, } /// Tags the example spheres. #[derive(Component)] struct ExampleSphere; /// Entry point. pub fn main() { App::new() .init_resource::<LightMode>() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, animate_light) .add_systems(Update, animate_spheres) .add_systems(Update, (handle_input, update_help_text).chain()) .run(); } /// Initializes the scene. fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, asset_server: Res<AssetServer>, light_mode: Res<LightMode>, ) { let sphere = create_sphere_mesh(&mut meshes); spawn_car_paint_sphere(&mut commands, &mut materials, &asset_server, &sphere); spawn_coated_glass_bubble_sphere(&mut commands, &mut materials, &sphere); spawn_golf_ball(&mut commands, &asset_server); spawn_scratched_gold_ball(&mut commands, &mut materials, &asset_server, &sphere); spawn_light(&mut commands); spawn_camera(&mut commands, &asset_server); spawn_text(&mut commands, &light_mode); } /// Generates a sphere. fn create_sphere_mesh(meshes: &mut Assets<Mesh>) -> Handle<Mesh> { // We're going to use normal maps, so make sure we've generated tangents, or // else the normal maps won't show up. let mut sphere_mesh = Sphere::new(1.0).mesh().build(); sphere_mesh .generate_tangents() .expect("Failed to generate tangents"); meshes.add(sphere_mesh) } /// Spawn a regular object with a clearcoat layer. This looks like car paint. 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 semitransparent object with a clearcoat layer. fn spawn_coated_glass_bubble_sphere( commands: &mut Commands, materials: &mut Assets<StandardMaterial>, sphere: &Handle<Mesh>, ) { commands .spawn(( Mesh3d(sphere.clone()), MeshMaterial3d(materials.add(StandardMaterial { clearcoat: 1.0, clearcoat_perceptual_roughness: 0.1, metallic: 0.5, perceptual_roughness: 0.1, base_color: Color::srgba(0.9, 0.9, 0.9, 0.3), alpha_mode: AlphaMode::Blend, ..default() })), Transform::from_xyz(-1.0, -1.0, 0.0).with_scale(Vec3::splat(SPHERE_SCALE)), )) .insert(ExampleSphere); } /// 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. 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 only a clearcoat normal map (a scratch pattern) and no /// main layer normal map. 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 a light. fn spawn_light(commands: &mut Commands) { commands.spawn(create_point_light()); } /// Spawns a camera with associated skybox and environment map. 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 the help text. fn spawn_text(commands: &mut Commands, light_mode: &LightMode) { commands.spawn(( light_mode.create_help_text(), Node { position_type: PositionType::Absolute, bottom: px(12), left: px(12), ..default() }, )); } /// Moves the light around. fn animate_light( mut lights: Query<&mut Transform, Or<(With<PointLight>, With<DirectionalLight>)>>, time: Res<Time>, ) { let now = time.elapsed_secs(); for mut transform in lights.iter_mut() { transform.translation = vec3( ops::sin(now * 1.4), ops::cos(now * 1.0), ops::cos(now * 0.6), ) * vec3(3.0, 4.0, 3.0); transform.look_at(Vec3::ZERO, Vec3::Y); } } /// Rotates the spheres. fn animate_spheres(mut spheres: Query<&mut Transform, With<ExampleSphere>>, time: Res<Time>) { let now = time.elapsed_secs(); for mut transform in spheres.iter_mut() { transform.rotation = Quat::from_rotation_y(SPHERE_ROTATION_SPEED * now); } } /// Handles the user pressing Space to change the type of light from point to /// directional and vice versa. 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()); } } } } /// Updates the help text at the bottom of the screen. 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(); } } /// Creates or recreates the moving point light. fn create_point_light() -> PointLight { PointLight { color: WHITE.into(), intensity: 100000.0, ..default() } } /// Creates or recreates the moving directional light. fn create_directional_light() -> DirectionalLight { DirectionalLight { color: WHITE.into(), illuminance: 1000.0, ..default() } } impl LightMode { /// Creates the help text at the bottom of the screen. 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) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/clustered_decal_maps.rs
examples/3d/clustered_decal_maps.rs
//! Demonstrates the normal map, metallic-roughness map, and emissive features //! of clustered decals. use std::{f32::consts::PI, time::Duration}; use bevy::{ asset::io::web::WebAssetPlugin, color::palettes::css::{CRIMSON, GOLD}, image::ImageLoaderSettings, light::ClusteredDecal, prelude::*, render::view::Hdr, }; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; use crate::widgets::{RadioButton, RadioButtonText, WidgetClickEvent, WidgetClickSender}; #[path = "../helpers/widgets.rs"] mod widgets; /// The demonstration textures that we use. /// /// We cache these for efficiency. #[derive(Resource)] struct AppTextures { /// The base color that all our decals have (the Bevy logo). decal_base_color_texture: Handle<Image>, /// A normal map that all our decals have. /// /// This provides a nice raised embossed look. decal_normal_map_texture: Handle<Image>, /// The metallic-roughness map that all our decals have. /// /// Metallic is in the blue channel and roughness is in the green channel, /// like glTF requires. decal_metallic_roughness_map_texture: Handle<Image>, /// The emissive texture that can optionally be enabled. /// /// This causes the white bird to glow. decal_emissive_texture: Handle<Image>, } impl FromWorld for AppTextures { fn from_world(world: &mut World) -> Self { // Load all the decal textures. let asset_server = world.resource::<AssetServer>(); AppTextures { decal_base_color_texture: asset_server.load("branding/bevy_bird_dark.png"), decal_normal_map_texture: asset_server.load_with_settings( get_web_asset_url("BevyLogo-Normal.png"), |settings: &mut ImageLoaderSettings| settings.is_srgb = false, ), decal_metallic_roughness_map_texture: asset_server.load_with_settings( get_web_asset_url("BevyLogo-MetallicRoughness.png"), |settings: &mut ImageLoaderSettings| settings.is_srgb = false, ), decal_emissive_texture: asset_server.load(get_web_asset_url("BevyLogo-Emissive.png")), } } } /// A component that we place on our decals to track them for animation /// purposes. #[derive(Component)] struct ExampleDecal { /// The width and height of the square decal in meters. size: f32, /// What state the decal is in (animating in, idling, or animating out). state: ExampleDecalState, } /// The animation state of a decal. /// /// When each [`Timer`] goes off, the decal advances to the next state. enum ExampleDecalState { /// The decal has just been spawned and is animating in. AnimatingIn(Timer), /// The decal has animated in and is waiting to animate out. Idling(Timer), /// The decal is animating out. /// /// When this timer expires, the decal is despawned. AnimatingOut(Timer), } /// All settings that the user can change. /// /// This app only has one: whether newly-spawned decals are emissive. #[derive(Clone, Copy, PartialEq)] enum AppSetting { /// True if newly-spawned decals have an emissive channel (i.e. they glow), /// or false otherwise. EmissiveDecals(bool), } /// The current values of the settings that the user can change. /// /// This app only has one: whether newly-spawned decals are emissive. #[derive(Default, Resource)] struct AppStatus { /// True if newly-spawned decals have an emissive channel (i.e. they glow), /// or false otherwise. emissive_decals: bool, } /// Half of the width and height of the plane onto which the decals are /// projected. const PLANE_HALF_SIZE: f32 = 2.0; /// The minimum width and height that a decal may have. /// /// The actual size is determined randomly, using this value as a lower bound. const DECAL_MIN_SIZE: f32 = 0.5; /// The maximum width and height that a decal may have. /// /// The actual size is determined randomly, using this value as an upper bound. const DECAL_MAX_SIZE: f32 = 1.5; /// How long it takes the decal to grow to its full size when animating in. const DECAL_ANIMATE_IN_DURATION: Duration = Duration::from_millis(300); /// How long a decal stays in the idle state before starting to animate out. const DECAL_IDLE_DURATION: Duration = Duration::from_secs(10); /// How long it takes the decal to shrink down to nothing when animating out. const DECAL_ANIMATE_OUT_DURATION: Duration = Duration::from_millis(300); /// The demo entry point. fn main() { App::new() .add_plugins( DefaultPlugins .set(WebAssetPlugin { silence_startup_warning: true, }) .set(WindowPlugin { primary_window: Some(Window { title: "Bevy Clustered Decal Maps Example".into(), ..default() }), ..default() }), ) .add_message::<WidgetClickEvent<AppSetting>>() .init_resource::<AppStatus>() .init_resource::<AppTextures>() .add_systems(Startup, setup) .add_systems(Update, draw_gizmos) .add_systems(Update, spawn_decal) .add_systems(Update, animate_decals) .add_systems( Update, ( widgets::handle_ui_interactions::<AppSetting>, update_radio_buttons, ), ) .add_systems( Update, handle_emission_type_change.after(widgets::handle_ui_interactions::<AppSetting>), ) .insert_resource(SeededRng(ChaCha8Rng::seed_from_u64(19878367467712))) .run(); } #[derive(Resource)] struct SeededRng(ChaCha8Rng); /// Spawns all the objects in the scene. fn setup( mut commands: Commands, asset_server: Res<AssetServer>, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { spawn_plane_mesh(&mut commands, &asset_server, &mut meshes, &mut materials); spawn_light(&mut commands); spawn_camera(&mut commands); spawn_buttons(&mut commands); } /// Spawns the plane onto which the decals are projected. fn spawn_plane_mesh( commands: &mut Commands, asset_server: &AssetServer, meshes: &mut Assets<Mesh>, materials: &mut Assets<StandardMaterial>, ) { // Create a plane onto which we project decals. // // As the plane has a normal map, we must generate tangents for the // vertices. let plane_mesh = meshes.add( Plane3d { normal: Dir3::NEG_Z, half_size: Vec2::splat(PLANE_HALF_SIZE), } .mesh() .build() .with_duplicated_vertices() .with_computed_flat_normals() .with_generated_tangents() .unwrap(), ); // Give the plane some texture. // // Note that, as this is a normal map, we must disable sRGB when loading. let normal_map_texture = asset_server.load_with_settings( "textures/ScratchedGold-Normal.png", |settings: &mut ImageLoaderSettings| settings.is_srgb = false, ); // Actually spawn the plane. commands.spawn(( Mesh3d(plane_mesh), MeshMaterial3d(materials.add(StandardMaterial { base_color: Color::from(CRIMSON), normal_map_texture: Some(normal_map_texture), ..StandardMaterial::default() })), Transform::IDENTITY, )); } /// Spawns a light to illuminate the scene. fn spawn_light(commands: &mut Commands) { commands.spawn(( PointLight { intensity: 10_000_000., range: 100.0, ..default() }, Transform::from_xyz(8.0, 16.0, -8.0), )); } /// Spawns a camera. fn spawn_camera(commands: &mut Commands) { commands.spawn(( Camera3d::default(), Transform::from_xyz(2.0, 0.0, -7.0).looking_at(Vec3::ZERO, Vec3::Y), Hdr, )); } /// Spawns all the buttons at the bottom of the screen. fn spawn_buttons(commands: &mut Commands) { commands.spawn(( widgets::main_ui_node(), children![widgets::option_buttons( "Emissive Decals", &[ (AppSetting::EmissiveDecals(true), "On"), (AppSetting::EmissiveDecals(false), "Off"), ], ),], )); } /// Draws the outlines that show the bounds of the clustered decals. fn draw_gizmos(mut gizmos: Gizmos, decals: Query<&GlobalTransform, With<ClusteredDecal>>) { for global_transform in &decals { gizmos.primitive_3d( &Cuboid { // Since the clustered decal is a 1×1×1 cube in model space, its // half-size is half of the scaling part of its transform. half_size: global_transform.scale() * 0.5, }, Isometry3d { rotation: global_transform.rotation(), translation: global_transform.translation_vec3a(), }, GOLD, ); } } /// A system that spawns new decals at fixed intervals. fn spawn_decal( mut commands: Commands, app_status: Res<AppStatus>, app_textures: Res<AppTextures>, time: Res<Time>, mut decal_spawn_timer: Local<Option<Timer>>, mut seeded_rng: ResMut<SeededRng>, ) { // Tick the decal spawn timer. Check to see if we should spawn a new decal, // and bail out if it's not yet time to. let decal_spawn_timer = decal_spawn_timer .get_or_insert_with(|| Timer::new(Duration::from_millis(1000), TimerMode::Repeating)); decal_spawn_timer.tick(time.delta()); if !decal_spawn_timer.just_finished() { return; } // Generate a random position along the plane. let decal_position = vec3( seeded_rng.0.random_range(-PLANE_HALF_SIZE..PLANE_HALF_SIZE), seeded_rng.0.random_range(-PLANE_HALF_SIZE..PLANE_HALF_SIZE), 0.0, ); // Generate a random size for the decal. let decal_size = seeded_rng.0.random_range(DECAL_MIN_SIZE..DECAL_MAX_SIZE); // Generate a random rotation for the decal. let theta = seeded_rng.0.random_range(0.0f32..PI); // Now spawn the decal. commands.spawn(( // Apply the textures. ClusteredDecal { base_color_texture: Some(app_textures.decal_base_color_texture.clone()), normal_map_texture: Some(app_textures.decal_normal_map_texture.clone()), metallic_roughness_texture: Some( app_textures.decal_metallic_roughness_map_texture.clone(), ), emissive_texture: if app_status.emissive_decals { Some(app_textures.decal_emissive_texture.clone()) } else { None }, ..ClusteredDecal::default() }, // Spawn the decal at the right place. Note that the scale is initially // zero; we'll animate it later. Transform::from_translation(decal_position) .with_scale(Vec3::ZERO) .looking_to(Vec3::Z, Vec3::ZERO.with_xy(Vec2::from_angle(theta))), // Create the component that tracks the animation state. ExampleDecal { size: decal_size, state: ExampleDecalState::AnimatingIn(Timer::new( DECAL_ANIMATE_IN_DURATION, TimerMode::Once, )), }, )); } /// A system that animates the decals growing as they enter and shrinking as /// they leave. fn animate_decals( mut commands: Commands, mut decals_query: Query<(Entity, &mut ExampleDecal, &mut Transform)>, time: Res<Time>, ) { for (decal_entity, mut example_decal, mut decal_transform) in decals_query.iter_mut() { // Update the animation timers, and advance the animation state if the // timer has expired. match example_decal.state { ExampleDecalState::AnimatingIn(ref mut timer) => { timer.tick(time.delta()); if timer.just_finished() { example_decal.state = ExampleDecalState::Idling(Timer::new(DECAL_IDLE_DURATION, TimerMode::Once)); } } ExampleDecalState::Idling(ref mut timer) => { timer.tick(time.delta()); if timer.just_finished() { example_decal.state = ExampleDecalState::AnimatingOut(Timer::new( DECAL_ANIMATE_OUT_DURATION, TimerMode::Once, )); } } ExampleDecalState::AnimatingOut(ref mut timer) => { timer.tick(time.delta()); if timer.just_finished() { commands.entity(decal_entity).despawn(); continue; } } } // Actually animate the decal by adjusting its transform. // All we have to do here is to compute the decal's scale as a fraction // of its full size. let new_decal_scale_factor = match example_decal.state { ExampleDecalState::AnimatingIn(ref timer) => timer.fraction(), ExampleDecalState::Idling(_) => 1.0, ExampleDecalState::AnimatingOut(ref timer) => timer.fraction_remaining(), }; decal_transform.scale = Vec3::splat(example_decal.size * new_decal_scale_factor).with_z(1.0); } } /// Updates the appearance of the radio buttons to reflect the current /// application status. fn update_radio_buttons( mut widgets: Query< ( Entity, Option<&mut BackgroundColor>, Has<Text>, &WidgetClickSender<AppSetting>, ), Or<(With<RadioButton>, With<RadioButtonText>)>, >, app_status: Res<AppStatus>, mut writer: TextUiWriter, ) { for (entity, image, has_text, sender) in widgets.iter_mut() { // We only have one setting in this particular application. let selected = match **sender { AppSetting::EmissiveDecals(emissive_decals) => { emissive_decals == app_status.emissive_decals } }; if let Some(mut bg_color) = image { // Update the colors of the button itself. widgets::update_ui_radio_button(&mut bg_color, selected); } if has_text { // Update the colors of the button text. widgets::update_ui_radio_button_text(entity, &mut writer, selected); } } } /// Handles the user's clicks on the radio button that determines whether the /// newly-spawned decals have an emissive map. fn handle_emission_type_change( mut app_status: ResMut<AppStatus>, mut events: MessageReader<WidgetClickEvent<AppSetting>>, ) { for event in events.read() { let AppSetting::EmissiveDecals(on) = **event; app_status.emissive_decals = on; } } /// Returns the GitHub download URL for the given asset. /// /// The files are expected to be in the `clustered_decal_maps` directory in the /// [repository]. /// /// [repository]: https://github.com/bevyengine/bevy_asset_files fn get_web_asset_url(name: &str) -> String { format!( "https://raw.githubusercontent.com/bevyengine/bevy_asset_files/refs/heads/main/\ clustered_decal_maps/{}", name ) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/lightmaps.rs
examples/3d/lightmaps.rs
//! Rendering a scene with baked lightmaps. use argh::FromArgs; use bevy::{ core_pipeline::prepass::{DeferredPrepass, DepthPrepass, MotionVectorPrepass}, gltf::GltfMeshName, pbr::{DefaultOpaqueRendererMethod, Lightmap}, prelude::*, }; /// Demonstrates lightmaps #[derive(FromArgs, Resource)] struct Args { /// enables deferred shading #[argh(switch)] deferred: bool, /// enables bicubic filtering #[argh(switch)] bicubic: bool, } fn main() { #[cfg(not(target_arch = "wasm32"))] let args: Args = argh::from_env(); #[cfg(target_arch = "wasm32")] let args: Args = Args::from_args(&[], &[]).unwrap(); let mut app = App::new(); app.add_plugins(DefaultPlugins) .insert_resource(GlobalAmbientLight::NONE); if args.deferred { app.insert_resource(DefaultOpaqueRendererMethod::deferred()); } app.insert_resource(args) .add_systems(Startup, setup) .add_systems(Update, add_lightmaps_to_meshes) .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>, args: Res<Args>) { commands.spawn(SceneRoot(asset_server.load( GltfAssetLabel::Scene(0).from_asset("models/CornellBox/CornellBox.glb"), ))); let mut camera = commands.spawn(( Camera3d::default(), Transform::from_xyz(-278.0, 273.0, 800.0), )); if args.deferred { camera.insert(( DepthPrepass, MotionVectorPrepass, DeferredPrepass, Msaa::Off, )); } } fn add_lightmaps_to_meshes( mut commands: Commands, asset_server: Res<AssetServer>, mut materials: ResMut<Assets<StandardMaterial>>, meshes: Query< (Entity, &GltfMeshName, &MeshMaterial3d<StandardMaterial>), (With<Mesh3d>, Without<Lightmap>), >, args: Res<Args>, ) { let exposure = 250.0; for (entity, name, material) in meshes.iter() { if &**name == "large_box" { materials.get_mut(material).unwrap().lightmap_exposure = exposure; commands.entity(entity).insert(Lightmap { image: asset_server.load("lightmaps/CornellBox-Large.zstd.ktx2"), bicubic_sampling: args.bicubic, ..default() }); continue; } if &**name == "small_box" { materials.get_mut(material).unwrap().lightmap_exposure = exposure; commands.entity(entity).insert(Lightmap { image: asset_server.load("lightmaps/CornellBox-Small.zstd.ktx2"), bicubic_sampling: args.bicubic, ..default() }); continue; } if name.starts_with("cornell_box") { materials.get_mut(material).unwrap().lightmap_exposure = exposure; commands.entity(entity).insert(Lightmap { image: asset_server.load("lightmaps/CornellBox-Box.zstd.ktx2"), bicubic_sampling: args.bicubic, ..default() }); continue; } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/parenting.rs
examples/3d/parenting.rs
//! Illustrates how to create parent-child relationships between entities and how parent transforms //! are propagated to their descendants. use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, rotator_system) .run(); } /// this component indicates what entities should rotate #[derive(Component)] struct Rotator; /// rotates the parent, which will result in the child also rotating fn rotator_system(time: Res<Time>, mut query: Query<&mut Transform, With<Rotator>>) { for mut transform in &mut query { transform.rotate_x(3.0 * time.delta_secs()); } } /// set up a simple scene with a "parent" cube and a "child" cube fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { let cube_handle = meshes.add(Cuboid::new(2.0, 2.0, 2.0)); let cube_material_handle = materials.add(StandardMaterial { base_color: Color::srgb(0.8, 0.7, 0.6), ..default() }); // parent cube commands.spawn(( Mesh3d(cube_handle.clone()), MeshMaterial3d(cube_material_handle.clone()), Transform::from_xyz(0.0, 0.0, 1.0), Rotator, children![( // child cube Mesh3d(cube_handle), MeshMaterial3d(cube_material_handle), Transform::from_xyz(0.0, 0.0, 3.0), )], )); // light commands.spawn((PointLight::default(), Transform::from_xyz(4.0, 5.0, -4.0))); // camera commands.spawn(( Camera3d::default(), Transform::from_xyz(5.0, 10.0, 10.0).looking_at(Vec3::ZERO, Vec3::Y), )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/render_to_texture.rs
examples/3d/render_to_texture.rs
//! Shows how to render to a texture. Useful for mirrors, UI, or exporting images. use std::f32::consts::PI; use bevy::camera::RenderTarget; use bevy::{camera::visibility::RenderLayers, prelude::*, render::render_resource::TextureFormat}; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, (cube_rotator_system, rotator_system)) .run(); } // Marks the first pass cube (rendered to a texture.) #[derive(Component)] struct FirstPassCube; // Marks the main pass cube, to which the texture is applied. #[derive(Component)] struct MainPassCube; fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, mut images: ResMut<Assets<Image>>, ) { // This is the texture that will be rendered to. let image = Image::new_target_texture( 512, 512, TextureFormat::Rgba8Unorm, Some(TextureFormat::Rgba8UnormSrgb), ); let image_handle = images.add(image); let cube_handle = meshes.add(Cuboid::new(4.0, 4.0, 4.0)); let cube_material_handle = materials.add(StandardMaterial { base_color: Color::srgb(0.8, 0.7, 0.6), reflectance: 0.02, unlit: false, ..default() }); // This specifies the layer used for the first pass, which will be attached to the first pass camera and cube. let first_pass_layer = RenderLayers::layer(1); // The cube that will be rendered to the texture. commands.spawn(( Mesh3d(cube_handle), MeshMaterial3d(cube_material_handle), Transform::from_translation(Vec3::new(0.0, 0.0, 1.0)), FirstPassCube, first_pass_layer.clone(), )); // Light // NOTE: we add the light to both layers so it affects both the rendered-to-texture cube, and the cube on which we display the texture // Setting the layer to RenderLayers::layer(0) would cause the main view to be lit, but the rendered-to-texture cube to be unlit. // Setting the layer to RenderLayers::layer(1) would cause the rendered-to-texture cube to be lit, but the main view to be unlit. commands.spawn(( PointLight::default(), Transform::from_translation(Vec3::new(0.0, 0.0, 10.0)), RenderLayers::layer(0).with(1), )); commands.spawn(( Camera3d::default(), Camera { // render before the "main pass" camera order: -1, clear_color: Color::WHITE.into(), ..default() }, RenderTarget::Image(image_handle.clone().into()), Transform::from_translation(Vec3::new(0.0, 0.0, 15.0)).looking_at(Vec3::ZERO, Vec3::Y), first_pass_layer, )); let cube_size = 4.0; let cube_handle = meshes.add(Cuboid::new(cube_size, cube_size, cube_size)); // This material has the texture that has been rendered. let material_handle = materials.add(StandardMaterial { base_color_texture: Some(image_handle), reflectance: 0.02, unlit: false, ..default() }); // Main pass cube, with material containing the rendered first pass texture. commands.spawn(( Mesh3d(cube_handle), MeshMaterial3d(material_handle), Transform::from_xyz(0.0, 0.0, 1.5).with_rotation(Quat::from_rotation_x(-PI / 5.0)), MainPassCube, )); // The main pass camera. commands.spawn(( Camera3d::default(), Transform::from_xyz(0.0, 0.0, 15.0).looking_at(Vec3::ZERO, Vec3::Y), )); } /// Rotates the inner cube (first pass) fn rotator_system(time: Res<Time>, mut query: Query<&mut Transform, With<FirstPassCube>>) { for mut transform in &mut query { transform.rotate_x(1.5 * time.delta_secs()); transform.rotate_z(1.3 * time.delta_secs()); } } /// Rotates the outer cube (main pass) fn cube_rotator_system(time: Res<Time>, mut query: Query<&mut Transform, With<MainPassCube>>) { for mut transform in &mut query { transform.rotate_x(1.0 * time.delta_secs()); transform.rotate_y(0.7 * time.delta_secs()); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/3d/orthographic.rs
examples/3d/orthographic.rs
//! Shows how to create a 3D orthographic view (for isometric-look games or CAD applications). use bevy::{camera::ScalingMode, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } /// set up a simple 3D scene fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // camera commands.spawn(( Camera3d::default(), Projection::from(OrthographicProjection { // 6 world units per pixel of window height. scaling_mode: ScalingMode::FixedVertical { viewport_height: 6.0, }, ..OrthographicProjection::default_3d() }), Transform::from_xyz(5.0, 5.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y), )); // plane commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(5.0, 5.0))), MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))), )); // cubes commands.spawn(( Mesh3d(meshes.add(Cuboid::default())), MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))), Transform::from_xyz(1.5, 0.5, 1.5), )); commands.spawn(( Mesh3d(meshes.add(Cuboid::default())), MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))), Transform::from_xyz(1.5, 0.5, -1.5), )); commands.spawn(( Mesh3d(meshes.add(Cuboid::default())), MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))), Transform::from_xyz(-1.5, 0.5, 1.5), )); commands.spawn(( Mesh3d(meshes.add(Cuboid::default())), MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))), Transform::from_xyz(-1.5, 0.5, -1.5), )); // light commands.spawn((PointLight::default(), Transform::from_xyz(3.0, 8.0, 5.0))); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false