Files
Greg Shuflin de31aaf4af Add targeting reticule and laser bullets with fade-out
Clicking while cursor is locked fires a red bullet in the camera's look
direction. Bullets spawn slightly behind and below the camera for an FPS
feel, travel at 50 units/s, fade to transparent over 5 seconds via a new
per-object opacity field in ModelUniform, then get removed. A CSS
crosshair reticule appears when the cursor is locked.
2026-02-15 17:11:25 -08:00

93 lines
2.5 KiB
Rust

use glam::{Mat4, Vec3};
pub struct Camera {
pub position: Vec3,
/// Yaw in radians (rotation around Y axis)
pub yaw: f32,
/// Pitch in radians (rotation around X axis), clamped
pub pitch: f32,
pub aspect: f32,
pub fov_y: f32,
pub near: f32,
pub far: f32,
}
impl Camera {
pub fn new(position: Vec3, aspect: f32) -> Self {
Self {
position,
yaw: 0.0,
pitch: 0.0,
aspect,
fov_y: 60.0_f32.to_radians(),
near: 0.1,
far: 200.0,
}
}
/// Forward direction on the XY plane (for WASD movement)
pub fn forward(&self) -> Vec3 {
Vec3::new(self.yaw.cos(), self.yaw.sin(), 0.0).normalize()
}
/// Right direction on the XY plane
pub fn right(&self) -> Vec3 {
Vec3::new(self.yaw.sin(), -self.yaw.cos(), 0.0).normalize()
}
/// The actual look direction (including pitch) for the view matrix
pub fn look_dir(&self) -> Vec3 {
Vec3::new(
self.pitch.cos() * self.yaw.cos(),
self.pitch.cos() * self.yaw.sin(),
self.pitch.sin(),
)
.normalize()
}
pub fn view_matrix(&self) -> Mat4 {
let target = self.position + self.look_dir();
Mat4::look_at_rh(self.position, target, Vec3::Z)
}
pub fn projection_matrix(&self) -> Mat4 {
Mat4::perspective_rh(self.fov_y, self.aspect, self.near, self.far)
}
pub fn view_proj(&self) -> Mat4 {
self.projection_matrix() * self.view_matrix()
}
/// Process mouse delta for look-around
pub fn mouse_look(&mut self, dx: f32, dy: f32) {
let sensitivity = 0.003;
self.yaw -= dx * sensitivity;
self.pitch -= dy * sensitivity;
// Wrap yaw to [0, 2π) to avoid precision loss over time
self.yaw = self.yaw.rem_euclid(std::f32::consts::TAU);
// Clamp pitch to avoid gimbal flip
self.pitch = self
.pitch
.clamp(-89.0_f32.to_radians(), 89.0_f32.to_radians());
}
}
/// Uniform data shipped to the GPU
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub struct CameraUniform {
pub view_proj: [[f32; 4]; 4],
pub eye_pos: [f32; 3],
pub _padding: f32,
}
impl CameraUniform {
pub fn from_camera(cam: &Camera) -> Self {
Self {
view_proj: cam.view_proj().to_cols_array_2d(),
eye_pos: cam.position.into(),
_padding: 0.0,
}
}
}