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"
28 #include "util/metricsbackend.h"
40 class ServerEnvironment;
41 class ActiveBlockModifier;
43 class ServerActiveObject;
45 class ServerScripting;
48 {Active, Loading} block modifier interface.
50 These are fed into ServerEnvironment at initialization time;
51 ServerEnvironment handles deleting them.
54 class ActiveBlockModifier
57 ActiveBlockModifier() = default;
58 virtual ~ActiveBlockModifier() = default;
60 // Set of contents to trigger on
61 virtual const std::vector<std::string> &getTriggerContents() const = 0;
62 // Set of required neighbors (trigger doesn't happen if none are found)
63 // Empty = do not check neighbors
64 virtual const std::vector<std::string> &getRequiredNeighbors() const = 0;
65 // Trigger interval in seconds
66 virtual float getTriggerInterval() = 0;
67 // Random chance of (1 / return value), 0 is disallowed
68 virtual u32 getTriggerChance() = 0;
69 // Whether to modify chance to simulate time lost by an unnattended block
70 virtual bool getSimpleCatchUp() = 0;
71 // get min Y for apply abm
72 virtual s16 getMinY() = 0;
73 // get max Y for apply abm
74 virtual s16 getMaxY() = 0;
75 // This is called usually at interval for 1/chance of the nodes
76 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
77 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
78 u32 active_object_count, u32 active_object_count_wider){};
83 ActiveBlockModifier *abm;
86 ABMWithState(ActiveBlockModifier *abm_);
89 struct LoadingBlockModifierDef
91 // Set of contents to trigger on
92 std::set<std::string> trigger_contents;
94 bool run_at_every_load = false;
96 virtual ~LoadingBlockModifierDef() = default;
98 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
101 struct LBMContentMapping
103 typedef std::unordered_map<content_t, std::vector<LoadingBlockModifierDef *>> lbm_map;
106 std::vector<LoadingBlockModifierDef *> lbm_list;
108 // Needs to be separate method (not inside destructor),
109 // because the LBMContentMapping may be copied and destructed
110 // many times during operation in the lbm_lookup_map.
111 void deleteContents();
112 void addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef);
113 const std::vector<LoadingBlockModifierDef *> *lookup(content_t c) const;
119 LBMManager() = default;
122 // Don't call this after loadIntroductionTimes() ran.
123 void addLBMDef(LoadingBlockModifierDef *lbm_def);
125 void loadIntroductionTimes(const std::string ×,
126 IGameDef *gamedef, u32 now);
128 // Don't call this before loadIntroductionTimes() ran.
129 std::string createIntroductionTimesString();
131 // Don't call this before loadIntroductionTimes() ran.
132 void applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp);
134 // Warning: do not make this std::unordered_map, order is relevant here
135 typedef std::map<u32, LBMContentMapping> lbm_lookup_map;
138 // Once we set this to true, we can only query,
140 bool m_query_mode = false;
142 // For m_query_mode == false:
143 // The key of the map is the LBM def's name.
144 // TODO make this std::unordered_map
145 std::map<std::string, LoadingBlockModifierDef *> m_lbm_defs;
147 // For m_query_mode == true:
148 // The key of the map is the LBM def's first introduction time.
149 lbm_lookup_map m_lbm_lookup;
151 // Returns an iterator to the LBMs that were introduced
152 // after the given time. This is guaranteed to return
153 // valid values for everything
154 lbm_lookup_map::const_iterator getLBMsIntroducedAfter(u32 time)
155 { return m_lbm_lookup.lower_bound(time); }
159 List of active blocks, used by ServerEnvironment
162 class ActiveBlockList
165 void update(std::vector<PlayerSAO*> &active_players,
166 s16 active_block_range,
167 s16 active_object_range,
168 std::set<v3s16> &blocks_removed,
169 std::set<v3s16> &blocks_added);
171 bool contains(v3s16 p) const {
172 return (m_list.find(p) != m_list.end());
176 return m_list.size();
183 void remove(v3s16 p) {
188 std::set<v3s16> m_list;
189 std::set<v3s16> m_abm_list;
190 // list of blocks that are always active, not modified by this class
191 std::set<v3s16> m_forceloaded_list;
195 Operation mode for ServerEnvironment::clearObjects()
197 enum ClearObjectsMode {
198 // Load and go through every mapblock, clearing objects
199 CLEAR_OBJECTS_MODE_FULL,
201 // Clear objects immediately in loaded mapblocks;
202 // clear objects in unloaded mapblocks only when the mapblocks are next activated.
203 CLEAR_OBJECTS_MODE_QUICK,
206 class ServerEnvironment final : public Environment
209 ServerEnvironment(ServerMap *map, ServerScripting *script_iface,
210 Server *server, const std::string &path_world, MetricsBackend *mb);
211 ~ServerEnvironment();
217 ServerMap & getServerMap();
219 //TODO find way to remove this fct!
220 ServerScripting* getScriptIface()
226 float getSendRecommendedInterval()
227 { return m_recommended_send_interval; }
229 void kickAllPlayers(AccessDeniedCode reason,
230 const std::string &str_reason, bool reconnect);
232 void saveLoadedPlayers(bool force = false);
233 void savePlayer(RemotePlayer *player);
234 PlayerSAO *loadPlayer(RemotePlayer *player, bool *new_player, session_t peer_id,
235 bool is_singleplayer);
236 void addPlayer(RemotePlayer *player);
237 void removePlayer(RemotePlayer *player);
238 bool removePlayerFromDatabase(const std::string &name);
241 Save and load time of day and game timer
246 u32 addParticleSpawner(float exptime);
247 u32 addParticleSpawner(float exptime, u16 attached_id);
248 void deleteParticleSpawner(u32 id, bool remove_from_object = true);
251 External ActiveObject interface
252 -------------------------------------------
255 ServerActiveObject* getActiveObject(u16 id)
257 return m_ao_manager.getActiveObject(id);
261 Add an active object to the environment.
262 Environment handles deletion of object.
263 Object may be deleted by environment immediately.
264 If id of object is 0, assigns a free id to it.
265 Returns the id of the object.
266 Returns 0 if not added and thus deleted.
268 u16 addActiveObject(ServerActiveObject *object);
271 Add an active object as a static object to the corresponding
273 Caller allocates memory, ServerEnvironment frees memory.
274 Return value: true if succeeded, false if failed.
275 (note: not used, pending removal from engine)
277 //bool addActiveObjectAsStatic(ServerActiveObject *object);
280 Find out what new objects have been added to
281 inside a radius around a position
283 void getAddedActiveObjects(PlayerSAO *playersao, s16 radius,
285 std::set<u16> ¤t_objects,
286 std::queue<u16> &added_objects);
289 Find out what new objects have been removed from
290 inside a radius around a position
292 void getRemovedActiveObjects(PlayerSAO *playersao, s16 radius,
294 std::set<u16> ¤t_objects,
295 std::queue<u16> &removed_objects);
298 Get the next message emitted by some active object.
299 Returns false if no messages are available, true otherwise.
301 bool getActiveObjectMessage(ActiveObjectMessage *dest);
303 virtual void getSelectedActiveObjects(
304 const core::line3d<f32> &shootline_on_map,
305 std::vector<PointedThing> &objects
309 Activate objects and dynamically modify for the dtime determined
310 from timestamp and additional_dtime
312 void activateBlock(MapBlock *block, u32 additional_dtime=0);
315 {Active,Loading}BlockModifiers
316 -------------------------------------------
319 void addActiveBlockModifier(ActiveBlockModifier *abm);
320 void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
324 -------------------------------------------
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);
332 // Find the daylight value at pos with a Depth First Search
333 u8 findSunlight(v3s16 pos) const;
335 // Find all active objects inside a radius around a point
336 void getObjectsInsideRadius(std::vector<ServerActiveObject *> &objects, const v3f &pos, float radius,
337 std::function<bool(ServerActiveObject *obj)> include_obj_cb)
339 return m_ao_manager.getObjectsInsideRadius(pos, radius, objects, include_obj_cb);
342 // Find all active objects inside a box
343 void getObjectsInArea(std::vector<ServerActiveObject *> &objects, const aabb3f &box,
344 std::function<bool(ServerActiveObject *obj)> include_obj_cb)
346 return m_ao_manager.getObjectsInArea(box, objects, include_obj_cb);
349 // Clear objects, loading and going through every MapBlock
350 void clearObjects(ClearObjectsMode mode);
352 // This makes stuff happen
353 void step(f32 dtime);
355 u32 getGameTime() const { return m_game_time; }
357 void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
358 float getMaxLagEstimate() { return m_max_lag_estimate; }
360 std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; }
362 // Sorted by how ready a mapblock is
367 BS_ACTIVE // always highest value
369 BlockStatus getBlockStatus(v3s16 blockpos);
371 // Sets the static object status all the active objects in the specified block
372 // This is only really needed for deleting blocks from the map
373 void setStaticForActiveObjectsInBlock(v3s16 blockpos,
374 bool static_exists, v3s16 static_block=v3s16(0,0,0));
376 RemotePlayer *getPlayer(const session_t peer_id);
377 RemotePlayer *getPlayer(const char* name);
378 const std::vector<RemotePlayer *> getPlayers() const { return m_players; }
379 u32 getPlayerCount() const { return m_players.size(); }
381 static bool migratePlayersDatabase(const GameParams &game_params,
382 const Settings &cmd_args);
384 AuthDatabase *getAuthDatabase() { return m_auth_database; }
385 static bool migrateAuthDatabase(const GameParams &game_params,
386 const Settings &cmd_args);
390 * called if env_meta.txt doesn't exist (e.g. new world)
392 void loadDefaultMeta();
394 static PlayerDatabase *openPlayerDatabase(const std::string &name,
395 const std::string &savedir, const Settings &conf);
396 static AuthDatabase *openAuthDatabase(const std::string &name,
397 const std::string &savedir, const Settings &conf);
399 Internal ActiveObject interface
400 -------------------------------------------
404 Add an active object to the environment.
406 Called by addActiveObject.
408 Object may be deleted by environment immediately.
409 If id of object is 0, assigns a free id to it.
410 Returns the id of the object.
411 Returns 0 if not added and thus deleted.
413 u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
416 Remove all objects that satisfy (isGone() && m_known_by_count==0)
418 void removeRemovedObjects();
421 Convert stored objects from block to active
423 void activateObjects(MapBlock *block, u32 dtime_s);
426 Convert objects that are not in active blocks to static.
428 If m_known_by_count != 0, active object is not deleted, but static
429 data is still updated.
431 If force_delete is set, active object is deleted nevertheless. It
432 shall only be set so in the destructor of the environment.
434 void deactivateFarObjects(bool force_delete);
437 A few helpers used by the three above methods
439 void deleteStaticFromBlock(
440 ServerActiveObject *obj, u16 id, u32 mod_reason, bool no_emerge);
441 bool saveStaticToBlock(v3s16 blockpos, u16 store_id,
442 ServerActiveObject *obj, const StaticObject &s_obj, u32 mod_reason);
451 ServerScripting* m_script;
454 // Active Object Manager
455 server::ActiveObjectMgr m_ao_manager;
457 const std::string m_path_world;
458 // Outgoing network message buffer for active objects
459 std::queue<ActiveObjectMessage> m_active_object_messages;
461 float m_send_recommended_timer = 0.0f;
462 IntervalLimiter m_object_management_interval;
463 // List of active blocks
464 ActiveBlockList m_active_blocks;
465 int m_fast_active_block_divider = 1;
466 IntervalLimiter m_active_blocks_mgmt_interval;
467 IntervalLimiter m_active_block_modifier_interval;
468 IntervalLimiter m_active_blocks_nodemetadata_interval;
469 // Whether the variables below have been read from file yet
470 bool m_meta_loaded = false;
471 // Time from the beginning of the game in seconds.
472 // Incremented in step().
474 // A helper variable for incrementing the latter
475 float m_game_time_fraction_counter = 0.0f;
476 // Time of last clearObjects call (game time).
477 // When a mapblock older than this is loaded, its objects are cleared.
478 u32 m_last_clear_objects_time = 0;
479 // Active block modifiers
480 std::vector<ABMWithState> m_abms;
481 LBMManager m_lbm_mgr;
482 // An interval for generally sending object positions and stuff
483 float m_recommended_send_interval = 0.1f;
484 // Estimate for general maximum lag as determined by server.
485 // Can raise to high values like 15s with eg. map generation mods.
486 float m_max_lag_estimate = 0.1f;
488 // peer_ids in here should be unique, except that there may be many 0s
489 std::vector<RemotePlayer*> m_players;
491 PlayerDatabase *m_player_database = nullptr;
492 AuthDatabase *m_auth_database = nullptr;
494 // Pseudo random generator for shuffling, etc.
498 IntervalLimiter m_particle_management_interval;
499 std::unordered_map<u32, float> m_particle_spawners;
500 std::unordered_map<u32, u16> m_particle_spawner_attachments;
502 // Environment metrics
503 MetricCounterPtr m_step_time_counter;
504 MetricGaugePtr m_active_block_gauge;
505 MetricGaugePtr m_active_object_gauge;
507 ServerActiveObject* createSAO(ActiveObjectType type, v3f pos, const std::string &data);