Skip to main content

Camera

Struct Camera 

Source
#[non_exhaustive]
pub struct Camera { pub pose: Pose, pub projection: Projection, pub exposure: PhysicalExposure, pub aspect: f32, }
Expand description

The viewport camera: where it is, how it projects, and how it exposes.

pose places the eye in f64 world space and orients it. projection maps view space to the screen, and aspect is the viewport’s width over height, set each frame from the viewport size. exposure carries the physical camera settings and the focus distance.

Build an orbit camera with Camera::orbit or a pointed one with Camera::look_at. The camera itself does not orbit: orbit controllers keep the centre and distance, and write the camera’s pose. The focus distance doubles as the orbit distance, so target is the orbit centre of a camera an orbit controller drives.

All matrices are right-handed (wgpu NDC convention).

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§pose: Pose

Eye position and orientation.

§projection: Projection

Projection.

§exposure: PhysicalExposure

Physical exposure settings and focus distance. The renderer reads exposure from DisplaySettings::exposure, not from here; set it from PhysicalExposure::to_exposure_mode.

§aspect: f32

Viewport width / height ratio, updated each frame from the viewport rect.

Implementations§

Source§

impl Camera

Source

pub const MIN_DISTANCE: f32 = 0.01

Minimum orbit distance the zoom helpers clamp to.

Source

pub const MAX_DISTANCE: f32 = 1.0e6

Maximum orbit distance the zoom helpers clamp to.

Source

pub fn new(pose: Pose) -> Camera

A camera with the given pose, the default perspective projection and the default exposure.

Source

pub fn orbit( centre: impl Into<DVec3>, distance: f32, orientation: Quat, ) -> Camera

An orbit camera: the eye sits distance from centre along the orientation’s local +Z (eye = centre + orientation * (Z * distance)), looking at centre, which is also the focus point.

Source

pub fn look_at( eye: impl Into<DVec3>, target: impl Into<DVec3>, up: Vec3, ) -> Camera

A camera at eye looking at target, with up as close to the screen’s up as it can be. target is the focus point.

Source

pub fn with_projection(self, projection: Projection) -> Camera

Builder: set the projection.

Source

pub fn with_aspect(self, aspect: f32) -> Camera

Builder: set the aspect ratio (width / height).

Source

pub fn orthographic(self) -> Camera

Builder: switch to the orthographic projection that frames the same height at the focus distance; see set_orthographic.

Source

pub fn with_fov_y(self, fov_y: f32) -> Camera

Builder: set the vertical field of view; see set_fov_y.

Source

pub fn with_exposure(self, exposure: PhysicalExposure) -> Camera

Builder: set the exposure.

Source

pub fn eye(&self) -> DVec3

Eye position in world space, in f64.

Source

pub fn orientation(&self) -> Quat

Camera orientation in f32.

Examples found in repository?
examples/custom_controller.rs (line 64)
38fn main() {
39    // 1. RESOLVE: feed native-shaped events into ViewportInput for one frame.
40    let mut input = ViewportInput::from_preset(BindingPreset::Viewer);
41    input.begin_frame(ViewportContext::new(
42        InputOwnership::full_window(),
43        [800.0, 600.0],
44    ));
45
46    // In the primitives preset, plain left-drag (no modifiers) orbits. Drive it
47    // by hand: place the pointer, press the button there (that sets the drag
48    // origin), then move across the viewport to accumulate the drag delta.
49    input.push_event(ViewportEvent::PointerMoved {
50        position: [400.0, 300.0].into(),
51    });
52    input.push_event(ViewportEvent::MouseButton {
53        button: MouseButton::Left,
54        state: ButtonState::Pressed,
55    });
56    input.push_event(ViewportEvent::PointerMoved {
57        position: [460.0, 300.0].into(),
58    });
59
60    let frame: ActionFrame = input.resolve();
61
62    // 2. APPLY: hand the resolved frame to your controller.
63    let mut camera = Camera::default();
64    let before = camera.orientation();
65
66    let mut controller = HalfSpeedOrbit;
67    controller.apply(&mut camera, &frame, 1.0 / 60.0);
68
69    println!("resolved orbit delta : {:?}", frame.navigation.orbit);
70    println!("camera orientation before : {before:?}");
71    println!("camera orientation after  : {:?}", camera.orientation());
72    println!(
73        "moved: {}",
74        before.abs_diff_eq(camera.orientation(), 1e-6) == false
75    );
76}
Source

pub fn forward(&self) -> Vec3

The direction the camera looks, in world space.

Source

pub fn right(&self) -> Vec3

Camera right vector in world space.

Source

