]> git.lizzy.rs Git - minetest.git/blob - src/client/client.h
Add minetest.get_player_window_information() (#12367)
[minetest.git] / src / client / 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 #pragma once
21
22 #include "clientenvironment.h"
23 #include "irrlichttypes_extrabloated.h"
24 #include <ostream>
25 #include <map>
26 #include <set>
27 #include <vector>
28 #include <unordered_set>
29 #include "clientobject.h"
30 #include "gamedef.h"
31 #include "inventorymanager.h"
32 #include "localplayer.h"
33 #include "client/hud.h"
34 #include "particles.h"
35 #include "mapnode.h"
36 #include "tileanimation.h"
37 #include "mesh_generator_thread.h"
38 #include "network/address.h"
39 #include "network/peerhandler.h"
40 #include "gameparams.h"
41 #include "clientdynamicinfo.h"
42 #include <fstream>
43 #include "util/numeric.h"
44
45 #define CLIENT_CHAT_MESSAGE_LIMIT_PER_10S 10.0f
46
47 struct ClientEvent;
48 struct MeshMakeData;
49 struct ChatMessage;
50 class MapBlockMesh;
51 class RenderingEngine;
52 class IWritableTextureSource;
53 class IWritableShaderSource;
54 class IWritableItemDefManager;
55 class ISoundManager;
56 class NodeDefManager;
57 //class IWritableCraftDefManager;
58 class ClientMediaDownloader;
59 class SingleMediaDownloader;
60 struct MapDrawControl;
61 class ModChannelMgr;
62 class MtEventManager;
63 struct PointedThing;
64 class MapDatabase;
65 class Minimap;
66 struct MinimapMapblock;
67 class Camera;
68 class NetworkPacket;
69 namespace con {
70 class Connection;
71 }
72
73 enum LocalClientState {
74         LC_Created,
75         LC_Init,
76         LC_Ready
77 };
78
79 /*
80         Packet counter
81 */
82
83 class PacketCounter
84 {
85 public:
86         PacketCounter() = default;
87
88         void add(u16 command)
89         {
90                 auto n = m_packets.find(command);
91                 if (n == m_packets.end())
92                         m_packets[command] = 1;
93                 else
94                         n->second++;
95         }
96
97         void clear()
98         {
99                 m_packets.clear();
100         }
101
102         u32 sum() const;
103         void print(std::ostream &o) const;
104
105 private:
106         // command, count
107         std::map<u16, u32> m_packets;
108 };
109
110 class ClientScripting;
111 class GameUI;
112
113 class Client : public con::PeerHandler, public InventoryManager, public IGameDef
114 {
115 public:
116         /*
117                 NOTE: Nothing is thread-safe here.
118         */
119
120         Client(
121                         const char *playername,
122                         const std::string &password,
123                         const std::string &address_name,
124                         MapDrawControl &control,
125                         IWritableTextureSource *tsrc,
126                         IWritableShaderSource *shsrc,
127                         IWritableItemDefManager *itemdef,
128                         NodeDefManager *nodedef,
129                         ISoundManager *sound,
130                         MtEventManager *event,
131                         RenderingEngine *rendering_engine,
132                         bool ipv6,
133                         GameUI *game_ui,
134                         ELoginRegister allow_login_or_register
135         );
136
137         ~Client();
138         DISABLE_CLASS_COPY(Client);
139
140         // Load local mods into memory
141         void scanModSubfolder(const std::string &mod_name, const std::string &mod_path,
142                                 std::string mod_subpath);
143         inline void scanModIntoMemory(const std::string &mod_name, const std::string &mod_path)
144         {
145                 scanModSubfolder(mod_name, mod_path, "");
146         }
147
148         /*
149          request all threads managed by client to be stopped
150          */
151         void Stop();
152
153
154         bool isShutdown();
155
156         /*
157                 The name of the local player should already be set when
158                 calling this, as it is sent in the initialization.
159         */
160         void connect(Address address, bool is_local_server);
161
162         /*
163                 Stuff that references the environment is valid only as
164                 long as this is not called. (eg. Players)
165                 If this throws a PeerNotFoundException, the connection has
166                 timed out.
167         */
168         void step(float dtime);
169
170         /*
171          * Command Handlers
172          */
173
174         void handleCommand(NetworkPacket* pkt);
175
176         void handleCommand_Null(NetworkPacket* pkt) {};
177         void handleCommand_Deprecated(NetworkPacket* pkt);
178         void handleCommand_Hello(NetworkPacket* pkt);
179         void handleCommand_AuthAccept(NetworkPacket* pkt);
180         void handleCommand_AcceptSudoMode(NetworkPacket* pkt);
181         void handleCommand_DenySudoMode(NetworkPacket* pkt);
182         void handleCommand_AccessDenied(NetworkPacket* pkt);
183         void handleCommand_RemoveNode(NetworkPacket* pkt);
184         void handleCommand_AddNode(NetworkPacket* pkt);
185         void handleCommand_NodemetaChanged(NetworkPacket *pkt);
186         void handleCommand_BlockData(NetworkPacket* pkt);
187         void handleCommand_Inventory(NetworkPacket* pkt);
188         void handleCommand_TimeOfDay(NetworkPacket* pkt);
189         void handleCommand_ChatMessage(NetworkPacket *pkt);
190         void handleCommand_ActiveObjectRemoveAdd(NetworkPacket* pkt);
191         void handleCommand_ActiveObjectMessages(NetworkPacket* pkt);
192         void handleCommand_Movement(NetworkPacket* pkt);
193         void handleCommand_Fov(NetworkPacket *pkt);
194         void handleCommand_HP(NetworkPacket* pkt);
195         void handleCommand_Breath(NetworkPacket* pkt);
196         void handleCommand_MovePlayer(NetworkPacket* pkt);
197         void handleCommand_DeathScreen(NetworkPacket* pkt);
198         void handleCommand_AnnounceMedia(NetworkPacket* pkt);
199         void handleCommand_Media(NetworkPacket* pkt);
200         void handleCommand_NodeDef(NetworkPacket* pkt);
201         void handleCommand_ItemDef(NetworkPacket* pkt);
202         void handleCommand_PlaySound(NetworkPacket* pkt);
203         void handleCommand_StopSound(NetworkPacket* pkt);
204         void handleCommand_FadeSound(NetworkPacket *pkt);
205         void handleCommand_Privileges(NetworkPacket* pkt);
206         void handleCommand_InventoryFormSpec(NetworkPacket* pkt);
207         void handleCommand_DetachedInventory(NetworkPacket* pkt);
208         void handleCommand_ShowFormSpec(NetworkPacket* pkt);
209         void handleCommand_SpawnParticle(NetworkPacket* pkt);
210         void handleCommand_AddParticleSpawner(NetworkPacket* pkt);
211         void handleCommand_DeleteParticleSpawner(NetworkPacket* pkt);
212         void handleCommand_HudAdd(NetworkPacket* pkt);
213         void handleCommand_HudRemove(NetworkPacket* pkt);
214         void handleCommand_HudChange(NetworkPacket* pkt);
215         void handleCommand_HudSetFlags(NetworkPacket* pkt);
216         void handleCommand_HudSetParam(NetworkPacket* pkt);
217         void handleCommand_HudSetSky(NetworkPacket* pkt);
218         void handleCommand_HudSetSun(NetworkPacket* pkt);
219         void handleCommand_HudSetMoon(NetworkPacket* pkt);
220         void handleCommand_HudSetStars(NetworkPacket* pkt);
221         void handleCommand_CloudParams(NetworkPacket* pkt);
222         void handleCommand_OverrideDayNightRatio(NetworkPacket* pkt);
223         void handleCommand_LocalPlayerAnimations(NetworkPacket* pkt);
224         void handleCommand_EyeOffset(NetworkPacket* pkt);
225         void handleCommand_UpdatePlayerList(NetworkPacket* pkt);
226         void handleCommand_ModChannelMsg(NetworkPacket *pkt);
227         void handleCommand_ModChannelSignal(NetworkPacket *pkt);
228         void handleCommand_SrpBytesSandB(NetworkPacket *pkt);
229         void handleCommand_FormspecPrepend(NetworkPacket *pkt);
230         void handleCommand_CSMRestrictionFlags(NetworkPacket *pkt);
231         void handleCommand_PlayerSpeed(NetworkPacket *pkt);
232         void handleCommand_MediaPush(NetworkPacket *pkt);
233         void handleCommand_MinimapModes(NetworkPacket *pkt);
234         void handleCommand_SetLighting(NetworkPacket *pkt);
235
236         void ProcessData(NetworkPacket *pkt);
237
238         void Send(NetworkPacket* pkt);
239
240         void interact(InteractAction action, const PointedThing &pointed);
241
242         void sendNodemetaFields(v3s16 p, const std::string &formname,
243                 const StringMap &fields);
244         void sendInventoryFields(const std::string &formname,
245                 const StringMap &fields);
246         void sendInventoryAction(InventoryAction *a);
247         void sendChatMessage(const std::wstring &message);
248         void clearOutChatQueue();
249         void sendChangePassword(const std::string &oldpassword,
250                 const std::string &newpassword);
251         void sendDamage(u16 damage);
252         void sendRespawn();
253         void sendReady();
254         void sendHaveMedia(const std::vector<u32> &tokens);
255         void sendUpdateClientInfo(const ClientDynamicInfo &info);
256
257         ClientEnvironment& getEnv() { return m_env; }
258         ITextureSource *tsrc() { return getTextureSource(); }
259         ISoundManager *sound() { return getSoundManager(); }
260         static const std::string &getBuiltinLuaPath();
261         static const std::string &getClientModsLuaPath();
262
263         const std::vector<ModSpec> &getMods() const override;
264         const ModSpec* getModSpec(const std::string &modname) const override;
265
266         // Causes urgent mesh updates (unlike Map::add/removeNodeWithEvent)
267         void removeNode(v3s16 p);
268
269         // helpers to enforce CSM restrictions
270         MapNode CSMGetNode(v3s16 p, bool *is_valid_position);
271         int CSMClampRadius(v3s16 pos, int radius);
272         v3s16 CSMClampPos(v3s16 pos);
273
274         void addNode(v3s16 p, MapNode n, bool remove_metadata = true);
275
276         void setPlayerControl(PlayerControl &control);
277
278         // Returns true if the inventory of the local player has been
279         // updated from the server. If it is true, it is set to false.
280         bool updateWieldedItem();
281
282         /* InventoryManager interface */
283         Inventory* getInventory(const InventoryLocation &loc) override;
284         void inventoryAction(InventoryAction *a) override;
285
286         // Send the item number 'item' as player item to the server
287         void setPlayerItem(u16 item);
288
289         const std::list<std::string> &getConnectedPlayerNames()
290         {
291                 return m_env.getPlayerNames();
292         }
293
294         float getAnimationTime();
295
296         int getCrackLevel();
297         v3s16 getCrackPos();
298         void setCrack(int level, v3s16 pos);
299
300         u16 getHP();
301
302         bool checkPrivilege(const std::string &priv) const
303         { return (m_privileges.count(priv) != 0); }
304
305         const std::unordered_set<std::string> &getPrivilegeList() const
306         { return m_privileges; }
307
308         bool getChatMessage(std::wstring &message);
309         void typeChatMessage(const std::wstring& message);
310
311         u64 getMapSeed(){ return m_map_seed; }
312
313         void addUpdateMeshTask(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
314         // Including blocks at appropriate edges
315         void addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
316         void addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server=false, bool urgent=false);
317
318         void updateCameraOffset(v3s16 camera_offset)
319         { m_mesh_update_manager.m_camera_offset = camera_offset; }
320
321         bool hasClientEvents() const { return !m_client_event_queue.empty(); }
322         // Get event from queue. If queue is empty, it triggers an assertion failure.
323         ClientEvent * getClientEvent();
324
325         bool accessDenied() const { return m_access_denied; }
326
327         bool reconnectRequested() const { return m_access_denied_reconnect; }
328
329         void setFatalError(const std::string &reason)
330         {
331                 m_access_denied = true;
332                 m_access_denied_reason = reason;
333         }
334         inline void setFatalError(const LuaError &e)
335         {
336                 setFatalError(std::string("Lua: ") + e.what());
337         }
338
339         // Renaming accessDeniedReason to better name could be good as it's used to
340         // disconnect client when CSM failed.
341         const std::string &accessDeniedReason() const { return m_access_denied_reason; }
342
343         bool itemdefReceived() const
344         { return m_itemdef_received; }
345         bool nodedefReceived() const
346         { return m_nodedef_received; }
347         bool mediaReceived() const
348         { return !m_media_downloader; }
349         bool activeObjectsReceived() const
350         { return m_activeobjects_received; }
351
352         u16 getProtoVersion()
353         { return m_proto_ver; }
354
355         bool m_simple_singleplayer_mode;
356
357         float mediaReceiveProgress();
358
359         void afterContentReceived();
360         void showUpdateProgressTexture(void *args, u32 progress, u32 max_progress);
361
362         float getRTT();
363         float getCurRate();
364
365         Minimap* getMinimap() { return m_minimap; }
366         void setCamera(Camera* camera) { m_camera = camera; }
367
368         Camera* getCamera () { return m_camera; }
369         scene::ISceneManager *getSceneManager();
370
371         bool shouldShowMinimap() const;
372
373         // IGameDef interface
374         IItemDefManager* getItemDefManager() override;
375         const NodeDefManager* getNodeDefManager() override;
376         ICraftDefManager* getCraftDefManager() override;
377         ITextureSource* getTextureSource();
378         virtual IWritableShaderSource* getShaderSource();
379         u16 allocateUnknownNodeId(const std::string &name) override;
380         virtual ISoundManager* getSoundManager();
381         MtEventManager* getEventManager();
382         virtual ParticleManager* getParticleManager();
383         bool checkLocalPrivilege(const std::string &priv)
384         { return checkPrivilege(priv); }
385         virtual scene::IAnimatedMesh* getMesh(const std::string &filename, bool cache = false);
386         const std::string* getModFile(std::string filename);
387         ModStorageDatabase *getModStorageDatabase() override { return m_mod_storage_database; }
388
389         // Migrates away old files-based mod storage if necessary
390         void migrateModStorage();
391
392         // The following set of functions is used by ClientMediaDownloader
393         // Insert a media file appropriately into the appropriate manager
394         bool loadMedia(const std::string &data, const std::string &filename,
395                 bool from_media_push = false);
396
397         // Send a request for conventional media transfer
398         void request_media(const std::vector<std::string> &file_requests);
399
400         LocalClientState getState() { return m_state; }
401
402         void makeScreenshot();
403
404         inline void pushToChatQueue(ChatMessage *cec)
405         {
406                 m_chat_queue.push(cec);
407         }
408
409         ClientScripting *getScript() { return m_script; }
410         bool modsLoaded() const { return m_mods_loaded; }
411
412         void pushToEventQueue(ClientEvent *event);
413
414         void showMinimap(bool show = true);
415
416         const Address getServerAddress();
417
418         const std::string &getAddressName() const
419         {
420                 return m_address_name;
421         }
422
423         inline u64 getCSMRestrictionFlags() const
424         {
425                 return m_csm_restriction_flags;
426         }
427
428         inline bool checkCSMRestrictionFlag(CSMRestrictionFlags flag) const
429         {
430                 return m_csm_restriction_flags & flag;
431         }
432
433         bool joinModChannel(const std::string &channel) override;
434         bool leaveModChannel(const std::string &channel) override;
435         bool sendModChannelMessage(const std::string &channel,
436                         const std::string &message) override;
437         ModChannel *getModChannel(const std::string &channel) override;
438
439         const std::string &getFormspecPrepend() const
440         {
441                 return m_env.getLocalPlayer()->formspec_prepend;
442         }
443         inline MeshGrid getMeshGrid()
444         {
445                 return m_mesh_grid;
446         }
447
448 private:
449         void loadMods();
450
451         // Virtual methods from con::PeerHandler
452         void peerAdded(con::Peer *peer) override;
453         void deletingPeer(con::Peer *peer, bool timeout) override;
454
455         void initLocalMapSaving(const Address &address,
456                         const std::string &hostname,
457                         bool is_local_server);
458
459         void ReceiveAll();
460
461         void sendPlayerPos();
462
463         void deleteAuthData();
464         // helper method shared with clientpackethandler
465         static AuthMechanism choseAuthMech(const u32 mechs);
466
467         void sendInit(const std::string &playerName);
468         void startAuth(AuthMechanism chosen_auth_mechanism);
469         void sendDeletedBlocks(std::vector<v3s16> &blocks);
470         void sendGotBlocks(const std::vector<v3s16> &blocks);
471         void sendRemovedSounds(std::vector<s32> &soundList);
472
473         // Helper function
474         inline std::string getPlayerName()
475         { return m_env.getLocalPlayer()->getName(); }
476
477         bool canSendChatMessage() const;
478
479         float m_packetcounter_timer = 0.0f;
480         float m_connection_reinit_timer = 0.1f;
481         float m_avg_rtt_timer = 0.0f;
482         float m_playerpos_send_timer = 0.0f;
483         IntervalLimiter m_map_timer_and_unload_interval;
484
485         IWritableTextureSource *m_tsrc;
486         IWritableShaderSource *m_shsrc;
487         IWritableItemDefManager *m_itemdef;
488         NodeDefManager *m_nodedef;
489         ISoundManager *m_sound;
490         MtEventManager *m_event;
491         RenderingEngine *m_rendering_engine;
492
493
494         MeshUpdateManager m_mesh_update_manager;
495         ClientEnvironment m_env;
496         ParticleManager m_particle_manager;
497         std::unique_ptr<con::Connection> m_con;
498         std::string m_address_name;
499         ELoginRegister m_allow_login_or_register = ELoginRegister::Any;
500         Camera *m_camera = nullptr;
501         Minimap *m_minimap = nullptr;
502         bool m_minimap_disabled_by_server = false;
503
504         // Server serialization version
505         u8 m_server_ser_ver;
506
507         // Used version of the protocol with server
508         // Values smaller than 25 only mean they are smaller than 25,
509         // and aren't accurate. We simply just don't know, because
510         // the server didn't send the version back then.
511         // If 0, server init hasn't been received yet.
512         u16 m_proto_ver = 0;
513
514         bool m_update_wielded_item = false;
515         Inventory *m_inventory_from_server = nullptr;
516         float m_inventory_from_server_age = 0.0f;
517         PacketCounter m_packetcounter;
518         // Block mesh animation parameters
519         float m_animation_time = 0.0f;
520         int m_crack_level = -1;
521         v3s16 m_crack_pos;
522         // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT
523         //s32 m_daynight_i;
524         //u32 m_daynight_ratio;
525         std::queue<std::wstring> m_out_chat_queue;
526         u32 m_last_chat_message_sent;
527         float m_chat_message_allowance = 5.0f;
528         std::queue<ChatMessage *> m_chat_queue;
529
530         // The authentication methods we can use to enter sudo mode (=change password)
531         u32 m_sudo_auth_methods;
532
533         // The seed returned by the server in TOCLIENT_INIT is stored here
534         u64 m_map_seed = 0;
535
536         // Auth data
537         std::string m_playername;
538         std::string m_password;
539         // If set, this will be sent (and cleared) upon a TOCLIENT_ACCEPT_SUDO_MODE
540         std::string m_new_password;
541         // Usable by auth mechanisms.
542         AuthMechanism m_chosen_auth_mech;
543         void *m_auth_data = nullptr;
544
545         bool m_access_denied = false;
546         bool m_access_denied_reconnect = false;
547         std::string m_access_denied_reason = "";
548         std::queue<ClientEvent *> m_client_event_queue;
549         bool m_itemdef_received = false;
550         bool m_nodedef_received = false;
551         bool m_activeobjects_received = false;
552         bool m_mods_loaded = false;
553
554         std::vector<std::string> m_remote_media_servers;
555         // Media downloader, only exists during init
556         ClientMediaDownloader *m_media_downloader;
557         // Pending downloads of dynamic media (key: token)
558         std::vector<std::pair<u32, std::shared_ptr<SingleMediaDownloader>>> m_pending_media_downloads;
559
560         // time_of_day speed approximation for old protocol
561         bool m_time_of_day_set = false;
562         float m_last_time_of_day_f = -1.0f;
563         float m_time_of_day_update_timer = 0.0f;
564
565         // An interval for generally sending object positions and stuff
566         float m_recommended_send_interval = 0.1f;
567
568         // Sounds
569         float m_removed_sounds_check_timer = 0.0f;
570         // Mapping from server sound ids to our sound ids
571         std::unordered_map<s32, int> m_sounds_server_to_client;
572         // And the other way!
573         std::unordered_map<int, s32> m_sounds_client_to_server;
574         // Relation of client id to object id
575         std::unordered_map<int, u16> m_sounds_to_objects;
576
577         // Privileges
578         std::unordered_set<std::string> m_privileges;
579
580         // Detached inventories
581         // key = name
582         std::unordered_map<std::string, Inventory*> m_detached_inventories;
583
584         // Storage for mesh data for creating multiple instances of the same mesh
585         StringMap m_mesh_data;
586
587         // own state
588         LocalClientState m_state;
589
590         GameUI *m_game_ui;
591
592         // Used for saving server map to disk client-side
593         MapDatabase *m_localdb = nullptr;
594         IntervalLimiter m_localdb_save_interval;
595         u16 m_cache_save_interval;
596
597         // Client modding
598         ClientScripting *m_script = nullptr;
599         ModStorageDatabase *m_mod_storage_database = nullptr;
600         float m_mod_storage_save_timer = 10.0f;
601         std::vector<ModSpec> m_mods;
602         StringMap m_mod_vfs;
603
604         bool m_shutdown = false;
605
606         // CSM restrictions byteflag
607         u64 m_csm_restriction_flags = CSMRestrictionFlags::CSM_RF_NONE;
608         u32 m_csm_restriction_noderange = 8;
609
610         std::unique_ptr<ModChannelMgr> m_modchannel_mgr;
611
612         // The number of blocks the client will combine for mesh generation.
613         MeshGrid m_mesh_grid;
614 };