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