achievements and stuff
[carveJwlIkooP6JGAAIwe30JlM.git] / network.h
1 /*
2 * Copyright (C) 2021-2022 Mt.ZERO Software, Harry Godden - All Rights Reserved
3 * All trademarks are property of their respective owners
4 */
5
6 #ifndef NETWORK_H
7 #define NETWORK_H
8
9 #include "vg/vg_stdint.h"
10 #include "steam.h"
11 #include "network_msg.h"
12 #include "highscores.h"
13
14 /*
15 * Interface
16 */
17 //#define SR_USE_LOCALHOST
18
19 /* Call it at start; Connects us to the gameserver */
20 static void network_init(void);
21
22 /* Run this from main loop */
23 static void network_update(void);
24
25 /* Call it at shutdown */
26 static void network_end(void*_);
27
28 /*
29 * Can buffer up a bunch of these by calling many times, they will be
30 * sent at the next connection
31 */
32 static void network_submit_highscore( u32 trackid, u16 points, u16 time );
33
34 /*
35 * Game endpoints are provided with the same names to allow running without a
36 * network connection.
37 */
38 #ifdef SR_NETWORKED
39
40 /*
41 * Runtime connection stuff
42 */
43 static u8 steam_app_ticket[ 1024 ];
44 static u32 steam_app_ticket_length;
45 static int network_name_update = 1;
46
47 static HSteamNetConnection cremote;
48 static ESteamNetworkingConnectionState cremote_state =
49 k_ESteamNetworkingConnectionState_None;
50
51 /*
52 * Implementation
53 */
54
55 static void scores_update(void);
56
57 static void on_auth_ticket_recieved( void *result, void *context )
58 {
59 EncryptedAppTicketResponse_t *response = result;
60
61 if( response->m_eResult == k_EResultOK )
62 {
63 vg_info( " New app ticket ready\n" );
64 }
65 else
66 {
67 vg_warn( " Could not request new encrypted app ticket (%u)\n",
68 response->m_eResult );
69 }
70
71 if( SteamAPI_ISteamUser_GetEncryptedAppTicket( hSteamUser,
72 steam_app_ticket,
73 vg_list_size(steam_app_ticket),
74 &steam_app_ticket_length ))
75 {
76 vg_success( " Loaded app ticket (%u bytes)\n", steam_app_ticket_length );
77 }
78 else
79 {
80 vg_error( " No ticket availible\n" );
81 steam_app_ticket_length = 0;
82 }
83 }
84
85 static void request_auth_ticket(void)
86 {
87 /*
88 * TODO Check for one thats cached on the disk and load it.
89 * This might be OK though because steam seems to cache the result
90 */
91
92 vg_info( "Requesting new authorization ticket\n" );
93 steam_async *call = steam_new_async();
94 call->data = NULL;
95 call->p_handler = on_auth_ticket_recieved;
96 call->id = SteamAPI_ISteamUser_RequestEncryptedAppTicket( hSteamUser,
97 NULL, 0 );
98 }
99
100 static void send_auth_ticket(void)
101 {
102 u32 size = sizeof(netmsg_auth) + steam_app_ticket_length;
103 netmsg_auth *auth = alloca(size);
104
105 auth->inetmsg_id = k_inetmsg_auth;
106 auth->ticket_length = steam_app_ticket_length;
107 for( int i=0; i<steam_app_ticket_length; i++ )
108 auth->ticket[i] = steam_app_ticket[i];
109
110 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
111 hSteamNetworkingSockets, cremote, auth, size,
112 k_nSteamNetworkingSend_Reliable, NULL );
113 }
114
115 static void send_score_request(void)
116 {
117 vg_info( "Requesting scores\n" );
118 netmsg_scores_request req;
119 req.inetmsg_id = k_inetmsg_scores_request;
120
121 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
122 hSteamNetworkingSockets, cremote, &req, sizeof(netmsg_scores_request),
123 k_nSteamNetworkingSend_Reliable, NULL );
124 }
125
126 static void send_score_update(void)
127 {
128 vg_info( "Sending scores\n" );
129 u32 size = sizeof(netmsg_set_score) +
130 vg_list_size(track_infos)*sizeof(struct netmsg_score_record);
131 netmsg_set_score *setscore = alloca( size );
132 setscore->inetmsg_id = k_inetmsg_set_score;
133
134 int count = 0;
135 for( u32 i=0; i<vg_list_size(track_infos); i++ )
136 {
137 if( track_infos[i].push )
138 {
139 track_infos[i].push = 0;
140 highscore_record *user_record = highscore_find_user_record( 0, i );
141
142 if( !user_record )
143 {
144 vg_error( "No score set but tried to upload for track %u\n", i );
145 continue;
146 }
147
148 setscore->records[count].trackid = i;
149 setscore->records[count].playerid = 0;
150 setscore->records[count].points = user_record->points;
151 setscore->records[count].time = user_record->time;
152
153 count ++;
154 }
155 }
156
157 if( count == 0 )
158 return;
159
160 u32 send_size = sizeof(netmsg_set_score) +
161 count*sizeof(struct netmsg_score_record);
162 setscore->record_count = count;
163
164 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
165 hSteamNetworkingSockets, cremote, setscore, send_size,
166 k_nSteamNetworkingSend_Reliable, NULL );
167 }
168
169 static void send_nickname(void)
170 {
171 netmsg_set_nickname nick;
172 nick.inetmsg_id = k_inetmsg_set_nickname;
173
174 memset( nick.nickname, 0, 16 );
175 vg_strncpy( steam_username_at_startup, nick.nickname, 16 );
176
177 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
178 hSteamNetworkingSockets, cremote, &nick, sizeof(netmsg_set_nickname),
179 k_nSteamNetworkingSend_Reliable, NULL );
180
181 network_name_update = 0;
182 }
183
184 static void server_routine_update(void)
185 {
186 send_auth_ticket();
187
188 if( network_name_update )
189 send_nickname();
190
191 send_score_update();
192 send_score_request();
193 }
194
195 static void on_server_connect_status( CallbackMsg_t *msg )
196 {
197 SteamNetConnectionStatusChangedCallback_t *info = (void *)msg->m_pubParam;
198 vg_info( " Connection status changed for %lu\n", info->m_hConn );
199 vg_info( " %s -> %s\n",
200 string_ESteamNetworkingConnectionState(info->m_eOldState),
201 string_ESteamNetworkingConnectionState(info->m_info.m_eState) );
202
203 if( info->m_hConn == cremote )
204 {
205 cremote_state = info->m_info.m_eState;
206 if( info->m_info.m_eState ==
207 k_ESteamNetworkingConnectionState_Connected )
208 {
209 vg_success(" Connected to remote server.. running updates\n");
210 server_routine_update();
211 }
212 }
213 else
214 {
215 vg_warn( " Recieved signal from unknown connection\n" );
216 }
217 }
218
219 static void network_connect_gc(void)
220 {
221 /* Connect to server if not connected */
222 SteamNetworkingIPAddr remoteAddr;
223
224 #ifdef SR_USE_LOCALHOST
225 SteamAPI_SteamNetworkingIPAddr_SetIPv6LocalHost( &remoteAddr, 27402 );
226 #else
227 const char *server_lon1 = "46.101.34.155:27402";
228 SteamAPI_SteamNetworkingIPAddr_ParseString( &remoteAddr, server_lon1 );
229 #endif
230
231 char buf[256];
232 SteamAPI_SteamNetworkingIPAddr_ToString( &remoteAddr, buf, 256, 1 );
233 vg_info( "connect to: %s\n", buf );
234
235 cremote = SteamAPI_ISteamNetworkingSockets_ConnectByIPAddress(
236 hSteamNetworkingSockets, &remoteAddr, 0, NULL );
237 }
238
239 static void on_inet_scoreboard( SteamNetworkingMessage_t *msg )
240 {
241 netmsg_scoreboard *sb = msg->m_pData;
242
243 u32 base_size = sizeof(netmsg_scoreboard)-
244 sizeof(struct netmsg_board)*vg_list_size(track_infos),
245 expected = base_size+sizeof(struct netmsg_board)*sb->board_count;
246
247 if( msg->m_cbSize != expected )
248 {
249 vg_error( "Server scoreboard was corrupted. Size: %u != %u\n",
250 msg->m_cbSize, expected );
251 }
252 else
253 {
254 if( vg_list_size(track_infos) > sb->board_count )
255 vg_warn( "Server is out of date, not enough boards recieved\n");
256 else if( vg_list_size(track_infos) < sb->board_count )
257 vg_warn( "Client out of date, server sent more boards than we have\n");
258 else
259 vg_success( "Recieved new scoreboards from server\n" );
260
261 for( int i=0; i < vg_min(sb->board_count,vg_list_size(track_infos)); i++)
262 {
263 scoreboard_client_data.boards[i] = sb->boards[i];
264 highscores_board_printf( stdout, sb->boards[i].data, 10 );
265 }
266 }
267
268 /* We dont need to stay on the server currently */
269 SteamAPI_ISteamNetworkingSockets_CloseConnection(
270 hSteamNetworkingSockets, cremote, 0, NULL, 1 );
271
272 network_scores_updated = 1;
273 }
274
275 static void poll_connection(void)
276 {
277 SteamNetworkingMessage_t *messages[32];
278 int len;
279
280 while(1)
281 {
282 len = SteamAPI_ISteamNetworkingSockets_ReceiveMessagesOnConnection(
283 hSteamNetworkingSockets, cremote, messages, vg_list_size(messages));
284
285 if( len <= 0 )
286 return;
287
288 for( int i=0; i<len; i++ )
289 {
290 SteamNetworkingMessage_t *msg = messages[i];
291
292 if( msg->m_cbSize < sizeof(netmsg_blank) )
293 {
294 vg_warn( "Discarding message (too small: %d)\n", msg->m_cbSize );
295 continue;
296 }
297
298 netmsg_blank *tmp = msg->m_pData;
299
300 if( tmp->inetmsg_id == k_inetmsg_scoreboard )
301 on_inet_scoreboard( msg );
302
303 SteamAPI_SteamNetworkingMessage_t_Release( msg );
304 }
305 }
306 }
307
308 /*
309 * Subroutine to be connected to main game loop, runs all routines on timers
310 */
311 static void network_update(void)
312 {
313 if( steam_ready )
314 {
315 static double last_update = 0.0;
316 poll_connection();
317
318 if( vg.time > (last_update + 60.0) )
319 {
320 last_update = vg.time;
321
322 if( steam_app_ticket_length )
323 {
324 network_connect_gc();
325 }
326 else
327 {
328 vg_low( "Not making remote connection; app ticket not gotten\n" );
329 }
330 }
331
332 if( vg.time > (last_update + 10.0) &&
333 (cremote_state == k_ESteamNetworkingConnectionState_Connected ))
334 {
335 vg_warn( "Connected to server but no return... disconnecting\n" );
336 SteamAPI_ISteamNetworkingSockets_CloseConnection(
337 hSteamNetworkingSockets, cremote, 0, NULL, 1 );
338 }
339 }
340 }
341
342 static void network_init(void)
343 {
344 if( steam_ready )
345 {
346 steam_register_callback( k_iSteamNetConnectionStatusChangedCallBack,
347 on_server_connect_status );
348 request_auth_ticket();
349 }
350 }
351
352 static void network_end(void*_)
353 {
354 /* TODO: Fire off any buffered highscores that need to be setn */
355 if( cremote_state == k_ESteamNetworkingConnectionState_Connected ||
356 cremote_state == k_ESteamNetworkingConnectionState_Connecting )
357 {
358 SteamAPI_ISteamNetworkingSockets_CloseConnection(
359 hSteamNetworkingSockets, cremote, 0, NULL, 1 );
360 }
361 }
362
363 #else /* SR_NETWORKED */
364
365 static void network_init(void){}
366 static void network_update(void){}
367 static void network_end(void*_){}
368
369 #endif /* SR_NETWORKED */
370 #endif /* NETWORK_H */