Add minetest.swap_node
[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 <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 IBackgroundBlockEmerger;
48 class Map;
49 class ServerMap;
50 class ClientMap;
51 class GameScripting;
52 class Player;
53
54 class Environment
55 {
56 public:
57         // Environment will delete the map passed to the constructor
58         Environment();
59         virtual ~Environment();
60
61         /*
62                 Step everything in environment.
63                 - Move players
64                 - Step mobs
65                 - Run timers of map
66         */
67         virtual void step(f32 dtime) = 0;
68
69         virtual Map & getMap() = 0;
70
71         virtual void addPlayer(Player *player);
72         void removePlayer(u16 peer_id);
73         Player * getPlayer(u16 peer_id);
74         Player * getPlayer(const char *name);
75         Player * getRandomConnectedPlayer();
76         Player * getNearestConnectedPlayer(v3f pos);
77         std::list<Player*> getPlayers();
78         std::list<Player*> getPlayers(bool ignore_disconnected);
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         std::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(std::list<v3s16> &active_positions,
160                         s16 radius,
161                         std::set<v3s16> &blocks_removed,
162                         std::set<v3s16> &blocks_added);
163
164         bool contains(v3s16 p){
165                 return (m_list.find(p) != m_list.end());
166         }
167
168         void clear(){
169                 m_list.clear();
170         }
171
172         std::set<v3s16> m_list;
173
174 private:
175 };
176
177 /*
178         The server-side environment.
179
180         This is not thread-safe. Server uses an environment mutex.
181 */
182
183 class ServerEnvironment : public Environment
184 {
185 public:
186         ServerEnvironment(ServerMap *map, GameScripting *scriptIface,
187                         IGameDef *gamedef,
188                         IBackgroundBlockEmerger *emerger);
189         ~ServerEnvironment();
190
191         Map & getMap();
192
193         ServerMap & getServerMap();
194
195         //TODO find way to remove this fct!
196         GameScripting* getScriptIface()
197                 { return m_script; }
198
199         IGameDef *getGameDef()
200                 { return m_gamedef; }
201
202         float getSendRecommendedInterval()
203                 { return m_recommended_send_interval; }
204
205         /*
206                 Save players
207         */
208         void serializePlayers(const std::string &savedir);
209         void deSerializePlayers(const std::string &savedir);
210
211         /*
212                 Save and load time of day and game timer
213         */
214         void saveMeta(const std::string &savedir);
215         void loadMeta(const std::string &savedir);
216
217         /*
218                 External ActiveObject interface
219                 -------------------------------------------
220         */
221
222         ServerActiveObject* getActiveObject(u16 id);
223
224         /*
225                 Add an active object to the environment.
226                 Environment handles deletion of object.
227                 Object may be deleted by environment immediately.
228                 If id of object is 0, assigns a free id to it.
229                 Returns the id of the object.
230                 Returns 0 if not added and thus deleted.
231         */
232         u16 addActiveObject(ServerActiveObject *object);
233         
234         /*
235                 Add an active object as a static object to the corresponding
236                 MapBlock.
237                 Caller allocates memory, ServerEnvironment frees memory.
238                 Return value: true if succeeded, false if failed.
239                 (note:  not used, pending removal from engine)
240         */
241         //bool addActiveObjectAsStatic(ServerActiveObject *object);
242         
243         /*
244                 Find out what new objects have been added to
245                 inside a radius around a position
246         */
247         void getAddedActiveObjects(v3s16 pos, s16 radius,
248                         std::set<u16> &current_objects,
249                         std::set<u16> &added_objects);
250
251         /*
252                 Find out what new objects have been removed from
253                 inside a radius around a position
254         */
255         void getRemovedActiveObjects(v3s16 pos, s16 radius,
256                         std::set<u16> &current_objects,
257                         std::set<u16> &removed_objects);
258         
259         /*
260                 Get the next message emitted by some active object.
261                 Returns a message with id=0 if no messages are available.
262         */
263         ActiveObjectMessage getActiveObjectMessage();
264
265         /*
266                 Activate objects and dynamically modify for the dtime determined
267                 from timestamp and additional_dtime
268         */
269         void activateBlock(MapBlock *block, u32 additional_dtime=0);
270
271         /*
272                 ActiveBlockModifiers
273                 -------------------------------------------
274         */
275
276         void addActiveBlockModifier(ActiveBlockModifier *abm);
277
278         /*
279                 Other stuff
280                 -------------------------------------------
281         */
282
283         // Script-aware node setters
284         bool setNode(v3s16 p, const MapNode &n);
285         bool removeNode(v3s16 p);
286         bool swapNode(v3s16 p, const MapNode &n);
287         
288         // Find all active objects inside a radius around a point
289         std::set<u16> getObjectsInsideRadius(v3f pos, float radius);
290         
291         // Clear all objects, loading and going through every MapBlock
292         void clearAllObjects();
293         
294         // This makes stuff happen
295         void step(f32 dtime);
296         
297         //check if there's a line of sight between two positions
298         bool line_of_sight(v3f pos1, v3f pos2, float stepsize=1.0);
299
300         u32 getGameTime() { return m_game_time; }
301
302         void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
303         float getMaxLagEstimate() { return m_max_lag_estimate; }
304         
305         // is weather active in this environment?
306         bool m_use_weather;
307         
308 private:
309
310         /*
311                 Internal ActiveObject interface
312                 -------------------------------------------
313         */
314
315         /*
316                 Add an active object to the environment.
317
318                 Called by addActiveObject.
319
320                 Object may be deleted by environment immediately.
321                 If id of object is 0, assigns a free id to it.
322                 Returns the id of the object.
323                 Returns 0 if not added and thus deleted.
324         */
325         u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
326         
327         /*
328                 Remove all objects that satisfy (m_removed && m_known_by_count==0)
329         */
330         void removeRemovedObjects();
331         
332         /*
333                 Convert stored objects from block to active
334         */
335         void activateObjects(MapBlock *block, u32 dtime_s);
336         
337         /*
338                 Convert objects that are not in active blocks to static.
339
340                 If m_known_by_count != 0, active object is not deleted, but static
341                 data is still updated.
342
343                 If force_delete is set, active object is deleted nevertheless. It
344                 shall only be set so in the destructor of the environment.
345         */
346         void deactivateFarObjects(bool force_delete);
347
348         /*
349                 Member variables
350         */
351         
352         // The map
353         ServerMap *m_map;
354         // Lua state
355         GameScripting* m_script;
356         // Game definition
357         IGameDef *m_gamedef;
358         // Background block emerger (the EmergeManager, in practice)
359         IBackgroundBlockEmerger *m_emerger;
360         // Active object list
361         std::map<u16, ServerActiveObject*> m_active_objects;
362         // Outgoing network message buffer for active objects
363         std::list<ActiveObjectMessage> m_active_object_messages;
364         // Some timers
365         float m_random_spawn_timer; // used for experimental code
366         float m_send_recommended_timer;
367         IntervalLimiter m_object_management_interval;
368         // List of active blocks
369         ActiveBlockList m_active_blocks;
370         IntervalLimiter m_active_blocks_management_interval;
371         IntervalLimiter m_active_block_modifier_interval;
372         IntervalLimiter m_active_blocks_nodemetadata_interval;
373         int m_active_block_interval_overload_skip;
374         // Time from the beginning of the game in seconds.
375         // Incremented in step().
376         u32 m_game_time;
377         // A helper variable for incrementing the latter
378         float m_game_time_fraction_counter;
379         std::list<ABMWithState> m_abms;
380         // An interval for generally sending object positions and stuff
381         float m_recommended_send_interval;
382         // Estimate for general maximum lag as determined by server.
383         // Can raise to high values like 15s with eg. map generation mods.
384         float m_max_lag_estimate;
385 };
386
387 #ifndef SERVER
388
389 #include "clientobject.h"
390 class ClientSimpleObject;
391
392 /*
393         The client-side environment.
394
395         This is not thread-safe.
396         Must be called from main (irrlicht) thread (uses the SceneManager)
397         Client uses an environment mutex.
398 */
399
400 enum ClientEnvEventType
401 {
402         CEE_NONE,
403         CEE_PLAYER_DAMAGE,
404         CEE_PLAYER_BREATH
405 };
406
407 struct ClientEnvEvent
408 {
409         ClientEnvEventType type;
410         union {
411                 struct{
412                 } none;
413                 struct{
414                         u8 amount;
415                         bool send_to_server;
416                 } player_damage;
417                 struct{
418                         u16 amount;
419                 } player_breath;
420         };
421 };
422
423 class ClientEnvironment : public Environment
424 {
425 public:
426         ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
427                         ITextureSource *texturesource, IGameDef *gamedef,
428                         IrrlichtDevice *device);
429         ~ClientEnvironment();
430
431         Map & getMap();
432         ClientMap & getClientMap();
433
434         IGameDef *getGameDef()
435         { return m_gamedef; }
436
437         void step(f32 dtime);
438
439         virtual void addPlayer(Player *player);
440         LocalPlayer * getLocalPlayer();
441         
442         /*
443                 ClientSimpleObjects
444         */
445
446         void addSimpleObject(ClientSimpleObject *simple);
447
448         /*
449                 ActiveObjects
450         */
451         
452         ClientActiveObject* getActiveObject(u16 id);
453
454         /*
455                 Adds an active object to the environment.
456                 Environment handles deletion of object.
457                 Object may be deleted by environment immediately.
458                 If id of object is 0, assigns a free id to it.
459                 Returns the id of the object.
460                 Returns 0 if not added and thus deleted.
461         */
462         u16 addActiveObject(ClientActiveObject *object);
463
464         void addActiveObject(u16 id, u8 type, const std::string &init_data);
465         void removeActiveObject(u16 id);
466
467         void processActiveObjectMessage(u16 id, const std::string &data);
468
469         /*
470                 Callbacks for activeobjects
471         */
472
473         void damageLocalPlayer(u8 damage, bool handle_hp=true);
474         void updateLocalPlayerBreath(u16 breath);
475
476         /*
477                 Client likes to call these
478         */
479         
480         // Get all nearby objects
481         void getActiveObjects(v3f origin, f32 max_d,
482                         std::vector<DistanceSortedActiveObject> &dest);
483         
484         // Get event from queue. CEE_NONE is returned if queue is empty.
485         ClientEnvEvent getClientEvent();
486
487         std::vector<core::vector2d<int> > attachment_list; // X is child ID, Y is parent ID
488
489         std::list<std::string> getPlayerNames()
490         { return m_player_names; }
491         void addPlayerName(std::string name)
492         { m_player_names.push_back(name); }
493         void removePlayerName(std::string name)
494         { m_player_names.remove(name); }
495         
496 private:
497         ClientMap *m_map;
498         scene::ISceneManager *m_smgr;
499         ITextureSource *m_texturesource;
500         IGameDef *m_gamedef;
501         IrrlichtDevice *m_irr;
502         std::map<u16, ClientActiveObject*> m_active_objects;
503         std::list<ClientSimpleObject*> m_simple_objects;
504         std::list<ClientEnvEvent> m_client_event_queue;
505         IntervalLimiter m_active_object_light_update_interval;
506         IntervalLimiter m_lava_hurt_interval;
507         IntervalLimiter m_drowning_interval;
508         IntervalLimiter m_breathing_interval;
509         std::list<std::string> m_player_names;
510 };
511
512 #endif
513
514 #endif
515