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