Environment cleanup
[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         u32 getDayNightRatio();
76
77         // 0-23999
78         virtual void setTimeOfDay(u32 time);
79         u32 getTimeOfDay();
80         float getTimeOfDayF();
81
82         void stepTimeOfDay(float dtime);
83
84         void setTimeOfDaySpeed(float speed);
85
86         void setDayNightRatioOverride(bool enable, u32 value);
87
88         u32 getDayCount();
89
90         // counter used internally when triggering ABMs
91         u32 m_added_objects;
92
93 protected:
94         GenericAtomic<float> m_time_of_day_speed;
95
96         /*
97          * Below: values managed by m_time_lock
98         */
99         // Time of day in milli-hours (0-23999); determines day and night
100         u32 m_time_of_day;
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;
112         /*
113          * Above: values managed by m_time_lock
114         */
115
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)
119          *
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
123          *       a later release.
124          */
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;
129
130 private:
131         Mutex m_time_lock;
132
133         DISABLE_CLASS_COPY(Environment);
134 };
135
136 /*
137         {Active, Loading} block modifier interface.
138
139         These are fed into ServerEnvironment at initialization time;
140         ServerEnvironment handles deleting them.
141 */
142
143 class ActiveBlockModifier
144 {
145 public:
146         ActiveBlockModifier(){};
147         virtual ~ActiveBlockModifier(){};
148
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){};
165 };
166
167 struct ABMWithState
168 {
169         ActiveBlockModifier *abm;
170         float timer;
171
172         ABMWithState(ActiveBlockModifier *abm_);
173 };
174
175 struct LoadingBlockModifierDef
176 {
177         // Set of contents to trigger on
178         std::set<std::string> trigger_contents;
179         std::string name;
180         bool run_at_every_load;
181
182         virtual ~LoadingBlockModifierDef() {}
183         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
184 };
185
186 struct LBMContentMapping
187 {
188         typedef std::map<content_t, std::vector<LoadingBlockModifierDef *> > container_map;
189         container_map map;
190
191         std::vector<LoadingBlockModifierDef *> lbm_list;
192
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;
199 };
200
201 class LBMManager
202 {
203 public:
204         LBMManager():
205                 m_query_mode(false)
206         {}
207
208         ~LBMManager();
209
210         // Don't call this after loadIntroductionTimes() ran.
211         void addLBMDef(LoadingBlockModifierDef *lbm_def);
212
213         void loadIntroductionTimes(const std::string &times,
214                 IGameDef *gamedef, u32 now);
215
216         // Don't call this before loadIntroductionTimes() ran.
217         std::string createIntroductionTimesString();
218
219         // Don't call this before loadIntroductionTimes() ran.
220         void applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp);
221
222         // Warning: do not make this std::unordered_map, order is relevant here
223         typedef std::map<u32, LBMContentMapping> lbm_lookup_map;
224
225 private:
226         // Once we set this to true, we can only query,
227         // not modify
228         bool m_query_mode;
229
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;
234
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;
238
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); }
244 };
245
246 /*
247         List of active blocks, used by ServerEnvironment
248 */
249
250 class ActiveBlockList
251 {
252 public:
253         void update(std::vector<v3s16> &active_positions,
254                         s16 radius,
255                         std::set<v3s16> &blocks_removed,
256                         std::set<v3s16> &blocks_added);
257
258         bool contains(v3s16 p){
259                 return (m_list.find(p) != m_list.end());
260         }
261
262         void clear(){
263                 m_list.clear();
264         }
265
266         std::set<v3s16> m_list;
267         std::set<v3s16> m_forceloaded_list;
268
269 private:
270 };
271
272 /*
273         Operation mode for ServerEnvironment::clearObjects()
274 */
275 enum ClearObjectsMode {
276         // Load and go through every mapblock, clearing objects
277         CLEAR_OBJECTS_MODE_FULL,
278
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,
282 };
283
284 /*
285         The server-side environment.
286
287         This is not thread-safe. Server uses an environment mutex.
288 */
289
290 typedef UNORDERED_MAP<u16, ServerActiveObject *> ActiveObjectMap;
291
292 class ServerEnvironment : public Environment
293 {
294 public:
295         ServerEnvironment(ServerMap *map, GameScripting *scriptIface,
296                         IGameDef *gamedef, const std::string &path_world);
297         ~ServerEnvironment();
298
299         Map & getMap();
300
301         ServerMap & getServerMap();
302
303         //TODO find way to remove this fct!
304         GameScripting* getScriptIface()
305                 { return m_script; }
306
307         IGameDef *getGameDef()
308                 { return m_gamedef; }
309
310         float getSendRecommendedInterval()
311                 { return m_recommended_send_interval; }
312
313         void kickAllPlayers(AccessDeniedCode reason,
314                 const std::string &str_reason, bool reconnect);
315         // Save players
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);
321
322         /*
323                 Save and load time of day and game timer
324         */
325         void saveMeta();
326         void loadMeta();
327         // to be called instead of loadMeta if
328         // env_meta.txt doesn't exist (e.g. new world)
329         void loadDefaultMeta();
330
331         u32 addParticleSpawner(float exptime);
332         void deleteParticleSpawner(u32 id) { m_particle_spawners.erase(id); }
333
334         /*
335                 External ActiveObject interface
336                 -------------------------------------------
337         */
338
339         ServerActiveObject* getActiveObject(u16 id);
340
341         /*
342                 Add an active object to the environment.
343                 Environment handles deletion of object.
344                 Object may be deleted by environment immediately.
345                 If id of object is 0, assigns a free id to it.
346                 Returns the id of the object.
347                 Returns 0 if not added and thus deleted.
348         */
349         u16 addActiveObject(ServerActiveObject *object);
350
351         /*
352                 Add an active object as a static object to the corresponding
353                 MapBlock.
354                 Caller allocates memory, ServerEnvironment frees memory.
355                 Return value: true if succeeded, false if failed.
356                 (note:  not used, pending removal from engine)
357         */
358         //bool addActiveObjectAsStatic(ServerActiveObject *object);
359
360         /*
361                 Find out what new objects have been added to
362                 inside a radius around a position
363         */
364         void getAddedActiveObjects(RemotePlayer *player, s16 radius,
365                         s16 player_radius,
366                         std::set<u16> &current_objects,
367                         std::queue<u16> &added_objects);
368
369         /*
370                 Find out what new objects have been removed from
371                 inside a radius around a position
372         */
373         void getRemovedActiveObjects(RemotePlayer *player, s16 radius,
374                         s16 player_radius,
375                         std::set<u16> &current_objects,
376                         std::queue<u16> &removed_objects);
377
378         /*
379                 Get the next message emitted by some active object.
380                 Returns a message with id=0 if no messages are available.
381         */
382         ActiveObjectMessage getActiveObjectMessage();
383
384         /*
385                 Activate objects and dynamically modify for the dtime determined
386                 from timestamp and additional_dtime
387         */
388         void activateBlock(MapBlock *block, u32 additional_dtime=0);
389
390         /*
391                 {Active,Loading}BlockModifiers
392                 -------------------------------------------
393         */
394
395         void addActiveBlockModifier(ActiveBlockModifier *abm);
396         void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
397
398         /*
399                 Other stuff
400                 -------------------------------------------
401         */
402
403         // Script-aware node setters
404         bool setNode(v3s16 p, const MapNode &n);
405         bool removeNode(v3s16 p);
406         bool swapNode(v3s16 p, const MapNode &n);
407
408         // Find all active objects inside a radius around a point
409         void getObjectsInsideRadius(std::vector<u16> &objects, v3f pos, float radius);
410
411         // Clear objects, loading and going through every MapBlock
412         void clearObjects(ClearObjectsMode mode);
413
414         // This makes stuff happen
415         void step(f32 dtime);
416
417         //check if there's a line of sight between two positions
418         bool line_of_sight(v3f pos1, v3f pos2, float stepsize=1.0, v3s16 *p=NULL);
419
420         u32 getGameTime() { return m_game_time; }
421
422         void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
423         float getMaxLagEstimate() { return m_max_lag_estimate; }
424
425         std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
426
427         // Sets the static object status all the active objects in the specified block
428         // This is only really needed for deleting blocks from the map
429         void setStaticForActiveObjectsInBlock(v3s16 blockpos,
430                 bool static_exists, v3s16 static_block=v3s16(0,0,0));
431
432         RemotePlayer *getPlayer(const u16 peer_id);
433         RemotePlayer *getPlayer(const char* name);
434 private:
435
436         /*
437                 Internal ActiveObject interface
438                 -------------------------------------------
439         */
440
441         /*
442                 Add an active object to the environment.
443
444                 Called by addActiveObject.
445
446                 Object may be deleted by environment immediately.
447                 If id of object is 0, assigns a free id to it.
448                 Returns the id of the object.
449                 Returns 0 if not added and thus deleted.
450         */
451         u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
452
453         /*
454                 Remove all objects that satisfy (m_removed && m_known_by_count==0)
455         */
456         void removeRemovedObjects();
457
458         /*
459                 Convert stored objects from block to active
460         */
461         void activateObjects(MapBlock *block, u32 dtime_s);
462
463         /*
464                 Convert objects that are not in active blocks to static.
465
466                 If m_known_by_count != 0, active object is not deleted, but static
467                 data is still updated.
468
469                 If force_delete is set, active object is deleted nevertheless. It
470                 shall only be set so in the destructor of the environment.
471         */
472         void deactivateFarObjects(bool force_delete);
473
474         /*
475                 Member variables
476         */
477
478         // The map
479         ServerMap *m_map;
480         // Lua state
481         GameScripting* m_script;
482         // Game definition
483         IGameDef *m_gamedef;
484         // World path
485         const std::string m_path_world;
486         // Active object list
487         ActiveObjectMap m_active_objects;
488         // Outgoing network message buffer for active objects
489         std::queue<ActiveObjectMessage> m_active_object_messages;
490         // Some timers
491         float m_send_recommended_timer;
492         IntervalLimiter m_object_management_interval;
493         // List of active blocks
494         ActiveBlockList m_active_blocks;
495         IntervalLimiter m_active_blocks_management_interval;
496         IntervalLimiter m_active_block_modifier_interval;
497         IntervalLimiter m_active_blocks_nodemetadata_interval;
498         int m_active_block_interval_overload_skip;
499         // Time from the beginning of the game in seconds.
500         // Incremented in step().
501         u32 m_game_time;
502         // A helper variable for incrementing the latter
503         float m_game_time_fraction_counter;
504         // Time of last clearObjects call (game time).
505         // When a mapblock older than this is loaded, its objects are cleared.
506         u32 m_last_clear_objects_time;
507         // Active block modifiers
508         std::vector<ABMWithState> m_abms;
509         LBMManager m_lbm_mgr;
510         // An interval for generally sending object positions and stuff
511         float m_recommended_send_interval;
512         // Estimate for general maximum lag as determined by server.
513         // Can raise to high values like 15s with eg. map generation mods.
514         float m_max_lag_estimate;
515
516         // peer_ids in here should be unique, except that there may be many 0s
517         std::vector<RemotePlayer*> m_players;
518
519         // Particles
520         IntervalLimiter m_particle_management_interval;
521         UNORDERED_MAP<u32, float> m_particle_spawners;
522 };
523
524 #ifndef SERVER
525
526 #include "clientobject.h"
527 #include "content_cao.h"
528
529 class ClientSimpleObject;
530
531 /*
532         The client-side environment.
533
534         This is not thread-safe.
535         Must be called from main (irrlicht) thread (uses the SceneManager)
536         Client uses an environment mutex.
537 */
538
539 enum ClientEnvEventType
540 {
541         CEE_NONE,
542         CEE_PLAYER_DAMAGE,
543         CEE_PLAYER_BREATH
544 };
545
546 struct ClientEnvEvent
547 {
548         ClientEnvEventType type;
549         union {
550                 //struct{
551                 //} none;
552                 struct{
553                         u8 amount;
554                         bool send_to_server;
555                 } player_damage;
556                 struct{
557                         u16 amount;
558                 } player_breath;
559         };
560 };
561
562 class ClientEnvironment : public Environment
563 {
564 public:
565         ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
566                         ITextureSource *texturesource, IGameDef *gamedef,
567                         IrrlichtDevice *device);
568         ~ClientEnvironment();
569
570         Map & getMap();
571         ClientMap & getClientMap();
572
573         IGameDef *getGameDef()
574         { return m_gamedef; }
575
576         void step(f32 dtime);
577
578         virtual void setLocalPlayer(LocalPlayer *player);
579         LocalPlayer *getLocalPlayer() { return m_local_player; }
580
581         /*
582                 ClientSimpleObjects
583         */
584
585         void addSimpleObject(ClientSimpleObject *simple);
586
587         /*
588                 ActiveObjects
589         */
590
591         GenericCAO* getGenericCAO(u16 id);
592         ClientActiveObject* getActiveObject(u16 id);
593
594         /*
595                 Adds an active object to the environment.
596                 Environment handles deletion of object.
597                 Object may be deleted by environment immediately.
598                 If id of object is 0, assigns a free id to it.
599                 Returns the id of the object.
600                 Returns 0 if not added and thus deleted.
601         */
602         u16 addActiveObject(ClientActiveObject *object);
603
604         void addActiveObject(u16 id, u8 type, const std::string &init_data);
605         void removeActiveObject(u16 id);
606
607         void processActiveObjectMessage(u16 id, const std::string &data);
608
609         /*
610                 Callbacks for activeobjects
611         */
612
613         void damageLocalPlayer(u8 damage, bool handle_hp=true);
614         void updateLocalPlayerBreath(u16 breath);
615
616         /*
617                 Client likes to call these
618         */
619
620         // Get all nearby objects
621         void getActiveObjects(v3f origin, f32 max_d,
622                         std::vector<DistanceSortedActiveObject> &dest);
623
624         // Get event from queue. CEE_NONE is returned if queue is empty.
625         ClientEnvEvent getClientEvent();
626
627         u16 attachement_parent_ids[USHRT_MAX + 1];
628
629         const std::list<std::string> &getPlayerNames() { return m_player_names; }
630         void addPlayerName(const std::string &name) { m_player_names.push_back(name); }
631         void removePlayerName(const std::string &name) { m_player_names.remove(name); }
632         void updateCameraOffset(v3s16 camera_offset)
633         { m_camera_offset = camera_offset; }
634         v3s16 getCameraOffset() const { return m_camera_offset; }
635 private:
636         ClientMap *m_map;
637         LocalPlayer *m_local_player;
638         scene::ISceneManager *m_smgr;
639         ITextureSource *m_texturesource;
640         IGameDef *m_gamedef;
641         IrrlichtDevice *m_irr;
642         UNORDERED_MAP<u16, ClientActiveObject*> m_active_objects;
643         std::vector<ClientSimpleObject*> m_simple_objects;
644         std::queue<ClientEnvEvent> m_client_event_queue;
645         IntervalLimiter m_active_object_light_update_interval;
646         IntervalLimiter m_lava_hurt_interval;
647         IntervalLimiter m_drowning_interval;
648         IntervalLimiter m_breathing_interval;
649         std::list<std::string> m_player_names;
650         v3s16 m_camera_offset;
651 };
652
653 #endif
654
655 #endif
656