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 virtual void addPlayer(Player *player);
76 void removePlayer(Player *player);
77 Player * getPlayer(u16 peer_id);
78 Player * getPlayer(const char *name);
79 Player * getRandomConnectedPlayer();
80 Player * getNearestConnectedPlayer(v3f pos);
81 std::vector<Player*> getPlayers();
82 std::vector<Player*> getPlayers(bool ignore_disconnected);
84 u32 getDayNightRatio();
87 virtual void setTimeOfDay(u32 time);
89 float getTimeOfDayF();
91 void stepTimeOfDay(float dtime);
93 void setTimeOfDaySpeed(float speed);
94 float getTimeOfDaySpeed();
96 void setDayNightRatioOverride(bool enable, u32 value);
98 // counter used internally when triggering ABMs
102 // peer_ids in here should be unique, except that there may be many 0s
103 std::vector<Player*> m_players;
105 GenericAtomic<float> m_time_of_day_speed;
108 * Below: values managed by m_time_lock
110 // Time of day in milli-hours (0-23999); determines day and night
112 // Time of day in 0...1
113 float m_time_of_day_f;
114 // Stores the skew created by the float -> u32 conversion
115 // to be applied at next conversion, so that there is no real skew.
116 float m_time_conversion_skew;
117 // Overriding the day-night ratio is useful for custom sky visuals
118 bool m_enable_day_night_ratio_override;
119 u32 m_day_night_ratio_override;
121 * Above: values managed by m_time_lock
124 /* TODO: Add a callback function so these can be updated when a setting
125 * changes. At this point in time it doesn't matter (e.g. /set
126 * is documented to change server settings only)
128 * TODO: Local caching of settings is not optimal and should at some stage
129 * be updated to use a global settings object for getting thse values
130 * (as opposed to the this local caching). This can be addressed in
133 bool m_cache_enable_shaders;
138 DISABLE_CLASS_COPY(Environment);
142 Active block modifier interface.
144 These are fed into ServerEnvironment at initialization time;
145 ServerEnvironment handles deleting them.
148 class ActiveBlockModifier
151 ActiveBlockModifier(){};
152 virtual ~ActiveBlockModifier(){};
154 // Set of contents to trigger on
155 virtual std::set<std::string> getTriggerContents()=0;
156 // Set of required neighbors (trigger doesn't happen if none are found)
157 // Empty = do not check neighbors
158 virtual std::set<std::string> getRequiredNeighbors()
159 { return std::set<std::string>(); }
160 // Trigger interval in seconds
161 virtual float getTriggerInterval() = 0;
162 // Random chance of (1 / return value), 0 is disallowed
163 virtual u32 getTriggerChance() = 0;
164 // Whether to modify chance to simulate time lost by an unnattended block
165 virtual bool getSimpleCatchUp() = 0;
166 // This is called usually at interval for 1/chance of the nodes
167 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
168 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
169 u32 active_object_count, u32 active_object_count_wider){};
174 ActiveBlockModifier *abm;
177 ABMWithState(ActiveBlockModifier *abm_);
181 List of active blocks, used by ServerEnvironment
184 class ActiveBlockList
187 void update(std::vector<v3s16> &active_positions,
189 std::set<v3s16> &blocks_removed,
190 std::set<v3s16> &blocks_added);
192 bool contains(v3s16 p){
193 return (m_list.find(p) != m_list.end());
200 std::set<v3s16> m_list;
201 std::set<v3s16> m_forceloaded_list;
207 The server-side environment.
209 This is not thread-safe. Server uses an environment mutex.
212 class ServerEnvironment : public Environment
215 ServerEnvironment(ServerMap *map, GameScripting *scriptIface,
216 IGameDef *gamedef, const std::string &path_world);
217 ~ServerEnvironment();
221 ServerMap & getServerMap();
223 //TODO find way to remove this fct!
224 GameScripting* getScriptIface()
227 IGameDef *getGameDef()
228 { return m_gamedef; }
230 float getSendRecommendedInterval()
231 { return m_recommended_send_interval; }
233 void kickAllPlayers(AccessDeniedCode reason,
234 const std::string &str_reason, bool reconnect);
236 void saveLoadedPlayers();
237 void savePlayer(RemotePlayer *player);
238 Player *loadPlayer(const std::string &playername);
241 Save and load time of day and game timer
247 External ActiveObject interface
248 -------------------------------------------
251 ServerActiveObject* getActiveObject(u16 id);
254 Add an active object to the environment.
255 Environment handles deletion of object.
256 Object may be deleted by environment immediately.
257 If id of object is 0, assigns a free id to it.
258 Returns the id of the object.
259 Returns 0 if not added and thus deleted.
261 u16 addActiveObject(ServerActiveObject *object);
264 Add an active object as a static object to the corresponding
266 Caller allocates memory, ServerEnvironment frees memory.
267 Return value: true if succeeded, false if failed.
268 (note: not used, pending removal from engine)
270 //bool addActiveObjectAsStatic(ServerActiveObject *object);
273 Find out what new objects have been added to
274 inside a radius around a position
276 void getAddedActiveObjects(Player *player, s16 radius,
278 std::set<u16> ¤t_objects,
279 std::queue<u16> &added_objects);
282 Find out what new objects have been removed from
283 inside a radius around a position
285 void getRemovedActiveObjects(Player* player, s16 radius,
287 std::set<u16> ¤t_objects,
288 std::queue<u16> &removed_objects);
291 Get the next message emitted by some active object.
292 Returns a message with id=0 if no messages are available.
294 ActiveObjectMessage getActiveObjectMessage();
297 Activate objects and dynamically modify for the dtime determined
298 from timestamp and additional_dtime
300 void activateBlock(MapBlock *block, u32 additional_dtime=0);
304 -------------------------------------------
307 void addActiveBlockModifier(ActiveBlockModifier *abm);
311 -------------------------------------------
314 // Script-aware node setters
315 bool setNode(v3s16 p, const MapNode &n);
316 bool removeNode(v3s16 p);
317 bool swapNode(v3s16 p, const MapNode &n);
319 // Find all active objects inside a radius around a point
320 void getObjectsInsideRadius(std::vector<u16> &objects, v3f pos, float radius);
322 // Clear all objects, loading and going through every MapBlock
323 void clearAllObjects();
325 // This makes stuff happen
326 void step(f32 dtime);
328 //check if there's a line of sight between two positions
329 bool line_of_sight(v3f pos1, v3f pos2, float stepsize=1.0, v3s16 *p=NULL);
331 u32 getGameTime() { return m_game_time; }
333 void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
334 float getMaxLagEstimate() { return m_max_lag_estimate; }
336 std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
338 // Sets the static object status all the active objects in the specified block
339 // This is only really needed for deleting blocks from the map
340 void setStaticForActiveObjectsInBlock(v3s16 blockpos,
341 bool static_exists, v3s16 static_block=v3s16(0,0,0));
346 Internal ActiveObject interface
347 -------------------------------------------
351 Add an active object to the environment.
353 Called by addActiveObject.
355 Object may be deleted by environment immediately.
356 If id of object is 0, assigns a free id to it.
357 Returns the id of the object.
358 Returns 0 if not added and thus deleted.
360 u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
363 Remove all objects that satisfy (m_removed && m_known_by_count==0)
365 void removeRemovedObjects();
368 Convert stored objects from block to active
370 void activateObjects(MapBlock *block, u32 dtime_s);
373 Convert objects that are not in active blocks to static.
375 If m_known_by_count != 0, active object is not deleted, but static
376 data is still updated.
378 If force_delete is set, active object is deleted nevertheless. It
379 shall only be set so in the destructor of the environment.
381 void deactivateFarObjects(bool force_delete);
390 GameScripting* m_script;
394 const std::string m_path_world;
395 // Active object list
396 std::map<u16, ServerActiveObject*> m_active_objects;
397 // Outgoing network message buffer for active objects
398 std::queue<ActiveObjectMessage> m_active_object_messages;
400 float m_send_recommended_timer;
401 IntervalLimiter m_object_management_interval;
402 // List of active blocks
403 ActiveBlockList m_active_blocks;
404 IntervalLimiter m_active_blocks_management_interval;
405 IntervalLimiter m_active_block_modifier_interval;
406 IntervalLimiter m_active_blocks_nodemetadata_interval;
407 int m_active_block_interval_overload_skip;
408 // Time from the beginning of the game in seconds.
409 // Incremented in step().
411 // A helper variable for incrementing the latter
412 float m_game_time_fraction_counter;
413 std::vector<ABMWithState> m_abms;
414 // An interval for generally sending object positions and stuff
415 float m_recommended_send_interval;
416 // Estimate for general maximum lag as determined by server.
417 // Can raise to high values like 15s with eg. map generation mods.
418 float m_max_lag_estimate;
423 #include "clientobject.h"
424 #include "content_cao.h"
426 class ClientSimpleObject;
429 The client-side environment.
431 This is not thread-safe.
432 Must be called from main (irrlicht) thread (uses the SceneManager)
433 Client uses an environment mutex.
436 enum ClientEnvEventType
443 struct ClientEnvEvent
445 ClientEnvEventType type;
459 class ClientEnvironment : public Environment
462 ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
463 ITextureSource *texturesource, IGameDef *gamedef,
464 IrrlichtDevice *device);
465 ~ClientEnvironment();
468 ClientMap & getClientMap();
470 IGameDef *getGameDef()
471 { return m_gamedef; }
473 void step(f32 dtime);
475 virtual void addPlayer(Player *player);
476 LocalPlayer * getLocalPlayer();
482 void addSimpleObject(ClientSimpleObject *simple);
488 GenericCAO* getGenericCAO(u16 id);
489 ClientActiveObject* getActiveObject(u16 id);
492 Adds an active object to the environment.
493 Environment handles deletion of object.
494 Object may be deleted by environment immediately.
495 If id of object is 0, assigns a free id to it.
496 Returns the id of the object.
497 Returns 0 if not added and thus deleted.
499 u16 addActiveObject(ClientActiveObject *object);
501 void addActiveObject(u16 id, u8 type, const std::string &init_data);
502 void removeActiveObject(u16 id);
504 void processActiveObjectMessage(u16 id, const std::string &data);
507 Callbacks for activeobjects
510 void damageLocalPlayer(u8 damage, bool handle_hp=true);
511 void updateLocalPlayerBreath(u16 breath);
514 Client likes to call these
517 // Get all nearby objects
518 void getActiveObjects(v3f origin, f32 max_d,
519 std::vector<DistanceSortedActiveObject> &dest);
521 // Get event from queue. CEE_NONE is returned if queue is empty.
522 ClientEnvEvent getClientEvent();
524 u16 attachement_parent_ids[USHRT_MAX + 1];
526 std::list<std::string> getPlayerNames()
527 { return m_player_names; }
528 void addPlayerName(std::string name)
529 { m_player_names.push_back(name); }
530 void removePlayerName(std::string name)
531 { m_player_names.remove(name); }
532 void updateCameraOffset(v3s16 camera_offset)
533 { m_camera_offset = camera_offset; }
534 v3s16 getCameraOffset()
535 { return m_camera_offset; }
539 scene::ISceneManager *m_smgr;
540 ITextureSource *m_texturesource;
542 IrrlichtDevice *m_irr;
543 std::map<u16, ClientActiveObject*> m_active_objects;
544 std::vector<ClientSimpleObject*> m_simple_objects;
545 std::queue<ClientEnvEvent> m_client_event_queue;
546 IntervalLimiter m_active_object_light_update_interval;
547 IntervalLimiter m_lava_hurt_interval;
548 IntervalLimiter m_drowning_interval;
549 IntervalLimiter m_breathing_interval;
550 std::list<std::string> m_player_names;
551 v3s16 m_camera_offset;