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