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 "server/activeobjectmgr.h"
27 #include "util/numeric.h"
38 class ServerEnvironment;
39 class ActiveBlockModifier;
41 class ServerActiveObject;
43 class ServerScripting;
46 {Active, Loading} block modifier interface.
48 These are fed into ServerEnvironment at initialization time;
49 ServerEnvironment handles deleting them.
52 class ActiveBlockModifier
55 ActiveBlockModifier() = default;
56 virtual ~ActiveBlockModifier() = default;
58 // Set of contents to trigger on
59 virtual const std::vector<std::string> &getTriggerContents() const = 0;
60 // Set of required neighbors (trigger doesn't happen if none are found)
61 // Empty = do not check neighbors
62 virtual const std::vector<std::string> &getRequiredNeighbors() const = 0;
63 // Trigger interval in seconds
64 virtual float getTriggerInterval() = 0;
65 // Random chance of (1 / return value), 0 is disallowed
66 virtual u32 getTriggerChance() = 0;
67 // Whether to modify chance to simulate time lost by an unnattended block
68 virtual bool getSimpleCatchUp() = 0;
69 // This is called usually at interval for 1/chance of the nodes
70 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
71 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
72 u32 active_object_count, u32 active_object_count_wider){};
77 ActiveBlockModifier *abm;
80 ABMWithState(ActiveBlockModifier *abm_);
83 struct LoadingBlockModifierDef
85 // Set of contents to trigger on
86 std::set<std::string> trigger_contents;
88 bool run_at_every_load = false;
90 virtual ~LoadingBlockModifierDef() = default;
92 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
95 struct LBMContentMapping
97 typedef std::unordered_map<content_t, std::vector<LoadingBlockModifierDef *>> lbm_map;
100 std::vector<LoadingBlockModifierDef *> lbm_list;
102 // Needs to be separate method (not inside destructor),
103 // because the LBMContentMapping may be copied and destructed
104 // many times during operation in the lbm_lookup_map.
105 void deleteContents();
106 void addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef);
107 const std::vector<LoadingBlockModifierDef *> *lookup(content_t c) const;
113 LBMManager() = default;
116 // Don't call this after loadIntroductionTimes() ran.
117 void addLBMDef(LoadingBlockModifierDef *lbm_def);
119 void loadIntroductionTimes(const std::string ×,
120 IGameDef *gamedef, u32 now);
122 // Don't call this before loadIntroductionTimes() ran.
123 std::string createIntroductionTimesString();
125 // Don't call this before loadIntroductionTimes() ran.
126 void applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp);
128 // Warning: do not make this std::unordered_map, order is relevant here
129 typedef std::map<u32, LBMContentMapping> lbm_lookup_map;
132 // Once we set this to true, we can only query,
134 bool m_query_mode = false;
136 // For m_query_mode == false:
137 // The key of the map is the LBM def's name.
138 // TODO make this std::unordered_map
139 std::map<std::string, LoadingBlockModifierDef *> m_lbm_defs;
141 // For m_query_mode == true:
142 // The key of the map is the LBM def's first introduction time.
143 lbm_lookup_map m_lbm_lookup;
145 // Returns an iterator to the LBMs that were introduced
146 // after the given time. This is guaranteed to return
147 // valid values for everything
148 lbm_lookup_map::const_iterator getLBMsIntroducedAfter(u32 time)
149 { return m_lbm_lookup.lower_bound(time); }
153 List of active blocks, used by ServerEnvironment
156 class ActiveBlockList
159 void update(std::vector<PlayerSAO*> &active_players,
160 s16 active_block_range,
161 s16 active_object_range,
162 std::set<v3s16> &blocks_removed,
163 std::set<v3s16> &blocks_added);
165 bool contains(v3s16 p){
166 return (m_list.find(p) != m_list.end());
173 std::set<v3s16> m_list;
174 std::set<v3s16> m_abm_list;
175 std::set<v3s16> m_forceloaded_list;
181 Operation mode for ServerEnvironment::clearObjects()
183 enum ClearObjectsMode {
184 // Load and go through every mapblock, clearing objects
185 CLEAR_OBJECTS_MODE_FULL,
187 // Clear objects immediately in loaded mapblocks;
188 // clear objects in unloaded mapblocks only when the mapblocks are next activated.
189 CLEAR_OBJECTS_MODE_QUICK,
193 The server-side environment.
195 This is not thread-safe. Server uses an environment mutex.
198 typedef std::unordered_map<u16, ServerActiveObject *> ServerActiveObjectMap;
200 class ServerEnvironment : public Environment
203 ServerEnvironment(ServerMap *map, ServerScripting *scriptIface,
204 Server *server, const std::string &path_world);
205 ~ServerEnvironment();
209 ServerMap & getServerMap();
211 //TODO find way to remove this fct!
212 ServerScripting* getScriptIface()
218 float getSendRecommendedInterval()
219 { return m_recommended_send_interval; }
221 void kickAllPlayers(AccessDeniedCode reason,
222 const std::string &str_reason, bool reconnect);
224 void saveLoadedPlayers();
225 void savePlayer(RemotePlayer *player);
226 PlayerSAO *loadPlayer(RemotePlayer *player, bool *new_player, session_t peer_id,
227 bool is_singleplayer);
228 void addPlayer(RemotePlayer *player);
229 void removePlayer(RemotePlayer *player);
230 bool removePlayerFromDatabase(const std::string &name);
233 Save and load time of day and game timer
238 u32 addParticleSpawner(float exptime);
239 u32 addParticleSpawner(float exptime, u16 attached_id);
240 void deleteParticleSpawner(u32 id, bool remove_from_object = true);
243 External ActiveObject interface
244 -------------------------------------------
247 ServerActiveObject* getActiveObject(u16 id)
249 return m_ao_manager.getActiveObject(id);
253 Add an active object to the environment.
254 Environment handles deletion of object.
255 Object may be deleted by environment immediately.
256 If id of object is 0, assigns a free id to it.
257 Returns the id of the object.
258 Returns 0 if not added and thus deleted.
260 u16 addActiveObject(ServerActiveObject *object);
263 Add an active object as a static object to the corresponding
265 Caller allocates memory, ServerEnvironment frees memory.
266 Return value: true if succeeded, false if failed.
267 (note: not used, pending removal from engine)
269 //bool addActiveObjectAsStatic(ServerActiveObject *object);
272 Find out what new objects have been added to
273 inside a radius around a position
275 void getAddedActiveObjects(PlayerSAO *playersao, s16 radius,
277 std::set<u16> ¤t_objects,
278 std::queue<u16> &added_objects);
281 Find out what new objects have been removed from
282 inside a radius around a position
284 void getRemovedActiveObjects(PlayerSAO *playersao, s16 radius,
286 std::set<u16> ¤t_objects,
287 std::queue<u16> &removed_objects);
290 Get the next message emitted by some active object.
291 Returns a message with id=0 if no messages are available.
293 ActiveObjectMessage getActiveObjectMessage();
295 virtual void getSelectedActiveObjects(
296 const core::line3d<f32> &shootline_on_map,
297 std::vector<PointedThing> &objects
301 Activate objects and dynamically modify for the dtime determined
302 from timestamp and additional_dtime
304 void activateBlock(MapBlock *block, u32 additional_dtime=0);
307 {Active,Loading}BlockModifiers
308 -------------------------------------------
311 void addActiveBlockModifier(ActiveBlockModifier *abm);
312 void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
316 -------------------------------------------
319 // Script-aware node setters
320 bool setNode(v3s16 p, const MapNode &n);
321 bool removeNode(v3s16 p);
322 bool swapNode(v3s16 p, const MapNode &n);
324 // Find all active objects inside a radius around a point
325 void getObjectsInsideRadius(std::vector<u16> &objects, const v3f &pos, float radius)
327 return m_ao_manager.getObjectsInsideRadius(pos, radius, objects);
330 // Clear objects, loading and going through every MapBlock
331 void clearObjects(ClearObjectsMode mode);
333 // This makes stuff happen
334 void step(f32 dtime);
337 * Returns false if the given line intersects with a
338 * non-air node, true otherwise.
339 * \param pos1 start of the line
340 * \param pos2 end of the line
341 * \param p output, position of the first non-air node
342 * the line intersects
344 bool line_of_sight(v3f pos1, v3f pos2, v3s16 *p = NULL);
346 u32 getGameTime() const { return m_game_time; }
348 void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
349 float getMaxLagEstimate() { return m_max_lag_estimate; }
351 std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
353 // Sets the static object status all the active objects in the specified block
354 // This is only really needed for deleting blocks from the map
355 void setStaticForActiveObjectsInBlock(v3s16 blockpos,
356 bool static_exists, v3s16 static_block=v3s16(0,0,0));
358 RemotePlayer *getPlayer(const session_t peer_id);
359 RemotePlayer *getPlayer(const char* name);
360 u32 getPlayerCount() const { return m_players.size(); }
362 static bool migratePlayersDatabase(const GameParams &game_params,
363 const Settings &cmd_args);
365 AuthDatabase *getAuthDatabase() { return m_auth_database; }
366 static bool migrateAuthDatabase(const GameParams &game_params,
367 const Settings &cmd_args);
371 * called if env_meta.txt doesn't exist (e.g. new world)
373 void loadDefaultMeta();
375 static PlayerDatabase *openPlayerDatabase(const std::string &name,
376 const std::string &savedir, const Settings &conf);
377 static AuthDatabase *openAuthDatabase(const std::string &name,
378 const std::string &savedir, const Settings &conf);
380 Internal ActiveObject interface
381 -------------------------------------------
385 Add an active object to the environment.
387 Called by addActiveObject.
389 Object may be deleted by environment immediately.
390 If id of object is 0, assigns a free id to it.
391 Returns the id of the object.
392 Returns 0 if not added and thus deleted.
394 u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
397 Remove all objects that satisfy (isGone() && m_known_by_count==0)
399 void removeRemovedObjects();
402 Convert stored objects from block to active
404 void activateObjects(MapBlock *block, u32 dtime_s);
407 Convert objects that are not in active blocks to static.
409 If m_known_by_count != 0, active object is not deleted, but static
410 data is still updated.
412 If force_delete is set, active object is deleted nevertheless. It
413 shall only be set so in the destructor of the environment.
415 void deactivateFarObjects(bool force_delete);
418 A few helpers used by the three above methods
420 void deleteStaticFromBlock(
421 ServerActiveObject *obj, u16 id, u32 mod_reason, bool no_emerge);
422 bool saveStaticToBlock(v3s16 blockpos, u16 store_id,
423 ServerActiveObject *obj, const StaticObject &s_obj, u32 mod_reason);
432 ServerScripting* m_script;
435 // Active Object Manager
436 server::ActiveObjectMgr m_ao_manager;
438 const std::string m_path_world;
439 // Outgoing network message buffer for active objects
440 std::queue<ActiveObjectMessage> m_active_object_messages;
442 float m_send_recommended_timer = 0.0f;
443 IntervalLimiter m_object_management_interval;
444 // List of active blocks
445 ActiveBlockList m_active_blocks;
446 IntervalLimiter m_active_blocks_management_interval;
447 IntervalLimiter m_active_block_modifier_interval;
448 IntervalLimiter m_active_blocks_nodemetadata_interval;
449 int m_active_block_interval_overload_skip = 0;
450 // Time from the beginning of the game in seconds.
451 // Incremented in step().
453 // A helper variable for incrementing the latter
454 float m_game_time_fraction_counter = 0.0f;
455 // Time of last clearObjects call (game time).
456 // When a mapblock older than this is loaded, its objects are cleared.
457 u32 m_last_clear_objects_time = 0;
458 // Active block modifiers
459 std::vector<ABMWithState> m_abms;
460 LBMManager m_lbm_mgr;
461 // An interval for generally sending object positions and stuff
462 float m_recommended_send_interval = 0.1f;
463 // Estimate for general maximum lag as determined by server.
464 // Can raise to high values like 15s with eg. map generation mods.
465 float m_max_lag_estimate = 0.1f;
467 // peer_ids in here should be unique, except that there may be many 0s
468 std::vector<RemotePlayer*> m_players;
470 PlayerDatabase *m_player_database = nullptr;
471 AuthDatabase *m_auth_database = nullptr;
474 IntervalLimiter m_particle_management_interval;
475 std::unordered_map<u32, float> m_particle_spawners;
476 std::unordered_map<u32, u16> m_particle_spawner_attachments;