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