serverenvironment.h 13 KB

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