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