]> git.lizzy.rs Git - minetest.git/blob - src/serverenvironment.h
Force player save before kicking on player shutdown (#8157)
[minetest.git] / src / serverenvironment.h
1 /*
2 Minetest
3 Copyright (C) 2010-2017 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #pragma once
21
22 #include "activeobject.h"
23 #include "environment.h"
24 #include "mapnode.h"
25 #include "settings.h"
26 #include "server/activeobjectmgr.h"
27 #include "util/numeric.h"
28 #include <set>
29
30 class IGameDef;
31 class ServerMap;
32 struct GameParams;
33 class MapBlock;
34 class RemotePlayer;
35 class PlayerDatabase;
36 class AuthDatabase;
37 class PlayerSAO;
38 class ServerEnvironment;
39 class ActiveBlockModifier;
40 struct StaticObject;
41 class ServerActiveObject;
42 class Server;
43 class ServerScripting;
44
45 /*
46         {Active, Loading} block modifier interface.
47
48         These are fed into ServerEnvironment at initialization time;
49         ServerEnvironment handles deleting them.
50 */
51
52 class ActiveBlockModifier
53 {
54 public:
55         ActiveBlockModifier() = default;
56         virtual ~ActiveBlockModifier() = default;
57
58         // Set of contents to trigger on
59         virtual const std::vector<std::string> &getTriggerContents() const = 0;
60         // Set of required neighbors (trigger doesn't happen if none are found)
61         // Empty = do not check neighbors
62         virtual const std::vector<std::string> &getRequiredNeighbors() const = 0;
63         // Trigger interval in seconds
64         virtual float getTriggerInterval() = 0;
65         // Random chance of (1 / return value), 0 is disallowed
66         virtual u32 getTriggerChance() = 0;
67         // Whether to modify chance to simulate time lost by an unnattended block
68         virtual bool getSimpleCatchUp() = 0;
69         // This is called usually at interval for 1/chance of the nodes
70         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
71         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
72                 u32 active_object_count, u32 active_object_count_wider){};
73 };
74
75 struct ABMWithState
76 {
77         ActiveBlockModifier *abm;
78         float timer = 0.0f;
79
80         ABMWithState(ActiveBlockModifier *abm_);
81 };
82
83 struct LoadingBlockModifierDef
84 {
85         // Set of contents to trigger on
86         std::set<std::string> trigger_contents;
87         std::string name;
88         bool run_at_every_load = false;
89
90         virtual ~LoadingBlockModifierDef() = default;
91
92         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
93 };
94
95 struct LBMContentMapping
96 {
97         typedef std::unordered_map<content_t, std::vector<LoadingBlockModifierDef *>> lbm_map;
98         lbm_map map;
99
100         std::vector<LoadingBlockModifierDef *> lbm_list;
101
102         // Needs to be separate method (not inside destructor),
103         // because the LBMContentMapping may be copied and destructed
104         // many times during operation in the lbm_lookup_map.
105         void deleteContents();
106         void addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef);
107         const std::vector<LoadingBlockModifierDef *> *lookup(content_t c) const;
108 };
109
110 class LBMManager
111 {
112 public:
113         LBMManager() = default;
114         ~LBMManager();
115
116         // Don't call this after loadIntroductionTimes() ran.
117         void addLBMDef(LoadingBlockModifierDef *lbm_def);
118
119         void loadIntroductionTimes(const std::string &times,
120                 IGameDef *gamedef, u32 now);
121
122         // Don't call this before loadIntroductionTimes() ran.
123         std::string createIntroductionTimesString();
124
125         // Don't call this before loadIntroductionTimes() ran.
126         void applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp);
127
128         // Warning: do not make this std::unordered_map, order is relevant here
129         typedef std::map<u32, LBMContentMapping> lbm_lookup_map;
130
131 private:
132         // Once we set this to true, we can only query,
133         // not modify
134         bool m_query_mode = false;
135
136         // For m_query_mode == false:
137         // The key of the map is the LBM def's name.
138         // TODO make this std::unordered_map
139         std::map<std::string, LoadingBlockModifierDef *> m_lbm_defs;
140
141         // For m_query_mode == true:
142         // The key of the map is the LBM def's first introduction time.
143         lbm_lookup_map m_lbm_lookup;
144
145         // Returns an iterator to the LBMs that were introduced
146         // after the given time. This is guaranteed to return
147         // valid values for everything
148         lbm_lookup_map::const_iterator getLBMsIntroducedAfter(u32 time)
149         { return m_lbm_lookup.lower_bound(time); }
150 };
151
152 /*
153         List of active blocks, used by ServerEnvironment
154 */
155
156 class ActiveBlockList
157 {
158 public:
159         void update(std::vector<PlayerSAO*> &active_players,
160                 s16 active_block_range,
161                 s16 active_object_range,
162                 std::set<v3s16> &blocks_removed,
163                 std::set<v3s16> &blocks_added);
164
165         bool contains(v3s16 p){
166                 return (m_list.find(p) != m_list.end());
167         }
168
169         void clear(){
170                 m_list.clear();
171         }
172
173         std::set<v3s16> m_list;
174         std::set<v3s16> m_abm_list;
175         std::set<v3s16> m_forceloaded_list;
176
177 private:
178 };
179
180 /*
181         Operation mode for ServerEnvironment::clearObjects()
182 */
183 enum ClearObjectsMode {
184         // Load and go through every mapblock, clearing objects
185                 CLEAR_OBJECTS_MODE_FULL,
186
187         // Clear objects immediately in loaded mapblocks;
188         // clear objects in unloaded mapblocks only when the mapblocks are next activated.
189                 CLEAR_OBJECTS_MODE_QUICK,
190 };
191
192 /*
193         The server-side environment.
194
195         This is not thread-safe. Server uses an environment mutex.
196 */
197
198 typedef std::unordered_map<u16, ServerActiveObject *> ServerActiveObjectMap;
199
200 class ServerEnvironment : public Environment
201 {
202 public:
203         ServerEnvironment(ServerMap *map, ServerScripting *scriptIface,
204                 Server *server, const std::string &path_world);
205         ~ServerEnvironment();
206
207         Map & getMap();
208
209         ServerMap & getServerMap();
210
211         //TODO find way to remove this fct!
212         ServerScripting* getScriptIface()
213         { return m_script; }
214
215         Server *getGameDef()
216         { return m_server; }
217
218         float getSendRecommendedInterval()
219         { return m_recommended_send_interval; }
220
221         void kickAllPlayers(AccessDeniedCode reason,
222                 const std::string &str_reason, bool reconnect);
223         // Save players
224         void saveLoadedPlayers(bool force = false);
225         void savePlayer(RemotePlayer *player);
226         PlayerSAO *loadPlayer(RemotePlayer *player, bool *new_player, session_t peer_id,
227                 bool is_singleplayer);
228         void addPlayer(RemotePlayer *player);
229         void removePlayer(RemotePlayer *player);
230         bool removePlayerFromDatabase(const std::string &name);
231
232         /*
233                 Save and load time of day and game timer
234         */
235         void saveMeta();
236         void loadMeta();
237
238         u32 addParticleSpawner(float exptime);
239         u32 addParticleSpawner(float exptime, u16 attached_id);
240         void deleteParticleSpawner(u32 id, bool remove_from_object = true);
241
242         /*
243                 External ActiveObject interface
244                 -------------------------------------------
245         */
246
247         ServerActiveObject* getActiveObject(u16 id)
248         {
249                 return m_ao_manager.getActiveObject(id);
250         }
251
252         /*
253                 Add an active object to the environment.
254                 Environment handles deletion of object.
255                 Object may be deleted by environment immediately.
256                 If id of object is 0, assigns a free id to it.
257                 Returns the id of the object.
258                 Returns 0 if not added and thus deleted.
259         */
260         u16 addActiveObject(ServerActiveObject *object);
261
262         /*
263                 Add an active object as a static object to the corresponding
264                 MapBlock.
265                 Caller allocates memory, ServerEnvironment frees memory.
266                 Return value: true if succeeded, false if failed.
267                 (note:  not used, pending removal from engine)
268         */
269         //bool addActiveObjectAsStatic(ServerActiveObject *object);
270
271         /*
272                 Find out what new objects have been added to
273                 inside a radius around a position
274         */
275         void getAddedActiveObjects(PlayerSAO *playersao, s16 radius,
276                 s16 player_radius,
277                 std::set<u16> &current_objects,
278                 std::queue<u16> &added_objects);
279
280         /*
281                 Find out what new objects have been removed from
282                 inside a radius around a position
283         */
284         void getRemovedActiveObjects(PlayerSAO *playersao, s16 radius,
285                 s16 player_radius,
286                 std::set<u16> &current_objects,
287                 std::queue<u16> &removed_objects);
288
289         /*
290                 Get the next message emitted by some active object.
291                 Returns a message with id=0 if no messages are available.
292         */
293         ActiveObjectMessage getActiveObjectMessage();
294
295         virtual void getSelectedActiveObjects(
296                 const core::line3d<f32> &shootline_on_map,
297                 std::vector<PointedThing> &objects
298         );
299
300         /*
301                 Activate objects and dynamically modify for the dtime determined
302                 from timestamp and additional_dtime
303         */
304         void activateBlock(MapBlock *block, u32 additional_dtime=0);
305
306         /*
307                 {Active,Loading}BlockModifiers
308                 -------------------------------------------
309         */
310
311         void addActiveBlockModifier(ActiveBlockModifier *abm);
312         void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
313
314         /*
315                 Other stuff
316                 -------------------------------------------
317         */
318
319         // Script-aware node setters
320         bool setNode(v3s16 p, const MapNode &n);
321         bool removeNode(v3s16 p);
322         bool swapNode(v3s16 p, const MapNode &n);
323
324         // Find all active objects inside a radius around a point
325         void getObjectsInsideRadius(std::vector<u16> &objects, const v3f &pos, float radius)
326         {
327                 return m_ao_manager.getObjectsInsideRadius(pos, radius, objects);
328         }
329
330         // Clear objects, loading and going through every MapBlock
331         void clearObjects(ClearObjectsMode mode);
332
333         // This makes stuff happen
334         void step(f32 dtime);
335
336         /*!
337          * Returns false if the given line intersects with a
338          * non-air node, true otherwise.
339          * \param pos1 start of the line
340          * \param pos2 end of the line
341          * \param p output, position of the first non-air node
342          * the line intersects
343          */
344         bool line_of_sight(v3f pos1, v3f pos2, v3s16 *p = NULL);
345
346         u32 getGameTime() const { return m_game_time; }
347
348         void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
349         float getMaxLagEstimate() { return m_max_lag_estimate; }
350
351         std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
352
353         // Sets the static object status all the active objects in the specified block
354         // This is only really needed for deleting blocks from the map
355         void setStaticForActiveObjectsInBlock(v3s16 blockpos,
356                 bool static_exists, v3s16 static_block=v3s16(0,0,0));
357
358         RemotePlayer *getPlayer(const session_t peer_id);
359         RemotePlayer *getPlayer(const char* name);
360         u32 getPlayerCount() const { return m_players.size(); }
361
362         static bool migratePlayersDatabase(const GameParams &game_params,
363                         const Settings &cmd_args);
364
365         AuthDatabase *getAuthDatabase() { return m_auth_database; }
366         static bool migrateAuthDatabase(const GameParams &game_params,
367                         const Settings &cmd_args);
368 private:
369
370         /**
371          * called if env_meta.txt doesn't exist (e.g. new world)
372          */
373         void loadDefaultMeta();
374
375         static PlayerDatabase *openPlayerDatabase(const std::string &name,
376                         const std::string &savedir, const Settings &conf);
377         static AuthDatabase *openAuthDatabase(const std::string &name,
378                         const std::string &savedir, const Settings &conf);
379         /*
380                 Internal ActiveObject interface
381                 -------------------------------------------
382         */
383
384         /*
385                 Add an active object to the environment.
386
387                 Called by addActiveObject.
388
389                 Object may be deleted by environment immediately.
390                 If id of object is 0, assigns a free id to it.
391                 Returns the id of the object.
392                 Returns 0 if not added and thus deleted.
393         */
394         u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
395
396         /*
397                 Remove all objects that satisfy (isGone() && m_known_by_count==0)
398         */
399         void removeRemovedObjects();
400
401         /*
402                 Convert stored objects from block to active
403         */
404         void activateObjects(MapBlock *block, u32 dtime_s);
405
406         /*
407                 Convert objects that are not in active blocks to static.
408
409                 If m_known_by_count != 0, active object is not deleted, but static
410                 data is still updated.
411
412                 If force_delete is set, active object is deleted nevertheless. It
413                 shall only be set so in the destructor of the environment.
414         */
415         void deactivateFarObjects(bool force_delete);
416
417         /*
418                 A few helpers used by the three above methods
419         */
420         void deleteStaticFromBlock(
421                         ServerActiveObject *obj, u16 id, u32 mod_reason, bool no_emerge);
422         bool saveStaticToBlock(v3s16 blockpos, u16 store_id,
423                         ServerActiveObject *obj, const StaticObject &s_obj, u32 mod_reason);
424
425         /*
426                 Member variables
427         */
428
429         // The map
430         ServerMap *m_map;
431         // Lua state
432         ServerScripting* m_script;
433         // Server definition
434         Server *m_server;
435         // Active Object Manager
436         server::ActiveObjectMgr m_ao_manager;
437         // World path
438         const std::string m_path_world;
439         // Outgoing network message buffer for active objects
440         std::queue<ActiveObjectMessage> m_active_object_messages;
441         // Some timers
442         float m_send_recommended_timer = 0.0f;
443         IntervalLimiter m_object_management_interval;
444         // List of active blocks
445         ActiveBlockList m_active_blocks;
446         IntervalLimiter m_active_blocks_management_interval;
447         IntervalLimiter m_active_block_modifier_interval;
448         IntervalLimiter m_active_blocks_nodemetadata_interval;
449         int m_active_block_interval_overload_skip = 0;
450         // Time from the beginning of the game in seconds.
451         // Incremented in step().
452         u32 m_game_time = 0;
453         // A helper variable for incrementing the latter
454         float m_game_time_fraction_counter = 0.0f;
455         // Time of last clearObjects call (game time).
456         // When a mapblock older than this is loaded, its objects are cleared.
457         u32 m_last_clear_objects_time = 0;
458         // Active block modifiers
459         std::vector<ABMWithState> m_abms;
460         LBMManager m_lbm_mgr;
461         // An interval for generally sending object positions and stuff
462         float m_recommended_send_interval = 0.1f;
463         // Estimate for general maximum lag as determined by server.
464         // Can raise to high values like 15s with eg. map generation mods.
465         float m_max_lag_estimate = 0.1f;
466
467         // peer_ids in here should be unique, except that there may be many 0s
468         std::vector<RemotePlayer*> m_players;
469
470         PlayerDatabase *m_player_database = nullptr;
471         AuthDatabase *m_auth_database = nullptr;
472
473         // Particles
474         IntervalLimiter m_particle_management_interval;
475         std::unordered_map<u32, float> m_particle_spawners;
476         std::unordered_map<u32, u16> m_particle_spawner_attachments;
477 };