serverenvironment.h 15 KB

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