veloren_common_state/
state.rs

1#[cfg(feature = "plugins")]
2use crate::plugin::PluginMgr;
3#[cfg(feature = "plugins")]
4use crate::plugin::memory_manager::EcsWorld;
5use crate::{BuildArea, NoDurabilityArea};
6#[cfg(feature = "plugins")]
7use common::uid::IdMaps;
8use common::{
9    calendar::Calendar,
10    comp,
11    event::{EventBus, LocalEvent},
12    interaction,
13    link::Is,
14    mounting::{Mount, Rider, VolumeRider, VolumeRiders},
15    outcome::Outcome,
16    resources::{
17        DeltaTime, EntitiesDiedLastTick, GameMode, PlayerEntity, PlayerPhysicsSettings,
18        ProgramTime, Time, TimeOfDay, TimeScale,
19    },
20    shared_server_config::ServerConstants,
21    slowjob::SlowJobPool,
22    terrain::{Block, MapSizeLg, TerrainChunk, TerrainGrid},
23    tether,
24    time::DayPeriod,
25    trade::Trades,
26    vol::{ReadVol, WriteVol},
27    weather::{Weather, WeatherGrid},
28};
29use common_base::{prof_span, span};
30use common_ecs::{PhysicsMetrics, SysMetrics};
31use common_net::sync::{WorldSyncExt, interpolation as sync_interp};
32use core::{convert::identity, time::Duration};
33use hashbrown::{HashMap, HashSet};
34use rayon::{ThreadPool, ThreadPoolBuilder};
35use specs::{
36    Component, DispatcherBuilder, Entity as EcsEntity, WorldExt,
37    prelude::Resource,
38    shred::{Fetch, FetchMut, SendDispatcher},
39    storage::{MaskedStorage as EcsMaskedStorage, Storage as EcsStorage},
40};
41use std::{sync::Arc, time::Instant};
42use timer_queue::TimerQueue;
43use vek::*;
44
45/// At what point should we stop speeding up physics to compensate for lag? If
46/// we speed physics up too fast, we'd skip important physics events like
47/// collisions. This constant determines the upper limit. If delta time exceeds
48/// this value, the game's physics will begin to produce time lag. Ideally, we'd
49/// avoid such a situation.
50const MAX_DELTA_TIME: f32 = 1.0;
51/// convert seconds to milliseconds to use in TimerQueue
52const SECONDS_TO_MILLISECONDS: f64 = 1000.0;
53
54#[derive(Default)]
55pub struct BlockChange {
56    blocks: HashMap<Vec3<i32>, Block>,
57}
58
59impl BlockChange {
60    pub fn set(&mut self, pos: Vec3<i32>, block: Block) { self.blocks.insert(pos, block); }
61
62    pub fn try_set(&mut self, pos: Vec3<i32>, block: Block) -> Option<()> {
63        if !self.blocks.contains_key(&pos) {
64            self.blocks.insert(pos, block);
65            Some(())
66        } else {
67            None
68        }
69    }
70
71    /// Check if the block at given position `pos` has already been modified
72    /// this tick.
73    pub fn can_set_block(&self, pos: Vec3<i32>) -> bool { !self.blocks.contains_key(&pos) }
74
75    pub fn clear(&mut self) { self.blocks.clear(); }
76}
77
78#[derive(Default)]
79pub struct ScheduledBlockChange {
80    changes: TimerQueue<HashMap<Vec3<i32>, Block>>,
81    outcomes: TimerQueue<HashMap<Vec3<i32>, Block>>,
82    last_poll_time: u64,
83}
84impl ScheduledBlockChange {
85    pub fn set(&mut self, pos: Vec3<i32>, block: Block, replace_time: f64) {
86        let timer = self.changes.insert(
87            (replace_time * SECONDS_TO_MILLISECONDS) as u64,
88            HashMap::new(),
89        );
90        self.changes.get_mut(timer).insert(pos, block);
91    }
92
93    pub fn outcome_set(&mut self, pos: Vec3<i32>, block: Block, replace_time: f64) {
94        let outcome_timer = self.outcomes.insert(
95            (replace_time * SECONDS_TO_MILLISECONDS) as u64,
96            HashMap::new(),
97        );
98        self.outcomes.get_mut(outcome_timer).insert(pos, block);
99    }
100}
101
102#[derive(Default)]
103pub struct TerrainChanges {
104    pub new_chunks: HashSet<Vec2<i32>>,
105    pub modified_chunks: HashSet<Vec2<i32>>,
106    pub removed_chunks: HashSet<Vec2<i32>>,
107    pub modified_blocks: HashMap<Vec3<i32>, Block>,
108}
109
110impl TerrainChanges {
111    pub fn clear(&mut self) {
112        self.new_chunks.clear();
113        self.modified_chunks.clear();
114        self.removed_chunks.clear();
115    }
116}
117
118#[derive(Clone)]
119pub struct BlockDiff {
120    pub wpos: Vec3<i32>,
121    pub old: Block,
122    pub new: Block,
123}
124
125/// A type used to represent game state stored on both the client and the
126/// server. This includes things like entity components, terrain data, and
127/// global states like weather, time of day, etc.
128pub struct State {
129    ecs: specs::World,
130    // Avoid lifetime annotation by storing a thread pool instead of the whole dispatcher
131    thread_pool: Arc<ThreadPool>,
132    dispatcher: SendDispatcher<'static>,
133}
134
135pub type Pools = Arc<ThreadPool>;
136
137impl State {
138    pub fn pools(game_mode: GameMode) -> Pools {
139        let thread_name_infix = match game_mode {
140            GameMode::Server => "s",
141            GameMode::Client => "c",
142            GameMode::Singleplayer => "sp",
143        };
144
145        Arc::new(
146            ThreadPoolBuilder::new()
147                .num_threads(num_cpus::get().max(common::consts::MIN_RECOMMENDED_RAYON_THREADS))
148                .thread_name(move |i| format!("rayon-{}-{}", thread_name_infix, i))
149                .build()
150                .unwrap(),
151        )
152    }
153
154    /// Create a new `State` in client mode.
155    pub fn client(
156        pools: Pools,
157        map_size_lg: MapSizeLg,
158        default_chunk: Arc<TerrainChunk>,
159        add_systems: impl Fn(&mut DispatcherBuilder),
160        #[cfg(feature = "plugins")] plugin_mgr: PluginMgr,
161    ) -> Self {
162        Self::new(
163            GameMode::Client,
164            pools,
165            map_size_lg,
166            default_chunk,
167            add_systems,
168            #[cfg(feature = "plugins")]
169            plugin_mgr,
170        )
171    }
172
173    /// Create a new `State` in server mode.
174    pub fn server(
175        pools: Pools,
176        map_size_lg: MapSizeLg,
177        default_chunk: Arc<TerrainChunk>,
178        add_systems: impl Fn(&mut DispatcherBuilder),
179        #[cfg(feature = "plugins")] plugin_mgr: PluginMgr,
180    ) -> Self {
181        Self::new(
182            GameMode::Server,
183            pools,
184            map_size_lg,
185            default_chunk,
186            add_systems,
187            #[cfg(feature = "plugins")]
188            plugin_mgr,
189        )
190    }
191
192    pub fn new(
193        game_mode: GameMode,
194        pools: Pools,
195        map_size_lg: MapSizeLg,
196        default_chunk: Arc<TerrainChunk>,
197        add_systems: impl Fn(&mut DispatcherBuilder),
198        #[cfg(feature = "plugins")] plugin_mgr: PluginMgr,
199    ) -> Self {
200        prof_span!(guard, "create dispatcher");
201        let mut dispatch_builder =
202            DispatcherBuilder::<'static, 'static>::new().with_pool(Arc::clone(&pools));
203        // TODO: Consider alternative ways to do this
204        add_systems(&mut dispatch_builder);
205        let dispatcher = dispatch_builder
206            .build()
207            .try_into_sendable()
208            .unwrap_or_else(|_| panic!("Thread local systems not allowed"));
209        drop(guard);
210
211        Self {
212            ecs: Self::setup_ecs_world(
213                game_mode,
214                Arc::clone(&pools),
215                map_size_lg,
216                default_chunk,
217                #[cfg(feature = "plugins")]
218                plugin_mgr,
219            ),
220            thread_pool: pools,
221            dispatcher,
222        }
223    }
224
225    /// Creates ecs world and registers all the common components and resources
226    // TODO: Split up registering into server and client (e.g. move
227    // EventBus<ServerEvent> to the server)
228    fn setup_ecs_world(
229        game_mode: GameMode,
230        thread_pool: Arc<ThreadPool>,
231        map_size_lg: MapSizeLg,
232        default_chunk: Arc<TerrainChunk>,
233        #[cfg(feature = "plugins")] mut plugin_mgr: PluginMgr,
234    ) -> specs::World {
235        prof_span!("State::setup_ecs_world");
236        let mut ecs = specs::World::new();
237        // Uids for sync
238        ecs.register_sync_marker();
239        // Register server -> all clients synced components.
240        ecs.register::<comp::Body>();
241        ecs.register::<comp::Hardcore>();
242        ecs.register::<comp::body::parts::Heads>();
243        ecs.register::<comp::Player>();
244        ecs.register::<comp::Stats>();
245        ecs.register::<comp::SkillSet>();
246        ecs.register::<comp::ActiveAbilities>();
247        ecs.register::<comp::Buffs>();
248        ecs.register::<comp::Auras>();
249        ecs.register::<comp::EnteredAuras>();
250        ecs.register::<comp::Energy>();
251        ecs.register::<comp::Combo>();
252        ecs.register::<comp::Health>();
253        ecs.register::<comp::Poise>();
254        ecs.register::<comp::CanBuild>();
255        ecs.register::<comp::LightEmitter>();
256        ecs.register::<comp::PickupItem>();
257        ecs.register::<comp::Scale>();
258        ecs.register::<Is<Mount>>();
259        ecs.register::<Is<Rider>>();
260        ecs.register::<Is<VolumeRider>>();
261        ecs.register::<Is<tether::Leader>>();
262        ecs.register::<Is<tether::Follower>>();
263        ecs.register::<Is<interaction::Interactor>>();
264        ecs.register::<interaction::Interactors>();
265        ecs.register::<comp::Mass>();
266        ecs.register::<comp::Density>();
267        ecs.register::<comp::Collider>();
268        ecs.register::<comp::Sticky>();
269        ecs.register::<comp::Immovable>();
270        ecs.register::<comp::CharacterState>();
271        ecs.register::<comp::CharacterActivity>();
272        ecs.register::<comp::Object>();
273        ecs.register::<comp::Group>();
274        ecs.register::<comp::Shockwave>();
275        ecs.register::<comp::ShockwaveHitEntities>();
276        ecs.register::<comp::Beam>();
277        ecs.register::<comp::Alignment>();
278        ecs.register::<comp::LootOwner>();
279        ecs.register::<comp::Admin>();
280        ecs.register::<comp::Stance>();
281        ecs.register::<comp::Teleporting>();
282
283        // Register components send from clients -> server
284        ecs.register::<comp::Controller>();
285
286        // Register components send directly from server -> all but one client
287        ecs.register::<comp::PhysicsState>();
288
289        // Register components synced from client -> server -> all other clients
290        ecs.register::<comp::Pos>();
291        ecs.register::<comp::Vel>();
292        ecs.register::<comp::Ori>();
293        ecs.register::<comp::Inventory>();
294
295        // Register common unsynced components
296        ecs.register::<comp::PreviousPhysCache>();
297        ecs.register::<comp::PosVelOriDefer>();
298
299        // Register client-local components
300        // TODO: only register on the client
301        ecs.register::<comp::LightAnimation>();
302        ecs.register::<sync_interp::InterpBuffer<comp::Pos>>();
303        ecs.register::<sync_interp::InterpBuffer<comp::Vel>>();
304        ecs.register::<sync_interp::InterpBuffer<comp::Ori>>();
305
306        // Register server-local components
307        // TODO: only register on the server
308        ecs.register::<comp::Last<comp::Pos>>();
309        ecs.register::<comp::Last<comp::Vel>>();
310        ecs.register::<comp::Last<comp::Ori>>();
311        ecs.register::<comp::Agent>();
312        ecs.register::<comp::WaypointArea>();
313        ecs.register::<comp::ForceUpdate>();
314        ecs.register::<comp::InventoryUpdate>();
315        ecs.register::<comp::Waypoint>();
316        ecs.register::<comp::MapMarker>();
317        ecs.register::<comp::Projectile>();
318        ecs.register::<comp::Melee>();
319        ecs.register::<comp::ItemDrops>();
320        ecs.register::<comp::ChatMode>();
321        ecs.register::<comp::Faction>();
322        ecs.register::<comp::invite::Invite>();
323        ecs.register::<comp::invite::PendingInvites>();
324        ecs.register::<VolumeRiders>();
325        ecs.register::<common::combat::DeathEffects>();
326
327        // Register synced resources used by the ECS.
328        ecs.insert(TimeOfDay(0.0));
329        ecs.insert(Calendar::default());
330        ecs.insert(WeatherGrid::new(Vec2::zero()));
331        ecs.insert(Time(0.0));
332        ecs.insert(ProgramTime(0.0));
333        ecs.insert(TimeScale(1.0));
334
335        // Register unsynced resources used by the ECS.
336        ecs.insert(DeltaTime(0.0));
337        ecs.insert(PlayerEntity(None));
338        ecs.insert(TerrainGrid::new(map_size_lg, default_chunk).unwrap());
339        ecs.insert(BlockChange::default());
340        ecs.insert(ScheduledBlockChange::default());
341        ecs.insert(crate::special_areas::AreasContainer::<BuildArea>::default());
342        ecs.insert(crate::special_areas::AreasContainer::<NoDurabilityArea>::default());
343        ecs.insert(TerrainChanges::default());
344        ecs.insert(EventBus::<LocalEvent>::default());
345        ecs.insert(game_mode);
346        ecs.insert(EventBus::<Outcome>::default());
347        ecs.insert(common::CachedSpatialGrid::default());
348        ecs.insert(EntitiesDiedLastTick::default());
349
350        let num_cpu = num_cpus::get() as u64;
351        let slow_limit = (num_cpu / 2 + num_cpu / 4).max(1);
352        tracing::trace!(?slow_limit, "Slow Thread limit");
353        ecs.insert(SlowJobPool::new(slow_limit, 10_000, thread_pool));
354
355        // TODO: only register on the server
356        ecs.insert(comp::group::GroupManager::default());
357        ecs.insert(SysMetrics::default());
358        ecs.insert(PhysicsMetrics::default());
359        ecs.insert(Trades::default());
360        ecs.insert(PlayerPhysicsSettings::default());
361        ecs.insert(VolumeRiders::default());
362
363        // Load plugins from asset directory
364        #[cfg(feature = "plugins")]
365        ecs.insert({
366            let ecs_world = EcsWorld {
367                entities: &ecs.entities(),
368                health: ecs.read_component().into(),
369                uid: ecs.read_component().into(),
370                id_maps: &ecs.read_resource::<IdMaps>().into(),
371                player: ecs.read_component().into(),
372            };
373            if let Err(e) = plugin_mgr.load_event(&ecs_world, game_mode) {
374                tracing::debug!(?e, "Failed to run plugin init");
375                tracing::info!("Plugins disabled, enable debug logging for more information.");
376                PluginMgr::default()
377            } else {
378                plugin_mgr
379            }
380        });
381
382        ecs
383    }
384
385    /// Register a component with the state's ECS.
386    #[must_use]
387    pub fn with_component<T: Component>(mut self) -> Self
388    where
389        <T as Component>::Storage: Default,
390    {
391        self.ecs.register::<T>();
392        self
393    }
394
395    /// Write a component attributed to a particular entity, ignoring errors.
396    ///
397    /// This should be used *only* when we can guarantee that the rest of the
398    /// code does not rely on the insert having succeeded (meaning the
399    /// entity is no longer alive!).
400    ///
401    /// Returns None if the entity was dead or there was no previous entry for
402    /// this component; otherwise, returns Some(old_component).
403    pub fn write_component_ignore_entity_dead<C: Component>(
404        &mut self,
405        entity: EcsEntity,
406        comp: C,
407    ) -> Option<C> {
408        self.ecs
409            .write_storage()
410            .insert(entity, comp)
411            .ok()
412            .and_then(identity)
413    }
414
415    /// Delete a component attributed to a particular entity.
416    pub fn delete_component<C: Component>(&mut self, entity: EcsEntity) -> Option<C> {
417        self.ecs.write_storage().remove(entity)
418    }
419
420    /// Read a component attributed to a particular entity.
421    pub fn read_component_cloned<C: Component + Clone>(&self, entity: EcsEntity) -> Option<C> {
422        self.ecs.read_storage().get(entity).cloned()
423    }
424
425    /// Read a component attributed to a particular entity.
426    pub fn read_component_copied<C: Component + Copy>(&self, entity: EcsEntity) -> Option<C> {
427        self.ecs.read_storage().get(entity).copied()
428    }
429
430    /// # Panics
431    /// Panics if `EventBus<E>` is borrowed
432    pub fn emit_event_now<E>(&self, event: E)
433    where
434        EventBus<E>: Resource,
435    {
436        self.ecs.write_resource::<EventBus<E>>().emit_now(event)
437    }
438
439    /// Given mutable access to the resource R, assuming the resource
440    /// component exists (this is already the behavior of functions like `fetch`
441    /// and `write_component_ignore_entity_dead`).  Since all of our resources
442    /// are generated up front, any failure here is definitely a code bug.
443    pub fn mut_resource<R: Resource>(&mut self) -> &mut R {
444        self.ecs.get_mut::<R>().expect(
445            "Tried to fetch an invalid resource even though all our resources should be known at \
446             compile time.",
447        )
448    }
449
450    /// Get a read-only reference to the storage of a particular component type.
451    pub fn read_storage<C: Component>(&self) -> EcsStorage<C, Fetch<EcsMaskedStorage<C>>> {
452        self.ecs.read_storage::<C>()
453    }
454
455    /// Get a reference to the internal ECS world.
456    pub fn ecs(&self) -> &specs::World { &self.ecs }
457
458    /// Get a mutable reference to the internal ECS world.
459    pub fn ecs_mut(&mut self) -> &mut specs::World { &mut self.ecs }
460
461    pub fn thread_pool(&self) -> &Arc<ThreadPool> { &self.thread_pool }
462
463    /// Get a reference to the `TerrainChanges` structure of the state. This
464    /// contains information about terrain state that has changed since the
465    /// last game tick.
466    pub fn terrain_changes(&self) -> Fetch<TerrainChanges> { self.ecs.read_resource() }
467
468    /// Get a reference the current in-game weather grid.
469    pub fn weather_grid(&self) -> Fetch<WeatherGrid> { self.ecs.read_resource() }
470
471    /// Get a mutable reference the current in-game weather grid.
472    pub fn weather_grid_mut(&mut self) -> FetchMut<WeatherGrid> { self.ecs.write_resource() }
473
474    /// Get the current weather at a position in worldspace.
475    pub fn weather_at(&self, pos: Vec2<f32>) -> Weather {
476        self.weather_grid().get_interpolated(pos)
477    }
478
479    /// Get the max weather near a position in worldspace.
480    pub fn max_weather_near(&self, pos: Vec2<f32>) -> Weather {
481        self.weather_grid().get_max_near(pos)
482    }
483
484    /// Get the current in-game time of day.
485    ///
486    /// Note that this should not be used for physics, animations or other such
487    /// localised timings.
488    pub fn get_time_of_day(&self) -> f64 { self.ecs.read_resource::<TimeOfDay>().0 }
489
490    /// Get the current in-game day period (period of the day/night cycle)
491    pub fn get_day_period(&self) -> DayPeriod { self.get_time_of_day().into() }
492
493    /// Get the current in-game time.
494    ///
495    /// Note that this does not correspond to the time of day.
496    pub fn get_time(&self) -> f64 { self.ecs.read_resource::<Time>().0 }
497
498    /// Get the current true in-game time, unaffected by time_scale.
499    ///
500    /// Note that this does not correspond to the time of day.
501    pub fn get_program_time(&self) -> f64 { self.ecs.read_resource::<ProgramTime>().0 }
502
503    /// Get the current delta time.
504    pub fn get_delta_time(&self) -> f32 { self.ecs.read_resource::<DeltaTime>().0 }
505
506    /// Get a reference to this state's terrain.
507    pub fn terrain(&self) -> Fetch<TerrainGrid> { self.ecs.read_resource() }
508
509    /// Get a reference to this state's terrain.
510    pub fn slow_job_pool(&self) -> Fetch<SlowJobPool> { self.ecs.read_resource() }
511
512    /// Get a writable reference to this state's terrain.
513    pub fn terrain_mut(&self) -> FetchMut<TerrainGrid> { self.ecs.write_resource() }
514
515    /// Get a block in this state's terrain.
516    pub fn get_block(&self, pos: Vec3<i32>) -> Option<Block> {
517        self.terrain().get(pos).ok().copied()
518    }
519
520    /// Set a block in this state's terrain.
521    pub fn set_block(&self, pos: Vec3<i32>, block: Block) {
522        self.ecs.write_resource::<BlockChange>().set(pos, block);
523    }
524
525    /// Set a block in this state's terrain (used to delete temporary summoned
526    /// sprites after a timeout).
527    pub fn schedule_set_block(
528        &self,
529        pos: Vec3<i32>,
530        block: Block,
531        sprite_block: Block,
532        replace_time: f64,
533    ) {
534        self.ecs
535            .write_resource::<ScheduledBlockChange>()
536            .set(pos, block, replace_time);
537        self.ecs
538            .write_resource::<ScheduledBlockChange>()
539            .outcome_set(pos, sprite_block, replace_time);
540    }
541
542    /// Check if the block at given position `pos` has already been modified
543    /// this tick.
544    pub fn can_set_block(&self, pos: Vec3<i32>) -> bool {
545        self.ecs.read_resource::<BlockChange>().can_set_block(pos)
546    }
547
548    /// Removes every chunk of the terrain.
549    pub fn clear_terrain(&mut self) -> usize {
550        let removed_chunks = &mut self.ecs.write_resource::<TerrainChanges>().removed_chunks;
551
552        self.terrain_mut()
553            .drain()
554            .map(|(key, _)| {
555                removed_chunks.insert(key);
556            })
557            .count()
558    }
559
560    /// Insert the provided chunk into this state's terrain.
561    pub fn insert_chunk(&mut self, key: Vec2<i32>, chunk: Arc<TerrainChunk>) {
562        if self
563            .ecs
564            .write_resource::<TerrainGrid>()
565            .insert(key, chunk)
566            .is_some()
567        {
568            self.ecs
569                .write_resource::<TerrainChanges>()
570                .modified_chunks
571                .insert(key);
572        } else {
573            self.ecs
574                .write_resource::<TerrainChanges>()
575                .new_chunks
576                .insert(key);
577        }
578    }
579
580    /// Remove the chunk with the given key from this state's terrain, if it
581    /// exists.
582    pub fn remove_chunk(&mut self, key: Vec2<i32>) -> bool {
583        if self
584            .ecs
585            .write_resource::<TerrainGrid>()
586            .remove(key)
587            .is_some()
588        {
589            self.ecs
590                .write_resource::<TerrainChanges>()
591                .removed_chunks
592                .insert(key);
593
594            true
595        } else {
596            false
597        }
598    }
599
600    // Apply terrain changes
601    pub fn apply_terrain_changes(&self, block_update: impl FnMut(&specs::World, Vec<BlockDiff>)) {
602        self.apply_terrain_changes_internal(false, block_update);
603    }
604
605    /// `during_tick` is true if and only if this is called from within
606    /// [State::tick].
607    ///
608    /// This only happens if [State::tick] is asked to update terrain itself
609    /// (using `update_terrain: true`).  [State::tick] is called from within
610    /// both the client and the server ticks, right after handling terrain
611    /// messages; currently, client sets it to true and server to false.
612    fn apply_terrain_changes_internal(
613        &self,
614        during_tick: bool,
615        mut block_update: impl FnMut(&specs::World, Vec<BlockDiff>),
616    ) {
617        span!(
618            _guard,
619            "apply_terrain_changes",
620            "State::apply_terrain_changes"
621        );
622        let mut terrain = self.ecs.write_resource::<TerrainGrid>();
623        let mut modified_blocks =
624            std::mem::take(&mut self.ecs.write_resource::<BlockChange>().blocks);
625
626        let mut scheduled_changes = self.ecs.write_resource::<ScheduledBlockChange>();
627        let current_time: f64 = self.ecs.read_resource::<Time>().0 * SECONDS_TO_MILLISECONDS;
628        let current_time = current_time as u64;
629        // This is important as the poll function has a debug assert that the new poll
630        // is at a more recent time than the old poll. As Time is synced between server
631        // and client, there is a chance that client dt can get slightly ahead of a
632        // server update, so we do not want to panic in that scenario.
633        if scheduled_changes.last_poll_time < current_time {
634            scheduled_changes.last_poll_time = current_time;
635            while let Some(changes) = scheduled_changes.changes.poll(current_time) {
636                modified_blocks.extend(changes.iter());
637            }
638            let outcome = self.ecs.read_resource::<EventBus<Outcome>>();
639            while let Some(outcomes) = scheduled_changes.outcomes.poll(current_time) {
640                for (pos, block) in outcomes.into_iter() {
641                    if let Some(sprite) = block.get_sprite() {
642                        outcome.emit_now(Outcome::SpriteDelete { pos, sprite });
643                    }
644                }
645            }
646        }
647        // Apply block modifications
648        // Only include in `TerrainChanges` if successful
649        let mut updated_blocks = Vec::with_capacity(modified_blocks.len());
650        modified_blocks.retain(|wpos, new| {
651            let res = terrain.map(*wpos, |old| {
652                updated_blocks.push(BlockDiff {
653                    wpos: *wpos,
654                    old,
655                    new: *new,
656                });
657                *new
658            });
659            if let (&Ok(old), true) = (&res, during_tick) {
660                // NOTE: If the changes are applied during the tick, we push the *old* value as
661                // the modified block (since it otherwise can't be recovered after the tick).
662                // Otherwise, the changes will be applied after the tick, so we push the *new*
663                // value.
664                *new = old;
665            }
666            res.is_ok()
667        });
668
669        if !updated_blocks.is_empty() {
670            block_update(&self.ecs, updated_blocks);
671        }
672
673        self.ecs.write_resource::<TerrainChanges>().modified_blocks = modified_blocks;
674    }
675
676    /// Execute a single tick, simulating the game state by the given duration.
677    pub fn tick(
678        &mut self,
679        dt: Duration,
680        update_terrain: bool,
681        mut metrics: Option<&mut StateTickMetrics>,
682        server_constants: &ServerConstants,
683        block_update: impl FnMut(&specs::World, Vec<BlockDiff>),
684    ) {
685        span!(_guard, "tick", "State::tick");
686
687        // Timing code for server metrics
688        macro_rules! section_span {
689            ($guard:ident, $label:literal) => {
690                span!(span_guard, $label);
691                let metrics_guard = metrics.as_mut().map(|m| MetricsGuard::new($label, m));
692                let $guard = (span_guard, metrics_guard);
693            };
694        }
695
696        // Change the time accordingly.
697        let time_scale = self.ecs.read_resource::<TimeScale>().0;
698        self.ecs.write_resource::<TimeOfDay>().0 +=
699            dt.as_secs_f64() * server_constants.day_cycle_coefficient * time_scale;
700        self.ecs.write_resource::<Time>().0 += dt.as_secs_f64() * time_scale;
701        self.ecs.write_resource::<ProgramTime>().0 += dt.as_secs_f64();
702
703        // Update delta time.
704        // Beyond a delta time of MAX_DELTA_TIME, start lagging to avoid skipping
705        // important physics events.
706        self.ecs.write_resource::<DeltaTime>().0 =
707            (dt.as_secs_f32() * time_scale as f32).min(MAX_DELTA_TIME);
708
709        section_span!(guard, "run systems");
710        // This dispatches all the systems in parallel.
711        self.dispatcher.dispatch(&self.ecs);
712        drop(guard);
713
714        self.maintain_ecs();
715
716        if update_terrain {
717            self.apply_terrain_changes_internal(true, block_update);
718        }
719
720        // Process local events
721        section_span!(guard, "process local events");
722
723        let outcomes = self.ecs.read_resource::<EventBus<Outcome>>();
724        let mut outcomes_emitter = outcomes.emitter();
725
726        let events = self.ecs.read_resource::<EventBus<LocalEvent>>().recv_all();
727        for event in events {
728            let mut velocities = self.ecs.write_storage::<comp::Vel>();
729            let physics = self.ecs.read_storage::<comp::PhysicsState>();
730            match event {
731                LocalEvent::Jump(entity, impulse) => {
732                    if let Some(vel) = velocities.get_mut(entity) {
733                        vel.0.z = impulse + physics.get(entity).map_or(0.0, |ps| ps.ground_vel.z);
734                    }
735                },
736                LocalEvent::ApplyImpulse { entity, impulse } => {
737                    if let Some(vel) = velocities.get_mut(entity) {
738                        vel.0 = impulse;
739                    }
740                },
741                LocalEvent::Boost {
742                    entity,
743                    vel: extra_vel,
744                } => {
745                    if let Some(vel) = velocities.get_mut(entity) {
746                        vel.0 += extra_vel;
747                    }
748                },
749                LocalEvent::CreateOutcome(outcome) => {
750                    outcomes_emitter.emit(outcome);
751                },
752            }
753        }
754        drop(guard);
755    }
756
757    pub fn maintain_ecs(&mut self) {
758        span!(_guard, "maintain ecs");
759        self.ecs.maintain();
760    }
761
762    /// Clean up the state after a tick.
763    pub fn cleanup(&mut self) {
764        span!(_guard, "cleanup", "State::cleanup");
765        // Clean up data structures from the last tick.
766        self.ecs.write_resource::<TerrainChanges>().clear();
767    }
768}
769
770// Timing code for server metrics
771#[derive(Default)]
772pub struct StateTickMetrics {
773    pub timings: Vec<(&'static str, Duration)>,
774}
775
776impl StateTickMetrics {
777    fn add(&mut self, label: &'static str, dur: Duration) {
778        // Check for duplicates!
779        debug_assert!(
780            self.timings.iter().all(|(l, _)| *l != label),
781            "Duplicate label in state tick metrics {label}"
782        );
783        self.timings.push((label, dur));
784    }
785}
786
787struct MetricsGuard<'a> {
788    start: Instant,
789    label: &'static str,
790    metrics: &'a mut StateTickMetrics,
791}
792
793impl<'a> MetricsGuard<'a> {
794    fn new(label: &'static str, metrics: &'a mut StateTickMetrics) -> Self {
795        Self {
796            start: Instant::now(),
797            label,
798            metrics,
799        }
800    }
801}
802
803impl Drop for MetricsGuard<'_> {
804    fn drop(&mut self) { self.metrics.add(self.label, self.start.elapsed()); }
805}