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