DEADSOFTWARE

Добавлена стрельба
[netwar.git] / client.c
1 #include <assert.h>
2 #include <SDL2/SDL_net.h>
4 #include "game.h"
5 #include "client.h"
6 #include "network.h"
7 #include "protocol.h"
9 int cl_playerid;
11 static bool run;
12 static IPaddress addr;
13 static UDPsocket sock;
14 static char nickname[32] = "Anonymous";
16 static void cl_kill_client(ProtocolMessage m) {
17 SDL_Log("Connection refused by server: %.*s\n", (int) sizeof(m.sv.kill.message), m.sv.kill.message);
18 cl_disconnect(true);
19 }
21 static void cl_update_svinfo(ProtocolMessage m) {
22 SDL_Log("Connected to server %.*s\n", (int) sizeof(m.sv.info.name), m.sv.info.name);
23 cl_playerid = m.sv.info.clientid;
24 assert(cl_playerid < MAX_PLAYERS);
25 SDL_Log("Player id%i\n", cl_playerid);
26 }
28 static void cl_update_svplayer(ProtocolMessage m) {
29 g_player_set(
30 m.sv.splr.clid,
31 m.sv.splr.live,
32 b2f(m.sv.splr.x),
33 b2f(m.sv.splr.y),
34 b2f(m.sv.splr.r),
35 b2f(m.sv.splr.vx),
36 b2f(m.sv.splr.vy),
37 b2f(m.sv.splr.vr)
38 );
39 }
41 static void cl_update_svbullet(ProtocolMessage m) {
42 g_bullet_set(
43 m.sv.sbul.id,
44 m.sv.sbul.owner,
45 m.sv.sbul.live,
46 b2f(m.sv.sbul.x),
47 b2f(m.sv.sbul.y),
48 b2f(m.sv.sbul.vx),
49 b2f(m.sv.sbul.vy),
50 m.sv.sbul.tick
51 );
52 }
54 void cl_connect(const char * host, uint16_t port) {
55 if(SDLNet_ResolveHost(&addr, host, (port) ? (port) : (DEFAULT_PORT)) != 0) {
56 SDL_Log("Unable to resolve host: %s\n", SDLNet_GetError());
57 exit(1);
58 }
60 sock = OpenPort(0);
61 SendMessage(sock, addr, cl_info(nickname));
63 ProtocolMessage m;
64 bool received = WaitMessage(sock, NULL, &m, 10000);
65 if(!received) {
66 SDL_Log("Connection timeout");
67 exit(1);
68 }
70 run = true;
71 if(m.type == SV_KILL) {
72 cl_kill_client(m);
73 } else if(m.type == SV_INFO) {
74 cl_update_svinfo(m);
75 } else {
76 SDL_Log("Invalid first message %i\n", m.type);
77 run = false;
78 }
79 }
81 void cl_move(DoesCode code) {
82 g_player_does(cl_playerid, code);
83 SendMessage(sock, addr, cl_does(code));
84 }
86 void cl_recv() {
87 IPaddress address;
88 ProtocolMessage m;
89 if(!RecvMessage(sock, &address, &m))
90 return;
92 switch(m.type) {
93 case SV_INFO: cl_update_svinfo(m); break;
94 case SV_KILL: cl_kill_client(m); break;
95 case SV_SPLR: cl_update_svplayer(m); break;
96 case SV_SBUL: cl_update_svbullet(m); break;
97 default: SDL_Log("invalid message %i", m.type);
98 }
99 }
101 void cl_disconnect(bool force) {
102 if(!run)
103 return;
105 if(!force)
106 SendMessage(sock, addr, cl_kill());
108 ClosePort(sock);
110 run = false;
113 bool cl_isrun() {
114 return run;