3 Copyright (C) 2010-2013 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.
20 #ifndef ENVIRONMENT_HEADER
21 #define ENVIRONMENT_HEADER
24 This class is the game's environment.
29 - The current time in the game
38 #include "activeobject.h"
39 #include "util/numeric.h"
42 #include "threading/mutex.h"
43 #include "threading/atomic.h"
44 #include "network/networkprotocol.h" // for AccessDeniedCode
46 class ServerEnvironment;
47 class ActiveBlockModifier;
48 class ServerActiveObject;
61 // Environment will delete the map passed to the constructor
63 virtual ~Environment();
66 Step everything in environment.
71 virtual void step(f32 dtime) = 0;
73 virtual Map & getMap() = 0;
75 u32 getDayNightRatio();
78 virtual void setTimeOfDay(u32 time);
80 float getTimeOfDayF();
82 void stepTimeOfDay(float dtime);
84 void setTimeOfDaySpeed(float speed);
86 void setDayNightRatioOverride(bool enable, u32 value);
90 // counter used internally when triggering ABMs
94 GenericAtomic<float> m_time_of_day_speed;
97 * Below: values managed by m_time_lock
99 // Time of day in milli-hours (0-23999); determines day and night
101 // Time of day in 0...1
102 float m_time_of_day_f;
103 // Stores the skew created by the float -> u32 conversion
104 // to be applied at next conversion, so that there is no real skew.
105 float m_time_conversion_skew;
106 // Overriding the day-night ratio is useful for custom sky visuals
107 bool m_enable_day_night_ratio_override;
108 u32 m_day_night_ratio_override;
109 // Days from the server start, accounts for time shift
110 // in game (e.g. /time or bed usage)
111 Atomic<u32> m_day_count;
113 * Above: values managed by m_time_lock
116 /* TODO: Add a callback function so these can be updated when a setting
117 * changes. At this point in time it doesn't matter (e.g. /set
118 * is documented to change server settings only)
120 * TODO: Local caching of settings is not optimal and should at some stage
121 * be updated to use a global settings object for getting thse values
122 * (as opposed to the this local caching). This can be addressed in
125 bool m_cache_enable_shaders;
126 float m_cache_active_block_mgmt_interval;
127 float m_cache_abm_interval;
128 float m_cache_nodetimer_interval;
133 DISABLE_CLASS_COPY(Environment);
137 {Active, Loading} block modifier interface.
139 These are fed into ServerEnvironment at initialization time;
140 ServerEnvironment handles deleting them.
143 class ActiveBlockModifier
146 ActiveBlockModifier(){};
147 virtual ~ActiveBlockModifier(){};
149 // Set of contents to trigger on
150 virtual std::set<std::string> getTriggerContents()=0;
151 // Set of required neighbors (trigger doesn't happen if none are found)
152 // Empty = do not check neighbors
153 virtual std::set<std::string> getRequiredNeighbors()
154 { return std::set<std::string>(); }
155 // Trigger interval in seconds
156 virtual float getTriggerInterval() = 0;
157 // Random chance of (1 / return value), 0 is disallowed
158 virtual u32 getTriggerChance() = 0;
159 // Whether to modify chance to simulate time lost by an unnattended block
160 virtual bool getSimpleCatchUp() = 0;
161 // This is called usually at interval for 1/chance of the nodes
162 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
163 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
164 u32 active_object_count, u32 active_object_count_wider){};
169 ActiveBlockModifier *abm;
172 ABMWithState(ActiveBlockModifier *abm_);
175 struct LoadingBlockModifierDef
177 // Set of contents to trigger on
178 std::set<std::string> trigger_contents;
180 bool run_at_every_load;
182 virtual ~LoadingBlockModifierDef() {}
183 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
186 struct LBMContentMapping
188 typedef std::map<content_t, std::vector<LoadingBlockModifierDef *> > container_map;
191 std::vector<LoadingBlockModifierDef *> lbm_list;
193 // Needs to be separate method (not inside destructor),
194 // because the LBMContentMapping may be copied and destructed
195 // many times during operation in the lbm_lookup_map.
196 void deleteContents();
197 void addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef);
198 const std::vector<LoadingBlockModifierDef *> *lookup(content_t c) const;
210 // Don't call this after loadIntroductionTimes() ran.
211 void addLBMDef(LoadingBlockModifierDef *lbm_def);
213 void loadIntroductionTimes(const std::string ×,
214 IGameDef *gamedef, u32 now);
216 // Don't call this before loadIntroductionTimes() ran.
217 std::string createIntroductionTimesString();
219 // Don't call this before loadIntroductionTimes() ran.
220 void applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp);
222 // Warning: do not make this std::unordered_map, order is relevant here
223 typedef std::map<u32, LBMContentMapping> lbm_lookup_map;
226 // Once we set this to true, we can only query,
230 // For m_query_mode == false:
231 // The key of the map is the LBM def's name.
232 // TODO make this std::unordered_map
233 std::map<std::string, LoadingBlockModifierDef *> m_lbm_defs;
235 // For m_query_mode == true:
236 // The key of the map is the LBM def's first introduction time.
237 lbm_lookup_map m_lbm_lookup;
239 // Returns an iterator to the LBMs that were introduced
240 // after the given time. This is guaranteed to return
241 // valid values for everything
242 lbm_lookup_map::const_iterator getLBMsIntroducedAfter(u32 time)
243 { return m_lbm_lookup.lower_bound(time); }
247 List of active blocks, used by ServerEnvironment
250 class ActiveBlockList
253 void update(std::vector<v3s16> &active_positions,
255 std::set<v3s16> &blocks_removed,
256 std::set<v3s16> &blocks_added);
258 bool contains(v3s16 p){
259 return (m_list.find(p) != m_list.end());
266 std::set<v3s16> m_list;
267 std::set<v3s16> m_forceloaded_list;
273 Operation mode for ServerEnvironment::clearObjects()
275 enum ClearObjectsMode {
276 // Load and go through every mapblock, clearing objects
277 CLEAR_OBJECTS_MODE_FULL,
279 // Clear objects immediately in loaded mapblocks;
280 // clear objects in unloaded mapblocks only when the mapblocks are next activated.
281 CLEAR_OBJECTS_MODE_QUICK,
285 The server-side environment.
287 This is not thread-safe. Server uses an environment mutex.
290 typedef UNORDERED_MAP<u16, ServerActiveObject *> ActiveObjectMap;
292 class ServerEnvironment : public Environment
295 ServerEnvironment(ServerMap *map, GameScripting *scriptIface,
296 IGameDef *gamedef, const std::string &path_world);
297 ~ServerEnvironment();
301 ServerMap & getServerMap();
303 //TODO find way to remove this fct!
304 GameScripting* getScriptIface()
307 IGameDef *getGameDef()
308 { return m_gamedef; }
310 float getSendRecommendedInterval()
311 { return m_recommended_send_interval; }
313 void kickAllPlayers(AccessDeniedCode reason,
314 const std::string &str_reason, bool reconnect);
316 void saveLoadedPlayers();
317 void savePlayer(RemotePlayer *player);
318 RemotePlayer *loadPlayer(const std::string &playername);
319 void addPlayer(RemotePlayer *player);
320 void removePlayer(RemotePlayer *player);
323 Save and load time of day and game timer
327 // to be called instead of loadMeta if
328 // env_meta.txt doesn't exist (e.g. new world)
329 void loadDefaultMeta();
331 u32 addParticleSpawner(float exptime);
332 u32 addParticleSpawner(float exptime, u16 attached_id);
333 void deleteParticleSpawner(u32 id, bool remove_from_object = true);
336 External ActiveObject interface
337 -------------------------------------------
340 ServerActiveObject* getActiveObject(u16 id);
343 Add an active object to the environment.
344 Environment handles deletion of object.
345 Object may be deleted by environment immediately.
346 If id of object is 0, assigns a free id to it.
347 Returns the id of the object.
348 Returns 0 if not added and thus deleted.
350 u16 addActiveObject(ServerActiveObject *object);
353 Add an active object as a static object to the corresponding
355 Caller allocates memory, ServerEnvironment frees memory.
356 Return value: true if succeeded, false if failed.
357 (note: not used, pending removal from engine)
359 //bool addActiveObjectAsStatic(ServerActiveObject *object);
362 Find out what new objects have been added to
363 inside a radius around a position
365 void getAddedActiveObjects(RemotePlayer *player, s16 radius,
367 std::set<u16> ¤t_objects,
368 std::queue<u16> &added_objects);
371 Find out what new objects have been removed from
372 inside a radius around a position
374 void getRemovedActiveObjects(RemotePlayer *player, s16 radius,
376 std::set<u16> ¤t_objects,
377 std::queue<u16> &removed_objects);
380 Get the next message emitted by some active object.
381 Returns a message with id=0 if no messages are available.
383 ActiveObjectMessage getActiveObjectMessage();
386 Activate objects and dynamically modify for the dtime determined
387 from timestamp and additional_dtime
389 void activateBlock(MapBlock *block, u32 additional_dtime=0);
392 {Active,Loading}BlockModifiers
393 -------------------------------------------
396 void addActiveBlockModifier(ActiveBlockModifier *abm);
397 void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
401 -------------------------------------------
404 // Script-aware node setters
405 bool setNode(v3s16 p, const MapNode &n);
406 bool removeNode(v3s16 p);
407 bool swapNode(v3s16 p, const MapNode &n);
409 // Find all active objects inside a radius around a point
410 void getObjectsInsideRadius(std::vector<u16> &objects, v3f pos, float radius);
412 // Clear objects, loading and going through every MapBlock
413 void clearObjects(ClearObjectsMode mode);
415 // This makes stuff happen
416 void step(f32 dtime);
418 //check if there's a line of sight between two positions
419 bool line_of_sight(v3f pos1, v3f pos2, float stepsize=1.0, v3s16 *p=NULL);
421 u32 getGameTime() { return m_game_time; }
423 void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
424 float getMaxLagEstimate() { return m_max_lag_estimate; }
426 std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
428 // Sets the static object status all the active objects in the specified block
429 // This is only really needed for deleting blocks from the map
430 void setStaticForActiveObjectsInBlock(v3s16 blockpos,
431 bool static_exists, v3s16 static_block=v3s16(0,0,0));
433 RemotePlayer *getPlayer(const u16 peer_id);
434 RemotePlayer *getPlayer(const char* name);
438 Internal ActiveObject interface
439 -------------------------------------------
443 Add an active object to the environment.
445 Called by addActiveObject.
447 Object may be deleted by environment immediately.
448 If id of object is 0, assigns a free id to it.
449 Returns the id of the object.
450 Returns 0 if not added and thus deleted.
452 u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
455 Remove all objects that satisfy (m_removed && m_known_by_count==0)
457 void removeRemovedObjects();
460 Convert stored objects from block to active
462 void activateObjects(MapBlock *block, u32 dtime_s);
465 Convert objects that are not in active blocks to static.
467 If m_known_by_count != 0, active object is not deleted, but static
468 data is still updated.
470 If force_delete is set, active object is deleted nevertheless. It
471 shall only be set so in the destructor of the environment.
473 void deactivateFarObjects(bool force_delete);
482 GameScripting* m_script;
486 const std::string m_path_world;
487 // Active object list
488 ActiveObjectMap m_active_objects;
489 // Outgoing network message buffer for active objects
490 std::queue<ActiveObjectMessage> m_active_object_messages;
492 float m_send_recommended_timer;
493 IntervalLimiter m_object_management_interval;
494 // List of active blocks
495 ActiveBlockList m_active_blocks;
496 IntervalLimiter m_active_blocks_management_interval;
497 IntervalLimiter m_active_block_modifier_interval;
498 IntervalLimiter m_active_blocks_nodemetadata_interval;
499 int m_active_block_interval_overload_skip;
500 // Time from the beginning of the game in seconds.
501 // Incremented in step().
503 // A helper variable for incrementing the latter
504 float m_game_time_fraction_counter;
505 // Time of last clearObjects call (game time).
506 // When a mapblock older than this is loaded, its objects are cleared.
507 u32 m_last_clear_objects_time;
508 // Active block modifiers
509 std::vector<ABMWithState> m_abms;
510 LBMManager m_lbm_mgr;
511 // An interval for generally sending object positions and stuff
512 float m_recommended_send_interval;
513 // Estimate for general maximum lag as determined by server.
514 // Can raise to high values like 15s with eg. map generation mods.
515 float m_max_lag_estimate;
517 // peer_ids in here should be unique, except that there may be many 0s
518 std::vector<RemotePlayer*> m_players;
521 IntervalLimiter m_particle_management_interval;
522 UNORDERED_MAP<u32, float> m_particle_spawners;
523 UNORDERED_MAP<u32, u16> m_particle_spawner_attachments;
528 #include "clientobject.h"
529 #include "content_cao.h"
531 class ClientSimpleObject;
534 The client-side environment.
536 This is not thread-safe.
537 Must be called from main (irrlicht) thread (uses the SceneManager)
538 Client uses an environment mutex.
541 enum ClientEnvEventType
548 struct ClientEnvEvent
550 ClientEnvEventType type;
564 class ClientEnvironment : public Environment
567 ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
568 ITextureSource *texturesource, IGameDef *gamedef,
569 IrrlichtDevice *device);
570 ~ClientEnvironment();
573 ClientMap & getClientMap();
575 IGameDef *getGameDef()
576 { return m_gamedef; }
578 void step(f32 dtime);
580 virtual void setLocalPlayer(LocalPlayer *player);
581 LocalPlayer *getLocalPlayer() { return m_local_player; }
587 void addSimpleObject(ClientSimpleObject *simple);
593 GenericCAO* getGenericCAO(u16 id);
594 ClientActiveObject* getActiveObject(u16 id);
597 Adds an active object to the environment.
598 Environment handles deletion of object.
599 Object may be deleted by environment immediately.
600 If id of object is 0, assigns a free id to it.
601 Returns the id of the object.
602 Returns 0 if not added and thus deleted.
604 u16 addActiveObject(ClientActiveObject *object);
606 void addActiveObject(u16 id, u8 type, const std::string &init_data);
607 void removeActiveObject(u16 id);
609 void processActiveObjectMessage(u16 id, const std::string &data);
612 Callbacks for activeobjects
615 void damageLocalPlayer(u8 damage, bool handle_hp=true);
616 void updateLocalPlayerBreath(u16 breath);
619 Client likes to call these
622 // Get all nearby objects
623 void getActiveObjects(v3f origin, f32 max_d,
624 std::vector<DistanceSortedActiveObject> &dest);
626 // Get event from queue. CEE_NONE is returned if queue is empty.
627 ClientEnvEvent getClientEvent();
629 u16 attachement_parent_ids[USHRT_MAX + 1];
631 const std::list<std::string> &getPlayerNames() { return m_player_names; }
632 void addPlayerName(const std::string &name) { m_player_names.push_back(name); }
633 void removePlayerName(const std::string &name) { m_player_names.remove(name); }
634 void updateCameraOffset(v3s16 camera_offset)
635 { m_camera_offset = camera_offset; }
636 v3s16 getCameraOffset() const { return m_camera_offset; }
639 LocalPlayer *m_local_player;
640 scene::ISceneManager *m_smgr;
641 ITextureSource *m_texturesource;
643 IrrlichtDevice *m_irr;
644 UNORDERED_MAP<u16, ClientActiveObject*> m_active_objects;
645 std::vector<ClientSimpleObject*> m_simple_objects;
646 std::queue<ClientEnvEvent> m_client_event_queue;
647 IntervalLimiter m_active_object_light_update_interval;
648 IntervalLimiter m_lava_hurt_interval;
649 IntervalLimiter m_drowning_interval;
650 IntervalLimiter m_breathing_interval;
651 std::list<std::string> m_player_names;
652 v3s16 m_camera_offset;