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