3 Copyright (C) 2010-2017 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
22 #include "activeobject.h"
23 #include "environment.h"
26 #include "util/numeric.h"
36 class ServerEnvironment;
37 class ActiveBlockModifier;
39 class ServerActiveObject;
41 class ServerScripting;
44 {Active, Loading} block modifier interface.
46 These are fed into ServerEnvironment at initialization time;
47 ServerEnvironment handles deleting them.
50 class ActiveBlockModifier
53 ActiveBlockModifier() = default;
54 virtual ~ActiveBlockModifier() = default;
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){};
75 ActiveBlockModifier *abm;
78 ABMWithState(ActiveBlockModifier *abm_);
81 struct LoadingBlockModifierDef
83 // Set of contents to trigger on
84 std::set<std::string> trigger_contents;
86 bool run_at_every_load = false;
88 virtual ~LoadingBlockModifierDef() = default;
90 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
93 struct LBMContentMapping
95 typedef std::unordered_map<content_t, std::vector<LoadingBlockModifierDef *>> lbm_map;
98 std::vector<LoadingBlockModifierDef *> lbm_list;
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;
111 LBMManager() = default;
114 // Don't call this after loadIntroductionTimes() ran.
115 void addLBMDef(LoadingBlockModifierDef *lbm_def);
117 void loadIntroductionTimes(const std::string ×,
118 IGameDef *gamedef, u32 now);
120 // Don't call this before loadIntroductionTimes() ran.
121 std::string createIntroductionTimesString();
123 // Don't call this before loadIntroductionTimes() ran.
124 void applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp);
126 // Warning: do not make this std::unordered_map, order is relevant here
127 typedef std::map<u32, LBMContentMapping> lbm_lookup_map;
130 // Once we set this to true, we can only query,
132 bool m_query_mode = false;
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;
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;
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); }
151 List of active blocks, used by ServerEnvironment
154 class ActiveBlockList
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);
163 bool contains(v3s16 p){
164 return (m_list.find(p) != m_list.end());
171 std::set<v3s16> m_list;
172 std::set<v3s16> m_abm_list;
173 std::set<v3s16> m_forceloaded_list;
179 Operation mode for ServerEnvironment::clearObjects()
181 enum ClearObjectsMode {
182 // Load and go through every mapblock, clearing objects
183 CLEAR_OBJECTS_MODE_FULL,
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,
191 The server-side environment.
193 This is not thread-safe. Server uses an environment mutex.
196 typedef std::unordered_map<u16, ServerActiveObject *> ServerActiveObjectMap;
198 class ServerEnvironment : public Environment
201 ServerEnvironment(ServerMap *map, ServerScripting *scriptIface,
202 Server *server, const std::string &path_world);
203 ~ServerEnvironment();
207 ServerMap & getServerMap();
209 //TODO find way to remove this fct!
210 ServerScripting* getScriptIface()
216 float getSendRecommendedInterval()
217 { return m_recommended_send_interval; }
219 void kickAllPlayers(AccessDeniedCode reason,
220 const std::string &str_reason, bool reconnect);
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);
231 Save and load time of day and game timer
235 // to be called instead of loadMeta if
236 // env_meta.txt doesn't exist (e.g. new world)
237 void loadDefaultMeta();
239 u32 addParticleSpawner(float exptime);
240 u32 addParticleSpawner(float exptime, u16 attached_id);
241 void deleteParticleSpawner(u32 id, bool remove_from_object = true);
244 External ActiveObject interface
245 -------------------------------------------
248 ServerActiveObject* getActiveObject(u16 id);
251 Add an active object to the environment.
252 Environment handles deletion of object.
253 Object may be deleted by environment immediately.
254 If id of object is 0, assigns a free id to it.
255 Returns the id of the object.
256 Returns 0 if not added and thus deleted.
258 u16 addActiveObject(ServerActiveObject *object);
261 Add an active object as a static object to the corresponding
263 Caller allocates memory, ServerEnvironment frees memory.
264 Return value: true if succeeded, false if failed.
265 (note: not used, pending removal from engine)
267 //bool addActiveObjectAsStatic(ServerActiveObject *object);
270 Find out what new objects have been added to
271 inside a radius around a position
273 void getAddedActiveObjects(PlayerSAO *playersao, s16 radius,
275 std::set<u16> ¤t_objects,
276 std::queue<u16> &added_objects);
279 Find out what new objects have been removed from
280 inside a radius around a position
282 void getRemovedActiveObjects(PlayerSAO *playersao, s16 radius,
284 std::set<u16> ¤t_objects,
285 std::queue<u16> &removed_objects);
288 Get the next message emitted by some active object.
289 Returns a message with id=0 if no messages are available.
291 ActiveObjectMessage getActiveObjectMessage();
293 virtual void getSelectedActiveObjects(
294 const core::line3d<f32> &shootline_on_map,
295 std::vector<PointedThing> &objects
299 Activate objects and dynamically modify for the dtime determined
300 from timestamp and additional_dtime
302 void activateBlock(MapBlock *block, u32 additional_dtime=0);
305 {Active,Loading}BlockModifiers
306 -------------------------------------------
309 void addActiveBlockModifier(ActiveBlockModifier *abm);
310 void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
314 -------------------------------------------
317 // Script-aware node setters
318 bool setNode(v3s16 p, const MapNode &n);
319 bool removeNode(v3s16 p);
320 bool swapNode(v3s16 p, const MapNode &n);
322 // Find all active objects inside a radius around a point
323 void getObjectsInsideRadius(std::vector<u16> &objects, v3f pos, float radius);
325 // Clear objects, loading and going through every MapBlock
326 void clearObjects(ClearObjectsMode mode);
328 // This makes stuff happen
329 void step(f32 dtime);
331 //check if there's a line of sight between two positions
332 bool line_of_sight(v3f pos1, v3f pos2, float stepsize=1.0, v3s16 *p=NULL);
334 u32 getGameTime() const { return m_game_time; }
336 void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
337 float getMaxLagEstimate() { return m_max_lag_estimate; }
339 std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
341 // Sets the static object status all the active objects in the specified block
342 // This is only really needed for deleting blocks from the map
343 void setStaticForActiveObjectsInBlock(v3s16 blockpos,
344 bool static_exists, v3s16 static_block=v3s16(0,0,0));
346 RemotePlayer *getPlayer(const session_t peer_id);
347 RemotePlayer *getPlayer(const char* name);
348 u32 getPlayerCount() const { return m_players.size(); }
350 static bool migratePlayersDatabase(const GameParams &game_params,
351 const Settings &cmd_args);
354 static PlayerDatabase *openPlayerDatabase(const std::string &name,
355 const std::string &savedir, const Settings &conf);
357 Internal ActiveObject interface
358 -------------------------------------------
362 Add an active object to the environment.
364 Called by addActiveObject.
366 Object may be deleted by environment immediately.
367 If id of object is 0, assigns a free id to it.
368 Returns the id of the object.
369 Returns 0 if not added and thus deleted.
371 u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
374 Remove all objects that satisfy (isGone() && m_known_by_count==0)
376 void removeRemovedObjects();
379 Convert stored objects from block to active
381 void activateObjects(MapBlock *block, u32 dtime_s);
384 Convert objects that are not in active blocks to static.
386 If m_known_by_count != 0, active object is not deleted, but static
387 data is still updated.
389 If force_delete is set, active object is deleted nevertheless. It
390 shall only be set so in the destructor of the environment.
392 void deactivateFarObjects(bool force_delete);
395 A few helpers used by the three above methods
397 void deleteStaticFromBlock(
398 ServerActiveObject *obj, u16 id, u32 mod_reason, bool no_emerge);
399 bool saveStaticToBlock(v3s16 blockpos, u16 store_id,
400 ServerActiveObject *obj, const StaticObject &s_obj, u32 mod_reason);
409 ServerScripting* m_script;
413 const std::string m_path_world;
414 // Active object list
415 ServerActiveObjectMap m_active_objects;
416 // Outgoing network message buffer for active objects
417 std::queue<ActiveObjectMessage> m_active_object_messages;
419 float m_send_recommended_timer = 0.0f;
420 IntervalLimiter m_object_management_interval;
421 // List of active blocks
422 ActiveBlockList m_active_blocks;
423 IntervalLimiter m_active_blocks_management_interval;
424 IntervalLimiter m_active_block_modifier_interval;
425 IntervalLimiter m_active_blocks_nodemetadata_interval;
426 int m_active_block_interval_overload_skip = 0;
427 // Time from the beginning of the game in seconds.
428 // Incremented in step().
430 // A helper variable for incrementing the latter
431 float m_game_time_fraction_counter = 0.0f;
432 // Time of last clearObjects call (game time).
433 // When a mapblock older than this is loaded, its objects are cleared.
434 u32 m_last_clear_objects_time = 0;
435 // Active block modifiers
436 std::vector<ABMWithState> m_abms;
437 LBMManager m_lbm_mgr;
438 // An interval for generally sending object positions and stuff
439 float m_recommended_send_interval = 0.1f;
440 // Estimate for general maximum lag as determined by server.
441 // Can raise to high values like 15s with eg. map generation mods.
442 float m_max_lag_estimate = 0.1f;
444 // peer_ids in here should be unique, except that there may be many 0s
445 std::vector<RemotePlayer*> m_players;
447 PlayerDatabase *m_player_database = nullptr;
450 IntervalLimiter m_particle_management_interval;
451 std::unordered_map<u32, float> m_particle_spawners;
452 std::unordered_map<u32, u16> m_particle_spawner_attachments;