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