Add consistent monotonic day counter - get_day_count()
[oweals/minetest.git] / src / environment.h
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #ifndef ENVIRONMENT_HEADER
21 #define ENVIRONMENT_HEADER
22
23 /*
24         This class is the game's environment.
25         It contains:
26         - The map
27         - Players
28         - Other objects
29         - The current time in the game
30         - etc.
31 */
32
33 #include <set>
34 #include <list>
35 #include <queue>
36 #include <map>
37 #include "irr_v3d.h"
38 #include "activeobject.h"
39 #include "util/numeric.h"
40 #include "mapnode.h"
41 #include "mapblock.h"
42 #include "threading/mutex.h"
43 #include "threading/atomic.h"
44 #include "network/networkprotocol.h" // for AccessDeniedCode
45
46 class ServerEnvironment;
47 class ActiveBlockModifier;
48 class ServerActiveObject;
49 class ITextureSource;
50 class IGameDef;
51 class Map;
52 class ServerMap;
53 class ClientMap;
54 class GameScripting;
55 class Player;
56 class RemotePlayer;
57
58 class Environment
59 {
60 public:
61         // Environment will delete the map passed to the constructor
62         Environment();
63         virtual ~Environment();
64
65         /*
66                 Step everything in environment.
67                 - Move players
68                 - Step mobs
69                 - Run timers of map
70         */
71         virtual void step(f32 dtime) = 0;
72
73         virtual Map & getMap() = 0;
74
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);
83
84         u32 getDayNightRatio();
85
86         // 0-23999
87         virtual void setTimeOfDay(u32 time);
88         u32 getTimeOfDay();
89         float getTimeOfDayF();
90
91         void stepTimeOfDay(float dtime);
92
93         void setTimeOfDaySpeed(float speed);
94         float getTimeOfDaySpeed();
95
96         void setDayNightRatioOverride(bool enable, u32 value);
97
98         u32 getDayCount();
99
100         // counter used internally when triggering ABMs
101         u32 m_added_objects;
102
103 protected:
104         // peer_ids in here should be unique, except that there may be many 0s
105         std::vector<Player*> m_players;
106
107         GenericAtomic<float> m_time_of_day_speed;
108
109         /*
110          * Below: values managed by m_time_lock
111         */
112         // Time of day in milli-hours (0-23999); determines day and night
113         u32 m_time_of_day;
114         // Time of day in 0...1
115         float m_time_of_day_f;
116         // Stores the skew created by the float -> u32 conversion
117         // to be applied at next conversion, so that there is no real skew.
118         float m_time_conversion_skew;
119         // Overriding the day-night ratio is useful for custom sky visuals
120         bool m_enable_day_night_ratio_override;
121         u32 m_day_night_ratio_override;
122         // Days from the server start, accounts for time shift
123         // in game (e.g. /time or bed usage)
124         Atomic<u32> m_day_count;
125         /*
126          * Above: values managed by m_time_lock
127         */
128
129         /* TODO: Add a callback function so these can be updated when a setting
130          *       changes.  At this point in time it doesn't matter (e.g. /set
131          *       is documented to change server settings only)
132          *
133          * TODO: Local caching of settings is not optimal and should at some stage
134          *       be updated to use a global settings object for getting thse values
135          *       (as opposed to the this local caching). This can be addressed in
136          *       a later release.
137          */
138         bool m_cache_enable_shaders;
139
140 private:
141         Mutex m_time_lock;
142
143         DISABLE_CLASS_COPY(Environment);
144 };
145
146 /*
147         {Active, Loading} block modifier interface.
148
149         These are fed into ServerEnvironment at initialization time;
150         ServerEnvironment handles deleting them.
151 */
152
153 class ActiveBlockModifier
154 {
155 public:
156         ActiveBlockModifier(){};
157         virtual ~ActiveBlockModifier(){};
158
159         // Set of contents to trigger on
160         virtual std::set<std::string> getTriggerContents()=0;
161         // Set of required neighbors (trigger doesn't happen if none are found)
162         // Empty = do not check neighbors
163         virtual std::set<std::string> getRequiredNeighbors()
164         { return std::set<std::string>(); }
165         // Trigger interval in seconds
166         virtual float getTriggerInterval() = 0;
167         // Random chance of (1 / return value), 0 is disallowed
168         virtual u32 getTriggerChance() = 0;
169         // Whether to modify chance to simulate time lost by an unnattended block
170         virtual bool getSimpleCatchUp() = 0;
171         // This is called usually at interval for 1/chance of the nodes
172         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
173         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
174                         u32 active_object_count, u32 active_object_count_wider){};
175 };
176
177 struct ABMWithState
178 {
179         ActiveBlockModifier *abm;
180         float timer;
181
182         ABMWithState(ActiveBlockModifier *abm_);
183 };
184
185 struct LoadingBlockModifierDef
186 {
187         // Set of contents to trigger on
188         std::set<std::string> trigger_contents;
189         std::string name;
190         bool run_at_every_load;
191
192         virtual ~LoadingBlockModifierDef() {}
193         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
194 };
195
196 struct LBMContentMapping
197 {
198         typedef std::map<content_t, std::vector<LoadingBlockModifierDef *> > container_map;
199         container_map map;
200
201         std::vector<LoadingBlockModifierDef *> lbm_list;
202
203         // Needs to be separate method (not inside destructor),
204         // because the LBMContentMapping may be copied and destructed
205         // many times during operation in the lbm_lookup_map.
206         void deleteContents();
207         void addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef);
208         const std::vector<LoadingBlockModifierDef *> *lookup(content_t c) const;
209 };
210
211 class LBMManager
212 {
213 public:
214         LBMManager():
215                 m_query_mode(false)
216         {}
217
218         ~LBMManager();
219
220         // Don't call this after loadIntroductionTimes() ran.
221         void addLBMDef(LoadingBlockModifierDef *lbm_def);
222
223         void loadIntroductionTimes(const std::string &times,
224                 IGameDef *gamedef, u32 now);
225
226         // Don't call this before loadIntroductionTimes() ran.
227         std::string createIntroductionTimesString();
228
229         // Don't call this before loadIntroductionTimes() ran.
230         void applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp);
231
232         // Warning: do not make this std::unordered_map, order is relevant here
233         typedef std::map<u32, LBMContentMapping> lbm_lookup_map;
234
235 private:
236         // Once we set this to true, we can only query,
237         // not modify
238         bool m_query_mode;
239
240         // For m_query_mode == false:
241         // The key of the map is the LBM def's name.
242         // TODO make this std::unordered_map
243         std::map<std::string, LoadingBlockModifierDef *> m_lbm_defs;
244
245         // For m_query_mode == true:
246         // The key of the map is the LBM def's first introduction time.
247         lbm_lookup_map m_lbm_lookup;
248
249         // Returns an iterator to the LBMs that were introduced
250         // after the given time. This is guaranteed to return
251         // valid values for everything
252         lbm_lookup_map::const_iterator getLBMsIntroducedAfter(u32 time)
253         { return m_lbm_lookup.lower_bound(time); }
254 };
255
256 /*
257         List of active blocks, used by ServerEnvironment
258 */
259
260 class ActiveBlockList
261 {
262 public:
263         void update(std::vector<v3s16> &active_positions,
264                         s16 radius,
265                         std::set<v3s16> &blocks_removed,
266                         std::set<v3s16> &blocks_added);
267
268         bool contains(v3s16 p){
269                 return (m_list.find(p) != m_list.end());
270         }
271
272         void clear(){
273                 m_list.clear();
274         }
275
276         std::set<v3s16> m_list;
277         std::set<v3s16> m_forceloaded_list;
278
279 private:
280 };
281
282 /*
283         Operation mode for ServerEnvironment::clearObjects()
284 */
285 enum ClearObjectsMode {
286         // Load and go through every mapblock, clearing objects
287         CLEAR_OBJECTS_MODE_FULL,
288
289         // Clear objects immediately in loaded mapblocks;
290         // clear objects in unloaded mapblocks only when the mapblocks are next activated.
291         CLEAR_OBJECTS_MODE_QUICK,
292 };
293
294 /*
295         The server-side environment.
296
297         This is not thread-safe. Server uses an environment mutex.
298 */
299
300 class ServerEnvironment : public Environment
301 {
302 public:
303         ServerEnvironment(ServerMap *map, GameScripting *scriptIface,
304                         IGameDef *gamedef, const std::string &path_world);
305         ~ServerEnvironment();
306
307         Map & getMap();
308
309         ServerMap & getServerMap();
310
311         //TODO find way to remove this fct!
312         GameScripting* getScriptIface()
313                 { return m_script; }
314
315         IGameDef *getGameDef()
316                 { return m_gamedef; }
317
318         float getSendRecommendedInterval()
319                 { return m_recommended_send_interval; }
320
321         void kickAllPlayers(AccessDeniedCode reason,
322                 const std::string &str_reason, bool reconnect);
323         // Save players
324         void saveLoadedPlayers();
325         void savePlayer(RemotePlayer *player);
326         Player *loadPlayer(const std::string &playername);
327
328         /*
329                 Save and load time of day and game timer
330         */
331         void saveMeta();
332         void loadMeta();
333         // to be called instead of loadMeta if
334         // env_meta.txt doesn't exist (e.g. new world)
335         void loadDefaultMeta();
336
337         /*
338                 External ActiveObject interface
339                 -------------------------------------------
340         */
341
342         ServerActiveObject* getActiveObject(u16 id);
343
344         /*
345                 Add an active object to the environment.
346                 Environment handles deletion of object.
347                 Object may be deleted by environment immediately.
348                 If id of object is 0, assigns a free id to it.
349                 Returns the id of the object.
350                 Returns 0 if not added and thus deleted.
351         */
352         u16 addActiveObject(ServerActiveObject *object);
353
354         /*
355                 Add an active object as a static object to the corresponding
356                 MapBlock.
357                 Caller allocates memory, ServerEnvironment frees memory.
358                 Return value: true if succeeded, false if failed.
359                 (note:  not used, pending removal from engine)
360         */
361         //bool addActiveObjectAsStatic(ServerActiveObject *object);
362
363         /*
364                 Find out what new objects have been added to
365                 inside a radius around a position
366         */
367         void getAddedActiveObjects(Player *player, s16 radius,
368                         s16 player_radius,
369                         std::set<u16> &current_objects,
370                         std::queue<u16> &added_objects);
371
372         /*
373                 Find out what new objects have been removed from
374                 inside a radius around a position
375         */
376         void getRemovedActiveObjects(Player* player, s16 radius,
377                         s16 player_radius,
378                         std::set<u16> &current_objects,
379                         std::queue<u16> &removed_objects);
380
381         /*
382                 Get the next message emitted by some active object.
383                 Returns a message with id=0 if no messages are available.
384         */
385         ActiveObjectMessage getActiveObjectMessage();
386
387         /*
388                 Activate objects and dynamically modify for the dtime determined
389                 from timestamp and additional_dtime
390         */
391         void activateBlock(MapBlock *block, u32 additional_dtime=0);
392
393         /*
394                 {Active,Loading}BlockModifiers
395                 -------------------------------------------
396         */
397
398         void addActiveBlockModifier(ActiveBlockModifier *abm);
399         void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
400
401         /*
402                 Other stuff
403                 -------------------------------------------
404         */
405
406         // Script-aware node setters
407         bool setNode(v3s16 p, const MapNode &n);
408         bool removeNode(v3s16 p);
409         bool swapNode(v3s16 p, const MapNode &n);
410
411         // Find all active objects inside a radius around a point
412         void getObjectsInsideRadius(std::vector<u16> &objects, v3f pos, float radius);
413
414         // Clear objects, loading and going through every MapBlock
415         void clearObjects(ClearObjectsMode mode);
416
417         // This makes stuff happen
418         void step(f32 dtime);
419
420         //check if there's a line of sight between two positions
421         bool line_of_sight(v3f pos1, v3f pos2, float stepsize=1.0, v3s16 *p=NULL);
422
423         u32 getGameTime() { return m_game_time; }
424
425         void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
426         float getMaxLagEstimate() { return m_max_lag_estimate; }
427
428         std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
429
430         // Sets the static object status all the active objects in the specified block
431         // This is only really needed for deleting blocks from the map
432         void setStaticForActiveObjectsInBlock(v3s16 blockpos,
433                 bool static_exists, v3s16 static_block=v3s16(0,0,0));
434
435 private:
436
437         /*
438                 Internal ActiveObject interface
439                 -------------------------------------------
440         */
441
442         /*
443                 Add an active object to the environment.
444
445                 Called by addActiveObject.
446
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.
451         */
452         u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
453
454         /*
455                 Remove all objects that satisfy (m_removed && m_known_by_count==0)
456         */
457         void removeRemovedObjects();
458
459         /*
460                 Convert stored objects from block to active
461         */
462         void activateObjects(MapBlock *block, u32 dtime_s);
463
464         /*
465                 Convert objects that are not in active blocks to static.
466
467                 If m_known_by_count != 0, active object is not deleted, but static
468                 data is still updated.
469
470                 If force_delete is set, active object is deleted nevertheless. It
471                 shall only be set so in the destructor of the environment.
472         */
473         void deactivateFarObjects(bool force_delete);
474
475         /*
476                 Member variables
477         */
478
479         // The map
480         ServerMap *m_map;
481         // Lua state
482         GameScripting* m_script;
483         // Game definition
484         IGameDef *m_gamedef;
485         // World path
486         const std::string m_path_world;
487         // Active object list
488         std::map<u16, ServerActiveObject*> m_active_objects;
489         // Outgoing network message buffer for active objects
490         std::queue<ActiveObjectMessage> m_active_object_messages;
491         // Some timers
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().
502         u32 m_game_time;
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;
516 };
517
518 #ifndef SERVER
519
520 #include "clientobject.h"
521 #include "content_cao.h"
522
523 class ClientSimpleObject;
524
525 /*
526         The client-side environment.
527
528         This is not thread-safe.
529         Must be called from main (irrlicht) thread (uses the SceneManager)
530         Client uses an environment mutex.
531 */
532
533 enum ClientEnvEventType
534 {
535         CEE_NONE,
536         CEE_PLAYER_DAMAGE,
537         CEE_PLAYER_BREATH
538 };
539
540 struct ClientEnvEvent
541 {
542         ClientEnvEventType type;
543         union {
544                 //struct{
545                 //} none;
546                 struct{
547                         u8 amount;
548                         bool send_to_server;
549                 } player_damage;
550                 struct{
551                         u16 amount;
552                 } player_breath;
553         };
554 };
555
556 class ClientEnvironment : public Environment
557 {
558 public:
559         ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
560                         ITextureSource *texturesource, IGameDef *gamedef,
561                         IrrlichtDevice *device);
562         ~ClientEnvironment();
563
564         Map & getMap();
565         ClientMap & getClientMap();
566
567         IGameDef *getGameDef()
568         { return m_gamedef; }
569
570         void step(f32 dtime);
571
572         virtual void addPlayer(Player *player);
573         LocalPlayer * getLocalPlayer();
574
575         /*
576                 ClientSimpleObjects
577         */
578
579         void addSimpleObject(ClientSimpleObject *simple);
580
581         /*
582                 ActiveObjects
583         */
584
585         GenericCAO* getGenericCAO(u16 id);
586         ClientActiveObject* getActiveObject(u16 id);
587
588         /*
589                 Adds an active object to the environment.
590                 Environment handles deletion of object.
591                 Object may be deleted by environment immediately.
592                 If id of object is 0, assigns a free id to it.
593                 Returns the id of the object.
594                 Returns 0 if not added and thus deleted.
595         */
596         u16 addActiveObject(ClientActiveObject *object);
597
598         void addActiveObject(u16 id, u8 type, const std::string &init_data);
599         void removeActiveObject(u16 id);
600
601         void processActiveObjectMessage(u16 id, const std::string &data);
602
603         /*
604                 Callbacks for activeobjects
605         */
606
607         void damageLocalPlayer(u8 damage, bool handle_hp=true);
608         void updateLocalPlayerBreath(u16 breath);
609
610         /*
611                 Client likes to call these
612         */
613
614         // Get all nearby objects
615         void getActiveObjects(v3f origin, f32 max_d,
616                         std::vector<DistanceSortedActiveObject> &dest);
617
618         // Get event from queue. CEE_NONE is returned if queue is empty.
619         ClientEnvEvent getClientEvent();
620
621         u16 attachement_parent_ids[USHRT_MAX + 1];
622
623         std::list<std::string> getPlayerNames()
624         { return m_player_names; }
625         void addPlayerName(std::string name)
626         { m_player_names.push_back(name); }
627         void removePlayerName(std::string name)
628         { m_player_names.remove(name); }
629         void updateCameraOffset(v3s16 camera_offset)
630         { m_camera_offset = camera_offset; }
631         v3s16 getCameraOffset()
632         { return m_camera_offset; }
633
634 private:
635         ClientMap *m_map;
636         scene::ISceneManager *m_smgr;
637         ITextureSource *m_texturesource;
638         IGameDef *m_gamedef;
639         IrrlichtDevice *m_irr;
640         std::map<u16, ClientActiveObject*> m_active_objects;
641         std::vector<ClientSimpleObject*> m_simple_objects;
642         std::queue<ClientEnvEvent> m_client_event_queue;
643         IntervalLimiter m_active_object_light_update_interval;
644         IntervalLimiter m_lava_hurt_interval;
645         IntervalLimiter m_drowning_interval;
646         IntervalLimiter m_breathing_interval;
647         std::list<std::string> m_player_names;
648         v3s16 m_camera_offset;
649 };
650
651 #endif
652
653 #endif
654