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