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