serverenvironment.h 14 KB

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