pub fn up(&self) -> Vec3

Camera up vector in world space.

Source

pub fn target_at(&self, distance: f32) -> DVec3

The point distance in front of the eye along the view direction.

Source

pub fn target(&self) -> DVec3

The focus point: focus_distance in front of the eye. For a camera an orbit controller drives, the orbit centre.

Source

pub fn focus_distance(&self) -> f32

Distance from the eye to the focus point.

Source

pub fn set_focus_distance(&mut self, distance: f32)

Set the focus distance without moving the camera.

Source

pub fn set_pose(&mut self, pose: Pose)

Replace the pose. The projection is left alone, so an orthographic height stays as it is.

Source

pub fn lerp(a: &Camera, b: &Camera, t: f32) -> Camera

The camera t of the way from a to b, with t clamped to 0..=1: t = 0 returns a and t = 1 returns b exactly.

The eye position is lerped and the orientation slerped, with no orbit centre involved. The aspect and the exposure (focus distance included) are lerped.

When both projections are orthographic the height is lerped, and when both are perspective the field of view is; near and far planes are lerped when both cameras set them, and otherwise taken from a below t = 0.5 and from b at or above it. When the projections differ in kind, or either is a matrix projection, the result takes a’s projection unchanged below t = 0.5 and b’s at or above it: there is no smooth blend between orthographic and perspective here, and a host that wants one builds it itself.

Source

pub fn orbit_target(&self) -> CameraTarget

The camera’s orbit view: its focus point, focus distance and orientation.

Examples found in repository?
examples/custom_controller.rs (line 29)
26    fn apply(&mut self, camera: &mut Camera, frame: &ActionFrame, _dt: f32) {
27        let nav = &frame.navigation;
28        if nav.orbit.x != 0.0 || nav.orbit.y != 0.0 {
29            let mut target = camera.orbit_target();
30            target.orbit(nav.orbit.x * 0.5, nav.orbit.y * 0.5);
31            camera.set_orbit_target(target);
32        }
33        // A real custom controller might map zoom to dolly, add inertia, clamp
34        // pitch differently, etc. The point is the app decides here.
35    }
Source

pub fn set_orbit( &mut self, centre: impl Into<DVec3>, distance: f32, orientation: Quat, )

Place the camera on an orbit: the pose of Camera::orbit, with the focus distance set to distance. An orthographic view height scales with the change in distance, so zooming frames the same way in both projections.

Source

pub fn set_orbit_centre(&mut self, centre: impl Into<DVec3>)

Move the orbit centre to centre, keeping the distance and orientation. Goes through set_orbit, so an orthographic height is rescaled if the focus distance differs from the distance kept.

Source

pub fn set_orbit_distance(&mut self, distance: f32)

Move the eye to distance from the orbit centre, keeping the centre and orientation. The distance is clamped to [MIN_DISTANCE, MAX_DISTANCE]. An orthographic height scales with the change in distance, as in set_orbit.

Source

pub fn set_orbit_orientation(&mut self, orientation: Quat)

Turn the camera to orientation (normalised) about the orbit centre, keeping the centre and distance. Goes through set_orbit, so an orthographic height is rescaled if the focus distance changes.

Source

pub fn set_orbit_target(&mut self, target: CameraTarget)

set_orbit from a CameraTarget. An orthographic height scales with the change in distance.

Examples found in repository?
examples/custom_controller.rs (line 31)
26    fn apply(&mut self, camera: &mut Camera, frame: &ActionFrame, _dt: f32) {
27        let nav = &frame.navigation;
28        if nav.orbit.x != 0.0 || nav.orbit.y != 0.0 {
29            let mut target = camera.orbit_target();
30            target.orbit(nav.orbit.x * 0.5, nav.orbit.y * 0.5);
31            camera.set_orbit_target(target);
32        }
33        // A real custom controller might map zoom to dolly, add inertia, clamp
34        // pitch differently, etc. The point is the app decides here.
35    }
Source

pub fn fov_y(&self) -> f32

Vertical angle that frames the view at the focus distance: a perspective camera’s field of view, or the matching angle for an orthographic one.

Source

pub fn set_fov_y(&mut self, fov_y: f32)

Set the vertical field of view in radians. An orthographic camera takes the height that angle frames at the focus distance, so on an orthographic camera this changes the zoom; use set_ortho_height to set it directly. A matrix projection is left alone.

Source

pub fn is_orthographic(&self) -> bool

Whether the projection is orthographic.

Source

pub fn set_ortho_height(&mut self, height: f32)

Set the orthographic view height in world units, leaving the pose and focus distance alone. A perspective camera becomes orthographic with that height, keeping its near and far planes; a matrix projection is left alone.

