veloren_server/rtsim/
mod.rs

1pub mod event;
2pub mod rule;
3pub mod tick;
4
5use atomicwrites::{AtomicFile, OverwriteBehavior};
6use common::{
7    grid::Grid,
8    mounting::VolumePos,
9    rtsim::{Actor, ChunkResource, NpcId, RtSimEntity, WorldSettings},
10    terrain::{CoordinateConversions, SpriteKind},
11};
12use common_ecs::{System, dispatch};
13use common_state::BlockDiff;
14use crossbeam_channel::{Receiver, Sender, unbounded};
15use enum_map::EnumMap;
16use rtsim::{
17    RtState,
18    data::{Data, ReadError, npc::SimulationMode},
19    event::{OnDeath, OnHealthChange, OnHelped, OnMountVolume, OnSetup, OnTheft},
20};
21use specs::DispatcherBuilder;
22use std::{
23    fs::{self, File},
24    io,
25    path::PathBuf,
26    thread::{self, JoinHandle},
27    time::Instant,
28};
29use tracing::{debug, error, info, trace, warn};
30use vek::*;
31use world::{IndexRef, World};
32
33pub struct RtSim {
34    file_path: PathBuf,
35    last_saved: Option<Instant>,
36    state: RtState,
37    save_thread: Option<(Sender<Data>, JoinHandle<()>)>,
38}
39
40impl RtSim {
41    pub fn new(
42        settings: &WorldSettings,
43        index: IndexRef,
44        world: &World,
45        data_dir: PathBuf,
46    ) -> Result<Self, ron::Error> {
47        let file_path = Self::get_file_path(data_dir);
48
49        info!("Looking for rtsim data at {}...", file_path.display());
50        let data = 'load: {
51            if std::env::var("RTSIM_NOLOAD").map_or(true, |v| v != "1") {
52                match File::open(&file_path) {
53                    Ok(file) => {
54                        info!("Rtsim data found. Attempting to load...");
55
56                        let ignore_version = std::env::var("RTSIM_IGNORE_VERSION").is_ok();
57
58                        match Data::from_reader(io::BufReader::new(file)) {
59                            Err(ReadError::VersionMismatch(_)) if !ignore_version => {
60                                warn!(
61                                    "Rtsim data version mismatch (implying a breaking change), \
62                                     rtsim data will be purged"
63                                );
64                            },
65                            Ok(data) | Err(ReadError::VersionMismatch(data)) => {
66                                info!("Rtsim data loaded.");
67                                if data.should_purge {
68                                    warn!(
69                                        "The should_purge flag was set on the rtsim data, \
70                                         generating afresh"
71                                    );
72                                } else {
73                                    break 'load *data;
74                                }
75                            },
76                            Err(ReadError::Load(err)) => {
77                                error!("Rtsim data failed to load: {}", err);
78                                info!("Old rtsim data will now be moved to a backup file");
79                                let mut i = 0;
80                                loop {
81                                    let mut backup_path = file_path.clone();
82                                    backup_path.set_extension(if i == 0 {
83                                        "ron_backup".to_string()
84                                    } else {
85                                        format!("ron_backup_{}", i)
86                                    });
87                                    if !backup_path.exists() {
88                                        fs::rename(&file_path, &backup_path)?;
89                                        warn!(
90                                            "Failed rtsim data was moved to {}",
91                                            backup_path.display()
92                                        );
93                                        info!("A fresh rtsim data will now be generated.");
94                                        break;
95                                    } else {
96                                        info!(
97                                            "Backup file {} already exists, trying another name...",
98                                            backup_path.display()
99                                        );
100                                    }
101                                    i += 1;
102                                }
103                            },
104                        }
105                    },
106                    Err(e) if e.kind() == io::ErrorKind::NotFound => {
107                        info!("No rtsim data found. Generating from world...")
108                    },
109                    Err(e) => return Err(e.into()),
110                }
111            } else {
112                warn!(
113                    "'RTSIM_NOLOAD' is set, skipping loading of rtsim state (old state will be \
114                     overwritten)."
115                );
116            }
117
118            let data = Data::generate(settings, world, index);
119            info!("Rtsim data generated.");
120            data
121        };
122
123        let mut this = Self {
124            last_saved: None,
125            state: RtState::new(data).with_resource(ChunkStates(Grid::populate_from(
126                world.sim().get_size().as_(),
127                |_| None,
128            ))),
129            file_path,
130            save_thread: None,
131        };
132
133        rule::start_rules(&mut this.state);
134
135        this.state.emit(OnSetup, &mut (), world, index);
136
137        Ok(this)
138    }
139
140    fn get_file_path(mut data_dir: PathBuf) -> PathBuf {
141        let mut path = std::env::var("VELOREN_RTSIM")
142            .map(PathBuf::from)
143            .unwrap_or_else(|_| {
144                data_dir.push("rtsim");
145                data_dir
146            });
147        path.push("data.dat");
148        path
149    }
150
151    pub fn hook_character_mount_volume(
152        &mut self,
153        world: &World,
154        index: IndexRef,
155        pos: VolumePos<NpcId>,
156        actor: Actor,
157    ) {
158        self.state
159            .emit(OnMountVolume { actor, pos }, &mut (), world, index)
160    }
161
162    pub fn hook_pickup_owned_sprite(
163        &mut self,
164        world: &World,
165        index: IndexRef,
166        sprite: SpriteKind,
167        wpos: Vec3<i32>,
168        actor: Actor,
169    ) {
170        let site = world.sim().get(wpos.xy().wpos_to_cpos()).and_then(|chunk| {
171            chunk
172                .sites
173                .iter()
174                .find_map(|site| self.state.data().sites.world_site_map.get(site).copied())
175        });
176
177        self.state.emit(
178            OnTheft {
179                actor,
180                wpos,
181                sprite,
182                site,
183            },
184            &mut (),
185            world,
186            index,
187        )
188    }
189
190    pub fn hook_load_chunk(&mut self, key: Vec2<i32>, max_res: EnumMap<ChunkResource, usize>) {
191        if let Some(chunk_state) = self.state.get_resource_mut::<ChunkStates>().0.get_mut(key) {
192            *chunk_state = Some(LoadedChunkState { max_res });
193        }
194    }
195
196    pub fn hook_unload_chunk(&mut self, key: Vec2<i32>) {
197        if let Some(chunk_state) = self.state.get_resource_mut::<ChunkStates>().0.get_mut(key) {
198            *chunk_state = None;
199        }
200    }
201
202    // Note that this hook only needs to be invoked if the block change results in a
203    // change to the rtsim resource produced by [`Block::get_rtsim_resource`].
204    pub fn hook_block_update(&mut self, world: &World, index: IndexRef, changes: Vec<BlockDiff>) {
205        self.state
206            .emit(event::OnBlockChange { changes }, &mut (), world, index);
207    }
208
209    pub fn hook_rtsim_entity_unload(&mut self, entity: RtSimEntity) {
210        let data = self.state.get_data_mut();
211
212        if let Some(npc) = data.npcs.get_mut(entity.0) {
213            if matches!(npc.mode, SimulationMode::Simulated) {
214                error!("Unloaded already unloaded entity");
215            }
216            npc.mode = SimulationMode::Simulated;
217        }
218    }
219
220    pub fn hook_rtsim_actor_hp_change(
221        &mut self,
222        world: &World,
223        index: IndexRef,
224        actor: Actor,
225        cause: Option<Actor>,
226        new_hp_fraction: f32,
227        change: f32,
228    ) {
229        self.state.emit(
230            OnHealthChange {
231                actor,
232                cause,
233                new_health_fraction: new_hp_fraction,
234                change,
235            },
236            &mut (),
237            world,
238            index,
239        )
240    }
241
242    pub fn hook_rtsim_actor_death(
243        &mut self,
244        world: &World,
245        index: IndexRef,
246        actor: Actor,
247        wpos: Option<Vec3<f32>>,
248        killer: Option<Actor>,
249    ) {
250        self.state.emit(
251            OnDeath {
252                wpos,
253                actor,
254                killer,
255            },
256            &mut (),
257            world,
258            index,
259        );
260    }
261
262    pub fn hook_rtsim_actor_helped(
263        &mut self,
264        world: &World,
265        index: IndexRef,
266        actor: Actor,
267        saver: Option<Actor>,
268    ) {
269        self.state
270            .emit(OnHelped { actor, saver }, &mut (), world, index);
271    }
272
273    pub fn save(&mut self, wait_until_finished: bool) {
274        debug!("Saving rtsim data...");
275
276        // Create the save thread if it doesn't already exist
277        // We're not using the slow job pool here for two reasons:
278        // 1) The thread is mostly blocked on IO, not compute
279        // 2) We need to synchronise saves to ensure monotonicity, which slow jobs
280        // aren't designed to allow
281        let (tx, _) = self.save_thread.get_or_insert_with(|| {
282            trace!("Starting rtsim data save thread...");
283            let (tx, rx) = unbounded();
284            let file_path = self.file_path.clone();
285            (tx, thread::spawn(move || save_thread(file_path, rx)))
286        });
287
288        // Send rtsim data to the save thread
289        if let Err(err) = tx.send(self.state.data().clone()) {
290            error!("Failed to perform rtsim save: {}", err);
291        }
292
293        // If we need to wait until the save thread has done its work (due to, for
294        // example, server shutdown) then do that.
295        if wait_until_finished {
296            if let Some((tx, handle)) = self.save_thread.take() {
297                drop(tx);
298                info!("Waiting for rtsim save thread to finish...");
299                handle.join().expect("Save thread failed to join");
300                info!("Rtsim save thread finished.");
301            }
302        }
303
304        self.last_saved = Some(Instant::now());
305    }
306
307    // TODO: Clean up this API a bit
308    pub fn get_chunk_resources(&self, key: Vec2<i32>) -> EnumMap<ChunkResource, f32> {
309        self.state.data().nature.get_chunk_resources(key)
310    }
311
312    pub fn state(&self) -> &RtState { &self.state }
313
314    pub fn set_should_purge(&mut self, should_purge: bool) {
315        self.state.data_mut().should_purge = should_purge;
316    }
317}
318
319fn save_thread(file_path: PathBuf, rx: Receiver<Data>) {
320    if let Some(dir) = file_path.parent() {
321        let _ = fs::create_dir_all(dir);
322    }
323
324    let atomic_file = AtomicFile::new(file_path, OverwriteBehavior::AllowOverwrite);
325    while let Ok(data) = rx.recv() {
326        debug!("Writing rtsim data to file...");
327        match atomic_file.write(move |file| data.write_to(io::BufWriter::new(file))) {
328            Ok(_) => debug!("Rtsim data saved."),
329            Err(e) => error!("Saving rtsim data failed: {}", e),
330        }
331    }
332}
333
334pub struct ChunkStates(pub Grid<Option<LoadedChunkState>>);
335
336pub struct LoadedChunkState {
337    // The maximum possible number of each resource in this chunk
338    pub max_res: EnumMap<ChunkResource, usize>,
339}
340
341pub fn add_server_systems(dispatch_builder: &mut DispatcherBuilder) {
342    dispatch::<tick::Sys>(dispatch_builder, &[&common_systems::phys::Sys::sys_name()]);
343}