2 * Copyright (C) Volition, Inc. 1999. All rights reserved.
4 * All source code herein is the property of Volition, Inc. You may not sell
5 * or otherwise commercially exploit the source or things you created based on
10 * $Logfile: /Freespace2/code/Network/multilag.cpp $
16 * Revision 1.6 2004/07/04 11:39:06 taylor
17 * fix missing debrief text, crash on exit, path separator's, warning fixes, no GR_SOFT
19 * Revision 1.5 2002/06/09 04:41:24 relnev
20 * added copyright header
22 * Revision 1.4 2002/05/26 20:49:54 theoddone33
25 * Revision 1.3 2002/05/26 20:22:48 theoddone33
26 * Most of network/ works
28 * Revision 1.2 2002/05/07 03:16:47 theoddone33
29 * The Great Newline Fix
31 * Revision 1.1.1.1 2002/05/03 03:28:10 root
35 * 4 11/19/98 8:03a Dave
36 * Full support for D3-style reliable sockets. Revamped packet lag/loss
37 * system, made it receiver side and at the lowest possible level.
39 * 3 11/17/98 11:12a Dave
40 * Removed player identification by address. Now assign explicit id #'s.
42 * 2 10/07/98 10:53a Dave
45 * 1 10/07/98 10:50a Dave
47 * 15 6/05/98 9:54a Lawrance
50 * 14 4/27/98 6:02p Dave
51 * Modify how missile scoring works. Fixed a team select ui bug. Speed up
52 * multi_lag system. Put in new main hall.
54 * 13 4/18/98 5:00p Dave
55 * Put in observer zoom key. Made mission sync screen more informative.
57 * 12 4/06/98 12:37a Lawrance
58 * fix compile bug with demo
60 * 11 4/04/98 8:42p Dave
61 * Tested and debugged UDP reliable socket layer. Modified lag system to
62 * take this into account.
64 * 10 4/02/98 6:29p Lawrance
65 * compile out multilag code for demo
67 * 9 3/14/98 2:48p Dave
68 * Cleaned up observer joining code. Put in support for file xfers to
69 * ingame joiners (observers or not). Revamped and reinstalled pseudo
72 * 8 1/11/98 10:03p Allender
73 * removed <winsock.h> from headers which included it. Made psnet_socket
74 * type which is defined just as SOCKET type is.
76 * 7 12/29/97 5:21p Dave
77 * Put in object update sequencing for multiplayer.
79 * 6 12/16/97 6:17p Dave
80 * Put in primary weapon support for multiplayer weapon select screen.
82 * 5 12/10/97 4:45p Dave
83 * Added in more detailed support for multiplayer packet lag/loss. Fixed
84 * some multiplayer stuff. Added some controls to the standalone.
86 * 4 12/01/97 4:59p Dave
87 * Synchronized multiplayer debris objects. Put in pilot popup in main
88 * hall. Optimized simulated multiplayer lag module. Fixed a potential
91 * 3 11/28/97 7:04p Dave
92 * Emergency checkin due to big system crash.
94 * 2 11/28/97 5:06p Dave
95 * Put in facilities for simulating multiplayer lag.
97 * 1 11/28/97 4:38p Dave
107 #include <sys/time.h>
108 #include <sys/types.h>
109 #include <sys/socket.h>
110 #include <netinet/in.h>
111 #include <arpa/inet.h>
117 #include "multilag.h"
120 #include "linklist.h"
122 // ----------------------------------------------------------------------------------------------------
123 // LAGLOSS DEFINES/VARS
126 // default LAGLOSS values
127 #define MULTI_LAGLOSS_DEF_LAG (-1)
128 #define MULTI_LAGLOSS_DEF_LAGMIN (-1)
129 #define MULTI_LAGLOSS_DEF_LAGMAX (-1)
130 #define MULTI_LAGLOSS_DEF_LOSS (-1.0f)
131 #define MULTI_LAGLOSS_DEF_LOSSMIN (-1.0f)
132 #define MULTI_LAGLOSS_DEF_LOSSMAX (-1.0f)
133 #define MULTI_LAGLOSS_DEF_STREAK (2500)
136 int Multi_lag_inited = 0;
138 // lag values (base - max and min)
139 int Multi_lag_base = -1;
140 int Multi_lag_min = -1;
141 int Multi_lag_max = -1;
143 // packet loss values (base - max and min)
144 float Multi_loss_base = -1.0f;
145 float Multi_loss_min = -1.0f;
146 float Multi_loss_max = -1.0f;
148 // streaks for lagging
149 int Multi_streak_stamp = -1; // timestamp telling when the streak of a certain lag is done
150 int Multi_streak_time = 0; // how long each streak will last
151 int Multi_current_streak = -1; // what lag the current streak has
153 // struct for buffering stuff on receives
154 typedef struct lag_buf {
155 ubyte data[700]; // the data from the packet
156 int data_len; // length of the data
157 uint socket; // this can be either a PSNET_SOCKET or a PSNET_SOCKET_RELIABLE
158 int stamp; // when this expires, make this packet available
159 SOCKADDR_IN ip_addr; // ip address when in TCP
161 SOCKADDR_IPX ipx_addr; // ipx address when in IPX mode
164 struct lag_buf * prev; // prev in the list
165 struct lag_buf * next; // next in the list
168 // lag buffers - malloced
170 #define MAX_LAG_BUFFERS 1 // only 1 buffer in non-debug builds
172 #define MAX_LAG_BUFFERS 1000
174 lag_buf *Lag_buffers[MAX_LAG_BUFFERS];
175 int Lag_buf_count = 0; // how many lag_buf's are currently in use
177 lag_buf Lag_free_list;
178 lag_buf Lag_used_list;
181 // ----------------------------------------------------------------------------------------------------
182 // LAGLOSS FORWARD DECLARATIONS
185 // get a value to lag a packet with (in ms)
186 int multi_lag_get_random_lag();
188 // boolean yes or no - should this packet be lost?
189 int multi_lag_should_be_lost();
191 // get a free packet buffer, return NULL on fail
192 lag_buf *multi_lag_get_free();
194 // put a lag buffer back
195 void multi_lag_put_free(lag_buf *buf);
197 // ----------------------------------------------------------------------------------------------------
201 void multi_lag_init()
203 // never do lag in a non-debug build
204 #if defined(NDEBUG) || !defined(MULTI_USE_LAG)
205 Multi_lag_inited = 0;
209 // if we're already inited, don't do anything
210 if(Multi_lag_inited){
214 // try and allocate lag bufs
215 for(idx=0; idx<MAX_LAG_BUFFERS; idx++){
216 Lag_buffers[idx] = (lag_buf*)malloc(sizeof(lag_buf));
217 if(Lag_buffers[idx] == NULL){
222 // initialize lag buffer lists
223 list_init( &Lag_free_list );
224 list_init( &Lag_used_list );
226 // Link all object slots into the free list
227 for (idx=0; idx<MAX_LAG_BUFFERS; idx++) {
228 list_append(&Lag_free_list, Lag_buffers[idx]);
231 // set the default lag values
232 Multi_lag_base = MULTI_LAGLOSS_DEF_LAG;
233 Multi_lag_min = MULTI_LAGLOSS_DEF_LAGMIN;
234 Multi_lag_max = MULTI_LAGLOSS_DEF_LAGMAX;
236 // set the default loss values
237 Multi_loss_base = MULTI_LAGLOSS_DEF_LOSS;
238 Multi_loss_min = MULTI_LAGLOSS_DEF_LOSSMIN;
239 Multi_loss_max = MULTI_LAGLOSS_DEF_LOSSMAX;
241 // set the default lag streak time
242 Multi_streak_time = MULTI_LAGLOSS_DEF_STREAK;
244 Multi_lag_inited = 1;
248 void multi_lag_close()
252 // if we're not inited already, don't do anything
253 if(!Multi_lag_inited){
257 // free up lag buffers
258 for(idx=0; idx<MAX_LAG_BUFFERS; idx++){
259 if(Lag_buffers[idx] != NULL){
260 free(Lag_buffers[idx]);
261 Lag_buffers[idx] = NULL;
265 Multi_lag_inited = 0;
268 // select for multi_lag
269 int multi_lag_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *except_fds, timeval *timeout)
278 SOCKADDR_IPX ipx_addr;
281 lag_buf *moveup, *item;
283 SDL_assert(readfds != NULL);
284 SDL_assert(writefds == NULL);
285 SDL_assert(except_fds == NULL);
287 // clear out addresses
288 memset(&ip_addr, 0, sizeof(SOCKADDR_IN));
290 memset(&ipx_addr, 0, sizeof(SOCKADDR_IPX));
293 // if there's data on the socket, read it
294 if(select(nfds, readfds, writefds, except_fds, timeout)){
295 // read the data and stuff it
297 t_from_len = sizeof(SOCKADDR_IN);
298 ret_val = recvfrom(readfds->fd_array[0], t_buf, 1024, 0, (SOCKADDR*)&ip_addr, &t_from_len);
301 t_from_len = sizeof(SOCKADDR_IPX);
302 ret_val = recvfrom(readfds->fd_array[0], t_buf, 1024, 0, (SOCKADDR*)&ipx_addr, &t_from_len);
306 // wacky socket error
307 if(ret_val == SOCKET_ERROR){
311 // if we should be dropping this packet
312 if(!multi_lag_should_be_lost()){
313 // get a free packet buf and stuff the data
314 item = multi_lag_get_free();
316 SDL_assert(ret_val < 700);
317 memcpy(item->data, t_buf, ret_val);
318 item->data_len = ret_val;
319 item->ip_addr = ip_addr;
321 item->ipx_addr = ipx_addr;
323 item->socket = readfds->fd_array[0];
324 item->stamp = timestamp(multi_lag_get_random_lag());
329 // always unset the readfds
330 readfds->fd_count = 0;
332 // now determine if we have any pending packets - find the first one
333 // NOTE : this _could_ be the packet we just read. In fact, with a 0 lag, this will always be the case
334 moveup=GET_FIRST(&Lag_used_list);
335 while ( moveup!=END_OF_LIST(&Lag_used_list) ) {
336 // if the timestamp has elapsed and we have a matching socket
337 if((readfds->fd_array[0] == (SOCKET)moveup->socket) && ((moveup->stamp <= 0) || timestamp_elapsed(moveup->stamp))){
338 // set this so we think select returned yes
339 readfds->fd_count = 1;
343 moveup = GET_NEXT(moveup);
351 // recvfrom for multilag
352 int multi_lag_recvfrom(uint s, char *buf, int len, int flags, struct sockaddr *from, int *fromlen)
354 lag_buf *moveup = NULL;
355 lag_buf *item = NULL;
357 // now determine if we have any pending packets - find the first one
358 moveup=GET_FIRST(&Lag_used_list);
359 while ( moveup!=END_OF_LIST(&Lag_used_list) ) {
360 // if the timestamp has elapsed
361 if(((int)s == (SOCKET)moveup->socket) && ((moveup->stamp <= 0) || timestamp_elapsed(moveup->stamp))){
366 moveup = GET_NEXT(moveup);
369 // if this happens, it means that the multi_lag_select() returned an improper value
372 SDL_assert(item->data_len <= len);
373 memcpy(buf, item->data, item->data_len);
375 memcpy(from, &item->ip_addr, sizeof(SOCKADDR_IN));
378 memcpy(from, &item->ipx_addr, sizeof(SOCKADDR_IPX));
382 // stick the item back on the free list
383 multi_lag_put_free(item);
385 // return the size in bytes
386 return item->data_len;
389 // ----------------------------------------------------------------------------------------------------
390 // LAGLOSS FORWARD DEFINITIONS
393 int multi_lag_get_random_lag()
395 // first determine the percentage we'll be checking against
399 // if the lag system isn't inited, don't do anything (no lag)
400 if(!Multi_lag_inited){
405 // see if we should be going up or down (loss max/loss min)
407 if((float)myrand()/(float)MY_RAND_MAX < 0.5){
409 if(Multi_lag_min >= 0){
410 mod = - (int)((float)(Multi_lag_base - Multi_lag_min) * ((float)myrand()/(float)MY_RAND_MAX));
414 if(Multi_lag_max >= 0){
415 mod = (int)((float)(Multi_lag_max - Multi_lag_base) * ((float)myrand()/(float)MY_RAND_MAX));
419 // if the current streak has elapsed, calculate a new one
420 if((Multi_streak_stamp == -1) || (timestamp_elapsed(Multi_streak_stamp))){
421 // timestamp the new streak
422 Multi_streak_stamp = timestamp(Multi_streak_time);
424 // set the return value
425 ret = Multi_lag_base + mod;
427 // set the lag value of this current streak
428 Multi_current_streak = ret;
430 // otherwise use the lag for the current streak
432 ret = Multi_current_streak;
438 // this _may_ be a bit heavyweight, but it _is_ debug code
439 int multi_lag_should_be_lost()
441 // first determine the percentage we'll be checking against
444 // if the lag system isn't inited, don't do anything
445 if(!Multi_lag_inited){
449 // see if we should be going up or down (loss max/loss min)
451 if((float)myrand()/(float)MY_RAND_MAX < 0.5){
453 if(Multi_loss_min >= 0.0f){
454 mod = - ((Multi_loss_base - Multi_loss_min) * ((float)myrand()/(float)MY_RAND_MAX));
458 if(Multi_loss_max >= 0.0f){
459 mod = ((Multi_loss_max - Multi_loss_base) * ((float)myrand()/(float)MY_RAND_MAX));
463 if((float)myrand()/(float)MY_RAND_MAX <= Multi_loss_base + mod){
470 // get a free packet buffer, return NULL on fail
471 lag_buf *multi_lag_get_free()
475 // if we're out of buffers
476 if(Lag_buf_count >= MAX_LAG_BUFFERS){
477 nprintf(("Network", "Out of lag buffers!\n"));
482 lagp = GET_FIRST(&Lag_free_list);
483 SDL_assert( lagp != &Lag_free_list ); // shouldn't have the dummy element
485 // remove trailp from the free list
486 list_remove( &Lag_free_list, lagp );
488 // insert trailp onto the end of used list
489 list_append( &Lag_used_list, lagp );
491 // increase the count
496 // put a lag buffer back
497 void multi_lag_put_free(lag_buf *buf)
499 // remove objp from the used list
500 list_remove( &Lag_used_list, buf);
502 // add objp to the end of the free
503 list_append( &Lag_free_list, buf );
509 void multi_lagloss_dcf()
511 // if the lag system isn't inited, don't do anything
512 if(!Multi_lag_inited){
513 dc_printf("Lag System Not Initialized!\n");
517 // display all available commands
518 dc_printf("Usage :\nlag <ms> (-1 to disable)\nlag_min <ms>\nlag_max <ms>\nloss <0-100> (-1 to disable)\nloss_min <0-100>\nloss_max <0-100>\nlag_streak <ms>\nlagloss\n");
520 // display lag settings
522 dc_printf("\n Base %d\n Min %d\n Max %d\n Streak %d\n", Multi_lag_base, Multi_lag_min, Multi_lag_max, Multi_streak_time);
524 // display loss settings
525 dc_printf("Loss : ");
526 dc_printf("\n Base %f\n Min %f\n Max %f\n", Multi_loss_base, Multi_loss_min, Multi_loss_max);
531 // if the lag system isn't inited, don't do anything
532 if(!Multi_lag_inited){
533 dc_printf("Lag System Not Initialized!\n");
538 // parse the argument and change things around accordingly
539 if(Dc_arg_type & ARG_INT){
541 // switch the lag sim off
545 dc_printf("Turning simulated lag off\n");
547 } else if((Multi_lag_max >= 0) && (Dc_arg_int > Multi_lag_max)){
548 dc_printf("Base value greater than max value, ignoring...");
549 } else if((Multi_lag_min >= 0) && (Dc_arg_int < Multi_lag_min)){
550 dc_printf("Base value smaller than min value, ignoring...");
552 Multi_lag_base = Dc_arg_int;
560 // if the lag system isn't inited, don't do anything
561 if(!Multi_lag_inited){
562 dc_printf("Lag System Not Initialized!\n");
567 // parse the argument and change things around accordingly
568 if(Dc_arg_type & ARG_INT){
569 if(Dc_arg_int > Multi_lag_base){
570 dc_printf("Min value greater than base value, ignoring...");
575 Multi_lag_min = Dc_arg_int;
584 // if the lag system isn't inited, don't do anything
585 if(!Multi_lag_inited){
586 dc_printf("Lag System Not Initialized!\n");
590 // parse the argument and change things around accordingly
592 if(Dc_arg_type & ARG_INT){
593 if((Dc_arg >=0) && (Dc_arg_int < Multi_lag_base)){
594 dc_printf("Max value smaller than base value, ignoring...");
599 Multi_lag_max = Dc_arg_int;
608 // if the lag system isn't inited, don't do anything
609 if(!Multi_lag_inited){
610 dc_printf("Lag System Not Initialized!\n");
614 // parse the argument and change things around accordingly
616 if(Dc_arg_type & ARG_INT){
617 float val = (float)Dc_arg_int / 100.0f;
619 if(Dc_arg_int > 100){
620 dc_printf("Illegal loss base value, ignoring...");
621 } else if(Dc_arg_int < 0){
622 // switch the loss sim off
623 dc_printf("Turning simulated loss off\n");
624 Multi_loss_base = -1.0f;
625 Multi_loss_min = -1.0f;
626 Multi_loss_max = -1.0f;
628 } else if((Multi_loss_max >= 0.0f) && (val > Multi_loss_max)){
629 dc_printf("Base value greater than max value, ignoring...");
630 } else if((Multi_loss_min >= 0.0f) && (val < Multi_loss_min)){
631 dc_printf("Base value smaller than min value, ignoring...");
633 Multi_loss_base = val;
641 // if the lag system isn't inited, don't do anything
642 if(!Multi_lag_inited){
643 dc_printf("Lag System Not Initialized!\n");
647 // parse the argument and change things around accordingly
649 if(Dc_arg_type & ARG_INT){
650 float val = (float)Dc_arg_int / 100.0f;
652 if(val > Multi_loss_base){
653 dc_printf("Min value greater than base value, ignoring...");
655 // otherwise set the value
657 Multi_loss_min = -1.0f;
659 Multi_loss_min = val;
668 // if the lag system isn't inited, don't do anything
669 if(!Multi_lag_inited){
670 dc_printf("Lag System Not Initialized!\n");
674 // parse the argument and change things around accordingly
676 if(Dc_arg_type & ARG_INT){
677 float val = (float)Dc_arg_int / 100.0f;
679 if(val < Multi_loss_base){
680 dc_printf("Max value smaller than base value, ignoring...");
682 // otherwise set the value
684 Multi_loss_max = -1.0f;
686 Multi_loss_min = val;
695 // if the lag system isn't inited, don't do anything
696 if(!Multi_lag_inited){
697 dc_printf("Lag System Not Initialized!\n");
706 // if the lag system isn't inited, don't do anything
707 if(!Multi_lag_inited){
708 dc_printf("Lag System Not Initialized!\n");
713 if(Dc_arg_type & ARG_INT){
715 Multi_streak_time = Dc_arg_int;
722 // if the lag system isn't inited, don't do anything
723 if(!Multi_lag_inited){
724 dc_printf("Lag System Not Initialized!\n");
728 dc_printf("Setting bad lag/loss parameters\n");
730 // set good lagloss parameters
731 Multi_lag_base = 500;
735 Multi_loss_base = 0.2f;
736 Multi_loss_min = 0.15f;
737 Multi_loss_max = 0.23f;
739 Multi_streak_time = 800;
740 Multi_streak_stamp = -1;
741 Multi_current_streak = -1;
746 // if the lag system isn't inited, don't do anything
747 if(!Multi_lag_inited){
748 dc_printf("Lag System Not Initialized!\n");
752 dc_printf("Setting avg lag/loss parameters\n");
754 // set good lagloss parameters
755 Multi_lag_base = 275;
759 Multi_loss_base = 0.15f;
760 Multi_loss_min = 0.1f;
761 Multi_loss_max = 0.20f;
763 Multi_streak_time = 900;
764 Multi_streak_stamp = -1;
765 Multi_current_streak = -1;
770 // if the lag system isn't inited, don't do anything
771 if(!Multi_lag_inited){
772 dc_printf("Lag System Not Initialized!\n");
776 dc_printf("Setting good lag/loss parameters\n");
778 // set good lagloss parameters
779 Multi_lag_base = 100;
783 Multi_loss_base = 0.08f;
784 Multi_loss_min = 0.0f;
785 Multi_loss_max = 0.1f;
787 Multi_streak_time = 1000;
788 Multi_streak_stamp = -1;
789 Multi_current_streak = -1;