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