utility.h: Change Buffer's interface to be more compatible with SharedBuffer's interf...
[oweals/minetest.git] / src / environment.h
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
14
15 You should have received a copy of the GNU 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 (actually it only contains the brightness)
30         - etc.
31 */
32
33 #include <list>
34 #include "common_irrlicht.h"
35 #include "player.h"
36 #include "map.h"
37 #include <ostream>
38 #include "utility.h"
39 #include "activeobject.h"
40
41 class Server;
42 class ActiveBlockModifier;
43 class ServerActiveObject;
44
45 class Environment
46 {
47 public:
48         // Environment will delete the map passed to the constructor
49         Environment();
50         virtual ~Environment();
51
52         /*
53                 Step everything in environment.
54                 - Move players
55                 - Step mobs
56                 - Run timers of map
57         */
58         virtual void step(f32 dtime) = 0;
59
60         virtual Map & getMap() = 0;
61
62         virtual void addPlayer(Player *player);
63         void removePlayer(u16 peer_id);
64         Player * getPlayer(u16 peer_id);
65         Player * getPlayer(const char *name);
66         Player * getRandomConnectedPlayer();
67         Player * getNearestConnectedPlayer(v3f pos);
68         core::list<Player*> getPlayers();
69         core::list<Player*> getPlayers(bool ignore_disconnected);
70         void printPlayers(std::ostream &o);
71         
72         //void setDayNightRatio(u32 r);
73         u32 getDayNightRatio();
74         
75         // 0-23999
76         virtual void setTimeOfDay(u32 time)
77         {
78                 m_time_of_day = time;
79         }
80
81         u32 getTimeOfDay()
82         {
83                 return m_time_of_day;
84         }
85
86 protected:
87         // peer_ids in here should be unique, except that there may be many 0s
88         core::list<Player*> m_players;
89         // Brightness
90         //u32 m_daynight_ratio;
91         // Time of day in milli-hours (0-23999); determines day and night
92         u32 m_time_of_day;
93 };
94
95 /*
96         List of active blocks, used by ServerEnvironment
97 */
98
99 class ActiveBlockList
100 {
101 public:
102         void update(core::list<v3s16> &active_positions,
103                         s16 radius,
104                         core::map<v3s16, bool> &blocks_removed,
105                         core::map<v3s16, bool> &blocks_added);
106
107         bool contains(v3s16 p){
108                 return (m_list.find(p) != NULL);
109         }
110
111         void clear(){
112                 m_list.clear();
113         }
114
115         core::map<v3s16, bool> m_list;
116
117 private:
118 };
119
120 /*
121         The server-side environment.
122
123         This is not thread-safe. Server uses an environment mutex.
124 */
125
126 class ServerEnvironment : public Environment
127 {
128 public:
129         ServerEnvironment(ServerMap *map, Server *server);
130         ~ServerEnvironment();
131
132         Map & getMap()
133         {
134                 return *m_map;
135         }
136
137         ServerMap & getServerMap()
138         {
139                 return *m_map;
140         }
141
142         Server * getServer()
143         {
144                 return m_server;
145         }
146
147         void step(f32 dtime);
148         
149         /*
150                 Save players
151         */
152         void serializePlayers(const std::string &savedir);
153         void deSerializePlayers(const std::string &savedir);
154
155         /*
156                 Save and load time of day and game timer
157         */
158         void saveMeta(const std::string &savedir);
159         void loadMeta(const std::string &savedir);
160
161         /*
162                 External ActiveObject interface
163                 -------------------------------------------
164         */
165
166         ServerActiveObject* getActiveObject(u16 id);
167
168         /*
169                 Add an active object to the environment.
170                 Environment handles deletion of object.
171                 Object may be deleted by environment immediately.
172                 If id of object is 0, assigns a free id to it.
173                 Returns the id of the object.
174                 Returns 0 if not added and thus deleted.
175         */
176         u16 addActiveObject(ServerActiveObject *object);
177         
178         /*
179                 Add an active object as a static object to the corresponding
180                 MapBlock.
181                 Caller allocates memory, ServerEnvironment frees memory.
182                 Return value: true if succeeded, false if failed.
183         */
184         bool addActiveObjectAsStatic(ServerActiveObject *object);
185         
186         /*
187                 Find out what new objects have been added to
188                 inside a radius around a position
189         */
190         void getAddedActiveObjects(v3s16 pos, s16 radius,
191                         core::map<u16, bool> &current_objects,
192                         core::map<u16, bool> &added_objects);
193
194         /*
195                 Find out what new objects have been removed from
196                 inside a radius around a position
197         */
198         void getRemovedActiveObjects(v3s16 pos, s16 radius,
199                         core::map<u16, bool> &current_objects,
200                         core::map<u16, bool> &removed_objects);
201         
202         /*
203                 Get the next message emitted by some active object.
204                 Returns a message with id=0 if no messages are available.
205         */
206         ActiveObjectMessage getActiveObjectMessage();
207
208         /*
209                 Activate objects and dynamically modify for the dtime determined
210                 from timestamp and additional_dtime
211         */
212         void activateBlock(MapBlock *block, u32 additional_dtime=0);
213
214         /*
215                 ActiveBlockModifiers (TODO)
216                 -------------------------------------------
217         */
218
219         void addActiveBlockModifier(ActiveBlockModifier *abm);
220
221         /* Other stuff */
222         
223         // Clear all objects, loading and going through every MapBlock
224         void clearAllObjects();
225
226 private:
227
228         /*
229                 Internal ActiveObject interface
230                 -------------------------------------------
231         */
232
233         /*
234                 Add an active object to the environment.
235
236                 Called by addActiveObject.
237
238                 Object may be deleted by environment immediately.
239                 If id of object is 0, assigns a free id to it.
240                 Returns the id of the object.
241                 Returns 0 if not added and thus deleted.
242         */
243         u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed);
244         
245         /*
246                 Remove all objects that satisfy (m_removed && m_known_by_count==0)
247         */
248         void removeRemovedObjects();
249         
250         /*
251                 Convert stored objects from block to active
252         */
253         void activateObjects(MapBlock *block);
254         
255         /*
256                 Convert objects that are not in active blocks to static.
257
258                 If m_known_by_count != 0, active object is not deleted, but static
259                 data is still updated.
260
261                 If force_delete is set, active object is deleted nevertheless. It
262                 shall only be set so in the destructor of the environment.
263         */
264         void deactivateFarObjects(bool force_delete);
265
266         /*
267                 Member variables
268         */
269         
270         // The map
271         ServerMap *m_map;
272         // Pointer to server (which is handling this environment)
273         Server *m_server;
274         // Active object list
275         core::map<u16, ServerActiveObject*> m_active_objects;
276         // Outgoing network message buffer for active objects
277         Queue<ActiveObjectMessage> m_active_object_messages;
278         // Some timers
279         float m_random_spawn_timer; // used for experimental code
280         float m_send_recommended_timer;
281         IntervalLimiter m_object_management_interval;
282         // List of active blocks
283         ActiveBlockList m_active_blocks;
284         IntervalLimiter m_active_blocks_management_interval;
285         IntervalLimiter m_active_blocks_test_interval;
286         IntervalLimiter m_active_blocks_nodemetadata_interval;
287         // Time from the beginning of the game in seconds.
288         // Incremented in step().
289         u32 m_game_time;
290         // A helper variable for incrementing the latter
291         float m_game_time_fraction_counter;
292 };
293
294 /*
295         Active block modifier interface.
296
297         These are fed into ServerEnvironment at initialization time;
298         ServerEnvironment handles deleting them.
299 */
300
301 class ActiveBlockModifier
302 {
303 public:
304         ActiveBlockModifier(){};
305         virtual ~ActiveBlockModifier(){};
306
307         //virtual core::list<u8> update(ServerEnvironment *env) = 0;
308         virtual u32 getTriggerContentCount(){ return 1;}
309         virtual u8 getTriggerContent(u32 i) = 0;
310         virtual float getActiveInterval() = 0;
311         // chance of (1 / return value), 0 is disallowed
312         virtual u32 getActiveChance() = 0;
313         // This is called usually at interval for 1/chance of the nodes
314         virtual void triggerEvent(ServerEnvironment *env, v3s16 p) = 0;
315 };
316
317 #ifndef SERVER
318
319 #include "clientobject.h"
320
321 /*
322         The client-side environment.
323
324         This is not thread-safe.
325         Must be called from main (irrlicht) thread (uses the SceneManager)
326         Client uses an environment mutex.
327 */
328
329 enum ClientEnvEventType
330 {
331         CEE_NONE,
332         CEE_PLAYER_DAMAGE
333 };
334
335 struct ClientEnvEvent
336 {
337         ClientEnvEventType type;
338         union {
339                 struct{
340                 } none;
341                 struct{
342                         u8 amount;
343                 } player_damage;
344         };
345 };
346
347 class ClientEnvironment : public Environment
348 {
349 public:
350         ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr);
351         ~ClientEnvironment();
352
353         Map & getMap()
354         {
355                 return *m_map;
356         }
357
358         ClientMap & getClientMap()
359         {
360                 return *m_map;
361         }
362
363         void step(f32 dtime);
364
365         virtual void addPlayer(Player *player);
366         LocalPlayer * getLocalPlayer();
367
368         void updateMeshes(v3s16 blockpos);
369         void expireMeshes(bool only_daynight_diffed);
370
371         void setTimeOfDay(u32 time)
372         {
373                 u32 old_dr = getDayNightRatio();
374
375                 Environment::setTimeOfDay(time);
376
377                 if(getDayNightRatio() != old_dr)
378                 {
379                         dout_client<<DTIME<<"ClientEnvironment: DayNightRatio changed"
380                                         <<" -> expiring meshes"<<std::endl;
381                         expireMeshes(true);
382                 }
383         }
384
385         /*
386                 ActiveObjects
387         */
388         
389         ClientActiveObject* getActiveObject(u16 id);
390
391         /*
392                 Adds an active object to the environment.
393                 Environment handles deletion of object.
394                 Object may be deleted by environment immediately.
395                 If id of object is 0, assigns a free id to it.
396                 Returns the id of the object.
397                 Returns 0 if not added and thus deleted.
398         */
399         u16 addActiveObject(ClientActiveObject *object);
400
401         void addActiveObject(u16 id, u8 type, const std::string &init_data);
402         void removeActiveObject(u16 id);
403
404         void processActiveObjectMessage(u16 id, const std::string &data);
405
406         /*
407                 Callbacks for activeobjects
408         */
409
410         void damageLocalPlayer(u8 damage);
411
412         /*
413                 Client likes to call these
414         */
415         
416         // Get all nearby objects
417         void getActiveObjects(v3f origin, f32 max_d,
418                         core::array<DistanceSortedActiveObject> &dest);
419         
420         // Get event from queue. CEE_NONE is returned if queue is empty.
421         ClientEnvEvent getClientEvent();
422         
423 private:
424         ClientMap *m_map;
425         scene::ISceneManager *m_smgr;
426         core::map<u16, ClientActiveObject*> m_active_objects;
427         Queue<ClientEnvEvent> m_client_event_queue;
428         IntervalLimiter m_active_object_light_update_interval;
429         IntervalLimiter m_lava_hurt_interval;
430 };
431
432 #endif
433
434 #endif
435