]> icculus.org git repositories - taylor/freespace2.git/blob - src/network/multiutil.cpp
remove IPX from multi*
[taylor/freespace2.git] / src / network / multiutil.cpp
1 /*
2  * Copyright (C) Volition, Inc. 1999.  All rights reserved.
3  *
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
6  * the source.
7  */
8
9 /*
10  * $Logfile: /Freespace2/code/Network/MultiUtil.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * C file that contains misc. functions to support multiplayer
16  *
17  * $Log$
18  * Revision 1.10  2006/04/26 19:48:58  taylor
19  * various big-endian fixes, mainly networking support related
20  *
21  * Revision 1.9  2003/05/25 02:30:43  taylor
22  * Freespace 1 support
23  *
24  * Revision 1.8  2002/06/17 06:33:10  relnev
25  * ryan's struct patch for gcc 2.95
26  *
27  * Revision 1.7  2002/06/09 04:41:24  relnev
28  * added copyright header
29  *
30  * Revision 1.6  2002/06/05 08:05:29  relnev
31  * stub/warning removal.
32  *
33  * reworked the sound code.
34  *
35  * Revision 1.5  2002/06/02 04:26:34  relnev
36  * warning cleanup
37  *
38  * Revision 1.4  2002/05/27 00:40:47  theoddone33
39  * Fix net_addr vs net_addr_t
40  *
41  * Revision 1.3  2002/05/26 20:49:54  theoddone33
42  * More progress
43  *
44  * Revision 1.2  2002/05/07 03:16:47  theoddone33
45  * The Great Newline Fix
46  *
47  * Revision 1.1.1.1  2002/05/03 03:28:10  root
48  * Initial import.
49  *
50  * 
51  * 47    9/15/99 1:45a Dave
52  * Don't init joystick on standalone. Fixed campaign mode on standalone.
53  * Fixed no-score-report problem in TvT
54  * 
55  * 46    9/09/99 8:53p Dave
56  * Fixed multiplayer degenerate orientation case problem. Make sure warp
57  * effect never goes lower than LOD 1. 
58  * 
59  * 45    8/24/99 1:50a Dave
60  * Fixed client-side afterburner stuttering. Added checkbox for no version
61  * checking on PXO join. Made button info passing more friendly between
62  * client and server.
63  * 
64  * 44    8/23/99 10:30a Dave
65  * Make sure a kill limit of 0 really means "no kill limit"
66  * 
67  * 43    8/22/99 5:53p Dave
68  * Scoring fixes. Added self destruct key. Put callsigns in the logfile
69  * instead of ship designations for multiplayer players.
70  * 
71  * 42    8/22/99 1:19p Dave
72  * Fixed up http proxy code. Cleaned up scoring code. Reverse the order in
73  * which d3d cards are detected.
74  * 
75  * 41    8/19/99 10:59a Dave
76  * Packet loss detection.
77  * 
78  * 40    8/06/99 2:44a Dave
79  * Make sure dead players who leave respawn AI.
80  * 
81  * 39    8/06/99 12:29a Dave
82  * Multiple bug fixes.
83  * 
84  * 38    8/03/99 11:02p Dave
85  * Maybe fixed sync problems in multiplayer.
86  * 
87  * 37    7/30/99 7:01p Dave
88  * Dogfight escort gauge. Fixed up laser rendering in Glide.
89  * 
90  * 36    7/26/99 5:50p Dave
91  * Revised ingame join. Better? We'll see....
92  * 
93  * 35    7/15/99 9:20a Andsager
94  * FS2_DEMO initial checkin
95  * 
96  * 34    7/08/99 10:53a Dave
97  * New multiplayer interpolation scheme. Not 100% done yet, but still
98  * better than the old way.
99  * 
100  * 33    6/25/99 5:04p Jasenw
101  * Added some debug line stuff.
102  * 
103  * 32    6/16/99 4:06p Dave
104  * New pilot info popup. Added new draw-bitmap-as-poly function.
105  * 
106  * 31    5/18/99 11:50a Andsager
107  * Remove unused object type OBJ_GHOST_SAVE
108  * 
109  * 30    5/04/99 5:20p Dave
110  * Fixed up multiplayer join screen and host options screen. Should both
111  * be at 100% now.
112  * 
113  * 29    5/03/99 8:33p Dave
114  * New version of multi host options screen.
115  * 
116  * 28    4/27/99 12:16a Dave
117  * Fixed beam weapon muzzle glow problem. Fixed premature timeout on the
118  * pxo server list screen. Fixed secondary firing for hosts on a
119  * standalone. Fixed wacky multiplayer weapon "shuddering" problem.
120  * 
121  * 27    4/25/99 7:43p Dave
122  * Misc small bug fixes. Made sun draw properly.
123  * 
124  * 26    4/25/99 3:02p Dave
125  * Build defines for the E3 build.
126  * 
127  * 25    4/09/99 2:21p Dave
128  * Multiplayer beta stuff. CD checking.
129  * 
130  * 24    4/08/99 2:10a Dave
131  * Numerous bug fixes for the beta. Added builtin mission info for the
132  * beta.
133  * 
134  * 23    3/10/99 6:50p Dave
135  * Changed the way we buffer packets for all clients. Optimized turret
136  * fired packets. Did some weapon firing optimizations.
137  * 
138  * 22    3/09/99 6:24p Dave
139  * More work on object update revamping. Identified several sources of
140  * unnecessary bandwidth.
141  * 
142  * 21    3/08/99 7:03p Dave
143  * First run of new object update system. Looks very promising.
144  * 
145  * 20    3/01/99 10:00a Dave
146  * Fxied several dogfight related stats bugs.
147  * 
148  * 19    2/24/99 2:25p Dave
149  * Fixed up chatbox bugs. Made squad war reporting better. Fixed a respawn
150  * bug for dogfight more.
151  * 
152  * 18    2/23/99 2:29p Dave
153  * First run of oldschool dogfight mode. 
154  * 
155  * 17    2/12/99 6:16p Dave
156  * Pre-mission Squad War code is 95% done.
157  * 
158  * 16    2/11/99 3:08p Dave
159  * PXO refresh button. Very preliminary squad war support.
160  * 
161  * 15    2/08/99 5:07p Dave
162  * FS2 chat server support. FS2 specific validated missions.
163  * 
164  * 14    1/30/99 1:29a Dave
165  * Fixed nebula thumbnail problem. Full support for 1024x768 choose pilot
166  * screen.  Fixed beam weapon death messages.
167  * 
168  * 13    1/14/99 6:06p Dave
169  * 100% full squad logo support for single player and multiplayer.
170  * 
171  * 12    1/12/99 4:07a Dave
172  * Put in barracks code support for selecting squad logos. Properly
173  * distribute squad logos in a multiplayer game.
174  * 
175  * 11    12/14/98 4:01p Dave
176  * Got multi_data stuff working well with new xfer stuff. 
177  * 
178  * 10    12/14/98 12:13p Dave
179  * Spiffed up xfer system a bit. Put in support for squad logo file xfer.
180  * Need to test now.
181  * 
182  * 9     11/19/98 4:19p Dave
183  * Put IPX sockets back in psnet. Consolidated all multiplayer config
184  * files into one.
185  * 
186  * 8     11/19/98 8:04a Dave
187  * Full support for D3-style reliable sockets. Revamped packet lag/loss
188  * system, made it receiver side and at the lowest possible level.
189  * 
190  * 7     11/17/98 11:12a Dave
191  * Removed player identification by address. Now assign explicit id #'s.
192  * 
193  * 6     11/05/98 5:55p Dave
194  * Big pass at reducing #includes
195  * 
196  * 5     10/13/98 9:29a Dave
197  * Started neatening up freespace.h. Many variables renamed and
198  * reorganized. Added AlphaColors.[h,cpp]
199  * 
200  * 4     10/09/98 2:57p Dave
201  * Starting splitting up OS stuff.
202  * 
203  * 3     10/07/98 6:27p Dave
204  * Globalized mission and campaign file extensions. Removed Silent Threat
205  * special code. Moved \cache \players and \multidata into the \data
206  * directory.
207  * 
208  * 2     10/07/98 10:53a Dave
209  * Initial checkin.
210  * 
211  * 1     10/07/98 10:50a Dave
212  * 
213  * 283   9/28/98 1:54p Dave
214  * Make sure French and German don't xfer builtin files they don't have
215  * (to themselves)
216  * 
217  * 282   9/28/98 1:41p Dave
218  * Properly detect "builtin" missions.
219  * 
220  * 281   9/21/98 11:46p Dave
221  * Flag mission disk players in the right spot.
222  * 
223  * 280   9/15/98 7:24p Dave
224  * Minor UI changes. Localized bunch of new text.
225  * 
226  * $NoKeywords: $
227  */
228
229 #ifndef PLAT_UNIX
230 #include <winsock.h>
231 #else
232 #include <sys/types.h>
233 #include <sys/socket.h>
234 #include <netinet/in.h>
235 #include <arpa/inet.h>
236 #include <netdb.h>
237 #include <errno.h>
238 #endif
239 #include <ctype.h>
240 #include "multiutil.h"
241 #include "multimsgs.h"
242 #include "multi.h"
243 #include "linklist.h"
244 #include "gamesequence.h"
245 #include "hudmessage.h"
246 #include "freespace.h"
247 #include "key.h"
248 #include "2d.h"
249 #include "weapon.h"
250 #include "timer.h"
251 #include "ship.h"
252 #include "psnet.h"
253 #include "player.h"
254 #include "missionparse.h"
255 #include "missionshipchoice.h"
256 #include "missionscreencommon.h"
257 #include "missionweaponchoice.h"
258 #include "multi_xfer.h"
259 #include "stand_gui.h"
260 #include "shipfx.h"
261 #include "object.h"
262 #include "managepilot.h"
263 #include "multiteamselect.h"
264 #include "shiphit.h"
265 #include "missiondebrief.h"
266 #include "observer.h"
267 #include "missionmessage.h"
268 #include "multilag.h"
269 #include "popup.h"
270 #include "popupdead.h"
271 #include "hudconfig.h"
272 #include "multiui.h"
273 #include "optionsmenu.h"
274 #include "missionhotkey.h"
275 #include "missiongoals.h"
276 #include "afterburner.h"
277 #include "chatbox.h"
278 #include "multi_kick.h"
279 #include "multi_data.h"
280 #include "multi_voice.h"
281 #include "multi_ping.h"
282 #include "multi_team.h"
283 #include "multi_respawn.h"
284 #include "multi_ingame.h"
285 #include "multi_observer.h"
286 #include "multi_pinfo.h"
287 #include "multi_endgame.h"
288 #include "multi_pmsg.h"
289 #include "multi_pause.h"
290 #include "multi_obj.h"
291 #include "multi_log.h"
292 #include "multi_rate.h"
293 #include "osregistry.h"
294 #include "hudescort.h"
295
296 extern int MSG_WINDOW_X_START;  // used to position multiplayer text messages
297 extern int MSG_WINDOW_Y_START;
298 extern int MSG_WINDOW_HEIGHT;
299
300 // if a client doesn't receive an update for an object after this many seconds, query server
301 // as to the objects status.
302 #define MULTI_CLIENT_OBJ_TIMEOUT                10
303 #define MAX_SHIPS_PER_QUERY                     10
304
305
306 // this function assignes the given object with the given signature.  If the signature is 0, then we choose
307 // the next signature number from the correct pool.  I thought that it might be desireable
308 // to not always have to take the next signature on the list.  what_kind is used to assign either a
309 // permanent or non-permanent signature to an object.  permanent signatures are used for ships, non_permanent
310 // signatures are used for everything else.
311 ushort multi_assign_network_signature( int what_kind )
312 {
313         ushort sig;     
314
315         // do limit checking on the permanent and non_permanent signatures.  Ships are considered "permanent"
316         // as are debris and asteroids since they don't die very often.  It would be vary rare for this
317         // value (the permanent signature) to wrap.  For now, this condition is an error condition
318         if ( what_kind == MULTI_SIG_SHIP ) {
319                 if ( Next_ship_signature == 0 ){
320                         Next_ship_signature = SHIP_SIG_MIN;
321                 }
322
323                 sig = Next_ship_signature++;
324
325                 if ( Next_ship_signature == SHIP_SIG_MAX ) {
326                         Int3();                 // get Allender -- signature stuff wrapped.
327                         Next_ship_signature = SHIP_SIG_MIN;
328                 }
329
330                 // signature stuff for asteroids.
331         } else if ( what_kind == MULTI_SIG_ASTEROID ) {
332                 if ( Next_asteroid_signature == 0 ){
333                         Next_asteroid_signature = ASTEROID_SIG_MIN;
334                 }
335
336                 sig = Next_asteroid_signature++;
337                 if ( Next_asteroid_signature == ASTEROID_SIG_MAX ) {
338                         Int3();                 // get Allender -- signature stuff wrapped.
339                         Next_asteroid_signature = ASTEROID_SIG_MIN;
340                 }
341
342                 // signatures for debris
343         } else if ( what_kind == MULTI_SIG_DEBRIS ) {
344                 if ( Next_debris_signature == 0 ){
345                         Next_debris_signature = DEBRIS_SIG_MIN;
346                 }
347
348                 sig = Next_debris_signature++;
349                 if ( Next_debris_signature == DEBRIS_SIG_MAX ) {
350                         Int3();                 // get Allender -- signature stuff wrapped.
351                         Next_debris_signature = DEBRIS_SIG_MIN;
352                 }
353
354                 // signature stuff for weapons and other expendable things.
355         } else if ( what_kind == MULTI_SIG_NON_PERMANENT ) {
356                 if ( Next_non_perm_signature == 0 ){
357                         Next_non_perm_signature = NPERM_SIG_MIN;
358                 }
359
360                 sig = Next_non_perm_signature++;
361                 if ( Next_non_perm_signature == NPERM_SIG_MAX ){
362                         Next_non_perm_signature = NPERM_SIG_MIN;
363                 }
364         } else {
365                 Int3();         // get allender - Illegal signature type requested
366                 sig = 0;
367         }
368
369         return sig;
370 }
371
372 // this function returns the next network signature that will be used for a newly created object
373 // what_kind parameter tells us what kind of signature to get -- permanent or non-permanent
374 ushort multi_get_next_network_signature( int what_kind )
375 {
376         if ( what_kind == MULTI_SIG_SHIP ) {
377                 if ( Next_ship_signature == 0 )
378                         Next_ship_signature = SHIP_SIG_MIN;
379                 return Next_ship_signature;
380
381         } else if ( what_kind == MULTI_SIG_DEBRIS ) {
382                 if ( Next_debris_signature == 0 )
383                         Next_debris_signature = DEBRIS_SIG_MIN;
384                 return Next_debris_signature;
385
386         } else if ( what_kind == MULTI_SIG_ASTEROID ) {
387                 if ( Next_asteroid_signature == 0 )
388                         Next_asteroid_signature = ASTEROID_SIG_MIN;
389                 return Next_asteroid_signature;
390
391         } else if ( what_kind == MULTI_SIG_NON_PERMANENT ) {
392                 if ( Next_non_perm_signature == 0 )
393                         Next_non_perm_signature = NPERM_SIG_MIN;
394                 return Next_non_perm_signature;
395
396         } else {
397                 Int3();                 // get allender
398                 return 0;
399         }
400 }
401
402 // this routine sets the network signature to the given value.  Should be called from client only
403 // and is used mainly for firing weapons.  what_kind tells us permanent or non-permanent signature
404 void multi_set_network_signature( ushort signature, int what_kind )
405 {
406         SDL_assert( signature != 0 );
407
408         if ( what_kind == MULTI_SIG_SHIP ) {
409                 SDL_assert( (signature >= SHIP_SIG_MIN) && (signature <= SHIP_SIG_MAX) );
410                 Next_ship_signature = signature;
411         } else if ( what_kind == MULTI_SIG_DEBRIS ) {
412                 SDL_assert( (signature >= DEBRIS_SIG_MIN) && (signature <= DEBRIS_SIG_MAX) );
413                 Next_debris_signature = signature;
414         } else if ( what_kind == MULTI_SIG_ASTEROID ) {
415                 SDL_assert( (signature >= ASTEROID_SIG_MIN) && (signature <= ASTEROID_SIG_MAX) );
416                 Next_asteroid_signature = signature;
417         } else if ( what_kind == MULTI_SIG_NON_PERMANENT ) {
418                 SDL_assert( (signature >= NPERM_SIG_MIN) && (signature <= NPERM_SIG_MAX) );
419                 Next_non_perm_signature = signature;
420         } else
421                 Int3();                 // get Allender
422 }
423
424 // multi_get_network_object() takes a net_signature and tries to locate the object in the object list
425 // with that network signature.  Returns NULL if the object cannot be found
426 object *multi_get_network_object( ushort net_signature )
427 {
428         object *objp;
429
430         if ( net_signature == 0 )
431                 return NULL;
432
433         if(GET_FIRST(&obj_used_list) == NULL)
434                 return NULL;
435
436         for ( objp = GET_FIRST(&obj_used_list); objp != END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) )
437                 if ( objp->net_signature == net_signature )
438                         break;
439
440         // if not found on used list, check create list
441         if ( objp == END_OF_LIST(&obj_used_list) ) {
442                 for ( objp = GET_FIRST(&obj_create_list); objp != END_OF_LIST(&obj_create_list); objp = GET_NEXT(objp) )
443                         if ( objp->net_signature == net_signature )
444                                 break;
445
446                 if ( objp == END_OF_LIST(&obj_create_list) )
447                         objp = NULL;
448         }
449
450         return objp;
451 }
452
453
454 // -------------------------------------------------------------------------------------------------
455 //      multi_random_death_word() will return a word from the below list at random.
456 //
457 //      Note:  Keep words grouped into sections of 10
458
459 #define NUM_DEATH_WORDS 40
460
461 const char *multi_random_death_word()
462 {
463         int index;
464
465         index = rand() % NUM_DEATH_WORDS;
466         switch (index) {
467                 case 0:
468                         return XSTR("zapped",853);
469                 case 1:
470                         return XSTR("caulked",854);
471                 case 2:
472                         return XSTR("killed",855);
473                 case 3:
474                         return XSTR("waxed",856);
475                 case 4:
476                         return XSTR("popped",857);
477                 case 5:
478                         return XSTR("murdered",858);
479                 case 6:
480                         return XSTR("bludgeoned",859);
481                 case 7:
482                         return XSTR("destroyed",860);
483                 case 8:
484                         return XSTR("iced",861);
485                 case 9:
486                         return XSTR("obliterated",862);
487                 case 10:
488                         return XSTR("toasted",863);
489                 case 11:
490                         return XSTR("roasted",864);
491                 case 12:
492                         return XSTR("turned into anti-matter",865);
493                 case 13:
494                         return XSTR("killed like a pig",866);
495                 case 14:
496                         return XSTR("taught a lesson",867);
497                 case 15:
498                         return XSTR("slaughtered with impunity",868);
499                 case 16:
500                         return XSTR("spanked like a naughty boy",869);
501                 case 17:
502                         return XSTR("skunked",870);
503                 case 18:
504                         return XSTR("beat senseless",871);
505                 case 19:
506                         return XSTR("shot up",872);
507                 case 20:
508                         return XSTR("spaced",873);
509                 case 21:
510                         return XSTR("hosed",874);
511                 case 22:
512                         return XSTR("capped",875);
513                 case 23:
514                         return XSTR("beat down",876);
515                 case 24:
516                         return XSTR("hit wit da shizzo",877);
517                 case 25:
518                         return XSTR("sk00led",878);
519                 case 26:
520                         return XSTR("whooped up",879);
521                 case 27:
522                         return XSTR("brought to the all-you-can-take whoop ass buffet",880);
523                 case 28:
524                         return XSTR("served up a whoop ass sandwich...hold the mercy",881);
525                 case 29:
526                         return XSTR("gibbed by Kayser Sozay's rocket",882);
527                 case 30:
528                         return XSTR("shot down",883);
529                 case 31:
530                         return XSTR("given early retirement",884);
531                 case 32:
532                         return XSTR("instructed",885);
533                 case 33:
534                         return XSTR("eviscerated",886);
535                 case 34:
536                         return XSTR("pummelled",887);
537                 case 35:
538                         return XSTR("eradicated",888);
539                 case 36:
540                         return XSTR("cleansed",889);
541                 case 37:
542                         return XSTR("perforated",890);
543                 case 38:
544                         return XSTR("canned",891);
545                 case 39:
546                         return XSTR("decompressed",892);
547         }
548
549         return NOX("Error");
550 }
551
552 // -------------------------------------------------------------------------------------------------
553 //      multi_random_chat_start() will return a word from the below list at random.
554 //
555 //
556
557 #define NUM_CHAT_START_WORDS    8
558 #define MAX_CHAT_PHRASE_LEN     25              // be careful not to exceed (or update if exceeded)
559
560 const char *multi_random_chat_start()
561 {
562         int index;
563
564         index = rand() % NUM_CHAT_START_WORDS;
565         switch (index) {
566                 case 0:
567                         return XSTR("says",893);
568                 case 1:
569                         return XSTR("bleats",894);
570                 case 2:
571                         return XSTR("opines",895);
572                 case 3:
573                         return XSTR("postulates",896);
574                 case 4:
575                         return XSTR("declares",897);
576                 case 5:
577                         return XSTR("vomits out",898);
578                 case 6:
579                         return XSTR("whines",899);
580                 case 7:
581                         return XSTR("barks",900);
582         }
583
584         return NOX("Error");
585 }
586
587 // -------------------------------------------------------------------------------------------------
588 //      multi_ship_class_lookup() will return the Ship_info[] index for the ship specified as a 
589 // parameter.
590 //
591 //
592
593 int multi_ship_class_lookup(const char* ship_name)
594 {
595         int i, player_ship_class;
596
597         // find the ship_info index for the ship_name
598
599         player_ship_class = -1;
600         for (i = 0; i < Num_ship_types; i++) {
601                 if ( !SDL_strcasecmp(Ship_info[i].name, ship_name) ) {
602                         player_ship_class = i;
603                         break;
604                 }
605         } // end for 
606
607         if (i == Num_ship_types){
608                 return -1;
609         }
610
611         return player_ship_class;
612 }
613
614 // -------------------------------------------------------------------------------------------------
615 //      find_player() is called when a packet arrives, and we need to know which net player to update.
616 // The matching is done based on the address and port.  Port checking is done in case multiple
617 // instances of FreeSpace are running on the same box.
618 //
619 //
620
621 int find_player( net_addr_t* addr )
622 {
623         int i;
624
625         for (i = 0; i < MAX_PLAYERS; i++ ) {
626                 if ( !MULTI_CONNECTED(Net_players[i])){
627                         continue;
628                 }
629                 if ( psnet_same( addr, &(Net_players[i].p_info.addr)) ){
630                         return i;
631                 }
632         }
633
634         return -1;
635 }
636
637 // so that we can lookup on the admin port transparently
638 int find_player_no_port(net_addr_t *addr)
639 {
640         int i;
641
642         for (i = 0; i < MAX_PLAYERS; i++ ) {
643                 if ( !MULTI_CONNECTED(Net_players[i])){
644                         continue;
645                 }
646
647                 if ( memcmp(&addr->addr, &Net_players[i].p_info.addr.addr, IP_ADDRESS_LENGTH) == 0 ) {
648                         return i;
649                 }
650         }
651
652         return -1;
653 }
654
655 int find_player_id(short player_id)
656 {
657         int i;
658         for (i = 0; i < MAX_PLAYERS; i++ ) {
659                 if ( !MULTI_CONNECTED(Net_players[i])){
660                         continue;
661                 }
662                 if(player_id == Net_players[i].player_id){
663                         return i;
664                 }
665         }       
666
667         // couldn't find the player
668         return -1;
669 }
670
671 // note this is only valid to do on a server!
672 int find_player_socket(PSNET_SOCKET_RELIABLE sock)
673 {
674         int i;
675         for (i = 0; i < MAX_PLAYERS; i++ ) {
676                 if ( !MULTI_CONNECTED(Net_players[i])){
677                         continue;
678                 }
679                 if(sock == Net_players[i].reliable_socket){
680                         return i;
681                 }
682         }       
683
684         // couldn't find the player
685         return -1;
686 }
687
688 // multi_find_player_by_object returns a player num (reference by Net_players[x]) when given a object *.
689 // used to find netplayers in game when only the object is known
690 int multi_find_player_by_object( object *objp )
691 {
692         int i, objnum;
693
694         objnum = OBJ_INDEX(objp);
695         for (i = 0; i < MAX_PLAYERS; i++ ) {
696                 if ( !MULTI_CONNECTED(Net_players[i])){
697                         continue;
698                 }
699                 if ( objnum == Net_players[i].player->objnum ){
700                         return i;
701                 }
702         }
703
704         // return -1 if the object is not found -- this is a bad situation, but we will handle it in higher
705         // level code
706         return -1;
707 }
708
709 // returns a player num based upon player object signature
710 int multi_find_player_by_signature( int signature )
711 {
712         int idx;
713
714         for(idx=0;idx<MAX_PLAYERS;idx++){
715                 // compare against each player's object signature
716                 if(MULTI_CONNECTED(Net_players[idx]) && (Objects[Net_players[idx].player->objnum].signature == signature)){
717                         // found the player
718                         return idx;
719                 }
720         }
721
722         // didn't find the player
723         return -1;
724 }
725
726 // returns a player num based upon object net signature
727 int multi_find_player_by_net_signature(ushort net_signature)
728 {
729         int idx;
730
731         for(idx=0;idx<MAX_PLAYERS;idx++){
732                 // compare against each player's object signature
733                 if(MULTI_CONNECTED(Net_players[idx]) && (Objects[Net_players[idx].player->objnum].net_signature == net_signature)){
734                         // found the player
735                         return idx;
736                 }
737         }
738
739         // didn't find the player
740         return -1;
741 }
742
743 int multi_find_player_by_ship_name(const char *ship_name)
744 {
745         int idx;
746
747         // bogus
748         if(ship_name == NULL){
749                 return -1;
750         }
751
752         for(idx=0; idx<MAX_PLAYERS; idx++){
753                 if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_OBSERVER(Net_players[idx]) && (Net_players[idx].player != NULL) && (Net_players[idx].player->objnum >= 0) && (Net_players[idx].player->objnum < MAX_OBJECTS) && (Objects[Net_players[idx].player->objnum].type == OBJ_SHIP) && 
754                         (Objects[Net_players[idx].player->objnum].instance >= 0) && (Objects[Net_players[idx].player->objnum].instance < MAX_SHIPS) && !SDL_strcasecmp(ship_name, Ships[Objects[Net_players[idx].player->objnum].instance].ship_name) ){
755                         return idx;
756                 }
757         }
758
759         // didn't find the player
760         return -1;
761 }
762
763 int multi_get_player_ship(int np_index)
764 {
765         // bogus
766         if((np_index < 0) || (np_index >= MAX_PLAYERS)){
767                 return -1;
768         }
769
770         // cool?
771         if(MULTI_CONNECTED(Net_players[np_index]) && !MULTI_OBSERVER(Net_players[np_index]) && !MULTI_STANDALONE(Net_players[np_index]) && 
772                 (Net_players[np_index].player != NULL) && (Net_players[np_index].player->objnum >= 0) && (Net_players[np_index].player->objnum < MAX_OBJECTS) && (Objects[Net_players[np_index].player->objnum].type == OBJ_SHIP) && 
773                 (Objects[Net_players[np_index].player->objnum].instance >= 0) && (Objects[Net_players[np_index].player->objnum].instance < MAX_SHIPS) ){
774
775                 return Objects[Net_players[np_index].player->objnum].instance;
776         }
777
778         // nope
779         return -1;
780 }
781
782 // find_open_netplayer_slot() attempts to find a free slot in the Net_players structure for a new player.
783 // it returns -1 if there is no new slot, and the slot number if one is found
784 // NOTE : this attempts to preserve a player object as long as possible for him to come back to
785 int multi_find_open_netplayer_slot()
786 {
787         int i;
788         int found_first;
789
790         found_first = -1;
791         for (i = 0; i < MAX_PLAYERS; i++)
792                 if ( !MULTI_CONNECTED(Net_players[i]) ){
793                    if(found_first == -1) {
794                                 found_first = i;
795                                 break;
796                         }
797                 }
798
799         if(i == MAX_PLAYERS){
800                 if(found_first == -1)
801                         return -1;
802                 else
803                         return found_first;
804         }
805
806         return i;
807 }
808
809 // find_open_player_slot() attempts to find an open player array slot.  The 0th element of the array
810 // should always be taken by the console player's pilot.  All other slots are up for grab though.
811 int multi_find_open_player_slot()
812 {
813         int i;
814
815         for (i = 0; i < MAX_PLAYERS; i++)
816                 if ( !(Players[i].flags & PLAYER_FLAGS_STRUCTURE_IN_USE) )
817                         break;
818         
819         if ( i == MAX_PLAYERS )
820                 return -1;
821
822         return i;
823 }
824
825 // stuff_netplayer_info stuffs information into the given Net_player structure.  It is called when
826 // a new person is entering the game.  The state of the Net_player is set to it's basic starting
827 // state
828 void stuff_netplayer_info( net_player *nplayer, net_addr_t *addr, int ship_class, player *pplayer )
829 {
830         nplayer->p_info.addr = *addr;
831         nplayer->flags |= NETINFO_FLAG_CONNECTED;
832         nplayer->state = NETPLAYER_STATE_JOINING;
833         nplayer->p_info.ship_class = ship_class;
834         nplayer->player = pplayer;
835         nplayer->p_info.options.obj_update_level = OBJ_UPDATE_HIGH;
836
837         // if setting up my net flags, then set the flag to say I can do networking.
838         if ( nplayer == Net_player ){
839                 nplayer->flags |= NETINFO_FLAG_DO_NETWORKING;
840         }
841 }
842
843 // multi_assign_player_ship takes a Net_player index and an object * and assigned that player to
844 // that object
845 void multi_assign_player_ship( int net_player, object *objp,int ship_class )
846 {
847         ship *shipp;
848         int idx;
849
850         SDL_assert ( MULTI_CONNECTED(Net_players[net_player]) );
851
852         shipp = &Ships[objp->instance];
853
854         Net_players[net_player].player->objnum = OBJ_INDEX(objp);
855         Net_players[net_player].p_info.ship_class = ship_class;
856
857         // check to see if we are assigning my player -- if so, then set Player_ship and Player_ai
858         if ( Net_player == &Net_players[net_player] ) {
859                 Player_obj = objp;
860                 Player_ship = shipp;
861                 Player_ai = &Ai_info[Player_ship->ai_index];
862         }
863
864         // find the parse object for this ship.  Also, set the wingman status stuff so wingman status gauge
865         // works properly.
866         Net_players[net_player].p_info.p_objp = mission_parse_get_arrival_ship( shipp->ship_name );
867         SDL_assert( Net_players[net_player].p_info.p_objp != NULL );            // get allender -- ship should be on list
868         Net_players[net_player].p_info.p_objp->ship_class = ship_class;         // be sure this gets set so respawns work
869
870         // game server and this client need to initialize this information so object updating
871         // works properly.
872         if ( MULTIPLAYER_MASTER || (Net_player == &Net_players[net_player]) ) {
873                 Net_players[net_player].s_info.eye_pos = objp->pos;
874                 Net_players[net_player].s_info.eye_orient = objp->orient;
875         }
876
877         // zero update info     
878         for(idx=0; idx<MAX_PLAYERS; idx++){
879                 shipp->np_updates[idx].orient_chksum = 0;
880                 shipp->np_updates[idx].pos_chksum = 0;
881                 shipp->np_updates[idx].seq = 0;
882                 shipp->np_updates[idx].status_update_stamp = -1;
883                 shipp->np_updates[idx].subsys_update_stamp = -1;
884                 shipp->np_updates[idx].update_stamp = -1;
885         }
886 }
887
888 // -------------------------------------------------------------------------------------------------
889 //      create_player() is called when a net player needs to be instantiated.  The ship that is created
890 // depends on the parameter ship_class.  Note that if ship_class is invalid, the ship default_player_ship
891 // is used.  Returns 1 on success, 0 otherwise
892
893 int multi_create_player( int net_player_num, player *pl, char* name, net_addr_t* addr, int ship_class, short id)
894 {
895         int player_ship_class = ship_class;
896         int i,current_player_count;
897
898         SDL_assert ( net_player_num < MAX_PLAYERS );                            // probably shoudln't be able to even get into this routine if no room  
899         
900         // blast _any_ old data
901         memset(&Net_players[net_player_num],0,sizeof(net_player));
902
903         // get the current # of players
904         current_player_count = multi_num_players();
905
906         // DOH!!! The lack of this caused many bugs. 
907         Net_players[net_player_num].flags = (NETINFO_FLAG_DO_NETWORKING);
908                 
909         if ( ship_class == -1 ) {
910                 nprintf(("Network","Network ==> ship class is -1, creating a default ship for multiplayer\n"));
911
912                 // find the ship that matches the string stored in default_player_ship
913
914                 for (i = 0; i < Num_ship_types; i++) {
915                         if ( !SDL_strcasecmp(Ship_info[i].name, default_player_ship) ) {
916                                 player_ship_class = i;
917                                 break;
918                         }
919                 }
920
921                 if (i == Num_ship_types)
922                         SDL_assert(0);
923         }
924         
925         if ( player_ship_class >= Num_ship_types ) {
926                 player_ship_class = multi_ship_class_lookup(default_player_ship);
927                 nprintf(("Network","Network ==> Ship class was %d Creating a default ship for multiplayer\n", player_ship_class));
928         }
929
930         // blast the old player data
931         memset(pl,0,sizeof(player));
932
933         // set up the net_player structure
934         stuff_netplayer_info( &Net_players[net_player_num], addr, player_ship_class, pl );
935         Net_players[net_player_num].s_info.num_last_buttons = 0;
936         // Net_players[net_player_num].respawn_count = 0;
937         Net_players[net_player_num].last_heard_time = timer_get_fixed_seconds();
938         Net_players[net_player_num].reliable_socket = INVALID_SOCKET;
939         Net_players[net_player_num].s_info.kick_timestamp = -1;
940         Net_players[net_player_num].s_info.voice_token_timestamp = -1;
941         Net_players[net_player_num].s_info.tracker_security_last = -1;
942         Net_players[net_player_num].s_info.target_objnum = -1;
943         Net_players[net_player_num].s_info.accum_buttons = 0;
944
945         // zero out this players ping times data
946         multi_ping_reset(&Net_players[net_player_num].s_info.ping);
947
948         // zero out his object update and control info sequencing data
949         Net_players[net_player_num].client_cinfo_seq = 0;
950         Net_players[net_player_num].client_server_seq = 0;              
951         
952         // timestamp his last_full_update_time
953         Net_players[net_player_num].s_info.last_full_update_time = timestamp(0);
954
955         // nil his file xfer handle
956         Net_players[net_player_num].s_info.xfer_handle = -1;
957
958         // nil his data rate timestamp stuff
959         Net_players[net_player_num].s_info.rate_stamp = -1;
960         Net_players[net_player_num].s_info.rate_bytes = 0;
961
962         // nil packet buffer stuff
963         Net_players[net_player_num].s_info.unreliable_buffer_size = 0;
964         Net_players[net_player_num].s_info.reliable_buffer_size = 0;
965         
966         // various ack handles  
967         SDL_strlcpy(pl->callsign, name, SDL_arraysize(pl->callsign));
968         pilot_set_short_callsign(pl, SHORT_CALLSIGN_PIXEL_W);   // calculate the short callsign 
969         pl->flags |= PLAYER_FLAGS_STRUCTURE_IN_USE;
970         pl->objnum = -1;
971
972         // if we're the standalone server and this is the first guy to join, mark him as the host
973         // and give him all host priveleges
974         if((Game_mode & GM_STANDALONE_SERVER) && (current_player_count == 0)){
975                 Net_players[net_player_num].flags |= NETINFO_FLAG_GAME_HOST;
976         }
977         
978         Net_players[net_player_num].player_id = id;
979
980         Net_player->sv_bytes_sent = 0;
981         Net_player->sv_last_pl = -1;
982         Net_player->cl_bytes_recvd = 0;
983         Net_player->cl_last_pl = -1;
984
985         // add to the escort list
986         if(MULTI_IN_MISSION){
987                 hud_escort_add_player(id);
988         }
989
990         return 1;
991 }
992
993 // next function makes a player object an ai object (also decrementing the num_players in the
994 // netgame).  It appropiately sets the object flags and other interesting AI information which
995 // ought to get set in order to make this new ai object behave correctly.
996 void multi_make_player_ai( object *pobj )
997 {
998
999         SDL_assert ( pobj != NULL );
1000
1001         if ( pobj->type != OBJ_SHIP )
1002                 return;
1003
1004         pobj->flags &= ~(OF_PLAYER_SHIP);
1005         obj_set_flags( pobj, pobj->flags | OF_COULD_BE_PLAYER );
1006
1007         // target_objnum must be -1 or else new AI ship will fire on whatever this player
1008         // had targeted.
1009         set_target_objnum( &(Ai_info[Ships[pobj->instance].ai_index]), -1 );
1010
1011 }
1012
1013 // delete_player takes an index into the Net_players array to delete.  Deletion of a player might happen
1014 // because of the player leaving the game on his own, or no net activity from the player after X seconds
1015 void delete_player(int player_num,int kicked_reason)
1016 {                       
1017         char notify_string[256] = "";
1018         int idx;
1019         
1020         if(!MULTI_CONNECTED(Net_players[player_num])){
1021                 return;
1022         }
1023
1024         // NETLOG
1025         ml_printf(NOX("Deleting player %s"), Net_players[player_num].player->callsign);
1026         
1027         psnet_rel_close_socket( &(Net_players[player_num].reliable_socket) );                                   // close out the reliable socket        
1028
1029         // if this guy was ingame joining, the remove my netgame flag so others may join
1030         if ( Net_players[player_num].flags & NETINFO_FLAG_INGAME_JOIN ) {
1031                 Netgame.flags &= ~NG_FLAG_INGAME_JOINING;
1032                 Netgame.flags &= ~NG_FLAG_INGAME_JOINING_CRITICAL;
1033         }
1034         
1035         Net_players[player_num].flags &= ~NETINFO_FLAG_CONNECTED;                                                       // person not connected anymore
1036         Net_players[player_num].player->flags &= ~(PLAYER_FLAGS_STRUCTURE_IN_USE);    // free up his player structure
1037
1038         Net_players[player_num].s_info.reliable_connect_time = -1;
1039
1040         // add to the escort list
1041         hud_escort_remove_player(Net_players[player_num].player_id);
1042
1043         // is this guy the server
1044         if(Net_players[player_num].flags & NETINFO_FLAG_AM_MASTER){
1045                 // if the server leaves in the debriefing state, we should still wait until the player selects accept before we quit
1046                 if ((gameseq_get_state() != GS_STATE_DEBRIEF) && (gameseq_get_state() != GS_STATE_MULTI_DOGFIGHT_DEBRIEF)){
1047                         multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_SERVER_LEFT);
1048                 }               
1049         }
1050         // if he was just the host      
1051         else if(Net_players[player_num].flags & NETINFO_FLAG_GAME_HOST){
1052                 Net_players[player_num].flags &= ~(NETINFO_FLAG_GAME_HOST);
1053         
1054                 // am I the server
1055                 if((Net_player != NULL) && (Net_player->flags & NETINFO_FLAG_AM_MASTER)){
1056                         // are we a standalone server and in a mission?
1057                         if((Game_mode & GM_STANDALONE_SERVER) && MULTI_IN_MISSION){                     
1058                                 // choose a new host                    
1059                                 int found_new_host = 0;
1060                                 for(idx=0; idx<MAX_PLAYERS; idx++){
1061                                         if(MULTI_CONNECTED(Net_players[idx]) && (Net_player != &Net_players[idx])){
1062                                                 // make this guy the host
1063                                                 Net_players[idx].flags |= NETINFO_FLAG_GAME_HOST;
1064
1065                                                 // send a packet
1066                                                 send_host_captain_change_packet(Net_players[idx].player_id, 0);
1067
1068                                                 found_new_host = 1;
1069                                                 break;
1070                                         }
1071                                 }
1072                                 // end the game         
1073                                 if(!found_new_host){
1074                                         multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_NONE, MULTI_END_ERROR_HOST_LEFT);
1075                                 }                        
1076                         } else {
1077                                 multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_NONE, MULTI_END_ERROR_HOST_LEFT);
1078                         }
1079                 } 
1080         }
1081
1082         // if we're the server of the game, notify everyone else that this guy has left
1083         // if he's marked as being kicked, then other players know about it already, so don't send again
1084         if(Net_player->flags & NETINFO_FLAG_AM_MASTER){
1085                 if(Net_players[player_num].flags & NETINFO_FLAG_KICKED){
1086                         char str[512];
1087                         memset(str, 0, 512);
1088                         multi_kick_get_text(&Net_players[player_num], Net_players[player_num].s_info.kick_reason, str, SDL_arraysize(str));
1089                         multi_display_chat_msg(str, player_num, 0);                                                      
1090                 } else {
1091                         send_leave_game_packet(Net_players[player_num].player_id, kicked_reason);
1092                 }
1093         }
1094         
1095         // if this guy is an observer, we have to make sure we delete his observer object (only if we're the server however)
1096         if( (Net_player->flags & NETINFO_FLAG_AM_MASTER) && (Net_players[player_num].flags & NETINFO_FLAG_OBSERVER) ) {
1097                 if ( Net_players[player_num].player->objnum != -1 ){
1098                         obj_delete(Net_players[player_num].player->objnum);                     // maybe change this to set flag instead                
1099                 }
1100         } else {
1101                 // otherwise mark it so that he can return to it later if possible
1102                 if ( (Net_players[player_num].player->objnum >= 0) && (Net_players[player_num].player->objnum < MAX_OBJECTS) && (Objects[Net_players[player_num].player->objnum].type == OBJ_SHIP) && (Objects[Net_players[player_num].player->objnum].instance >= 0) && (Objects[Net_players[player_num].player->objnum].instance < MAX_SHIPS)) {
1103                         multi_make_player_ai( &Objects[Net_players[player_num].player->objnum] );
1104                 } else {
1105                         multi_respawn_player_leave(&Net_players[player_num]);
1106                 }
1107         }
1108
1109         // if we're in the team select, and we're the host, we have to make sure all team select data is correctly updated                      
1110         // MWA 7/28/98.  Don't do this for a standalone server.  Since he doesn't go through the team selection
1111         // screens, his data structures are not 100% accurate.  Doing so on a standalone resulted in the wrong
1112         // ships getting marked as COULD_BE_PLAYER.  On the standalone, these flags will get properly set
1113         // in the multi_make_player_ai code above.
1114         if( (Netgame.game_state == NETGAME_STATE_BRIEFING) && !(Game_mode & GM_STANDALONE_SERVER) ) {
1115                 multi_ts_handle_player_drop();                  
1116         }                                                               
1117
1118         if (gameseq_get_state() == GS_STATE_DEBRIEF){
1119                 debrief_handle_player_drop();
1120         }
1121
1122         // handle any specific dropping conditions
1123         if(Net_player->flags & NETINFO_FLAG_AM_MASTER){
1124                 multi_team_handle_drop();
1125         }       
1126         multi_data_handle_drop(player_num);     
1127
1128         // tell the pinfo popup that a player has left
1129         multi_pinfo_notify_drop(&Net_players[player_num]);
1130
1131         // tell the datarate stuff that the player has dropped
1132         multi_rate_reset(player_num);
1133
1134         // display a message that this guy has left
1135         if(Net_players[player_num].player->callsign){
1136                 SDL_snprintf(notify_string,SDL_arraysize(notify_string),XSTR("<%s has left>",901),Net_players[player_num].player->callsign);
1137                 multi_display_chat_msg(notify_string,0,0);
1138         }
1139         
1140         // standalone gui type stuff
1141         if (Game_mode & GM_STANDALONE_SERVER) {
1142                 std_remove_player(&Net_players[player_num]);
1143                 std_connect_set_connect_count();
1144         }
1145
1146         // blast this memory clean
1147         memset(&Net_players[player_num], 0, sizeof(net_player));
1148         Net_players[player_num].reliable_socket = INVALID_SOCKET;
1149
1150         extern int Multi_client_update_times[MAX_PLAYERS];
1151         Multi_client_update_times[player_num] = -1;
1152 }
1153
1154 #define INACTIVE_LIMIT_NORMAL (15 * F1_0)
1155 #define INACTIVE_LIMIT_WAIT   (20 * F1_0)
1156
1157 // -------------------------------------------------------------------------------------------------
1158 //      multi_cull_zombies() will check if there has been any net players or observers that have been inactive for
1159 // INACTIVE_LIMIT milliseconds since last check.  If so, they are taken out of the net game.
1160 //
1161 //
1162
1163 void multi_cull_zombies()
1164 {
1165 #if 0
1166         fix current_time;
1167         int inactive_limit;
1168         int i;
1169
1170         if(gameseq_get_state() == GS_STATE_MULTI_WAIT)
1171                 inactive_limit = INACTIVE_LIMIT_WAIT;
1172         else
1173                 inactive_limit = INACTIVE_LIMIT_NORMAL;
1174
1175         current_time = timer_get_fixed_seconds();
1176
1177         for (i = 0; i < MAX_PLAYERS; i++) {
1178                 if ( !MULTI_CONNECTED(&Net_players[i])){
1179                         continue;
1180                 }
1181
1182                 // server will(should) cull out players based on their sockets dying.
1183                 if ( Net_players[i].flags & NETINFO_FLAG_MASTER ){
1184                         continue;
1185                 }
1186
1187                 if ( (current_time - Net_players[i].last_heard_time) > inactive_limit) {
1188                         HUD_printf(XSTR("Dumping %s after prolonged inactivity",902),Net_players[i].player->callsign);
1189                         nprintf(("Network", "Assuming %s is a zombie, removing from game\n", Net_players[i].player->callsign));
1190
1191                         multi_kick_player(i,0);                 
1192                 }
1193         }
1194 #endif
1195 }
1196
1197 // -------------------------------------------------------------------------------------------------
1198 // netmisc_calc_checksum() calculates the checksum of a block of memory.
1199 //
1200 //
1201 ushort netmisc_calc_checksum( void * vptr, int len )
1202 {
1203         ubyte * ptr = (ubyte *)vptr;
1204         unsigned int sum1,sum2;
1205
1206         sum1 = sum2 = 0;
1207
1208         while(len--)    {
1209                 sum1 += *ptr++;
1210                 if (sum1 >= 255 ) sum1 -= 255;
1211                 sum2 += sum1;
1212         }
1213         sum2 %= 255;
1214         
1215         return (unsigned short)((sum1<<8)+ sum2);
1216 }
1217
1218
1219 // -------------------------------------------------------------------------------------------------
1220 // fill_net_addr() calculates the checksum of a block of memory.
1221 //
1222 //
1223
1224 void fill_net_addr(net_addr_t* addr, ubyte* address, ubyte* net_id, ushort port)
1225 {
1226         SDL_assert(addr != NULL);
1227         SDL_assert(address != NULL);
1228         SDL_assert(net_id != NULL);
1229
1230         addr->type = Multi_options_g.protocol;
1231         memcpy( addr->addr, address, IP_ADDRESS_LENGTH);
1232         memcpy( addr->net_id, net_id, 4);
1233         addr->port = port;
1234 }
1235
1236
1237
1238 // -------------------------------------------------------------------------------------------------
1239 // get_text_address()
1240 //
1241 //
1242
1243 char* get_text_address( char * text, const int max_textlen, ubyte * address )
1244 {
1245
1246         in_addr temp_addr;
1247
1248         switch ( Multi_options_g.protocol ) {
1249                 case NET_TCP:
1250                         memcpy(&temp_addr.s_addr, address, 4);
1251                         SDL_strlcpy( text, inet_ntoa(temp_addr), max_textlen );
1252                         break;
1253
1254                 default:
1255                         SDL_assert(0);
1256                         break;
1257
1258         } // end switch
1259
1260         return text;
1261 }
1262
1263 // non-16byte version of matrix packing
1264 // return size of packed matrix
1265 void multi_pack_orient_matrix(ubyte *data,matrix *m)
1266 {       
1267         data[16] = 0;
1268         float x1, y1, x2, y2;
1269
1270         if(m->v.rvec.xyz.z < 0) data[16] |= (1<<0);     // X
1271         if(m->v.uvec.xyz.z < 0) data[16] |= (1<<1);     // Y
1272         if(m->v.fvec.xyz.z < 0) data[16] |= (1<<2);     // V
1273         if(m->v.fvec.xyz.x < 0) data[16] |= (1<<3);     // Z
1274         if(m->v.fvec.xyz.y < 0) data[16] |= (1<<4);     // W
1275
1276         x1 = INTEL_FLOAT(m->v.rvec.xyz.x);
1277         y1 = INTEL_FLOAT(m->v.rvec.xyz.y);
1278         x2 = INTEL_FLOAT(m->v.uvec.xyz.x);
1279         y2 = INTEL_FLOAT(m->v.uvec.xyz.y);
1280
1281         memcpy(&data[0], &x1, 4);       // a
1282         memcpy(&data[4], &y1, 4);       // b
1283         memcpy(&data[8], &x2, 4);       // c
1284         memcpy(&data[12], &y2, 4);      // d
1285 }
1286
1287 // return bytes processed
1288 // non-16 byte version of unpack matrix code
1289 void multi_unpack_orient_matrix(ubyte *data,matrix *m)
1290 {
1291         float x1, y1, x2, y2;
1292
1293         memcpy(&x1, &data[0], 4);
1294         memcpy(&y1, &data[4], 4);
1295         memcpy(&x2, &data[8], 4);
1296         memcpy(&y2, &data[12],4);
1297
1298         m->v.rvec.xyz.x = INTEL_FLOAT(x1);
1299         m->v.rvec.xyz.y = INTEL_FLOAT(y1);
1300         m->v.uvec.xyz.x = INTEL_FLOAT(x2);
1301         m->v.uvec.xyz.y = INTEL_FLOAT(y2);
1302         
1303         m->v.rvec.xyz.z = fl_sqrt(fl_abs(1 - (m->v.rvec.xyz.x * m->v.rvec.xyz.x) - (m->v.rvec.xyz.y * m->v.rvec.xyz.y))); // X
1304         m->v.uvec.xyz.z = fl_sqrt(fl_abs(1 - (m->v.uvec.xyz.x * m->v.uvec.xyz.x) - (m->v.uvec.xyz.y * m->v.uvec.xyz.y))); // Y
1305         m->v.fvec.xyz.z = fl_sqrt(fl_abs(1 - (m->v.rvec.xyz.z * m->v.rvec.xyz.z) - (m->v.uvec.xyz.z * m->v.uvec.xyz.z))); // V
1306         m->v.fvec.xyz.x = fl_sqrt(fl_abs(1 - (m->v.rvec.xyz.x * m->v.rvec.xyz.x) - (m->v.uvec.xyz.x * m->v.uvec.xyz.x))); // Z
1307         m->v.fvec.xyz.y = fl_sqrt(fl_abs(1 - (m->v.rvec.xyz.y * m->v.rvec.xyz.y) - (m->v.uvec.xyz.y * m->v.uvec.xyz.y))); // W
1308
1309         m->v.rvec.xyz.z *= (data[16] & (1<<0)) ? -1.0f : 1.0f;
1310         m->v.uvec.xyz.z *= (data[16] & (1<<1)) ? -1.0f : 1.0f;
1311         m->v.fvec.xyz.z *= (data[16] & (1<<2)) ? -1.0f : 1.0f;
1312         m->v.fvec.xyz.x *= (data[16] & (1<<3)) ? -1.0f : 1.0f;
1313         m->v.fvec.xyz.y *= (data[16] & (1<<4)) ? -1.0f : 1.0f;
1314 }
1315                               
1316 void multi_do_client_warp(float flFrametime)
1317 {
1318    ship_obj *moveup;
1319         
1320    moveup = GET_FIRST(&Ship_obj_list);
1321         while(moveup!=END_OF_LIST(&Ship_obj_list)){
1322                 // do all _necessary_ ship warp in (arrival) processing
1323                 if ( Ships[Objects[moveup->objnum].instance].flags & SF_ARRIVING )      
1324                         shipfx_warpin_frame( &Objects[moveup->objnum], flFrametime );
1325                 moveup = GET_NEXT(moveup);
1326         }       
1327 }       
1328
1329 // ------------------------------------------------------------------------------------
1330 // ship status change stuff
1331
1332 int lookup_ship_status(net_player *p,int unique_id,int remove)
1333 {
1334         int idx;
1335         
1336         for(idx=0;idx<p->s_info.num_last_buttons;idx++){
1337                 if(p->s_info.last_buttons_id[idx] == unique_id){
1338                         if(remove){
1339                                 remove_ship_status_item(p,idx);
1340                                 p->s_info.num_last_buttons--;
1341                         }
1342                         return 1;
1343                 }
1344         }
1345         return 0;
1346 }
1347
1348 void remove_ship_status_item(net_player *p,int id)
1349 {
1350         int idx;
1351         for(idx=id;idx<BUTTON_INFO_SAVE_COUNT-1;idx++){
1352                 p->s_info.last_buttons[idx] = p->s_info.last_buttons[idx+1];
1353                 p->s_info.last_buttons_id[idx] = p->s_info.last_buttons_id[idx+1];
1354                 p->s_info.last_buttons_time[idx] = p->s_info.last_buttons_time[idx+1];
1355         }
1356 }
1357
1358 // 
1359 void add_net_button_info(net_player *p,button_info *bi,int unique_id)
1360 {
1361    int lookup,idx;
1362         fix earliest;
1363
1364         // if the list is full, put it in the oldest slot since it's probably a lost packet anyway
1365    if(p->s_info.num_last_buttons < BUTTON_INFO_SAVE_COUNT-1){
1366                 p->s_info.last_buttons[p->s_info.num_last_buttons] = *bi;
1367                 p->s_info.last_buttons_id[p->s_info.num_last_buttons] = unique_id;
1368                 p->s_info.last_buttons_time[p->s_info.num_last_buttons] = timer_get_fixed_seconds();
1369                 p->s_info.num_last_buttons++;
1370         } else {
1371                 earliest = 0;
1372       lookup = -1;
1373                 for(idx=0;idx<BUTTON_INFO_SAVE_COUNT;idx++){
1374                         if((p->s_info.last_buttons_time[idx] < earliest) || (earliest == 0)){
1375                                 earliest = p->s_info.last_buttons_time[idx];
1376                                 lookup = idx;
1377                         }
1378                 }
1379                 if(lookup != -1){
1380                         p->s_info.last_buttons[lookup] = *bi;
1381                         p->s_info.last_buttons_id[lookup] = unique_id;
1382                         p->s_info.last_buttons_time[lookup] = timer_get_fixed_seconds();
1383                 }
1384         }               
1385 }
1386
1387 extern int button_function_critical(int n,net_player *p = NULL);
1388 void multi_apply_ship_status(net_player *p,button_info *bi,int locally)
1389 {
1390         int i, j;
1391         Multi_button_info_ok=1;
1392         for ( i = 0; i < NUM_BUTTON_FIELDS; i++ ) {
1393                 if ( bi->status[i] == 0 )
1394                         continue;
1395                 // at least one bit is set in the status integer
1396                 for ( j = 0; j < 32; j++ ) {
1397
1398                         // check if the bit is set. If button_function returns 1 (implying the action was taken), then unset the bit
1399                         if ( bi->status[i] & (1<<j) ) {
1400             if(locally){
1401                                         if(button_function_critical(32*i + j,NULL))   // will apply to this console
1402                                                 bi->status[i] &= ~(1<<j);
1403                                 } else {
1404                                         if(button_function_critical(32*i + j,p))      // will only apply to a net-player
1405                                                 bi->status[i] &= ~(1<<j);
1406                                 }
1407                         }
1408                 }
1409         }
1410         Multi_button_info_ok=0;
1411 }
1412
1413 // send 10x a second MAX
1414 #define MULTI_SHIP_STATUS_TIME                  350
1415 int Multi_ship_status_stamp = -1;
1416 button_info Multi_ship_status_bi;
1417
1418 void multi_maybe_send_ship_status()
1419 {
1420         int idx;
1421         button_info *bi = &Player->bi;
1422
1423         // strip out noncritical button presses
1424         button_strip_noncritical_keys(bi);
1425
1426         // xor all fields into the accum button info
1427         for(idx=0; idx<NUM_BUTTON_FIELDS; idx++){               
1428                 Multi_ship_status_bi.status[idx] |= bi->status[idx];            
1429         }
1430
1431         // check timestamp
1432         if((Multi_ship_status_stamp < 0) || timestamp_elapsed_safe(Multi_ship_status_stamp, MULTI_SHIP_STATUS_TIME*2)){
1433                 int should_send = 0;
1434                 for(idx=0; idx<NUM_BUTTON_FIELDS; idx++){                       
1435                         // we have at least something to send
1436                         if(Multi_ship_status_bi.status[idx] != 0){
1437                                 should_send = 1;                        
1438                         }               
1439                 }
1440
1441                 // do we have something to send
1442                 if(should_send){
1443                         // add_net_button_info(Net_player, &Multi_ship_status_bi, Multi_button_info_id);
1444                         send_ship_status_packet(Net_player, &Multi_ship_status_bi, Multi_button_info_id++);
1445                 }
1446
1447                 // zero it out
1448                 memset(&Multi_ship_status_bi, 0, sizeof(button_info));
1449
1450                 // reset timestamp
1451                 Multi_ship_status_stamp = timestamp(MULTI_SHIP_STATUS_TIME);
1452         }
1453 }
1454
1455 void multi_subsys_update_all()
1456 {
1457         /*
1458         int idx;
1459         SDL_assert(Net_player->flags & NETINFO_FLAG_AM_MASTER);
1460         for(idx=0;idx<MAX_PLAYERS;idx++){
1461                 if((Net_players[idx].flags & NETINFO_FLAG_CONNECTED) && !psnet_same(&My_addr,&Net_players[idx].addr) && !(Net_players[idx].flags & NETINFO_FLAG_OBSERVER))
1462                         send_subsys_update_packet(&Net_players[idx]);
1463         }
1464         */
1465 }
1466
1467 int multi_find_player_by_callsign(const char *callsign)
1468 {
1469         int idx;
1470         for(idx=0;idx<MAX_PLAYERS;idx++){
1471                 if(MULTI_CONNECTED(Net_players[idx]) && (strcmp(callsign,Net_players[idx].player->callsign)==0)){
1472                         return idx;
1473                 }
1474         }
1475
1476         return -1;
1477 }
1478
1479 // if Game_current_mission_filename is a builtin multiplayer mission
1480 int multi_is_builtin_mission()
1481 {
1482         // int idx;
1483         char name[512];
1484
1485         // get the full filename
1486         memset(name,0,512);
1487         SDL_strlcpy(name, Game_current_mission_filename, SDL_arraysize(name));
1488         cf_add_ext(name, FS_MISSION_FILE_EXT);
1489
1490         // if this mission is builtin   
1491         if(game_find_builtin_mission(name) != NULL){
1492                 return 1;
1493         }
1494
1495         // not builtin
1496         return 0;
1497 }
1498
1499 // verify that the player has a valid mission file and do 1 of 3 things
1500 void server_verify_filesig(short player_id, ushort sum_sig, int length_sig)
1501 {       
1502 #if defined(MULTIPLAYER_BETA_BUILD) || defined(FS2_DEMO)
1503         net_player *pl;
1504    int player;
1505
1506         player = find_player_id(player_id);
1507         SDL_assert(player >= 0);
1508         if(player < 0){
1509                 return;
1510         }
1511         pl = &Net_players[player];
1512
1513         // all missions should be builtin, so if we don't have a match, kick the player
1514         if((sum_sig != Multi_current_file_checksum) || (length_sig != Multi_current_file_length)){
1515                 multi_kick_player(player, 0, KICK_REASON_CANT_XFER);
1516         } else {
1517                 pl->flags |= NETINFO_FLAG_MISSION_OK;
1518         }
1519 #else
1520         net_player *pl;
1521    int player;
1522         int ok; 
1523         int is_builtin;
1524    
1525         player = find_player_id(player_id);
1526         SDL_assert(player >= 0);
1527         if(player < 0){
1528                 return;
1529         }
1530         pl = &Net_players[player];
1531
1532         // if the current mission is a builtin mission, check stuff out
1533         is_builtin = multi_is_builtin_mission();
1534                 
1535         if(is_builtin){
1536                 // if the player doesn't have it, kick him
1537                 if((sum_sig == 0xffff) && (length_sig == -1)){
1538                         multi_kick_player(player, 0, KICK_REASON_CANT_XFER);
1539                 } else {
1540                         pl->flags |= NETINFO_FLAG_MISSION_OK;
1541                 }
1542
1543                 // done
1544                 return;
1545         }
1546
1547         if( (length_sig != Multi_current_file_length) || (sum_sig != Multi_current_file_checksum)){
1548                 ok = 0;
1549         } else {
1550                 ok = 1; 
1551         }
1552
1553    // in an ingame join situation
1554         if(pl->flags & NETINFO_FLAG_INGAME_JOIN){               
1555                 if(!ok){
1556                         // if the netgame settings allow in-mission file xfers
1557                         if(Netgame.options.flags & MSO_FLAG_INGAME_XFER){
1558                                 pl->s_info.ingame_join_flags |= INGAME_JOIN_FLAG_FILE_XFER;
1559                                 pl->s_info.xfer_handle = multi_xfer_send_file(pl->reliable_socket, Netgame.mission_name, CF_TYPE_MISSIONS);
1560                         }
1561                         // otherwise send him a nak and tell him to get the hell away 
1562                         else {
1563                                 send_ingame_nak(ACK_FILE_ACCEPTED,pl);
1564                         }
1565                 } else {
1566                         pl->flags |= NETINFO_FLAG_MISSION_OK;
1567                 }
1568         }
1569         // in a normal join situation
1570         else {
1571                 // if the file does not check out, send it to him
1572                 if(!ok){                        
1573                         pl->s_info.xfer_handle = multi_xfer_send_file(pl->reliable_socket, Netgame.mission_name, CF_TYPE_MISSIONS);
1574                 }
1575                 // otherwise mark him as having a valid mission
1576                 else {
1577                         pl->flags |= NETINFO_FLAG_MISSION_OK;                   
1578                 }
1579         }
1580 #endif
1581 }
1582
1583 // check to see if every client has NETINFO_FLAG_MISSION_OK
1584 int server_all_filesigs_ok()
1585 {
1586         int idx;
1587         int ok = 1;
1588         
1589         for(idx=0;idx<MAX_PLAYERS;idx++){
1590                 if(MULTI_CONNECTED(Net_players[idx]) && !(Net_players[idx].flags & NETINFO_FLAG_MISSION_OK)){
1591                         ok = 0;
1592                         break;
1593                 }
1594         }
1595
1596         return ok;
1597 }
1598
1599 void multi_untag_player_ships()
1600 {
1601         ship_obj *moveup;
1602
1603         moveup = GET_FIRST(&Ship_obj_list);
1604         while(moveup != END_OF_LIST(&Ship_obj_list)){
1605                 if(Objects[moveup->objnum].flags & OF_PLAYER_SHIP){
1606                         Objects[moveup->objnum].flags &= ~(OF_PLAYER_SHIP);
1607                         obj_set_flags( &Objects[moveup->objnum], Objects[moveup->objnum].flags | OF_COULD_BE_PLAYER );
1608                 }
1609                 moveup = GET_NEXT(moveup);
1610         }
1611 }
1612
1613 // broadcast alltime stats to everyone in the game
1614 void multi_broadcast_stats(int stats_code)
1615 {
1616         int idx;
1617
1618         // broadcast everyone's stats to everyone else
1619         for(idx=0;idx<MAX_PLAYERS;idx++){
1620                 if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_PERM_OBSERVER(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx])){                 
1621                         send_player_stats_block_packet(&Net_players[idx], stats_code);
1622                 }
1623         }                       
1624 }
1625
1626 // check to see if all players other than the local player are in a given NETPLAYER_ state
1627 // this is _EXTREMELY_ useful when doing network sequencing with the reliable sockets
1628 int multi_netplayer_state_check(int state,int ignore_standalone)
1629 {
1630         int idx;        
1631         for(idx=0;idx<MAX_PLAYERS;idx++){
1632                 if(MULTI_CONNECTED(Net_players[idx]) && (Net_player->player_id != Net_players[idx].player_id)){
1633                         if(ignore_standalone && ((Net_players[idx].flags & NETINFO_FLAG_AM_MASTER) && !(Net_players[idx].flags & NETINFO_FLAG_GAME_HOST)) ){
1634                                 continue;
1635                         }
1636
1637                         if(Net_players[idx].state != state){
1638                                 return 0;
1639                         }
1640                 }
1641         }
1642         return 1;
1643 }
1644
1645 int multi_netplayer_state_check2(int state, int state2, int ignore_standalone)
1646 {
1647         int idx;        
1648         for(idx=0;idx<MAX_PLAYERS;idx++){
1649                 if(MULTI_CONNECTED(Net_players[idx]) && (Net_player->player_id != Net_players[idx].player_id)){
1650                         if(ignore_standalone && ((Net_players[idx].flags & NETINFO_FLAG_AM_MASTER) && !(Net_players[idx].flags & NETINFO_FLAG_GAME_HOST)) ){
1651                                 continue;
1652                         }
1653
1654                         if((Net_players[idx].state != state) && (Net_players[idx].state != state2)){
1655                                 return 0;
1656                         }
1657                 }
1658         }
1659         return 1;
1660 }
1661
1662 int multi_netplayer_state_check3(int state, int state2, int state3, int ignore_standalone)
1663 {
1664         int idx;        
1665         for(idx=0;idx<MAX_PLAYERS;idx++){
1666                 if(MULTI_CONNECTED(Net_players[idx]) && (Net_player->player_id != Net_players[idx].player_id)){
1667                         if(ignore_standalone && ((Net_players[idx].flags & NETINFO_FLAG_AM_MASTER) && !(Net_players[idx].flags & NETINFO_FLAG_GAME_HOST)) ){
1668                                 continue;
1669                         }
1670
1671                         if((Net_players[idx].state != state) && (Net_players[idx].state != state2) && (Net_players[idx].state != state3)){
1672                                 return 0;
1673                         }
1674                 }
1675         }
1676         return 1;
1677 }
1678
1679 // check to see if all players other than the local player are in a given NETPLAYER_ state
1680 // this is _EXTREMELY_ useful when doing network sequencing with the reliable sockets
1681 int multi_netplayer_flag_check(int flags,int ignore_standalone)
1682 {
1683         int idx;        
1684         for(idx=0;idx<MAX_PLAYERS;idx++){
1685                 if(MULTI_CONNECTED(Net_players[idx]) && (Net_player->player_id != Net_players[idx].player_id)){
1686                         if(ignore_standalone && ((Net_players[idx].flags & NETINFO_FLAG_AM_MASTER) && !(Net_players[idx].flags & NETINFO_FLAG_GAME_HOST)) ){
1687                                 continue;
1688                         }
1689
1690                         if(!(Net_players[idx].flags & flags)){
1691                                 return 0;
1692                         }
1693                 }
1694         }
1695         return 1;
1696 }
1697
1698 // function which gets called from psnet_* code to evaluate an error received on a reliable
1699 // socket.  In general, we only want to do drastic measures if the error indicates that the client
1700 // is no longer there.
1701 void multi_eval_socket_error(PSNET_SOCKET sock, int error)
1702 {
1703         if ( error == WSAENOTSOCK ){
1704                 nprintf(("Network","Socket connection terminated and/or nonexistent, bailing..\n"));
1705
1706                 // mwa -- don't go back to main menu.  You don't want host to do this.  Maybe we can ignore it
1707                 // because of a leaving player.
1708                 return;
1709                 //gameseq_post_event(GS_EVENT_MAIN_MENU);
1710                 // Int3();                                                      // get allender -- something happened to socket connection!!!
1711         }
1712
1713         if ( (error != WSAECONNRESET) && (error != WSAECONNABORTED) && (error != WSAESHUTDOWN) ) {
1714                 nprintf(("Network", "Error %d received on reliable socket -- ignoring\n", error));
1715                 return;
1716         }
1717
1718         if(error == WSAESHUTDOWN){
1719                 nprintf(("Network","Received WSAESHUTDOWN on client socket. Cool.\n"));
1720         }
1721
1722         // mwa -- always return for now because debugging with the stuff below is a real pain.
1723         // in essence, you can't do it!
1724         //return;
1725
1726         if( Net_player->flags & NETINFO_FLAG_AM_MASTER ) {
1727                 int idx;
1728
1729                 nprintf(("Network", "pitching player because drop on reliable socket\n"));
1730                 // find the netplayer whose socket we have an error on.  Dump the player when we find him.
1731                 // NOTE : make sure not to ban him
1732                 for(idx=0;idx<MAX_PLAYERS;idx++){
1733                         if(Net_players[idx].reliable_socket == sock){
1734                                 delete_player(idx);
1735                                 return;
1736                         }
1737                 }
1738         } else {
1739                 nprintf(("Network", "Communications to server lost -- quitting game\n"));
1740                 multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_NONE, MULTI_END_ERROR_CONTACT_LOST);
1741         }
1742 }
1743
1744 // send a repair info packet with code == code to a player if his object is the one being acted upon
1745 // dest_objp is the player object (or possible player object).  source_objp is the object pointer
1746 // of the repair ship that is the source of the action.  code means what is happening -- queueing up
1747 // for repair, getting repaired, aborted, complete, etc. 
1748 void multi_maybe_send_repair_info(object *dest_objp, object *source_objp, int code )
1749 {
1750         // only send information on player objects
1751         if ( !MULTIPLAYER_MASTER )
1752                 return;
1753         
1754         SDL_assert( dest_objp->type == OBJ_SHIP );
1755         SDL_assert( dest_objp != source_objp );
1756
1757         send_repair_info_packet( dest_objp, source_objp, code );
1758 }
1759
1760 int multi_is_valid_unknown_packet(ubyte type){
1761         return (type == GAME_QUERY) || (type == JOIN) || (type == PING) || (type == PONG) || (type == GAME_INFO)
1762                 || (type == ACCEPT) || (type == GAME_ACTIVE) || (type == INGAME_NAK) || (type == DENY)
1763                 || (type == UPDATE_DESCRIPT) || (type == ACCEPT_PLAYER_DATA) ? 1 : 0;   
1764 }
1765
1766 void multi_create_standalone_object()
1767 {
1768         // now create a bullshit ship for the standalone
1769         matrix m = IDENTITY_MATRIX;
1770         vector v;
1771         int objnum, pobj_num;
1772
1773         vm_vec_zero(&v);
1774         objnum = observer_create(&m,&v);
1775         Player_obj = &Objects[objnum];
1776         obj_set_flags(Player_obj, Player_obj->flags & (~OF_COLLIDES) );
1777         //obj_set_flags(Player_obj, Player_obj->flags | OF_SHOULD_BE_DEAD);
1778         obj_set_flags(Player_obj, Player_obj->flags & (~OF_PLAYER_SHIP));
1779         Net_player->player->objnum = objnum;
1780
1781         // create the default player ship object and use that as my default virtual "ship", and make it "invisible"
1782         pobj_num = parse_create_object(&Player_start_pobject);
1783         SDL_assert(pobj_num != -1);
1784         obj_set_flags(&Objects[pobj_num],OF_PLAYER_SHIP);
1785         Objects[pobj_num].net_signature = STANDALONE_SHIP_SIG;
1786         Player_ship = &Ships[Objects[pobj_num].instance];
1787
1788         // make ship hidden from sensors so that this observer cannot target it.  Observers really have two ships
1789         // one observer, and one "Player_ship".  Observer needs to ignore the Player_ship.
1790         Player_ship->flags |= SF_HIDDEN_FROM_SENSORS;
1791         SDL_strlcpy(Player_ship->ship_name, XSTR("Standalone Ship",904), SDL_arraysize(Player_ship->ship_name));
1792         Player_ai = &Ai_info[Ships[Objects[pobj_num].instance].ai_index];               
1793
1794 }
1795
1796 int multi_message_should_broadcast(int type)
1797 {
1798         return (type == MESSAGE_ARRIVE_ENEMY) || (type == MESSAGE_BETA_ARRIVED) || 
1799                     (type == MESSAGE_GAMMA_ARRIVED) || (type == MESSAGE_HELP) || (type == MESSAGE_REINFORCEMENTS) ? 1 : 0;
1800 }
1801
1802 // active game list handling functions
1803 active_game *multi_new_active_game( void )
1804 {
1805         active_game *new_game;
1806
1807         new_game = (active_game *)malloc(sizeof(active_game));
1808         if ( new_game == NULL ) {
1809                 nprintf(("Network", "Cannot allocate space for new active game structure\n"));
1810                 return NULL;
1811         }       
1812
1813         if ( Active_game_head != NULL ) {
1814                 new_game->next = Active_game_head->next;
1815                 new_game->next->prev = new_game;
1816                 Active_game_head->next = new_game;
1817                 new_game->prev = Active_game_head;
1818         } else {
1819                 Active_game_head = new_game;
1820                 Active_game_head->next = Active_game_head->prev = Active_game_head;
1821         }
1822
1823         Active_game_count++;
1824
1825         // notify the join game screen of this new item
1826         multi_join_notify_new_game();
1827                 
1828         return new_game;
1829 }
1830
1831 active_game *multi_update_active_games(active_game *ag)
1832 {
1833         active_game *gp = NULL;
1834         active_game *stop = NULL;               
1835
1836         // see if we have a game from this address already -- if not, create one.  In either case, get a pointer
1837         // to an active_game structure
1838         if ( Active_game_head != NULL ) {       // no games on list at all
1839                 int on_list;
1840
1841                 gp = Active_game_head;
1842                 stop = Active_game_head;
1843
1844                 on_list = 0;
1845                 do {
1846                         if ( psnet_same(&gp->server_addr, &ag->server_addr) /*&& (gp->game.security == game->security)*/ ) {
1847                                 on_list = 1;
1848                                 break;
1849                         }
1850                         gp = gp->next;
1851                 } while (gp != stop);
1852
1853                 // insert in the list
1854                 if (!on_list){
1855                         gp = multi_new_active_game();
1856                         // gp->ping_time = -1.0f;                       
1857
1858                         // copy in the game information
1859                         memcpy(&gp->server_addr,&ag->server_addr,sizeof(net_addr_t));
1860                         SDL_strlcpy(gp->name, ag->name, SDL_arraysize(gp->name));
1861                         SDL_strlcpy(gp->mission_name, ag->mission_name, SDL_arraysize(gp->mission_name));
1862                         SDL_strlcpy(gp->title, ag->title, SDL_arraysize(gp->title));
1863                         gp->num_players = ag->num_players;
1864                         gp->flags = ag->flags;
1865                         
1866                         // ping him
1867                         /*
1868                         gp->ping_start = timer_get_fixed_seconds();
1869                         gp->ping_end = -1;
1870                         send_ping(&gp->server_addr);                    
1871                         */
1872                         multi_ping_reset(&gp->ping);
1873                         multi_ping_send(&gp->server_addr,&gp->ping);
1874                 }
1875                 // otherwise update the netgame info we have for this guy
1876                 else {                          
1877                         memset(gp->name,0,MAX_GAMENAME_LEN+1);
1878                         SDL_strlcpy(gp->name, ag->name, SDL_arraysize(gp->name));
1879                         memset(gp->mission_name,0,NAME_LENGTH+1);
1880                         SDL_strlcpy(gp->mission_name, ag->mission_name, SDL_arraysize(gp->mission_name));
1881                         memset(gp->title,0,NAME_LENGTH+1);
1882                         SDL_strlcpy(gp->title, ag->title, SDL_arraysize(gp->title));
1883                         gp->num_players = ag->num_players;
1884                         gp->flags = ag->flags;                  
1885                 }
1886         } else {
1887                 gp = multi_new_active_game();
1888                 // gp->ping_time = -1.0f;               
1889
1890                 // copy in the game information 
1891                 memcpy(&gp->server_addr,&ag->server_addr,sizeof(net_addr_t));
1892                 SDL_strlcpy(gp->name, ag->name, SDL_arraysize(gp->name));
1893                 SDL_strlcpy(gp->mission_name, ag->mission_name, SDL_arraysize(gp->mission_name));
1894                 SDL_strlcpy(gp->title, ag->title, SDL_arraysize(gp->title));
1895                 gp->num_players = ag->num_players;
1896                 gp->flags = ag->flags;
1897                 
1898                 // ping him
1899                 // gp->ping_start = timer_get_fixed_seconds();
1900                 // gp->ping_end = -1;
1901                 // send_ping(&gp->server_addr);
1902                 multi_ping_reset(&gp->ping);
1903                 multi_ping_send(&gp->server_addr,&gp->ping);
1904         }               
1905
1906         // don't do anything if we don't have a game entry
1907         if(gp == NULL){
1908                 return NULL;
1909         }
1910         
1911         // update the last time we heard from him
1912         if((Multi_options_g.protocol == NET_TCP) && (Net_player->p_info.options.flags & MLO_FLAG_LOCAL_BROADCAST)){
1913                 gp->heard_from_timer = timestamp(MULTI_JOIN_SERVER_TIMEOUT_LOCAL);
1914         } else {
1915                 gp->heard_from_timer = timestamp(MULTI_JOIN_SERVER_TIMEOUT);
1916         }
1917
1918         return gp;
1919 }
1920
1921 void multi_free_active_games()
1922 {
1923         active_game *moveup,*backup;    
1924
1925         moveup = Active_game_head;
1926         backup = NULL;
1927         if(moveup != NULL){
1928                 do {                    
1929                         backup = moveup;
1930                         moveup = moveup->next;
1931                         
1932                         free(backup);
1933                         backup = NULL;
1934                 } while(moveup != Active_game_head);
1935                 Active_game_head = NULL;
1936         }       
1937         Active_game_count = 0;
1938 }
1939
1940 server_item *multi_new_server_item( void )
1941 {
1942         server_item *new_game;
1943
1944         new_game = (server_item *)malloc(sizeof(server_item));
1945         if ( new_game == NULL ) {
1946                 nprintf(("Network", "Cannot allocate space for new server_item structure\n"));
1947                 return NULL;
1948         }
1949
1950         if ( Game_server_head != NULL ) {
1951                 new_game->next = Game_server_head->next;
1952                 new_game->next->prev = new_game;
1953                 Game_server_head->next = new_game;
1954                 new_game->prev = Game_server_head;
1955         } else {
1956                 Game_server_head = new_game;
1957                 Game_server_head->next = Game_server_head->prev = Game_server_head;
1958         }
1959                 
1960         return new_game;
1961 }
1962
1963 void multi_free_server_list()
1964 {
1965         server_item *moveup,*backup;    
1966
1967         moveup = Game_server_head;
1968         backup = NULL;
1969         if(moveup != NULL){
1970                 do {                    
1971                         backup = moveup;
1972                         moveup = moveup->next;
1973                         
1974                         free(backup);
1975                         backup = NULL;
1976                 } while(moveup != Game_server_head);
1977                 Game_server_head = NULL;
1978         }       
1979 }
1980
1981 int multi_num_players()
1982 {
1983         int idx,count;
1984
1985         // count the players who are actively connected
1986         count = 0;
1987         for(idx=0;idx<MAX_PLAYERS;idx++){
1988                 // count all connected players except the standalone server (if any)
1989                 if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx]) && !MULTI_PERM_OBSERVER(Net_players[idx])){                 
1990                         count++;
1991                 }
1992         }
1993
1994         return count;
1995 }
1996
1997 int multi_num_observers()
1998 {
1999         int idx,count;
2000
2001         // count the players who are actively connected
2002         count = 0;
2003         for(idx=0;idx<MAX_PLAYERS;idx++){
2004                 // count all connected players except the standalone server (if any)
2005                 if(MULTI_CONNECTED(Net_players[idx]) && MULTI_PERM_OBSERVER(Net_players[idx])){
2006                         count++;
2007                 }
2008         }
2009
2010         return count;
2011
2012 }
2013
2014 int multi_num_connections()
2015 {
2016         int idx,count;
2017
2018         // count the players who are actively connected
2019         count = 0;
2020         for(idx=0;idx<MAX_PLAYERS;idx++){
2021                 // count all connected players except the standalone server (if any)
2022                 if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx])){
2023                         count++;
2024                 }
2025         }
2026
2027         return count;
2028 }
2029
2030 int multi_can_message(net_player *p)
2031 {
2032         int max_rank;
2033         ship *sp;
2034
2035         // if the player is an observer of any kind, he cannot message
2036         if(p->flags & NETINFO_FLAG_OBSERVER){
2037                 return 0;
2038         }
2039
2040         switch(Netgame.options.squad_set){
2041         // only those of the highest rank can message
2042         case MSO_SQUAD_RANK:
2043                 max_rank = multi_get_highest_rank();
2044                 if(p->player->stats.rank < max_rank){
2045                         return 0;
2046                 }
2047                 break;
2048
2049         // only wing/team leaders can message
2050         case MSO_SQUAD_LEADER:
2051                 // if the player has an invalid object #
2052                 if(p->player->objnum < 0){
2053                         return 0;
2054                 }
2055
2056                 // check to see if he's a wingleader
2057                 sp = &Ships[Objects[p->player->objnum].instance];               
2058                 if(SDL_strcasecmp(sp->ship_name,NOX("alpha 1")) && SDL_strcasecmp(sp->ship_name,NOX("beta 1")) && SDL_strcasecmp(sp->ship_name,NOX("gamma 1")) && SDL_strcasecmp(sp->ship_name,NOX("zeta 1")) ){
2059                         return 0;
2060                 }       
2061                 break;
2062
2063         // anyone can end message
2064         case MSO_SQUAD_ANY:
2065                 break;
2066
2067         // only the host can message
2068         case MSO_SQUAD_HOST:
2069                 if(!(p->flags & NETINFO_FLAG_GAME_HOST)){
2070                         return 0;
2071                 }
2072                 break;
2073         }       
2074         
2075         return 1;
2076 }
2077
2078 int multi_can_end_mission(net_player *p)
2079 {
2080         int max_rank;
2081         ship *sp;       
2082
2083         // the host can _always_ unpause a game
2084         if(p->flags & NETINFO_FLAG_GAME_HOST){
2085                 return 1;
2086         }
2087
2088         switch(Netgame.options.endgame_set){
2089         // only those of the highest rank can end the mission
2090         case MSO_END_RANK:
2091                 max_rank = multi_get_highest_rank();
2092                 if(p->player->stats.rank < max_rank){
2093                         return 0;
2094                 }
2095                 break;
2096
2097         // only wing/team leaders can end the mission
2098         case MSO_END_LEADER:
2099                 // if the player has an invalid object #
2100                 if(p->player->objnum < 0){
2101                         return 0;
2102                 }
2103
2104                 // check to see if he's a wingleader
2105                 sp = &Ships[Objects[p->player->objnum].instance];
2106                 if(SDL_strcasecmp(sp->ship_name,NOX("alpha 1")) && SDL_strcasecmp(sp->ship_name,NOX("beta 1")) && SDL_strcasecmp(sp->ship_name,NOX("gamma 1")) && SDL_strcasecmp(sp->ship_name,NOX("zeta 1")) ){
2107                         return 0;
2108                 }       
2109                 break;
2110
2111         // anyone can end the mission
2112         case MSO_END_ANY:
2113                 break;
2114
2115         // only the host can end the mission
2116         case MSO_END_HOST:
2117                 if(!(p->flags & NETINFO_FLAG_GAME_HOST)){
2118                         return 0;
2119                 }
2120                 break;
2121         }       
2122         
2123         return 1;
2124 }
2125
2126 int multi_eval_join_request(join_request *jr,net_addr_t *addr)
2127 {       
2128         int team0_avail,team1_avail;
2129
2130         // if the server versions are incompatible
2131         if(jr->version < MULTI_FS_SERVER_COMPATIBLE_VERSION){
2132                 return JOIN_DENY_JR_BAD_VERSION;
2133         }
2134
2135         // check to make sure we are otherwise in a state to accept
2136         if(Netgame.game_state != NETGAME_STATE_FORMING){
2137                 return JOIN_DENY_JR_STATE;
2138         }
2139         
2140         // the standalone has some oddball situations which we must handle seperately
2141         if(Game_mode & GM_STANDALONE_SERVER){           
2142                 // if this is the first connection, he will be the host so we must always accept him
2143                 if(multi_num_players() == 0){
2144                         // check to see if this is a tracker game, and if so make sure this is a valid MT player        
2145                         // we probably eventually want to make sure he's not passing us a fake tracker id#
2146                         if (MULTI_IS_TRACKER_GAME) {
2147                                 if(jr->tracker_id < 0){
2148                                         return JOIN_DENY_JR_TRACKER_INVAL;
2149                                 }                       
2150                         }                       
2151
2152                         // if we're password protected          
2153                         if(std_is_host_passwd() && strcmp(jr->passwd, Multi_options_g.std_passwd)){
2154                                 return JOIN_DENY_JR_PASSWD;
2155                         }
2156                                 
2157                         // don't allow the host to join as an observer
2158                         if(jr->flags & JOIN_FLAG_AS_OBSERVER){
2159                                 return JOIN_DENY_JR_NOOBS;
2160                         } else {
2161                                 return -1;
2162                         }
2163                 }               
2164         }
2165
2166         // first off check to see if we're violating any of our max players/observers/connections boundaries    
2167                 // if we've already got the full 16 (MAX_PLAYERS) connections - yow
2168         if( (multi_num_connections() >= MULTI_MAX_CONNECTIONS) ||                       
2169                 // if we're full of observers and this guy wants to be an observer
2170                 ((multi_num_observers() >= MAX_OBSERVERS) && (jr->flags & JOIN_FLAG_AS_OBSERVER)) ||
2171                 // if we're up to MULTI_MAX_PLAYERS-1 and we're on the standalone
2172                 ((multi_num_players() >= (MULTI_MAX_PLAYERS - 1)) && (Game_mode & GM_STANDALONE_SERVER)) ||
2173                 // if we're up to MULTI_MAX_PLAYERS
2174                 (multi_num_players() >= MULTI_MAX_PLAYERS) ||
2175                 // if the max players for a standalone was set
2176                 ((Multi_options_g.std_max_players != -1) && (multi_num_players() >= Multi_options_g.std_max_players)) ){
2177
2178                 // we're full buddy - sorry
2179                 return JOIN_DENY_JR_FULL;
2180         }
2181         
2182         // check to see if this is a tracker game, and if so make sure this is a valid MT player        
2183         // we probably eventually want to make sure he's not passing us a fake tracker id#
2184         if (MULTI_IS_TRACKER_GAME) {
2185                 if(jr->tracker_id < 0){
2186                         return JOIN_DENY_JR_TRACKER_INVAL;
2187                 }                       
2188         }
2189
2190         // check to see if the player is trying to ingame join in a closed game
2191         if(MULTI_IN_MISSION && (Netgame.mode == NG_MODE_CLOSED)){
2192                 return JOIN_DENY_JR_CLOSED;
2193         }       
2194
2195         // check to see if the player has passed a valid password in a password protected game
2196         if((Netgame.mode == NG_MODE_PASSWORD) && strcmp(Netgame.passwd,jr->passwd)){
2197                 return JOIN_DENY_JR_PASSWD;
2198         }
2199
2200         // check to see if the netgame is forming and is temporarily marked as closed
2201         if((Netgame.game_state == NETGAME_STATE_FORMING) && (Netgame.flags & NG_FLAG_TEMP_CLOSED)){
2202                 return JOIN_DENY_JR_TEMP_CLOSED;
2203         }       
2204
2205         // check to make sure he meets the rank requirement
2206         if((Netgame.mode == NG_MODE_RANK_ABOVE) && (jr->player_rank < Netgame.rank_base)){
2207                 return JOIN_DENY_JR_RANK_LOW;
2208         }
2209
2210         // check to make sure he meets the rank requirement
2211         if((Netgame.mode == NG_MODE_RANK_BELOW) && (jr->player_rank > Netgame.rank_base)){
2212                 return JOIN_DENY_JR_RANK_HIGH;
2213         }       
2214
2215         // can't ingame join a non-dogfight game
2216         if((Netgame.game_state != NETGAME_STATE_FORMING) && !(Netgame.type_flags & NG_TYPE_DOGFIGHT)){
2217                 return JOIN_DENY_JR_TYPE;
2218         }       
2219
2220         // if the player was banned by the standalone
2221         if((Game_mode & GM_STANDALONE_SERVER) && std_player_is_banned(jr->callsign)){
2222                 return JOIN_DENY_JR_BANNED;
2223         }
2224
2225         // if the game is in-mission, make sure there are ships available
2226         if(MULTI_IN_MISSION && !(jr->flags & JOIN_FLAG_AS_OBSERVER)){
2227                 team0_avail = 0;
2228                 team1_avail = 0;
2229                 multi_player_ships_available(&team0_avail,&team1_avail);
2230
2231                 // if there are no ships available on either team
2232                 if((team0_avail == 0) && (team1_avail == 0)){
2233                         return JOIN_DENY_JR_FULL;
2234                 }
2235         }
2236
2237         // if my ingame joining flag is set, then deny since we only allow one ingame joiner at a time
2238         if ( Netgame.flags & NG_FLAG_INGAME_JOINING ){
2239                 return JOIN_DENY_JR_INGAME_JOIN;
2240         }
2241
2242         // check to make sure the game is not full (of observers, or players, as appropriate)
2243         if((jr->flags & JOIN_FLAG_AS_OBSERVER)){
2244                 if((multi_num_observers() + 1) > Netgame.options.max_observers){
2245                         return JOIN_DENY_JR_FULL;
2246                 }
2247         } 
2248
2249         // if the netgame is restricted or is team vs. team
2250         if((Netgame.mode == NG_MODE_RESTRICTED) || (Netgame.type_flags & NG_TYPE_TEAM)){
2251                 // ingame, we must query the host to see if this guy is accepted
2252                 if(MULTI_IN_MISSION){
2253                         return JOIN_QUERY_RESTRICTED;
2254                 }               
2255         }               
2256         
2257         // check to make sure this player hasn't been kick/banned
2258         if(multi_kick_is_banned(addr)){
2259                 return JOIN_DENY_JR_BANNED;
2260         }
2261
2262         // check to make sure this player doesn't already exist
2263         if ( find_player(addr) >= 0 ) {
2264                 return JOIN_DENY_JR_DUP;
2265         }
2266
2267         return -1;
2268 }
2269
2270 // called by any machine (client, host, server, standalone, etc), to begin warping out all player objects
2271 void multi_warpout_all_players()
2272 {
2273         int idx;
2274
2275         // i'f i'm already marked as warping out, don't do this again
2276         if(Net_player->flags & NETINFO_FLAG_WARPING_OUT){
2277                 return;
2278         }
2279
2280         // stop my afterburners
2281         if((Player_obj != NULL) && (Player_obj->type == OBJ_SHIP) && !(Game_mode & GM_STANDALONE_SERVER)){
2282                 afterburners_stop( Player_obj, 1 );
2283         }
2284
2285         // traverse through each player
2286         for(idx=0;idx<MAX_PLAYERS;idx++) {
2287                 object *objp;
2288
2289                 // only warpout player _ships_ which are not mine
2290                 if(MULTI_CONNECTED(Net_players[idx]) && (Net_player != &Net_players[idx]) && (Objects[Net_players[idx].player->objnum].type == OBJ_SHIP)){
2291
2292                         objp = &Objects[Net_players[idx].player->objnum];
2293
2294                         obj_set_flags( objp, objp->flags & (~OF_COLLIDES) );
2295                         shipfx_warpout_start( objp );
2296                 }
2297         }
2298
2299         // now, mark ourselves as needing to warp out
2300         Net_player->flags |= NETINFO_FLAG_WARPING_OUT;
2301         
2302         // if we're an observer, or we're respawning, or we can't warp out. so just jump into the debrief state
2303         if((Net_player->flags & NETINFO_FLAG_OBSERVER) || (Net_player->flags & NETINFO_FLAG_RESPAWNING) ||
2304                 (Net_player->flags & NETINFO_FLAG_OBSERVER) || ((Player_obj->type == OBJ_SHIP) && (Player_ship->flags & SF_CANNOT_WARP)) ){             
2305
2306                 if(Netgame.type_flags & NG_TYPE_DOGFIGHT){
2307                         gameseq_post_event(GS_EVENT_MULTI_DOGFIGHT_DEBRIEF);
2308                 } else {
2309                         gameseq_post_event(GS_EVENT_DEBRIEF);           
2310                 }
2311         }
2312         // if we're a ship, then begin the warpout process
2313         else {
2314                 // turn off collision detection for my ship
2315                 obj_set_flags(Player_obj, Player_obj->flags & (~OF_COLLIDES) );
2316                 gameseq_post_event(GS_EVENT_PLAYER_WARPOUT_START_FORCED);                               
2317         }
2318 }
2319
2320 // determine the highest rank of any of the players in the game
2321 int multi_get_highest_rank()
2322 {
2323         int idx;
2324         int max_rank = -1;
2325         
2326         // go through all the players
2327         for(idx=0;idx<MAX_PLAYERS;idx++){
2328                 if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx]) && !MULTI_PERM_OBSERVER(Net_players[idx]) && (Net_players[idx].player->stats.rank > max_rank)){
2329                         max_rank = Net_players[idx].player->stats.rank;
2330                 }
2331         }
2332
2333         // return what we found
2334         return max_rank;                        
2335 }
2336
2337 // called on the machine of the player who hit alt+j
2338 void multi_handle_end_mission_request()
2339 {
2340         int idx;
2341         
2342         // all clients should send the request to the server. no exceptions
2343         if(!(Net_player->flags & NETINFO_FLAG_AM_MASTER)){
2344                 send_endgame_packet();
2345         }
2346         // the server of the game does some further processing
2347         else {
2348                 ml_string("Server received endgame request, proceeding...");                    
2349
2350                 // first we should toss all ingame joiners
2351                 for(idx=0;idx<MAX_PLAYERS;idx++){
2352                         if(MULTI_CONNECTED(Net_players[idx]) && (Net_players[idx].flags & NETINFO_FLAG_INGAME_JOIN)){
2353                                 multi_kick_player(idx,0,KICK_REASON_INGAME_ENDED);
2354                         }
2355                 }               
2356                                 
2357                 // send the endgame packet to all clients, who will act on it immediately
2358                 send_endgame_packet();                  
2359                 Netgame.game_state = NETGAME_STATE_ENDGAME;             
2360                 send_netgame_update_packet();                                   
2361                 
2362                 if(Game_mode & GM_STANDALONE_SERVER){                                   
2363                         // move to the standalone postgame (which is where we'll handle stats packets, etc)
2364                         gameseq_post_event(GS_EVENT_STANDALONE_POSTGAME);
2365                 }
2366
2367                 // begin the warpout process for all players and myself
2368                 multi_warpout_all_players();
2369         } 
2370 }
2371
2372 // called to handle any special cases where a player is in some submemu when the game is ended 
2373 void multi_handle_state_special()
2374 {
2375         int stack_depth,current_depth;  
2376         
2377         // first off - kill any active popups
2378         popup_kill_any_active();
2379
2380         // kill any popupdeads
2381         if(popupdead_is_active()){
2382                 popupdead_close();
2383         }
2384
2385         // kill off the pilot info popup if its active
2386         if(multi_pinfo_popup_active()){
2387                 multi_pinfo_popup_kill();
2388         }
2389
2390         // now do any special processing for being in states other then the gameplay states
2391         stack_depth = gameseq_get_depth();
2392         
2393         // if we're not pushed on top of any states, do any special state case handling here
2394         if(stack_depth == 0){           
2395                 // currently there are no special cases, so return
2396                 return;
2397         } 
2398         // if we are pushed on any states, post events to pop them off one by one
2399         else {
2400                 current_depth = stack_depth;
2401                 do {            
2402                         switch(gameseq_get_state(stack_depth - current_depth)){                         
2403                         // the hotkey screen
2404                         case GS_STATE_HOTKEY_SCREEN :           
2405                                 mission_hotkey_exit();
2406                                 Game_do_state_should_skip = 1;
2407                                 break;
2408                         // the options menu
2409                         case GS_STATE_OPTIONS_MENU:             
2410                                 options_cancel_exit();
2411                                 Game_do_state_should_skip = 1;
2412                                 break;
2413                         // the hud config (1 deeper in the options menu)
2414                         case GS_STATE_HUD_CONFIG:
2415                                 hud_config_cancel();                    
2416                                 Game_do_state_should_skip = 1;
2417                                 break;
2418                         // controls config (1 deeper than the options menu)
2419                         case GS_STATE_CONTROL_CONFIG:
2420                                 control_config_cancel_exit();   
2421                                 Game_do_state_should_skip = 1;
2422                                 break;
2423                         // mission goals screen
2424                         case GS_STATE_SHOW_GOALS:
2425                                 mission_goal_exit();
2426                                 Game_do_state_should_skip = 1;
2427                                 break;                  
2428                         // mission log scrollback
2429                         case GS_STATE_MISSION_LOG_SCROLLBACK:
2430                                 hud_scrollback_exit();
2431                                 Game_do_state_should_skip = 1;
2432                                 break;
2433                         // pause screen
2434                         case GS_STATE_MULTI_PAUSED:
2435                                 gameseq_pop_state();
2436                                 Game_do_state_should_skip = 1;
2437                                 break;
2438                         }
2439
2440                         // next pushed state
2441                         current_depth--;
2442                 } while(current_depth > 0);     
2443         }
2444 }
2445
2446 // called by the file xfer subsytem when we start receiving a file
2447 void multi_file_xfer_notify(int handle)
2448 {
2449         char *filename;
2450         int cf_type;
2451         int is_mission = 0;     
2452
2453         // get the filename of the file we are receiving
2454         filename = NULL;
2455         filename = multi_xfer_get_filename(handle);
2456
2457         // something is messed up
2458         if(filename == NULL){
2459                 return;
2460         }
2461
2462         // convert the filename to all lowercase
2463         SDL_strlwr(filename);
2464
2465         // if this is a mission file
2466         is_mission = (strstr(filename, FS_MISSION_FILE_EXT) != NULL);
2467         
2468         // determine where its going to go
2469         if(is_mission){
2470                 cf_type = Net_player->p_info.options.flags & MLO_FLAG_XFER_MULTIDATA ? CF_TYPE_MULTI_CACHE : CF_TYPE_MISSIONS;
2471         } else {
2472                 cf_type = CF_TYPE_MULTI_CACHE;
2473         }
2474
2475         // QUICK FIX
2476         // check to see if the file is read-only                        
2477         if((strlen(filename) > 0) && !cf_access(filename, cf_type, 00) && (cf_access(filename, cf_type, 02) == -1)){    
2478                 multi_xfer_xor_flags(handle, MULTI_XFER_FLAG_REJECT);
2479
2480                 Net_player->flags &= ~(NETINFO_FLAG_DO_NETWORKING);
2481                 popup(PF_USE_AFFIRMATIVE_ICON, 1, XSTR("&Ok", 713), XSTR("An outdated copy of this file exists, but it cannot be overwritten by the server because it is set to be read-only. Change the permissions on this file next time.", 714));           
2482                 multi_quit_game(PROMPT_NONE);           
2483                 return;
2484         }       
2485
2486         // if the incoming filename is a freespace file, set my netplayer state to be "file xfer"
2487         if(is_mission){
2488                 // we'd better not be xferring a file right now
2489                 SDL_assert(Net_player->s_info.xfer_handle == -1);
2490
2491                 // force into the multidata directory
2492                 multi_xfer_handle_force_dir(handle, cf_type);           
2493         
2494                 // set my xfer handle
2495                 Net_player->s_info.xfer_handle = handle;
2496                 
2497                 Net_player->state = NETPLAYER_STATE_MISSION_XFER;
2498                 send_netplayer_update_packet();
2499         }
2500         // otherwise always hand it off to the multi_data system
2501         else {
2502                 multi_data_handle_incoming(handle);             
2503         }
2504 }
2505
2506 // return the lag/disconnected status of the game
2507 #define MULTI_LAG_VAL           400
2508 int multi_query_lag_status()
2509 {
2510         // -1 == not lagged, 0 == lagged, 1 == disconnected
2511
2512         // if I'm the server of the game, I can't be lagged
2513         if(Net_player->flags & NETINFO_FLAG_AM_MASTER){
2514                 return -1;
2515         }
2516         
2517         // if we've been disconnected for some reason or another
2518         if(multi_client_server_dead()){
2519                 return 1;
2520         }
2521
2522         // if our ping time to the server is over a certain time
2523         if(Netgame.server->s_info.ping.ping_avg >= MULTI_LAG_VAL){
2524                 return 0;
2525         } 
2526
2527         // not lagged
2528         return -1;
2529 }
2530
2531 // process a valid join request
2532 void multi_process_valid_join_request(join_request *jr, net_addr_t *who_from, int ingame_join_team)
2533 {
2534         int net_player_num,player_num;
2535         short id_num;
2536         
2537         // create netplayer and player objects for this guy
2538         net_player_num = multi_find_open_netplayer_slot();
2539         player_num = multi_find_open_player_slot();
2540         id_num = multi_get_new_id();
2541         SDL_assert((net_player_num != -1) && (player_num != -1));                       
2542
2543         // if he is requesting to join as an observer
2544         if(jr->flags & JOIN_FLAG_AS_OBSERVER){                  
2545                 // create the (permanently) observer player
2546                 if(!multi_obs_create_player(net_player_num, jr->callsign, who_from, &Players[player_num])){
2547                         Int3();
2548                 }
2549
2550                 // copy his pilot image filename
2551                 if(strlen(jr->image_filename) > 0){
2552                         SDL_strlcpy(Net_players[net_player_num].player->image_filename, jr->image_filename, MAX_FILENAME_LEN);
2553                 } else {
2554                         SDL_strlcpy(Net_players[net_player_num].player->image_filename, "", MAX_FILENAME_LEN);
2555                 }
2556
2557                 // copy his pilot squad filename
2558 #ifndef MAKE_FS1
2559                 Net_players[net_player_num].player->insignia_texture = -1;
2560                 player_set_squad_bitmap(Net_players[net_player_num].player, jr->squad_filename);                
2561 #endif
2562
2563                 // clear his multi_data info
2564                 multi_data_handle_join(net_player_num);
2565
2566                 // set some extra flags for him as appropriate
2567                 if(MULTI_IN_MISSION){
2568                         Net_players[net_player_num].flags |= NETINFO_FLAG_INGAME_JOIN;                  
2569                 }
2570
2571                 Net_players[net_player_num].flags |= NETINFO_FLAG_CONNECTED;            
2572                 Net_players[net_player_num].player_id = id_num;
2573                 Net_players[net_player_num].tracker_player_id = jr->tracker_id;
2574
2575                 // store pxo info
2576 #ifndef MAKE_FS1
2577                 if(strlen(jr->pxo_squad_name) > 0){
2578                         SDL_strlcpy(Net_players[net_player_num].p_info.pxo_squad_name, jr->pxo_squad_name, LOGIN_LEN);
2579                 } else {
2580                         SDL_strlcpy(Net_players[net_player_num].p_info.pxo_squad_name, "", LOGIN_LEN);
2581                 }               
2582 #endif
2583
2584                 // if he's using hacked data
2585                 if(jr->flags & JOIN_FLAG_HAXOR){
2586                         Net_players[net_player_num].flags |= NETINFO_FLAG_HAXOR;
2587                 }
2588
2589                 // set his reliable connect time
2590                 Net_players[net_player_num].s_info.reliable_connect_time = time(NULL);
2591
2592                 // send the accept packet here
2593                 send_accept_packet(net_player_num, (Net_players[net_player_num].flags & NETINFO_FLAG_INGAME_JOIN) ? ACCEPT_OBSERVER | ACCEPT_INGAME : ACCEPT_OBSERVER);
2594         } else {
2595                 // create the player object     
2596                 if(!multi_create_player( net_player_num, &Players[player_num], jr->callsign, who_from, -1, id_num )){
2597                         Int3();
2598                 }
2599                 
2600                 // copy his pilot image filename
2601                 if(strlen(jr->image_filename) > 0){
2602                         SDL_strlcpy(Net_players[net_player_num].player->image_filename, jr->image_filename, MAX_FILENAME_LEN);
2603                 } else {
2604                         SDL_strlcpy(Net_players[net_player_num].player->image_filename, "", MAX_FILENAME_LEN);
2605                 }
2606
2607                 // copy his pilot squad filename                
2608 #ifndef MAKE_FS1
2609                 Net_players[net_player_num].player->insignia_texture = -1;
2610                 player_set_squad_bitmap(Net_players[net_player_num].player, jr->squad_filename);                                
2611 #endif
2612
2613                 // clear his multi_data info
2614                 multi_data_handle_join(net_player_num);
2615
2616                 // mark him as being connected
2617                 Net_players[net_player_num].flags |= NETINFO_FLAG_CONNECTED;
2618                                                 
2619                 // set his tracker id correctly
2620                 Net_players[net_player_num].tracker_player_id = jr->tracker_id;                         
2621
2622                 // set his player id#
2623                 Net_players[net_player_num].player_id = id_num;
2624
2625                 // store pxo info
2626 #ifndef MAKE_FS1
2627                 if(strlen(jr->pxo_squad_name) > 0){
2628                         SDL_strlcpy(Net_players[net_player_num].p_info.pxo_squad_name, jr->pxo_squad_name, LOGIN_LEN);
2629                 } else {
2630                         SDL_strlcpy(Net_players[net_player_num].p_info.pxo_squad_name, "", LOGIN_LEN);
2631                 }               
2632 #endif
2633
2634                 // if he's using hacked data
2635                 if(jr->flags & JOIN_FLAG_HAXOR){
2636                         Net_players[net_player_num].flags |= NETINFO_FLAG_HAXOR;
2637                 }
2638                 
2639                 // flag him appropriately if he's doing an ingame join
2640                 if(MULTI_IN_MISSION){
2641                         Int3();
2642                         Net_players[net_player_num].flags |= NETINFO_FLAG_INGAME_JOIN;
2643                         Net_players[net_player_num].s_info.ingame_join_flags = 0;
2644                 }               
2645
2646                 // set his reliable connect time
2647                 Net_players[net_player_num].s_info.reliable_connect_time = time(NULL);
2648
2649                 // if he's joining as a host (on the standalone)
2650                 if(Net_players[net_player_num].flags & NETINFO_FLAG_GAME_HOST){
2651                         send_accept_packet(net_player_num, ACCEPT_HOST);
2652
2653                         Netgame.host = &Net_players[net_player_num];
2654
2655                         // set the game and player states appropriately
2656                         Netgame.game_state = NETGAME_STATE_STD_HOST_SETUP;                      
2657                 }
2658                 // if he's joining ingame
2659                 else if(Net_players[net_player_num].flags & NETINFO_FLAG_INGAME_JOIN){
2660                         // if we're in team vs. team mode
2661                         if(Netgame.type_flags & NG_TYPE_TEAM){
2662                                 SDL_assert(ingame_join_team != -1);
2663
2664                                 Net_players[net_player_num].p_info.team = ingame_join_team;
2665                         }
2666
2667                         send_accept_packet(net_player_num, ACCEPT_INGAME, ingame_join_team);
2668
2669                         // set his last full update time for updating him on ingame join ships
2670                         Net_players[net_player_num].s_info.last_full_update_time = timestamp(INGAME_SHIP_UPDATE_TIME);
2671                 } 
2672                 // if he's joining as an otherwise ordinary client
2673                 else {
2674                         send_accept_packet(net_player_num, ACCEPT_CLIENT);
2675                 }
2676         }
2677
2678         // set my ingame joining flag if the new guy is joining ingame
2679         if ( Net_players[net_player_num].flags & NETINFO_FLAG_INGAME_JOIN ){
2680                 Int3();
2681                 Netgame.flags |= NG_FLAG_INGAME_JOINING;
2682         }       
2683         
2684         // copy in his options
2685         memcpy(&Net_players[net_player_num].p_info.options, &jr->player_options, sizeof(multi_local_options));
2686
2687         // if on the standalone, then do any necessary gui updating
2688         if(Game_mode & GM_STANDALONE_SERVER) {          
2689                 std_add_player(&Net_players[net_player_num]);
2690                 std_connect_set_connect_count();
2691                 std_connect_set_host_connect_status();
2692         } else {
2693                 // let the create game screen know someone has joined
2694                 if(gameseq_get_state() == GS_STATE_MULTI_HOST_SETUP){
2695                         multi_create_handle_join(&Net_players[net_player_num]);
2696                 }
2697         }
2698
2699         extern int Multi_client_update_times[MAX_PLAYERS];
2700         Multi_client_update_times[net_player_num] = -1;
2701
2702         // notify datarate
2703         multi_rate_reset(net_player_num);
2704 }
2705
2706 // if a player is trying to join a restricted game, evaluate the keypress (accept or not, etc)
2707 int multi_process_restricted_keys(int k)
2708 {       
2709         int key1=-1,key2=-1;    //JAS: Get rid of optimized warning
2710         int team_val;
2711         
2712         // if the query timestamp is not set, don't do anything
2713         if(Multi_restr_query_timestamp == -1){
2714                 return 0;
2715         }
2716
2717         // determine what keys to look for based upon the mode we're in
2718         switch(Multi_join_restr_mode){
2719         // normal restricted join, Y or N
2720         case MULTI_JOIN_RESTR_MODE_1:
2721                 key1 = SDLK_y;
2722                 key2 = SDLK_n;
2723                 break;
2724
2725         // team vs team, team 0 only has ships
2726         case MULTI_JOIN_RESTR_MODE_2:
2727                 key1 = SDLK_y;
2728                 key2 = SDLK_n;
2729                 break;
2730
2731         // team vs team, team 1 only has ships          
2732         case MULTI_JOIN_RESTR_MODE_3:
2733                 key1 = SDLK_y;
2734                 key2 = SDLK_n;
2735                 break;
2736
2737         // team vs team, both teams have ships
2738         case MULTI_JOIN_RESTR_MODE_4:
2739                 key1 = SDLK_1;
2740                 key2 = SDLK_2;
2741                 break;
2742         
2743         // illegal mode
2744         default :
2745                 Int3();
2746         }       
2747
2748         // check the keypress
2749         if((k == key1) || (k == key2)){
2750                 // unset the timestamp
2751                 Multi_restr_query_timestamp = -1;                       
2752
2753                 // MWA -- 5/26/98.  Next line commented out.  It should be cleared when the ingame joiner
2754                 // actually gets into the mission
2755                 //Netgame.flags &= ~(NG_FLAG_INGAME_JOINING);
2756
2757                 // determine which team to put him on (if any)
2758                 switch(Multi_join_restr_mode){
2759                 // normal restricted join, Y or N
2760                 case MULTI_JOIN_RESTR_MODE_1:
2761                         team_val = (k == key1) ? 0 : -1;
2762                         break;
2763
2764                 // team vs team, team 0 only has ships
2765                 case MULTI_JOIN_RESTR_MODE_2:
2766                         team_val = (k == key1) ? 0 : -1;                        
2767                         break;
2768
2769                 // team vs team, team 1 only has ships          
2770                 case MULTI_JOIN_RESTR_MODE_3:
2771                         team_val = (k == key1) ? 1 : -1;                        
2772                         break;
2773
2774                 // team vs team, both teams have ships
2775                 case MULTI_JOIN_RESTR_MODE_4:
2776                         team_val = (k == key1) ? 0 : 1;                 
2777                         break;
2778         
2779                 // illegal mode
2780                 default :
2781                         team_val = -1;  // JAS: Get rid of optimized warning
2782                         Int3();
2783                 }                               
2784
2785                 // perform the proper response  
2786                 if(Net_player->flags & NETINFO_FLAG_AM_MASTER){
2787                         if(team_val >= 0){                      
2788                                 multi_process_valid_join_request(&Multi_restr_join_request,&Multi_restr_addr,team_val);                 
2789                         }
2790                 }
2791                 // otherwise tell the standalone to accept him
2792                 else {
2793                         if(team_val >= 0){
2794                                 send_host_restr_packet("null",1,team_val);
2795                         } else {
2796                                 send_host_restr_packet("null",2,-1);
2797                         }
2798                 }
2799
2800                 // processed a key
2801                 return 1;
2802         }
2803         
2804         // didn't process any keys
2805         return 0;
2806 }
2807
2808 // determine the status of available player ships (use team_0 for non team vs. team situations)
2809 void multi_player_ships_available(int *team_0,int *team_1)
2810 {
2811         ship_obj *moveup;
2812         int mp_team_num;
2813         
2814         *team_0 = 0;
2815         *team_1 = 0;
2816         
2817         moveup = GET_FIRST(&Ship_obj_list);
2818         while(moveup!=END_OF_LIST(&Ship_obj_list)){
2819                 // if this ship is flagged as OF_COULD_BE_PLAYER
2820                 if(Objects[moveup->objnum].flags & OF_COULD_BE_PLAYER){
2821                         // get the team # for this ship
2822                         mp_team_num = multi_ts_get_team(Ships[Objects[moveup->objnum].instance].ship_name);
2823                         if(mp_team_num == 0){
2824                                 (*team_0)++;
2825                         } else if(mp_team_num == 1){
2826                                 (*team_1)++;
2827                         }
2828                 }
2829                 
2830                 moveup = GET_NEXT(moveup);
2831         }       
2832 }
2833
2834 // server should update the player's bank/link status with the data in the passed ship
2835 void multi_server_update_player_weapons(net_player *pl,ship *shipp)
2836 {
2837         // don't process when the ship is dying.
2838         if ( (shipp->flags & SF_DYING) || NETPLAYER_IS_DEAD(pl) )
2839                 return;
2840
2841         // primary bank status
2842         pl->s_info.cur_primary_bank = (char)shipp->weapons.current_primary_bank;
2843
2844         // primary link status
2845         pl->s_info.cur_link_status &= ~(1<<0);
2846         if(shipp->flags & SF_PRIMARY_LINKED){
2847                 pl->s_info.cur_link_status |= (1<<0);
2848         }
2849
2850         // secondary bank status
2851         if ( shipp->weapons.current_secondary_bank < 0 ) {
2852                 nprintf(("Network", "bashing %s's current sbank to 0\n", shipp->ship_name));
2853                 shipp->weapons.current_secondary_bank = 0;
2854         }
2855         pl->s_info.cur_secondary_bank = (char)shipp->weapons.current_secondary_bank;
2856
2857         // secondary link status
2858         pl->s_info.cur_link_status &= ~(1<<1);
2859         if(shipp->flags & SF_SECONDARY_DUAL_FIRE){
2860                 pl->s_info.cur_link_status |= (1<<1);
2861         }
2862
2863         // ets values
2864         pl->s_info.ship_ets = 0x0000;
2865         // shield ets           
2866         pl->s_info.ship_ets |= ((ushort)shipp->shield_recharge_index << 8);
2867         // weapon ets
2868         pl->s_info.ship_ets |= ((ushort)shipp->weapon_recharge_index << 4);
2869         // engine ets
2870         pl->s_info.ship_ets |= ((ushort)shipp->engine_recharge_index);
2871
2872         SDL_assert( pl->s_info.ship_ets != 0 );
2873 }
2874
2875 // flush the multidata cache directory
2876 void multi_flush_multidata_cache()
2877 {
2878         nprintf(("Network","FLUSHING MULTIDATA CACHE\n"));
2879         
2880         // call the cfile function to flush the directory
2881         cfile_flush_dir(CF_TYPE_MULTI_CACHE);
2882 }
2883
2884 // flush all data from a previous mission before starting the next
2885 void multi_flush_mission_stuff()
2886 {
2887         int idx;
2888         
2889         for(idx=0;idx<MAX_PLAYERS;idx++){
2890                 if(MULTI_CONNECTED(Net_players[idx])){                  
2891                         // unset all unneeded status bits
2892                         Net_players[idx].flags &= ~(NETINFO_FLAG_MISSION_OK | NETINFO_FLAG_RESPAWNING | NETINFO_FLAG_WARPING_OUT);
2893                         
2894                         // server is always "mission ok"
2895                         if(Net_players[idx].flags & NETINFO_FLAG_AM_MASTER){
2896                                 Net_players[idx].flags |= NETINFO_FLAG_MISSION_OK;
2897                         }
2898
2899                         // if this guy is a non-permanent observer, unset the appropriate flags
2900                         if(MULTI_TEMP_OBSERVER(Net_players[idx])){
2901                                 Net_players[idx].flags &= ~(NETINFO_FLAG_OBSERVER | NETINFO_FLAG_OBS_PLAYER);
2902                         }
2903
2904                         // misc
2905                         multi_ping_reset(&Net_players[idx].s_info.ping);                                
2906                         Net_players[idx].s_info.num_last_buttons = 0;
2907                         Net_players[idx].s_info.wing_index_backup = 0;
2908                         Net_players[idx].s_info.wing_index = 0;
2909                         Net_players[idx].p_info.ship_class = -1;
2910                         Net_players[idx].p_info.ship_index = -1;
2911                         Net_players[idx].s_info.xfer_handle = -1;
2912
2913                         // ack handles
2914                         Net_players[idx].s_info.wing_index_backup = 0;
2915                                 
2916                         // objnum 
2917                         Players[idx].objnum = -1;
2918                 }
2919         }       
2920
2921         // reset netgame stuff
2922         Netgame.flags &= ~(NG_FLAG_TEMP_CLOSED);                
2923
2924         multi_xfer_reset();
2925
2926         // standalone servers should clear their goal trees now
2927         if(Game_mode & GM_STANDALONE_SERVER){
2928                 std_multi_setup_goal_tree();
2929         }
2930         
2931         // object signatures
2932         // this will eventually get reset to Netgame.security the next time an object gets its signature assigned.
2933         // We do this to resynchronize the host/server and all clients
2934         Next_ship_signature = SHIP_SIG_MIN;
2935         Next_asteroid_signature = ASTEROID_SIG_MIN;
2936         Next_non_perm_signature = NPERM_SIG_MIN;
2937
2938         // everyone will need to either reload the current mission, leave, or load the next mission, so in any case
2939         Multi_mission_loaded = 0;
2940 }
2941
2942 // should we ignore all controls and keypresses because of some multiplayer 
2943 int multi_ignore_controls(int key)
2944 {               
2945         // if the multiplayer text messaging system is active, don't return any keys    
2946         if((key > 0) && multi_msg_text_process(key)){
2947                 return 1;
2948         }
2949
2950         // if the host of the game is being prompted to accept or deny a player in a restricted game
2951         if((key > 0) && multi_process_restricted_keys(key)){
2952                 return 1;
2953         }
2954         
2955         // if we're in text messaging mode, ignore controls
2956         if(multi_msg_text_mode()){
2957                 return 1;
2958         }       
2959
2960         // if the pause system wants to eat keys for a while
2961         if(multi_pause_eat_keys()){
2962                 return 1;
2963         }
2964
2965         // multiplayer didn't eat the key
2966         return 0;
2967 }
2968
2969 // if the kill limit has been reached by any given player
2970 int multi_kill_limit_reached()
2971 {
2972         int idx;
2973
2974         // is the kill limit <= 0 ?
2975         // if so, consider it as _no_ kill limit
2976         if(Netgame.options.kill_limit <= 0){
2977                 return 0;
2978         }
2979         
2980         // look through all active, non-observer players
2981         for(idx=0;idx<MAX_PLAYERS;idx++){
2982                 if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx]) && !MULTI_OBSERVER(Net_players[idx]) && (Net_players[idx].player->stats.m_kill_count_ok >= Netgame.options.kill_limit)){
2983                         // someone reached the limit
2984                         return 1;
2985                 }
2986         }
2987
2988         // limit has not been reached yet
2989         return 0;
2990 }
2991
2992 // display a chat message (write to the correct spot - hud, standalone gui, chatbox, etc)
2993 void multi_display_chat_msg(const char *msg, int player_index, int add_id)
2994 {
2995         // if i'm a standalone, always add to the gui
2996         if(Game_mode & GM_STANDALONE_SERVER){
2997                 std_add_chat_text(msg,player_index,add_id);
2998                 return;
2999         }
3000         
3001         // in gameplay
3002         if(Game_mode & GM_IN_MISSION){                                  
3003                 // if we're paused, send it to the chatbox
3004                 if(Multi_pause_status){
3005                         chatbox_add_line(msg, player_index, add_id);
3006                 }
3007                 // otherwise print to the HUD
3008                 else {
3009                         multi_msg_display_mission_text(msg, player_index);
3010                 }
3011         }
3012         // otherwise add it to the chatbox
3013         else {
3014                 chatbox_add_line(msg, player_index, add_id);
3015         }               
3016 }
3017
3018 // fill in Current_file_checksum and Current_file_length
3019 void multi_get_mission_checksum(const char *filename)
3020 {
3021         CFILE *in;
3022
3023         Multi_current_file_checksum = 0xffff;
3024         Multi_current_file_length = -1;
3025
3026         // get the filename
3027         in = cfopen(filename,"rb");
3028         if(in != NULL){
3029                 // get the length of the file
3030                 Multi_current_file_length = cfilelength(in);
3031                 cfclose(in);
3032
3033                 in = cfopen(filename,"rb");
3034                 if(in != NULL){
3035                         // get the checksum of the file
3036                         cf_chksum_short(in,&Multi_current_file_checksum);
3037
3038                         // close the file
3039                         cfclose(in);
3040                         in = NULL;
3041                 }
3042                 // if the file doesn't exist, setup some special values, so the server recognizes this
3043                 else {
3044                         Multi_current_file_checksum = 0xffff;
3045                         Multi_current_file_length = -1;
3046                 }
3047         } else {
3048                 // don't transfew builtin missions
3049                 if(multi_is_builtin_mission()){ 
3050                         multi_quit_game(PROMPT_ALL, MULTI_END_NOTIFY_KICKED_CANT_XFER);
3051                 }
3052         }
3053         nprintf(("Network","NET FILE CHECKSUM : %d %d\n",Multi_current_file_checksum,Multi_current_file_length));
3054 }
3055
3056 char multi_unit_to_char(float unit)
3057 {
3058         char ret;
3059         
3060         if(unit > 1.0f){
3061                 Int3();
3062                 unit = 1.0f;
3063         }
3064         if(unit < -1.0f){
3065                 Int3();
3066                 unit = -1.0f;
3067         }
3068
3069         ret = (char)(unit * 127.0f);
3070         return ret;
3071 }
3072
3073 float multi_char_to_unit(float val)
3074 {
3075         float ret;
3076
3077         ret = (float)val / 127.0f;
3078         if(ret > 1.0f){
3079                 Int3();
3080                 ret = 1.0f;
3081         }
3082         if(ret < -1.0f){
3083                 Int3();
3084                 ret = -1.0f;
3085         }
3086
3087         return ret;
3088 }
3089
3090 // if we should render our ping time to the server in a multiplayer game
3091 int multi_show_ingame_ping()
3092 {
3093         // always show it for now
3094         return 1;
3095 }
3096
3097 int multi_get_connection_speed()
3098 {
3099         int cspeed;
3100         const char *connection_speed;
3101
3102         // 'Fast' should be a safe default in 2015
3103         connection_speed = os_config_read_string("Network", "ConnectionSpeed", "Fast");
3104
3105         if ( !SDL_strcasecmp(connection_speed, NOX("Slow")) ) {
3106                 cspeed = CONNECTION_SPEED_288;
3107         } else if ( !SDL_strcasecmp(connection_speed, NOX("56K")) ) {
3108                 cspeed = CONNECTION_SPEED_56K;
3109         } else if ( !SDL_strcasecmp(connection_speed, NOX("ISDN")) ) {
3110                 cspeed = CONNECTION_SPEED_SISDN;
3111         } else if ( !SDL_strcasecmp(connection_speed, NOX("Cable")) ) {
3112                 cspeed = CONNECTION_SPEED_CABLE;
3113         } else if ( !SDL_strcasecmp(connection_speed, NOX("Fast")) ) {
3114                 cspeed = CONNECTION_SPEED_T1;
3115         } else {
3116                 cspeed = CONNECTION_SPEED_NONE;
3117         }
3118
3119         return cspeed;
3120 }
3121
3122 // return a MVALID_STATUS_* define based upon the passed string
3123 int multi_string_to_status(char *valid_string)
3124 {
3125         return MVALID_STATUS_UNKNOWN;   
3126 }
3127
3128 // if we're in tracker mode, do a validation update on all known missions
3129 void multi_update_valid_missions()
3130 {
3131         char next_filename[MAX_FILENAME_LEN+1]; 
3132         char next_line[512];
3133         char status_string[50];
3134         char temp[256];
3135         char *tok;
3136         CFILE *in;
3137         int idx, file_index;    
3138         int was_cancelled;
3139
3140         // if we're a standalone, show a dialog saying "validating missions"
3141         if(Game_mode & GM_STANDALONE_SERVER){
3142                 std_create_gen_dialog("Validating missions");
3143                 std_gen_set_text("Querying:",1);
3144         }
3145
3146         // mark all missions on our list as being MVALID_STATUS_UNKNOWN
3147         for(idx=0; idx<Multi_create_mission_count; idx++){
3148                 Multi_create_mission_list[idx].valid_status = MVALID_STATUS_UNKNOWN;
3149         }
3150         
3151         // attempt to open the valid mission config file
3152         in = cfopen(MULTI_VALID_MISSION_FILE, "rt", CFILE_NORMAL, CF_TYPE_DATA);
3153         if(in != NULL){         
3154                 // read in all listed missions
3155                 while(!cfeof(in)){
3156                         // read in a line
3157                         memset(next_line, 0, 512);
3158                         cfgets(next_line, 512, in);
3159                         drop_trailing_white_space(next_line);
3160                         drop_leading_white_space(next_line);
3161
3162                         // read in a filename
3163                         memset(next_filename, 0, MAX_FILENAME_LEN+1);
3164                         memset(temp, 0, 256);
3165                         tok = strtok(next_line, " ");
3166                         if(tok == NULL){
3167                                 continue;
3168                         }                       
3169                         SDL_strlcpy(temp, tok, SDL_arraysize(temp));
3170                         drop_trailing_white_space(temp);
3171                         drop_leading_white_space(temp);
3172                         SDL_strlcpy(next_filename, temp, SDL_arraysize(next_filename));
3173                         
3174                         // read in the status string
3175                         memset(status_string, 0, 50);
3176                         memset(temp, 0, 256);
3177                         tok = strtok(NULL," \n");
3178                         if(tok == NULL){
3179                                 continue;
3180                         }
3181                         SDL_strlcpy(temp, tok, SDL_arraysize(temp));
3182                         drop_trailing_white_space(temp);
3183                         drop_leading_white_space(temp);
3184                         SDL_strlcpy(status_string, temp, SDL_arraysize(status_string));
3185
3186                         // try and find the file
3187                         file_index = multi_create_lookup_mission(next_filename);
3188                         if(file_index >= 0){
3189                                 Multi_create_mission_list[file_index].valid_status = (char)multi_string_to_status(status_string);
3190                         }
3191                 }
3192
3193                 // close the infile
3194                 cfclose(in);
3195                 in = NULL;      
3196         }       
3197
3198         // now poll for all unknown missions
3199         was_cancelled = 0;
3200
3201         // if the operation was cancelled, don't write anything new
3202         if(was_cancelled){
3203                 // if we're a standalone, kill the validate dialog
3204                 if(Game_mode & GM_STANDALONE_SERVER){
3205                         std_destroy_gen_dialog();
3206                 }
3207
3208                 return;
3209         }
3210
3211         // now rewrite the outfile with the new mission info
3212         in = cfopen(MULTI_VALID_MISSION_FILE, "wt", CFILE_NORMAL, CF_TYPE_DATA);
3213         if(in == NULL){
3214                 // if we're a standalone, kill the validate dialog
3215                 if(Game_mode & GM_STANDALONE_SERVER){
3216                         std_destroy_gen_dialog();
3217                 }
3218
3219                 return;
3220         }
3221         for(idx=0; idx<Multi_create_mission_count; idx++){
3222                 switch(Multi_create_mission_list[idx].valid_status){
3223                 case MVALID_STATUS_VALID:
3224                         cfputs(Multi_create_mission_list[idx].filename, in);
3225                         cfputs(NOX("   valid"), in);
3226                         cfputs(NOX("\n"), in);
3227                         break;
3228
3229                 case MVALID_STATUS_INVALID:
3230                         cfputs(Multi_create_mission_list[idx].filename, in);
3231                         cfputs(NOX("   invalid"), in);
3232                         cfputs(NOX("\n"), in);
3233                         break;
3234                 }
3235         }
3236
3237         // close the outfile
3238         cfclose(in);
3239         in = NULL;
3240
3241         // if we're a standalone, kill the validate dialog
3242         if(Game_mode & GM_STANDALONE_SERVER){
3243                 std_destroy_gen_dialog();
3244         }
3245 }
3246
3247 // get a new id# for a player
3248 short multi_get_new_id()
3249 {
3250         if(Multi_id_num > 20000){
3251                 Multi_id_num = 0;
3252         } 
3253
3254         return Multi_id_num++;
3255 }
3256
3257
3258 // ------------------------------------
3259
3260 //XSTR:OFF
3261 DCF(multi,"changes multiplayer settings")
3262 {
3263         if(Dc_command){
3264                 dc_get_arg(ARG_STRING);
3265                 
3266                 if(strcmp(Dc_arg, "kick")==0){                          // kick a player
3267                         multi_dcf_kick();
3268 #ifndef NDEBUG
3269                 } else if(strcmp(Dc_arg, "stats")==0) {
3270                         // multi_toggle_stats();
3271                 } else if(strcmp(Dc_arg, "show_stats")==0) {
3272                         // multi_show_basic_stats(0);
3273                 } else if(strcmp(Dc_arg, "dump_stats")==0) {
3274                         // multi_show_basic_stats(1);
3275 #endif
3276                 } else if(strcmp(Dc_arg, "voice")==0){                          // settings for multiplayer voice
3277                         multi_voice_dcf();
3278                 } else if(strcmp(Dc_arg, "respawn_chump")==0){  // set a really large # of respawns
3279                         if((Net_player != NULL) && (Net_player->flags & NETINFO_FLAG_GAME_HOST)){                       
3280                                 Netgame.respawn = 9999;
3281                                 Netgame.options.respawn = 9999;                         
3282
3283                                 // if i'm the server, send a netgame update
3284                                 if(Net_player->flags & NETINFO_FLAG_AM_MASTER){
3285                                         send_netgame_update_packet();
3286                                 } 
3287                         }
3288                 } else if(strcmp(Dc_arg, "ss_leaders")==0){             // only host or team captains can modify ships
3289                         if((Net_player != NULL) && (Net_player->flags & NETINFO_FLAG_GAME_HOST)){                       
3290                                 Netgame.options.flags |= MSO_FLAG_SS_LEADERS;
3291                                 multi_options_update_netgame();
3292                         }
3293                 } else if(strcmp(Dc_arg, "make_players")==0){
3294 #ifndef NDEBUG
3295                         multi_make_fake_players(MAX_PLAYERS);
3296 #endif
3297                 } else if(strcmp(Dc_arg, "givecd")==0){
3298                         extern int Multi_has_cd;
3299                         Multi_has_cd = 1;
3300                 /*
3301                 } else if(strcmp(Dc_arg, "oo")==0){
3302                         int new_flags = -1;
3303
3304                         dc_get_arg(ARG_INT);
3305                         if(Dc_arg_type & ARG_INT){
3306                                 new_flags = Dc_arg_int;
3307                         }
3308
3309                         dc_printf("Interesting flags\nPos : %d\nVelocity : %d\nDesired vel : %d\nOrient : %d\nRotvel : %d\nDesired rotvel %d\n",
3310                                                  1<<0, 1<<7, 1<<8, 1<<1, 1<<9, 1<<10);
3311                 */
3312                 } else if(strcmp(Dc_arg, "oo_sort")==0){                        
3313                         extern int OO_sort;
3314
3315                         OO_sort = !OO_sort;
3316                         if(OO_sort){
3317                                 dc_printf("Network object sorting ENABLED\n");
3318                         } else {
3319                                 dc_printf("Network object sorting DISABLED\n");
3320                         }
3321                 }
3322         }
3323 }
3324
3325 //XSTR:ON
3326
3327 // PXO crc checking stuff
3328 #ifndef NDEBUG
3329
3330 void multi_spew_pxo_checksums(int max_files, char *outfile)
3331 {
3332         char **file_names;
3333         char full_name[MAX_FILENAME_LEN+1];
3334         char wild_card[6];
3335         int count, idx;
3336         uint checksum;
3337         FILE *out;
3338
3339         // allocate filename space      
3340         file_names = (char**)malloc(sizeof(char*) * max_files);
3341         if(file_names != NULL){
3342                 SDL_snprintf(wild_card, SDL_arraysize(wild_card), "*%s", FS_MISSION_FILE_EXT);
3343                 count = cf_get_file_list(max_files, file_names, CF_TYPE_MISSIONS, wild_card);   
3344         
3345                 // open the outfile
3346                 out = fopen(outfile, "wt");
3347                 if(out == NULL){
3348                         return;
3349                 }
3350                 
3351                 // do all the checksums
3352                 for(idx=0; idx<count; idx++){
3353                         memset(full_name, 0, MAX_FILENAME_LEN+1);                       
3354                         SDL_strlcpy(full_name, cf_add_ext(file_names[idx], FS_MISSION_FILE_EXT), SDL_arraysize(full_name));
3355
3356                         if(cf_chksum_long(full_name, &checksum)){
3357                                 fprintf(out, "%s        :       %d\n", full_name, (int)checksum);
3358                         }
3359                 }
3360
3361                 fclose(out);
3362                 free(file_names);
3363         }
3364 }
3365
3366 DCF(pxospew,"spew PXO 32 bit checksums for all visible mission files")
3367 {
3368         int max_files;
3369
3370         dc_get_arg(ARG_INT);
3371         if(Dc_arg_type & ARG_INT){
3372                 max_files = Dc_arg_int; 
3373
3374                 dc_get_arg(ARG_STRING);
3375                 if(Dc_arg_type & ARG_STRING){
3376                         multi_spew_pxo_checksums(max_files, Dc_arg);
3377                 }
3378         }
3379 }
3380
3381 #endif
3382
3383 // make a bunch of fake players - don't rely on this to be very safe - its mostly used for interface testing
3384 #ifndef NDEBUG
3385 void multi_make_fake_players(int count)
3386 {
3387         int idx;
3388         
3389         for(idx=0;idx<count;idx++){
3390                 if(!MULTI_CONNECTED(Net_players[idx])){
3391                         Net_players[idx].player = &Players[idx];
3392                         SDL_snprintf(Net_players[idx].player->callsign, CALLSIGN_LEN, "Player %d", idx);
3393                         Net_players[idx].flags |= NETINFO_FLAG_CONNECTED;
3394                 }
3395         }
3396 }
3397 #endif
3398
3399 // ---------------------------------------------------------------------------------------------------------------------
3400 // PACK UNPACK STUFF
3401 //
3402
3403 #ifndef PLAT_UNIX
3404 #pragma optimize("", off)
3405 #endif
3406
3407 typedef struct bitbuffer {
3408         ubyte           mask;
3409    int          rack;
3410         ubyte           *data;
3411         ubyte           *org_data;
3412 } bitbuffer;
3413
3414 void bitbuffer_init( bitbuffer *bitbuf, ubyte *data )
3415 {
3416         bitbuf->rack = 0;       
3417         bitbuf->mask = 0x80;
3418         bitbuf->data = data;
3419         bitbuf->org_data = data;
3420 }
3421
3422 int bitbuffer_write_flush( bitbuffer *bitbuf )
3423 {
3424         // Flush to next byte
3425         if ( bitbuf->mask != 0x80 )     {
3426         *bitbuf->data++ = (ubyte)bitbuf->rack;
3427         }
3428         return bitbuf->data-bitbuf->org_data;
3429 }
3430
3431 int bitbuffer_read_flush( bitbuffer *bitbuf )
3432 {
3433         return bitbuf->data-bitbuf->org_data;
3434 }
3435
3436 void bitbuffer_put( bitbuffer *bitbuf, uint data, int bit_count ) 
3437 {
3438         uint mask;
3439
3440         mask = 1L << ( bit_count - 1 );
3441         while ( mask != 0) {
3442                 if ( mask & data )      {
3443                         bitbuf->rack |= bitbuf->mask;
3444                 }
3445                 bitbuf->mask >>= 1;
3446                 if ( bitbuf->mask == 0 ) {
3447                         *bitbuf->data++=(ubyte)bitbuf->rack;
3448                         bitbuf->rack = 0;
3449                         bitbuf->mask = 0x80;
3450                 }
3451                 mask >>= 1;
3452         }
3453 }
3454
3455 uint bitbuffer_get_unsigned( bitbuffer *bitbuf, int bit_count ) 
3456 {
3457         uint mask;
3458         uint return_value;
3459
3460         mask = 1L << ( bit_count - 1 );
3461         return_value = 0;
3462
3463         while ( mask != 0)      {
3464                 if ( bitbuf->mask == 0x80 ) {
3465                         bitbuf->rack = *bitbuf->data++;
3466                 }
3467                 if ( bitbuf->rack & bitbuf->mask )      {
3468                         return_value |= mask;
3469                 }
3470                 mask >>= 1;
3471                 bitbuf->mask >>= 1;
3472                 if ( bitbuf->mask == 0 )        {
3473                         bitbuf->mask = 0x80;
3474                 }
3475         }
3476
3477         return return_value;
3478 }
3479
3480 int bitbuffer_get_signed( bitbuffer *bitbuf, int bit_count ) 
3481 {
3482         uint mask;
3483         uint return_value;
3484
3485         mask = 1L << ( bit_count - 1 );
3486         return_value = 0;
3487
3488         while ( mask != 0)      {
3489                 if ( bitbuf->mask == 0x80 ) {
3490                         bitbuf->rack = *bitbuf->data++;
3491                 }
3492                 if ( bitbuf->rack & bitbuf->mask )      {
3493                         return_value |= mask;
3494                 }
3495                 mask >>= 1;
3496                 bitbuf->mask >>= 1;
3497                 if ( bitbuf->mask == 0 )        {
3498                         bitbuf->mask = 0x80;
3499                 }
3500         }
3501
3502         // sign extend return value
3503         return_value <<= (32-bit_count);
3504         
3505         return ((int)return_value)>>(32-bit_count);
3506 }
3507         
3508
3509
3510 // Packs/unpacks an object position.
3511 // Returns number of bytes read or written.
3512 // #define OO_POS_RET_SIZE                                                      9
3513 int multi_pack_unpack_position( int write, ubyte *data, vector *pos)
3514 {
3515         bitbuffer buf;
3516
3517         bitbuffer_init(&buf,data);
3518
3519         int a, b, c;
3520
3521         if ( write )    {
3522                 // Output pos
3523
3524                 a = fl2i(pos->xyz.x*105.0f+0.5f); 
3525                 b = fl2i(pos->xyz.y*105.0f+0.5f);
3526                 c = fl2i(pos->xyz.z*105.0f+0.5f);
3527                 CAP(a,-8388608,8388607);
3528                 CAP(b,-8388608,8388607);
3529                 CAP(c,-8388608,8388607);
3530                 
3531                 bitbuffer_put( &buf, (uint)a, 24 );
3532                 bitbuffer_put( &buf, (uint)b, 24 );
3533                 bitbuffer_put( &buf, (uint)c, 24 );
3534
3535
3536                 return bitbuffer_write_flush(&buf);
3537
3538         } else {
3539
3540                 // unpack pos
3541                 a = bitbuffer_get_signed(&buf,24);
3542                 b = bitbuffer_get_signed(&buf,24);
3543                 c = bitbuffer_get_signed(&buf,24);
3544
3545                 pos->xyz.x = i2fl(a)/105.0f;
3546                 pos->xyz.y = i2fl(b)/105.0f;
3547                 pos->xyz.z = i2fl(c)/105.0f;
3548
3549                 return bitbuffer_read_flush(&buf);
3550         }
3551 }
3552
3553 int degenerate_count = 0;
3554 int non_degenerate_count = 0;
3555
3556 /*
3557 hack = ((ushort)orient->v.fvec.xyz.x * 32767);
3558                         memcpy(&hack, &orient->v.fvec.xyz.x, 4);
3559                         bitbuffer_put( &buf, hack, 32  );
3560                         memcpy(&hack, &orient->v.fvec.xyz.y, 4);
3561                         bitbuffer_put( &buf, hack, 32  );
3562                         memcpy(&hack, &orient->v.fvec.xyz.z, 4);
3563                         bitbuffer_put( &buf, hack, 32  );
3564
3565                         memcpy(&hack, &orient->v.uvec.xyz.x, 4);
3566                         bitbuffer_put( &buf, hack, 32  );
3567                         memcpy(&hack, &orient->v.uvec.xyz.y, 4);
3568                         bitbuffer_put( &buf, hack, 32  );
3569                         memcpy(&hack, &orient->v.uvec.xyz.z, 4);
3570                         bitbuffer_put( &buf, hack, 32  );
3571
3572                         memcpy(&hack, &orient->v.rvec.xyz.x, 4);
3573                         bitbuffer_put( &buf, hack, 32  );
3574                         memcpy(&hack, &orient->v.rvec.xyz.y, 4);
3575                         bitbuffer_put( &buf, hack, 32  );
3576                         memcpy(&hack, &orient->v.rvec.xyz.z, 4);
3577                         bitbuffer_put( &buf, hack, 32  );*/
3578
3579 /*
3580 hack = bitbuffer_get_unsigned(&buf, 32);
3581                         memcpy(&orient->v.fvec.xyz.x, &hack, 4);
3582                         hack = bitbuffer_get_unsigned(&buf, 32);
3583                         memcpy(&orient->v.fvec.xyz.y, &hack, 4);
3584                         hack = bitbuffer_get_unsigned(&buf, 32);
3585                         memcpy(&orient->v.fvec.xyz.z, &hack, 4);
3586
3587                         hack = bitbuffer_get_unsigned(&buf, 32);
3588                         memcpy(&orient->v.uvec.xyz.x, &hack, 4);
3589                         hack = bitbuffer_get_unsigned(&buf, 32);
3590                         memcpy(&orient->v.uvec.xyz.y, &hack, 4);
3591                         hack = bitbuffer_get_unsigned(&buf, 32);
3592                         memcpy(&orient->v.uvec.xyz.z, &hack, 4);
3593
3594                         hack = bitbuffer_get_unsigned(&buf, 32);
3595                         memcpy(&orient->v.rvec.xyz.x, &hack, 4);
3596                         hack = bitbuffer_get_unsigned(&buf, 32);
3597                         memcpy(&orient->v.rvec.xyz.y, &hack, 4);
3598                         hack = bitbuffer_get_unsigned(&buf, 32);
3599                         memcpy(&orient->v.rvec.xyz.z, &hack, 4);*/
3600
3601 // Packs/unpacks an orientation matrix.
3602 // Returns number of bytes read or written.
3603 // #define OO_ORIENT_RET_SIZE                                           6
3604 int multi_pack_unpack_orient( int write, ubyte *data, matrix *orient)
3605 {
3606         bitbuffer buf;
3607
3608         bitbuffer_init(&buf, data + 1);
3609
3610         vector rot_axis;        
3611         float theta;
3612         int a, b, c, d;
3613         angles ang;     
3614         ubyte flag = 0x00;      
3615
3616         #define D_SCALE 32768.0f
3617         #define D_MAX_RANGE 32767
3618         #define D_MIN_RANGE -32768
3619
3620         #define N_SCALE 2048.0f
3621         #define N_MAX_RANGE 2047
3622         #define N_MIN_RANGE -2048
3623
3624         if ( write )    {                       
3625                 // degenerate case - send the whole orient matrix
3626                 vm_extract_angles_matrix(&ang, orient); 
3627                 if((ang.h > 3.130) && (ang.h < 3.150)){
3628                         degenerate_count++;
3629
3630                         flag = 0xff;
3631                         
3632                         // stuff it     
3633                         a = fl2i(orient->v.fvec.xyz.x * D_SCALE);
3634                         CAP(a, D_MIN_RANGE, D_MAX_RANGE);                       
3635                         bitbuffer_put( &buf, a, 16  );
3636                         a = fl2i(orient->v.fvec.xyz.y * D_SCALE);
3637                         CAP(a, D_MIN_RANGE, D_MAX_RANGE);                       
3638                         bitbuffer_put( &buf, a, 16  );
3639                         a = fl2i(orient->v.fvec.xyz.z * D_SCALE);
3640                         CAP(a, D_MIN_RANGE, D_MAX_RANGE);                       
3641                         bitbuffer_put( &buf, a, 16  );
3642
3643                         a = fl2i(orient->v.uvec.xyz.x * D_SCALE);
3644                         CAP(a, D_MIN_RANGE, D_MAX_RANGE);                       
3645                         bitbuffer_put( &buf, a, 16  );
3646                         a = fl2i(orient->v.uvec.xyz.y * D_SCALE);
3647                         CAP(a, D_MIN_RANGE, D_MAX_RANGE);                       
3648                         bitbuffer_put( &buf, a, 16  );
3649                         a = fl2i(orient->v.uvec.xyz.z * D_SCALE);
3650                         CAP(a, D_MIN_RANGE, D_MAX_RANGE);                       
3651                         bitbuffer_put( &buf, a, 16  );
3652
3653                         a = fl2i(orient->v.rvec.xyz.x * D_SCALE);
3654                         CAP(a, D_MIN_RANGE, D_MAX_RANGE);                       
3655                         bitbuffer_put( &buf, a, 16  );
3656                         a = fl2i(orient->v.rvec.xyz.y * D_SCALE);
3657                         CAP(a, D_MIN_RANGE, D_MAX_RANGE);                       
3658                         bitbuffer_put( &buf, a, 16  );
3659                         a = fl2i(orient->v.rvec.xyz.z * D_SCALE);
3660                         CAP(a, D_MIN_RANGE, D_MAX_RANGE);                       
3661                         bitbuffer_put( &buf, a, 16  );
3662                 } else {
3663                         non_degenerate_count++;
3664                                 
3665                         vm_matrix_to_rot_axis_and_angle(orient, &theta, &rot_axis);             
3666                         // Have theta, which is an angle between 0 and PI.
3667                         // Convert it to be between -1.0f and 1.0f
3668                         theta = theta*2.0f/PI-1.0f;                     
3669
3670                         // -1 to 1
3671                         a = fl2i(rot_axis.xyz.x*N_SCALE); 
3672                         b = fl2i(rot_axis.xyz.y*N_SCALE);
3673                         c = fl2i(rot_axis.xyz.z*N_SCALE);
3674                         d = fl2i(theta*N_SCALE);
3675
3676                         CAP(a, N_MIN_RANGE, N_MAX_RANGE);
3677                         CAP(b, N_MIN_RANGE, N_MAX_RANGE);
3678                         CAP(c, N_MIN_RANGE, N_MAX_RANGE);
3679                         CAP(d, N_MIN_RANGE, N_MAX_RANGE);
3680                                         
3681                         bitbuffer_put( &buf, (uint)a, 12 );
3682                         bitbuffer_put( &buf, (uint)b, 12 );
3683                         bitbuffer_put( &buf, (uint)c, 12 );
3684                         bitbuffer_put( &buf, (uint)d, 12 );
3685                 }
3686
3687                 // flag for degenerate case
3688                 data[0] = flag;
3689
3690                 return bitbuffer_write_flush(&buf) + 1;
3691         } else {
3692                 flag = data[0];
3693
3694                 // degenerate
3695                 if(flag){
3696                         a = bitbuffer_get_signed(&buf, 16);
3697                         orient->v.fvec.xyz.x = i2fl(a) / D_SCALE;                       
3698                         a = bitbuffer_get_signed(&buf, 16);
3699                         orient->v.fvec.xyz.y = i2fl(a) / D_SCALE;                       
3700                         a = bitbuffer_get_signed(&buf, 16);
3701                         orient->v.fvec.xyz.z = i2fl(a) / D_SCALE;                       
3702
3703                         a = bitbuffer_get_signed(&buf, 16);
3704                         orient->v.uvec.xyz.x = i2fl(a) / D_SCALE;                       
3705                         a = bitbuffer_get_signed(&buf, 16);
3706                         orient->v.uvec.xyz.y = i2fl(a) / D_SCALE;                       
3707                         a = bitbuffer_get_signed(&buf, 16);
3708                         orient->v.uvec.xyz.z = i2fl(a) / D_SCALE;                       
3709
3710                         a = bitbuffer_get_signed(&buf, 16);
3711                         orient->v.rvec.xyz.x = i2fl(a) / D_SCALE;                       
3712                         a = bitbuffer_get_signed(&buf, 16);
3713                         orient->v.rvec.xyz.y = i2fl(a) / D_SCALE;                       
3714                         a = bitbuffer_get_signed(&buf, 16);
3715                         orient->v.rvec.xyz.z = i2fl(a) / D_SCALE;                       
3716                 } else {
3717                         a = bitbuffer_get_signed(&buf,12);
3718                         b = bitbuffer_get_signed(&buf,12);
3719                         c = bitbuffer_get_signed(&buf,12);
3720                         d = bitbuffer_get_signed(&buf,12);
3721
3722                         // special case         
3723                         rot_axis.xyz.x = i2fl(a)/N_SCALE;
3724                         rot_axis.xyz.y = i2fl(b)/N_SCALE;
3725                         rot_axis.xyz.z = i2fl(c)/N_SCALE;
3726                         theta = i2fl(d)/N_SCALE;
3727                                 
3728                         // Convert theta back to range 0-PI
3729                         theta = (theta+1.0f)*PI/2.0f;
3730                                 
3731                         vm_quaternion_rotate(orient, theta, &rot_axis);         
3732
3733                         vm_orthogonalize_matrix(orient);                
3734                 }
3735
3736                 return bitbuffer_read_flush(&buf) + 1;
3737         }
3738 }
3739
3740
3741 // Packs/unpacks an orientation matrix.
3742 // Returns number of bytes read or written.
3743 // #define OO_ORIENT_RET_SIZE                                           6
3744 /*
3745 int multi_pack_unpack_orient( int write, ubyte *data, matrix *orient)
3746 {
3747         bitbuffer buf;
3748
3749         bitbuffer_init(&buf,data);
3750
3751         vector rot_axis;        
3752         float theta;
3753         int a, b, c, d;
3754
3755         if ( write )    {
3756
3757                 // if our heading is 3.14 radians
3758                 //angles ang;
3759                 //vm_extract_angles_matrix(&a, orient);
3760                 //if((ang.h > 3.1300) && (ang.h < 3.1500)){                     
3761                 //} else {
3762
3763                         util_matrix_to_rot_axis_and_angle(orient, &theta, &rot_axis);           
3764                         // Have theta, which is an angle between 0 and PI.
3765                         // Convert it to be between -1.0f and 1.0f
3766                         theta = theta*2.0f/PI-1.0f;
3767
3768                         #define SCALE 2048.0f
3769
3770                         #define MAX_RANGE 2047
3771                         #define MIN_RANGE -2048
3772
3773                         // -1 to 1
3774                         a = fl2i(rot_axis.xyz.x*SCALE); 
3775                         b = fl2i(rot_axis.xyz.y*SCALE);
3776                         c = fl2i(rot_axis.xyz.z*SCALE);
3777                         d = fl2i(theta*SCALE);
3778
3779                         CAP(a,MIN_RANGE,MAX_RANGE);
3780                         CAP(b,MIN_RANGE,MAX_RANGE);
3781                         CAP(c,MIN_RANGE,MAX_RANGE);
3782                         CAP(d,MIN_RANGE,MAX_RANGE);
3783                 //}
3784                 
3785                 bitbuffer_put( &buf, (uint)a, 12 );
3786                 bitbuffer_put( &buf, (uint)b, 12 );
3787                 bitbuffer_put( &buf, (uint)c, 12 );
3788                 bitbuffer_put( &buf, (uint)d, 12 );
3789
3790                 return bitbuffer_write_flush(&buf);
3791
3792         } else {
3793
3794                 a = bitbuffer_get_signed(&buf,12);
3795                 b = bitbuffer_get_signed(&buf,12);
3796                 c = bitbuffer_get_signed(&buf,12);
3797                 d = bitbuffer_get_signed(&buf,12);
3798
3799                 // special case         
3800                 rot_axis.xyz.x = i2fl(a)/SCALE;
3801                 rot_axis.xyz.y = i2fl(b)/SCALE;
3802                 rot_axis.xyz.z = i2fl(c)/SCALE;
3803                 theta = i2fl(d)/SCALE;
3804                         
3805                 // Convert theta back to range 0-PI
3806                 theta = (theta+1.0f)*PI/2.0f;
3807                         
3808                 vm_quaternion_rotate(orient, theta, &rot_axis);         
3809
3810                 vm_orthogonalize_matrix(orient);                
3811
3812                 return bitbuffer_read_flush(&buf);
3813         }
3814 }
3815 */
3816
3817 // Packs/unpacks velocity
3818 // Returns number of bytes read or written.
3819 // #define OO_VEL_RET_SIZE                                                      4
3820 int multi_pack_unpack_vel( int write, ubyte *data, matrix *orient, vector *pos, physics_info *pi)
3821 {
3822         bitbuffer buf;
3823
3824         bitbuffer_init(&buf,data);
3825
3826         int a, b, c;
3827         float r, u, f;
3828
3829         if ( write )    {
3830                 // output velocity
3831                 r = vm_vec_dot( &orient->v.rvec, &pi->vel );
3832                 u = vm_vec_dot( &orient->v.uvec, &pi->vel );
3833                 f = vm_vec_dot( &orient->v.fvec, &pi->vel );
3834
3835                 a = fl2i(r * 0.5f); 
3836                 b = fl2i(u * 0.5f);
3837                 c = fl2i(f * 0.5f);
3838                 CAP(a,-512,511);
3839                 CAP(b,-512,511);
3840                 CAP(c,-512,511);
3841                 bitbuffer_put( &buf, (uint)a, 10 );
3842                 bitbuffer_put( &buf, (uint)b, 10 );
3843                 bitbuffer_put( &buf, (uint)c, 10 );
3844
3845                 return bitbuffer_write_flush(&buf);
3846         } else {
3847                 // unpack velocity
3848                 float r, u, f;
3849                 a = bitbuffer_get_signed(&buf,10);
3850                 b = bitbuffer_get_signed(&buf,10);
3851                 c = bitbuffer_get_signed(&buf,10);
3852                 r = i2fl(a)/0.5f;
3853                 u = i2fl(b)/0.5f;
3854                 f = i2fl(c)/0.5f;
3855
3856                 // Convert into world coordinates
3857                 vm_vec_zero(&pi->vel);
3858                 vm_vec_scale_add2( &pi->vel, &orient->v.rvec, r );
3859                 vm_vec_scale_add2( &pi->vel, &orient->v.uvec, u );
3860                 vm_vec_scale_add2( &pi->vel, &orient->v.fvec, f );
3861
3862                 return bitbuffer_read_flush(&buf);
3863         }
3864 }
3865
3866 // Packs/unpacks desired_velocity
3867 // Returns number of bytes read or written.
3868 // #define OO_DESIRED_VEL_RET_SIZE                              3
3869 int multi_pack_unpack_desired_vel( int write, ubyte *data, matrix *orient, vector *pos, physics_info *pi, ship_info *sip)
3870 {
3871         bitbuffer buf;
3872
3873         bitbuffer_init(&buf,data);
3874
3875         int a;
3876         vector  max_vel;
3877         float r,u,f;
3878         int fields = 0;
3879
3880         max_vel.xyz.x = max( sip->max_vel.xyz.x, sip->afterburner_max_vel.xyz.x );
3881         max_vel.xyz.y = max( sip->max_vel.xyz.y, sip->afterburner_max_vel.xyz.y );
3882         max_vel.xyz.z = max( sip->max_vel.xyz.z, sip->afterburner_max_vel.xyz.z );      
3883
3884         if ( write )    {
3885                 // Find desired vel in local coordinates
3886                 // Velocity can be from -1024 to 1024
3887
3888                 // bitfields for each value             
3889                 if(max_vel.xyz.x > 0.0f){
3890                         fields |= (1<<0);
3891                 }
3892                 if(max_vel.xyz.y > 0.0f){
3893                         fields |= (1<<1);
3894                 }
3895                 if(max_vel.xyz.z > 0.0f){
3896                         fields |= (1<<2);
3897                 }               
3898                 // fields = sip - Ship_info;
3899                 bitbuffer_put(&buf, (uint)fields, 8);
3900
3901                 r = vm_vec_dot( &orient->v.rvec, &pi->desired_vel );
3902                 u = vm_vec_dot( &orient->v.uvec, &pi->desired_vel );
3903                 f = vm_vec_dot( &orient->v.fvec, &pi->desired_vel );
3904
3905                 if ( max_vel.xyz.x > 0.0f )     {
3906                         r = r / max_vel.xyz.x;
3907                         a = fl2i( r * 128.0f );
3908                         CAP(a,-128, 127 );                      
3909                         bitbuffer_put( &buf, (uint)a, 8 );                      
3910                 } 
3911
3912                 if ( max_vel.xyz.y > 0.0f )     {
3913                         u = u / max_vel.xyz.y;
3914                         a = fl2i( u * 128.0f );
3915                         CAP(a,-128, 127 );
3916                         bitbuffer_put( &buf, (uint)a, 8 );
3917                 } 
3918
3919                 if ( max_vel.xyz.z > 0.0f )     {
3920                         f = f / max_vel.xyz.z;
3921                         a = fl2i( f * 128.0f );
3922                         CAP(a,-128, 127 );
3923                         bitbuffer_put( &buf, (uint)a, 8 );
3924                 }
3925
3926                 return bitbuffer_write_flush(&buf);
3927         } else {
3928
3929                 // Find desired vel in local coordinates
3930                 // Velocity can be from -1024 to 1024
3931
3932                 // get the fields bitbuffer
3933                 fields = bitbuffer_get_signed(&buf, 8);
3934                 
3935                 if ( fields & (1<<0) )  {
3936                         a = bitbuffer_get_signed(&buf,8);
3937                         r = i2fl(a)/128.0f;
3938                 } else {
3939                         r = 0.0f;
3940                 }
3941                 
3942                 if ( fields & (1<<1) )  {
3943                         a = bitbuffer_get_signed(&buf,8);
3944                         u = i2fl(a)/128.0f;
3945                 } else {
3946                         u = 0.0f;
3947                 }
3948                 
3949                 if ( fields & (1<<2) )  {
3950                         a = bitbuffer_get_signed(&buf,8);
3951                         f = i2fl(a)/128.0f;
3952                 } else {
3953                         f = 0.0f;
3954                 }               
3955                 
3956                 // Convert into world coordinates
3957                 vm_vec_zero(&pi->vel);
3958                 vm_vec_scale_add2( &pi->desired_vel, &orient->v.rvec, r*max_vel.xyz.x );
3959                 vm_vec_scale_add2( &pi->desired_vel, &orient->v.uvec, u*max_vel.xyz.y );
3960                 vm_vec_scale_add2( &pi->desired_vel, &orient->v.fvec, f*max_vel.xyz.z );
3961
3962                 return bitbuffer_read_flush(&buf);
3963         }
3964 }
3965
3966 // Packs/unpacks rotational velocity
3967 // Returns number of bytes read or written.
3968 // #define OO_ROTVEL_RET_SIZE                                           4
3969 int multi_pack_unpack_rotvel( int write, ubyte *data, matrix *orient, vector *pos, physics_info *pi)
3970 {
3971         bitbuffer buf;
3972
3973         bitbuffer_init(&buf,data);
3974
3975         int a, b, c;
3976
3977         if ( write )    {
3978                 // output rotational velocity
3979                 a = fl2i(pi->rotvel.xyz.x*32.0f); 
3980                 b = fl2i(pi->rotvel.xyz.y*32.0f);
3981                 c = fl2i(pi->rotvel.xyz.z*32.0f);
3982                 CAP(a,-512,511);
3983                 CAP(b,-512,511);
3984                 CAP(c,-512,511);
3985                 bitbuffer_put( &buf, (uint)a, 10 );
3986                 bitbuffer_put( &buf, (uint)b, 10 );
3987                 bitbuffer_put( &buf, (uint)c, 10 );
3988
3989
3990                 return bitbuffer_write_flush(&buf);
3991
3992         } else {
3993
3994                 // unpack rotational velocity
3995                 a = bitbuffer_get_signed(&buf,10);
3996                 b = bitbuffer_get_signed(&buf,10);
3997                 c = bitbuffer_get_signed(&buf,10);
3998                 pi->rotvel.xyz.x = i2fl(a)/32.0f;
3999                 pi->rotvel.xyz.y = i2fl(b)/32.0f;
4000                 pi->rotvel.xyz.z = i2fl(c)/32.0f;
4001
4002                 return bitbuffer_read_flush(&buf);
4003         }
4004 }
4005
4006 // Packs/unpacks desired rotvel
4007 // Returns number of bytes read or written.
4008 // #define OO_DESIRED_ROTVEL_RET_SIZE                   3
4009 int multi_pack_unpack_desired_rotvel( int write, ubyte *data, matrix *orient, vector *pos, physics_info *pi, ship_info *sip)
4010 {
4011         bitbuffer buf;
4012         int fields = 0;
4013
4014         bitbuffer_init(&buf,data);
4015
4016         int a;
4017         float r,u,f;
4018
4019         if ( write )    {
4020                 // use ship_info values for max_rotvel instead of taking it from physics info
4021
4022                 // bitfields for each value
4023                 if(sip->max_rotvel.xyz.x > 0.0f){
4024                         fields |= (1<<0);
4025                 }
4026                 if(sip->max_rotvel.xyz.y > 0.0f){
4027                         fields |= (1<<1);
4028                 }
4029                 if(sip->max_rotvel.xyz.z > 0.0f){
4030                         fields |= (1<<2);
4031
4032                 }
4033                 bitbuffer_put(&buf, (uint)fields, 8);
4034
4035                 // output desired rotational velocity as a percent of max               
4036                 if ( sip->max_rotvel.xyz.x > 0.0f )     {               
4037                         a = fl2i( pi->desired_rotvel.xyz.x*128.0f / sip->max_rotvel.xyz.x );
4038                         CAP(a,-128, 127 );
4039                         bitbuffer_put( &buf, (uint)a, 8 );
4040                 } 
4041
4042                 if ( sip->max_rotvel.xyz.y > 0.0f )     {               
4043                         a = fl2i( pi->desired_rotvel.xyz.y*128.0f / sip->max_rotvel.xyz.y );
4044                         CAP(a,-128, 127 );
4045                         bitbuffer_put( &buf, (uint)a, 8 );
4046                 } 
4047
4048                 if ( sip->max_rotvel.xyz.z > 0.0f )     {               
4049                         a = fl2i( pi->desired_rotvel.xyz.z*128.0f / sip->max_rotvel.xyz.z );
4050                         CAP(a,-128, 127 );
4051                         bitbuffer_put( &buf, (uint)a, 8 );
4052                 } 
4053
4054                 return bitbuffer_write_flush(&buf);
4055         } else {
4056                 fields = bitbuffer_get_signed(&buf, 8);
4057
4058                 // unpack desired rotational velocity
4059                 if ( fields & (1<<0) )  {               
4060                         a = bitbuffer_get_signed(&buf,8);
4061                         r = i2fl(a)/128.0f;
4062                 } else {
4063                         r = 0.0f;
4064                 }
4065                 if ( fields & (1<<1) )  {               
4066                         a = bitbuffer_get_signed(&buf,8);
4067                         u = i2fl(a)/128.0f;
4068                 } else {
4069                         u = 0.0f;
4070                 }
4071                 if ( fields & (1<<2) )  {               
4072                         a = bitbuffer_get_signed(&buf,8);
4073                         f = i2fl(a)/128.0f;
4074                 } else {
4075                         f = 0.0f;
4076                 }
4077                 pi->desired_rotvel.xyz.x = r*sip->max_rotvel.xyz.x;
4078                 pi->desired_rotvel.xyz.y = u*sip->max_rotvel.xyz.y;
4079                 pi->desired_rotvel.xyz.z = f*sip->max_rotvel.xyz.z;
4080
4081                 return bitbuffer_read_flush(&buf);
4082         }
4083 }
4084
4085 #ifndef PLAT_UNIX
4086 #pragma optimize("", on)
4087 #endif