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