Skip to main content

veloren_voxygen/scene/
mod.rs

1pub mod camera;
2pub mod debug;
3pub mod figure;
4pub mod lod;
5pub mod math;
6pub mod particle;
7pub mod simple;
8pub mod smoke_cycle;
9pub mod terrain;
10pub mod tether;
11pub mod trail;
12
13use std::collections::HashSet;
14
15pub use self::{
16    camera::{Camera, CameraMode},
17    debug::{Debug, DebugShape, DebugShapeId},
18    figure::FigureMgr,
19    lod::Lod,
20    particle::ParticleMgr,
21    terrain::{SpriteRenderContextLazy, Terrain},
22    tether::TetherMgr,
23    trail::TrailMgr,
24};
25use crate::{
26    audio::{
27        AudioFrontend,
28        ambience::{self, AmbienceMgr},
29        music::MusicMgr,
30        sfx::SfxMgr,
31    },
32    ecs::comp::Interpolated,
33    render::{
34        CloudsLocals, Consts, CullingMode, Drawer, GlobalModel, Globals, GlobalsBindGroup, Light,
35        Model, PointLightMatrix, PostProcessLocals, RainOcclusionLocals, Renderer, Shadow,
36        ShadowLocals, SkyboxVertex, create_skybox_mesh,
37    },
38    session::PlayerDebugLines,
39    settings::Settings,
40    window::{AnalogGameInput, Event},
41};
42use client::Client;
43use common::{
44    calendar::Calendar,
45    comp::{
46        self, CapsulePrism, CharacterState, item::ItemDesc,
47        ship::figuredata::VOXEL_COLLIDER_MANIFEST, slot::EquipSlot, tool::ToolKind,
48    },
49    outcome::Outcome,
50    resources::{DeltaTime, TimeOfDay, TimeScale},
51    terrain::{BlockKind, TerrainChunk, TerrainGrid},
52    vol::ReadVol,
53    weather::WeatherGrid,
54};
55use common_base::{prof_span, span};
56use common_state::State;
57use comp::item::Reagent;
58use hashbrown::HashMap;
59use num::traits::{Float, FloatConst};
60use specs::{Entity as EcsEntity, Join, LendJoin, WorldExt};
61use vek::*;
62
63const ZOOM_CAP_PLAYER: f32 = 1000.0;
64const ZOOM_CAP_ADMIN: f32 = 100000.0;
65
66// TODO: Don't hard-code this.
67const CURSOR_PAN_SCALE: f32 = 0.005;
68
69pub(crate) const MAX_LIGHT_COUNT: usize = 20; // 31 (total shadow_mats is limited to 128 with default
70// max_uniform_buffer_binding_size)
71pub(crate) const MAX_SHADOW_COUNT: usize = 24;
72pub(crate) const MAX_POINT_LIGHT_MATRICES_COUNT: usize = MAX_LIGHT_COUNT * 6 + 6;
73const NUM_DIRECTED_LIGHTS: usize = 1;
74const LIGHT_DIST_RADIUS: f32 = 64.0; // The distance beyond which lights may not emit light from their origin
75const SHADOW_DIST_RADIUS: f32 = 8.0;
76const SHADOW_MAX_DIST: f32 = 96.0; // The distance beyond which shadows may not be visible
77/// The minimum sin γ we will use before switching to uniform mapping.
78const EPSILON_UPSILON: f64 = -1.0;
79
80const SHADOW_NEAR: f32 = 0.25; // Near plane for shadow map point light rendering.
81const SHADOW_FAR: f32 = 128.0; // Far plane for shadow map point light rendering.
82
83/// Above this speed is considered running
84/// Used for first person camera effects
85const RUNNING_THRESHOLD: f32 = 0.7;
86
87/// The threashold for starting calculations with rain.
88const RAIN_THRESHOLD: f32 = 0.0;
89
90/// is_daylight, array of active lights.
91pub type LightData<'a> = (bool, &'a [Light]);
92
93struct EventLight {
94    light: Light,
95    timeout: f32,
96    fadeout: fn(f32) -> f32,
97}
98
99struct Skybox {
100    model: Model<SkyboxVertex>,
101}
102
103pub struct Scene {
104    data: GlobalModel,
105    globals_bind_group: GlobalsBindGroup,
106    camera: Camera,
107    camera_input_state: Vec2<f32>,
108    event_lights: Vec<EventLight>,
109
110    skybox: Skybox,
111    terrain: Terrain<TerrainChunk>,
112    pub debug: Debug,
113    pub lod: Lod,
114    loaded_distance: f32,
115    /// x coordinate is sea level (minimum height for any land chunk), and y
116    /// coordinate is the maximum height above the mnimimum for any land
117    /// chunk.
118    map_bounds: Vec2<f32>,
119    select_pos: Option<Vec3<i32>>,
120    light_data: Vec<Light>,
121
122    particle_mgr: ParticleMgr,
123    trail_mgr: TrailMgr,
124    figure_mgr: FigureMgr,
125    tether_mgr: TetherMgr,
126    pub sfx_mgr: SfxMgr,
127    pub music_mgr: MusicMgr,
128    ambience_mgr: AmbienceMgr,
129
130    integrated_rain_vel: f32,
131    pub wind_vel: Vec2<f32>,
132    pub interpolated_time_of_day: Option<f64>,
133    last_lightning: Option<(Vec3<f32>, f64)>,
134    local_time: f64,
135
136    pub screen_fade: f32,
137    pub screen_fade_tgt: f32,
138
139    pub debug_vectors_enabled: bool,
140}
141
142pub struct SceneData<'a> {
143    pub client: &'a Client,
144    pub state: &'a State,
145    pub viewpoint_entity: specs::Entity,
146    pub mutable_viewpoint: bool,
147    pub target_entities: &'a HashSet<specs::Entity>,
148    pub loaded_distance: f32,
149    pub terrain_view_distance: u32, // not used currently
150    pub entity_view_distance: u32,
151    pub tick: u64,
152    pub gamma: f32,
153    pub exposure: f32,
154    pub ambiance: f32,
155    pub mouse_smoothing: bool,
156    pub sprite_render_distance: f32,
157    pub particles_enabled: bool,
158    pub weapon_trails_enabled: bool,
159    pub flashing_lights_enabled: bool,
160    pub figure_lod_render_distance: f32,
161    pub is_aiming: bool,
162    pub interpolated_time_of_day: Option<f64>,
163    pub wind_vel: Vec2<f32>,
164}
165
166impl SceneData<'_> {
167    pub fn get_sun_dir(&self) -> Vec3<f32> {
168        TimeOfDay::new(self.interpolated_time_of_day.unwrap_or(0.0)).get_sun_dir()
169    }
170
171    pub fn get_moon_dir(&self) -> Vec3<f32> {
172        TimeOfDay::new(self.interpolated_time_of_day.unwrap_or(0.0)).get_moon_dir()
173    }
174}
175
176/// Approximate a scalar field of view angle using the parameterization from
177/// section 4.3 of Lloyd's thesis:
178///
179/// W_e = 2 n_e tan θ
180///
181/// where
182///
183/// W_e = 2 is the width of the image plane (for our projections, since they go
184/// from -1 to 1) n_e = near_plane is the near plane for the view frustum
185/// θ = (fov / 2) is the half-angle of the FOV (the one passed to
186/// Mat4::projection_rh_zo).
187///
188/// Although the widths for the x and y image planes are the same, they are
189/// different in this framework due to the introduction of an aspect ratio:
190///
191/// y'(p) = 1.0 / tan(fov / 2) * p.y / -p.z
192/// x'(p) = 1.0 / (aspect * tan(fov / 2)) * p.x / -p.z
193///
194/// i.e.
195///
196/// y'(x, y, -near, w) = 1 / tan(fov / 2) p.y / near
197/// x'(x, y, -near, w) = 1 / (aspect * tan(fov / 2)) p.x / near
198///
199/// W_e,y = 2 * near_plane * tan(fov / 2)
200/// W_e,x = 2 * near_plane * aspect * W_e,y
201///
202/// Θ_x = atan(W_e_y / 2 / near_plane) = atanfov / t()
203///
204/// i.e. we have an "effective" W_e_x of
205///
206/// 2 = 2 * near_plane * tan Θ
207///
208/// atan(1 / near_plane) = θ
209///
210/// y'
211/// x(-near)
212/// W_e = 2 * near_plane *
213///
214/// W_e_y / n_e = tan (fov / 2)
215/// W_e_x = 2 n
216fn compute_scalar_fov<F: Float>(_near_plane: F, fov: F, aspect: F) -> F {
217    let two = F::one() + F::one();
218    let theta_y = fov / two;
219    let theta_x = (aspect * theta_y.tan()).atan();
220    theta_x.min(theta_y)
221}
222
223/// Compute a near-optimal warping parameter that helps minimize error in a
224/// shadow map.
225///
226/// See section 5.2 of Brandon Lloyd's thesis:
227///
228/// [http://gamma.cs.unc.edu/papers/documents/dissertations/lloyd07.pdf](Logarithmic Perspective Shadow Maps).
229///
230/// η =
231///     0                                                         γ < γ_a
232///     -1 + (η_b + 1)(1 + cos(90 (γ - γ_a)/(γ_b - γ_a)))   γ_a ≤ γ < γ_b
233///     η_b + (η_c - η_b)  sin(90 (γ - γ_b)/(γ_c - γ_b))    γ_b ≤ γ < γ_c
234///     η_c                                                 γ_c ≤ γ
235///
236/// NOTE: Equation's described behavior is *wrong!*  I have pieced together a
237/// slightly different function that seems to more closely satisfy the author's
238/// intent:
239///
240/// η =
241///     -1                                                        γ < γ_a
242///     -1 + (η_b + 1)            (γ - γ_a)/(γ_b - γ_a)     γ_a ≤ γ < γ_b
243///     η_b + (η_c - η_b)  sin(90 (γ - γ_b)/(γ_c - γ_b))    γ_b ≤ γ < γ_c
244///     η_c                                                 γ_c ≤ γ
245///
246/// There are other alternatives that may have more desirable properties, such
247/// as:
248///
249/// η =
250///     -1                                                        γ < γ_a
251///     -1 + (η_b + 1)(1 - cos(90 (γ - γ_a)/(γ_b - γ_a)))   γ_a ≤ γ < γ_b
252///     η_b + (η_c - η_b)  sin(90 (γ - γ_b)/(γ_c - γ_b))    γ_b ≤ γ < γ_c
253///     η_c                                                 γ_c ≤ γ
254fn compute_warping_parameter<F: Float + FloatConst>(
255    gamma: F,
256    (gamma_a, gamma_b, gamma_c): (F, F, F),
257    (eta_b, eta_c): (F, F),
258) -> F {
259    if gamma < gamma_a {
260        -F::one()
261        /* F::zero() */
262    } else if gamma_a <= gamma && gamma < gamma_b {
263        /* -F::one() + (eta_b + F::one()) * (F::one() + (F::FRAC_PI_2() * (gamma - gamma_a) / (gamma_b - gamma_a)).cos()) */
264        -F::one() + (eta_b + F::one()) * (F::one() - (F::FRAC_PI_2() * (gamma - gamma_a) / (gamma_b - gamma_a)).cos())
265        // -F::one() + (eta_b + F::one()) * ((gamma - gamma_a) / (gamma_b - gamma_a))
266    } else if gamma_b <= gamma && gamma < gamma_c {
267        eta_b + (eta_c - eta_b) * (F::FRAC_PI_2() * (gamma - gamma_b) / (gamma_c - gamma_b)).sin()
268    } else {
269        eta_c
270    }
271    // NOTE: Just in case we go out of range due to floating point imprecision.
272    .max(-F::one()).min(F::one())
273}
274
275/// Compute a near-optimal warping parameter that falls off quickly enough
276/// when the warp angle goes past the minimum field of view angle, for
277/// perspective projections.
278///
279/// For F_p (perspective warping) and view fov angle θ,the parameters are:
280///
281/// γ_a = θ / 3
282/// γ_b = θ
283/// γ_c = θ + 0.3(90 - θ)
284///
285/// η_b = -0.2
286/// η_c = 0
287///
288/// See compute_warping_parameter.
289fn compute_warping_parameter_perspective<F: Float + FloatConst>(
290    gamma: F,
291    near_plane: F,
292    fov: F,
293    aspect: F,
294) -> F {
295    let theta = compute_scalar_fov(near_plane, fov, aspect);
296    let two = F::one() + F::one();
297    let three = two + F::one();
298    let ten = three + three + three + F::one();
299    compute_warping_parameter(
300        gamma,
301        (
302            theta / three,
303            theta,
304            theta + (three / ten) * (F::FRAC_PI_2() - theta),
305        ),
306        (-two / ten, F::zero()),
307    )
308}
309
310impl Scene {
311    /// Create a new `Scene` with default parameters.
312    pub fn new(
313        renderer: &mut Renderer,
314        lazy_init: &mut SpriteRenderContextLazy,
315        client: &Client,
316        settings: &Settings,
317    ) -> Self {
318        let resolution = renderer.resolution().map(|e| e as f32);
319        let sprite_render_context = lazy_init(renderer);
320
321        let data = GlobalModel {
322            globals: renderer.create_consts(&[Globals::default()]),
323            lights: renderer.create_consts(&[Light::default(); MAX_LIGHT_COUNT]),
324            shadows: renderer.create_consts(&[Shadow::default(); MAX_SHADOW_COUNT]),
325            shadow_mats: renderer.create_shadow_bound_locals(&[ShadowLocals::default()]),
326            rain_occlusion_mats: renderer
327                .create_rain_occlusion_bound_locals(&[RainOcclusionLocals::default()]),
328            point_light_matrices: Box::new(
329                [PointLightMatrix::default(); MAX_POINT_LIGHT_MATRICES_COUNT],
330            ),
331        };
332
333        let lod = Lod::new(renderer, client, settings);
334
335        let globals_bind_group = renderer.bind_globals(&data, lod.get_data());
336
337        let terrain = Terrain::new(renderer, &data, lod.get_data(), sprite_render_context);
338
339        let camera_mode = match client.presence() {
340            Some(comp::PresenceKind::Spectator) => CameraMode::Freefly,
341            _ => CameraMode::ThirdPerson,
342        };
343
344        let calendar = client.state().ecs().read_resource::<Calendar>();
345
346        Self {
347            data,
348            globals_bind_group,
349            camera: Camera::new(resolution.x / resolution.y, camera_mode),
350            camera_input_state: Vec2::zero(),
351            event_lights: Vec::new(),
352
353            skybox: Skybox {
354                model: renderer.create_model(&create_skybox_mesh()).unwrap(),
355            },
356            terrain,
357            debug: Debug::new(),
358            lod,
359            loaded_distance: 0.0,
360            map_bounds: Vec2::new(
361                client.world_data().min_chunk_alt(),
362                client.world_data().max_chunk_alt(),
363            ),
364            select_pos: None,
365            light_data: Vec::new(),
366            particle_mgr: ParticleMgr::new(renderer),
367            trail_mgr: TrailMgr::default(),
368            figure_mgr: FigureMgr::new(renderer),
369            tether_mgr: TetherMgr::new(renderer),
370            sfx_mgr: SfxMgr::default(),
371            music_mgr: MusicMgr::new(&calendar),
372            ambience_mgr: AmbienceMgr::new(ambience::load_ambience_items()),
373            integrated_rain_vel: 0.0,
374            wind_vel: Vec2::zero(),
375            interpolated_time_of_day: None,
376            last_lightning: None,
377            local_time: 0.0,
378            // Keep the screen entirely black for a while, to give the scene time to sort itself out
379            screen_fade: -0.5,
380            screen_fade_tgt: 1.0,
381            debug_vectors_enabled: false,
382        }
383    }
384
385    /// Get a reference to the scene's globals.
386    pub fn globals(&self) -> &Consts<Globals> { &self.data.globals }
387
388    /// Get a reference to the scene's camera.
389    pub fn camera(&self) -> &Camera { &self.camera }
390
391    /// Get a reference to the scene's terrain.
392    pub fn terrain(&self) -> &Terrain<TerrainChunk> { &self.terrain }
393
394    /// Get a reference to the scene's lights.
395    pub fn lights(&self) -> &Vec<Light> { &self.light_data }
396
397    /// Get a reference to the scene's particle manager.
398    pub fn particle_mgr(&self) -> &ParticleMgr { &self.particle_mgr }
399
400    /// Get a reference to the scene's trail manager.
401    pub fn trail_mgr(&self) -> &TrailMgr { &self.trail_mgr }
402
403    /// Get a reference to the scene's figure manager.
404    pub fn figure_mgr(&self) -> &FigureMgr { &self.figure_mgr }
405
406    pub fn music_mgr(&self) -> &MusicMgr { &self.music_mgr }
407
408    /// Get a mutable reference to the scene's camera.
409    pub fn camera_mut(&mut self) -> &mut Camera { &mut self.camera }
410
411    /// Set the block position that the player is interacting with
412    pub fn set_select_pos(&mut self, pos: Option<Vec3<i32>>) { self.select_pos = pos; }
413
414    pub fn select_pos(&self) -> Option<Vec3<i32>> { self.select_pos }
415
416    /// Handle an incoming user input event (e.g.: cursor moved, key pressed,
417    /// window closed).
418    ///
419    /// If the event is handled, return true.
420    pub fn handle_input_event(&mut self, event: Event, client: &Client) -> bool {
421        match event {
422            // When the window is resized, change the camera's aspect ratio
423            Event::Resize(dims) => {
424                self.camera.set_aspect_ratio(dims.x as f32 / dims.y as f32);
425                true
426            },
427            // Panning the cursor makes the camera rotate
428            Event::CursorPan(delta) => {
429                self.camera.rotate_by(Vec3::from(delta) * CURSOR_PAN_SCALE);
430                true
431            },
432            // Zoom the camera when a zoom event occurs
433            Event::Zoom(delta) => {
434                let cap = if client.is_moderator() {
435                    ZOOM_CAP_ADMIN
436                } else {
437                    ZOOM_CAP_PLAYER
438                };
439                // when zooming in the distance the camera travelles should be based on the
440                // final distance. This is to make sure the camera travelles the
441                // same distance when zooming in and out
442                let player_scale = client
443                    .state()
444                    .read_component_copied::<comp::Scale>(client.entity())
445                    .map_or(1.0, |s| s.0);
446                if delta < 0.0 {
447                    self.camera.zoom_switch(
448                        // Thank you Imbris for doing the math
449                        delta * (0.05 + self.camera.get_distance() * 0.01) / (1.0 - delta * 0.01),
450                        cap,
451                        player_scale,
452                    );
453                } else {
454                    self.camera.zoom_switch(
455                        delta * (0.05 + self.camera.get_distance() * 0.01),
456                        cap,
457                        player_scale,
458                    );
459                }
460                true
461            },
462            Event::AnalogGameInput(input) => match input {
463                AnalogGameInput::CameraX(d) => {
464                    self.camera_input_state.x = d;
465                    true
466                },
467                AnalogGameInput::CameraY(d) => {
468                    self.camera_input_state.y = d;
469                    true
470                },
471                _ => false,
472            },
473            // All other events are unhandled
474            _ => false,
475        }
476    }
477
478    pub fn handle_outcome(
479        &mut self,
480        outcome: &Outcome,
481        scene_data: &SceneData,
482        audio: &mut AudioFrontend,
483    ) {
484        span!(_guard, "handle_outcome", "Scene::handle_outcome");
485        self.particle_mgr
486            .handle_outcome(outcome, scene_data, &self.figure_mgr);
487        self.sfx_mgr
488            .handle_outcome(outcome, audio, scene_data.client);
489
490        match outcome {
491            Outcome::Lightning { pos } => {
492                self.last_lightning = Some((*pos, scene_data.state.get_time()));
493            },
494            Outcome::Explosion {
495                pos,
496                power,
497                is_attack,
498                reagent,
499                ..
500            } => self.event_lights.push(EventLight {
501                light: Light::new(
502                    *pos,
503                    match reagent {
504                        Some(Reagent::Blue) => Rgb::new(0.15, 0.4, 1.0),
505                        Some(Reagent::Green) => Rgb::new(0.0, 1.0, 0.0),
506                        Some(Reagent::Purple) => Rgb::new(0.7, 0.0, 1.0),
507                        Some(Reagent::Red) => {
508                            if *is_attack {
509                                Rgb::new(1.0, 0.5, 0.0)
510                            } else {
511                                Rgb::new(1.0, 0.0, 0.0)
512                            }
513                        },
514                        Some(Reagent::White) => Rgb::new(1.0, 1.0, 1.0),
515                        Some(Reagent::Yellow) => Rgb::new(1.0, 1.0, 0.0),
516                        Some(Reagent::FireRain) => Rgb::new(1.0, 0.8, 0.3),
517                        Some(Reagent::FireGigas) => Rgb::new(1.0, 0.6, 0.2),
518                        None => Rgb::new(1.0, 0.5, 0.0),
519                    },
520                    power
521                        * if *is_attack || reagent.is_none() {
522                            25.0
523                        } else {
524                            100.0
525                        },
526                ),
527                timeout: match reagent {
528                    Some(_) => 0.8,
529                    None => 0.25,
530                },
531                fadeout: |timeout| timeout * 2.0,
532            }),
533            Outcome::ProjectileShot { .. } => {},
534            _ => {},
535        }
536    }
537
538    /// Maintain data such as GPU constant buffers, models, etc. To be called
539    /// once per tick.
540    pub fn maintain(
541        &mut self,
542        renderer: &mut Renderer,
543        audio: &mut AudioFrontend,
544        scene_data: &SceneData,
545        client: &Client,
546        settings: &Settings,
547        mmap_face_north: bool,
548    ) {
549        span!(_guard, "maintain", "Scene::maintain");
550        // Get player position.
551        let ecs = scene_data.state.ecs();
552
553        let dt = ecs.fetch::<DeltaTime>().0;
554
555        self.local_time += dt as f64 * ecs.fetch::<TimeScale>().0;
556
557        let positions = ecs.read_storage::<comp::Pos>();
558
559        let viewpoint_ori = ecs
560            .read_storage::<comp::Ori>()
561            .get(scene_data.viewpoint_entity)
562            .map_or(Quaternion::identity(), |ori| ori.to_quat());
563
564        let viewpoint_look_ori = ecs
565            .read_storage::<comp::CharacterActivity>()
566            .get(scene_data.viewpoint_entity)
567            .and_then(|activity| activity.look_dir)
568            .map(|dir| {
569                let d = dir.to_vec();
570
571                let pitch = (-d.z).asin();
572                let yaw = d.x.atan2(d.y);
573
574                Vec3::new(yaw, pitch, 0.0)
575            })
576            .unwrap_or_else(|| {
577                let q = viewpoint_ori;
578                let sinr_cosp = 2.0 * (q.w * q.x + q.y * q.z);
579                let cosr_cosp = 1.0 - 2.0 * (q.x * q.x + q.y * q.y);
580                let pitch = sinr_cosp.atan2(cosr_cosp);
581
582                let siny_cosp = 2.0 * (q.w * q.z + q.x * q.y);
583                let cosy_cosp = 1.0 - 2.0 * (q.y * q.y + q.z * q.z);
584                let yaw = siny_cosp.atan2(cosy_cosp);
585
586                Vec3::new(-yaw, -pitch, 0.0)
587            });
588
589        let viewpoint_scale = ecs
590            .read_storage::<comp::Scale>()
591            .get(scene_data.viewpoint_entity)
592            .map_or(1.0, |scale| scale.0);
593
594        let (is_humanoid, viewpoint_height, viewpoint_eye_height) = ecs
595            .read_storage::<comp::Body>()
596            .get(scene_data.viewpoint_entity)
597            .map_or((false, 1.0, 0.0), |b| {
598                (
599                    matches!(b, comp::Body::Humanoid(_)),
600                    b.height() * viewpoint_scale,
601                    b.eye_height(1.0) * viewpoint_scale, // Scale is applied later
602                )
603            });
604        // When in first person, use the animated head position for the viewpoint
605        let viewpoint_eye_height = if matches!(self.camera.get_mode(), CameraMode::FirstPerson)
606            && let Some(char_state) = self
607                .figure_mgr
608                .states
609                .character_states
610                .get(&scene_data.viewpoint_entity)
611            && let Some(interpolated) = ecs
612                .read_storage::<Interpolated>()
613                .get(scene_data.viewpoint_entity)
614        {
615            // TODO: Don't hard-code this offset
616            char_state
617                .wpos_of(
618                    char_state
619                        .computed_skeleton
620                        .head
621                        .mul_point(Vec3::unit_z() * 0.6),
622                )
623                .z
624                - interpolated.pos.z
625        } else {
626            // When not in first-person, just use the game-provided eye height, combined
627            // with a per-state factor
628            match ecs
629                .read_storage::<CharacterState>()
630                .get(scene_data.viewpoint_entity)
631            {
632                Some(CharacterState::Crawl) => viewpoint_eye_height * 0.3,
633                Some(CharacterState::Sit) => viewpoint_eye_height * 0.7,
634                Some(c) if c.is_stealthy() => viewpoint_eye_height * 0.6,
635                _ => viewpoint_eye_height,
636            }
637        };
638
639        if scene_data.mutable_viewpoint || matches!(self.camera.get_mode(), CameraMode::Freefly) {
640            // Add the analog input to camera if it's a mutable viewpoint
641            self.camera.rotate_by(self.camera_input_state.with_z(0.0));
642        } else {
643            // Otherwise set the cameras rotation to the viewpoints
644            self.camera.set_orientation(viewpoint_look_ori);
645        }
646
647        let viewpoint_offset = if is_humanoid {
648            let is_running = ecs
649                .read_storage::<comp::Vel>()
650                .get(scene_data.viewpoint_entity)
651                .zip(
652                    ecs.read_storage::<comp::PhysicsState>()
653                        .get(scene_data.viewpoint_entity),
654                )
655                .map(|(v, ps)| {
656                    (v.0 - ps.ground_vel).magnitude_squared() > RUNNING_THRESHOLD.powi(2)
657                })
658                .unwrap_or(false);
659
660            let on_ground = ecs
661                .read_storage::<comp::PhysicsState>()
662                .get(scene_data.viewpoint_entity)
663                .map(|p| p.on_ground.is_some());
664
665            let holding_ranged = client
666                .inventories()
667                .get(scene_data.viewpoint_entity)
668                .and_then(|inv| inv.equipped(EquipSlot::ActiveMainhand))
669                .and_then(|item| item.tool_info())
670                .is_some_and(|tool_kind| {
671                    matches!(
672                        tool_kind,
673                        ToolKind::Bow | ToolKind::Staff | ToolKind::Sceptre | ToolKind::Throwable
674                    )
675                })
676                || client
677                    .current::<CharacterState>()
678                    .is_some_and(|char_state| matches!(char_state, CharacterState::Throw(_)));
679
680            let up = match self.camera.get_mode() {
681                CameraMode::FirstPerson => {
682                    if is_running && on_ground.unwrap_or(false) {
683                        viewpoint_eye_height
684                            + (scene_data.state.get_time() as f32 * 17.0).sin() * 0.05
685                    } else {
686                        viewpoint_eye_height
687                    }
688                },
689                CameraMode::ThirdPerson if scene_data.is_aiming && holding_ranged => {
690                    viewpoint_height * 1.05 + settings.gameplay.aim_offset_y
691                },
692                CameraMode::ThirdPerson if scene_data.is_aiming => viewpoint_height * 1.05,
693                CameraMode::ThirdPerson => viewpoint_eye_height,
694                CameraMode::Freefly => 0.0,
695            };
696
697            let right = match self.camera.get_mode() {
698                CameraMode::FirstPerson => 0.0,
699                CameraMode::ThirdPerson if scene_data.is_aiming && holding_ranged => {
700                    settings.gameplay.aim_offset_x
701                },
702                CameraMode::ThirdPerson => 0.0,
703                CameraMode::Freefly => 0.0,
704            };
705
706            // Alter camera position to match player.
707            let tilt = self.camera.get_orientation().y;
708            let dist = self.camera.get_distance();
709
710            Vec3::unit_z() * (up - tilt.min(0.0).sin() * dist * 0.6)
711                + self.camera.right() * (right * viewpoint_scale)
712        } else {
713            self.figure_mgr
714                .viewpoint_offset(scene_data, scene_data.viewpoint_entity)
715        };
716
717        let entity_pos = positions
718            .get(scene_data.viewpoint_entity)
719            .map_or(Vec3::zero(), |pos| pos.0);
720
721        let viewpoint_pos = match self.camera.get_mode() {
722            CameraMode::FirstPerson => {
723                // The camera is forced to focus on the interpolated x/y position but
724                // interpolates z. Effectively, x/y are controlled by entity
725                // interpolation, z is controlled by camera interpolation. Why? Because
726                // this produces visually smooth results in a larger variety of cases
727                let viewpoint_pos = ecs
728                    .read_storage::<Interpolated>()
729                    .get(scene_data.viewpoint_entity)
730                    .map_or(entity_pos, |i| i.pos.xy().with_z(entity_pos.z));
731                self.camera
732                    .force_xy_focus_pos(viewpoint_pos + viewpoint_offset);
733                viewpoint_pos
734            },
735            CameraMode::ThirdPerson => {
736                let viewpoint_pos = entity_pos;
737                if let Some(health) = ecs
738                    .read_storage::<comp::Health>()
739                    .get(scene_data.viewpoint_entity)
740                    && health.is_dead
741                {
742                    // When dead, fade the screen to black
743                    self.camera.reset_focus();
744                } else {
745                    self.screen_fade_tgt = 1.0;
746                    self.camera.set_focus_pos(viewpoint_pos + viewpoint_offset)
747                };
748                viewpoint_pos
749            },
750            CameraMode::Freefly => entity_pos,
751        };
752
753        // Tick camera for interpolation.
754        self.camera
755            .update(scene_data.state.get_time(), dt, scene_data.mouse_smoothing);
756
757        // Compute camera matrices.
758        self.camera.compute_dependents(&scene_data.state.terrain());
759        let camera::Dependents {
760            view_mat,
761            view_mat_inv,
762            proj_mat,
763            proj_mat_inv,
764            cam_pos,
765            ..
766        } = self.camera.dependents();
767
768        // Update chunk loaded distance smoothly for nice shader fog
769        let loaded_distance =
770            (0.98 * self.loaded_distance + 0.02 * scene_data.loaded_distance).max(0.01);
771
772        // Reset lights ready for the next tick
773        let lights = &mut self.light_data;
774        lights.clear();
775
776        // Maintain the particles.
777        self.particle_mgr.maintain(
778            renderer,
779            scene_data,
780            &self.terrain,
781            &self.figure_mgr,
782            lights,
783        );
784
785        // Maintain the trails.
786        self.trail_mgr.maintain(renderer, scene_data);
787
788        // Update light constants
789        let max_light_dist = loaded_distance.powi(2) + LIGHT_DIST_RADIUS;
790        lights.extend(
791            (
792                &scene_data.state.ecs().read_storage::<comp::Pos>(),
793                scene_data
794                    .state
795                    .ecs()
796                    .read_storage::<crate::ecs::comp::Interpolated>()
797                    .maybe(),
798                &scene_data
799                    .state
800                    .ecs()
801                    .read_storage::<comp::LightAnimation>(),
802                scene_data
803                    .state
804                    .ecs()
805                    .read_storage::<comp::Health>()
806                    .maybe(),
807            )
808                .join()
809                .filter(|(pos, _, light_anim, h)| {
810                    light_anim.col != Rgb::zero()
811                        && light_anim.strength > 0.0
812                        && pos.0.distance_squared(viewpoint_pos) < max_light_dist
813                        && h.is_none_or(|h| !h.is_dead)
814                })
815                .map(|(pos, interpolated, light_anim, _)| {
816                    // Use interpolated values if they are available
817                    let pos = interpolated.map_or(pos.0, |i| i.pos);
818                    let mut light =
819                        Light::new(pos + light_anim.offset, light_anim.col, light_anim.strength);
820                    if let Some((dir, fov)) = light_anim.dir {
821                        light = light.with_dir(dir, fov);
822                    }
823                    light
824                })
825                .chain(
826                    self.event_lights
827                        .iter()
828                        .map(|el| el.light.with_strength((el.fadeout)(el.timeout))),
829                ),
830        );
831        let voxel_colliders_manifest = VOXEL_COLLIDER_MANIFEST.read();
832        let figure_mgr = &self.figure_mgr;
833        lights.extend(
834            (
835                &scene_data.state.ecs().entities(),
836                &scene_data
837                    .state
838                    .read_storage::<crate::ecs::comp::Interpolated>(),
839                &scene_data.state.read_storage::<comp::Body>(),
840                &scene_data.state.read_storage::<comp::Collider>(),
841            )
842                .join()
843                .filter_map(|(entity, interpolated, body, collider)| {
844                    let vol = collider.get_vol(&voxel_colliders_manifest)?;
845                    let (blocks_of_interest, offset) =
846                        figure_mgr.get_blocks_of_interest(entity, body, Some(collider))?;
847
848                    let mat = Mat4::from(interpolated.ori.to_quat())
849                        .translated_3d(interpolated.pos)
850                        * Mat4::translation_3d(offset);
851
852                    let p = mat.inverted().mul_point(viewpoint_pos);
853                    let aabb = Aabb {
854                        min: Vec3::zero(),
855                        max: vol.volume().sz.as_(),
856                    };
857                    if aabb.contains_point(p) || aabb.distance_to_point(p) < max_light_dist {
858                        Some(
859                            blocks_of_interest
860                                .lights
861                                .iter()
862                                .map(move |(block_offset, level)| {
863                                    let wpos = mat.mul_point(block_offset.as_() + 0.5);
864                                    (wpos, level)
865                                })
866                                .filter(move |(wpos, _)| {
867                                    wpos.distance_squared(viewpoint_pos) < max_light_dist
868                                })
869                                .map(|(wpos, level)| {
870                                    Light::new(wpos, Rgb::white(), *level as f32 / 7.0)
871                                }),
872                        )
873                    } else {
874                        None
875                    }
876                })
877                .flatten(),
878        );
879        lights.sort_by_key(|light| light.get_pos().distance_squared(viewpoint_pos) as i32);
880        lights.truncate(MAX_LIGHT_COUNT);
881        renderer.update_consts(&mut self.data.lights, lights);
882
883        // Update event lights
884        self.event_lights.retain_mut(|el| {
885            el.timeout -= dt;
886            el.timeout > 0.0
887        });
888
889        // Update shadow constants
890        let mut shadows = (
891            &scene_data.state.ecs().read_storage::<comp::Pos>(),
892            scene_data
893                .state
894                .ecs()
895                .read_storage::<crate::ecs::comp::Interpolated>()
896                .maybe(),
897            scene_data.state.ecs().read_storage::<comp::Scale>().maybe(),
898            &scene_data.state.ecs().read_storage::<comp::Body>(),
899            &scene_data.state.ecs().read_storage::<comp::Health>(),
900        )
901            .join()
902            .filter(|(_, _, _, _, health)| !health.is_dead)
903            .filter(|(pos, _, _, _, _)| {
904                pos.0.distance_squared(viewpoint_pos)
905                    < (loaded_distance.min(SHADOW_MAX_DIST) + SHADOW_DIST_RADIUS).powi(2)
906            })
907            .map(|(pos, interpolated, scale, _, _)| {
908                Shadow::new(
909                    // Use interpolated values pos if it is available
910                    interpolated.map_or(pos.0, |i| i.pos),
911                    scale.map_or(1.0, |s| s.0),
912                )
913            })
914            .collect::<Vec<_>>();
915        shadows.sort_by_key(|shadow| shadow.get_pos().distance_squared(viewpoint_pos) as i32);
916        shadows.truncate(MAX_SHADOW_COUNT);
917        renderer.update_consts(&mut self.data.shadows, &shadows);
918
919        // Remember to put the new loaded distance back in the scene.
920        self.loaded_distance = loaded_distance;
921
922        // Update light projection matrices for the shadow map.
923
924        // When the target time of day and time of day have a large discrepancy
925        // (i.e two days), the linear interpolation causes brght flashing effects
926        // in the sky. This will snap the time of day to the target time of day
927        // for the client to avoid the flashing effect if flashing lights is
928        // disabled.
929        const DAY: f64 = 60.0 * 60.0 * 24.0;
930        let time_of_day = scene_data.state.get_time_of_day();
931        let max_lerp_period = if scene_data.flashing_lights_enabled {
932            DAY * 2.0
933        } else {
934            DAY * 0.25
935        };
936        self.interpolated_time_of_day =
937            Some(self.interpolated_time_of_day.map_or(time_of_day, |tod| {
938                if (tod - time_of_day).abs() > max_lerp_period {
939                    time_of_day
940                } else {
941                    Lerp::lerp(tod, time_of_day, dt as f64)
942                }
943            }));
944        let time_of_day = self.interpolated_time_of_day.unwrap_or(time_of_day);
945        let focus_pos = self.camera.get_focus_pos();
946        let focus_off = focus_pos.map(|e| e.trunc());
947
948        let step = 0.5 * dt;
949        self.screen_fade = if step > (self.screen_fade - self.screen_fade_tgt).abs() {
950            self.screen_fade_tgt
951        } else {
952            self.screen_fade + (self.screen_fade_tgt - self.screen_fade).signum() * step
953        };
954
955        let player_dir = client
956            .state()
957            .ecs()
958            .read_storage::<comp::Ori>()
959            .get(client.entity())
960            .copied()
961            .unwrap_or_default()
962            .look_dir()
963            .to_vec();
964
965        // atan2(x,y) instead of (y,x) so that north is 0
966        let player_mmap_ori = player_dir.x.atan2(player_dir.y)
967            - if !mmap_face_north {
968                // If the map follows the camera, subtract the camera's angle from player angle
969                self.camera.get_orientation().x
970            } else {
971                0.0
972            };
973
974        // Update global constants.
975        renderer.update_consts(&mut self.data.globals, &[Globals::new(
976            view_mat,
977            proj_mat,
978            cam_pos,
979            focus_pos,
980            self.loaded_distance,
981            self.lod.get_data().tgt_detail as f32,
982            self.map_bounds,
983            time_of_day,
984            scene_data.state.get_time(),
985            self.local_time,
986            renderer.resolution().as_(),
987            Vec2::new(SHADOW_NEAR, SHADOW_FAR),
988            lights.len(),
989            shadows.len(),
990            NUM_DIRECTED_LIGHTS,
991            scene_data
992                .state
993                .terrain()
994                .get((cam_pos + focus_off).map(|e| e.floor() as i32))
995                .ok()
996                // Don't block the camera's view in solid blocks if the player is a moderator
997                .filter(|b| !(b.is_filled() && client.is_moderator()))
998                .map(|b| b.kind())
999                .unwrap_or(BlockKind::Air),
1000            self.select_pos.map(|e| e - focus_off.map(|e| e as i32)),
1001            scene_data.gamma,
1002            scene_data.exposure,
1003            self.last_lightning.unwrap_or((Vec3::zero(), -1000.0)),
1004            self.wind_vel,
1005            scene_data.ambiance,
1006            self.camera.get_mode(),
1007            scene_data.sprite_render_distance - 20.0,
1008            player_mmap_ori,
1009            self.screen_fade,
1010        )]);
1011        renderer.update_clouds_locals(CloudsLocals::new(proj_mat_inv, view_mat_inv));
1012        renderer.update_postprocess_locals(PostProcessLocals::new(proj_mat_inv, view_mat_inv));
1013
1014        // Maintain LoD.
1015        self.lod.maintain(renderer, client, focus_pos, &self.camera);
1016
1017        // Maintain tethers.
1018        self.tether_mgr.maintain(renderer, client, focus_pos);
1019
1020        // Maintain debug shapes
1021        self.debug.maintain(renderer);
1022
1023        // Maintain the terrain.
1024        let (
1025            _visible_bounds,
1026            visible_light_volume,
1027            visible_psr_bounds,
1028            visible_occlusion_volume,
1029            visible_por_bounds,
1030        ) = self.terrain.maintain(
1031            renderer,
1032            scene_data,
1033            focus_pos,
1034            self.loaded_distance,
1035            &self.camera,
1036        );
1037
1038        // Maintain the figures.
1039        let _figure_bounds = self.figure_mgr.maintain(
1040            renderer,
1041            &mut self.trail_mgr,
1042            scene_data,
1043            visible_psr_bounds,
1044            visible_por_bounds,
1045            &self.camera,
1046            Some(&self.terrain),
1047        );
1048
1049        let fov = self.camera.get_effective_fov();
1050        let aspect_ratio = self.camera.get_aspect_ratio();
1051        let view_dir = ((focus_pos.map(f32::fract)) - cam_pos).normalized();
1052
1053        // We need to compute these offset matrices to transform world space coordinates
1054        // to the translated ones we use when multiplying by the light space
1055        // matrix; this helps avoid precision loss during the
1056        // multiplication.
1057        let look_at = cam_pos;
1058        let new_dir = view_dir;
1059        let new_dir = new_dir.normalized();
1060        let up: math::Vec3<f32> = math::Vec3::unit_y();
1061
1062        // Optimal warping for directed lights:
1063        //
1064        // n_opt = 1 / sin y (z_n + √(z_n + (f - n) sin y))
1065        //
1066        // where n is near plane, f is far plane, y is the tilt angle between view and
1067        // light direction, and n_opt is the optimal near plane.
1068        // We also want a way to transform and scale this matrix (* 0.5 + 0.5) in order
1069        // to transform it correctly into texture coordinates, as well as
1070        // OpenGL coordinates.  Note that the matrix for directional light
1071        // is *already* linear in the depth buffer.
1072        //
1073        // Also, observe that we flip the texture sampling matrix in order to account
1074        // for the fact that DirectX renders top-down.
1075        let texture_mat = Mat4::<f32>::scaling_3d::<Vec3<f32>>(Vec3::new(0.5, -0.5, 1.0))
1076            * Mat4::translation_3d(Vec3::new(1.0, -1.0, 0.0));
1077
1078        let directed_mats = |d_view_mat: math::Mat4<f32>,
1079                             d_dir: math::Vec3<f32>,
1080                             volume: &Vec<math::Vec3<f32>>|
1081         -> (Mat4<f32>, Mat4<f32>) {
1082            // NOTE: Light view space, right-handed.
1083            let v_p_orig = math::Vec3::from(d_view_mat * math::Vec4::from_direction(new_dir));
1084            let mut v_p = v_p_orig.normalized();
1085            let cos_gamma = new_dir.map(f64::from).dot(d_dir.map(f64::from));
1086            let sin_gamma = (1.0 - cos_gamma * cos_gamma).sqrt();
1087            let gamma = sin_gamma.asin();
1088            let view_mat = math::Mat4::from_col_array(view_mat.into_col_array());
1089            // coordinates are transformed from world space (right-handed) to view space
1090            // (right-handed).
1091            let bounds1 = math::fit_psr(
1092                view_mat.map_cols(math::Vec4::from),
1093                volume.iter().copied(),
1094                math::Vec4::homogenized,
1095            );
1096            let n_e = f64::from(-bounds1.max.z);
1097            let factor = compute_warping_parameter_perspective(
1098                gamma,
1099                n_e,
1100                f64::from(fov),
1101                f64::from(aspect_ratio),
1102            );
1103
1104            v_p.z = 0.0;
1105            v_p.normalize();
1106            let l_r: math::Mat4<f32> = if factor > EPSILON_UPSILON {
1107                // NOTE: Our coordinates are now in left-handed space, but v_p isn't; however,
1108                // v_p has no z component, so we don't have to adjust it for left-handed
1109                // spaces.
1110                math::Mat4::look_at_lh(math::Vec3::zero(), math::Vec3::unit_z(), v_p)
1111            } else {
1112                math::Mat4::identity()
1113            };
1114            // Convert from right-handed to left-handed coordinates.
1115            let directed_proj_mat = math::Mat4::new(
1116                1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
1117            );
1118
1119            let light_all_mat = l_r * directed_proj_mat * d_view_mat;
1120            // coordinates are transformed from world space (right-handed) to rotated light
1121            // space (left-handed).
1122            let bounds0 = math::fit_psr(
1123                light_all_mat,
1124                volume.iter().copied(),
1125                math::Vec4::homogenized,
1126            );
1127            // Vague idea: project z_n from the camera view to the light view (where it's
1128            // tilted by γ).
1129            //
1130            // NOTE: To transform a normal by M, we multiply by the transpose of the inverse
1131            // of M. For the cases below, we are transforming by an
1132            // already-inverted matrix, so the transpose of its inverse is
1133            // just the transpose of the original matrix.
1134            let (z_0, z_1) = {
1135                let f_e = f64::from(-bounds1.min.z).max(n_e);
1136                // view space, right-handed coordinates.
1137                let p_z = bounds1.max.z;
1138                // rotated light space, left-handed coordinates.
1139                let p_y = bounds0.min.y;
1140                let p_x = bounds0.center().x;
1141                // moves from view-space (right-handed) to world space (right-handed)
1142                let view_inv = view_mat.inverted();
1143                // moves from rotated light space (left-handed) to world space (right-handed).
1144                let light_all_inv = light_all_mat.inverted();
1145
1146                // moves from view-space (right-handed) to world-space (right-handed).
1147                let view_point = view_inv
1148                    * math::Vec4::from_point(
1149                        -math::Vec3::unit_z() * p_z, /* + math::Vec4::unit_w() */
1150                    );
1151                let view_plane = view_mat.transposed() * -math::Vec4::unit_z();
1152
1153                // moves from rotated light space (left-handed) to world space (right-handed).
1154                let light_point = light_all_inv
1155                    * math::Vec4::from_point(
1156                        math::Vec3::unit_y() * p_y, /* + math::Vec4::unit_w() */
1157                    );
1158                let light_plane = light_all_mat.transposed() * math::Vec4::unit_y();
1159
1160                // moves from rotated light space (left-handed) to world space (right-handed).
1161                let shadow_point = light_all_inv
1162                    * math::Vec4::from_point(
1163                        math::Vec3::unit_x() * p_x, /* + math::Vec4::unit_w() */
1164                    );
1165                let shadow_plane = light_all_mat.transposed() * math::Vec4::unit_x();
1166
1167                // Find the point at the intersection of the three planes; note that since the
1168                // equations are already in right-handed world space, we don't need to negate
1169                // the z coordinates.
1170                let solve_p0 = math::Mat4::new(
1171                    view_plane.x,
1172                    view_plane.y,
1173                    view_plane.z,
1174                    0.0,
1175                    light_plane.x,
1176                    light_plane.y,
1177                    light_plane.z,
1178                    0.0,
1179                    shadow_plane.x,
1180                    shadow_plane.y,
1181                    shadow_plane.z,
1182                    0.0,
1183                    0.0,
1184                    0.0,
1185                    0.0,
1186                    1.0,
1187                );
1188
1189                // in world-space (right-handed).
1190                let plane_dist = math::Vec4::new(
1191                    view_plane.dot(view_point),
1192                    light_plane.dot(light_point),
1193                    shadow_plane.dot(shadow_point),
1194                    1.0,
1195                );
1196                let p0_world = solve_p0.inverted() * plane_dist;
1197                // in rotated light-space (left-handed).
1198                let p0 = light_all_mat * p0_world;
1199                let mut p1 = p0;
1200                // in rotated light-space (left-handed).
1201                p1.y = bounds0.max.y;
1202
1203                // transforms from rotated light-space (left-handed) to view space
1204                // (right-handed).
1205                let view_from_light_mat = view_mat * light_all_inv;
1206                // z0 and z1 are in view space (right-handed).
1207                let z0 = view_from_light_mat * p0;
1208                let z1 = view_from_light_mat * p1;
1209
1210                // Extract the homogenized forward component (right-handed).
1211                //
1212                // NOTE: I don't think the w component should be anything but 1 here, but
1213                // better safe than sorry.
1214                (
1215                    f64::from(z0.homogenized().dot(-math::Vec4::unit_z())).clamp(n_e, f_e),
1216                    f64::from(z1.homogenized().dot(-math::Vec4::unit_z())).clamp(n_e, f_e),
1217                )
1218            };
1219
1220            // all of this is in rotated light-space (left-handed).
1221            let mut light_focus_pos: math::Vec3<f32> = math::Vec3::zero();
1222            light_focus_pos.x = bounds0.center().x;
1223            light_focus_pos.y = bounds0.min.y;
1224            light_focus_pos.z = bounds0.center().z;
1225
1226            let d = f64::from(bounds0.max.y - bounds0.min.y).abs();
1227
1228            let w_l_y = d;
1229
1230            // NOTE: See section 5.1.2.2 of Lloyd's thesis.
1231            // NOTE: Since z_1 and z_0 are in the same coordinate space, we don't have to
1232            // worry about the handedness of their ratio.
1233            let alpha = z_1 / z_0;
1234            let alpha_sqrt = alpha.sqrt();
1235            let directed_near_normal = if factor < 0.0 {
1236                // Standard shadow map to LiSPSM
1237                (1.0 + alpha_sqrt - factor * (alpha - 1.0)) / ((alpha - 1.0) * (factor + 1.0))
1238            } else {
1239                // LiSPSM to PSM
1240                ((alpha_sqrt - 1.0) * (factor * alpha_sqrt + 1.0)).recip()
1241            };
1242
1243            // Equation 5.14 - 5.16
1244            let y_ = |v: f64| w_l_y * (v + directed_near_normal).abs();
1245            let directed_near = y_(0.0) as f32;
1246            let directed_far = y_(1.0) as f32;
1247            light_focus_pos.y = if factor > EPSILON_UPSILON {
1248                light_focus_pos.y - directed_near
1249            } else {
1250                light_focus_pos.y
1251            };
1252            // Left-handed translation.
1253            let w_v: math::Mat4<f32> = math::Mat4::translation_3d(-math::Vec3::new(
1254                light_focus_pos.x,
1255                light_focus_pos.y,
1256                light_focus_pos.z,
1257            ));
1258            let shadow_view_mat: math::Mat4<f32> = w_v * light_all_mat;
1259            let w_p: math::Mat4<f32> = {
1260                if factor > EPSILON_UPSILON {
1261                    // Projection for y
1262                    let near = directed_near;
1263                    let far = directed_far;
1264                    let left = -1.0;
1265                    let right = 1.0;
1266                    let bottom = -1.0;
1267                    let top = 1.0;
1268                    let s_x = 2.0 * near / (right - left);
1269                    let o_x = (right + left) / (right - left);
1270                    let s_z = 2.0 * near / (top - bottom);
1271                    let o_z = (top + bottom) / (top - bottom);
1272
1273                    let s_y = (far + near) / (far - near);
1274                    let o_y = -2.0 * far * near / (far - near);
1275
1276                    math::Mat4::new(
1277                        s_x, o_x, 0.0, 0.0, 0.0, s_y, 0.0, o_y, 0.0, o_z, s_z, 0.0, 0.0, 1.0, 0.0,
1278                        0.0,
1279                    )
1280                } else {
1281                    math::Mat4::identity()
1282                }
1283            };
1284
1285            let shadow_all_mat: math::Mat4<f32> = w_p * shadow_view_mat;
1286            // coordinates are transformed from world space (right-handed)
1287            // to post-warp light space (left-handed), then homogenized.
1288            let math::Aabb::<f32> {
1289                min:
1290                    math::Vec3 {
1291                        x: xmin,
1292                        y: ymin,
1293                        z: zmin,
1294                    },
1295                max:
1296                    math::Vec3 {
1297                        x: xmax,
1298                        y: ymax,
1299                        z: zmax,
1300                    },
1301            } = math::fit_psr(
1302                shadow_all_mat,
1303                volume.iter().copied(),
1304                math::Vec4::homogenized,
1305            );
1306            let s_x = 2.0 / (xmax - xmin);
1307            let s_y = 2.0 / (ymax - ymin);
1308            let s_z = 1.0 / (zmax - zmin);
1309            let o_x = -(xmax + xmin) / (xmax - xmin);
1310            let o_y = -(ymax + ymin) / (ymax - ymin);
1311            let o_z = -zmin / (zmax - zmin);
1312            let directed_proj_mat = Mat4::new(
1313                s_x, 0.0, 0.0, o_x, 0.0, s_y, 0.0, o_y, 0.0, 0.0, s_z, o_z, 0.0, 0.0, 0.0, 1.0,
1314            );
1315
1316            let shadow_all_mat: Mat4<f32> = Mat4::from_col_arrays(shadow_all_mat.into_col_arrays());
1317
1318            let directed_texture_proj_mat = texture_mat * directed_proj_mat;
1319            (
1320                directed_proj_mat * shadow_all_mat,
1321                directed_texture_proj_mat * shadow_all_mat,
1322            )
1323        };
1324
1325        let weather = client
1326            .state()
1327            .max_weather_near(focus_off.xy() + cam_pos.xy());
1328        self.wind_vel = weather.wind_vel();
1329        if weather.rain > RAIN_THRESHOLD {
1330            let weather = client.weather_at_player();
1331            let rain_vel = weather.rain_vel();
1332            let rain_view_mat = math::Mat4::look_at_rh(look_at, look_at + rain_vel, up);
1333
1334            self.integrated_rain_vel += rain_vel.magnitude() * dt;
1335            let rain_dir_mat = Mat4::rotation_from_to_3d(-Vec3::unit_z(), rain_vel);
1336
1337            let (shadow_mat, texture_mat) =
1338                directed_mats(rain_view_mat, rain_vel, &visible_occlusion_volume);
1339
1340            let rain_occlusion_locals = RainOcclusionLocals::new(
1341                shadow_mat,
1342                texture_mat,
1343                rain_dir_mat,
1344                weather.rain,
1345                self.integrated_rain_vel,
1346            );
1347
1348            renderer.update_consts(&mut self.data.rain_occlusion_mats, &[rain_occlusion_locals]);
1349        } else if self.integrated_rain_vel > 0.0 {
1350            self.integrated_rain_vel = 0.0;
1351            // Need to set rain to zero
1352            let rain_occlusion_locals = RainOcclusionLocals::default();
1353            renderer.update_consts(&mut self.data.rain_occlusion_mats, &[rain_occlusion_locals]);
1354        }
1355
1356        let sun_dir = scene_data.get_sun_dir();
1357        let is_daylight = sun_dir.z < 0.0;
1358        if renderer.pipeline_modes().shadow.is_map() && (is_daylight || !lights.is_empty()) {
1359            let (point_shadow_res, _directed_shadow_res) = renderer.get_shadow_resolution();
1360            // NOTE: The aspect ratio is currently always 1 for our cube maps, since they
1361            // are equal on all sides.
1362            let point_shadow_aspect = point_shadow_res.x as f32 / point_shadow_res.y as f32;
1363            // Construct matrices to transform from world space to light space for the sun
1364            // and moon.
1365            let directed_light_dir = sun_dir;
1366
1367            // We upload view matrices as well, to assist in linearizing vertex positions.
1368            // (only for directional lights, so far).
1369            let mut directed_shadow_mats = Vec::with_capacity(6);
1370
1371            let light_view_mat = math::Mat4::look_at_rh(look_at, look_at + directed_light_dir, up);
1372            let (shadow_mat, texture_mat) =
1373                directed_mats(light_view_mat, directed_light_dir, &visible_light_volume);
1374
1375            let shadow_locals = ShadowLocals::new(shadow_mat, texture_mat);
1376
1377            renderer.update_consts(&mut self.data.shadow_mats, &[shadow_locals]);
1378
1379            directed_shadow_mats.push(light_view_mat);
1380            // This leaves us with five dummy slots, which we push as defaults.
1381            directed_shadow_mats
1382                .extend_from_slice(&[math::Mat4::default(); 6 - NUM_DIRECTED_LIGHTS] as _);
1383            // Now, construct the full projection matrices in the first two directed light
1384            // slots.
1385            let mut shadow_mats = Vec::with_capacity(6 * (lights.len() + 1));
1386            shadow_mats.resize_with(6, PointLightMatrix::default);
1387            // Now, we tackle point lights.
1388            // First, create a perspective projection matrix at 90 degrees (to cover a whole
1389            // face of the cube map we're using); we use a negative near plane to exactly
1390            // match OpenGL's behavior if we use a left-handed coordinate system everywhere
1391            // else.
1392            let shadow_proj = camera::perspective_rh_zo_general(
1393                90.0f32.to_radians(),
1394                point_shadow_aspect,
1395                1.0 / SHADOW_NEAR,
1396                1.0 / SHADOW_FAR,
1397            );
1398            // NOTE: We negate here to emulate a right-handed projection with a negative
1399            // near plane, which produces the correct transformation to exactly match
1400            // OpenGL's rendering behavior if we use a left-handed coordinate
1401            // system everywhere else.
1402            let shadow_proj = shadow_proj * Mat4::scaling_3d(-1.0);
1403
1404            // Next, construct the 6 orientations we'll use for the six faces, in terms of
1405            // their (forward, up) vectors.
1406            let orientations = [
1407                (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, -1.0, 0.0)),
1408                (Vec3::new(-1.0, 0.0, 0.0), Vec3::new(0.0, -1.0, 0.0)),
1409                (Vec3::new(0.0, 1.0, 0.0), Vec3::new(0.0, 0.0, 1.0)),
1410                (Vec3::new(0.0, -1.0, 0.0), Vec3::new(0.0, 0.0, -1.0)),
1411                (Vec3::new(0.0, 0.0, 1.0), Vec3::new(0.0, -1.0, 0.0)),
1412                (Vec3::new(0.0, 0.0, -1.0), Vec3::new(0.0, -1.0, 0.0)),
1413            ];
1414
1415            // NOTE: We could create the shadow map collection at the same time as the
1416            // lights, but then we'd have to sort them both, which wastes time.  Plus, we
1417            // want to prepend our directed lights.
1418            shadow_mats.extend(lights.iter().flat_map(|light| {
1419                // Now, construct the full projection matrix by making the light look at each
1420                // cube face.
1421                let eye = Vec3::new(light.pos[0], light.pos[1], light.pos[2]) - focus_off;
1422                orientations.iter().map(move |&(forward, up)| {
1423                    // NOTE: We don't currently try to linearize point lights or need a separate
1424                    // transform for them.
1425                    PointLightMatrix::new(shadow_proj * Mat4::look_at_lh(eye, eye + forward, up))
1426                })
1427            }));
1428
1429            for (i, val) in shadow_mats.into_iter().enumerate() {
1430                self.data.point_light_matrices[i] = val
1431            }
1432        }
1433
1434        // Remove unused figures.
1435        self.figure_mgr.clean(scene_data.tick);
1436
1437        // Maintain audio
1438        self.sfx_mgr.maintain(
1439            audio,
1440            scene_data.state,
1441            scene_data.viewpoint_entity,
1442            &self.camera,
1443            &self.terrain,
1444            client,
1445            &self.figure_mgr,
1446        );
1447
1448        self.ambience_mgr.maintain(
1449            audio,
1450            &settings.audio,
1451            scene_data.state,
1452            client,
1453            &self.camera,
1454            &self.terrain,
1455        );
1456
1457        self.music_mgr.maintain(audio, scene_data.state, client);
1458    }
1459
1460    pub fn global_bind_group(&self) -> &GlobalsBindGroup { &self.globals_bind_group }
1461
1462    /// Render the scene using the provided `Drawer`.
1463    pub fn render(
1464        &self,
1465        drawer: &mut Drawer<'_>,
1466        state: &State,
1467        viewpoint_entity: EcsEntity,
1468        tick: u64,
1469        scene_data: &SceneData,
1470    ) {
1471        span!(_guard, "render", "Scene::render");
1472        let sun_dir = scene_data.get_sun_dir();
1473        let is_daylight = sun_dir.z < 0.0;
1474        let focus_pos = self.camera.get_focus_pos();
1475        let cam_pos = self.camera.dependents().cam_pos + focus_pos.map(|e| e.trunc());
1476        let is_rain = state.max_weather_near(cam_pos.xy()).rain > RAIN_THRESHOLD;
1477        let culling_mode = if scene_data
1478            .state
1479            .terrain()
1480            .get_key(scene_data.state.terrain().pos_key(cam_pos.as_()))
1481            .is_some_and(|c| cam_pos.z < c.meta().alt() - terrain::UNDERGROUND_ALT)
1482        {
1483            CullingMode::Underground
1484        } else {
1485            CullingMode::Surface
1486        };
1487
1488        let camera_data = (&self.camera, scene_data.figure_lod_render_distance);
1489
1490        // would instead have this as an extension.
1491        if drawer.pipeline_modes().shadow.is_map() && (is_daylight || !self.light_data.is_empty()) {
1492            if is_daylight {
1493                prof_span!("directed shadows");
1494                if let Some(mut shadow_pass) = drawer.shadow_pass() {
1495                    // Render terrain directed shadows.
1496                    self.terrain.render_shadows(
1497                        &mut shadow_pass.draw_terrain_shadows(),
1498                        focus_pos,
1499                        culling_mode,
1500                    );
1501
1502                    // Render figure directed shadows.
1503                    self.figure_mgr.render_shadows(
1504                        &mut shadow_pass.draw_figure_shadows(),
1505                        state,
1506                        tick,
1507                        camera_data,
1508                    );
1509                    self.debug
1510                        .render_shadows(&mut shadow_pass.draw_debug_shadows());
1511                }
1512            }
1513
1514            // Render terrain point light shadows.
1515            {
1516                prof_span!("point shadows");
1517                drawer.draw_point_shadows(
1518                    &self.data.point_light_matrices,
1519                    self.terrain.chunks_for_point_shadows(focus_pos),
1520                )
1521            }
1522        }
1523        // Render rain occlusion texture
1524        if is_rain {
1525            prof_span!("rain occlusion");
1526            if let Some(mut occlusion_pass) = drawer.rain_occlusion_pass() {
1527                self.terrain
1528                    .render_rain_occlusion(&mut occlusion_pass.draw_terrain_shadows(), cam_pos);
1529
1530                self.figure_mgr.render_rain_occlusion(
1531                    &mut occlusion_pass.draw_figure_shadows(),
1532                    state,
1533                    tick,
1534                    camera_data,
1535                );
1536            }
1537        }
1538
1539        prof_span!(guard, "main pass");
1540        if let Some(mut first_pass) = drawer.first_pass() {
1541            self.figure_mgr.render_viewpoint(
1542                &mut first_pass.draw_figures(),
1543                state,
1544                viewpoint_entity,
1545                tick,
1546                camera_data,
1547            );
1548
1549            self.terrain
1550                .render(&mut first_pass, focus_pos, culling_mode);
1551
1552            self.figure_mgr.render(
1553                &mut first_pass.draw_figures(),
1554                state,
1555                viewpoint_entity,
1556                tick,
1557                camera_data,
1558            );
1559
1560            self.lod.render(&mut first_pass, culling_mode);
1561
1562            // Render the skybox.
1563            first_pass.draw_skybox(&self.skybox.model);
1564
1565            // Draws sprites
1566            let mut sprite_drawer = first_pass.draw_sprites(
1567                &self.terrain.sprite_globals,
1568                &self.terrain.sprite_render_state.sprite_atlas_textures,
1569            );
1570            self.figure_mgr.render_sprites(
1571                &mut sprite_drawer,
1572                state,
1573                cam_pos,
1574                scene_data.sprite_render_distance,
1575            );
1576            self.terrain.render_sprites(
1577                &mut sprite_drawer,
1578                focus_pos,
1579                cam_pos,
1580                scene_data.sprite_render_distance,
1581                culling_mode,
1582            );
1583            drop(sprite_drawer);
1584
1585            // Render tethers.
1586            self.tether_mgr.render(&mut first_pass);
1587
1588            // Render particle effects.
1589            self.particle_mgr
1590                .render(&mut first_pass.draw_particles(), scene_data);
1591
1592            // Draws translucent
1593            self.terrain.render_translucent(&mut first_pass, focus_pos);
1594
1595            // Render debug shapes
1596            self.debug.render(&mut first_pass.draw_debug());
1597        }
1598        drop(guard);
1599    }
1600
1601    pub fn maintain_debug_hitboxes(
1602        &mut self,
1603        client: &Client,
1604        settings: &Settings,
1605        hitboxes: &mut HashMap<specs::Entity, DebugShapeId>,
1606        tracks: &mut HashMap<Vec2<i32>, Vec<DebugShapeId>>,
1607        gizmos: &mut Vec<(DebugShapeId, common::resources::Time, bool)>,
1608    ) {
1609        let ecs = client.state().ecs();
1610        {
1611            let mut current_chunks = hashbrown::HashSet::new();
1612            let terrain_grid = ecs.read_resource::<TerrainGrid>();
1613            for (key, chunk) in terrain_grid.iter() {
1614                current_chunks.insert(key);
1615                tracks.entry(key).or_insert_with(|| {
1616                    let mut ret = Vec::new();
1617                    for bezier in chunk.meta().tracks().iter() {
1618                        let shape_id = self.debug.add_shape(DebugShape::TrainTrack {
1619                            path: *bezier,
1620                            rail_width: 0.35,
1621                            rail_sep: 2.5,
1622                            plank_width: 0.75,
1623                            plank_height: 0.25,
1624                            plank_sep: 6.0,
1625                        });
1626                        ret.push(shape_id);
1627                        self.debug
1628                            .set_context(shape_id, [0.0; 4], [1.0; 4], [0.0, 0.0, 0.0, 1.0]);
1629                    }
1630                    for point in chunk.meta().debug_points().iter() {
1631                        let shape_id = self.debug.add_shape(DebugShape::Cylinder {
1632                            radius: 0.1,
1633                            height: 0.1,
1634                        });
1635                        ret.push(shape_id);
1636                        self.debug.set_context(
1637                            shape_id,
1638                            point.with_w(0.0).into_array(),
1639                            [1.0; 4],
1640                            [0.0, 0.0, 0.0, 1.0],
1641                        );
1642                    }
1643                    for line in chunk.meta().debug_lines().iter() {
1644                        let shape_id = self
1645                            .debug
1646                            .add_shape(DebugShape::Line([line.start, line.end], 0.1));
1647                        ret.push(shape_id);
1648                        self.debug
1649                            .set_context(shape_id, [0.0; 4], [1.0; 4], [0.0, 0.0, 0.0, 1.0]);
1650                    }
1651                    ret
1652                });
1653            }
1654            tracks.retain(|k, v| {
1655                let keep = current_chunks.contains(k);
1656                if !keep {
1657                    for shape in v.iter() {
1658                        self.debug.remove_shape(*shape);
1659                    }
1660                }
1661                keep
1662            });
1663        }
1664        let mut current_entities = hashbrown::HashSet::new();
1665        if settings.interface.toggle_hitboxes {
1666            let positions = ecs.read_component::<comp::Pos>();
1667            let colliders = ecs.read_component::<comp::Collider>();
1668            let orientations = ecs.read_component::<comp::Ori>();
1669            let scales = ecs.read_component::<comp::Scale>();
1670            let groups = ecs.read_component::<comp::Group>();
1671            let bodies = ecs.read_component::<comp::Body>();
1672            for (entity, pos, collider, ori, body, scale, group) in (
1673                &ecs.entities(),
1674                &positions,
1675                &colliders,
1676                &orientations,
1677                &bodies,
1678                scales.maybe(),
1679                groups.maybe(),
1680            )
1681                .join()
1682            {
1683                match collider {
1684                    comp::Collider::CapsulePrism(CapsulePrism {
1685                        p0,
1686                        p1,
1687                        radius,
1688                        z_min,
1689                        z_max,
1690                    }) => {
1691                        let scale = scale.map_or(1.0, |s| s.0);
1692                        current_entities.insert(entity);
1693
1694                        let shape = DebugShape::CapsulePrism {
1695                            p0: *p0 * scale,
1696                            p1: *p1 * scale,
1697                            radius: *radius * scale,
1698                            head_ratio: body.top_ratio(),
1699                            height: (*z_max - *z_min) * scale,
1700                        };
1701
1702                        // If this shape no longer matches, remove the old one
1703                        if let Some(shape_id) = hitboxes.get(&entity)
1704                            && self.debug.get_shape(*shape_id).is_some_and(|s| s != &shape)
1705                        {
1706                            self.debug.remove_shape(*shape_id);
1707                            hitboxes.remove(&entity);
1708                        }
1709
1710                        let shape_id = hitboxes
1711                            .entry(entity)
1712                            .or_insert_with(|| self.debug.add_shape(shape));
1713                        let hb_pos = [pos.0.x, pos.0.y, pos.0.z + *z_min * scale, 0.0];
1714                        let color = if group == Some(&comp::group::ENEMY) {
1715                            [1.0, 0.0, 0.0, 0.5]
1716                        } else if group == Some(&comp::group::NPC) {
1717                            [0.0, 0.0, 1.0, 0.5]
1718                        } else {
1719                            [0.0, 1.0, 0.0, 0.5]
1720                        };
1721                        //let color = [1.0, 1.0, 1.0, 1.0];
1722                        let ori = ori.to_quat();
1723                        let hb_ori = [ori.x, ori.y, ori.z, ori.w];
1724                        self.debug.set_context(*shape_id, hb_pos, color, hb_ori);
1725                    },
1726                    comp::Collider::Voxel { .. }
1727                    | comp::Collider::Volume(_)
1728                    | comp::Collider::Point => {
1729                        // ignore terrain-like or point-hitboxes
1730                    },
1731                }
1732            }
1733        }
1734        hitboxes.retain(|k, v| {
1735            let keep = current_entities.contains(k);
1736            if !keep {
1737                self.debug.remove_shape(*v);
1738            }
1739            keep
1740        });
1741
1742        let time = client.state().get_time();
1743        gizmos.retain(|(id, end_time, _)| {
1744            let keep = end_time.0 > time;
1745            if !keep {
1746                self.debug.remove_shape(*id);
1747            }
1748            keep
1749        });
1750    }
1751
1752    pub fn maintain_debug_vectors(&mut self, client: &Client, lines: &mut PlayerDebugLines) {
1753        lines
1754            .chunk_normal
1755            .take()
1756            .map(|id| self.debug.remove_shape(id));
1757        lines.fluid_vel.take().map(|id| self.debug.remove_shape(id));
1758        lines.wind.take().map(|id| self.debug.remove_shape(id));
1759        lines.vel.take().map(|id| self.debug.remove_shape(id));
1760        if self.debug_vectors_enabled {
1761            let ecs = client.state().ecs();
1762
1763            let vels = &ecs.read_component::<comp::Vel>();
1764            let Some(vel) = vels.get(client.entity()) else {
1765                return;
1766            };
1767
1768            let phys_states = &ecs.read_component::<comp::PhysicsState>();
1769            let Some(phys) = phys_states.get(client.entity()) else {
1770                return;
1771            };
1772
1773            let positions = &ecs.read_component::<comp::Pos>();
1774            let Some(pos) = positions.get(client.entity()) else {
1775                return;
1776            };
1777
1778            let weather = ecs.read_resource::<WeatherGrid>();
1779            // take id and remove to delete the previous lines.
1780
1781            const LINE_WIDTH: f32 = 0.05;
1782            // Fluid Velocity
1783            {
1784                let Some(fluid) = phys.in_fluid else {
1785                    return;
1786                };
1787                let shape = DebugShape::Line([pos.0, pos.0 + fluid.flow_vel().0 / 2.], LINE_WIDTH);
1788                let id = self.debug.add_shape(shape);
1789                lines.fluid_vel = Some(id);
1790                self.debug
1791                    .set_context(id, [0.0; 4], [0.18, 0.72, 0.87, 0.8], [0.0, 0.0, 0.0, 1.0]);
1792            }
1793            // Chunk Terrain Normal Vector
1794            {
1795                let Some(chunk) = client.current_chunk() else {
1796                    return;
1797                };
1798                let shape = DebugShape::Line(
1799                    [
1800                        pos.0,
1801                        pos.0
1802                            + chunk
1803                                .meta()
1804                                .approx_chunk_terrain_normal()
1805                                .unwrap_or(Vec3::unit_z())
1806                                * 2.5,
1807                    ],
1808                    LINE_WIDTH,
1809                );
1810                let id = self.debug.add_shape(shape);
1811                lines.chunk_normal = Some(id);
1812                self.debug
1813                    .set_context(id, [0.0; 4], [0.22, 0.63, 0.1, 0.8], [0.0, 0.0, 0.0, 1.0]);
1814            }
1815            // Wind
1816            {
1817                let wind = weather.get_interpolated(pos.0.xy()).wind_vel();
1818                let shape = DebugShape::Line([pos.0, pos.0 + wind * 5.0], LINE_WIDTH);
1819                let id = self.debug.add_shape(shape);
1820                lines.wind = Some(id);
1821                self.debug
1822                    .set_context(id, [0.0; 4], [0.76, 0.76, 0.76, 0.8], [0.0, 0.0, 0.0, 1.0]);
1823            }
1824            // Player Vel
1825            {
1826                let shape = DebugShape::Line([pos.0, pos.0 + vel.0 / 2.0], LINE_WIDTH);
1827                let id = self.debug.add_shape(shape);
1828                lines.vel = Some(id);
1829                self.debug
1830                    .set_context(id, [0.0; 4], [0.98, 0.76, 0.01, 0.8], [0.0, 0.0, 0.0, 1.0]);
1831            }
1832        }
1833    }
1834}