diff --git a/crates/bevy_gltf/src/loader.rs b/crates/bevy_gltf/src/loader.rs index b138e85d5d..0f05f98a2a 100644 --- a/crates/bevy_gltf/src/loader.rs +++ b/crates/bevy_gltf/src/loader.rs @@ -1398,7 +1398,9 @@ fn load_node( let orthographic_projection = OrthographicProjection { near: orthographic.znear(), far: orthographic.zfar(), - scaling_mode: ScalingMode::FixedHorizontal(xmag), + scaling_mode: ScalingMode::FixedHorizontal { + viewport_width: xmag, + }, ..OrthographicProjection::default_3d() }; diff --git a/crates/bevy_render/src/camera/projection.rs b/crates/bevy_render/src/camera/projection.rs index 486acb91ee..7deb061fdc 100644 --- a/crates/bevy_render/src/camera/projection.rs +++ b/crates/bevy_render/src/camera/projection.rs @@ -1,7 +1,4 @@ -use core::{ - marker::PhantomData, - ops::{Div, DivAssign, Mul, MulAssign}, -}; +use core::marker::PhantomData; use crate::{primitives::Frustum, view::VisibilitySystems}; use bevy_app::{App, Plugin, PostStartup, PostUpdate}; @@ -269,6 +266,11 @@ impl Default for PerspectiveProjection { /// Scaling mode for [`OrthographicProjection`]. /// +/// The effect of these scaling modes are combined with the [`OrthographicProjection::scale`] property. +/// +/// For example, if the scaling mode is `ScalingMode::Fixed { width: 100.0, height: 300 }` and the scale is `2.0`, +/// the projection will be 200 world units wide and 600 world units tall. +/// /// # Examples /// /// Configure the orthographic projection to two world units per window height: @@ -276,85 +278,44 @@ impl Default for PerspectiveProjection { /// ``` /// # use bevy_render::camera::{OrthographicProjection, Projection, ScalingMode}; /// let projection = Projection::Orthographic(OrthographicProjection { -/// scaling_mode: ScalingMode::FixedVertical(2.0), +/// scaling_mode: ScalingMode::FixedVertical { viewport_height: 2.0 }, /// ..OrthographicProjection::default_2d() /// }); /// ``` -#[derive(Debug, Clone, Copy, Reflect, Serialize, Deserialize)] +#[derive(Default, Debug, Clone, Copy, Reflect, Serialize, Deserialize)] #[reflect(Serialize, Deserialize)] pub enum ScalingMode { - /// Manually specify the projection's size, ignoring window resizing. The image will stretch. - /// Arguments are in world units. - Fixed { width: f32, height: f32 }, /// Match the viewport size. - /// The argument is the number of pixels that equals one world unit. - WindowSize(f32), + /// + /// With a scale of 1, lengths in world units will map 1:1 with the number of pixels used to render it. + /// For example, if we have a 64x64 sprite with a [`Transform::scale`](bevy_transform::prelude::Transform) of 1.0, + /// no custom size and no inherited scale, the sprite will be 64 world units wide and 64 world units tall. + /// When rendered with [`OrthographicProjection::scaling_mode`] set to `WindowSize` when the window scale factor is 1 + /// the sprite will be rendered at 64 pixels wide and 64 pixels tall. + /// + /// Changing any of these properties will multiplicatively affect the final size. + #[default] + WindowSize, + /// Manually specify the projection's size, ignoring window resizing. The image will stretch. + /// + /// Arguments describe the area of the world that is shown (in world units). + Fixed { width: f32, height: f32 }, /// Keeping the aspect ratio while the axes can't be smaller than given minimum. + /// /// Arguments are in world units. AutoMin { min_width: f32, min_height: f32 }, /// Keeping the aspect ratio while the axes can't be bigger than given maximum. + /// /// Arguments are in world units. AutoMax { max_width: f32, max_height: f32 }, /// Keep the projection's height constant; width will be adjusted to match aspect ratio. + /// /// The argument is the desired height of the projection in world units. - FixedVertical(f32), + FixedVertical { viewport_height: f32 }, /// Keep the projection's width constant; height will be adjusted to match aspect ratio. + /// /// The argument is the desired width of the projection in world units. - FixedHorizontal(f32), -} - -impl Mul for ScalingMode { - type Output = ScalingMode; - - /// Scale the `ScalingMode`. For example, multiplying by 2 makes the viewport twice as large. - fn mul(self, rhs: f32) -> ScalingMode { - match self { - ScalingMode::Fixed { width, height } => ScalingMode::Fixed { - width: width * rhs, - height: height * rhs, - }, - ScalingMode::WindowSize(pixels_per_world_unit) => { - ScalingMode::WindowSize(pixels_per_world_unit / rhs) - } - ScalingMode::AutoMin { - min_width, - min_height, - } => ScalingMode::AutoMin { - min_width: min_width * rhs, - min_height: min_height * rhs, - }, - ScalingMode::AutoMax { - max_width, - max_height, - } => ScalingMode::AutoMax { - max_width: max_width * rhs, - max_height: max_height * rhs, - }, - ScalingMode::FixedVertical(size) => ScalingMode::FixedVertical(size * rhs), - ScalingMode::FixedHorizontal(size) => ScalingMode::FixedHorizontal(size * rhs), - } - } -} - -impl MulAssign for ScalingMode { - fn mul_assign(&mut self, rhs: f32) { - *self = *self * rhs; - } -} - -impl Div for ScalingMode { - type Output = ScalingMode; - - /// Scale the `ScalingMode`. For example, dividing by 2 makes the viewport half as large. - fn div(self, rhs: f32) -> ScalingMode { - self * (1.0 / rhs) - } -} - -impl DivAssign for ScalingMode { - fn div_assign(&mut self, rhs: f32) { - *self = *self / rhs; - } + FixedHorizontal { viewport_width: f32 }, } /// Project a 3D space onto a 2D surface using parallel lines, i.e., unlike [`PerspectiveProjection`], @@ -373,7 +334,8 @@ impl DivAssign for ScalingMode { /// ``` /// # use bevy_render::camera::{OrthographicProjection, Projection, ScalingMode}; /// let projection = Projection::Orthographic(OrthographicProjection { -/// scaling_mode: ScalingMode::WindowSize(100.0), +/// scaling_mode: ScalingMode::WindowSize, +/// scale: 0.01, /// ..OrthographicProjection::default_2d() /// }); /// ``` @@ -407,8 +369,24 @@ pub struct OrthographicProjection { pub viewport_origin: Vec2, /// How the projection will scale to the viewport. /// - /// Defaults to `ScalingMode::WindowSize(1.0)` + /// Defaults to [`ScalingMode::WindowSize`], + /// and works in concert with [`OrthographicProjection::scale`] to determine the final effect. + /// + /// For simplicity, zooming should be done by changing [`OrthographicProjection::scale`], + /// rather than changing the parameters of the scaling mode. pub scaling_mode: ScalingMode, + /// Scales the projection. + /// + /// As scale increases, the apparent size of objects decreases, and vice versa. + /// + /// Note: scaling can be set by [`scaling_mode`](Self::scaling_mode) as well. + /// This parameter scales on top of that. + /// + /// This property is particularly useful in implementing zoom functionality. + /// + /// Defaults to `1.0`, which under standard settings corresponds to a 1:1 mapping of world units to rendered pixels. + /// See [`ScalingMode::WindowSize`] for more information. + pub scale: f32, /// The area that the projection covers relative to `viewport_origin`. /// /// Bevy's [`camera_system`](crate::camera::camera_system) automatically @@ -478,7 +456,7 @@ impl CameraProjection for OrthographicProjection { fn update(&mut self, width: f32, height: f32) { let (projection_width, projection_height) = match self.scaling_mode { - ScalingMode::WindowSize(pixel_scale) => (width / pixel_scale, height / pixel_scale), + ScalingMode::WindowSize => (width, height), ScalingMode::AutoMin { min_width, min_height, @@ -503,31 +481,23 @@ impl CameraProjection for OrthographicProjection { (max_width, height * max_width / width) } } - ScalingMode::FixedVertical(viewport_height) => { + ScalingMode::FixedVertical { viewport_height } => { (width * viewport_height / height, viewport_height) } - ScalingMode::FixedHorizontal(viewport_width) => { + ScalingMode::FixedHorizontal { viewport_width } => { (viewport_width, height * viewport_width / width) } ScalingMode::Fixed { width, height } => (width, height), }; - let mut origin_x = projection_width * self.viewport_origin.x; - let mut origin_y = projection_height * self.viewport_origin.y; - - // If projection is based on window pixels, - // ensure we don't end up with fractional pixels! - if let ScalingMode::WindowSize(pixel_scale) = self.scaling_mode { - // round to nearest multiple of `pixel_scale` - origin_x = (origin_x * pixel_scale).round() / pixel_scale; - origin_y = (origin_y * pixel_scale).round() / pixel_scale; - } + let origin_x = projection_width * self.viewport_origin.x; + let origin_y = projection_height * self.viewport_origin.y; self.area = Rect::new( - -origin_x, - -origin_y, - projection_width - origin_x, - projection_height - origin_y, + self.scale * -origin_x, + self.scale * -origin_y, + self.scale * (projection_width - origin_x), + self.scale * (projection_height - origin_y), ); } @@ -575,10 +545,11 @@ impl OrthographicProjection { /// objects that are behind it. pub fn default_3d() -> Self { OrthographicProjection { + scale: 1.0, near: 0.0, far: 1000.0, viewport_origin: Vec2::new(0.5, 0.5), - scaling_mode: ScalingMode::WindowSize(1.0), + scaling_mode: ScalingMode::WindowSize, area: Rect::new(-1.0, -1.0, 1.0, 1.0), } } diff --git a/examples/2d/pixel_grid_snap.rs b/examples/2d/pixel_grid_snap.rs index 82de9f9a42..3d9de7b84d 100644 --- a/examples/2d/pixel_grid_snap.rs +++ b/examples/2d/pixel_grid_snap.rs @@ -3,7 +3,7 @@ use bevy::{ prelude::*, render::{ - camera::{RenderTarget, ScalingMode}, + camera::RenderTarget, render_resource::{ Extent3d, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages, }, @@ -149,6 +149,6 @@ fn fit_canvas( for event in resize_events.read() { let h_scale = event.width / RES_WIDTH as f32; let v_scale = event.height / RES_HEIGHT as f32; - projection.scaling_mode = ScalingMode::WindowSize(h_scale.min(v_scale).round()); + projection.scale = 1. / h_scale.min(v_scale).round(); } } diff --git a/examples/3d/camera_sub_view.rs b/examples/3d/camera_sub_view.rs index ce287f3e9e..0e7ba74ff7 100644 --- a/examples/3d/camera_sub_view.rs +++ b/examples/3d/camera_sub_view.rs @@ -141,7 +141,9 @@ fn setup( commands.spawn(( Camera3d::default(), Projection::from(OrthographicProjection { - scaling_mode: ScalingMode::FixedVertical(6.0), + scaling_mode: ScalingMode::FixedVertical { + viewport_height: 6.0, + }, ..OrthographicProjection::default_3d() }), Camera { @@ -161,7 +163,9 @@ fn setup( commands.spawn(( Camera3d::default(), Projection::from(OrthographicProjection { - scaling_mode: ScalingMode::FixedVertical(6.0), + scaling_mode: ScalingMode::FixedVertical { + viewport_height: 6.0, + }, ..OrthographicProjection::default_3d() }), Camera { @@ -187,7 +191,9 @@ fn setup( commands.spawn(( Camera3d::default(), Projection::from(OrthographicProjection { - scaling_mode: ScalingMode::FixedVertical(6.0), + scaling_mode: ScalingMode::FixedVertical { + viewport_height: 6.0, + }, ..OrthographicProjection::default_3d() }), Camera { @@ -214,7 +220,9 @@ fn setup( commands.spawn(( Camera3d::default(), Projection::from(OrthographicProjection { - scaling_mode: ScalingMode::FixedVertical(6.0), + scaling_mode: ScalingMode::FixedVertical { + viewport_height: 6.0, + }, ..OrthographicProjection::default_3d() }), Camera { diff --git a/examples/3d/orthographic.rs b/examples/3d/orthographic.rs index 4b4070285c..e6bb11d274 100644 --- a/examples/3d/orthographic.rs +++ b/examples/3d/orthographic.rs @@ -19,8 +19,10 @@ fn setup( commands.spawn(( Camera3d::default(), Projection::from(OrthographicProjection { - // 6 world units per window height. - scaling_mode: ScalingMode::FixedVertical(6.0), + // 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), diff --git a/examples/3d/pbr.rs b/examples/3d/pbr.rs index f593d4be4f..f6c12ef7da 100644 --- a/examples/3d/pbr.rs +++ b/examples/3d/pbr.rs @@ -1,6 +1,7 @@ //! This example shows how to configure Physically Based Rendering (PBR) parameters. -use bevy::{prelude::*, render::camera::ScalingMode}; +use bevy::prelude::*; +use bevy::render::camera::ScalingMode; fn main() { App::new() @@ -110,7 +111,8 @@ fn setup( Camera3d::default(), Transform::from_xyz(0.0, 0.0, 8.0).looking_at(Vec3::default(), Vec3::Y), Projection::from(OrthographicProjection { - scaling_mode: ScalingMode::WindowSize(100.0), + scale: 100., + scaling_mode: ScalingMode::WindowSize, ..OrthographicProjection::default_3d() }), EnvironmentMapLight { diff --git a/examples/camera/projection_zoom.rs b/examples/camera/projection_zoom.rs index a55a733140..8776c41618 100644 --- a/examples/camera/projection_zoom.rs +++ b/examples/camera/projection_zoom.rs @@ -4,22 +4,36 @@ use std::{f32::consts::PI, ops::Range}; use bevy::{input::mouse::AccumulatedMouseScroll, prelude::*, render::camera::ScalingMode}; -#[derive(Debug, Default, Resource)] +#[derive(Debug, Resource)] struct CameraSettings { - // Clamp fixed vertical scale to this range + /// The height of the viewport in world units when the orthographic camera's scale is 1 + pub orthographic_viewport_height: f32, + /// Clamp the orthographic camera's scale to this range pub orthographic_zoom_range: Range, - // Multiply mouse wheel inputs by this factor + /// Multiply mouse wheel inputs by this factor when using the orthographic camera pub orthographic_zoom_speed: f32, - // Clamp field of view to this range + /// Clamp perspective camera's field of view to this range pub perspective_zoom_range: Range, - // Multiply mouse wheel inputs by this factor + /// Multiply mouse wheel inputs by this factor when using the perspective camera pub perspective_zoom_speed: f32, } fn main() { App::new() .add_plugins(DefaultPlugins) - .init_resource::() + .insert_resource(CameraSettings { + orthographic_viewport_height: 5., + // In orthographic projections, we specify camera scale relative to a default value of 1, + // in which one unit in world space corresponds to one pixel. + orthographic_zoom_range: 0.1..10.0, + // This value was hand-tuned to ensure that zooming in and out feels smooth but not slow. + orthographic_zoom_speed: 0.2, + // Perspective projections use field of view, expressed in radians. We would + // normally not set it to more than π, which represents a 180° FOV. + perspective_zoom_range: (PI / 5.)..(PI - 0.2), + // Changes in FOV are much more noticeable due to its limited range in radians + perspective_zoom_speed: 0.05, + }) .add_systems(Startup, (setup, instructions)) .add_systems(Update, (switch_projection, zoom)) .run(); @@ -28,33 +42,23 @@ fn main() { /// Set up a simple 3D scene fn setup( asset_server: Res, - mut camera_settings: ResMut, + camera_settings: Res, mut commands: Commands, mut meshes: ResMut>, mut materials: ResMut>, ) { - // Perspective projections use field of view, expressed in radians. We would - // normally not set it to more than π, which represents a 180° FOV. - let min_fov = PI / 5.; - let max_fov = PI - 0.2; - - // In orthographic projections, we specify sizes in world units. The below values - // are very roughly similar to the above FOV settings, in terms of how "far away" - // the subject will appear when used with FixedVertical scaling mode. - let min_zoom = 5.0; - let max_zoom = 150.0; - - camera_settings.orthographic_zoom_range = min_zoom..max_zoom; - camera_settings.orthographic_zoom_speed = 1.0; - camera_settings.perspective_zoom_range = min_fov..max_fov; - // Changes in FOV are much more noticeable due to its limited range in radians - camera_settings.perspective_zoom_speed = 0.05; - commands.spawn(( Name::new("Camera"), Camera3d::default(), Projection::from(OrthographicProjection { - scaling_mode: ScalingMode::FixedVertical(camera_settings.orthographic_zoom_range.start), + // We can set the scaling mode to FixedVertical to keep the viewport height constant as its aspect ratio changes. + // The viewport height is the height of the camera's view in world units when the scale is 1. + scaling_mode: ScalingMode::FixedVertical { + viewport_height: camera_settings.orthographic_viewport_height, + }, + // This is the default value for scale for orthographic projections. + // To zoom in and out, change this value, rather than `ScalingMode` or the camera's position. + scale: 1., ..OrthographicProjection::default_3d() }), Transform::from_xyz(5.0, 5.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y), @@ -117,9 +121,9 @@ fn switch_projection( ..default() }), Projection::Perspective(_) => Projection::Orthographic(OrthographicProjection { - scaling_mode: ScalingMode::FixedVertical( - camera_settings.orthographic_zoom_range.start, - ), + scaling_mode: ScalingMode::FixedVertical { + viewport_height: camera_settings.orthographic_viewport_height, + }, ..OrthographicProjection::default_3d() }), } @@ -131,30 +135,32 @@ fn zoom( camera_settings: Res, mouse_wheel_input: Res, ) { - // Usually, you won't need to handle both types of projection. This is by way of demonstration. + // Usually, you won't need to handle both types of projection, + // but doing so makes for a more complete example. match *camera.into_inner() { Projection::Orthographic(ref mut orthographic) => { - // Get the current scaling_mode value to allow clamping the new value to our zoom range. - let ScalingMode::FixedVertical(current) = orthographic.scaling_mode else { - return; - }; - // Set a new ScalingMode, clamped to a limited range. - let zoom_level = (current - + camera_settings.orthographic_zoom_speed * mouse_wheel_input.delta.y) - .clamp( - camera_settings.orthographic_zoom_range.start, - camera_settings.orthographic_zoom_range.end, - ); - orthographic.scaling_mode = ScalingMode::FixedVertical(zoom_level); + // We want scrolling up to zoom in, decreasing the scale, so we negate the delta. + let delta_zoom = -mouse_wheel_input.delta.y * camera_settings.orthographic_zoom_speed; + // When changing scales, logarithmic changes are more intuitive. + // To get this effect, we add 1 to the delta, so that a delta of 0 + // results in no multiplicative effect, positive values result in a multiplicative increase, + // and negative values result in multiplicative decreases. + let multiplicative_zoom = 1. + delta_zoom; + + orthographic.scale = (orthographic.scale * multiplicative_zoom).clamp( + camera_settings.orthographic_zoom_range.start, + camera_settings.orthographic_zoom_range.end, + ); } Projection::Perspective(ref mut perspective) => { + // We want scrolling up to zoom in, decreasing the scale, so we negate the delta. + let delta_zoom = -mouse_wheel_input.delta.y * camera_settings.perspective_zoom_speed; + // Adjust the field of view, but keep it within our stated range. - perspective.fov = (perspective.fov - + camera_settings.perspective_zoom_speed * mouse_wheel_input.delta.y) - .clamp( - camera_settings.perspective_zoom_range.start, - camera_settings.perspective_zoom_range.end, - ); + perspective.fov = (perspective.fov + delta_zoom).clamp( + camera_settings.perspective_zoom_range.start, + camera_settings.perspective_zoom_range.end, + ); } } } diff --git a/examples/math/custom_primitives.rs b/examples/math/custom_primitives.rs index 21c0e66adb..69890ba0d9 100644 --- a/examples/math/custom_primitives.rs +++ b/examples/math/custom_primitives.rs @@ -36,6 +36,7 @@ const TRANSFORM_2D: Transform = Transform { const PROJECTION_2D: Projection = Projection::Orthographic(OrthographicProjection { near: -1.0, far: 10.0, + scale: 1.0, viewport_origin: Vec2::new(0.5, 0.5), scaling_mode: ScalingMode::AutoMax { max_width: 8.0, diff --git a/examples/stress_tests/many_lights.rs b/examples/stress_tests/many_lights.rs index da3a3f3429..696e63b930 100644 --- a/examples/stress_tests/many_lights.rs +++ b/examples/stress_tests/many_lights.rs @@ -93,7 +93,9 @@ fn setup( Some("orthographic") => commands.spawn(( Camera3d::default(), Projection::from(OrthographicProjection { - scaling_mode: ScalingMode::FixedHorizontal(20.0), + scaling_mode: ScalingMode::FixedHorizontal { + viewport_width: 20.0, + }, ..OrthographicProjection::default_3d() }), )),