]> git.lizzy.rs Git - minetest.git/blob - src/client.h
Add particle animation, glow
[minetest.git] / src / client.h
1 /*
2 Minetest
3 Copyright (C) 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 CLIENT_HEADER
21 #define CLIENT_HEADER
22
23 #include "network/connection.h"
24 #include "clientenvironment.h"
25 #include "irrlichttypes_extrabloated.h"
26 #include "threading/mutex.h"
27 #include <ostream>
28 #include <map>
29 #include <set>
30 #include <vector>
31 #include "clientobject.h"
32 #include "gamedef.h"
33 #include "inventorymanager.h"
34 #include "localplayer.h"
35 #include "hud.h"
36 #include "particles.h"
37 #include "mapnode.h"
38 #include "tileanimation.h"
39
40 struct MeshMakeData;
41 class MapBlockMesh;
42 class IWritableTextureSource;
43 class IWritableShaderSource;
44 class IWritableItemDefManager;
45 class IWritableNodeDefManager;
46 //class IWritableCraftDefManager;
47 class ClientMediaDownloader;
48 struct MapDrawControl;
49 class MtEventManager;
50 struct PointedThing;
51 class Database;
52 class Mapper;
53 struct MinimapMapblock;
54 class Camera;
55 class NetworkPacket;
56
57 struct QueuedMeshUpdate
58 {
59         v3s16 p;
60         MeshMakeData *data;
61         bool ack_block_to_server;
62
63         QueuedMeshUpdate();
64         ~QueuedMeshUpdate();
65 };
66
67 enum LocalClientState {
68         LC_Created,
69         LC_Init,
70         LC_Ready
71 };
72
73 /*
74         A thread-safe queue of mesh update tasks
75 */
76 class MeshUpdateQueue
77 {
78 public:
79         MeshUpdateQueue();
80
81         ~MeshUpdateQueue();
82
83         /*
84                 peer_id=0 adds with nobody to send to
85         */
86         void addBlock(v3s16 p, MeshMakeData *data,
87                         bool ack_block_to_server, bool urgent);
88
89         // Returned pointer must be deleted
90         // Returns NULL if queue is empty
91         QueuedMeshUpdate * pop();
92
93         u32 size()
94         {
95                 MutexAutoLock lock(m_mutex);
96                 return m_queue.size();
97         }
98
99 private:
100         std::vector<QueuedMeshUpdate*> m_queue;
101         std::set<v3s16> m_urgents;
102         Mutex m_mutex;
103 };
104
105 struct MeshUpdateResult
106 {
107         v3s16 p;
108         MapBlockMesh *mesh;
109         bool ack_block_to_server;
110
111         MeshUpdateResult():
112                 p(-1338,-1338,-1338),
113                 mesh(NULL),
114                 ack_block_to_server(false)
115         {
116         }
117 };
118
119 class MeshUpdateThread : public UpdateThread
120 {
121 private:
122         MeshUpdateQueue m_queue_in;
123
124 protected:
125         virtual void doUpdate();
126
127 public:
128
129         MeshUpdateThread() : UpdateThread("Mesh") {}
130
131         void enqueueUpdate(v3s16 p, MeshMakeData *data,
132                         bool ack_block_to_server, bool urgent);
133         MutexedQueue<MeshUpdateResult> m_queue_out;
134
135         v3s16 m_camera_offset;
136 };
137
138 enum ClientEventType
139 {
140         CE_NONE,
141         CE_PLAYER_DAMAGE,
142         CE_PLAYER_FORCE_MOVE,
143         CE_DEATHSCREEN,
144         CE_SHOW_FORMSPEC,
145         CE_SPAWN_PARTICLE,
146         CE_ADD_PARTICLESPAWNER,
147         CE_DELETE_PARTICLESPAWNER,
148         CE_HUDADD,
149         CE_HUDRM,
150         CE_HUDCHANGE,
151         CE_SET_SKY,
152         CE_OVERRIDE_DAY_NIGHT_RATIO,
153 };
154
155 struct ClientEvent
156 {
157         ClientEventType type;
158         union{
159                 //struct{
160                 //} none;
161                 struct{
162                         u8 amount;
163                 } player_damage;
164                 struct{
165                         f32 pitch;
166                         f32 yaw;
167                 } player_force_move;
168                 struct{
169                         bool set_camera_point_target;
170                         f32 camera_point_target_x;
171                         f32 camera_point_target_y;
172                         f32 camera_point_target_z;
173                 } deathscreen;
174                 struct{
175                         std::string *formspec;
176                         std::string *formname;
177                 } show_formspec;
178                 //struct{
179                 //} textures_updated;
180                 struct{
181                         v3f *pos;
182                         v3f *vel;
183                         v3f *acc;
184                         f32 expirationtime;
185                         f32 size;
186                         bool collisiondetection;
187                         bool collision_removal;
188                         bool vertical;
189                         std::string *texture;
190                         struct TileAnimationParams animation;
191                         u8 glow;
192                 } spawn_particle;
193                 struct{
194                         u16 amount;
195                         f32 spawntime;
196                         v3f *minpos;
197                         v3f *maxpos;
198                         v3f *minvel;
199                         v3f *maxvel;
200                         v3f *minacc;
201                         v3f *maxacc;
202                         f32 minexptime;
203                         f32 maxexptime;
204                         f32 minsize;
205                         f32 maxsize;
206                         bool collisiondetection;
207                         bool collision_removal;
208                         u16 attached_id;
209                         bool vertical;
210                         std::string *texture;
211                         u32 id;
212                         struct TileAnimationParams animation;
213                         u8 glow;
214                 } add_particlespawner;
215                 struct{
216                         u32 id;
217                 } delete_particlespawner;
218                 struct{
219                         u32 id;
220                         u8 type;
221                         v2f *pos;
222                         std::string *name;
223                         v2f *scale;
224                         std::string *text;
225                         u32 number;
226                         u32 item;
227                         u32 dir;
228                         v2f *align;
229                         v2f *offset;
230                         v3f *world_pos;
231                         v2s32 * size;
232                 } hudadd;
233                 struct{
234                         u32 id;
235                 } hudrm;
236                 struct{
237                         u32 id;
238                         HudElementStat stat;
239                         v2f *v2fdata;
240                         std::string *sdata;
241                         u32 data;
242                         v3f *v3fdata;
243                         v2s32 * v2s32data;
244                 } hudchange;
245                 struct{
246                         video::SColor *bgcolor;
247                         std::string *type;
248                         std::vector<std::string> *params;
249                 } set_sky;
250                 struct{
251                         bool do_override;
252                         float ratio_f;
253                 } override_day_night_ratio;
254         };
255 };
256
257 /*
258         Packet counter
259 */
260
261 class PacketCounter
262 {
263 public:
264         PacketCounter()
265         {
266         }
267
268         void add(u16 command)
269         {
270                 std::map<u16, u16>::iterator n = m_packets.find(command);
271                 if(n == m_packets.end())
272                 {
273                         m_packets[command] = 1;
274                 }
275                 else
276                 {
277                         n->second++;
278                 }
279         }
280
281         void clear()
282         {
283                 for(std::map<u16, u16>::iterator
284                                 i = m_packets.begin();
285                                 i != m_packets.end(); ++i)
286                 {
287                         i->second = 0;
288                 }
289         }
290
291         void print(std::ostream &o)
292         {
293                 for(std::map<u16, u16>::iterator
294                                 i = m_packets.begin();
295                                 i != m_packets.end(); ++i)
296                 {
297                         o<<"cmd "<<i->first
298                                         <<" count "<<i->second
299                                         <<std::endl;
300                 }
301         }
302
303 private:
304         // command, count
305         std::map<u16, u16> m_packets;
306 };
307
308 class Client : public con::PeerHandler, public InventoryManager, public IGameDef
309 {
310 public:
311         /*
312                 NOTE: Nothing is thread-safe here.
313         */
314
315         Client(
316                         IrrlichtDevice *device,
317                         const char *playername,
318                         std::string password,
319                         MapDrawControl &control,
320                         IWritableTextureSource *tsrc,
321                         IWritableShaderSource *shsrc,
322                         IWritableItemDefManager *itemdef,
323                         IWritableNodeDefManager *nodedef,
324                         ISoundManager *sound,
325                         MtEventManager *event,
326                         bool ipv6
327         );
328
329         ~Client();
330
331         /*
332          request all threads managed by client to be stopped
333          */
334         void Stop();
335
336
337         bool isShutdown();
338
339         /*
340                 The name of the local player should already be set when
341                 calling this, as it is sent in the initialization.
342         */
343         void connect(Address address,
344                         const std::string &address_name,
345                         bool is_local_server);
346
347         /*
348                 Stuff that references the environment is valid only as
349                 long as this is not called. (eg. Players)
350                 If this throws a PeerNotFoundException, the connection has
351                 timed out.
352         */
353         void step(float dtime);
354
355         /*
356          * Command Handlers
357          */
358
359         void handleCommand(NetworkPacket* pkt);
360
361         void handleCommand_Null(NetworkPacket* pkt) {};
362         void handleCommand_Deprecated(NetworkPacket* pkt);
363         void handleCommand_Hello(NetworkPacket* pkt);
364         void handleCommand_AuthAccept(NetworkPacket* pkt);
365         void handleCommand_AcceptSudoMode(NetworkPacket* pkt);
366         void handleCommand_DenySudoMode(NetworkPacket* pkt);
367         void handleCommand_InitLegacy(NetworkPacket* pkt);
368         void handleCommand_AccessDenied(NetworkPacket* pkt);
369         void handleCommand_RemoveNode(NetworkPacket* pkt);
370         void handleCommand_AddNode(NetworkPacket* pkt);
371         void handleCommand_BlockData(NetworkPacket* pkt);
372         void handleCommand_Inventory(NetworkPacket* pkt);
373         void handleCommand_TimeOfDay(NetworkPacket* pkt);
374         void handleCommand_ChatMessage(NetworkPacket* pkt);
375         void handleCommand_ActiveObjectRemoveAdd(NetworkPacket* pkt);
376         void handleCommand_ActiveObjectMessages(NetworkPacket* pkt);
377         void handleCommand_Movement(NetworkPacket* pkt);
378         void handleCommand_HP(NetworkPacket* pkt);
379         void handleCommand_Breath(NetworkPacket* pkt);
380         void handleCommand_MovePlayer(NetworkPacket* pkt);
381         void handleCommand_PlayerItem(NetworkPacket* pkt);
382         void handleCommand_DeathScreen(NetworkPacket* pkt);
383         void handleCommand_AnnounceMedia(NetworkPacket* pkt);
384         void handleCommand_Media(NetworkPacket* pkt);
385         void handleCommand_ToolDef(NetworkPacket* pkt);
386         void handleCommand_NodeDef(NetworkPacket* pkt);
387         void handleCommand_CraftItemDef(NetworkPacket* pkt);
388         void handleCommand_ItemDef(NetworkPacket* pkt);
389         void handleCommand_PlaySound(NetworkPacket* pkt);
390         void handleCommand_StopSound(NetworkPacket* pkt);
391         void handleCommand_Privileges(NetworkPacket* pkt);
392         void handleCommand_InventoryFormSpec(NetworkPacket* pkt);
393         void handleCommand_DetachedInventory(NetworkPacket* pkt);
394         void handleCommand_ShowFormSpec(NetworkPacket* pkt);
395         void handleCommand_SpawnParticle(NetworkPacket* pkt);
396         void handleCommand_AddParticleSpawner(NetworkPacket* pkt);
397         void handleCommand_DeleteParticleSpawner(NetworkPacket* pkt);
398         void handleCommand_HudAdd(NetworkPacket* pkt);
399         void handleCommand_HudRemove(NetworkPacket* pkt);
400         void handleCommand_HudChange(NetworkPacket* pkt);
401         void handleCommand_HudSetFlags(NetworkPacket* pkt);
402         void handleCommand_HudSetParam(NetworkPacket* pkt);
403         void handleCommand_HudSetSky(NetworkPacket* pkt);
404         void handleCommand_OverrideDayNightRatio(NetworkPacket* pkt);
405         void handleCommand_LocalPlayerAnimations(NetworkPacket* pkt);
406         void handleCommand_EyeOffset(NetworkPacket* pkt);
407         void handleCommand_SrpBytesSandB(NetworkPacket* pkt);
408
409         void ProcessData(NetworkPacket *pkt);
410
411         void Send(NetworkPacket* pkt);
412
413         void interact(u8 action, const PointedThing& pointed);
414
415         void sendNodemetaFields(v3s16 p, const std::string &formname,
416                 const StringMap &fields);
417         void sendInventoryFields(const std::string &formname,
418                 const StringMap &fields);
419         void sendInventoryAction(InventoryAction *a);
420         void sendChatMessage(const std::wstring &message);
421         void sendChangePassword(const std::string &oldpassword,
422                 const std::string &newpassword);
423         void sendDamage(u8 damage);
424         void sendBreath(u16 breath);
425         void sendRespawn();
426         void sendReady();
427
428         ClientEnvironment& getEnv() { return m_env; }
429         ITextureSource *tsrc() { return getTextureSource(); }
430         ISoundManager *sound() { return getSoundManager(); }
431
432         // Causes urgent mesh updates (unlike Map::add/removeNodeWithEvent)
433         void removeNode(v3s16 p);
434         void addNode(v3s16 p, MapNode n, bool remove_metadata = true);
435
436         void setPlayerControl(PlayerControl &control);
437
438         void selectPlayerItem(u16 item);
439         u16 getPlayerItem() const
440         { return m_playeritem; }
441
442         // Returns true if the inventory of the local player has been
443         // updated from the server. If it is true, it is set to false.
444         bool getLocalInventoryUpdated();
445         // Copies the inventory of the local player to parameter
446         void getLocalInventory(Inventory &dst);
447
448         /* InventoryManager interface */
449         Inventory* getInventory(const InventoryLocation &loc);
450         void inventoryAction(InventoryAction *a);
451
452         const std::list<std::string> &getConnectedPlayerNames()
453         {
454                 return m_env.getPlayerNames();
455         }
456
457         float getAnimationTime();
458
459         int getCrackLevel();
460         void setCrack(int level, v3s16 pos);
461
462         u16 getHP();
463
464         bool checkPrivilege(const std::string &priv) const
465         { return (m_privileges.count(priv) != 0); }
466
467         bool getChatMessage(std::wstring &message);
468         void typeChatMessage(const std::wstring& message);
469
470         u64 getMapSeed(){ return m_map_seed; }
471
472         void addUpdateMeshTask(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
473         // Including blocks at appropriate edges
474         void addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
475         void addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server=false, bool urgent=false);
476
477         void updateCameraOffset(v3s16 camera_offset)
478         { m_mesh_update_thread.m_camera_offset = camera_offset; }
479
480         // Get event from queue. CE_NONE is returned if queue is empty.
481         ClientEvent getClientEvent();
482
483         bool accessDenied()
484         { return m_access_denied; }
485
486         bool reconnectRequested() { return m_access_denied_reconnect; }
487
488         std::string accessDeniedReason()
489         { return m_access_denied_reason; }
490
491         bool itemdefReceived()
492         { return m_itemdef_received; }
493         bool nodedefReceived()
494         { return m_nodedef_received; }
495         bool mediaReceived()
496         { return m_media_downloader == NULL; }
497
498         u8 getProtoVersion()
499         { return m_proto_ver; }
500
501         bool connectedToServer()
502         { return m_con.Connected(); }
503
504         float mediaReceiveProgress();
505
506         void afterContentReceived(IrrlichtDevice *device);
507
508         float getRTT(void);
509         float getCurRate(void);
510         float getAvgRate(void);
511
512         Mapper* getMapper ()
513         { return m_mapper; }
514
515         void setCamera(Camera* camera)
516         { m_camera = camera; }
517
518         Camera* getCamera ()
519         { return m_camera; }
520
521         bool isMinimapDisabledByServer()
522         { return m_minimap_disabled_by_server; }
523
524         // IGameDef interface
525         virtual IItemDefManager* getItemDefManager();
526         virtual INodeDefManager* getNodeDefManager();
527         virtual ICraftDefManager* getCraftDefManager();
528         ITextureSource* getTextureSource();
529         virtual IShaderSource* getShaderSource();
530         IShaderSource *shsrc() { return getShaderSource(); }
531         scene::ISceneManager* getSceneManager();
532         virtual u16 allocateUnknownNodeId(const std::string &name);
533         virtual ISoundManager* getSoundManager();
534         virtual MtEventManager* getEventManager();
535         virtual ParticleManager* getParticleManager();
536         bool checkLocalPrivilege(const std::string &priv)
537         { return checkPrivilege(priv); }
538         virtual scene::IAnimatedMesh* getMesh(const std::string &filename);
539
540         // The following set of functions is used by ClientMediaDownloader
541         // Insert a media file appropriately into the appropriate manager
542         bool loadMedia(const std::string &data, const std::string &filename);
543         // Send a request for conventional media transfer
544         void request_media(const std::vector<std::string> &file_requests);
545         // Send a notification that no conventional media transfer is needed
546         void received_media();
547
548         LocalClientState getState() { return m_state; }
549
550         void makeScreenshot(IrrlichtDevice *device);
551
552 private:
553
554         // Virtual methods from con::PeerHandler
555         void peerAdded(con::Peer *peer);
556         void deletingPeer(con::Peer *peer, bool timeout);
557
558         void initLocalMapSaving(const Address &address,
559                         const std::string &hostname,
560                         bool is_local_server);
561
562         void ReceiveAll();
563         void Receive();
564
565         void sendPlayerPos();
566         // Send the item number 'item' as player item to the server
567         void sendPlayerItem(u16 item);
568
569         void deleteAuthData();
570         // helper method shared with clientpackethandler
571         static AuthMechanism choseAuthMech(const u32 mechs);
572
573         void sendLegacyInit(const char* playerName, const char* playerPassword);
574         void sendInit(const std::string &playerName);
575         void startAuth(AuthMechanism chosen_auth_mechanism);
576         void sendDeletedBlocks(std::vector<v3s16> &blocks);
577         void sendGotBlocks(v3s16 block);
578         void sendRemovedSounds(std::vector<s32> &soundList);
579
580         // Helper function
581         inline std::string getPlayerName()
582         { return m_env.getLocalPlayer()->getName(); }
583
584         float m_packetcounter_timer;
585         float m_connection_reinit_timer;
586         float m_avg_rtt_timer;
587         float m_playerpos_send_timer;
588         float m_ignore_damage_timer; // Used after server moves player
589         IntervalLimiter m_map_timer_and_unload_interval;
590
591         IWritableTextureSource *m_tsrc;
592         IWritableShaderSource *m_shsrc;
593         IWritableItemDefManager *m_itemdef;
594         IWritableNodeDefManager *m_nodedef;
595         ISoundManager *m_sound;
596         MtEventManager *m_event;
597
598
599         MeshUpdateThread m_mesh_update_thread;
600         ClientEnvironment m_env;
601         ParticleManager m_particle_manager;
602         con::Connection m_con;
603         IrrlichtDevice *m_device;
604         Camera *m_camera;
605         Mapper *m_mapper;
606         bool m_minimap_disabled_by_server;
607         // Server serialization version
608         u8 m_server_ser_ver;
609
610         // Used version of the protocol with server
611         // Values smaller than 25 only mean they are smaller than 25,
612         // and aren't accurate. We simply just don't know, because
613         // the server didn't send the version back then.
614         // If 0, server init hasn't been received yet.
615         u8 m_proto_ver;
616
617         u16 m_playeritem;
618         bool m_inventory_updated;
619         Inventory *m_inventory_from_server;
620         float m_inventory_from_server_age;
621         PacketCounter m_packetcounter;
622         // Block mesh animation parameters
623         float m_animation_time;
624         int m_crack_level;
625         v3s16 m_crack_pos;
626         // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT
627         //s32 m_daynight_i;
628         //u32 m_daynight_ratio;
629         std::queue<std::wstring> m_chat_queue;
630
631         // The authentication methods we can use to enter sudo mode (=change password)
632         u32 m_sudo_auth_methods;
633
634         // The seed returned by the server in TOCLIENT_INIT is stored here
635         u64 m_map_seed;
636
637         // Auth data
638         std::string m_playername;
639         std::string m_password;
640         // If set, this will be sent (and cleared) upon a TOCLIENT_ACCEPT_SUDO_MODE
641         std::string m_new_password;
642         // Usable by auth mechanisms.
643         AuthMechanism m_chosen_auth_mech;
644         void * m_auth_data;
645
646
647         bool m_access_denied;
648         bool m_access_denied_reconnect;
649         std::string m_access_denied_reason;
650         std::queue<ClientEvent> m_client_event_queue;
651         bool m_itemdef_received;
652         bool m_nodedef_received;
653         ClientMediaDownloader *m_media_downloader;
654
655         // time_of_day speed approximation for old protocol
656         bool m_time_of_day_set;
657         float m_last_time_of_day_f;
658         float m_time_of_day_update_timer;
659
660         // An interval for generally sending object positions and stuff
661         float m_recommended_send_interval;
662
663         // Sounds
664         float m_removed_sounds_check_timer;
665         // Mapping from server sound ids to our sound ids
666         UNORDERED_MAP<s32, int> m_sounds_server_to_client;
667         // And the other way!
668         UNORDERED_MAP<int, s32> m_sounds_client_to_server;
669         // And relations to objects
670         UNORDERED_MAP<int, u16> m_sounds_to_objects;
671
672         // Privileges
673         UNORDERED_SET<std::string> m_privileges;
674
675         // Detached inventories
676         // key = name
677         UNORDERED_MAP<std::string, Inventory*> m_detached_inventories;
678
679         // Storage for mesh data for creating multiple instances of the same mesh
680         StringMap m_mesh_data;
681
682         // own state
683         LocalClientState m_state;
684
685         // Used for saving server map to disk client-side
686         Database *m_localdb;
687         IntervalLimiter m_localdb_save_interval;
688         u16 m_cache_save_interval;
689
690         // TODO: Add callback to update these when g_settings changes
691         bool m_cache_smooth_lighting;
692         bool m_cache_enable_shaders;
693         bool m_cache_use_tangent_vertices;
694
695         DISABLE_CLASS_COPY(Client);
696 };
697
698 #endif // !CLIENT_HEADER