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