Skip to content

Commit

Permalink
Improve OrthographicCamera consistency and usability (#6201)
Browse files Browse the repository at this point in the history
# Objective

- Terminology used in field names and docs aren't accurate
- `window_origin` doesn't have any effect when `scaling_mode` is `ScalingMode::None`
- `left`, `right`, `bottom`, and `top` are set automatically unless `scaling_mode` is `None`. Fields that only sometimes give feedback are confusing.
- `ScalingMode::WindowSize` has no arguments, which is inconsistent with other `ScalingMode`s. 1 pixel = 1 world unit is also typically way too wide.
- `OrthographicProjection` feels generally less streamlined than its `PerspectiveProjection` counterpart
- Fixes #5818 
- Fixes #6190 

## Solution

- Improve consistency in `OrthographicProjection`'s public fields (they should either always give feedback or never give feedback).
- Improve consistency in `ScalingMode`'s arguments
- General usability improvements
- Improve accuracy of terminology:
  - "Window" should refer to the physical window on the desktop
  - "Viewport" should refer to the component in the window that images are drawn on (typically all of it)
  - "View frustum" should refer to the volume captured by the projection

---

## Changelog

### Added
- Added argument to `ScalingMode::WindowSize` that specifies the number of pixels that equals one world unit.
- Added documentation for fields and enums

### Changed
- Renamed `window_origin` to `viewport_origin`, which now:
  - Affects all `ScalingMode`s
  - Takes a fraction of the viewport's width and height instead of an enum
    - Removed `WindowOrigin` enum as it's obsolete
- Renamed `ScalingMode::None` to `ScalingMode::Fixed`, which now:
  - Takes arguments to specify the projection size
- Replaced `left`, `right`, `bottom`, and `top` fields with a single `area: Rect`
- `scale` is now applied before updating `area`. Reading from it will take `scale` into account.
- Documentation changes to make terminology more accurate and consistent

## Migration Guide
- Change `window_origin` to `viewport_origin`; replace `WindowOrigin::Center` with `Vec2::new(0.5, 0.5)` and `WindowOrigin::BottomLeft` with `Vec2::new(0.0, 0.0)`
- For shadow projections and such, replace `left`, `right`, `bottom`, and `top` with `area: Rect::new(left, bottom, right, top)`
- For camera projections, remove l/r/b/t values from `OrthographicProjection` instantiations, as they no longer have any effect in any `ScalingMode`
- Change `ScalingMode::None` to `ScalingMode::Fixed`
  - Replace manual changes of l/r/b/t with:
    - Arguments in `ScalingMode::Fixed` to specify size
    - `viewport_origin` to specify offset
- Change `ScalingMode::WindowSize` to `ScalingMode::WindowSize(1.0)`
  • Loading branch information
xgbwei committed Feb 8, 2023
1 parent 26e00f9 commit 09cb590
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 64 deletions.
4 changes: 2 additions & 2 deletions crates/bevy_gltf/src/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -719,9 +719,9 @@ fn load_node(
let projection = match camera.projection() {
gltf::camera::Projection::Orthographic(orthographic) => {
let xmag = orthographic.xmag();
let orthographic_projection: OrthographicProjection = OrthographicProjection {
far: orthographic.zfar(),
let orthographic_projection = OrthographicProjection {
near: orthographic.znear(),
far: orthographic.zfar(),
scaling_mode: ScalingMode::FixedHorizontal(1.0),
scale: xmag,
..Default::default()
Expand Down
1 change: 0 additions & 1 deletion crates/bevy_render/src/camera/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ impl Plugin for CameraPlugin {
app.register_type::<Camera>()
.register_type::<Viewport>()
.register_type::<Option<Viewport>>()
.register_type::<WindowOrigin>()
.register_type::<ScalingMode>()
.register_type::<CameraRenderGraph>()
.register_type::<RenderTarget>()
Expand Down
138 changes: 77 additions & 61 deletions crates/bevy_render/src/camera/projection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::marker::PhantomData;

use bevy_app::{App, CoreSchedule, CoreSet, Plugin, StartupSet};
use bevy_ecs::{prelude::*, reflect::ReflectComponent};
use bevy_math::Mat4;
use bevy_math::{Mat4, Rect, Vec2};
use bevy_reflect::{
std_traits::ReflectDefault, FromReflect, GetTypeRegistration, Reflect, ReflectDeserialize,
ReflectSerialize,
Expand Down Expand Up @@ -169,57 +169,92 @@ impl Default for PerspectiveProjection {
}
}

// TODO: make this a component instead of a property
#[derive(Debug, Clone, Reflect, FromReflect, Serialize, Deserialize)]
#[reflect(Serialize, Deserialize)]
pub enum WindowOrigin {
Center,
BottomLeft,
}

#[derive(Debug, Clone, Reflect, FromReflect, Serialize, Deserialize)]
#[reflect(Serialize, Deserialize)]
pub enum ScalingMode {
/// Manually specify left/right/top/bottom values.
/// Ignore window resizing; the image will stretch.
None,
/// Match the window size. 1 world unit = 1 pixel.
WindowSize,
/// 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),
/// 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 vertical axis constant; resize horizontal with aspect ratio.
/// The argument is the desired height of the viewport in world units.
/// 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),
/// Keep horizontal axis constant; resize vertical with aspect ratio.
/// The argument is the desired width of the viewport in world units.
/// 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),
}

/// Project a 3D space onto a 2D surface using parallel lines, i.e., unlike [`PerspectiveProjection`],
/// the size of objects remains the same regardless of their distance to the camera.
///
/// The volume contained in the projection is called the *view frustum*. Since the viewport is rectangular
/// and projection lines are parallel, the view frustum takes the shape of a cuboid.
///
/// Note that the scale of the projection and the apparent size of objects are inversely proportional.
/// As the size of the projection increases, the size of objects decreases.
#[derive(Component, Debug, Clone, Reflect, FromReflect)]
#[reflect(Component, Default)]
pub struct OrthographicProjection {
pub left: f32,
pub right: f32,
pub bottom: f32,
pub top: f32,
/// The distance of the near clipping plane in world units.
///
/// Objects closer than this will not be rendered.
///
/// Defaults to `0.0`
pub near: f32,
/// The distance of the far clipping plane in world units.
///
/// Objects further than this will not be rendered.
///
/// Defaults to `1000.0`
pub far: f32,
pub window_origin: WindowOrigin,
/// Specifies the origin of the viewport as a normalized position from 0 to 1, where (0, 0) is the bottom left
/// and (1, 1) is the top right. This determines where the camera's position sits inside the viewport.
///
/// When the projection scales due to viewport resizing, the position of the camera, and thereby `viewport_origin`,
/// remains at the same relative point.
///
/// Consequently, this is pivot point when scaling. With a bottom left pivot, the projection will expand
/// upwards and to the right. With a top right pivot, the projection will expand downwards and to the left.
/// Values in between will caused the projection to scale proportionally on each axis.
///
/// Defaults to `(0.5, 0.5)`, which makes scaling affect opposite sides equally, keeping the center
/// point of the viewport centered.
pub viewport_origin: Vec2,
/// How the projection will scale when the viewport is resized.
///
/// Defaults to `ScalingMode::WindowScale(1.0)`
pub scaling_mode: ScalingMode,
/// Scales the projection in world units.
///
/// As scale increases, the apparent size of objects decreases, and vice versa.
///
/// Defaults to `1.0`
pub scale: f32,
/// The area that the projection covers relative to `viewport_origin`.
///
/// Bevy's [`camera_system`](crate::camera::camera_system) automatically
/// updates this value when the viewport is resized depending on `OrthographicProjection`'s other fields.
/// In this case, `area` should not be manually modified.
///
/// It may be necessary to set this manually for shadow projections and such.
pub area: Rect,
}

impl CameraProjection for OrthographicProjection {
fn get_projection_matrix(&self) -> Mat4 {
Mat4::orthographic_rh(
self.left * self.scale,
self.right * self.scale,
self.bottom * self.scale,
self.top * self.scale,
self.area.min.x,
self.area.max.x,
self.area.min.y,
self.area.max.y,
// NOTE: near and far are swapped to invert the depth range from [0,1] to [1,0]
// This is for interoperability with pipelines using infinite reverse perspective projections.
self.far,
Expand All @@ -228,8 +263,8 @@ impl CameraProjection for OrthographicProjection {
}

fn update(&mut self, width: f32, height: f32) {
let (viewport_width, viewport_height) = match self.scaling_mode {
ScalingMode::WindowSize => (width, height),
let (projection_width, projection_height) = match self.scaling_mode {
ScalingMode::WindowSize(pixel_scale) => (width / pixel_scale, height / pixel_scale),
ScalingMode::AutoMin {
min_width,
min_height,
Expand Down Expand Up @@ -260,34 +295,18 @@ impl CameraProjection for OrthographicProjection {
ScalingMode::FixedHorizontal(viewport_width) => {
(viewport_width, height * viewport_width / width)
}
ScalingMode::None => return,
ScalingMode::Fixed { width, height } => (width, height),
};

match self.window_origin {
WindowOrigin::Center => {
let half_width = viewport_width / 2.0;
let half_height = viewport_height / 2.0;
self.left = -half_width;
self.bottom = -half_height;
self.right = half_width;
self.top = half_height;
let origin_x = projection_width * self.viewport_origin.x;
let origin_y = projection_height * self.viewport_origin.y;

if let ScalingMode::WindowSize = self.scaling_mode {
if self.scale == 1.0 {
self.left = self.left.floor();
self.bottom = self.bottom.floor();
self.right = self.right.floor();
self.top = self.top.floor();
}
}
}
WindowOrigin::BottomLeft => {
self.left = 0.0;
self.bottom = 0.0;
self.right = viewport_width;
self.top = viewport_height;
}
}
self.area = Rect::new(
self.scale * -origin_x,
self.scale * -origin_y,
self.scale * (projection_width - origin_x),
self.scale * (projection_height - origin_y),
);
}

fn far(&self) -> f32 {
Expand All @@ -298,15 +317,12 @@ impl CameraProjection for OrthographicProjection {
impl Default for OrthographicProjection {
fn default() -> Self {
OrthographicProjection {
left: -1.0,
right: 1.0,
bottom: -1.0,
top: 1.0,
scale: 1.0,
near: 0.0,
far: 1000.0,
window_origin: WindowOrigin::Center,
scaling_mode: ScalingMode::WindowSize,
scale: 1.0,
viewport_origin: Vec2::new(0.5, 0.5),
scaling_mode: ScalingMode::WindowSize(1.0),
area: Rect::new(-1.0, -1.0, 1.0, 1.0),
}
}
}

0 comments on commit 09cb590

Please sign in to comment.