Source

pub fn set_orthographic(&mut self, orthographic: bool)

Switch between perspective and orthographic, keeping the framing at the focus distance. A matrix projection is left alone.

Source

pub fn set_aspect_ratio(&mut self, width: f32, height: f32)

Set the aspect ratio from pixel dimensions. A zero or negative height gives 1.0.

Source

pub fn set_clip_planes(&mut self, znear: f32, zfar: f32)

Set the near and far plane distances. On a matrix projection, sets the culling range.

Source

pub fn depth_range(&self) -> (f32, f32)

(near, far) distances the camera culls between; see Projection::depth_range.

Source

pub fn view_height_at(&self, depth: f32) -> f32

World-space height of the view at view depth depth.

Source

pub fn view_matrix(&self) -> Mat4

Right-handed view matrix (world -> camera space), in f32 world coordinates. Far from the world origin its translation loses precision; the renderer rebuilds it from the f64 eye.

Source

pub fn proj_matrix(&self) -> Mat4

The projection matrix the renderer draws with; see Projection::proj_matrix.

Source

pub fn culling_proj_matrix(&self) -> Mat4

The finite culling projection; see Projection::culling_proj_matrix.

Source

pub fn view_proj_matrix(&self) -> Mat4

proj_matrix times the view matrix. Unproject screen points with screen_ray rather than through its inverse at depth 0 and 1.

Source

pub fn culling_view_proj_matrix(&self) -> Mat4

culling_proj_matrix times the view matrix.

Source

pub fn frustum(&self) -> Frustum

The view frustum of culling_view_proj_matrix in world space, built relative to the eye; see Frustum::from_eye_relative.

Source

pub fn screen_ray(&self, ndc: Vec2) -> (Vec3, Vec3)

The world-space ray through a point on screen, as (origin, direction) with a unit direction.

ndc is the point in normalised device coordinates: -1..1 left to right and bottom to top. A perspective ray starts at the eye; an orthographic ray starts on the near plane and runs along forward.

Source

pub fn frame_sphere(&mut self, centre: impl Into<DVec3>, radius: f32)

Frame a bounding sphere, keeping the orientation. Goes through set_orbit, so an orthographic height scales with the change in distance; set it afterwards with set_ortho_height to fix the zoom.

Source

pub fn frame_aabb(&mut self, aabb: &Aabb)

Frame an AABB, keeping the orientation. An orthographic height scales with the change in distance, as in frame_sphere.

Source

pub fn fit_sphere_target( &self, centre: impl Into<DVec3>, radius: f32, ) -> CameraTarget

The CameraTarget that frames a bounding sphere, keeping the orientation.

Source

pub fn fit_aabb_target(&self, aabb: &Aabb) -> CameraTarget

The CameraTarget that frames an AABB, keeping the orientation.

Source

pub fn fit_sphere(&self, centre: impl Into<DVec3>, radius: f32) -> (DVec3, f32)

(centre, distance) that frames a bounding sphere, keeping the orientation. Pads by 1.2x so the object does not touch the edges.

Source

pub fn fit_aabb(&self, aabb: &Aabb) -> (DVec3, f32)

(centre, distance) that frames an AABB, through its bounding sphere.

Source

pub fn centre_on_domain(&mut self, nx: f32, ny: f32, nz: f32)

Centre the camera on a domain of the given extents, with the distance and clipping planes set so all of it is visible. An orthographic height scales with the change in distance, as in set_orbit.

Trait Implementations§

Source§

impl Clone for Camera

Source§

fn clone(&self) -> Camera

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Camera

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for Camera

Source§

fn default() -> Camera

An orbit camera 5 units from the origin, about 27 degrees above the x-y plane, with a 45 degree perspective.

Source§

impl<'de> Deserialize<'de> for Camera

Source§

fn deserialize<D>( deserializer: D, ) -> Result<Camera, <D as Deserializer<'de>>::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl From<CameraV0> for Camera

Source§

fn from(v0: CameraV0) -> Camera

The same view as a pose camera. A far plane other than the default becomes a finite one; the default draws with no far plane, as before.

Source§

impl PartialEq for Camera

Source§

fn eq(&self, other: &Camera) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for Camera

Source§

fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for Camera

Auto Trait Implementations§

§

impl Forget for Camera

§

impl Freeze for Camera

§

impl Move for Camera

§

impl RefUnwindSafe for Camera

§

impl Send for Camera

§

impl Sync for Camera

§

impl Unpin for Camera

§

impl UnsafeUnpin for Camera

§

impl UnwindSafe for Camera

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.