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