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