]> git.lizzy.rs Git - minetest.git/blob - src/environment.h
Fix server crashing on Lua errors
[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 "network/networkprotocol.h" // for AccessDeniedCode
44
45 class ServerEnvironment;
46 class ActiveBlockModifier;
47 class ServerActiveObject;
48 class ITextureSource;
49 class IGameDef;
50 class Map;
51 class ServerMap;
52 class ClientMap;
53 class GameScripting;
54 class Player;
55 class RemotePlayer;
56
57 class Environment
58 {
59 public:
60         // Environment will delete the map passed to the constructor
61         Environment();
62         virtual ~Environment();
63
64         /*
65                 Step everything in environment.
66                 - Move players
67                 - Step mobs
68                 - Run timers of map
69         */
70         virtual void step(f32 dtime) = 0;
71
72         virtual Map & getMap() = 0;
73
74         virtual void addPlayer(Player *player);
75         void removePlayer(Player *player);
76         Player * getPlayer(u16 peer_id);
77         Player * getPlayer(const char *name);
78         Player * getRandomConnectedPlayer();
79         Player * getNearestConnectedPlayer(v3f pos);
80         std::vector<Player*> getPlayers();
81         std::vector<Player*> getPlayers(bool ignore_disconnected);
82
83         u32 getDayNightRatio();
84
85         // 0-23999
86         virtual void setTimeOfDay(u32 time);
87         u32 getTimeOfDay();
88         float getTimeOfDayF();
89
90         void stepTimeOfDay(float dtime);
91
92         void setTimeOfDaySpeed(float speed);
93         float getTimeOfDaySpeed();
94
95         void setDayNightRatioOverride(bool enable, u32 value)
96         {
97                 m_enable_day_night_ratio_override = enable;
98                 m_day_night_ratio_override = value;
99         }
100
101         // counter used internally when triggering ABMs
102         u32 m_added_objects;
103
104 protected:
105         // peer_ids in here should be unique, except that there may be many 0s
106         std::vector<Player*> m_players;
107
108
109         /*
110          *  Below: values under 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         float m_time_of_day_speed;
117         // Used to buffer dtime for adding to m_time_of_day
118         float m_time_counter;
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         /*
123          * Above: values under m_time_lock
124          */
125
126         /* TODO: Add a callback function so these can be updated when a setting
127          *       changes.  At this point in time it doesn't matter (e.g. /set
128          *       is documented to change server settings only)
129          *
130          * TODO: Local caching of settings is not optimal and should at some stage
131          *       be updated to use a global settings object for getting thse values
132          *       (as opposed to the this local caching). This can be addressed in
133          *       a later release.
134          */
135         bool m_cache_enable_shaders;
136
137 private:
138         Mutex m_time_lock;
139
140         DISABLE_CLASS_COPY(Environment);
141 };
142
143 /*
144         Active block modifier interface.
145
146         These are fed into ServerEnvironment at initialization time;
147         ServerEnvironment handles deleting them.
148 */
149
150 class ActiveBlockModifier
151 {
152 public:
153         ActiveBlockModifier(){};
154         virtual ~ActiveBlockModifier(){};
155
156         // Set of contents to trigger on
157         virtual std::set<std::string> getTriggerContents()=0;
158         // Set of required neighbors (trigger doesn't happen if none are found)
159         // Empty = do not check neighbors
160         virtual std::set<std::string> getRequiredNeighbors()
161         { return std::set<std::string>(); }
162         // Trigger interval in seconds
163         virtual float getTriggerInterval() = 0;
164         // Random chance of (1 / return value), 0 is disallowed
165         virtual u32 getTriggerChance() = 0;
166         // Whether to modify chance to simulate time lost by an unnattended block
167         virtual bool getSimpleCatchUp() = 0;
168         // This is called usually at interval for 1/chance of the nodes
169         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
170         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
171                         u32 active_object_count, u32 active_object_count_wider){};
172 };
173
174 struct ABMWithState
175 {
176         ActiveBlockModifier *abm;
177         float timer;
178
179         ABMWithState(ActiveBlockModifier *abm_);
180 };
181
182 /*
183         List of active blocks, used by ServerEnvironment
184 */
185
186 class ActiveBlockList
187 {
188 public:
189         void update(std::vector<v3s16> &active_positions,
190                         s16 radius,
191                         std::set<v3s16> &blocks_removed,
192                         std::set<v3s16> &blocks_added);
193
194         bool contains(v3s16 p){
195                 return (m_list.find(p) != m_list.end());
196         }
197
198         void clear(){
199                 m_list.clear();
200         }
201
202         std::set<v3s16> m_list;
203         std::set<v3s16> m_forceloaded_list;
204
205 private:
206 };
207
208 /*
209         The server-side environment.
210
211         This is not thread-safe. Server uses an environment mutex.
212 */
213
214 class ServerEnvironment : public Environment
215 {
216 public:
217         ServerEnvironment(ServerMap *map, GameScripting *scriptIface,
218                         IGameDef *gamedef, const std::string &path_world);
219         ~ServerEnvironment();
220
221         Map & getMap();
222
223         ServerMap & getServerMap();
224
225         //TODO find way to remove this fct!
226         GameScripting* getScriptIface()
227                 { return m_script; }
228
229         IGameDef *getGameDef()
230                 { return m_gamedef; }
231
232         float getSendRecommendedInterval()
233                 { return m_recommended_send_interval; }
234
235         void kickAllPlayers(AccessDeniedCode reason,
236                 const std::string &str_reason, bool reconnect);
237         // Save players
238         void saveLoadedPlayers();
239         void savePlayer(RemotePlayer *player);
240         Player *loadPlayer(const std::string &playername);
241
242         /*
243                 Save and load time of day and game timer
244         */
245         void saveMeta();
246         void loadMeta();
247
248         /*
249                 External ActiveObject interface
250                 -------------------------------------------
251         */
252
253         ServerActiveObject* getActiveObject(u16 id);
254
255         /*
256                 Add an active object to the environment.
257                 Environment handles deletion of object.
258                 Object may be deleted by environment immediately.
259                 If id of object is 0, assigns a free id to it.
260                 Returns the id of the object.
261                 Returns 0 if not added and thus deleted.
262         */
263         u16 addActiveObject(ServerActiveObject *object);
264
265         /*
266                 Add an active object as a static object to the corresponding
267                 MapBlock.
268                 Caller allocates memory, ServerEnvironment frees memory.
269                 Return value: true if succeeded, false if failed.
270                 (note:  not used, pending removal from engine)
271         */
272         //bool addActiveObjectAsStatic(ServerActiveObject *object);
273
274         /*
275                 Find out what new objects have been added to
276                 inside a radius around a position
277         */
278         void getAddedActiveObjects(Player *player, s16 radius,
279                         s16 player_radius,
280                         std::set<u16> &current_objects,
281                         std::queue<u16> &added_objects);
282
283         /*
284                 Find out what new objects have been removed from
285                 inside a radius around a position
286         */
287         void getRemovedActiveObjects(Player* player, s16 radius,
288                         s16 player_radius,
289                         std::set<u16> &current_objects,
290                         std::queue<u16> &removed_objects);
291
292         /*
293                 Get the next message emitted by some active object.
294                 Returns a message with id=0 if no messages are available.
295         */
296         ActiveObjectMessage getActiveObjectMessage();
297
298         /*
299                 Activate objects and dynamically modify for the dtime determined
300                 from timestamp and additional_dtime
301         */
302         void activateBlock(MapBlock *block, u32 additional_dtime=0);
303
304         /*
305                 ActiveBlockModifiers
306                 -------------------------------------------
307         */
308
309         void addActiveBlockModifier(ActiveBlockModifier *abm);
310
311         /*
312                 Other stuff
313                 -------------------------------------------
314         */
315
316         // Script-aware node setters
317         bool setNode(v3s16 p, const MapNode &n);
318         bool removeNode(v3s16 p);
319         bool swapNode(v3s16 p, const MapNode &n);
320
321         // Find all active objects inside a radius around a point
322         void getObjectsInsideRadius(std::vector<u16> &objects, v3f pos, float radius);
323
324         // Clear all objects, loading and going through every MapBlock
325         void clearAllObjects();
326
327         // This makes stuff happen
328         void step(f32 dtime);
329
330         //check if there's a line of sight between two positions
331         bool line_of_sight(v3f pos1, v3f pos2, float stepsize=1.0, v3s16 *p=NULL);
332
333         u32 getGameTime() { return m_game_time; }
334
335         void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
336         float getMaxLagEstimate() { return m_max_lag_estimate; }
337
338         std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
339
340         // Sets the static object status all the active objects in the specified block
341         // This is only really needed for deleting blocks from the map
342         void setStaticForActiveObjectsInBlock(v3s16 blockpos,
343                 bool static_exists, v3s16 static_block=v3s16(0,0,0));
344
345 private:
346
347         /*
348                 Internal ActiveObject interface
349                 -------------------------------------------
350         */
351
352         /*
353                 Add an active object to the environment.
354
355                 Called by addActiveObject.
356
357                 Object may be deleted by environment immediately.
358                 If id of object is 0, assigns a free id to it.
359                 Returns the id of the object.
360                 Returns 0 if not added and thus deleted.
361         */
362         u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
363
364         /*
365                 Remove all objects that satisfy (m_removed && m_known_by_count==0)
366         */
367         void removeRemovedObjects();
368
369         /*
370                 Convert stored objects from block to active
371         */
372         void activateObjects(MapBlock *block, u32 dtime_s);
373
374         /*
375                 Convert objects that are not in active blocks to static.
376
377                 If m_known_by_count != 0, active object is not deleted, but static
378                 data is still updated.
379
380                 If force_delete is set, active object is deleted nevertheless. It
381                 shall only be set so in the destructor of the environment.
382         */
383         void deactivateFarObjects(bool force_delete);
384
385         /*
386                 Member variables
387         */
388
389         // The map
390         ServerMap *m_map;
391         // Lua state
392         GameScripting* m_script;
393         // Game definition
394         IGameDef *m_gamedef;
395         // World path
396         const std::string m_path_world;
397         // Active object list
398         std::map<u16, ServerActiveObject*> m_active_objects;
399         // Outgoing network message buffer for active objects
400         std::queue<ActiveObjectMessage> m_active_object_messages;
401         // Some timers
402         float m_send_recommended_timer;
403         IntervalLimiter m_object_management_interval;
404         // List of active blocks
405         ActiveBlockList m_active_blocks;
406         IntervalLimiter m_active_blocks_management_interval;
407         IntervalLimiter m_active_block_modifier_interval;
408         IntervalLimiter m_active_blocks_nodemetadata_interval;
409         int m_active_block_interval_overload_skip;
410         // Time from the beginning of the game in seconds.
411         // Incremented in step().
412         u32 m_game_time;
413         // A helper variable for incrementing the latter
414         float m_game_time_fraction_counter;
415         std::vector<ABMWithState> m_abms;
416         // An interval for generally sending object positions and stuff
417         float m_recommended_send_interval;
418         // Estimate for general maximum lag as determined by server.
419         // Can raise to high values like 15s with eg. map generation mods.
420         float m_max_lag_estimate;
421 };
422
423 #ifndef SERVER
424
425 #include "clientobject.h"
426 #include "content_cao.h"
427
428 class ClientSimpleObject;
429
430 /*
431         The client-side environment.
432
433         This is not thread-safe.
434         Must be called from main (irrlicht) thread (uses the SceneManager)
435         Client uses an environment mutex.
436 */
437
438 enum ClientEnvEventType
439 {
440         CEE_NONE,
441         CEE_PLAYER_DAMAGE,
442         CEE_PLAYER_BREATH
443 };
444
445 struct ClientEnvEvent
446 {
447         ClientEnvEventType type;
448         union {
449                 //struct{
450                 //} none;
451                 struct{
452                         u8 amount;
453                         bool send_to_server;
454                 } player_damage;
455                 struct{
456                         u16 amount;
457                 } player_breath;
458         };
459 };
460
461 class ClientEnvironment : public Environment
462 {
463 public:
464         ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
465                         ITextureSource *texturesource, IGameDef *gamedef,
466                         IrrlichtDevice *device);
467         ~ClientEnvironment();
468
469         Map & getMap();
470         ClientMap & getClientMap();
471
472         IGameDef *getGameDef()
473         { return m_gamedef; }
474
475         void step(f32 dtime);
476
477         virtual void addPlayer(Player *player);
478         LocalPlayer * getLocalPlayer();
479
480         /*
481                 ClientSimpleObjects
482         */
483
484         void addSimpleObject(ClientSimpleObject *simple);
485
486         /*
487                 ActiveObjects
488         */
489
490         GenericCAO* getGenericCAO(u16 id);
491         ClientActiveObject* getActiveObject(u16 id);
492
493         /*
494                 Adds an active object to the environment.
495                 Environment handles deletion of object.
496                 Object may be deleted by environment immediately.
497                 If id of object is 0, assigns a free id to it.
498                 Returns the id of the object.
499                 Returns 0 if not added and thus deleted.
500         */
501         u16 addActiveObject(ClientActiveObject *object);
502
503         void addActiveObject(u16 id, u8 type, const std::string &init_data);
504         void removeActiveObject(u16 id);
505
506         void processActiveObjectMessage(u16 id, const std::string &data);
507
508         /*
509                 Callbacks for activeobjects
510         */
511
512         void damageLocalPlayer(u8 damage, bool handle_hp=true);
513         void updateLocalPlayerBreath(u16 breath);
514
515         /*
516                 Client likes to call these
517         */
518
519         // Get all nearby objects
520         void getActiveObjects(v3f origin, f32 max_d,
521                         std::vector<DistanceSortedActiveObject> &dest);
522
523         // Get event from queue. CEE_NONE is returned if queue is empty.
524         ClientEnvEvent getClientEvent();
525
526         u16 attachement_parent_ids[USHRT_MAX + 1];
527
528         std::list<std::string> getPlayerNames()
529         { return m_player_names; }
530         void addPlayerName(std::string name)
531         { m_player_names.push_back(name); }
532         void removePlayerName(std::string name)
533         { m_player_names.remove(name); }
534         void updateCameraOffset(v3s16 camera_offset)
535         { m_camera_offset = camera_offset; }
536         v3s16 getCameraOffset()
537         { return m_camera_offset; }
538
539 private:
540         ClientMap *m_map;
541         scene::ISceneManager *m_smgr;
542         ITextureSource *m_texturesource;
543         IGameDef *m_gamedef;
544         IrrlichtDevice *m_irr;
545         std::map<u16, ClientActiveObject*> m_active_objects;
546         std::vector<ClientSimpleObject*> m_simple_objects;
547         std::queue<ClientEnvEvent> m_client_event_queue;
548         IntervalLimiter m_active_object_light_update_interval;
549         IntervalLimiter m_lava_hurt_interval;
550         IntervalLimiter m_drowning_interval;
551         IntervalLimiter m_breathing_interval;
552         std::list<std::string> m_player_names;
553         v3s16 m_camera_offset;
554 };
555
556 #endif
557
558 #endif
559