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