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