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