]> icculus.org git repositories - btb/d2x.git/blob - main/network.c
SDL Joystick works\!
[btb/d2x.git] / main / network.c
1 /*
2 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
3 SOFTWARE CORPORATION ("PARALLAX").  PARALLAX, IN DISTRIBUTING THE CODE TO
4 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
5 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
6 IN USING, DISPLAYING,  AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
7 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
8 FREE PURPOSES.  IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
9 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES.  THE END-USER UNDERSTANDS
10 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.  
11 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION.  ALL RIGHTS RESERVED.
12 */
13
14 /*
15  * $Source: /cvs/cvsroot/d2x/main/network.c,v $
16  * $Revision: 1.8 $
17  * $Author: bradleyb $
18  * $Date: 2002-02-14 09:24:19 $
19  *
20  * FIXME: put description here
21  *
22  * $Log: not supported by cvs2svn $
23  * Revision 1.7  2002/02/13 10:39:21  bradleyb
24  * Lotsa networking stuff from d1x
25  *
26  * Revision 1.6  2001/10/23 22:03:03  bradleyb
27  * No longer #ifdef'ing out the whole file.  RCS header added
28  *
29  *
30  */
31
32 #ifdef HAVE_CONFIG_H
33 #include <conf.h>
34 #endif
35
36 #define PATCH12
37
38 #include <stdio.h>
39 #include <string.h>
40 #include <stdlib.h>
41
42 #include "pstypes.h"
43 #include "strutil.h"
44 #include "args.h"
45 #include "timer.h"
46 #include "mono.h"
47 #include "ipx.h"
48 #include "newmenu.h"
49 #include "key.h"
50 #include "gauges.h"
51 #include "object.h"
52 #include "error.h"
53 #include "laser.h"
54 #include "gamesave.h"
55 #include "gamemine.h"
56 #include "player.h"
57 #include "gameseq.h"
58 #include "fireball.h"
59 #include "network.h"
60 #include "game.h"
61 #include "multi.h"
62 #include "endlevel.h"
63 #include "palette.h"
64 #include "cntrlcen.h"
65 #include "powerup.h"
66 #include "menu.h"
67 #include "sounds.h"
68 #include "text.h"
69 #include "kmatrix.h"
70 #include "newdemo.h"
71 #include "multibot.h"
72 #include "wall.h"
73 #include "bm.h"
74 #include "effects.h"
75 #include "physics.h"
76 #include "switch.h"
77 #include "automap.h"
78 #include "byteswap.h"
79 #include "netmisc.h"
80 #include "kconfig.h"
81 #include "playsave.h"
82
83 #ifdef MACINTOSH
84 #include <Events.h>
85 #include <Errors.h>             // for appletalk networking errors
86 #include "appltalk.h"
87 #endif
88
89 void network_send_rejoin_sync(int player_num);
90 void network_update_netgame(void);
91 void network_read_endlevel_packet( ubyte *data );
92 void network_read_object_packet( ubyte *data );
93 void network_read_sync_packet( netgame_info * sp, int d1x );
94 void network_flush();
95 void network_listen();
96 void network_read_pdata_packet(frame_info *pd );
97
98 void network_check_for_old_version (char pnum);
99 void network_send_endlevel_short_sub(int from_player_num,int to_player);
100 int network_wait_for_playerinfo();
101 void network_process_pdata (char *data);
102 void network_read_endlevel_short_packet( ubyte *data );
103 void network_ping (ubyte flag,int pnum);
104 void network_handle_ping_return (ubyte pnum);
105 void network_process_names_return (char *data);
106 void network_send_player_names (sequence_packet *their);
107 int network_choose_connect ();
108 void network_more_game_options ();
109 void network_count_powerups_in_mine(void);
110 int network_wait_for_all_info (int choice);
111 void network_do_big_wait(int choice);
112 void network_send_extras ();
113 void network_read_pdata_short_packet(short_frame_info *pd );
114
115 void network_AdjustMaxDataSize ();
116
117 void ClipRank (signed char *rank);
118 void DoRefuseStuff (sequence_packet *their);
119 void SetAllAllowablesTo (int on);
120 int GetNewPlayerNumber (sequence_packet *their);
121
122 #define LHX(x)          ((x)*(MenuHires?2:1))
123 #define LHY(y)          ((y)*(MenuHires?2.4:1))
124
125 #define NETSECURITY_OFF 0
126 #define NETSECURITY_WAIT_FOR_PLAYERS 1
127 #define NETSECURITY_WAIT_FOR_GAMEINFO 2
128 #define NETSECURITY_WAIT_FOR_SYNC 3
129
130 // MWA -- these structures are aligned -- please save me sanity and
131 // headaches by keeping alignment if these are changed!!!!  Contact
132 // me for info.
133
134 typedef struct endlevel_info_short {
135         ubyte                                   type;
136         ubyte                                   player_num;
137         byte                                    connected;
138         ubyte                                   seconds_left;
139 } endlevel_info_short;
140
141 // WARNING!!! This is the top part of netgame_info...if that struct changes,
142 //      this struct much change as well.  ie...they are aligned and the join system will
143 // not work without it.
144
145 // MWA  if this structure changes -- please make appropriate changes to receive_netgame_info
146 // code for macintosh in netmisc.c
147
148 typedef struct lite_info {
149         ubyte                           type;
150         int                             Security;
151         char                            game_name[NETGAME_NAME_LEN+1];
152         char                            mission_title[MISSION_NAME_LEN+1];
153         char                            mission_name[9];
154         int                             levelnum;
155         ubyte                           gamemode;
156         ubyte                           RefusePlayers;
157         ubyte                           difficulty;
158         ubyte                           game_status;
159         ubyte                           numplayers;
160         ubyte                           max_numplayers;
161         ubyte                           numconnected;
162         ubyte                           game_flags;
163         ubyte                           protocol_version;
164         ubyte                           version_major;
165         ubyte                           version_minor;
166         ubyte                           team_vector;
167  } lite_info;
168
169 // IF YOU CHANGE THE SIZE OF ANY OF THE FOLLOWING STRUCTURES
170 // MAKE THE MACINTOSH DEFINES BE THE SAME SIZE AS THE PC OR
171 // I WILL HAVE TO HURT YOU VERY BADLY!!!  -- MWA
172
173 #ifdef MACINTOSH
174 #define NETGAME_INFO_SIZE               ( Network_game_type == IPX_GAME?355:sizeof(netgame_info) )
175 #define ALLNETPLAYERSINFO_SIZE  ( Network_game_type == IPX_GAME?317:sizeof(AllNetPlayers_info) )
176 #define LITE_INFO_SIZE                  ( Network_game_type == IPX_GAME?72:sizeof(lite_info) )
177 #define SEQUENCE_PACKET_SIZE    ( Network_game_type == IPX_GAME?34:sizeof(sequence_packet) )
178 #define FRAME_INFO_SIZE                 ( Network_game_type == IPX_GAME?541:sizeof(frame_info) )
179 #define IPX_SHORT_INFO_SIZE             ( 490 )
180 #else
181 #define NETGAME_INFO_SIZE               sizeof(netgame_info)
182 #define ALLNETPLAYERSINFO_SIZE  sizeof(AllNetPlayers_info)
183 #define LITE_INFO_SIZE                  sizeof(lite_info)
184 #define SEQUENCE_PACKET_SIZE    sizeof(sequence_packet)
185 #define FRAME_INFO_SIZE                 sizeof(frame_info)
186 #endif
187
188 #define MAX_ACTIVE_NETGAMES     12
189
190 netgame_info Active_games[MAX_ACTIVE_NETGAMES];
191 AllNetPlayers_info ActiveNetPlayers[MAX_ACTIVE_NETGAMES];
192 AllNetPlayers_info *TempPlayersInfo,TempPlayersBase;
193 int NamesInfoSecurity=-1;
194
195 // MWAnetgame_info *TempNetInfo; 
196 netgame_info TempNetInfo;
197
198 extern void multi_send_drop_marker (int player,vms_vector position,char messagenum,char text[]);
199 extern void multi_send_kill_goal_counts();
200 extern int newmenu_dotiny( char * title, char * subtitle, int nitems, newmenu_item * item, void (*subfunction)(int nitems,newmenu_item * items, int * last_key, int citem) );
201
202 void network_process_naked_pdata (char *,int);
203 extern void multi_send_robot_controls(char);
204
205 int num_active_games = 0;
206 int PacketsPerSec=10;
207 int MaxXDataSize=NET_XDATA_SIZE;
208
209 int       Netlife_kills=0, Netlife_killed=0;
210
211 int     Network_debug=0;
212 int     Network_active=0;
213
214 int     Network_status = 0;
215 int     Network_games_changed = 0;
216
217 int     Network_socket = 0;
218 int     Network_allow_socket_changes = 1;
219
220 int     Network_initial_pps = 10;
221 int     Network_initial_shortpackets = 0;
222
223 int     NetSecurityFlag=NETSECURITY_OFF;
224 int     NetSecurityNum=0;
225 int       Network_sending_extras=0;
226 int      VerifyPlayerJoined=-1;
227 int       Player_joining_extras=-1;  // This is so we know who to send 'latecomer' packets to.
228                                                                                           // We could just send updates to everyone but that kills the sender!   
229
230 // For rejoin object syncing
231
232 int     Network_rejoined = 0;       // Did WE rejoin this game?
233 int     Network_new_game = 0;            // Is this the first level of a new game?
234 int     Network_send_objects = 0;  // Are we in the process of sending objects to a player?
235 int     Network_send_objnum = -1;   // What object are we sending next?
236 int     Network_player_added = 0;   // Is this a new player or a returning player?
237 int     Network_send_object_mode = 0; // What type of objects are we sending, static or dynamic?
238 sequence_packet Network_player_rejoining; // Who is rejoining now?
239
240 fix     LastPacketTime[MAX_PLAYERS]; // For timeouts of idle/crashed players
241
242 int     PacketUrgent = 0;
243 int   NetGameType=0;
244 int     TotalMissedPackets=0,TotalPacketsGot=0;
245
246 frame_info      MySyncPack,UrgentSyncPack;
247 ubyte           MySyncPackInitialized = 0;              // Set to 1 if the MySyncPack is zeroed.
248 ushort          my_segments_checksum = 0;
249
250 sequence_packet My_Seq;
251 char WantPlayersInfo=0;
252 char WaitingForPlayerInfo=0;
253
254 char *RankStrings[]={"(unpatched) ","Cadet ","Ensign ","Lieutenant ","Lt.Commander ",
255                                                                 "Commander ","Captain ","Vice Admiral ","Admiral ","Demigod "};
256
257 extern obj_position Player_init[MAX_PLAYERS];
258
259 extern int force_cockpit_redraw;
260
261 #define DUMP_CLOSED 0
262 #define DUMP_FULL 1
263 #define DUMP_ENDLEVEL 2
264 #define DUMP_DORK 3
265 #define DUMP_ABORTED 4
266 #define DUMP_CONNECTED 5
267 #define DUMP_LEVEL 6
268 #define DUMP_KICKED 7
269
270 extern ubyte Version_major,Version_minor;
271 extern ubyte SurfingNet;
272 extern char MaxPowerupsAllowed[MAX_POWERUP_TYPES];
273 extern char PowerupsInMine[MAX_POWERUP_TYPES];
274
275 extern void multi_send_stolen_items();
276
277 int network_wait_for_snyc();
278 extern void multi_send_wall_status (int,ubyte,ubyte,ubyte);
279 extern void multi_send_wall_status_specific (int,int,ubyte,ubyte,ubyte);
280
281 extern void game_disable_cheats();
282
283 char IWasKicked=0;
284 FILE *SendLogFile,*RecieveLogFile;
285 int TTSent[100],TTRecv[100];
286
287 extern int Final_boss_is_dead;
288
289 // following is network stuff for appletalk
290
291 void network_dump_appletalk_player(ubyte node, ushort net, ubyte socket, int why);
292
293 #define NETWORK_OEM 0x10
294
295 #ifdef MACINTOSH
296
297 int Network_game_type;                                  // used to tell IPX vs. appletalk games
298
299 #define MAX_ZONES                       255
300 #define MAX_ZONE_LENGTH         33
301 #define DEFAULT_ZONE_NAME       "\p*"
302 #define MAX_REGISTER_TRIES      5                                       // maximum time we will try and register a netgame
303 char Network_zone_name[MAX_ZONE_LENGTH];                // zone name game being played in for appletalk
304 char Zone_names[MAX_ZONES][MAX_ZONE_LENGTH];    // total list of zones that we can see
305 ubyte appletalk_use_broadcast = 0;
306 ubyte Network_game_validated = 0;               // validates a game before being able to join
307 ubyte Network_game_validate_choice = 0;
308 ubyte Network_appletalk_type = 0;               // type of appletalk network game is being played on
309
310 #define ETHERTALK_TYPE  0
311 #define LOCALTALK_TYPE  1
312 #define OTHERTALK_TYPE  2
313
314
315 void network_release_registered_game(void);
316
317 #endif
318
319 void
320 network_init(void)
321 {
322   
323         // So you want to play a netgame, eh?  Let's a get a few things
324         // straight
325
326    int t;
327         int save_pnum = Player_num;
328
329         game_disable_cheats();
330    IWasKicked=0;
331    Final_boss_is_dead=0;
332    NamesInfoSecurity=-1;
333
334
335    #ifdef NETPROFILING
336            OpenSendLog();
337                 OpenRecieveLog(); 
338         #endif
339         
340         for (t=0;t<MAX_POWERUP_TYPES;t++)
341                 {
342                         MaxPowerupsAllowed[t]=0;
343                         PowerupsInMine[t]=0;
344                 }
345
346    TotalMissedPackets=0; TotalPacketsGot=0;
347
348         memset(&Netgame, 0, sizeof(netgame_info));
349         memset(&NetPlayers,0,sizeof(AllNetPlayers_info));
350         memset(&My_Seq, 0, sizeof(sequence_packet));
351         My_Seq.type = PID_REQUEST;
352         memcpy(My_Seq.player.callsign, Players[Player_num].callsign, CALLSIGN_LEN+1);
353
354    #if defined (D2_OEM)
355            Version_minor|=NETWORK_OEM;
356         #endif
357  
358         My_Seq.player.version_major=Version_major;
359         My_Seq.player.version_minor=Version_minor;
360    My_Seq.player.rank=GetMyNetRanking();        
361  
362         if (Network_game_type == IPX_GAME) {
363                 memcpy(My_Seq.player.network.ipx.node, ipx_get_my_local_address(), 6);
364                 memcpy(My_Seq.player.network.ipx.server, ipx_get_my_server_address(), 4 );
365         #ifdef MACINTOSH
366         } else {
367                 My_Seq.player.network.appletalk.node = appletalk_get_my_node();
368                 My_Seq.player.network.appletalk.net = appletalk_get_my_net();
369                 My_Seq.player.network.appletalk.socket = appletalk_get_my_socket();
370         #endif
371         }
372 #ifdef MACINTOSH
373         My_Seq.player.computer_type = MAC;
374 #else
375         My_Seq.player.computer_type = DOS;
376 #endif
377
378         for (Player_num = 0; Player_num < MAX_NUM_NET_PLAYERS; Player_num++)
379                 init_player_stats_game();
380
381         Player_num = save_pnum;         
382         multi_new_game();
383         Network_new_game = 1;
384         Control_center_destroyed = 0;
385         network_flush();
386
387         Netgame.PacketsPerSec=10;
388
389    if ((t=FindArg("-packets")))
390     {
391      Netgame.PacketsPerSec=atoi(Args[t+1]);
392      if (Netgame.PacketsPerSec<1)
393       Netgame.PacketsPerSec=1;
394      else if (Netgame.PacketsPerSec>20)
395       Netgame.PacketsPerSec=20;
396      mprintf ((0,"Will send %d packets per second",Netgame.PacketsPerSec));
397     }
398    if (FindArg("-shortpackets"))
399     {
400      Netgame.ShortPackets=1;
401      mprintf ((0,"Will send short packets.\n"));
402     }
403 }
404
405 int
406 network_i_am_master(void)
407 {
408         // I am the lowest numbered player in this game?
409
410         int i;
411
412         if (!(Game_mode & GM_NETWORK))
413                 return (Player_num == 0);
414
415         for (i = 0; i < Player_num; i++)
416                 if (Players[i].connected)
417                         return 0;
418         return 1;
419 }
420 int
421 network_who_is_master(void)
422 {
423         // Who is the master of this game?
424
425         int i;
426
427         if (!(Game_mode & GM_NETWORK))
428                 return (Player_num == 0);
429
430         for (i = 0; i < N_players; i++)
431                 if (Players[i].connected)
432                         return i;
433         return Player_num;
434 }
435 int network_how_many_connected()
436  {
437   int num=0,i;
438  
439         for (i = 0; i < N_players; i++)
440                 if (Players[i].connected)
441                         num++;
442    return (num);
443  }
444
445 #define ENDLEVEL_SEND_INTERVAL (F1_0*2)
446 #define ENDLEVEL_IDLE_TIME      (F1_0*20)
447 /*      
448 void 
449 network_endlevel_poll( int nitems, newmenu_item * menus, int * key, int citem )
450 {
451         // Polling loop for End-of-level menu
452
453         static fix t1 = 0;
454         int i = 0;
455         int num_ready = 0;
456         int num_escaped = 0;
457         int goto_secret = 0;
458
459         int previous_state[MAX_NUM_NET_PLAYERS];
460         int previous_seconds_left;
461
462         menus = menus;
463         citem = citem;
464         nitems = nitems;
465         key = key;
466
467         // Send our endlevel packet at regular intervals
468
469         if (timer_get_approx_seconds() > (t1+ENDLEVEL_SEND_INTERVAL))
470         {
471                 network_send_endlevel_packet();
472                 t1 = timer_get_approx_seconds();
473         }
474
475         for (i = 0; i < N_players; i++)
476                 previous_state[i] = Players[i].connected;
477
478         previous_seconds_left = Countdown_seconds_left;
479
480         network_listen();
481
482         for (i = 0; i < N_players; i++)
483         {
484                 if (Players[i].connected == 1)
485                 {
486                         // Check timeout for idle players
487                         if (timer_get_approx_seconds() > LastPacketTime[i]+ENDLEVEL_IDLE_TIME)
488                         {
489                                 mprintf((0, "idle timeout for player %d.\n", i));
490                                 Players[i].connected = 0;
491                                 network_send_endlevel_sub(i);
492                         }                               
493                 }
494
495                 if ((Players[i].connected != 1) && (Players[i].connected != 5) && (Players[i].connected != 6))
496                         num_ready++;
497                 if (Players[i].connected != 1)
498                         num_escaped++;
499                 if (Players[i].connected == 4)
500                         goto_secret = 1;
501         }
502
503         if (num_escaped == N_players) // All players are out of the mine
504         {
505                 Countdown_seconds_left = -1;
506         }
507
508
509         if (num_ready == N_players) // All players have checked in or are disconnected
510         {
511                 if (goto_secret)
512                         *key = -3;
513                 else
514                         *key = -2;
515         }
516 } */
517   
518 void 
519 network_endlevel_poll2( int nitems, newmenu_item * menus, int * key, int citem )
520 {
521         // Polling loop for End-of-level menu
522
523         static fix t1 = 0;
524         int i = 0;
525         int num_ready = 0;
526         int goto_secret = 0;
527
528         menus = menus;
529         citem = citem;
530         nitems = nitems;
531         key = key;
532
533         // Send our endlevel packet at regular intervals
534
535         if (timer_get_approx_seconds() > (t1+ENDLEVEL_SEND_INTERVAL))
536         {
537                 network_send_endlevel_packet();
538                 t1 = timer_get_approx_seconds();
539         }
540
541 //   mprintf ((0,"Trying to listen!\n"));
542         network_listen();
543
544         for (i = 0; i < N_players; i++)
545         {
546                 if ((Players[i].connected != 1) && (Players[i].connected != 5) && (Players[i].connected != 6))
547                         num_ready++;
548                 if (Players[i].connected == 4)
549                         goto_secret = 1;                                        
550         }
551
552         if (num_ready == N_players) // All players have checked in or are disconnected
553         {
554                 if (goto_secret)
555                         *key = -3;
556                 else
557                         *key = -2;
558         }
559 }
560
561
562 extern fix StartAbortMenuTime;
563
564 void 
565 network_endlevel_poll3( int nitems, newmenu_item * menus, int * key, int citem )
566 {
567         // Polling loop for End-of-level menu
568
569    int num_ready=0,i;
570  
571         menus = menus;
572         citem = citem;
573         nitems = nitems;
574         key = key;
575
576         if (timer_get_approx_seconds() > (StartAbortMenuTime+(F1_0 * 8)))
577     *key=-2;
578
579
580         network_listen();
581
582
583         for (i = 0; i < N_players; i++)
584                 if ((Players[i].connected != 1) && (Players[i].connected != 5) && (Players[i].connected != 6))
585                         num_ready++;
586
587         if (num_ready == N_players) // All players have checked in or are disconnected
588                         *key = -2;
589
590 }
591
592
593 int
594 network_endlevel(int *secret)
595 {
596         // Do whatever needs to be done between levels
597
598    int i;
599
600    *secret=0;
601
602         //network_flush();
603
604         Network_status = NETSTAT_ENDLEVEL; // We are between levels
605
606         network_listen();
607
608         network_send_endlevel_packet();
609
610         for (i=0; i<N_players; i++) 
611         {
612                 LastPacketTime[i] = timer_get_approx_seconds();
613         }
614    
615         network_send_endlevel_packet();
616         network_send_endlevel_packet();
617         MySyncPackInitialized = 0;
618
619         network_update_netgame();
620
621         return(0);
622 }
623
624 int 
625 can_join_netgame(netgame_info *game,AllNetPlayers_info *people)
626 {
627         // Can this player rejoin a netgame in progress?
628
629         int i, num_players;
630
631         if (game->game_status == NETSTAT_STARTING)
632      return 1;
633
634         if (game->game_status != NETSTAT_PLAYING)
635     {
636       mprintf ((0,"Error: Can't join because game_status !=NETSTAT_PLAYING\n"));
637                 return 0;
638     }
639
640    if (game->version_major==0 && Version_major>0)
641     {
642            mprintf ((0,"Error:Can't join because version majors don't match!\n"));
643                 return (0);
644     }
645
646         if (game->version_major>0 && Version_major==0)
647     {
648            mprintf ((0,"Error:Can't join because version majors2 don't match!\n"));
649                 return (0);
650     }
651
652         // Game is in progress, figure out if this guy can re-join it
653
654         num_players = game->numplayers;
655
656         if (!(game->game_flags & NETGAME_FLAG_CLOSED)) {
657                 // Look for player that is not connected
658                 
659                 if (game->numconnected==game->max_numplayers)
660                  return (2);
661
662 //      mprintf ((0,"Refuse = %d\n",game->RefusePlayers));
663                 
664                 if (game->RefusePlayers)
665                  return (3);
666                 
667                 if (game->numplayers < game->max_numplayers)
668                         return 1;
669
670                 if (game->numconnected<num_players)
671                         return 1;
672                      
673         }
674
675         if (people==NULL)
676     {
677       mprintf ((0,"Error! Can't join because people==NULL!\n"));
678                 return 0;
679     }
680         
681         // Search to see if we were already in this closed netgame in progress
682
683         for (i = 0; i < num_players; i++) {
684                 if (Network_game_type == IPX_GAME) {
685                         if ( (!stricmp(Players[Player_num].callsign, people->players[i].callsign)) &&
686                                   (!memcmp(My_Seq.player.network.ipx.node, people->players[i].network.ipx.node, 6)) &&
687                                   (!memcmp(My_Seq.player.network.ipx.server, people->players[i].network.ipx.server, 4)) )
688                                 break;
689                 } else {
690                         if ( (!stricmp(Players[Player_num].callsign, people->players[i].callsign)) &&
691                                   (My_Seq.player.network.appletalk.node == people->players[i].network.appletalk.node) &&
692                                   (My_Seq.player.network.appletalk.net == people->players[i].network.appletalk.net) )
693                                 break;
694                 }
695         }
696
697         if (i != num_players)
698                 return 1;
699  
700    mprintf ((0,"Error: Can't join because at end of list!\n"));
701         return 0;
702 }
703
704 void
705 network_disconnect_player(int playernum)
706 {
707         // A player has disconnected from the net game, take whatever steps are
708         // necessary 
709
710         if (playernum == Player_num) 
711         {
712                 Int3(); // Weird, see Rob
713                 return;
714         }
715
716         Players[playernum].connected = 0;
717    NetPlayers.players[playernum].connected = 0;
718    if (VerifyPlayerJoined==playernum)
719           VerifyPlayerJoined=-1;
720
721 //      create_player_appearance_effect(&Objects[Players[playernum].objnum]);
722         multi_make_player_ghost(playernum);
723
724         if (Newdemo_state == ND_STATE_RECORDING)
725                 newdemo_record_multi_disconnect(playernum);
726
727         multi_strip_robots(playernum);
728 }
729                 
730 void
731 network_new_player(sequence_packet *their)
732 {
733         int objnum;
734         int pnum;
735
736         pnum = their->player.connected;
737
738         Assert(pnum >= 0);
739         Assert(pnum < MaxNumNetPlayers);        
740         
741         objnum = Players[pnum].objnum;
742
743         if (Newdemo_state == ND_STATE_RECORDING) {
744                 int new_player;
745
746                 if (pnum == N_players)
747                         new_player = 1;
748                 else
749                         new_player = 0;
750                 newdemo_record_multi_connect(pnum, new_player, their->player.callsign);
751         }
752
753         memcpy(Players[pnum].callsign, their->player.callsign, CALLSIGN_LEN+1);
754         memcpy(NetPlayers.players[pnum].callsign, their->player.callsign, CALLSIGN_LEN+1);
755         
756
757    ClipRank (&their->player.rank);
758    NetPlayers.players[pnum].rank=their->player.rank;
759         NetPlayers.players[pnum].version_major=their->player.version_major;
760         NetPlayers.players[pnum].version_minor=their->player.version_minor;
761    network_check_for_old_version(pnum);
762
763         if (Network_game_type == IPX_GAME) {
764                 if ( (*(uint *)their->player.network.ipx.server) != 0 )
765                         ipx_get_local_target( their->player.network.ipx.server, their->player.network.ipx.node, Players[pnum].net_address );
766                 else
767                         memcpy(Players[pnum].net_address, their->player.network.ipx.node, 6);
768         
769                 memcpy(NetPlayers.players[pnum].network.ipx.node, their->player.network.ipx.node, 6);
770                 memcpy(NetPlayers.players[pnum].network.ipx.server, their->player.network.ipx.server, 4);
771         } else {
772                 NetPlayers.players[pnum].network.appletalk.node = their->player.network.appletalk.node;
773                 NetPlayers.players[pnum].network.appletalk.net = their->player.network.appletalk.net;
774                 NetPlayers.players[pnum].network.appletalk.socket = their->player.network.appletalk.socket;
775         }
776
777         Players[pnum].n_packets_got = 0;
778         Players[pnum].connected = 1;
779         Players[pnum].net_kills_total = 0;
780         Players[pnum].net_killed_total = 0;
781         memset(kill_matrix[pnum], 0, MAX_PLAYERS*sizeof(short)); 
782         Players[pnum].score = 0;
783         Players[pnum].flags = 0;
784         Players[pnum].KillGoalCount=0;
785
786         if (pnum == N_players)
787         {
788                 N_players++;
789                 Netgame.numplayers = N_players;
790         }
791
792         digi_play_sample(SOUND_HUD_MESSAGE, F1_0);
793
794    ClipRank (&their->player.rank);
795    
796    if (FindArg("-norankings"))
797           HUD_init_message("'%s' %s\n",their->player.callsign, TXT_JOINING);
798    else   
799      HUD_init_message("%s'%s' %s\n",RankStrings[their->player.rank],their->player.callsign, TXT_JOINING);
800         
801         multi_make_ghost_player(pnum);
802
803         multi_send_score();
804         multi_sort_kill_list();
805
806 //      create_player_appearance_effect(&Objects[objnum]);
807 }
808
809 char RefuseThisPlayer=0,WaitForRefuseAnswer=0,RefuseTeam;
810 char RefusePlayerName[12];
811 fix RefuseTimeLimit=0;
812
813 void network_welcome_player(sequence_packet *their)
814 {
815         // Add a player to a game already in progress
816         ubyte local_address[6];
817         int player_num;
818         int i;
819
820    WaitForRefuseAnswer=0;
821
822         if (FindArg("-NoMatrixCheat"))
823         {
824                 if (their->player.version_minor & (0x0F<3))
825                 {
826                                         network_dump_player(their->player.network.ipx.server, their->player.network.ipx.node, DUMP_DORK);
827                                         return;
828                 }
829         }
830
831         if (HoardEquipped())
832         {
833    // If hoard game, and this guy isn't D2 Christmas (v1.2), dump him
834
835            if ((Game_mode & GM_HOARD) && ((their->player.version_minor & 0x0F)<2))
836                 {
837                         if (Network_game_type == IPX_GAME)
838                                 network_dump_player(their->player.network.ipx.server, their->player.network.ipx.node, DUMP_DORK);
839                         #ifdef MACINTOSH
840                         else
841                                 network_dump_appletalk_player(their->player.network.appletalk.node, their->player.network.appletalk.net, their->player.network.appletalk.socket, DUMP_DORK);
842                         #endif
843                         return;
844                 }
845         }
846
847         // Don't accept new players if we're ending this level.  Its safe to
848         // ignore since they'll request again later
849
850         if ((Endlevel_sequence) || (Control_center_destroyed))
851         {
852                 mprintf((0, "Ignored request from new player to join during endgame.\n"));
853                 if (Network_game_type == IPX_GAME)
854                         network_dump_player(their->player.network.ipx.server,their->player.network.ipx.node, DUMP_ENDLEVEL);
855                 #ifdef MACINTOSH
856                 else
857                         network_dump_appletalk_player(their->player.network.appletalk.node, their->player.network.appletalk.net, their->player.network.appletalk.socket, DUMP_ENDLEVEL);
858                 #endif
859                 return; 
860         }
861
862         if (Network_send_objects || Network_sending_extras)
863         {
864                 // Ignore silently, we're already responding to someone and we can't
865                 // do more than one person at a time.  If we don't dump them they will
866                 // re-request in a few seconds.
867                 return;
868         }
869
870         if (their->player.connected != Current_level_num)
871         {
872                 mprintf((0, "Dumping player due to old level number.\n"));
873                 if (Network_game_type == IPX_GAME)
874                         network_dump_player(their->player.network.ipx.server, their->player.network.ipx.node, DUMP_LEVEL);
875                 #ifdef MACINTOSH
876                 else
877                         network_dump_appletalk_player(their->player.network.appletalk.node, their->player.network.appletalk.net, their->player.network.appletalk.socket, DUMP_LEVEL);
878                 #endif
879                 return;
880         }
881
882         player_num = -1;
883         memset(&Network_player_rejoining, 0, sizeof(sequence_packet));
884         Network_player_added = 0;
885
886         if (Network_game_type == IPX_GAME) {
887                 if ( (*(uint *)their->player.network.ipx.server) != 0 )
888                         ipx_get_local_target( their->player.network.ipx.server, their->player.network.ipx.node, local_address );
889                 else
890                         memcpy(local_address, their->player.network.ipx.node, 6);
891         }
892
893         for (i = 0; i < N_players; i++)
894         {
895                 if ( (Network_game_type == IPX_GAME) && (!stricmp(Players[i].callsign, their->player.callsign )) && (!memcmp(Players[i].net_address,local_address, 6)) ) 
896                 {
897                         player_num = i;
898                         break;
899                 }
900 #ifdef MACINTOSH                // note link to above if
901                         else if ( (!stricmp(Players[i].callsign, their->player.callsign)) &&
902                                     (NetPlayers.players[i].network.appletalk.node == their->player.network.appletalk.node) &&
903                                         (NetPlayers.players[i].network.appletalk.net == their->player.network.appletalk.net)) {
904                         player_num = i;
905                         break;
906                 }
907 #endif
908         }
909
910         if (player_num == -1)
911         {
912                 // Player is new to this game
913
914                 if ( !(Netgame.game_flags & NETGAME_FLAG_CLOSED) && (N_players < MaxNumNetPlayers))
915                 {
916                         // Add player in an open slot, game not full yet
917
918                         player_num = N_players;
919                         Network_player_added = 1;
920                 }
921                 else if (Netgame.game_flags & NETGAME_FLAG_CLOSED)
922                 {
923                         // Slots are open but game is closed
924
925                         if (Network_game_type == IPX_GAME)
926                                 network_dump_player(their->player.network.ipx.server, their->player.network.ipx.node, DUMP_CLOSED);
927                         #ifdef MACINTOSH
928                         else
929                                 network_dump_appletalk_player(their->player.network.appletalk.node, their->player.network.appletalk.net, their->player.network.appletalk.socket, DUMP_CLOSED);
930                         #endif
931                         return;
932                 }
933                 else
934                 {
935                         // Slots are full but game is open, see if anyone is
936                         // disconnected and replace the oldest player with this new one
937                 
938                         int oldest_player = -1;
939                         fix oldest_time = timer_get_approx_seconds();
940
941                         Assert(N_players == MaxNumNetPlayers);
942
943                         for (i = 0; i < N_players; i++)
944                         {
945                                 if ( (!Players[i].connected) && (LastPacketTime[i] < oldest_time))
946                                 {
947                                         oldest_time = LastPacketTime[i];
948                                         oldest_player = i;
949                                 }
950                         }
951
952                         if (oldest_player == -1)
953                         {
954                                 // Everyone is still connected 
955
956                                 if (Network_game_type == IPX_GAME)
957                                         network_dump_player(their->player.network.ipx.server, their->player.network.ipx.node, DUMP_FULL);
958                                 #ifdef MACINTOSH
959                                 else
960                                         network_dump_appletalk_player(their->player.network.appletalk.node, their->player.network.appletalk.net, their->player.network.appletalk.socket, DUMP_FULL);
961                                 #endif
962                                 return;
963                         }
964                         else
965                         {       
966                                 // Found a slot!
967
968                                 player_num = oldest_player;
969                                 Network_player_added = 1;
970                         }
971                 }
972         }
973         else 
974         {
975                 // Player is reconnecting
976                 
977                 if (Players[player_num].connected)
978                 {
979                         mprintf((0, "Extra REQUEST from player ignored.\n"));
980                         return;
981                 }
982
983                 if (Newdemo_state == ND_STATE_RECORDING)
984                         newdemo_record_multi_reconnect(player_num);
985
986                 Network_player_added = 0;
987
988                 digi_play_sample(SOUND_HUD_MESSAGE, F1_0);
989                 
990                 if (FindArg("-norankings"))
991                         HUD_init_message("'%s' %s", Players[player_num].callsign, TXT_REJOIN);
992                 else
993                         HUD_init_message("%s'%s' %s", RankStrings[NetPlayers.players[player_num].rank],Players[player_num].callsign, TXT_REJOIN);
994         }
995
996         Players[player_num].KillGoalCount=0;
997
998         // Send updated Objects data to the new/returning player
999
1000         
1001         Network_player_rejoining = *their;
1002         Network_player_rejoining.player.connected = player_num;
1003         Network_send_objects = 1;
1004         Network_send_objnum = -1;
1005
1006         network_send_objects();
1007 }
1008
1009 int network_objnum_is_past(int objnum)
1010 {
1011         // determine whether or not a given object number has already been sent
1012         // to a re-joining player.
1013         
1014         int player_num = Network_player_rejoining.player.connected;
1015         int obj_mode = !((object_owner[objnum] == -1) || (object_owner[objnum] == player_num));
1016
1017         if (!Network_send_objects)
1018                 return 0; // We're not sending objects to a new player
1019
1020         if (obj_mode > Network_send_object_mode)
1021                 return 0;
1022         else if (obj_mode < Network_send_object_mode)
1023                 return 1;
1024         else if (objnum < Network_send_objnum)
1025                 return 1;
1026         else
1027                 return 0;
1028 }
1029
1030 #define OBJ_PACKETS_PER_FRAME 1
1031 extern void multi_send_active_door(char);
1032 extern void multi_send_door_open_specific(int,int,int,ubyte);
1033
1034
1035 void network_send_door_updates(int pnum)
1036 {
1037         // Send door status when new player joins
1038         
1039         int i;
1040    
1041    pnum=pnum;
1042
1043 //   Assert (pnum>-1 && pnum<N_players);
1044
1045         for (i = 0; i < Num_walls; i++)
1046         {
1047       if ((Walls[i].type == WALL_DOOR) && ((Walls[i].state == WALL_DOOR_OPENING) || (Walls[i].state == WALL_DOOR_WAITING) || (Walls[i].state == WALL_DOOR_OPEN)))
1048                         multi_send_door_open_specific(pnum,Walls[i].segnum, Walls[i].sidenum,Walls[i].flags);
1049                 else if ((Walls[i].type == WALL_BLASTABLE) && (Walls[i].flags & WALL_BLASTED))
1050                         multi_send_door_open_specific(pnum,Walls[i].segnum, Walls[i].sidenum,Walls[i].flags);
1051                 else if ((Walls[i].type == WALL_BLASTABLE) && (Walls[i].hps != WALL_HPS))
1052                         multi_send_hostage_door_status(i);
1053                 else
1054                         multi_send_wall_status_specific(pnum,i,Walls[i].type,Walls[i].flags,Walls[i].state);
1055         }
1056 }
1057
1058 extern vms_vector MarkerPoint[];
1059 void network_send_markers()
1060  {
1061   // send marker positions/text to new player
1062
1063   
1064   int i;
1065   
1066   for (i=0;i<8;i++)
1067    {
1068     if (MarkerObject[(i*2)]!=-1)
1069      multi_send_drop_marker (i,MarkerPoint[(i*2)],0,MarkerMessage[i*2]);
1070     if (MarkerObject[(i*2)+1]!=-1)
1071      multi_send_drop_marker (i,MarkerPoint[(i*2)+1],1,MarkerMessage[(i*2)+1]);
1072    }
1073  }
1074
1075 void network_process_monitor_vector(int vector)
1076 {
1077         int i, j;
1078         int count = 0;
1079         segment *seg;
1080         
1081         for (i=0; i <= Highest_segment_index; i++)
1082         {
1083                 int tm, ec, bm;
1084                 seg = &Segments[i];
1085                 for (j = 0; j < 6; j++)
1086                 {
1087                         if ( ((tm = seg->sides[j].tmap_num2) != 0) &&
1088                                   ((ec = TmapInfo[tm&0x3fff].eclip_num) != -1) &&
1089                                   ((bm = Effects[ec].dest_bm_num) != -1) )
1090                         {
1091                                 if (vector & (1 << count))
1092                                 {
1093                                         seg->sides[j].tmap_num2 = bm | (tm&0xc000);
1094                                 //      mprintf((0, "Monitor %d blown up.\n", count));
1095                                 }
1096                                 //else
1097                                   //    mprintf((0, "Monitor %d intact.\n", count));
1098                                 count++;
1099                                 Assert(count < 32);
1100                         }
1101                 }
1102         }
1103 }
1104
1105 int network_create_monitor_vector(void)
1106 {
1107         int i, j, k;
1108         int num_blown_bitmaps = 0;
1109         int monitor_num = 0;
1110         #define NUM_BLOWN_BITMAPS 20
1111         int blown_bitmaps[NUM_BLOWN_BITMAPS];
1112         int vector = 0;
1113         segment *seg;
1114
1115         for (i=0; i < Num_effects; i++)
1116         {
1117                 if (Effects[i].dest_bm_num > 0) {
1118                         for (j = 0; j < num_blown_bitmaps; j++)
1119                                 if (blown_bitmaps[j] == Effects[i].dest_bm_num)
1120                                         break;
1121                         if (j == num_blown_bitmaps) {
1122                                 blown_bitmaps[num_blown_bitmaps++] = Effects[i].dest_bm_num;
1123                                 Assert(num_blown_bitmaps < NUM_BLOWN_BITMAPS);
1124                         }
1125                 }
1126         }               
1127                 
1128 //      for (i = 0; i < num_blown_bitmaps; i++)
1129 //              mprintf((0, "Blown bitmap #%d = %d.\n", i, blown_bitmaps[i]));
1130
1131         for (i=0; i <= Highest_segment_index; i++)
1132         {
1133                 int tm, ec;
1134                 seg = &Segments[i];
1135                 for (j = 0; j < 6; j++)
1136                 {
1137                         if ((tm = seg->sides[j].tmap_num2) != 0) 
1138                         {
1139                                 if ( ((ec = TmapInfo[tm&0x3fff].eclip_num) != -1) &&
1140                                           (Effects[ec].dest_bm_num != -1) )
1141                                 {
1142                                 //      mprintf((0, "Monitor %d intact.\n", monitor_num));
1143                                         monitor_num++;
1144                                         Assert(monitor_num < 32);
1145                                 }
1146                                 else
1147                                 {
1148                                         for (k = 0; k < num_blown_bitmaps; k++)
1149                                         {
1150                                                 if ((tm&0x3fff) == blown_bitmaps[k])
1151                                                 {
1152                                                         //mprintf((0, "Monitor %d destroyed.\n", monitor_num));
1153                                                         vector |= (1 << monitor_num);
1154                                                         monitor_num++;
1155                                                         Assert(monitor_num < 32);
1156                                                         break;
1157                                                 }
1158                                         }
1159                                 }
1160                         }
1161                 }
1162         }
1163   //    mprintf((0, "Final monitor vector %x.\n", vector));
1164         return(vector);
1165 }
1166
1167 void network_stop_resync(sequence_packet *their)
1168 {
1169         if (Network_game_type == IPX_GAME) {
1170                 if ( (!memcmp(Network_player_rejoining.player.network.ipx.node, their->player.network.ipx.node, 6)) &&
1171                           (!memcmp(Network_player_rejoining.player.network.ipx.server, their->player.network.ipx.server, 4)) &&
1172                      (!stricmp(Network_player_rejoining.player.callsign, their->player.callsign)) )
1173                 {
1174                         mprintf((0, "Aborting resync for player %s.\n", their->player.callsign));
1175                         Network_send_objects = 0;
1176                         Network_sending_extras=0;
1177                         Network_rejoined=0;
1178                         Player_joining_extras=-1;
1179                         Network_send_objnum = -1;
1180                 }
1181         } else {
1182                 if ( (Network_player_rejoining.player.network.appletalk.node == their->player.network.appletalk.node) &&
1183                          (Network_player_rejoining.player.network.appletalk.net == their->player.network.appletalk.net) &&
1184                          (!stricmp(Network_player_rejoining.player.callsign, their->player.callsign)) )
1185                 {
1186                         mprintf((0, "Aborting resync for player %s.\n", their->player.callsign));
1187                         Network_send_objects = 0;
1188                         Network_sending_extras=0;
1189                         Network_rejoined=0;
1190                         Player_joining_extras=-1;
1191                         Network_send_objnum = -1;
1192                 }
1193         }
1194 }
1195
1196 byte object_buffer[IPX_MAX_DATA_SIZE];
1197
1198 void network_send_objects(void)
1199 {
1200         short remote_objnum;
1201         byte owner;
1202         int loc, i, h;
1203
1204         static int obj_count = 0;
1205         static int frame_num = 0;
1206
1207         int obj_count_frame = 0;
1208         int player_num = Network_player_rejoining.player.connected;
1209
1210         // Send clear objects array trigger and send player num
1211
1212         Assert(Network_send_objects != 0);
1213         Assert(player_num >= 0);
1214         Assert(player_num < MaxNumNetPlayers);
1215
1216         if (Endlevel_sequence || Control_center_destroyed)
1217         {
1218                 // Endlevel started before we finished sending the goods, we'll
1219                 // have to stop and try again after the level.
1220
1221                 if (Network_game_type == IPX_GAME)
1222                         network_dump_player(Network_player_rejoining.player.network.ipx.server,Network_player_rejoining.player.network.ipx.node, DUMP_ENDLEVEL);
1223                 #ifdef MACINTOSH
1224                 else
1225                         network_dump_appletalk_player(Network_player_rejoining.player.network.appletalk.node,Network_player_rejoining.player.network.appletalk.net, Network_player_rejoining.player.network.appletalk.socket, DUMP_ENDLEVEL);
1226                 #endif
1227                 Network_send_objects = 0; 
1228                 return;
1229         }
1230
1231         for (h = 0; h < OBJ_PACKETS_PER_FRAME; h++) // Do more than 1 per frame, try to speed it up without
1232                                                                                                                           // over-stressing the receiver.
1233         {
1234                 obj_count_frame = 0;
1235                 memset(object_buffer, 0, IPX_MAX_DATA_SIZE);
1236                 object_buffer[0] = PID_OBJECT_DATA;
1237                 loc = 3;
1238         
1239                 if (Network_send_objnum == -1)
1240                 {
1241                         obj_count = 0;
1242                         Network_send_object_mode = 0;
1243 //       mprintf((0, "Sending object array to player %d.\n", player_num));
1244                         *(short *)(object_buffer+loc) = INTEL_SHORT(-1);        loc += 2;
1245                         object_buffer[loc] = player_num;                loc += 1;
1246                                                                                                         loc += 2; // Placeholder for remote_objnum, not used here
1247                         Network_send_objnum = 0;
1248                         obj_count_frame = 1;
1249                         frame_num = 0;
1250                 }
1251                 
1252                 for (i = Network_send_objnum; i <= Highest_object_index; i++)
1253                 {
1254                         if ((Objects[i].type != OBJ_POWERUP) && (Objects[i].type != OBJ_PLAYER) &&
1255                                  (Objects[i].type != OBJ_CNTRLCEN) && (Objects[i].type != OBJ_GHOST) &&
1256                                  (Objects[i].type != OBJ_ROBOT) && (Objects[i].type != OBJ_HOSTAGE) &&
1257                                  !(Objects[i].type==OBJ_WEAPON && Objects[i].id==PMINE_ID))
1258                                 continue;
1259                         if ((Network_send_object_mode == 0) && ((object_owner[i] != -1) && (object_owner[i] != player_num)))
1260                                 continue;
1261                         if ((Network_send_object_mode == 1) && ((object_owner[i] == -1) || (object_owner[i] == player_num)))
1262                                 continue;
1263
1264                         if ( ((IPX_MAX_DATA_SIZE-1) - loc) < (sizeof(object)+5) )
1265                                 break; // Not enough room for another object
1266
1267                         obj_count_frame++;
1268                         obj_count++;
1269         
1270                         remote_objnum = objnum_local_to_remote((short)i, &owner);
1271                         Assert(owner == object_owner[i]);
1272
1273                         *(short *)(object_buffer+loc) = INTEL_SHORT((short)i);                          loc += 2;
1274                         object_buffer[loc] = owner;                                                                                     loc += 1;
1275                         *(short *)(object_buffer+loc) = INTEL_SHORT(remote_objnum);             loc += 2;
1276 #ifndef MACINTOSH
1277                         memcpy(object_buffer+loc, &Objects[i], sizeof(object)); loc += sizeof(object);
1278 #else
1279                         if (Network_game_type == IPX_GAME) {
1280                                 object tmpobj;
1281
1282                                 memcpy(&tmpobj, &(Objects[i]), sizeof(object));
1283                                 swap_object(&tmpobj);
1284                                 memcpy(&(object_buffer[loc]), &tmpobj, sizeof(object));                 loc += sizeof(object);
1285                         }
1286                         else
1287                                 memcpy(object_buffer+loc, &Objects[i], sizeof(object)); loc += sizeof(object);
1288 #endif
1289 //                      mprintf((0, "..packing object %d, remote %d\n", i, remote_objnum));
1290                 }
1291
1292                 if (obj_count_frame) // Send any objects we've buffered
1293                 {
1294                         frame_num++;
1295         
1296                         Network_send_objnum = i;
1297                         object_buffer[1] = obj_count_frame;  object_buffer[2] = frame_num;
1298 //       mprintf((0, "Object packet %d contains %d objects.\n", frame_num, obj_count_frame));
1299
1300                         Assert(loc <= IPX_MAX_DATA_SIZE);
1301
1302                         if (Network_game_type == IPX_GAME)
1303                                 ipx_send_internetwork_packet_data( object_buffer, loc, Network_player_rejoining.player.network.ipx.server, Network_player_rejoining.player.network.ipx.node );
1304                         #ifdef MACINTOSH
1305                         else
1306                                 appletalk_send_packet_data( object_buffer, loc, Network_player_rejoining.player.network.appletalk.node,
1307                                         Network_player_rejoining.player.network.appletalk.net,
1308                                         Network_player_rejoining.player.network.appletalk.socket);
1309                         #endif
1310
1311                         // OLD ipx_send_packet_data(object_buffer, loc, &Network_player_rejoining.player.node);
1312                 }
1313
1314                 if (i > Highest_object_index)
1315                 {
1316                         if (Network_send_object_mode == 0)
1317                         {
1318                                 Network_send_objnum = 0;
1319                                 Network_send_object_mode = 1; // go to next mode
1320                         }
1321                         else 
1322                         {
1323                                 Assert(Network_send_object_mode == 1); 
1324
1325                                 frame_num++;
1326                                 // Send count so other side can make sure he got them all
1327 //                              mprintf((0, "Sending end marker in packet #%d.\n", frame_num));
1328                                 mprintf((0, "Sent %d objects.\n", obj_count));
1329                                 object_buffer[0] = PID_OBJECT_DATA;
1330                                 object_buffer[1] = 1;
1331                                 object_buffer[2] = frame_num;
1332                                 *(short *)(object_buffer+3) = INTEL_SHORT(-2);
1333                                 *(short *)(object_buffer+6) = INTEL_SHORT(obj_count);
1334                                 //OLD ipx_send_packet_data(object_buffer, 8, &Network_player_rejoining.player.node);
1335                                 if (Network_game_type == IPX_GAME)
1336                                         ipx_send_internetwork_packet_data(object_buffer, 8, Network_player_rejoining.player.network.ipx.server, Network_player_rejoining.player.network.ipx.node);
1337                                 #ifdef MACINTOSH
1338                                 else
1339                                         appletalk_send_packet_data( object_buffer, 8, Network_player_rejoining.player.network.appletalk.node,
1340                                                                                                 Network_player_rejoining.player.network.appletalk.net,
1341                                                                                                 Network_player_rejoining.player.network.appletalk.socket);
1342                                 #endif
1343                                 
1344                         
1345                                 // Send sync packet which tells the player who he is and to start!
1346                                 network_send_rejoin_sync(player_num);
1347                                 mprintf ((0,"VerfiyPlayerJoined is now set to %d\n",player_num));
1348                                 VerifyPlayerJoined=player_num;
1349
1350                                 // Turn off send object mode
1351                                 Network_send_objnum = -1;
1352                                 Network_send_objects = 0;
1353                                 obj_count = 0;
1354
1355                                 //if (!network_i_am_master ())
1356                                 // Int3();  // Bad!! Get Jason.  Someone goofy is trying to get ahold of the game!
1357
1358                                 Network_sending_extras=40; // start to send extras
1359                            Player_joining_extras=player_num;
1360
1361                                 return;
1362                         } // mode == 1;
1363                 } // i > Highest_object_index
1364         } // For PACKETS_PER_FRAME
1365 }
1366
1367 extern void multi_send_powerup_update();
1368
1369 void network_send_rejoin_sync(int player_num)
1370 {
1371         int i, j;
1372
1373         Players[player_num].connected = 1; // connect the new guy
1374         LastPacketTime[player_num] = timer_get_approx_seconds();
1375
1376         if (Endlevel_sequence || Control_center_destroyed)
1377         {
1378                 // Endlevel started before we finished sending the goods, we'll
1379                 // have to stop and try again after the level.
1380
1381                 if (Network_game_type == IPX_GAME)
1382                         network_dump_player(Network_player_rejoining.player.network.ipx.server,Network_player_rejoining.player.network.ipx.node, DUMP_ENDLEVEL);
1383                 #ifdef MACINTOSH
1384                 else
1385                         network_dump_appletalk_player(Network_player_rejoining.player.network.appletalk.node,Network_player_rejoining.player.network.appletalk.net, Network_player_rejoining.player.network.appletalk.socket, DUMP_ENDLEVEL);
1386                 #endif
1387                 Network_send_objects = 0; 
1388                 Network_sending_extras=0;
1389                 return;
1390         }
1391
1392         if (Network_player_added)
1393         {
1394                 Network_player_rejoining.type = PID_ADDPLAYER;
1395                 Network_player_rejoining.player.connected = player_num;
1396                 network_new_player(&Network_player_rejoining);
1397
1398                 for (i = 0; i < N_players; i++)
1399                 {
1400                         if ((i != player_num) && (i != Player_num) && (Players[i].connected))
1401                                 if (Network_game_type == IPX_GAME) {
1402                                         #ifndef MACINTOSH
1403                                         ipx_send_packet_data( (ubyte *)&Network_player_rejoining, sizeof(sequence_packet), NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node, Players[i].net_address);
1404                                         #else
1405                                         send_sequence_packet( Network_player_rejoining, NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node, Players[i].net_address);
1406                                         #endif
1407                                 #ifdef MACINTOSH
1408                                 } else {
1409                                         appletalk_send_packet_data( (ubyte *)&Network_player_rejoining, sizeof(sequence_packet), NetPlayers.players[i].network.appletalk.node,
1410                                                                                                 NetPlayers.players[i].network.appletalk.net, NetPlayers.players[i].network.appletalk.socket);
1411                                 #endif
1412                                 }
1413                 }
1414         }       
1415
1416         // Send sync packet to the new guy
1417
1418         network_update_netgame();
1419
1420         // Fill in the kill list
1421         for (j=0; j<MAX_PLAYERS; j++)
1422         {
1423                 for (i=0; i<MAX_PLAYERS;i++)
1424                         Netgame.kills[j][i] = kill_matrix[j][i];
1425                 Netgame.killed[j] = Players[j].net_killed_total;
1426                 Netgame.player_kills[j] = Players[j].net_kills_total;
1427                 Netgame.player_score[j] = Players[j].score;
1428         }       
1429
1430         Netgame.level_time = Players[Player_num].time_level;
1431         Netgame.monitor_vector = network_create_monitor_vector();
1432
1433         mprintf((0, "Sending rejoin sync packet!!!\n"));
1434
1435         if (Network_game_type == IPX_GAME) {
1436                 #ifndef MACINTOSH       
1437                 ipx_send_internetwork_packet_data( (ubyte *)&Netgame, sizeof(netgame_info), Network_player_rejoining.player.network.ipx.server, Network_player_rejoining.player.network.ipx.node );
1438                 ipx_send_internetwork_packet_data( (ubyte *)&NetPlayers, sizeof(AllNetPlayers_info), Network_player_rejoining.player.network.ipx.server, Network_player_rejoining.player.network.ipx.node );
1439                 #else
1440                 send_netgame_packet(Network_player_rejoining.player.network.ipx.server, Network_player_rejoining.player.network.ipx.node, NULL, 0);
1441                 send_netplayers_packet(Network_player_rejoining.player.network.ipx.server, Network_player_rejoining.player.network.ipx.node);
1442                 #endif
1443         #ifdef MACINTOSH
1444         } else {
1445                 appletalk_send_packet_data( (ubyte *)&Netgame, sizeof(netgame_info), Network_player_rejoining.player.network.appletalk.node,
1446                                                                         Network_player_rejoining.player.network.appletalk.net,
1447                                                                         Network_player_rejoining.player.network.appletalk.socket);
1448                 appletalk_send_packet_data( (ubyte *)&NetPlayers, sizeof(AllNetPlayers_info), Network_player_rejoining.player.network.appletalk.node,
1449                                                                         Network_player_rejoining.player.network.appletalk.net,
1450                                                                         Network_player_rejoining.player.network.appletalk.socket);
1451         #endif
1452         }
1453         return;
1454 }
1455 void resend_sync_due_to_packet_loss_for_allender ()
1456 {
1457    int i,j;
1458
1459    mprintf ((0,"I'm resending a sync packet! VPJ=%d\n",VerifyPlayerJoined));
1460   
1461         network_update_netgame();
1462
1463         // Fill in the kill list
1464         for (j=0; j<MAX_PLAYERS; j++)
1465         {
1466                 for (i=0; i<MAX_PLAYERS;i++)
1467                         Netgame.kills[j][i] = kill_matrix[j][i];
1468                 Netgame.killed[j] = Players[j].net_killed_total;
1469                 Netgame.player_kills[j] = Players[j].net_kills_total;
1470                 Netgame.player_score[j] = Players[j].score;
1471         }       
1472
1473         Netgame.level_time = Players[Player_num].time_level;
1474         Netgame.monitor_vector = network_create_monitor_vector();
1475
1476         if (Network_game_type == IPX_GAME) {
1477                 #ifndef MACINTOSH       
1478                 ipx_send_internetwork_packet_data( (ubyte *)&Netgame, sizeof(netgame_info), Network_player_rejoining.player.network.ipx.server, Network_player_rejoining.player.network.ipx.node );
1479                 ipx_send_internetwork_packet_data( (ubyte *)&NetPlayers, sizeof(AllNetPlayers_info), Network_player_rejoining.player.network.ipx.server, Network_player_rejoining.player.network.ipx.node );
1480                 #else
1481                 send_netgame_packet(Network_player_rejoining.player.network.ipx.server, Network_player_rejoining.player.network.ipx.node, NULL, 0);
1482                 send_netplayers_packet(Network_player_rejoining.player.network.ipx.server, Network_player_rejoining.player.network.ipx.node);
1483                 #endif
1484         #ifdef MACINTOSH
1485         } else {
1486                 appletalk_send_packet_data( (ubyte *)&Netgame, sizeof(netgame_info), Network_player_rejoining.player.network.appletalk.node,
1487                                                                         Network_player_rejoining.player.network.appletalk.net,
1488                                                                         Network_player_rejoining.player.network.appletalk.socket);
1489                 appletalk_send_packet_data( (ubyte *)&NetPlayers, sizeof(AllNetPlayers_info), Network_player_rejoining.player.network.appletalk.node,
1490                                                                         Network_player_rejoining.player.network.appletalk.net,
1491                                                                         Network_player_rejoining.player.network.appletalk.socket);
1492         #endif
1493         }
1494 }
1495
1496
1497 char * network_get_player_name( int objnum )
1498 {
1499         if ( objnum < 0 ) return NULL; 
1500         if ( Objects[objnum].type != OBJ_PLAYER ) return NULL;
1501         if ( Objects[objnum].id >= MAX_PLAYERS ) return NULL;
1502         if ( Objects[objnum].id >= N_players ) return NULL;
1503         
1504         return Players[Objects[objnum].id].callsign;
1505 }
1506
1507
1508 void network_add_player(sequence_packet *p)
1509 {
1510         int i;
1511         
1512         mprintf((0, "Got add player request!\n"));
1513
1514         for (i=0; i<N_players; i++ )    {
1515                 if (Network_game_type == IPX_GAME) {
1516                         if ( !memcmp( NetPlayers.players[i].network.ipx.node, p->player.network.ipx.node, 6) && !memcmp(NetPlayers.players[i].network.ipx.server, p->player.network.ipx.server, 4)) 
1517                                 return;         // already got them
1518                 } else {
1519                         if ( (NetPlayers.players[i].network.appletalk.node == p->player.network.appletalk.node) &&
1520                                  (NetPlayers.players[i].network.appletalk.net == p->player.network.appletalk.net))
1521                                         return;
1522                 }
1523         }
1524
1525         if (Network_game_type == IPX_GAME) {
1526                 memcpy( NetPlayers.players[N_players].network.ipx.node, p->player.network.ipx.node, 6 );
1527                 memcpy( NetPlayers.players[N_players].network.ipx.server, p->player.network.ipx.server, 4 );
1528         } else {
1529                 NetPlayers.players[N_players].network.appletalk.node = p->player.network.appletalk.node;
1530                 NetPlayers.players[N_players].network.appletalk.net = p->player.network.appletalk.net;
1531                 NetPlayers.players[N_players].network.appletalk.socket = p->player.network.appletalk.socket;
1532         }
1533    
1534    ClipRank (&p->player.rank);
1535   
1536         memcpy( NetPlayers.players[N_players].callsign, p->player.callsign, CALLSIGN_LEN+1 );
1537         NetPlayers.players[N_players].version_major=p->player.version_major;
1538         NetPlayers.players[N_players].version_minor=p->player.version_minor;
1539    NetPlayers.players[N_players].rank=p->player.rank;
1540         NetPlayers.players[N_players].connected = 1;
1541    network_check_for_old_version (N_players);
1542
1543         Players[N_players].KillGoalCount=0;
1544         Players[N_players].connected = 1;
1545         LastPacketTime[N_players] = timer_get_approx_seconds();
1546         N_players++;
1547         Netgame.numplayers = N_players;
1548
1549         // Broadcast updated info
1550
1551    mprintf ((0,"sending_game_info!\n"));
1552         network_send_game_info(NULL);
1553 }
1554
1555 // One of the players decided not to join the game
1556
1557 void network_remove_player(sequence_packet *p)
1558 {
1559         int i,pn;
1560         
1561         pn = -1;
1562         for (i=0; i<N_players; i++ )    {
1563                 if (Network_game_type == IPX_GAME) {
1564                         if (!memcmp(NetPlayers.players[i].network.ipx.node, p->player.network.ipx.node, 6) && !memcmp(NetPlayers.players[i].network.ipx.server, p->player.network.ipx.server, 4)) {
1565                                 pn = i;
1566                                 break;
1567                         }
1568                 } else {
1569                         if ( (NetPlayers.players[i].network.appletalk.node == p->player.network.appletalk.node) && (NetPlayers.players[i].network.appletalk.net == p->player.network.appletalk.net) ) {
1570                                 pn = i;
1571                                 break;
1572                         }
1573                 }
1574         }
1575         
1576         if (pn < 0 ) return;
1577
1578         for (i=pn; i<N_players-1; i++ ) {
1579                 if (Network_game_type == IPX_GAME) {
1580                         memcpy( NetPlayers.players[i].network.ipx.node, NetPlayers.players[i+1].network.ipx.node, 6 );
1581                         memcpy( NetPlayers.players[i].network.ipx.server, NetPlayers.players[i+1].network.ipx.server, 4 );
1582                 } else {
1583                         NetPlayers.players[i].network.appletalk.node = NetPlayers.players[i+1].network.appletalk.node;
1584                         NetPlayers.players[i].network.appletalk.net = NetPlayers.players[i+1].network.appletalk.net;
1585                         NetPlayers.players[i].network.appletalk.socket = NetPlayers.players[i+1].network.appletalk.socket;
1586                 }
1587                 memcpy( NetPlayers.players[i].callsign, NetPlayers.players[i+1].callsign, CALLSIGN_LEN+1 );
1588                 NetPlayers.players[i].version_major=NetPlayers.players[i+1].version_major;
1589                 NetPlayers.players[i].version_minor=NetPlayers.players[i+1].version_minor;
1590
1591            NetPlayers.players[i].rank=NetPlayers.players[i+1].rank;
1592                 ClipRank (&NetPlayers.players[i].rank);
1593            network_check_for_old_version(i);    
1594         }
1595                 
1596         N_players--;
1597         Netgame.numplayers = N_players;
1598
1599         // Broadcast new info
1600
1601         network_send_game_info(NULL);
1602
1603 }
1604
1605 void
1606 network_dump_player(ubyte * server, ubyte *node, int why)
1607 {
1608         // Inform player that he was not chosen for the netgame
1609
1610         sequence_packet temp;
1611
1612         temp.type = PID_DUMP;
1613         memcpy(temp.player.callsign, Players[Player_num].callsign, CALLSIGN_LEN+1);
1614         temp.player.connected = why;
1615         if (Network_game_type == IPX_GAME) {
1616                 #ifndef MACINTOSH
1617                 ipx_send_internetwork_packet_data( (ubyte *)&temp, sizeof(sequence_packet), server, node);
1618                 #else
1619                 send_sequence_packet( temp, server, node, NULL);
1620                 #endif
1621         } else {
1622                 Int3();
1623         }
1624 }
1625
1626 #ifdef MACINTOSH
1627 void network_dump_appletalk_player(ubyte node, ushort net, ubyte socket, int why)
1628 {
1629         sequence_packet temp;
1630
1631         temp.type = PID_DUMP;
1632         memcpy(temp.player.callsign, Players[Player_num].callsign, CALLSIGN_LEN+1);
1633         temp.player.connected = why;
1634         if (Network_game_type == APPLETALK_GAME) {
1635                 appletalk_send_packet_data( (ubyte *)&temp, sizeof(sequence_packet), node, net, socket );
1636         } else {
1637                 Int3();
1638         }
1639 }
1640 #endif
1641
1642 void
1643 network_send_game_list_request()
1644 {
1645         // Send a broadcast request for game info
1646
1647         sequence_packet me;
1648
1649         mprintf((0, "Sending game_list request.\n"));
1650         me.type = PID_GAME_LIST;
1651         memcpy( me.player.callsign, Players[Player_num].callsign, CALLSIGN_LEN+1 );
1652
1653         if (Network_game_type == IPX_GAME) {
1654                 memcpy( me.player.network.ipx.node, ipx_get_my_local_address(), 6 );
1655                 memcpy( me.player.network.ipx.server, ipx_get_my_server_address(), 4 );
1656
1657                 #ifndef MACINTOSH       
1658                 ipx_send_broadcast_packet_data( (ubyte *)&me, sizeof(sequence_packet) );
1659                 #else
1660                 send_sequence_packet( me, NULL, NULL, NULL);
1661                 #endif
1662         #ifdef MACINTOSH
1663         } else {
1664                 me.player.network.appletalk.node = appletalk_get_my_node();
1665                 me.player.network.appletalk.net = appletalk_get_my_net();
1666                 me.player.network.appletalk.socket = appletalk_get_my_socket();
1667                 appletalk_send_game_info( (ubyte *)&me, sizeof(sequence_packet), Network_zone_name );
1668         #endif
1669         }
1670 }
1671
1672 void network_send_all_info_request(char type,int which_security)
1673 {
1674         // Send a broadcast request for game info
1675
1676         sequence_packet me;
1677
1678         mprintf((0, "Sending all_info request.\n"));
1679    
1680         me.Security=which_security;
1681         me.type = type;
1682         memcpy( me.player.callsign, Players[Player_num].callsign, CALLSIGN_LEN+1 );
1683         
1684         if (Network_game_type == IPX_GAME) {
1685                 memcpy( me.player.network.ipx.node, ipx_get_my_local_address(), 6 );
1686                 memcpy( me.player.network.ipx.server, ipx_get_my_server_address(), 4 );
1687
1688                 #ifndef MACINTOSH       
1689                 ipx_send_broadcast_packet_data( (ubyte *)&me, sizeof(sequence_packet) );
1690                 #else
1691                 send_sequence_packet(me, NULL, NULL, NULL);
1692                 #endif
1693         #ifdef MACINTOSH
1694         } else {
1695                 me.player.network.appletalk.node = appletalk_get_my_node();
1696                 me.player.network.appletalk.net = appletalk_get_my_net();
1697                 me.player.network.appletalk.socket = appletalk_get_my_socket();
1698                 appletalk_send_game_info( (ubyte *)&me, sizeof(sequence_packet), Network_zone_name );
1699         #endif
1700         }
1701 }
1702
1703
1704 void
1705 network_update_netgame(void)
1706 {
1707         // Update the netgame struct with current game variables
1708
1709         int i, j;
1710
1711    Netgame.numconnected=0;
1712    for (i=0;i<N_players;i++)
1713          if (Players[i].connected)
1714                 Netgame.numconnected++;
1715
1716 // This is great: D2 1.0 and 1.1 ignore upper part of the game_flags field of
1717 //      the lite_info struct when you're sitting on the join netgame screen.  We can
1718 //      "sneak" Hoard information into this field.  This is better than sending 
1719 //      another packet that could be lost in transit.
1720
1721
1722         if (HoardEquipped())
1723         {
1724                 if (Game_mode & GM_HOARD)
1725                 {
1726                         Netgame.game_flags |=NETGAME_FLAG_HOARD;
1727                         if (Game_mode & GM_TEAM)
1728                                 Netgame.game_flags |=NETGAME_FLAG_TEAM_HOARD;
1729                 }
1730         }
1731  
1732         if (Network_status == NETSTAT_STARTING)
1733                 return;
1734
1735         Netgame.numplayers = N_players;
1736         Netgame.game_status = Network_status;
1737         Netgame.max_numplayers = MaxNumNetPlayers;
1738
1739         for (i = 0; i < MAX_NUM_NET_PLAYERS; i++) 
1740         {
1741                 NetPlayers.players[i].connected = Players[i].connected;
1742                 for(j = 0; j < MAX_NUM_NET_PLAYERS; j++)
1743                         Netgame.kills[i][j] = kill_matrix[i][j];
1744
1745                 Netgame.killed[i] = Players[i].net_killed_total;
1746                 Netgame.player_kills[i] = Players[i].net_kills_total;
1747                 Netgame.player_score[i] = Players[i].score;
1748                 Netgame.player_flags[i] = (Players[i].flags & (PLAYER_FLAGS_BLUE_KEY | PLAYER_FLAGS_RED_KEY | PLAYER_FLAGS_GOLD_KEY));
1749         }
1750         Netgame.team_kills[0] = team_kills[0];
1751         Netgame.team_kills[1] = team_kills[1];
1752         Netgame.levelnum = Current_level_num;
1753
1754  
1755 }
1756
1757 void
1758 network_send_endlevel_sub(int player_num)
1759 {
1760         endlevel_info end;
1761         int i, j;
1762
1763         // Send an endlevel packet for a player
1764         end.type                = PID_ENDLEVEL;
1765         end.player_num = player_num;
1766         end.connected   = Players[player_num].connected;
1767         end.kills               = INTEL_SHORT(Players[player_num].net_kills_total);
1768         end.killed              = INTEL_SHORT(Players[player_num].net_killed_total);
1769         memcpy(end.kill_matrix, kill_matrix[player_num], MAX_PLAYERS*sizeof(short));
1770 #ifdef MACINTOSH
1771         for (i = 0; i < MAX_PLAYERS; i++)
1772                 for (j = 0; j < MAX_PLAYERS; j++)
1773                         end.kill_matrix[i][j] = INTEL_SHORT(end.kill_matrix[i][j]);
1774 #else
1775         j = j;          // to satisfy compiler
1776 #endif
1777
1778         if (Players[player_num].connected == 1) // Still playing
1779         {
1780                 Assert(Control_center_destroyed);
1781                 end.seconds_left = Countdown_seconds_left;
1782         }
1783
1784 //      mprintf((0, "Sending endlevel packet.\n"));
1785
1786         for (i = 0; i < N_players; i++)
1787         {       
1788                 if ((i != Player_num) && (i!=player_num) && (Players[i].connected)) {
1789                   if (Players[i].connected==1)
1790                          network_send_endlevel_short_sub(player_num,i);
1791                   else {
1792                         if (Network_game_type == IPX_GAME)
1793                                 ipx_send_packet_data((ubyte *)&end, sizeof(endlevel_info), NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node,Players[i].net_address);
1794                         #ifdef MACINTOSH
1795                         else
1796                                 appletalk_send_packet_data( (ubyte *)&end, sizeof(endlevel_info), NetPlayers.players[i].network.appletalk.node,
1797                                                                                         NetPlayers.players[i].network.appletalk.net,
1798                                                                                         NetPlayers.players[i].network.appletalk.socket);
1799                         #endif
1800                         }       
1801                 }
1802         }
1803 }
1804
1805 void
1806 network_send_endlevel_packet(void)
1807 {
1808         // Send an updated endlevel status to other hosts
1809
1810         network_send_endlevel_sub(Player_num);
1811 }
1812
1813
1814 void
1815 network_send_endlevel_short_sub(int from_player_num,int to_player)
1816 {
1817         endlevel_info_short end;
1818
1819         // Send an endlevel packet for a player
1820         end.type                = PID_ENDLEVEL_SHORT;
1821         end.player_num = from_player_num;
1822         end.connected   = Players[from_player_num].connected;
1823         end.seconds_left = Countdown_seconds_left;
1824
1825
1826         if (Players[from_player_num].connected == 1) // Still playing
1827         {
1828                 Assert(Control_center_destroyed);
1829         }
1830
1831         if ((to_player != Player_num) && (to_player!=from_player_num) && (Players[to_player].connected))
1832         {
1833                 mprintf((0, "Sending short endlevel packet to %s.\n",Players[to_player].callsign));
1834                 if (Network_game_type == IPX_GAME)
1835                         ipx_send_packet_data((ubyte *)&end, sizeof(endlevel_info_short), NetPlayers.players[to_player].network.ipx.server, NetPlayers.players[to_player].network.ipx.node,Players[to_player].net_address);
1836                 #ifdef MACINTOSH
1837                 else
1838                         appletalk_send_packet_data( (ubyte *)&end, sizeof(endlevel_info_short), NetPlayers.players[to_player].network.appletalk.node,
1839                                                                                 NetPlayers.players[to_player].network.appletalk.net,
1840                                                                                 NetPlayers.players[to_player].network.appletalk.socket);
1841                 #endif
1842         }
1843 }
1844
1845 extern fix ThisLevelTime;
1846
1847 void
1848 network_send_game_info(sequence_packet *their)
1849 {
1850         // Send game info to someone who requested it
1851
1852         char old_type, old_status;
1853    fix timevar;
1854    int i;
1855
1856         mprintf((0, "Sending game info.\n"));
1857
1858         network_update_netgame(); // Update the values in the netgame struct
1859
1860         old_type = Netgame.type;
1861         old_status = Netgame.game_status;
1862
1863         Netgame.type = PID_GAME_INFO;
1864    NetPlayers.type = PID_PLAYERSINFO;
1865
1866    NetPlayers.Security=Netgame.Security;
1867         Netgame.version_major=Version_major;
1868         Netgame.version_minor=Version_minor;
1869
1870         if (Endlevel_sequence || Control_center_destroyed)
1871                 Netgame.game_status = NETSTAT_ENDLEVEL;
1872
1873         if (Netgame.PlayTimeAllowed)
1874     {
1875                 timevar=i2f (Netgame.PlayTimeAllowed*5*60);
1876                 i=f2i(timevar-ThisLevelTime);
1877                 if (i<30)
1878                         Netgame.game_status=NETSTAT_ENDLEVEL;
1879         }       
1880
1881         if (!their) {
1882                 if (Network_game_type == IPX_GAME) {
1883                         #ifndef MACINTOSH
1884                         ipx_send_broadcast_packet_data((ubyte *)&Netgame, sizeof(netgame_info));
1885                         ipx_send_broadcast_packet_data((ubyte *)&NetPlayers,sizeof(AllNetPlayers_info));
1886                         #else
1887                         send_netgame_packet(NULL, NULL, NULL, 0);               // server == NULL says to broadcast packet
1888                         send_netplayers_packet(NULL, NULL);
1889                         #endif
1890                 } // nothing to do for appletalk games I think....
1891         } else {
1892                 if (Network_game_type == IPX_GAME) {
1893                         #ifndef MACINTOSH        
1894                     ipx_send_internetwork_packet_data((ubyte *)&Netgame, sizeof(netgame_info), their->player.network.ipx.server, their->player.network.ipx.node);
1895                         ipx_send_internetwork_packet_data((ubyte *)&NetPlayers,sizeof(AllNetPlayers_info),their->player.network.ipx.server,their->player.network.ipx.node);
1896                         #else
1897                         send_netgame_packet(their->player.network.ipx.server, their->player.network.ipx.node, NULL, 0);
1898                         send_netplayers_packet(their->player.network.ipx.server, their->player.network.ipx.node);
1899                         #endif
1900                 #ifdef MACINTOSH
1901                 } else {
1902                         appletalk_send_packet_data( (ubyte *)&Netgame, sizeof(netgame_info), their->player.network.appletalk.node,
1903                                                                                 their->player.network.appletalk.net, their->player.network.appletalk.socket );
1904                         appletalk_send_packet_data( (ubyte *)&NetPlayers, sizeof(AllNetPlayers_info), their->player.network.appletalk.node,
1905                                                                                 their->player.network.appletalk.net, their->player.network.appletalk.socket );
1906                 #endif
1907                 }
1908         }  
1909
1910         Netgame.type = old_type;
1911         Netgame.game_status = old_status;
1912 }       
1913
1914 void network_send_lite_info(sequence_packet *their)
1915 {
1916         // Send game info to someone who requested it
1917
1918         char old_type, old_status,oldstatus;
1919
1920         mprintf((0, "Sending lite game info.\n"));
1921
1922         network_update_netgame(); // Update the values in the netgame struct
1923
1924         old_type = Netgame.type;
1925         old_status = Netgame.game_status;
1926
1927         Netgame.type = PID_LITE_INFO;
1928
1929         if (Endlevel_sequence || Control_center_destroyed)
1930                 Netgame.game_status = NETSTAT_ENDLEVEL;
1931
1932 // If hoard mode, make this game look closed even if it isn't
1933    if (HoardEquipped())
1934         {
1935                 if (Game_mode & GM_HOARD)
1936                 {
1937                         oldstatus=Netgame.game_status;
1938                         Netgame.game_status=NETSTAT_ENDLEVEL;
1939                         Netgame.gamemode=NETGAME_CAPTURE_FLAG;
1940                         if (oldstatus==NETSTAT_ENDLEVEL)
1941                                 Netgame.game_flags|=NETGAME_FLAG_REALLY_ENDLEVEL;
1942                         if (oldstatus==NETSTAT_STARTING)
1943                                 Netgame.game_flags|=NETGAME_FLAG_REALLY_FORMING;
1944                 }
1945         }
1946
1947         if (!their) {
1948                 if (Network_game_type == IPX_GAME) {
1949                         #ifndef MACINTOSH
1950                         ipx_send_broadcast_packet_data((ubyte *)&Netgame, sizeof(lite_info));
1951                         #else
1952                         send_netgame_packet(NULL, NULL, NULL, 1);                       // server == NULL says broadcast
1953                         #endif
1954                 }               // nothing to do for appletalk I think....
1955         } else {
1956                 if (Network_game_type == IPX_GAME) {
1957                         #ifndef MACINTOSH
1958                     ipx_send_internetwork_packet_data((ubyte *)&Netgame, sizeof(lite_info), their->player.network.ipx.server, their->player.network.ipx.node);
1959                         #else
1960                         send_netgame_packet(their->player.network.ipx.server, their->player.network.ipx.node, NULL, 1);
1961                         #endif
1962                 #ifdef MACINTOSH
1963                 } else {
1964                         appletalk_send_packet_data( (ubyte *)&Netgame, sizeof(lite_info), their->player.network.appletalk.node,
1965                                                                                 their->player.network.appletalk.net, their->player.network.appletalk.socket );
1966                 #endif
1967                 }
1968         }  
1969
1970         //  Restore the pre-hoard mode
1971         if (HoardEquipped())
1972         {
1973                 if (Game_mode & GM_HOARD)
1974                 {
1975                         if (!(Game_mode & GM_TEAM))
1976                            Netgame.gamemode=NETGAME_HOARD;
1977                         else
1978                            Netgame.gamemode=NETGAME_TEAM_HOARD;
1979                         Netgame.game_flags&=~NETGAME_FLAG_REALLY_ENDLEVEL;
1980                         Netgame.game_flags&=~NETGAME_FLAG_REALLY_FORMING;
1981                         Netgame.game_flags&=~NETGAME_FLAG_TEAM_HOARD;
1982                 }
1983         }
1984
1985         Netgame.type = old_type;
1986         Netgame.game_status = old_status;
1987
1988 }       
1989
1990 void network_send_netgame_update()
1991 {
1992         // Send game info to someone who requested it
1993
1994         char old_type, old_status;
1995         int i;
1996
1997         mprintf((0, "Sending updated game info.\n"));
1998
1999         network_update_netgame(); // Update the values in the netgame struct
2000
2001         old_type = Netgame.type;
2002         old_status = Netgame.game_status;
2003
2004         Netgame.type = PID_GAME_UPDATE;
2005
2006         if (Endlevel_sequence || Control_center_destroyed)
2007                 Netgame.game_status = NETSTAT_ENDLEVEL;
2008  
2009         for (i=0; i<N_players; i++ )    {
2010                 if ( (Players[i].connected) && (i!=Player_num ) )       {
2011                         if (Network_game_type == IPX_GAME) {
2012                                 #ifndef MACINTOSH
2013                                 ipx_send_packet_data( (ubyte *)&Netgame, sizeof(lite_info), NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node,Players[i].net_address );
2014                                 #else
2015                                 send_netgame_packet(NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node, Players[i].net_address, 0);
2016                                 #endif
2017                         #ifdef MACINTOSH
2018                         } else {
2019                                 appletalk_send_packet_data( (ubyte *)&Netgame, sizeof(lite_info), NetPlayers.players[i].network.appletalk.node,
2020                                                                                         NetPlayers.players[i].network.appletalk.net, NetPlayers.players[i].network.appletalk.socket );
2021                         #endif
2022                         }
2023                 }
2024         }
2025
2026         Netgame.type = old_type;
2027         Netgame.game_status = old_status;
2028 }       
2029                           
2030 int network_send_request(void)
2031 {
2032         // Send a request to join a game 'Netgame'.  Returns 0 if we can join this
2033         // game, non-zero if there is some problem.
2034         int i;
2035
2036         if (Netgame.numplayers < 1)
2037          return 1;
2038
2039         for (i = 0; i < MAX_NUM_NET_PLAYERS; i++)
2040           if (NetPlayers.players[i].connected)
2041               break;
2042
2043         Assert(i < MAX_NUM_NET_PLAYERS);
2044
2045         mprintf((0, "Sending game enroll request to player %d (%s). Serv=%x Node=%x Level=%d\n", i, Players[i].callsign,NetPlayers.players[i].network.ipx.server,NetPlayers.players[i].network.ipx.node,Netgame.levelnum));
2046
2047 //      segments_checksum = netmisc_calc_checksum( Segments, sizeof(segment)*(Highest_segment_index+1) );       
2048
2049         My_Seq.type = PID_REQUEST;
2050         My_Seq.player.connected = Current_level_num;
2051
2052         if (Network_game_type == IPX_GAME) {
2053                 #ifndef MACINTOSH
2054                 ipx_send_internetwork_packet_data((ubyte *)&My_Seq, sizeof(sequence_packet), NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node);
2055                 #else
2056                 send_sequence_packet(My_Seq, NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node, NULL);
2057                 #endif
2058         #ifdef MACINTOSH
2059         } else {
2060                 appletalk_send_packet_data( (ubyte *)&My_Seq, sizeof(sequence_packet), NetPlayers.players[i].network.appletalk.node,
2061                                                                         NetPlayers.players[i].network.appletalk.net,
2062                                                                         NetPlayers.players[i].network.appletalk.socket);
2063         #endif
2064         }
2065
2066         return i;
2067 }
2068
2069 int SecurityCheck=0;
2070         
2071 void network_process_gameinfo(ubyte *data)
2072 {
2073 #ifdef MACINTOSH
2074         netgame_info tmp_info;
2075 #endif
2076         int i, j;
2077         netgame_info *new = (netgame_info *)data;
2078
2079 #ifdef MACINTOSH
2080         if (Network_game_type == IPX_GAME)  {
2081                 receive_netgame_packet(data, &tmp_info, 0);                     // get correctly aligned structure
2082                 new = &tmp_info;
2083         }
2084 #endif
2085         
2086
2087    WaitingForPlayerInfo=0;
2088
2089    if (new->Security !=TempPlayersInfo->Security)
2090     {
2091      Int3();     // Get Jason
2092      return;     // If this first half doesn't go with the second half
2093     }
2094
2095         Network_games_changed = 1;
2096
2097    //mprintf((0, "Got game data for game %s.\n", new->game_name));
2098
2099    Assert (TempPlayersInfo!=NULL);
2100
2101         for (i = 0; i < num_active_games; i++)
2102          {
2103           //mprintf ((0,"GAMEINFO: Game %d is %s!\n",i,Active_games[i].game_name));
2104           
2105           if (!stricmp(Active_games[i].game_name, new->game_name) && 
2106                                   Active_games[i].Security==new->Security)
2107                break;
2108          }
2109
2110         if (i == MAX_ACTIVE_NETGAMES)
2111         {
2112                 mprintf((0, "Too many netgames.\n"));
2113                 return;
2114         }
2115         
2116 // MWA  memcpy(&Active_games[i], data, sizeof(netgame_info));
2117         memcpy(&Active_games[i], (ubyte *)new, sizeof(netgame_info));
2118         memcpy (&ActiveNetPlayers[i],TempPlayersInfo,sizeof(AllNetPlayers_info));
2119
2120    if (SecurityCheck)
2121          if (Active_games[i].Security==SecurityCheck)
2122                 SecurityCheck=-1;
2123
2124         //mprintf ((0,"Recieved %d unique games...\n",i));
2125
2126         if (i == num_active_games)
2127                 num_active_games++;
2128
2129         if (Active_games[i].numplayers == 0)
2130         {
2131          mprintf ((0,"DELETING THIS GAME!!!\n"));       
2132                 // Delete this game
2133                 for (j = i; j < num_active_games-1; j++)
2134         {
2135              memcpy(&Active_games[j], &Active_games[j+1], sizeof(netgame_info));
2136            memcpy (&ActiveNetPlayers[j],&ActiveNetPlayers[j+1],sizeof(AllNetPlayers_info));
2137         }
2138                 num_active_games--;
2139                 SecurityCheck=0;
2140         }
2141 }
2142
2143 void network_process_lite_info(ubyte *data)
2144 {
2145 #ifdef MACINTOSH
2146         lite_info tmp_info;
2147 #endif
2148         int i, j;
2149         lite_info *new = (lite_info *)data;
2150
2151 #ifdef MACINTOSH
2152         if (Network_game_type == IPX_GAME) {
2153                 receive_netgame_packet(data, (netgame_info *)&tmp_info, 1);
2154                 new = &tmp_info;
2155         }
2156 #endif
2157
2158         Network_games_changed = 1;
2159
2160    //mprintf((0, "Got game data for game %s.\n", new->game_name));
2161
2162         for (i = 0; i < num_active_games; i++)
2163     {
2164       //mprintf ((0,"GAMEINFO: Game %d is %s!\n",i,Active_games[i].game_name));
2165       
2166       if ((!stricmp(Active_games[i].game_name, new->game_name)) && 
2167                          Active_games[i].Security==new->Security)
2168                                 break;
2169     }
2170
2171         if (i == MAX_ACTIVE_NETGAMES)
2172         {
2173                 mprintf((0, "Too many netgames.\n"));
2174                 return;
2175         }
2176         
2177         memcpy(&Active_games[i], (ubyte *)new, sizeof(lite_info));
2178
2179 // See if this is really a Hoard game
2180 // If so, adjust all the data accordingly
2181
2182         if (HoardEquipped())
2183         {
2184                 if (Active_games[i].game_flags & NETGAME_FLAG_HOARD)
2185                 {
2186                         Active_games[i].gamemode=NETGAME_HOARD;                                   
2187                         Active_games[i].game_status=NETSTAT_PLAYING;
2188                         
2189                         if (Active_games[i].game_flags & NETGAME_FLAG_TEAM_HOARD)
2190                                 Active_games[i].gamemode=NETGAME_TEAM_HOARD;                                      
2191                         if (Active_games[i].game_flags & NETGAME_FLAG_REALLY_ENDLEVEL)
2192                                 Active_games[i].game_status=NETSTAT_ENDLEVEL;
2193                         if (Active_games[i].game_flags & NETGAME_FLAG_REALLY_FORMING)
2194                                 Active_games[i].game_status=NETSTAT_STARTING;
2195                 }
2196         }
2197
2198    //mprintf ((0,"Recieved %d unique games...\n",i));
2199
2200         if (i == num_active_games)
2201                 num_active_games++;
2202
2203         if (Active_games[i].numplayers == 0)
2204     {
2205            mprintf ((0,"DELETING THIS GAME!!!\n"));     
2206                 // Delete this game
2207                 for (j = i; j < num_active_games-1; j++)
2208         {
2209              memcpy(&Active_games[j], &Active_games[j+1], sizeof(netgame_info));
2210         }
2211                 num_active_games--;
2212         }
2213 }
2214
2215 void network_process_dump(sequence_packet *their)
2216 {
2217         // Our request for join was denied.  Tell the user why.
2218
2219    char temp[40];
2220    int i;
2221  
2222         mprintf((0, "Dumped by player %s, type %d.\n", their->player.callsign, their->player.connected));
2223
2224    if (their->player.connected!=7)
2225                 nm_messagebox(NULL, 1, TXT_OK, NET_DUMP_STRINGS(their->player.connected));
2226         else
2227                 {
2228                  for (i=0;i<N_players;i++)
2229                         if (!stricmp (their->player.callsign,Players[i].callsign))
2230                         {
2231                                 if (i!=network_who_is_master())
2232                                 {
2233                                         HUD_init_message ("%s attempted to kick you out.",their->player.callsign);
2234                                 }
2235                                 else
2236                                 {
2237                                   sprintf (temp,"%s has kicked you out!",their->player.callsign);
2238                                   nm_messagebox(NULL, 1, TXT_OK, &temp);
2239                             if (Network_status==NETSTAT_PLAYING)
2240                                   {
2241                                         IWasKicked=1;
2242                                         multi_leave_game();     
2243                                   }
2244                                  else
2245                                         Network_status = NETSTAT_MENU;
2246                       }
2247                    }
2248                 }
2249 }       
2250 void network_process_request(sequence_packet *their)
2251 {
2252         // Player is ready to receieve a sync packet
2253         int i;
2254
2255         mprintf((0, "Player %s ready for sync.\n", their->player.callsign));
2256
2257         for (i = 0; i < N_players; i++) {
2258                 if (Network_game_type == IPX_GAME) {
2259                         if (!memcmp(their->player.network.ipx.server, NetPlayers.players[i].network.ipx.server, 4) && !memcmp(their->player.network.ipx.node, NetPlayers.players[i].network.ipx.node, 6) && (!stricmp(their->player.callsign, NetPlayers.players[i].callsign))) {
2260                                 Players[i].connected = 1;
2261                                 break;
2262                         }
2263                 } else {
2264                         if ( (their->player.network.appletalk.node == NetPlayers.players[i].network.appletalk.node) && (their->player.network.appletalk.net == NetPlayers.players[i].network.appletalk.net) && (!stricmp(their->player.callsign, NetPlayers.players[i].callsign)) ) {
2265                                 Players[i].connected = 1;
2266                                 break;
2267                         }
2268                 }
2269         }                       
2270 }
2271
2272 #define REFUSE_INTERVAL F1_0 * 8
2273 extern void multi_reset_object_texture (object *);
2274
2275 void network_process_packet(ubyte *data, int length )
2276 {
2277 #ifdef MACINTOSH
2278         sequence_packet tmp_packet;
2279 #endif
2280         sequence_packet *their = (sequence_packet *)data;
2281
2282 #ifdef MACINTOSH
2283         if (Network_game_type == IPX_GAME) {
2284                 receive_sequence_packet(data, &tmp_packet);
2285                 their = &tmp_packet;                                            // reassign their to point to correctly alinged structure
2286         }
2287 #endif
2288
2289    //mprintf( (0, "Got packet of length %d, type %d\n", length, their->type ));
2290         
2291 //      if ( length < sizeof(sequence_packet) ) return;
2292
2293         length = length;
2294
2295         switch( data[0] )       {
2296         
2297          case PID_GAME_INFO:            // Jason L. says we can safely ignore this type.
2298                 break;
2299         
2300      case PID_PLAYERSINFO:
2301
2302                 mprintf ((0,"Got a PID_PLAYERSINFO!\n"));
2303
2304                 if (Network_status==NETSTAT_WAITING)
2305                 {
2306 #ifndef MACINTOSH                        
2307                         memcpy (&TempPlayersBase,data,sizeof(AllNetPlayers_info));
2308 #else
2309                         if (Network_game_type == IPX_GAME)
2310                                 receive_netplayers_packet(data, &TempPlayersBase);
2311                         else
2312                                 memcpy (&TempPlayersBase,data,sizeof(AllNetPlayers_info));
2313 #endif
2314
2315                         if (TempPlayersBase.Security!=Netgame.Security)
2316                          {
2317                           mprintf ((0,"Bad security for PLAYERSINFO\n"));
2318                           break;
2319                          }      
2320                 
2321                         mprintf ((0,"Got a waiting PID_PLAYERSINFO!\n"));
2322                         if (length!=ALLNETPLAYERSINFO_SIZE)
2323                         {
2324                                 mprintf ((0,"Invalid size for netplayers packet!\n"));
2325                                 return;
2326                         }
2327
2328                         TempPlayersInfo=&TempPlayersBase;
2329                         WaitingForPlayerInfo=0;
2330                         NetSecurityNum=TempPlayersInfo->Security;
2331                         NetSecurityFlag=NETSECURITY_WAIT_FOR_SYNC;
2332            }
2333
2334      break;
2335
2336    case PID_LITE_INFO:
2337
2338          if (length != LITE_INFO_SIZE)
2339                  {
2340                   mprintf ((0,"WARNING! Recieved invalid size for PID_LITE_INFO\n"));
2341                   return;
2342                  }
2343  
2344          if (Network_status == NETSTAT_BROWSING)
2345                 network_process_lite_info (data);
2346     break;
2347
2348         case PID_GAME_LIST:
2349                 // Someone wants a list of games
2350
2351            if (length != SEQUENCE_PACKET_SIZE)
2352                  {
2353                   mprintf ((0,"WARNING! Recieved invalid size for PID_GAME_LIST\n"));
2354                   return;
2355                  }
2356                         
2357                 mprintf((0, "Got a PID_GAME_LIST!\n"));
2358                 if ((Network_status == NETSTAT_PLAYING) || (Network_status == NETSTAT_STARTING) || (Network_status == NETSTAT_ENDLEVEL))
2359                         if (network_i_am_master())
2360                                 network_send_lite_info(their);
2361                 break;
2362
2363
2364         case PID_SEND_ALL_GAMEINFO:
2365
2366            if (length != SEQUENCE_PACKET_SIZE)
2367                  {
2368                   mprintf ((0,"WARNING! Recieved invalid size for PID_SEND_ALL_GAMEINFO\n"));
2369                   return;
2370                  }
2371
2372                 if ((Network_status == NETSTAT_PLAYING) || (Network_status == NETSTAT_STARTING) || (Network_status == NETSTAT_ENDLEVEL))
2373                         if (network_i_am_master() && their->Security==Netgame.Security)
2374                                 network_send_game_info(their);
2375                 break;
2376         
2377         case PID_ADDPLAYER:
2378
2379                 mprintf( (0, "Got NEWPLAYER message from %s.\n", their->player.callsign));
2380                 
2381            if (length != SEQUENCE_PACKET_SIZE)
2382                  {
2383                   mprintf ((0,"WARNING! Recieved invalid size for PID_ADDPLAYER\n"));
2384                   return;
2385                  }
2386                 mprintf( (0, "Got NEWPLAYER message from %s.\n", their->player.callsign));
2387                 network_new_player(their);
2388                 break;                  
2389         case PID_REQUEST:
2390            if (length != SEQUENCE_PACKET_SIZE)
2391                  {
2392                   mprintf ((0,"WARNING! Recieved invalid size for PID_REQUEST\n"));
2393                   return;
2394                  }
2395
2396                 mprintf( (0, "Got REQUEST from '%s'\n", their->player.callsign ));
2397                 if (Network_status == NETSTAT_STARTING) 
2398                 {
2399                         // Someone wants to join our game!
2400                         network_add_player(their);
2401                 }
2402                 else if (Network_status == NETSTAT_WAITING)
2403                 {
2404                         // Someone is ready to recieve a sync packet
2405                         network_process_request(their);
2406                 }
2407                 else if (Network_status == NETSTAT_PLAYING)
2408                 {
2409                         // Someone wants to join a game in progress!
2410                         if (Netgame.RefusePlayers)
2411                 DoRefuseStuff (their);
2412                    else 
2413                                 network_welcome_player(their);
2414                 }
2415                 break;
2416         case PID_DUMP:  
2417
2418            if (length != SEQUENCE_PACKET_SIZE)
2419                  {
2420                   mprintf ((0,"WARNING! Recieved invalid size for PID_DUMP\n"));
2421                   return;
2422                  }
2423   
2424                 if (Network_status == NETSTAT_WAITING || Network_status==NETSTAT_PLAYING )
2425                         network_process_dump(their);
2426                 break;
2427         case PID_QUIT_JOINING:
2428
2429            if (length != SEQUENCE_PACKET_SIZE)
2430                  {
2431                   mprintf ((0,"WARNING! Recieved invalid size for PID_QUIT_JOINING\n"));
2432                   return;
2433                  }
2434                 if (Network_status == NETSTAT_STARTING)
2435                         network_remove_player( their );
2436                 else if ((Network_status == NETSTAT_PLAYING) && (Network_send_objects))
2437                         network_stop_resync( their );
2438                 break;
2439         case PID_SYNC:  
2440
2441                 mprintf ((0,"Got a sync packet! Network_status=%d\n",NETSTAT_WAITING));
2442
2443                 if (Network_status == NETSTAT_WAITING)  {
2444
2445 #ifndef MACINTOSH
2446                         memcpy((ubyte *)&(TempNetInfo), data, sizeof(netgame_info));
2447 #else
2448                         if (Network_game_type == IPX_GAME)
2449                                 receive_netgame_packet(data, &TempNetInfo, 0);
2450                         else
2451                                 memcpy((ubyte *)&(TempNetInfo), data, sizeof(netgame_info));
2452 #endif
2453
2454                         if (TempNetInfo.Security!=Netgame.Security)
2455                          {
2456                                 mprintf ((0,"Bad security on sync packet.\n"));
2457                                 break;
2458                          }
2459
2460                         if (NetSecurityFlag==NETSECURITY_WAIT_FOR_SYNC)
2461                          {
2462                           if (TempNetInfo.Security==TempPlayersInfo->Security)
2463                           {
2464                                 network_read_sync_packet (&TempNetInfo,0);
2465                                 NetSecurityFlag=0;
2466                                 NetSecurityNum=0;
2467                           }     
2468                          }
2469                         else
2470                          {      
2471                         NetSecurityFlag=NETSECURITY_WAIT_FOR_PLAYERS;
2472                         NetSecurityNum=TempNetInfo.Security;
2473
2474                         if ( network_wait_for_playerinfo())
2475                                 network_read_sync_packet((netgame_info *)data,0);
2476  
2477                         NetSecurityFlag=0;
2478                         NetSecurityNum=0;
2479                          }
2480                 }
2481                 break;
2482
2483         case PID_PDATA: 
2484                 if ((Game_mode&GM_NETWORK) && ((Network_status == NETSTAT_PLAYING)||(Network_status == NETSTAT_ENDLEVEL) || Network_status==NETSTAT_WAITING)) { 
2485                         network_process_pdata((char *)data);
2486                 }
2487                 break;
2488    case PID_NAKED_PDATA:
2489                 if ((Game_mode&GM_NETWORK) && ((Network_status == NETSTAT_PLAYING)||(Network_status == NETSTAT_ENDLEVEL) || Network_status==NETSTAT_WAITING)) 
2490                         network_process_naked_pdata((char *)data,length);
2491            break;
2492
2493         case PID_OBJECT_DATA:
2494                 if (Network_status == NETSTAT_WAITING) 
2495                         network_read_object_packet(data);
2496                 break;
2497         case PID_ENDLEVEL:
2498                 if ((Network_status == NETSTAT_ENDLEVEL) || (Network_status == NETSTAT_PLAYING))
2499                         network_read_endlevel_packet(data);
2500                 else
2501                         mprintf((0, "Junked endlevel packet.\n"));
2502                 break;
2503         case PID_ENDLEVEL_SHORT:
2504                 if ((Network_status == NETSTAT_ENDLEVEL) || (Network_status == NETSTAT_PLAYING))
2505                         network_read_endlevel_short_packet(data);
2506                 else
2507                         mprintf((0, "Junked short endlevel packet!\n"));
2508                 break;
2509
2510         case PID_GAME_UPDATE:
2511                 mprintf ((0,"Got a GAME_UPDATE!\n"));
2512                         
2513                 if (Network_status==NETSTAT_PLAYING)
2514                  {
2515 #ifndef MACINTOSH
2516                         memcpy((ubyte *)&TempNetInfo, data, sizeof(lite_info) );
2517 #else
2518                         if (Network_game_type == IPX_GAME)
2519                                 receive_netgame_packet(data, &TempNetInfo, 1);
2520                         else
2521                                 memcpy((ubyte *)&TempNetInfo, data, sizeof(lite_info) );
2522 #endif
2523                   if (TempNetInfo.Security==Netgame.Security)
2524                          memcpy (&Netgame,(ubyte *)&TempNetInfo,sizeof(lite_info));
2525                  }
2526                 if (Game_mode & GM_TEAM)
2527                  {
2528                         int i;
2529
2530                         for (i=0;i<N_players;i++)
2531                          if (Players[i].connected)
2532                         multi_reset_object_texture (&Objects[Players[i].objnum]);
2533                     reset_cockpit();
2534                  }
2535            break;
2536    case PID_PING_SEND:
2537                 network_ping (PID_PING_RETURN,data[1]);
2538                 break;
2539    case PID_PING_RETURN:
2540                 network_handle_ping_return(data[1]);  // data[1] is player who told us of their ping time
2541                 break;
2542    case PID_NAMES_RETURN:
2543                 if (Network_status==NETSTAT_BROWSING && NamesInfoSecurity!=-1)
2544                   network_process_names_return (data);
2545                 break;
2546         case PID_GAME_PLAYERS:
2547                 // Someone wants a list of players in this game
2548
2549            if (length != SEQUENCE_PACKET_SIZE)
2550                  {
2551                   mprintf ((0,"WARNING! Recieved invalid size for PID_GAME_PLAYERS\n"));
2552                   return;
2553                  }
2554                         
2555                 mprintf((0, "Got a PID_GAME_PLAYERS!\n"));
2556                 if ((Network_status == NETSTAT_PLAYING) || (Network_status == NETSTAT_STARTING) || (Network_status == NETSTAT_ENDLEVEL))
2557                         if (network_i_am_master() && their->Security==Netgame.Security)
2558                                 network_send_player_names(their);
2559                 break;
2560
2561         default:
2562                 mprintf((0, "Ignoring invalid packet type.\n"));
2563                 Int3(); // Invalid network packet type, see ROB
2564            break;
2565         }
2566 }
2567
2568 #ifndef NDEBUG
2569 void dump_segments()
2570 {
2571         FILE * fp;
2572
2573         fp = fopen( "TEST.DMP", "wb" );
2574         fwrite( Segments, sizeof(segment)*(Highest_segment_index+1),1, fp );    
2575         fclose(fp);
2576         mprintf( (0, "SS=%d\n", sizeof(segment) ));
2577 }
2578 #endif
2579
2580
2581 void
2582 network_read_endlevel_packet( ubyte *data )
2583 {
2584         // Special packet for end of level syncing
2585 #ifdef MACINTOSH
2586         int i, j;
2587 #endif
2588         int playernum;
2589         endlevel_info *end;     
2590
2591         end = (endlevel_info *)data;
2592 #ifdef MACINTOSH
2593         for (i = 0; i < MAX_PLAYERS; i++)
2594                 for (j = 0; j < MAX_PLAYERS; j++)
2595                         end->kill_matrix[i][j] = INTEL_SHORT(end->kill_matrix[i][j]);
2596         end->kills = INTEL_SHORT(end->kills);
2597         end->killed = INTEL_SHORT(end->killed);
2598 #endif
2599
2600         playernum = end->player_num;
2601         
2602         Assert(playernum != Player_num);
2603     
2604         if (playernum>=N_players)
2605          {              
2606                 Int3(); // weird, but it an happen in a coop restore game
2607                 return; // if it happens in a coop restore, don't worry about it
2608          }
2609
2610         if ((Network_status == NETSTAT_PLAYING) && (end->connected != 0))
2611                 return; // Only accept disconnect packets if we're not out of the level yet
2612
2613         Players[playernum].connected = end->connected;
2614         memcpy(&kill_matrix[playernum][0], end->kill_matrix, MAX_PLAYERS*sizeof(short));
2615         Players[playernum].net_kills_total = end->kills;
2616         Players[playernum].net_killed_total = end->killed;
2617
2618         if ((Players[playernum].connected == 1) && (end->seconds_left < Countdown_seconds_left))
2619                 Countdown_seconds_left = end->seconds_left;
2620
2621         LastPacketTime[playernum] = timer_get_approx_seconds();
2622
2623 //      mprintf((0, "Got endlevel packet from player %d.\n", playernum));
2624 }
2625
2626 void
2627 network_read_endlevel_short_packet( ubyte *data )
2628 {
2629         // Special packet for end of level syncing
2630
2631         int playernum;
2632         endlevel_info_short *end;       
2633
2634         end = (endlevel_info_short *)data;
2635
2636         playernum = end->player_num;
2637         
2638         Assert(playernum != Player_num);
2639     
2640         if (playernum>=N_players)
2641          {              
2642                 Int3(); // weird, but it can happen in a coop restore game
2643                 return; // if it happens in a coop restore, don't worry about it
2644          }
2645
2646         if ((Network_status == NETSTAT_PLAYING) && (end->connected != 0))
2647          {
2648                 //mprintf ((0,"Returning early for short_endlevel\n"));
2649                 return; // Only accept disconnect packets if we're not out of the level yet
2650          }
2651
2652         Players[playernum].connected = end->connected;
2653
2654         if ((Players[playernum].connected == 1) && (end->seconds_left < Countdown_seconds_left))
2655                 Countdown_seconds_left = end->seconds_left;
2656
2657         LastPacketTime[playernum] = timer_get_approx_seconds();
2658 }
2659
2660
2661 void
2662 network_pack_objects(void)
2663 {
2664         // Switching modes, pack the object array
2665
2666         special_reset_objects();
2667 }                               
2668
2669 int
2670 network_verify_objects(int remote, int local)
2671 {
2672         int i;
2673         int nplayers, got_controlcen=0;
2674
2675    mprintf ((0,"NETWORK:remote=%d local=%d\n",remote,local));
2676
2677         if ((remote-local) > 10)
2678                 return(-1);
2679
2680         if (Game_mode & GM_MULTI_ROBOTS)
2681                 got_controlcen = 1;
2682
2683         nplayers = 0;
2684
2685         for (i = 0; i <= Highest_object_index; i++)
2686         {
2687                 if ((Objects[i].type == OBJ_PLAYER) || (Objects[i].type == OBJ_GHOST))
2688                         nplayers++;
2689                 if (Objects[i].type == OBJ_CNTRLCEN)
2690                         got_controlcen=1;
2691         }
2692
2693     if (got_controlcen && (MaxNumNetPlayers<=nplayers))
2694                 return(0);
2695
2696         return(1);
2697 }
2698         
2699 void
2700 network_read_object_packet( ubyte *data )
2701 {
2702         // Object from another net player we need to sync with
2703
2704         short objnum, remote_objnum;
2705         byte obj_owner;
2706         int segnum, i;
2707         object *obj;
2708
2709         static int my_pnum = 0;
2710         static int mode = 0;
2711         static int object_count = 0;
2712         static int frame_num = 0;
2713         int nobj = data[1];
2714         int loc = 3;
2715         int remote_frame_num = data[2];
2716         
2717         frame_num++;
2718
2719 //      mprintf((0, "Object packet %d (remote #%d) contains %d objects.\n", frame_num, remote_frame_num, nobj));
2720
2721         for (i = 0; i < nobj; i++)
2722         {
2723                 objnum = INTEL_SHORT( *(short *)(data+loc) );                   loc += 2;
2724                 obj_owner = data[loc];                                                                  loc += 1;
2725                 remote_objnum = INTEL_SHORT( *(short *)(data+loc) );    loc += 2;
2726
2727                 if (objnum == -1) 
2728                 {
2729                         // Clear object array
2730                         mprintf((0, "Clearing object array.\n"));
2731
2732                         init_objects();
2733                         Network_rejoined = 1;
2734                         my_pnum = obj_owner;
2735                         change_playernum_to(my_pnum);
2736                         mode = 1;
2737                         object_count = 0;
2738                         frame_num = 1;
2739                 }
2740                 else if (objnum == -2)
2741                 {
2742                         // Special debug checksum marker for entire send
2743                         if (mode == 1)
2744                         {
2745                                 network_pack_objects();
2746                                 mode = 0;
2747                         }
2748                         mprintf((0, "Objnum -2 found in frame local %d remote %d.\n", frame_num, remote_frame_num));
2749                         mprintf((0, "Got %d objects, expected %d.\n", object_count, remote_objnum));
2750                         if (remote_objnum != object_count) {
2751                                 Int3();
2752                         }
2753                         if (network_verify_objects(remote_objnum, object_count))
2754                         {
2755                                 // Failed to sync up 
2756                                 nm_messagebox(NULL, 1, TXT_OK, TXT_NET_SYNC_FAILED);
2757                                 Network_status = NETSTAT_MENU;                          
2758                                 return;
2759                         }
2760                         frame_num = 0;
2761                 }
2762                 else 
2763                 {
2764                         if (frame_num != remote_frame_num)
2765                                 Int3();
2766                         mprintf ((0,"Got a type 3 object packet!\n"));
2767                         object_count++;
2768                         if ((obj_owner == my_pnum) || (obj_owner == -1)) 
2769                         {
2770                                 if (mode != 1)
2771                                         Int3(); // SEE ROB
2772                                 objnum = remote_objnum;
2773                                 //if (objnum > Highest_object_index)
2774                                 //{
2775                                 //      Highest_object_index = objnum;
2776                                 //      num_objects = Highest_object_index+1;
2777                                 //}
2778                         }
2779                         else {
2780                                 if (mode == 1)
2781                                 {
2782                                         network_pack_objects();
2783                                         mode = 0;
2784                                 }
2785                                 objnum = obj_allocate();
2786                         }
2787                         if (objnum != -1) {
2788                                 obj = &Objects[objnum];
2789                                 if (obj->segnum != -1)
2790                                         obj_unlink(objnum);
2791                                 Assert(obj->segnum == -1);
2792                                 Assert(objnum < MAX_OBJECTS);
2793                                 memcpy(obj,data+loc,sizeof(object));            loc += sizeof(object);
2794 #ifdef MACINTOSH
2795                                 if (Network_game_type == IPX_GAME)
2796                                         swap_object(obj);
2797 #endif
2798                                 segnum = obj->segnum;
2799                                 obj->next = obj->prev = obj->segnum = -1;
2800                                 obj->attached_obj = -1;
2801                                 if (segnum > -1)
2802                                         obj_link(obj-Objects,segnum);
2803                                 if (obj_owner == my_pnum) 
2804                                         map_objnum_local_to_local(objnum);
2805                                 else if (obj_owner != -1)
2806                                         map_objnum_local_to_remote(objnum, remote_objnum, obj_owner);
2807                                 else
2808                                         object_owner[objnum] = -1;
2809                         }
2810                 } // For a standard onbject
2811         } // For each object in packet
2812 }
2813         
2814 void network_sync_poll( int nitems, newmenu_item * menus, int * key, int citem )
2815 {
2816         // Polling loop waiting for sync packet to start game
2817
2818         static fix t1 = 0;
2819
2820         menus = menus;
2821         citem = citem;
2822         nitems = nitems;
2823
2824         network_listen();
2825
2826         if (Network_status != NETSTAT_WAITING)  // Status changed to playing, exit the menu
2827                 *key = -2;
2828
2829         if (!Network_rejoined && (timer_get_approx_seconds() > t1+F1_0*2))
2830         {
2831                 int i;
2832
2833                 // Poll time expired, re-send request
2834                 
2835                 t1 = timer_get_approx_seconds();
2836
2837                 mprintf((0, "Re-sending join request.\n"));
2838                 i = network_send_request();
2839                 if (i < 0)
2840                         *key = -2;
2841         }
2842 }
2843
2844 void network_start_poll( int nitems, newmenu_item * menus, int * key, int citem )
2845 {
2846         int i,n,nm;
2847
2848         key=key;
2849         citem=citem;
2850
2851         Assert(Network_status == NETSTAT_STARTING);
2852
2853         if (!menus[0].value) {
2854                         menus[0].value = 1;
2855                         menus[0].redraw = 1;
2856         }
2857
2858         for (i=1; i<nitems; i++ )       {
2859                 if ( (i>= N_players) && (menus[i].value) )      {
2860                         menus[i].value = 0;
2861                         menus[i].redraw = 1;
2862                 }
2863         }
2864
2865         nm = 0;
2866         for (i=0; i<nitems; i++ )       {
2867                 if ( menus[i].value )   {
2868                         nm++;
2869                         if ( nm > N_players )   {
2870                                 menus[i].value = 0;
2871                                 menus[i].redraw = 1;
2872                         }
2873                 }
2874         }
2875
2876         if ( nm > MaxNumNetPlayers )    {
2877                 nm_messagebox( TXT_ERROR, 1, TXT_OK, "%s %d %s", TXT_SORRY_ONLY, MaxNumNetPlayers, TXT_NETPLAYERS_IN );
2878                 // Turn off the last player highlighted
2879                 for (i = N_players; i > 0; i--)
2880                         if (menus[i].value == 1) 
2881                         {
2882                                 menus[i].value = 0;
2883                                 menus[i].redraw = 1;
2884                                 break;
2885                         }
2886         }
2887
2888 //       if (nitems > MAX_PLAYERS ) return; 
2889         
2890         n = Netgame.numplayers;
2891         network_listen();
2892
2893         if (n < Netgame.numplayers )    
2894         {
2895                 digi_play_sample (SOUND_HUD_MESSAGE,F1_0);
2896
2897       mprintf ((0,"More players are printed!"));
2898                 if (FindArg("-norankings"))
2899               sprintf( menus[N_players-1].text, "%d. %-20s", N_players,NetPlayers.players[N_players-1].callsign );
2900                 else
2901               sprintf( menus[N_players-1].text, "%d. %s%-20s", N_players, RankStrings[NetPlayers.players[N_players-1].rank],NetPlayers.players[N_players-1].callsign );
2902
2903                 menus[N_players-1].redraw = 1;
2904                 if (N_players <= MaxNumNetPlayers)
2905                 {
2906                         menus[N_players-1].value = 1;
2907                 }
2908         } 
2909         else if ( n > Netgame.numplayers )      
2910         {
2911                 // One got removed...
2912
2913       digi_play_sample (SOUND_HUD_KILL,F1_0);
2914   
2915                 for (i=0; i<N_players; i++ )    
2916                 {
2917          
2918          if (FindArg("-norankings"))    
2919                  sprintf( menus[i].text, "%d. %-20s", i+1, NetPlayers.players[i].callsign );
2920          else
2921                  sprintf( menus[i].text, "%d. %s%-20s", i+1, RankStrings[NetPlayers.players[i].rank],NetPlayers.players[i].callsign );
2922                         if (i < MaxNumNetPlayers)
2923                                 menus[i].value = 1;
2924                         else
2925                                 menus[i].value = 0;
2926                         menus[i].redraw = 1;
2927                 }
2928                 for (i=N_players; i<n; i++ )    
2929                 {
2930                         sprintf( menus[i].text, "%d. ", i+1 );          // Clear out the deleted entries...
2931                         menus[i].value = 0;
2932                         menus[i].redraw = 1;
2933                 }
2934    }
2935 }
2936
2937 int opt_cinvul, opt_team_anarchy, opt_coop, opt_show_on_map, opt_closed,opt_maxnet;
2938 int last_cinvul=0,last_maxnet,opt_team_hoard;
2939 int opt_refuse,opt_capture;
2940
2941 void network_game_param_poll( int nitems, newmenu_item * menus, int * key, int citem )
2942 {
2943         static int oldmaxnet=0;
2944
2945         if (((HoardEquipped() && menus[opt_team_hoard].value) || (menus[opt_team_anarchy].value || menus[opt_capture].value)) && !menus[opt_closed].value && !menus[opt_refuse].value) { 
2946                 menus[opt_refuse].value = 1;
2947                 menus[opt_refuse].redraw = 1;
2948                 menus[opt_refuse-1].value = 0;
2949                 menus[opt_refuse-1].redraw = 1;
2950                 menus[opt_refuse-2].value = 0;
2951                 menus[opt_refuse-2].redraw = 1;
2952         }
2953
2954         #ifndef MACINTOSH
2955         if (menus[opt_coop].value)
2956         #else
2957         if ( (menus[opt_coop].value) || ((Network_game_type == APPLETALK_GAME) && (Network_appletalk_type == LOCALTALK_TYPE) && (menus[opt_coop-1].value)) )
2958         #endif
2959         {
2960                 oldmaxnet=1;
2961
2962                 if (menus[opt_maxnet].value>2) 
2963                 {
2964                     menus[opt_maxnet].value=2;
2965                     menus[opt_maxnet].redraw=1;
2966                 }
2967
2968                 if (menus[opt_maxnet].max_value>2)
2969                 {
2970                     menus[opt_maxnet].max_value=2;
2971                     menus[opt_maxnet].redraw=1;
2972                 }
2973
2974                 #ifdef MACINTOSH
2975                 if ( (Network_game_type == APPLETALK_GAME) && (Network_appletalk_type == LOCALTALK_TYPE) ) {
2976                         if (menus[opt_maxnet].value > 0) {
2977                             menus[opt_maxnet].value=0;
2978                             menus[opt_maxnet].redraw=1;
2979                         }
2980                         if (menus[opt_maxnet].max_value > 0) {
2981                                 menus[opt_maxnet].max_value=0;
2982                                 menus[opt_maxnet].redraw=1;
2983                         }
2984                 }
2985                 #endif
2986
2987              if (!Netgame.game_flags & NETGAME_FLAG_SHOW_MAP) 
2988                         Netgame.game_flags |= NETGAME_FLAG_SHOW_MAP;
2989
2990                 if (Netgame.PlayTimeAllowed || Netgame.KillGoal)
2991                 {
2992                     Netgame.PlayTimeAllowed=0;
2993                     Netgame.KillGoal=0;
2994                 }
2995
2996         }
2997         else // if !Coop game
2998     {
2999                 if (oldmaxnet)
3000                 {
3001                     oldmaxnet=0;
3002                         menus[opt_maxnet].value=6;
3003                         menus[opt_maxnet].max_value=6;
3004
3005                     #ifdef MACINTOSH
3006                         if ( (Network_game_type == APPLETALK_GAME) && (Network_appletalk_type == LOCALTALK_TYPE) ) {
3007                                 menus[opt_maxnet].value=1;
3008                                 menus[opt_maxnet].max_value=1;
3009                         }
3010                         #endif
3011                           
3012                 }
3013         }         
3014
3015     if ( last_maxnet != menus[opt_maxnet].value )   
3016         {
3017                 sprintf( menus[opt_maxnet].text, "Maximum players: %d", menus[opt_maxnet].value+2 );
3018                 last_maxnet = menus[opt_maxnet].value;
3019                 menus[opt_maxnet].redraw = 1;
3020         }               
3021  }
3022
3023 int netgame_difficulty;
3024
3025 int network_get_game_params( char * game_name, int *mode, int *game_flags, int *level )
3026 {
3027         int i;
3028    int opt, opt_name, opt_level, opt_mode,opt_moreopts;
3029         newmenu_item m[20];
3030         char name[NETGAME_NAME_LEN+1];
3031         char slevel[5];
3032         char level_text[32];
3033    char srmaxnet[50];
3034
3035         int new_mission_num;
3036         int anarchy_only;
3037             
3038    *game_flags=*game_flags;
3039
3040    SetAllAllowablesTo (1);
3041    NamesInfoSecurity=-1;
3042
3043         for (i=0;i<MAX_PLAYERS;i++)
3044          if (i!=Player_num)     
3045                 Players[i].callsign[0]=0;    
3046
3047         MaxNumNetPlayers=8;
3048    Netgame.KillGoal=0;
3049    Netgame.PlayTimeAllowed=0;
3050         Netgame.Allow_marker_view=1;
3051         netgame_difficulty=Player_default_difficulty;
3052
3053         new_mission_num = multi_choose_mission(&anarchy_only);
3054
3055         if (new_mission_num < 0)
3056                 return -1;
3057
3058    if (!(FindArg ("-packets") && FindArg ("-shortpackets")))
3059            if (!network_choose_connect ())
3060                         return -1;
3061
3062         #ifdef MACINTOSH
3063         if ( (Network_game_type == APPLETALK_GAME) && (Network_appletalk_type == LOCALTALK_TYPE) )
3064                 MaxNumNetPlayers = 3;
3065         #endif
3066         
3067         strcpy(Netgame.mission_name, Mission_list[new_mission_num].filename);
3068         strcpy(Netgame.mission_title, Mission_list[new_mission_num].mission_name);
3069         Netgame.control_invul_time = control_invul_time;
3070         
3071         sprintf( name, "%s%s", Players[Player_num].callsign, TXT_S_GAME );
3072         sprintf( slevel, "1" );
3073
3074         opt = 0;
3075         m[opt].type = NM_TYPE_TEXT; m[opt].text = TXT_DESCRIPTION; opt++;
3076
3077         opt_name = opt;
3078         m[opt].type = NM_TYPE_INPUT; m[opt].text = name; m[opt].text_len = NETGAME_NAME_LEN; opt++;
3079
3080         sprintf(level_text, "%s (1-%d)", TXT_LEVEL_, Last_level);
3081
3082 //      if (Last_secret_level < -1)
3083 //              sprintf(level_text+strlen(level_text)-1, ", S1-S%d)", -Last_secret_level);
3084 //      else if (Last_secret_level == -1)
3085 //              sprintf(level_text+strlen(level_text)-1, ", S1)");
3086
3087         Assert(strlen(level_text) < 32);
3088
3089         m[opt].type = NM_TYPE_TEXT; m[opt].text = level_text; opt++;
3090
3091         opt_level = opt;
3092         m[opt].type = NM_TYPE_INPUT; m[opt].text = slevel; m[opt].text_len=4; opt++;
3093 //      m[opt].type = NM_TYPE_TEXT; m[opt].text = TXT_OPTIONS; opt++;
3094         
3095         opt_mode = opt;
3096         m[opt].type = NM_TYPE_RADIO; m[opt].text = TXT_ANARCHY; m[opt].value=1; m[opt].group=0; opt++;
3097         m[opt].type = NM_TYPE_RADIO; m[opt].text = TXT_TEAM_ANARCHY; m[opt].value=0; m[opt].group=0; opt_team_anarchy=opt; opt++;
3098         m[opt].type = NM_TYPE_RADIO; m[opt].text = TXT_ANARCHY_W_ROBOTS; m[opt].value=0; m[opt].group=0; opt++;
3099         m[opt].type = NM_TYPE_RADIO; m[opt].text = TXT_COOPERATIVE; m[opt].value=0; m[opt].group=0; opt_coop=opt; opt++;
3100         m[opt].type = NM_TYPE_RADIO; m[opt].text = "Capture the flag"; m[opt].value=0; m[opt].group=0; opt_capture=opt; opt++;
3101    
3102         if (HoardEquipped())
3103         {
3104                 m[opt].type = NM_TYPE_RADIO; m[opt].text = "Hoard"; m[opt].value=0; m[opt].group=0; opt++;
3105                 m[opt].type = NM_TYPE_RADIO; m[opt].text = "Team Hoard"; m[opt].value=0; m[opt].group=0; opt_team_hoard=opt; opt++;
3106            m[opt].type = NM_TYPE_TEXT; m[opt].text = ""; opt++;
3107         } 
3108         else
3109          {  m[opt].type = NM_TYPE_TEXT; m[opt].text = ""; opt++; }
3110
3111         m[opt].type = NM_TYPE_RADIO; m[opt].text = "Open game"; m[opt].group=1; m[opt].value=0; opt++;
3112         opt_closed = opt;
3113         m[opt].type = NM_TYPE_RADIO; m[opt].text = TXT_CLOSED_GAME; m[opt].group=1; m[opt].value=0; opt++;
3114    opt_refuse = opt;
3115    m[opt].type = NM_TYPE_RADIO; m[opt].text = "Restricted Game              "; m[opt].group=1; m[opt].value=Netgame.RefusePlayers; opt++;
3116
3117 //      m[opt].type = NM_TYPE_CHECK; m[opt].text = TXT_SHOW_IDS; m[opt].value=0; opt++;
3118
3119    opt_maxnet = opt;
3120    sprintf( srmaxnet, "Maximum players: %d", MaxNumNetPlayers);
3121    m[opt].type = NM_TYPE_SLIDER; m[opt].value=MaxNumNetPlayers-2; m[opt].text= srmaxnet; m[opt].min_value=0; 
3122    m[opt].max_value=MaxNumNetPlayers-2; opt++;
3123    last_maxnet=MaxNumNetPlayers-2;
3124
3125    opt_moreopts=opt;
3126    m[opt].type = NM_TYPE_MENU;  m[opt].text = "More options..."; opt++;
3127
3128         Assert(opt <= 20);
3129
3130 menu:
3131    ExtGameStatus=GAMESTAT_NETGAME_OPTIONS; 
3132         i = newmenu_do1( NULL, NULL, opt, m, network_game_param_poll, 1 );
3133                                                                         //TXT_NETGAME_SETUP
3134    if (i==opt_moreopts)
3135     {
3136      if ( m[opt_mode+3].value )
3137       Game_mode=GM_MULTI_COOP;
3138      network_more_game_options();
3139      Game_mode=0;
3140      goto menu;
3141     }
3142   Netgame.RefusePlayers=m[opt_refuse].value;
3143
3144
3145         if ( i > -1 )   {
3146                 int j;
3147                       
3148    MaxNumNetPlayers = m[opt_maxnet].value+2;
3149    Netgame.max_numplayers=MaxNumNetPlayers;
3150                                 
3151                 for (j = 0; j < num_active_games; j++)
3152                         if (!stricmp(Active_games[j].game_name, name))
3153                         {
3154                                 nm_messagebox(TXT_ERROR, 1, TXT_OK, TXT_DUPLICATE_NAME);
3155                                 goto menu;
3156                         }
3157
3158                 strcpy( game_name, name );
3159                 
3160
3161                 *level = atoi(slevel);
3162
3163                 if ((*level < 1) || (*level > Last_level))
3164                 {
3165                         nm_messagebox(TXT_ERROR, 1, TXT_OK, TXT_LEVEL_OUT_RANGE );
3166                         sprintf(slevel, "1");
3167                         goto menu;
3168                 }
3169                 if ( m[opt_mode].value )
3170                         *mode = NETGAME_ANARCHY;
3171
3172 #ifdef SHAREWARE
3173                 else 
3174                 {
3175                         nm_messagebox(TXT_SORRY, 1, TXT_OK, TXT_REGISTERED_ONLY );
3176                         m[opt_mode+1].value = 0;
3177                         m[opt_mode+2].value = 0;
3178                         m[opt_mode+3].value = 0;
3179                    if (HoardEquipped())
3180                                 m[opt_mode+4].value = 0;
3181
3182                         m[opt_mode].value = 1;
3183                         goto menu;
3184                 }
3185 #else
3186                 else if (m[opt_mode+1].value) {
3187                         *mode = NETGAME_TEAM_ANARCHY;
3188                 }
3189                 else if (m[opt_capture].value)
3190                         *mode = NETGAME_CAPTURE_FLAG;
3191                 else if (HoardEquipped() && m[opt_capture+1].value)
3192                                 *mode = NETGAME_HOARD;
3193                 else if (HoardEquipped() && m[opt_capture+2].value)
3194                                 *mode = NETGAME_TEAM_HOARD;
3195                 else if (anarchy_only) {
3196                         nm_messagebox(NULL, 1, TXT_OK, TXT_ANARCHY_ONLY_MISSION);
3197                         m[opt_mode+2].value = 0;
3198                         m[opt_mode+3].value = 0;
3199                         m[opt_mode].value = 1;
3200                         goto menu;
3201                 }               
3202                 else if ( m[opt_mode+2].value ) 
3203                         *mode = NETGAME_ROBOT_ANARCHY;
3204                 else if ( m[opt_mode+3].value ) 
3205                         *mode = NETGAME_COOPERATIVE;
3206                 else Int3(); // Invalid mode -- see Rob
3207 #endif
3208                 if (m[opt_closed].value)
3209                         Netgame.game_flags |= NETGAME_FLAG_CLOSED;
3210       
3211         }
3212
3213         return i;
3214 }
3215
3216 void
3217 network_set_game_mode(int gamemode)
3218 {
3219         Show_kill_list = 1;
3220
3221         if ( gamemode == NETGAME_ANARCHY )
3222                 Game_mode = GM_NETWORK;
3223         else if ( gamemode == NETGAME_ROBOT_ANARCHY )
3224                 Game_mode = GM_NETWORK | GM_MULTI_ROBOTS;
3225         else if ( gamemode == NETGAME_COOPERATIVE ) 
3226                 Game_mode = GM_NETWORK | GM_MULTI_COOP | GM_MULTI_ROBOTS;
3227         else if (gamemode == NETGAME_CAPTURE_FLAG)
3228                 {
3229                  Game_mode = GM_NETWORK | GM_TEAM | GM_CAPTURE;
3230                  Show_kill_list=3;
3231                 }
3232
3233         else if (HoardEquipped() && gamemode == NETGAME_HOARD)
3234                  Game_mode = GM_NETWORK | GM_HOARD;
3235         else if (HoardEquipped() && gamemode == NETGAME_TEAM_HOARD)
3236                  {
3237                   Game_mode = GM_NETWORK | GM_HOARD | GM_TEAM;
3238                   Show_kill_list=3;
3239                  }
3240         else if ( gamemode == NETGAME_TEAM_ANARCHY )
3241         {
3242                 Game_mode = GM_NETWORK | GM_TEAM;
3243                 Show_kill_list = 3;
3244         }
3245         else
3246                 Int3();
3247
3248 #if 0
3249 #ifdef MACINTOSH                        // minimize players on localtalk games
3250         if ( (Network_game_type == APPLETALK_GAME) && (Network_appletalk_type == LOCALTALK_TYPE) ) {
3251                 if (Game_mode & GM_MULTI_ROBOTS)
3252                         MaxNumNetPlayers = 2;
3253                 else
3254                         MaxNumNetPlayers = 3;
3255         } else {
3256                 if (Game_mode & GM_MULTI_COOP)
3257                         MaxNumNetPlayers = 4;
3258                 else
3259                         MaxNumNetPlayers = 8;
3260         }
3261 #endif
3262 #endif
3263
3264 }
3265
3266 int
3267 network_find_game(void)
3268 {
3269         // Find out whether or not there is space left on this socket
3270
3271         fix t1;
3272
3273         Network_status = NETSTAT_BROWSING;
3274
3275         num_active_games = 0;
3276
3277         show_boxed_message(TXT_WAIT);
3278
3279         network_send_game_list_request();
3280         t1 = timer_get_approx_seconds() + F1_0*3;
3281
3282         while (timer_get_approx_seconds() < t1) // Wait 3 seconds for replies
3283                 network_listen();
3284
3285         clear_boxed_message();
3286
3287 //      mprintf((0, "%s %d %s\n", TXT_FOUND, num_active_games, TXT_ACTIVE_GAMES));
3288
3289         if (num_active_games < MAX_ACTIVE_NETGAMES)
3290                 return 0;
3291         return 1;
3292 }
3293         
3294 void network_read_sync_packet( netgame_info * sp, int rsinit)
3295 {       
3296 #ifdef MACINTOSH
3297         netgame_info tmp_info;
3298 #endif
3299
3300         int i, j;
3301         char temp_callsign[CALLSIGN_LEN+1];
3302
3303 #ifdef MACINTOSH
3304         if ( (Network_game_type == IPX_GAME) && (sp != &Netgame) ) {                            // for macintosh -- get the values unpacked to our structure format
3305                 receive_netgame_packet((ubyte *)sp, &tmp_info, 0);
3306                 sp = &tmp_info;
3307         }
3308 #endif
3309
3310    if (rsinit)
3311      TempPlayersInfo=&NetPlayers;
3312         
3313         // This function is now called by all people entering the netgame.
3314
3315         // mprintf( (0, "%s %d\n", TXT_STARTING_NETGAME, sp->levelnum ));
3316
3317         if (sp != &Netgame)
3318          {
3319           memcpy( &Netgame, sp, sizeof(netgame_info) );
3320           memcpy (&NetPlayers,TempPlayersInfo,sizeof (AllNetPlayers_info));
3321          }
3322
3323         N_players = sp->numplayers;
3324         Difficulty_level = sp->difficulty;
3325         Network_status = sp->game_status;
3326
3327    //Assert(Function_mode != FMODE_GAME);
3328
3329         // New code, 11/27
3330
3331         mprintf((1, "Netgame.checksum = %d, calculated checksum = %d.\n", Netgame.segments_checksum, my_segments_checksum));
3332
3333         if (Netgame.segments_checksum != my_segments_checksum)
3334         {
3335                 Network_status = NETSTAT_MENU;
3336                 nm_messagebox(TXT_ERROR, 1, TXT_OK, TXT_NETLEVEL_NMATCH);
3337 #ifdef RELEASE
3338                 return;
3339 #endif
3340         }
3341
3342         // Discover my player number
3343
3344         memcpy(temp_callsign, Players[Player_num].callsign, CALLSIGN_LEN+1);
3345         
3346         Player_num = -1;
3347
3348         for (i=0; i<MAX_NUM_NET_PLAYERS; i++ )  {
3349                 Players[i].net_kills_total = 0;
3350 //              Players[i].net_killed_total = 0;
3351         }
3352
3353         for (i=0; i<N_players; i++ )    {
3354                 if (Network_game_type == IPX_GAME) {
3355                         if ( (!memcmp( TempPlayersInfo->players[i].network.ipx.node, My_Seq.player.network.ipx.node, 6 )) && (!stricmp( TempPlayersInfo->players[i].callsign, temp_callsign)) ) {
3356                                 if (Player_num!=-1) {
3357                                         Int3(); // Hey, we've found ourselves twice
3358                                         mprintf ((0,"Hey, we've found ourselves twice!\n"));
3359                                         Network_status = NETSTAT_MENU;
3360                                         return; 
3361                                 }
3362                                 change_playernum_to(i);
3363                         }
3364                 } else {
3365                         if ( (TempPlayersInfo->players[i].network.appletalk.node == My_Seq.player.network.appletalk.node) && (!stricmp( TempPlayersInfo->players[i].callsign, temp_callsign)) ) {
3366                                 if (Player_num!=-1) {
3367                                         Int3(); // Hey, we've found ourselves twice
3368                                         Network_status = NETSTAT_MENU;
3369                                         return; 
3370                                 }
3371                                 change_playernum_to(i);
3372                         }
3373                 }
3374                 memcpy( Players[i].callsign, TempPlayersInfo->players[i].callsign, CALLSIGN_LEN+1 );
3375
3376                 if (Network_game_type == IPX_GAME) {
3377                         if ( (*(uint *)TempPlayersInfo->players[i].network.ipx.server) != 0 )
3378                                 ipx_get_local_target( TempPlayersInfo->players[i].network.ipx.server, TempPlayersInfo->players[i].network.ipx.node, Players[i].net_address );
3379                         else
3380                                 memcpy( Players[i].net_address, TempPlayersInfo->players[i].network.ipx.node, 6 );
3381                 }
3382                                 
3383                 Players[i].n_packets_got=0;                             // How many packets we got from them
3384                 Players[i].n_packets_sent=0;                            // How many packets we sent to them
3385                 Players[i].connected = TempPlayersInfo->players[i].connected;
3386                 Players[i].net_kills_total = sp->player_kills[i];
3387                 Players[i].net_killed_total = sp->killed[i];
3388                 if ((Network_rejoined) || (i != Player_num))
3389                         Players[i].score = sp->player_score[i];
3390                 for (j = 0; j < MAX_NUM_NET_PLAYERS; j++)
3391                 {
3392                         kill_matrix[i][j] = sp->kills[i][j];
3393                 }
3394         }
3395
3396         if ( Player_num < 0 )   {
3397                 mprintf ((0,"Bad Player_num, resetting to NETSTAT_MENU!\n"));
3398                 Network_status = NETSTAT_MENU;
3399                 return;
3400         }
3401
3402         if (Network_rejoined) 
3403                 for (i=0; i<N_players;i++)
3404                         Players[i].net_killed_total = sp->killed[i];
3405
3406         if (Network_rejoined) {
3407                 network_process_monitor_vector(sp->monitor_vector);
3408                 Players[Player_num].time_level = sp->level_time;
3409         }
3410
3411         team_kills[0] = sp->team_kills[0];
3412         team_kills[1] = sp->team_kills[1];
3413         
3414         Players[Player_num].connected = 1;
3415    NetPlayers.players[Player_num].connected = 1;
3416    NetPlayers.players[Player_num].rank=GetMyNetRanking();
3417
3418         if (!Network_rejoined)
3419                 for (i=0; i<NumNetPlayerPositions; i++) {
3420                         Objects[Players[i].objnum].pos = Player_init[Netgame.locations[i]].pos;
3421                         Objects[Players[i].objnum].orient = Player_init[Netgame.locations[i]].orient;
3422                         obj_relink(Players[i].objnum,Player_init[Netgame.locations[i]].segnum);
3423                 }
3424
3425         Objects[Players[Player_num].objnum].type = OBJ_PLAYER;
3426
3427    mprintf ((0,"Changing to NETSTAT_PLAYING!\n"));
3428         Network_status = NETSTAT_PLAYING;
3429         Function_mode = FMODE_GAME;
3430         multi_sort_kill_list();
3431
3432 }
3433
3434 void
3435 network_send_sync(void)
3436 {
3437         int i, j, np;
3438
3439         // Randomize their starting locations...
3440
3441         d_srand( timer_get_fixed_seconds() );
3442         for (i=0; i<NumNetPlayerPositions; i++ )        
3443         {
3444                 if (Players[i].connected)
3445                         Players[i].connected = 1; // Get rid of endlevel connect statuses
3446                 if (Game_mode & GM_MULTI_COOP)
3447                         Netgame.locations[i] = i;
3448                 else {
3449                         do 
3450                         {
3451                                 np = d_rand() % NumNetPlayerPositions;
3452                                 for (j=0; j<i; j++ )    
3453                                 {
3454                                         if (Netgame.locations[j]==np)   
3455                                         {
3456                                                 np =-1;
3457                                                 break;
3458                                         }
3459                                 }
3460                         } while (np<0);
3461                         // np is a location that is not used anywhere else..
3462                         Netgame.locations[i]=np;
3463 //                      mprintf((0, "Player %d starting in location %d\n" ,i ,np ));
3464                 }
3465         }
3466
3467         // Push current data into the sync packet
3468
3469         network_update_netgame();
3470         Netgame.game_status = NETSTAT_PLAYING;
3471         Netgame.type = PID_SYNC;
3472         Netgame.segments_checksum = my_segments_checksum;
3473
3474         for (i=0; i<N_players; i++ )    {
3475                 if ((!Players[i].connected) || (i == Player_num))
3476                         continue;
3477
3478                 if (Network_game_type == IPX_GAME) {
3479                 // Send several times, extras will be ignored
3480                         #ifndef MACINTOSH
3481                         ipx_send_internetwork_packet_data( (ubyte *)&Netgame, sizeof(netgame_info), NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node);
3482                         ipx_send_internetwork_packet_data( (ubyte *)&NetPlayers, sizeof(AllNetPlayers_info), NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node);
3483                         #else
3484                         send_netgame_packet(NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node, NULL, 0);
3485                         send_netplayers_packet(NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node);
3486                         #endif
3487                 #ifdef MACINTOSH
3488                 } else {
3489                                 appletalk_send_packet_data( (ubyte *)&Netgame, sizeof(netgame_info), NetPlayers.players[i].network.appletalk.node,
3490                                         NetPlayers.players[i].network.appletalk.net,
3491                                         NetPlayers.players[i].network.appletalk.socket);
3492                                 appletalk_send_packet_data( (ubyte *)&NetPlayers, sizeof(AllNetPlayers_info), NetPlayers.players[i].network.appletalk.node,
3493                                         NetPlayers.players[i].network.appletalk.net,
3494                                         NetPlayers.players[i].network.appletalk.socket);
3495                 #endif
3496                 }
3497
3498         }       
3499         network_read_sync_packet(&Netgame,1); // Read it myself, as if I had sent it
3500 }
3501
3502 int
3503 network_select_teams(void)
3504 {
3505 #ifndef SHAREWARE
3506         newmenu_item m[MAX_PLAYERS+4];
3507         int choice, opt, opt_team_b;
3508         ubyte team_vector = 0;
3509         char team_names[2][CALLSIGN_LEN+1];
3510         int i;
3511         int pnums[MAX_PLAYERS+2];
3512
3513         // One-time initialization
3514
3515         for (i = N_players/2; i < N_players; i++) // Put first half of players on team A
3516         {
3517                 team_vector |= (1 << i);
3518         }
3519
3520         sprintf(team_names[0], "%s", TXT_BLUE);
3521         sprintf(team_names[1], "%s", TXT_RED);
3522
3523         // Here comes da menu
3524 menu:
3525         m[0].type = NM_TYPE_INPUT; m[0].text = team_names[0]; m[0].text_len = CALLSIGN_LEN; 
3526
3527         opt = 1;
3528         for (i = 0; i < N_players; i++)
3529         {
3530                 if (!(team_vector & (1 << i)))
3531                 {
3532                         m[opt].type = NM_TYPE_MENU; m[opt].text = NetPlayers.players[i].callsign; pnums[opt] = i; opt++;
3533                 }
3534         }
3535         opt_team_b = opt;
3536         m[opt].type = NM_TYPE_INPUT; m[opt].text = team_names[1]; m[opt].text_len = CALLSIGN_LEN; opt++;
3537         for (i = 0; i < N_players; i++)
3538         {
3539                 if (team_vector & (1 << i))
3540                 {
3541                         m[opt].type = NM_TYPE_MENU; m[opt].text = NetPlayers.players[i].callsign; pnums[opt] = i; opt++;
3542                 }
3543         }
3544         m[opt].type = NM_TYPE_TEXT; m[opt].text = ""; opt++;
3545         m[opt].type = NM_TYPE_MENU; m[opt].text = TXT_ACCEPT; opt++;
3546
3547         Assert(opt <= MAX_PLAYERS+4);
3548         
3549         choice = newmenu_do(NULL, TXT_TEAM_SELECTION, opt, m, NULL);
3550
3551         if (choice == opt-1)
3552         {
3553                 if ((opt-2-opt_team_b < 2) || (opt_team_b == 1)) 
3554                 {
3555                         nm_messagebox(NULL, 1, TXT_OK, TXT_TEAM_MUST_ONE);
3556                         #ifdef RELEASE
3557                                 goto menu;
3558                         #endif
3559                 }
3560                 
3561                 Netgame.team_vector = team_vector;
3562                 strcpy(Netgame.team_name[0], team_names[0]);
3563                 strcpy(Netgame.team_name[1], team_names[1]);
3564                 return 1;
3565         }
3566
3567         else if ((choice > 0) && (choice < opt_team_b)) {
3568                 team_vector |= (1 << pnums[choice]);
3569         }
3570         else if ((choice > opt_team_b) && (choice < opt-2)) {
3571                 team_vector &= ~(1 << pnums[choice]);
3572         }
3573         else if (choice == -1)
3574                 return 0;
3575         goto menu;
3576 #else
3577         return 0;
3578 #endif
3579 }
3580
3581 int
3582 network_select_players(void)
3583 {
3584         int i, j;
3585    newmenu_item m[MAX_PLAYERS+4];
3586    char text[MAX_PLAYERS+4][45];
3587         char title[50];
3588         int save_nplayers;              //how may people would like to join
3589
3590         network_add_player( &My_Seq );
3591                 
3592         for (i=0; i< MAX_PLAYERS+4; i++ ) {
3593                 sprintf( text[i], "%d.  %-20s", i+1, "" );
3594                 m[i].type = NM_TYPE_CHECK; m[i].text = text[i]; m[i].value = 0;
3595         }
3596
3597         m[0].value = 1;                         // Assume server will play...
3598
3599    if (FindArg("-norankings"))
3600                 sprintf( text[0], "%d. %-20s", 1, Players[Player_num].callsign );
3601         else
3602                 sprintf( text[0], "%d. %s%-20s", 1, RankStrings[NetPlayers.players[Player_num].rank],Players[Player_num].callsign );
3603
3604         sprintf( title, "%s %d %s", TXT_TEAM_SELECT, MaxNumNetPlayers, TXT_TEAM_PRESS_ENTER );
3605
3606 GetPlayersAgain:
3607    ExtGameStatus=GAMESTAT_NETGAME_PLAYER_SELECT;
3608         j=newmenu_do1( NULL, title, MAX_PLAYERS+4, m, network_start_poll, 1 );
3609
3610         save_nplayers = N_players;
3611
3612         if (j<0) 
3613         {
3614                 // Aborted!                                      
3615                 // Dump all players and go back to menu mode
3616
3617 abort:
3618                 for (i=1; i<save_nplayers; i++) {
3619                         if (Network_game_type == IPX_GAME)
3620                                 network_dump_player(NetPlayers.players[i].network.ipx.server,NetPlayers.players[i].network.ipx.node, DUMP_ABORTED);
3621                         #ifdef MACINTOSH
3622                         else
3623                                 network_dump_appletalk_player(NetPlayers.players[i].network.appletalk.node,NetPlayers.players[i].network.appletalk.net, NetPlayers.players[i].network.appletalk.socket, DUMP_ABORTED);
3624                         #endif
3625                 }
3626                         
3627
3628                 Netgame.numplayers = 0;
3629                 network_send_game_info(0); // Tell everyone we're bailing
3630
3631                 Network_status = NETSTAT_MENU;
3632                 return(0);
3633         }
3634        
3635         // Count number of players chosen
3636
3637         N_players = 0;
3638         for (i=0; i<save_nplayers; i++ )
3639         {
3640                 if (m[i].value) 
3641                         N_players++;
3642         }
3643         
3644         if ( N_players > Netgame.max_numplayers) {
3645                 #ifndef MACINTOSH
3646                 nm_messagebox( TXT_ERROR, 1, TXT_OK, "%s %d %s", TXT_SORRY_ONLY, MaxNumNetPlayers, TXT_NETPLAYERS_IN );
3647                 #else
3648                 nm_messagebox( TXT_ERROR, 1, TXT_OK, "%s %d netplayers for this game.", TXT_SORRY_ONLY, MaxNumNetPlayers );
3649                 #endif
3650                 N_players = save_nplayers;
3651                 goto GetPlayersAgain;
3652         }
3653
3654 #ifdef RELEASE
3655         if ( N_players < 2 )    {
3656                 nm_messagebox( TXT_ERROR, 1, TXT_OK, TXT_TEAM_ATLEAST_TWO );
3657                 N_players = save_nplayers;
3658                 goto GetPlayersAgain;
3659         }
3660 #endif
3661
3662 #ifdef RELEASE
3663         if ( (Netgame.gamemode == NETGAME_TEAM_ANARCHY ||
3664                    Netgame.gamemode == NETGAME_CAPTURE_FLAG || Netgame.gamemode == NETGAME_TEAM_HOARD) && (N_players < 2) ) {
3665                 nm_messagebox(TXT_ERROR, 1, TXT_OK, "You must select at least two\nplayers to start a team game" );
3666                 N_players = save_nplayers;
3667                 goto GetPlayersAgain;
3668         }
3669 #endif
3670
3671         // Remove players that aren't marked.
3672         N_players = 0;
3673         for (i=0; i<save_nplayers; i++ )        {
3674                 if (m[i].value) 
3675                 {
3676                         if (i > N_players)
3677                         {
3678                                 if (Network_game_type == IPX_GAME) {
3679                                         memcpy(NetPlayers.players[N_players].network.ipx.node, NetPlayers.players[i].network.ipx.node, 6);
3680                                         memcpy(NetPlayers.players[N_players].network.ipx.server, NetPlayers.players[i].network.ipx.server, 4);
3681                                 } else {
3682                                         NetPlayers.players[N_players].network.appletalk.node = NetPlayers.players[i].network.appletalk.node;
3683                                         NetPlayers.players[N_players].network.appletalk.net = NetPlayers.players[i].network.appletalk.net;
3684                                         NetPlayers.players[N_players].network.appletalk.socket = NetPlayers.players[i].network.appletalk.socket;
3685                                 }
3686                                 memcpy(NetPlayers.players[N_players].callsign, NetPlayers.players[i].callsign, CALLSIGN_LEN+1);
3687                                 NetPlayers.players[N_players].version_major=NetPlayers.players[i].version_major;
3688                                 NetPlayers.players[N_players].version_minor=NetPlayers.players[i].version_minor;
3689                                 NetPlayers.players[N_players].rank=NetPlayers.players[i].rank;
3690                                 ClipRank (&NetPlayers.players[N_players].rank);
3691                                 network_check_for_old_version(i);
3692                         }
3693                         Players[N_players].connected = 1;
3694                         N_players++;
3695                 }
3696                 else
3697                 {
3698                         if (Network_game_type == IPX_GAME)
3699                                 network_dump_player(NetPlayers.players[i].network.ipx.server,NetPlayers.players[i].network.ipx.node, DUMP_DORK);
3700                         #ifdef MACINTOSH
3701                         else
3702                                 network_dump_appletalk_player(NetPlayers.players[i].network.appletalk.node,NetPlayers.players[i].network.appletalk.net, NetPlayers.players[i].network.appletalk.socket, DUMP_DORK);
3703                         #endif
3704                 }
3705         }
3706
3707         for (i = N_players; i < MAX_NUM_NET_PLAYERS; i++) {
3708                 if (Network_game_type == IPX_GAME) {
3709                 memset(NetPlayers.players[i].network.ipx.node, 0, 6);
3710                 memset(NetPlayers.players[i].network.ipx.server, 0, 4);
3711             } else {
3712                 NetPlayers.players[i].network.appletalk.node = 0;
3713                 NetPlayers.players[i].network.appletalk.net = 0;
3714                 NetPlayers.players[i].network.appletalk.socket = 0;
3715             }
3716         memset(NetPlayers.players[i].callsign, 0, CALLSIGN_LEN+1);
3717                 NetPlayers.players[i].version_major=0;
3718                 NetPlayers.players[i].version_minor=0;
3719                 NetPlayers.players[i].rank=0;
3720         }
3721
3722    mprintf ((0,"Select teams: Game mode is %d\n",Netgame.gamemode));
3723
3724         if (Netgame.gamemode == NETGAME_TEAM_ANARCHY ||
3725             Netgame.gamemode == NETGAME_CAPTURE_FLAG ||
3726                  Netgame.gamemode == NETGAME_TEAM_HOARD)
3727                  if (!network_select_teams())
3728                         goto abort;
3729
3730         return(1); 
3731 }
3732
3733 void 
3734 network_start_game()
3735 {
3736         int i;
3737         char game_name[NETGAME_NAME_LEN+1];
3738         int chosen_game_mode, game_flags, level;
3739
3740         if (Network_game_type == IPX_GAME) {
3741
3742                 Assert( FRAME_INFO_SIZE < IPX_MAX_DATA_SIZE );
3743                 mprintf((0, "Using frame_info len %d, max %d.\n", FRAME_INFO_SIZE, IPX_MAX_DATA_SIZE));
3744                 
3745                 if ( !Network_active )
3746                 {
3747                         nm_messagebox(NULL, 1, TXT_OK, TXT_IPX_NOT_FOUND );
3748                         return;
3749                 }
3750         #ifdef MACINTOSH
3751         } else {
3752                 int err;
3753                 char buf[256];
3754
3755                 Assert( FRAME_INFO_SIZE < APPLETALK_MAX_DATA_SIZE );            
3756                 mprintf((0, "Using frame_info len %d, max %d.\n", sizeof(frame_info), APPLETALK_MAX_DATA_SIZE));
3757                 if (Appletalk_active <= 0) {
3758                         switch (Appletalk_active) {
3759                         case APPLETALK_NOT_OPEN:
3760                                 sprintf(buf, "Appletalk is not currently active.\nPlease enable AppleTalk from the\nChooser and restart Descent.");
3761                                 break;
3762                         case APPLETALK_BAD_LISTENER:
3763                                 sprintf(buf, "The Resource Fork of Descent appears damaged.\nPlease re-install Descent or contact\nMacPlay technical support.");
3764                                 break;
3765                         case APPLETALK_NO_LOCAL_ADDR:
3766                                 sprintf(buf, "Wow! Strange!\n\nNo Local Address.");
3767                                 break;
3768                         case APPLETALK_NO_SOCKET:
3769                                 sprintf(buf, "All AppleTalk sockets are in use.\nTry shutting down other network\napplications and restarting Descent.\n");
3770                                 break;
3771                         }
3772                         nm_messagebox(NULL, 1, TXT_OK, buf);
3773                         return;
3774                 }
3775                 strcpy(Network_zone_name, DEFAULT_ZONE_NAME);
3776         #endif
3777         }
3778
3779         network_init();
3780         change_playernum_to(0);
3781
3782         if (network_find_game())
3783         {
3784                 nm_messagebox(NULL, 1, TXT_OK, TXT_NET_FULL);
3785                 return;
3786         }
3787
3788         game_flags = 0;
3789         i = network_get_game_params( game_name, &chosen_game_mode, &game_flags, &level );
3790
3791         if (i<0) return;
3792
3793         N_players = 0;
3794
3795 // LoadLevel(level); Old, no longer used.
3796
3797         Netgame.difficulty = Difficulty_level;
3798         Netgame.gamemode = chosen_game_mode;
3799         Netgame.game_status = NETSTAT_STARTING;
3800         Netgame.numplayers = 0;
3801         Netgame.max_numplayers = MaxNumNetPlayers;
3802         Netgame.levelnum = level;
3803         Netgame.protocol_version = MULTI_PROTO_VERSION;
3804
3805         strcpy(Netgame.game_name, game_name);
3806         
3807         Network_status = NETSTAT_STARTING;
3808
3809         #ifdef MACINTOSH
3810         if (Network_game_type == APPLETALK_GAME) {
3811                 OSErr err;
3812                 fix t1;
3813                 int count = 0;
3814                 
3815                 show_boxed_message("Registering Netgame");
3816                 do {
3817                         err = appletalk_register_netgame( game_name, TickCount() );
3818                         t1 = timer_get_fixed_seconds() + F1_0;
3819                         while (timer_get_fixed_seconds() < t1) ;
3820                         count++;
3821                 } while ( (err == nbpDuplicate) && (count != MAX_REGISTER_TRIES) );
3822                 clear_boxed_message();
3823                 if ( (err == tooManyReqs) || (count == MAX_REGISTER_TRIES) ) {
3824                         nm_messagebox(NULL, 1, TXT_OK, "AppleTalk Network is too busy.\nPlease try again shortly.");
3825                         Game_mode = GM_GAME_OVER;
3826                         return;
3827                 }
3828         }
3829         #endif
3830
3831         network_set_game_mode(Netgame.gamemode);
3832
3833    d_srand( timer_get_fixed_seconds() );
3834    Netgame.Security=d_rand();  // For syncing Netgames with player packets
3835
3836         if(network_select_players())
3837         {
3838                 StartNewLevel(Netgame.levelnum, 0);
3839         }
3840         else
3841                 Game_mode = GM_GAME_OVER;
3842         
3843 }
3844
3845 void restart_net_searching(newmenu_item * m)
3846 {
3847         int i;
3848         N_players = 0;
3849         num_active_games = 0;
3850
3851         memset(Active_games, 0, sizeof(netgame_info)*MAX_ACTIVE_NETGAMES);
3852
3853         for (i = 0; i < MAX_ACTIVE_NETGAMES; i++)
3854         {
3855                 sprintf(m[i+2].text, "%d.                                                     ",i+1);
3856                 m[i+2].redraw = 1;
3857         }
3858   
3859    NamesInfoSecurity=-1;
3860         Network_games_changed = 1;      
3861 }
3862
3863 char *ModeLetters[]={"ANRCHY","TEAM","ROBO","COOP","FLAG","HOARD","TMHOARD"};
3864
3865 int NumActiveNetgames=0;
3866
3867 void network_join_poll( int nitems, newmenu_item * menus, int * key, int citem )
3868 {
3869         // Polling loop for Join Game menu
3870         static fix t1 = 0;
3871         int i, osocket,join_status,temp;
3872
3873         menus = menus;
3874         citem = citem;
3875         nitems = nitems;
3876         key = key;
3877
3878         if ( (Network_game_type == IPX_GAME) && Network_allow_socket_changes )      {
3879                 osocket = Network_socket;
3880         
3881                 if ( *key==KEY_PAGEDOWN )       { Network_socket--; *key = 0; }
3882                 if ( *key==KEY_PAGEUP )         { Network_socket++; *key = 0; }
3883         
3884                 if (Network_socket>99)
3885                  Network_socket=99;
3886            if (Network_socket<-99)
3887                  Network_socket=-99;    
3888         
3889                 if ( Network_socket+IPX_DEFAULT_SOCKET > 0x8000 )
3890                         Network_socket  = 0x8000 - IPX_DEFAULT_SOCKET;
3891         
3892                 if ( Network_socket+IPX_DEFAULT_SOCKET < 0 )
3893                         Network_socket  = IPX_DEFAULT_SOCKET;
3894         
3895                 if (Network_socket != osocket )         {
3896                         sprintf( menus[0].text, "\t%s %+d (PgUp/PgDn to change)", TXT_CURRENT_IPX_SOCKET, Network_socket );
3897                         menus[0].redraw = 1;
3898                         mprintf(( 0, "Changing to socket %d\n", Network_socket ));
3899                         network_listen();
3900                         mprintf ((0,"netgood 1!\n"));
3901                         ipx_change_default_socket( IPX_DEFAULT_SOCKET + Network_socket );
3902                         mprintf ((0,"netgood 2!\n"));
3903                         restart_net_searching(menus);
3904                         mprintf ((0,"netgood 3!\n"));
3905                         network_send_game_list_request();
3906                         mprintf ((0,"netgood 4!\n"));
3907                         return;
3908                 }
3909         }
3910
3911    // send a request for game info every 3 seconds
3912   
3913         if (Network_game_type == IPX_GAME) {  
3914                 if (timer_get_approx_seconds() > t1+F1_0*3) {
3915                         t1 = timer_get_approx_seconds();
3916                         network_send_game_list_request();
3917                 }
3918         #ifdef MACINTOSH
3919         } else if (timer_get_approx_seconds() > t1+F1_0*20) {
3920                 hide_cursor();
3921                 t1 = timer_get_approx_seconds();
3922                 restart_net_searching(menus);
3923                 show_boxed_message("Requesting list of Netgames");
3924                 network_send_game_list_request();
3925                 clear_boxed_message();
3926                 show_cursor();
3927         #endif
3928         }
3929    
3930    temp=num_active_games;
3931         
3932         network_listen();
3933
3934    NumActiveNetgames=num_active_games;
3935
3936    if (!Network_games_changed)
3937      return;
3938
3939    if (temp!=num_active_games)
3940            digi_play_sample (SOUND_HUD_MESSAGE,F1_0);
3941  
3942         Network_games_changed = 0;
3943    mprintf ((0,"JOIN POLL: I'm looking at %d games!\n",num_active_games));
3944
3945         // Copy the active games data into the menu options
3946         for (i = 0; i < num_active_games; i++)
3947         {
3948                 int game_status = Active_games[i].game_status;
3949       int j,x, k,tx,ty,ta,nplayers = 0;
3950       char levelname[8],MissName[25],GameName[25],thold[2];
3951       thold[1]=0;
3952
3953       // These next two loops protect against menu skewing
3954       // if missiontitle or gamename contain a tab
3955                  
3956       for (x=0,tx=0,k=0,j=0;j<15;j++)
3957         {
3958           if (Active_games[i].mission_title[j]=='\t')
3959             continue;
3960           thold[0]=Active_games[i].mission_title[j];
3961           gr_get_string_size (thold,&tx,&ty,&ta);
3962  
3963           if ((x+=tx)>=LHX(55))
3964             {
3965               MissName[k]=MissName[k+1]=MissName[k+2]='.';
3966               k+=3;
3967               break;
3968             }
3969           
3970           MissName[k++]=Active_games[i].mission_title[j];
3971         }
3972       MissName[k]=0;
3973
3974       for (x=0,tx=0,k=0,j=0;j<15;j++)
3975         {
3976           if (Active_games[i].game_name[j]=='\t')
3977             continue;
3978           thold[0]=Active_games[i].game_name[j];
3979           gr_get_string_size (thold,&tx,&ty,&ta);
3980
3981           if ((x+=tx)>=LHX(55))
3982             {
3983               GameName[k]=GameName[k+1]=GameName[k+2]='.';
3984               k+=3;
3985               break;
3986             }
3987           GameName[k++]=Active_games[i].game_name[j];
3988         }
3989       GameName[k]=0;
3990
3991            
3992       nplayers=Active_games[i].numconnected;
3993
3994                 if (Active_games[i].levelnum < 0)
3995                         sprintf(levelname, "S%d", -Active_games[i].levelnum);
3996                 else 
3997                         sprintf(levelname, "%d", Active_games[i].levelnum);
3998           
3999                 if (game_status == NETSTAT_STARTING) 
4000                 {
4001         sprintf (menus[i+2].text,"%d.\t%s \t%s \t  %d/%d \t%s \t %s \t%s",
4002                  i+1,GameName,ModeLetters[Active_games[i].gamemode],nplayers,
4003                  Active_games[i].max_numplayers,MissName,levelname,"Forming");
4004                 }
4005                 else if (game_status == NETSTAT_PLAYING)
4006                 {
4007                  join_status=can_join_netgame(&Active_games[i],NULL);   
4008 //               mprintf ((0,"Joinstatus=%d\n",join_status));
4009                 
4010         if (join_status==1)
4011             sprintf (menus[i+2].text,"%d.\t%s \t%s \t  %d/%d \t%s \t %s \t%s",
4012                      i+1,GameName,ModeLetters[Active_games[i].gamemode],nplayers,
4013                      Active_games[i].max_numplayers,MissName,levelname,"Open");
4014                         else if (join_status==2)
4015             sprintf (menus[i+2].text,"%d.\t%s \t%s \t  %d/%d \t%s \t %s \t%s",
4016                      i+1,GameName,ModeLetters[Active_games[i].gamemode],nplayers,
4017                      Active_games[i].max_numplayers,MissName,levelname,"Full");
4018                         else if (join_status==3)
4019             sprintf (menus[i+2].text,"%d.\t%s \t%s \t  %d/%d \t%s \t %s \t%s",
4020                      i+1,GameName,ModeLetters[Active_games[i].gamemode],nplayers,
4021                      Active_games[i].max_numplayers,MissName,levelname,"Restrict");
4022                         else
4023             sprintf (menus[i+2].text,"%d.\t%s \t%s \t  %d/%d \t%s \t %s \t%s",
4024                      i+1,GameName,ModeLetters[Active_games[i].gamemode],nplayers,
4025                      Active_games[i].max_numplayers,MissName,levelname,"Closed");
4026
4027                 }
4028                 else
4029          sprintf (menus[i+2].text,"%d.\t%s \t%s \t  %d/%d \t%s \t %s \t%s",
4030                   i+1,GameName,ModeLetters[Active_games[i].gamemode],nplayers,
4031                   Active_games[i].max_numplayers,MissName,levelname,"Between");
4032                  
4033
4034       Assert(strlen(menus[i+2].text) < 100);
4035       menus[i+2].redraw = 1;
4036         }
4037
4038         for (i = num_active_games; i < MAX_ACTIVE_NETGAMES; i++)
4039         {
4040                 sprintf(menus[i+2].text, "%d.                                                     ",i+1);
4041                 menus[i+2].redraw = 1;
4042         }
4043 }
4044
4045 int
4046 network_wait_for_sync(void)
4047 {
4048         char text[60];
4049         newmenu_item m[2];
4050         int i, choice;
4051         
4052         Network_status = NETSTAT_WAITING;
4053
4054         m[0].type=NM_TYPE_TEXT; m[0].text = text;
4055         m[1].type=NM_TYPE_TEXT; m[1].text = TXT_NET_LEAVE;
4056         
4057         i = network_send_request();
4058
4059         if (i < 0)
4060                 return(-1);
4061
4062         sprintf( m[0].text, "%s\n'%s' %s", TXT_NET_WAITING, NetPlayers.players[i].callsign, TXT_NET_TO_ENTER );
4063
4064 menu:   
4065         choice=newmenu_do( NULL, TXT_WAIT, 2, m, network_sync_poll );
4066
4067         if (choice > -1)
4068                 goto menu;
4069
4070         if (Network_status != NETSTAT_PLAYING)  
4071         {
4072                 sequence_packet me;
4073
4074 //              if (Network_status == NETSTAT_ENDLEVEL)
4075 //              {
4076 //                      network_send_endlevel_packet(0);
4077 //                      longjmp(LeaveGame, 0);
4078 //              }               
4079
4080                 mprintf((0, "Aborting join.\n"));
4081                 me.type = PID_QUIT_JOINING;
4082                 memcpy( me.player.callsign, Players[Player_num].callsign, CALLSIGN_LEN+1 );
4083                 if (Network_game_type == IPX_GAME) {
4084                         memcpy( me.player.network.ipx.node, ipx_get_my_local_address(), 6 );
4085                         memcpy( me.player.network.ipx.server, ipx_get_my_server_address(), 4 );
4086                         #ifndef MACINTOSH
4087                         ipx_send_internetwork_packet_data( (ubyte *)&me, sizeof(sequence_packet), NetPlayers.players[0].network.ipx.server, NetPlayers.players[0].network.ipx.node );
4088                         #else
4089                         send_sequence_packet(me, NetPlayers.players[0].network.ipx.server, NetPlayers.players[0].network.ipx.node, NULL);
4090                         #endif
4091                 #ifdef MACINTOSH
4092                 } else {
4093                         me.player.network.appletalk.node = appletalk_get_my_node();
4094                         me.player.network.appletalk.net = appletalk_get_my_net();
4095                         me.player.network.appletalk.socket = appletalk_get_my_socket();
4096                 #endif
4097                 }
4098                 N_players = 0;
4099                 Function_mode = FMODE_MENU;
4100                 Game_mode = GM_GAME_OVER;
4101                 return(-1);     // they cancelled               
4102         }
4103         return(0);
4104 }
4105
4106 void 
4107 network_request_poll( int nitems, newmenu_item * menus, int * key, int citem )
4108 {
4109         // Polling loop for waiting-for-requests menu
4110
4111         int i = 0;
4112         int num_ready = 0;
4113
4114         menus = menus;
4115         citem = citem;
4116         nitems = nitems;
4117         key = key;
4118
4119         // Send our endlevel packet at regular intervals
4120
4121 //      if (timer_get_approx_seconds() > t1+ENDLEVEL_SEND_INTERVAL)
4122 //      {
4123 //              network_send_endlevel_packet();
4124 //              t1 = timer_get_approx_seconds();
4125 //      }
4126
4127         network_listen();
4128
4129         for (i = 0; i < N_players; i++)
4130         {
4131                 if ((Players[i].connected == 1) || (Players[i].connected == 0))
4132                         num_ready++;
4133         }
4134
4135         if (num_ready == N_players) // All players have checked in or are disconnected
4136         {
4137                 *key = -2;
4138         }
4139 }
4140
4141 void
4142 network_wait_for_requests(void)
4143 {
4144         // Wait for other players to load the level before we send the sync
4145         int choice, i;
4146         newmenu_item m[1];
4147         
4148         Network_status = NETSTAT_WAITING;
4149
4150         m[0].type=NM_TYPE_TEXT; m[0].text = TXT_NET_LEAVE;
4151
4152         mprintf((0, "Entered wait_for_requests : N_players = %d.\n", N_players));
4153
4154         for (choice = 0; choice < N_players; choice++)
4155                 mprintf((0, "Players[%d].connected = %d.\n", choice, Players[choice].connected));
4156
4157         Network_status = NETSTAT_WAITING;
4158         network_flush();
4159
4160         Players[Player_num].connected = 1;
4161
4162 menu:
4163         choice = newmenu_do(NULL, TXT_WAIT, 1, m, network_request_poll);        
4164
4165         if (choice == -1)
4166         {
4167                 // User aborted
4168                 choice = nm_messagebox(NULL, 3, TXT_YES, TXT_NO, TXT_START_NOWAIT, TXT_QUITTING_NOW);
4169                 if (choice == 2)
4170                         return;
4171                 if (choice != 0)
4172                         goto menu;
4173                 
4174                 // User confirmed abort
4175                 
4176                 for (i=0; i < N_players; i++) {
4177                         if ((Players[i].connected != 0) && (i != Player_num)) {
4178                                 if (Network_game_type == IPX_GAME)
4179                                         network_dump_player(NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node, DUMP_ABORTED);
4180                                 #ifdef MACINTOSH
4181                                 else
4182                                         network_dump_appletalk_player(NetPlayers.players[i].network.appletalk.node, NetPlayers.players[i].network.appletalk.net, NetPlayers.players[i].network.appletalk.socket, DUMP_ABORTED);
4183                                 #endif
4184                         }
4185                 }
4186
4187                 #ifdef MACINTOSH
4188                 if (Network_game_type == APPLETALK_GAME)
4189                         network_release_registered_game();
4190                 #endif
4191                 longjmp(LeaveGame, 0);  
4192         }
4193         else if (choice != -2)
4194                 goto menu;
4195 }
4196
4197 int
4198 network_level_sync(void)
4199 {
4200         // Do required syncing between (before) levels
4201
4202         int result;
4203
4204         mprintf((0, "Player %d entering network_level_sync.\n", Player_num));
4205         
4206         MySyncPackInitialized = 0;
4207
4208 //      my_segments_checksum = netmisc_calc_checksum(Segments, sizeof(segment)*(Highest_segment_index+1));
4209
4210         network_flush(); // Flush any old packets
4211
4212         if (N_players == 0)
4213                 result = network_wait_for_sync();
4214         else if (network_i_am_master())
4215         {
4216                 network_wait_for_requests();
4217                 network_send_sync();
4218                 result = 0;
4219         }
4220         else
4221                 result = network_wait_for_sync();
4222
4223    network_count_powerups_in_mine();
4224
4225         if (result)
4226         {
4227                 Players[Player_num].connected = 0;
4228                 network_send_endlevel_packet();
4229                 #ifdef MACINTOSH
4230                 if (Network_game_type == APPLETALK_GAME)
4231                         network_release_registered_game();
4232                 #endif
4233                 longjmp(LeaveGame, 0);
4234         }
4235         return(0);
4236 }
4237
4238 void network_count_powerups_in_mine(void)
4239  {
4240   int i;
4241
4242   for (i=0;i<MAX_POWERUP_TYPES;i++)
4243         PowerupsInMine[i]=0;
4244         
4245   for (i=0;i<=Highest_object_index;i++) 
4246         {
4247          if (Objects[i].type==OBJ_POWERUP)
4248           {
4249                 PowerupsInMine[Objects[i].id]++;
4250                 if (multi_powerup_is_4pack(Objects[i].id))
4251                    PowerupsInMine[Objects[i].id-1]+=4;
4252           }
4253         }
4254                   
4255  }
4256
4257 #ifdef MACINTOSH
4258
4259 // code to release the NBP binding of an appletalk game
4260
4261 void network_release_registered_game()
4262 {
4263         if (Network_game_type == APPLETALK_GAME)
4264                 appletalk_remove_netgame();
4265 }
4266
4267 // code to sort zone lists....
4268
4269 int zone_sort_func(const char **e0, const char **e1)
4270 {
4271         return strcmp(*e0, *e1);
4272 }
4273
4274 void network_get_appletalk_zone()
4275 {
4276         int num_zones, i, item, default_item;
4277         char **zone_list;
4278         char default_zone[MAX_ZONE_LENGTH];                     // my zone
4279
4280         Network_zone_name[0] = '\0';
4281         
4282         show_boxed_message("Looking for AppleTalk Zones");
4283         num_zones = appletalk_get_zone_names(&zone_list);
4284         clear_boxed_message();
4285
4286         if (num_zones < 0)      {               // error in getting zone list...maybe no router available....
4287                 if ( (num_zones == tooManyReqs) || (num_zones == noDataArea) ){
4288                         nm_messagebox(NULL, 1, TXT_OK, "AppleTalk Network is too busy.\nPlease try again shortly.");
4289                         longjmp(LeaveGame,0);
4290                 }
4291                 num_zones = 0;
4292         }
4293         
4294         if (num_zones == 0) {
4295                 strcpy(Network_zone_name, DEFAULT_ZONE_NAME);
4296                 return;
4297         }
4298         
4299         if (num_zones == 1) {
4300                 Network_zone_name[0] = (char)(strlen(zone_list[0]));
4301                 memcpy( &(Network_zone_name[1]), zone_list[0], strlen(zone_list[0]) );
4302                 goto zone_done;
4303         }
4304         
4305 // sort the zone names
4306
4307         for (i = 0; i < num_zones; i++)
4308                 strlwr(zone_list[i]);
4309
4310         qsort(zone_list, num_zones, sizeof(char *), zone_sort_func);
4311
4312 // get my current zone so we can highlight that one first
4313
4314         if (appletalk_get_my_zone(default_zone))
4315                 default_item = 0;
4316         else {
4317                 for (i = 0; i < num_zones; i++) {
4318                         if ( !stricmp(zone_list[i], default_zone) ) {
4319                                 default_item = i;
4320                                 break;
4321                         }
4322                 }
4323         }
4324
4325 rezone:         
4326         item = newmenu_listbox1("AppleTalk Zones", num_zones, zone_list, 0, default_item, NULL);
4327         
4328         if (item == -1)
4329                 goto rezone;
4330                 
4331         Network_zone_name[0] = (char)(strlen(zone_list[item]));
4332         memcpy( &(Network_zone_name[1]), zone_list[item], strlen(zone_list[item]) );
4333         
4334 zone_done:
4335         for (i = 0; i < num_zones; i++)
4336                 d_free(zone_list[i]);
4337         d_free(zone_list);
4338 }
4339 #endif
4340
4341 void nm_draw_background1(char * filename);
4342
4343 //moved 2000/02/07 Matt Mueller - clipped stuff from network_join_game into new network_do_join_game to allow easy joining from other funcs too.
4344 int network_do_join_game(netgame_info *jgame, AllNetPlayers_info *jplayers){
4345         if (jgame->game_status == NETSTAT_ENDLEVEL)
4346         {
4347                 nm_messagebox(TXT_SORRY, 1, TXT_OK, TXT_NET_GAME_BETWEEN2);
4348                 return 0;
4349         }
4350
4351         if ((jgame->protocol_version != MULTI_PROTO_VERSION) &&
4352             (jgame->protocol_version != MULTI_PROTO_D2X_VER))
4353         {
4354                 nm_messagebox(TXT_SORRY, 1, TXT_OK, TXT_VERSION_MISMATCH);
4355                 return 0;
4356         }
4357 #ifndef SHAREWARE
4358         if (jgame->protocol_version == MULTI_PROTO_D2X_VER &&
4359             jgame->required_subprotocol > MULTI_PROTO_D2X_MINOR)
4360         {
4361                 nm_messagebox(TXT_SORRY, 1, TXT_OK, "This game uses features\nnot present in this version.");
4362                 return 0;
4363         }
4364         {       
4365                 // Check for valid mission name
4366                         mprintf((0, "Loading mission:%s.\n", jgame->mission_name));
4367                         if (!load_mission_by_name(jgame->mission_name))
4368                         {
4369                                 nm_messagebox(NULL, 1, TXT_OK, TXT_MISSION_NOT_FOUND);
4370
4371                                 //add getlevel functionality here - Victor Rachels
4372
4373                                 return 0;
4374                         }
4375         }
4376 #endif
4377
4378         if (!can_join_netgame(jgame, jplayers))
4379         {
4380                 if (jgame->numplayers == jgame->max_numplayers)
4381                         nm_messagebox(TXT_SORRY, 1, TXT_OK, TXT_GAME_FULL);
4382                 else
4383                         nm_messagebox(TXT_SORRY, 1, TXT_OK, TXT_IN_PROGRESS);
4384                 return 0;
4385         }
4386
4387         // Choice is valid, prepare to join in
4388
4389         memcpy(&Netgame, jgame, sizeof(netgame_info));
4390
4391         Difficulty_level = Netgame.difficulty;
4392         MaxNumNetPlayers = Netgame.max_numplayers;
4393         change_playernum_to(1);
4394
4395         network_set_game_mode(Netgame.gamemode);
4396
4397         StartNewLevel(Netgame.levelnum, 0);
4398
4399         return 1;     // look ma, we're in a game!!!
4400 }
4401
4402 void network_join_game()
4403 {
4404         int choice, i;
4405         char menu_text[MAX_ACTIVE_NETGAMES+2][200];
4406         
4407         newmenu_item m[MAX_ACTIVE_NETGAMES+2];
4408
4409         if (Network_game_type == IPX_GAME) {
4410                 if ( !Network_active )
4411                 {
4412                         nm_messagebox(NULL, 1, TXT_OK, TXT_IPX_NOT_FOUND);
4413                         return;
4414                 }
4415         #ifdef MACINTOSH
4416         } else if (Appletalk_active <= 0) {
4417                 char buf[256];
4418                 
4419                 switch (Appletalk_active) {
4420                         case APPLETALK_NOT_OPEN:
4421                                 sprintf(buf, "Appletalk is not currently active.\nPlease enable AppleTalk from the\nChooser and restart Descent.");
4422                                 break;
4423                         case APPLETALK_BAD_LISTENER:
4424                                 sprintf(buf, "The Resource Fork of Descent appears damaged.\nPlease re-install Descent or contact\nMacPlay technical support.");
4425                                 break;
4426                         case APPLETALK_NO_LOCAL_ADDR:
4427                                 sprintf(buf, "Wow! Strange!\n\nNo Local Address.");
4428                                 break;
4429                         case APPLETALK_NO_SOCKET:
4430                                 sprintf(buf, "All AppleTalk sockets are in use.\nTry shutting down other network\napplications and restarting Descent.\n");
4431                                 break;
4432                 }
4433                 nm_messagebox(NULL, 1, TXT_OK, buf);
4434                 return;
4435         #endif
4436         }
4437
4438         network_init();
4439
4440         N_players = 0;
4441
4442         setjmp(LeaveGame);
4443         
4444         #ifdef MACINTOSH
4445         if (Network_game_type == APPLETALK_GAME)
4446                 network_get_appletalk_zone();
4447         #endif
4448         
4449         Network_send_objects = 0; 
4450         Network_sending_extras=0;
4451         Network_rejoined=0;
4452           
4453         Network_status = NETSTAT_BROWSING; // We are looking at a game menu
4454         
4455    network_flush();
4456         network_listen();  // Throw out old info
4457
4458         #ifdef MACINTOSH
4459         if (Network_game_type == IPX_GAME)
4460         #endif          // note link to if
4461                 network_send_game_list_request(); // broadcast a request for lists
4462
4463         num_active_games = 0;
4464
4465    memset(m, 0, sizeof(newmenu_item)*MAX_ACTIVE_NETGAMES);
4466    memset(Active_games, 0, sizeof(netgame_info)*MAX_ACTIVE_NETGAMES);
4467    memset(ActiveNetPlayers,0,sizeof(AllNetPlayers_info)*MAX_ACTIVE_NETGAMES);
4468         
4469         gr_set_fontcolor(BM_XRGB(15,15,23),-1);
4470
4471         m[0].text = menu_text[0];
4472         m[0].type = NM_TYPE_TEXT;
4473         if (Network_game_type == IPX_GAME) {
4474                 if (Network_allow_socket_changes)
4475                         sprintf( m[0].text, "\tCurrent IPX Socket is default %+d (PgUp/PgDn to change)", Network_socket );
4476                 else
4477                         strcpy( m[0].text, "" );
4478         #ifdef MACINTOSH
4479         } else {
4480                 p2cstr(Network_zone_name);
4481                 if (strcmp(Network_zone_name, "*"))             // only print if there is a zone name
4482                         sprintf(m[0].text, "\tCurrent Zone is %s", Network_zone_name);          // is Network_zone_name a pascal string????
4483                 c2pstr(Network_zone_name);
4484         #endif
4485         }
4486
4487         m[1].text=menu_text[1];
4488         m[1].type=NM_TYPE_TEXT;
4489         sprintf (m[1].text,"\tGAME \tMODE \t#PLYRS \tMISSION \tLEV \tSTATUS");
4490
4491         for (i = 0; i < MAX_ACTIVE_NETGAMES; i++) {
4492                 m[i+2].text = menu_text[i+2];
4493                 m[i+2].type = NM_TYPE_MENU;
4494                 sprintf(m[i+2].text, "%d.                                                               ", i+1);
4495                 m[i+2].redraw = 1;
4496         }
4497
4498         Network_games_changed = 1;      
4499 remenu:
4500         SurfingNet=1;
4501         nm_draw_background1(Menu_pcx_name);             //load this here so if we abort after loading level, we restore the palette
4502         gr_palette_load(gr_palette);
4503    ExtGameStatus=GAMESTAT_JOIN_NETGAME;
4504         choice=newmenu_dotiny("NETGAMES", NULL,MAX_ACTIVE_NETGAMES+2, m, network_join_poll);
4505         SurfingNet=0;
4506
4507         if (choice==-1) {
4508                 Network_status = NETSTAT_MENU;
4509                 return; // they cancelled               
4510         }               
4511    choice-=2;
4512
4513         if (choice >=num_active_games)
4514         {
4515                 nm_messagebox(TXT_SORRY, 1, TXT_OK, TXT_INVALID_CHOICE);
4516                 goto remenu;
4517         }
4518
4519         // Choice has been made and looks legit
4520         if (Active_games[choice].game_status == NETSTAT_ENDLEVEL)
4521         {
4522                 nm_messagebox(TXT_SORRY, 1, TXT_OK, TXT_NET_GAME_BETWEEN2);
4523                 goto remenu;
4524         }
4525
4526         if (Active_games[choice].protocol_version != MULTI_PROTO_VERSION)
4527         {
4528                 if (Active_games[choice].protocol_version == 3) {
4529                         #ifndef SHAREWARE
4530                                 nm_messagebox(TXT_SORRY, 1, TXT_OK, "Your version of Descent 2\nis incompatible with the\nDemo version");
4531                         #endif
4532                 }
4533                 else if (Active_games[choice].protocol_version == 4) {
4534                         #ifdef SHAREWARE
4535                                 nm_messagebox(TXT_SORRY, 1, TXT_OK, "This Demo version of\nDescent 2 is incompatible\nwith the full commercial version");
4536                         #endif
4537                 }
4538                 else
4539                         nm_messagebox(TXT_SORRY, 1, TXT_OK, TXT_VERSION_MISMATCH);
4540
4541                 goto remenu;
4542         }
4543
4544 #ifndef SHAREWARE
4545         {       
4546                 // Check for valid mission name
4547                         mprintf((0, "Loading mission:%s.\n", Active_games[choice].mission_name));
4548                         if (!load_mission_by_name(Active_games[choice].mission_name))
4549                         {
4550                                 nm_messagebox(NULL, 1, TXT_OK, TXT_MISSION_NOT_FOUND);
4551                                 goto remenu;
4552                         }
4553         }
4554 #endif
4555
4556 #if defined (D2_OEM)
4557         {
4558                 if (Active_games[choice].levelnum>8)
4559                  {
4560                                 nm_messagebox(NULL, 1, TXT_OK, "This OEM version only supports\nthe first 8 levels!");
4561                                 goto remenu;
4562                  }
4563         }
4564 #endif                  
4565
4566      if (!network_wait_for_all_info (choice))
4567                 {
4568                   nm_messagebox (TXT_SORRY,1,TXT_OK,"There was a join error!");
4569                   Network_status = NETSTAT_BROWSING; // We are looking at a game menu
4570                   goto remenu;
4571                 }       
4572           
4573           Network_status = NETSTAT_BROWSING; // We are looking at a game menu
4574  
4575      if (!can_join_netgame(&Active_games[choice],&ActiveNetPlayers[choice]))
4576                         {
4577                                 if (Active_games[choice].numplayers == Active_games[choice].max_numplayers)
4578                                         nm_messagebox(TXT_SORRY, 1, TXT_OK, TXT_GAME_FULL);
4579                                 else
4580                                         nm_messagebox(TXT_SORRY, 1, TXT_OK, TXT_IN_PROGRESS);
4581                                 goto remenu;
4582                         }
4583
4584         // Choice is valid, prepare to join in
4585
4586         memcpy(&Netgame, &Active_games[choice], sizeof(netgame_info));
4587    memcpy (&NetPlayers,&ActiveNetPlayers[choice],sizeof(AllNetPlayers_info));
4588
4589         Difficulty_level = Netgame.difficulty;
4590         MaxNumNetPlayers = Netgame.max_numplayers;
4591         change_playernum_to(1);
4592
4593         #ifdef MACINTOSH
4594
4595 // register the joining player with NBP.  This will have the nice effect of a player wanting to
4596 // join to be able to see the netgame if this player were to become the master.
4597
4598         if (Network_game_type == APPLETALK_GAME) {
4599                 OSErr err;
4600                 int count = 0;
4601                 fix t1;
4602                 
4603                 show_boxed_message("Registering Netgame");
4604                 do {
4605                         err = appletalk_register_netgame( Active_games[choice].game_name, TickCount() );
4606                         t1 = timer_get_fixed_seconds() + F1_0;
4607                         while ( timer_get_fixed_seconds() < t1 ) ;
4608                         count++;
4609                 } while ( (err == nbpDuplicate) && (count != MAX_REGISTER_TRIES) );
4610                 clear_boxed_message();
4611                 if ( (err == tooManyReqs) || (count == MAX_REGISTER_TRIES) ) {
4612                         nm_messagebox(NULL, 1, TXT_OK, "AppleTalk Network is too busy.\nPlease try again shortly.");
4613                         goto remenu;
4614                 }
4615         }
4616         #endif
4617
4618         network_set_game_mode(Netgame.gamemode);
4619
4620         network_AdjustMaxDataSize ();
4621
4622         StartNewLevel(Netgame.levelnum, 0);
4623
4624         return;         // look ma, we're in a game!!!
4625 }
4626
4627 void network_AdjustMaxDataSize ()
4628  {
4629           
4630    if (Netgame.ShortPackets)
4631         MaxXDataSize=NET_XDATA_SIZE;
4632    else
4633       MaxXDataSize=NET_XDATA_SIZE;
4634  }
4635   
4636
4637 fix StartWaitAllTime=0;
4638 int WaitAllChoice=0;
4639 #define ALL_INFO_REQUEST_INTERVAL F1_0*3
4640
4641 void network_wait_all_poll( int nitems, newmenu_item * menus, int * key, int citem )
4642  {
4643   static fix t1=0;
4644
4645   menus=menus;
4646   nitems=nitems;
4647   citem=citem;
4648
4649   if (timer_get_approx_seconds() > t1+ALL_INFO_REQUEST_INTERVAL)
4650         {
4651                 network_send_all_info_request(PID_SEND_ALL_GAMEINFO,SecurityCheck);
4652                 t1 = timer_get_approx_seconds();
4653         }
4654
4655   network_do_big_wait(WaitAllChoice);  
4656    
4657   if(SecurityCheck==-1)
4658    *key=-2;
4659  }
4660  
4661 int network_wait_for_all_info (int choice)
4662  {
4663   int pick;
4664   
4665   newmenu_item m[2];
4666
4667   m[0].type=NM_TYPE_TEXT; m[0].text = "Press Escape to cancel";
4668
4669   WaitAllChoice=choice;
4670   StartWaitAllTime=timer_get_approx_seconds();
4671   SecurityCheck=Active_games[choice].Security;
4672   NetSecurityFlag=0;
4673
4674   GetMenu:
4675   pick=newmenu_do( NULL, "Connecting...", 1, m, network_wait_all_poll );
4676
4677   if (pick>-1 && SecurityCheck!=-1)
4678         goto GetMenu;
4679
4680   if (SecurityCheck==-1)
4681     {   
4682            SecurityCheck=0;     
4683            return (1);
4684          }
4685   SecurityCheck=0;      
4686   return (0);
4687  }
4688
4689 void network_do_big_wait(int choice)
4690 {
4691         int size;
4692         ubyte packet[IPX_MAX_DATA_SIZE],*data;
4693         AllNetPlayers_info *temp_info;
4694 #ifdef MACINTOSH
4695         AllNetPlayers_info info_struct;
4696         ubyte apacket[APPLETALK_MAX_DATA_SIZE];
4697 #endif
4698   
4699         #ifdef MACINTOSH
4700         if (Network_game_type == APPLETALK_GAME)
4701                 size=appletalk_get_packet_data( apacket );
4702         else
4703         #endif
4704                 size=ipx_get_packet_data( packet );
4705         
4706   if (size>0)
4707         {
4708                 #ifdef MACINTOSH
4709                 if (Network_game_type == APPLETALK_GAME)
4710                         data = apacket;
4711                 else
4712                 #endif
4713                         data = packet;
4714   
4715          switch (data[0])
4716      {  
4717                 case PID_GAME_INFO:
4718
4719                 if (Network_game_type == IPX_GAME) {
4720                         #ifndef MACINTOSH
4721                         memcpy((ubyte *)&TempNetInfo, data, sizeof(netgame_info));
4722                         #else
4723                         receive_netgame_packet(data, &TempNetInfo, 0);
4724                         #endif
4725                 } else {
4726                         memcpy((ubyte *)&TempNetInfo, data, sizeof(netgame_info));
4727                 }
4728                 mprintf ((0,"This is %s game with a security of %d\n",TempNetInfo.game_name,TempNetInfo.Security));
4729
4730       if (TempNetInfo.Security !=SecurityCheck)
4731                  {
4732                   mprintf ((0,"Bad security on big_wait...rejecting.\n"));      
4733                   break;
4734                  }
4735                       
4736       if (NetSecurityFlag==NETSECURITY_WAIT_FOR_GAMEINFO)
4737            {
4738                    if (TempPlayersInfo->Security==TempNetInfo.Security)
4739                         {
4740                           mprintf ((0,"EQUAL !: Game=%d Players=%d ",TempPlayersInfo->Security,TempNetInfo.Security));
4741                 if (TempPlayersInfo->Security==SecurityCheck)
4742                           {
4743                                         memcpy (&Active_games[choice],(ubyte *)&TempNetInfo,sizeof(netgame_info));
4744                                         memcpy (&ActiveNetPlayers[choice],TempPlayersInfo,sizeof(AllNetPlayers_info));
4745                                         SecurityCheck=-1;
4746                           }
4747                         }
4748            }
4749                 else
4750            {
4751               NetSecurityFlag=NETSECURITY_WAIT_FOR_PLAYERS;
4752               NetSecurityNum=TempNetInfo.Security;
4753                                     
4754               if (network_wait_for_playerinfo())
4755                         {
4756                            mprintf ((0,"HUH? Game=%d Player=%d\n",NetSecurityNum,TempPlayersInfo->Security));
4757                                 memcpy (&Active_games[choice],(ubyte *)&TempNetInfo,sizeof(netgame_info));
4758                                 memcpy (&ActiveNetPlayers[choice],TempPlayersInfo,sizeof(AllNetPlayers_info));
4759                                 SecurityCheck=-1;
4760                         }
4761               NetSecurityFlag=0;
4762               NetSecurityNum=0;
4763            }
4764         break;
4765       case PID_PLAYERSINFO:
4766                mprintf ((0,"Got a PID_PLAYERSINFO!\n"));
4767
4768                         if (Network_game_type == IPX_GAME) {
4769                                 #ifndef MACINTOSH
4770                                 temp_info=(AllNetPlayers_info *)data;
4771                                 #else
4772                                 receive_netplayers_packet(data, &info_struct);
4773                                 temp_info = &info_struct;
4774                                 #endif
4775                         } else {
4776                                 temp_info = (AllNetPlayers_info *)data;
4777                         }
4778                         if (temp_info->Security!=SecurityCheck) 
4779                                 break;     // If this isn't the guy we're looking for, move on
4780
4781                         memcpy (&TempPlayersBase,(ubyte *)&temp_info,sizeof(AllNetPlayers_info));
4782                         TempPlayersInfo=&TempPlayersBase;
4783                         WaitingForPlayerInfo=0;
4784                         NetSecurityNum=TempPlayersInfo->Security;
4785                         NetSecurityFlag=NETSECURITY_WAIT_FOR_GAMEINFO;
4786                         break;
4787            }
4788         }
4789 }
4790
4791 void network_leave_game()
4792
4793    int nsave;
4794                 
4795         network_do_frame(1, 1);
4796    
4797    #ifdef NETPROFILING
4798         fclose (SendLogFile);
4799            fclose (RecieveLogFile);
4800         #endif
4801
4802         if ((network_i_am_master()))
4803         {
4804                 while (Network_sending_extras>1 && Player_joining_extras!=-1)
4805                   network_send_extras();
4806    
4807                 Netgame.numplayers = 0;
4808            nsave=N_players;
4809            N_players=0;
4810                 network_send_game_info(NULL);
4811                 N_players=nsave;
4812                 
4813                 mprintf ((0,"HEY! I'm master and I've left.\n"));
4814         }
4815         
4816         Players[Player_num].connected = 0;
4817         network_send_endlevel_packet();
4818         change_playernum_to(0);
4819         Game_mode = GM_GAME_OVER;
4820    write_player_file();
4821
4822 //      WIN(ipx_destroy_read_thread());
4823
4824         network_flush();
4825 }
4826
4827 void network_flush()
4828 {
4829         #ifdef MACINTOSH
4830         ubyte apacket[APPLETALK_MAX_DATA_SIZE];
4831         #endif
4832         ubyte packet[IPX_MAX_DATA_SIZE];
4833
4834         #ifdef MACINTOSH
4835         if ( (Network_game_type == APPLETALK_GAME) && (Appletalk_active <= 0) )
4836                 return;
4837         #endif
4838         
4839         if ( Network_game_type == IPX_GAME )
4840                 if (!Network_active) return;
4841
4842         #ifdef MACINTOSH
4843         if (Network_game_type == APPLETALK_GAME)
4844                 while (appletalk_get_packet_data(apacket) > 0) ;
4845         else
4846         #endif
4847                 while (ipx_get_packet_data(packet) > 0) ;
4848 }
4849
4850 void network_listen()
4851 {
4852         #ifdef MACINTOSH
4853         ubyte apacket[APPLETALK_MAX_DATA_SIZE];
4854         #endif
4855         int size;
4856         ubyte packet[IPX_MAX_DATA_SIZE];
4857         int i,loopmax=999;
4858
4859         if (Network_status==NETSTAT_PLAYING && Netgame.ShortPackets && !Network_send_objects)
4860          {
4861                 loopmax=N_players*Netgame.PacketsPerSec;
4862          }
4863         
4864         #ifdef MACINTOSH
4865         if ( (Network_game_type == APPLETALK_GAME) && (Appletalk_active <= 0) )
4866                 return;
4867         #endif
4868
4869         if (Network_game_type == IPX_GAME)      
4870                 if (!Network_active) return;
4871
4872         if (!(Game_mode & GM_NETWORK) && (Function_mode == FMODE_GAME))
4873                 mprintf((0, "Calling network_listen() when not in net game.\n"));
4874
4875         WaitingForPlayerInfo=1;
4876         NetSecurityFlag=NETSECURITY_OFF;
4877
4878         i=1;
4879         if (Network_game_type == IPX_GAME) {
4880                 size = ipx_get_packet_data( packet );
4881                 while ( size > 0)       {
4882                         network_process_packet( packet, size );
4883                         if (++i>loopmax)
4884                          break;
4885                         size = ipx_get_packet_data( packet );
4886                 }
4887         #ifdef MACINTOSH
4888         } else {
4889                 size = appletalk_get_packet_data( apacket );
4890                 while ( size > 0)       {
4891                         network_process_packet( apacket, size );
4892                         if (++i>loopmax)
4893                          break;
4894                         size = appletalk_get_packet_data( apacket );
4895                 }
4896         #endif
4897         }
4898 }
4899
4900 int network_wait_for_playerinfo()
4901 {
4902         int size,retries=0;
4903         ubyte packet[IPX_MAX_DATA_SIZE];
4904         struct AllNetPlayers_info *TempInfo;
4905         fix basetime;
4906         ubyte id;
4907 #ifdef MACINTOSH
4908         AllNetPlayers_info info_struct;
4909         ubyte apacket[APPLETALK_MAX_DATA_SIZE];
4910 #endif
4911
4912         #ifdef MACINTOSH
4913         if ( (Network_game_type == APPLETALK_GAME) && (Appletalk_active <= 0) )
4914                 return;
4915         #endif
4916
4917         if ( Network_game_type == IPX_GAME)
4918                 if (!Network_active) return(0);
4919                 
4920       //  if (!WaitingForPlayerInfo)
4921         // return (1);
4922
4923         if (!(Game_mode & GM_NETWORK) && (Function_mode == FMODE_GAME))
4924                 {
4925         mprintf((0, "Calling network_wait_for_playerinfo() when not in net game.\n"));
4926                 }       
4927         if (Network_status==NETSTAT_PLAYING)
4928          {
4929                   Int3(); //MY GOD! Get Jason...this is the source of many problems
4930              return (0);
4931          }
4932    basetime=timer_get_approx_seconds();
4933
4934    while (WaitingForPlayerInfo && retries<50 && (timer_get_approx_seconds()<(basetime+(F1_0*5))))
4935       {
4936                 if (Network_game_type == IPX_GAME) {
4937                         size = ipx_get_packet_data( packet );
4938                         id = packet[0];
4939                 } else {
4940                         #ifdef MACINTOSH
4941                         size = appletalk_get_packet_data( apacket );
4942                         id = apacket[0];
4943                         #endif
4944                 }
4945
4946         if (size>0 && id==PID_PLAYERSINFO)
4947         {
4948                 #ifdef MACINTOSH
4949                 if (Network_game_type == APPLETALK_GAME) {
4950                         TempInfo = (AllNetPlayers_info *)apacket;
4951                 } else {
4952                         receive_netplayers_packet(packet, &info_struct);
4953                         TempInfo = &info_struct;
4954                 }
4955                 #else
4956                 TempInfo=(AllNetPlayers_info *)packet;
4957                 #endif
4958     
4959                 retries++;
4960
4961             if (NetSecurityFlag==NETSECURITY_WAIT_FOR_PLAYERS)
4962              {
4963               if (NetSecurityNum==TempInfo->Security)
4964                {
4965                 mprintf ((0,"HEYEQUAL: Player=%d Game=%d\n",TempInfo->Security,NetSecurityNum));
4966                 memcpy (&TempPlayersBase,(ubyte *)TempInfo,sizeof(AllNetPlayers_info));
4967                 TempPlayersInfo=&TempPlayersBase;
4968                 NetSecurityFlag=NETSECURITY_OFF;
4969                 NetSecurityNum=0;
4970                 WaitingForPlayerInfo=0;
4971                 return (1);
4972                }
4973               else
4974                continue;
4975              }
4976             else
4977              {
4978               mprintf ((0,"I'm original!\n"));
4979
4980               NetSecurityNum=TempInfo->Security;
4981               NetSecurityFlag=NETSECURITY_WAIT_FOR_GAMEINFO;
4982            
4983               memcpy (&TempPlayersBase,(ubyte *)TempInfo,sizeof(AllNetPlayers_info));
4984               TempPlayersInfo=&TempPlayersBase;
4985               WaitingForPlayerInfo=0;
4986               return (1);
4987              }
4988            }
4989          }
4990    return (0);
4991   }
4992
4993
4994 void network_send_data( ubyte * ptr, int len, int urgent )
4995 {
4996         char check;
4997
4998    #ifdef NETPROFILING
4999            TTSent[ptr[0]]++;  
5000            fprintf (SendLogFile,"Packet type: %d Len:%d Urgent:%d TT=%d\n",ptr[0],len,urgent,TTSent[ptr[0]]);
5001            fflush (SendLogFile);
5002         #endif
5003     
5004         if (Endlevel_sequence)
5005                 return;
5006
5007         if (!MySyncPackInitialized)     {
5008                 MySyncPackInitialized = 1;
5009                 memset( &MySyncPack, 0, sizeof(frame_info) );
5010         }
5011         
5012         if (urgent)
5013                 PacketUrgent = 1;
5014
5015         if ((MySyncPack.data_size+len) > MaxXDataSize ) {
5016                 check = ptr[0];
5017                 network_do_frame(1, 0);
5018                 if (MySyncPack.data_size != 0) {
5019                         mprintf((0, "%d bytes were added to data by network_do_frame!\n", MySyncPack.data_size));
5020                         Int3();
5021                 }
5022 //              Int3();         // Trying to send too much!
5023 //              return;
5024                 mprintf((0, "Packet overflow, sending additional packet, type %d len %d.\n", ptr[0], len));
5025                 Assert(check == ptr[0]);
5026         }
5027
5028         Assert(MySyncPack.data_size+len <= MaxXDataSize);
5029
5030         memcpy( &MySyncPack.data[MySyncPack.data_size], ptr, len );
5031         MySyncPack.data_size += len;
5032 }
5033
5034 void network_timeout_player(int playernum)
5035 {
5036         // Remove a player from the game if we haven't heard from them in 
5037         // a long time.
5038         int i, n = 0;
5039
5040         Assert(playernum < N_players);
5041         Assert(playernum > -1);
5042
5043         network_disconnect_player(playernum);
5044         create_player_appearance_effect(&Objects[Players[playernum].objnum]);
5045
5046         digi_play_sample(SOUND_HUD_MESSAGE, F1_0);
5047
5048         HUD_init_message("%s %s", Players[playernum].callsign, TXT_DISCONNECTING);
5049         for (i = 0; i < N_players; i++)
5050                 if (Players[i].connected) 
5051                         n++;
5052
5053         if (n == 1)
5054         {
5055                 nm_messagebox(NULL, 1, TXT_OK, TXT_YOU_ARE_ONLY);
5056         }
5057 }
5058
5059 fix last_send_time = 0;
5060 fix last_timeout_check = 0;
5061
5062 #ifdef MACINTOSH
5063 void squish_short_frame_info(short_frame_info old_info, ubyte *data)
5064 {
5065         int loc = 0;
5066         int tmpi;
5067         short tmps;
5068         
5069         data[0] = old_info.type;                              loc++;  loc += 3;               // skip three for pad byte
5070         tmpi = swapint(old_info.numpackets);
5071         memcpy(&(data[loc]), &tmpi, 4);                                                 loc += 4;
5072
5073         memcpy(&(data[loc]), old_info.thepos.bytemat, 9);               loc += 9;
5074         tmps = INTEL_SHORT(old_info.thepos.xo);
5075         memcpy(&(data[loc]), &tmps, 2);                 loc += 2;
5076         tmps = INTEL_SHORT(old_info.thepos.yo);
5077         memcpy(&(data[loc]), &tmps, 2);                 loc += 2;
5078         tmps = INTEL_SHORT(old_info.thepos.zo);
5079         memcpy(&(data[loc]), &tmps, 2);                 loc += 2;
5080         tmps = INTEL_SHORT(old_info.thepos.segment);
5081         memcpy(&(data[loc]), &tmps, 2);    loc += 2;
5082         tmps = INTEL_SHORT(old_info.thepos.velx);
5083         memcpy(&(data[loc]), &tmps, 2);               loc += 2;
5084         tmps = INTEL_SHORT(old_info.thepos.vely);
5085         memcpy(&(data[loc]), &tmps, 2);               loc += 2;
5086         tmps = INTEL_SHORT(old_info.thepos.velz);
5087         memcpy(&(data[loc]), &tmps, 2);               loc += 2;
5088
5089         tmps = swapshort(old_info.data_size);
5090         memcpy(&(data[loc]), &tmps, 2);                                                 loc += 2;
5091
5092         data[loc] = old_info.playernum; loc++;
5093         data[loc] = old_info.obj_render_type; loc++;
5094         data[loc] = old_info.level_num; loc++;
5095         memcpy(&(data[loc]), old_info.data, old_info.data_size);
5096 }
5097 #endif
5098
5099 char NakedBuf[NET_XDATA_SIZE+4];
5100 int NakedPacketLen=0;
5101 int NakedPacketDestPlayer=-1;
5102
5103 void network_do_frame(int force, int listen)
5104 {
5105         int i;
5106         short_frame_info ShortSyncPack;
5107         static fix LastEndlevel=0;
5108
5109         if (!(Game_mode&GM_NETWORK)) return;
5110
5111         if ((Network_status != NETSTAT_PLAYING) || (Endlevel_sequence)) // Don't send postion during escape sequence...
5112                 goto listen;
5113
5114   if (NakedPacketLen)
5115         {
5116                 Assert (NakedPacketDestPlayer>-1);
5117 //         mprintf ((0,"Sending a naked packet to %s (%d bytes)!\n",Players[NakedPacketDestPlayer].callsign,NakedPacketLen));
5118                 if (Network_game_type == IPX_GAME) 
5119                         ipx_send_packet_data( (ubyte *)NakedBuf, NakedPacketLen, NetPlayers.players[NakedPacketDestPlayer].network.ipx.server, NetPlayers.players[NakedPacketDestPlayer].network.ipx.node,Players[NakedPacketDestPlayer].net_address );
5120                 #ifdef MACINTOSH
5121                 else
5122                         appletalk_send_packet_data( (ubyte *)NakedBuf, NakedPacketLen, NetPlayers.players[NakedPacketDestPlayer].network.appletalk.node, NetPlayers.players[NakedPacketDestPlayer].network.appletalk.net,NetPlayers.players[NakedPacketDestPlayer].network.appletalk.socket );
5123                 #endif
5124                 NakedPacketLen=0;
5125                 NakedPacketDestPlayer=-1;
5126    }
5127   
5128    if (WaitForRefuseAnswer && timer_get_approx_seconds()>(RefuseTimeLimit+(F1_0*12)))
5129                 WaitForRefuseAnswer=0;
5130                         
5131         last_send_time += FrameTime;
5132         last_timeout_check += FrameTime;
5133
5134    // Send out packet PacksPerSec times per second maximum... unless they fire, then send more often...
5135    if ( (last_send_time>F1_0/Netgame.PacketsPerSec) || (Network_laser_fired) || force || PacketUrgent )       {        
5136                 if ( Players[Player_num].connected )    {
5137                         int objnum = Players[Player_num].objnum;
5138                         PacketUrgent = 0;
5139
5140                         if (listen) {
5141                                 multi_send_robot_frame(0);
5142                                 multi_send_fire();              // Do firing if needed..
5143                         }
5144
5145                         last_send_time = 0;
5146
5147                         if (Netgame.ShortPackets)
5148                         {
5149 #ifdef MACINTOSH
5150                                 ubyte send_data[IPX_MAX_DATA_SIZE];
5151                                 int squished_size;
5152 #endif
5153                                 create_shortpos(&ShortSyncPack.thepos, Objects+objnum, 0);
5154                                 ShortSyncPack.type                                      = PID_PDATA;
5155                                 ShortSyncPack.playernum                         = Player_num;
5156                                 ShortSyncPack.obj_render_type           = Objects[objnum].render_type;
5157                                 ShortSyncPack.level_num                         = Current_level_num;
5158                                 ShortSyncPack.data_size                         = MySyncPack.data_size;
5159                                 memcpy (&ShortSyncPack.data[0],&MySyncPack.data[0],MySyncPack.data_size);
5160
5161                                 for (i=0; i<N_players; i++ )    {
5162                                         if ( (Players[i].connected) && (i!=Player_num ) )       {
5163                                                 MySyncPack.numpackets = Players[i].n_packets_sent++;
5164                                                 ShortSyncPack.numpackets=MySyncPack.numpackets;
5165                                                 if (Network_game_type == IPX_GAME) {
5166                                                         #ifndef MACINTOSH
5167                                                         ipx_send_packet_data( (ubyte *)&ShortSyncPack, sizeof(short_frame_info)-MaxXDataSize+MySyncPack.data_size, NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node,Players[i].net_address );
5168                                                         #else
5169                                                         squish_short_frame_info(ShortSyncPack, send_data);
5170                                                         ipx_send_packet_data( (ubyte *)send_data, IPX_SHORT_INFO_SIZE-MaxXDataSize+MySyncPack.data_size, NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node,Players[i].net_address );
5171                                                         #endif
5172                                                 #ifdef MACINTOSH
5173                                                 } else {
5174                                                         appletalk_send_packet_data( (ubyte *)&ShortSyncPack, sizeof(short_frame_info)-MaxXDataSize+MySyncPack.data_size, NetPlayers.players[i].network.appletalk.node, NetPlayers.players[i].network.appletalk.net, NetPlayers.players[i].network.appletalk.socket );
5175                                                 #endif
5176                                                 }
5177                                         }
5178                                 }
5179                         }
5180                         else  // If long packets
5181                         {
5182                                 int send_data_size;
5183                                 
5184                                 MySyncPack.type                                 = PID_PDATA;
5185                                 MySyncPack.playernum                    = Player_num;
5186                                 MySyncPack.obj_render_type              = Objects[objnum].render_type;
5187                                 MySyncPack.level_num                    = Current_level_num;
5188                                 MySyncPack.obj_segnum                   = Objects[objnum].segnum;
5189                                 MySyncPack.obj_pos                              = Objects[objnum].pos;
5190                                 MySyncPack.obj_orient                   = Objects[objnum].orient;
5191                                 MySyncPack.phys_velocity                = Objects[objnum].mtype.phys_info.velocity;
5192                                 MySyncPack.phys_rotvel                  = Objects[objnum].mtype.phys_info.rotvel;
5193                                 
5194                                 send_data_size = MySyncPack.data_size;                  // do this so correct size data is sent
5195
5196                                 #ifdef MACINTOSH                        // do the swap stuff
5197                                 if (Network_game_type == IPX_GAME) {
5198                                         MySyncPack.obj_segnum = INTEL_SHORT(MySyncPack.obj_segnum);
5199                                         MySyncPack.obj_pos.x = INTEL_INT((int)MySyncPack.obj_pos.x);
5200                                         MySyncPack.obj_pos.y = INTEL_INT((int)MySyncPack.obj_pos.y);
5201                                         MySyncPack.obj_pos.z = INTEL_INT((int)MySyncPack.obj_pos.z);
5202                                         
5203                                         MySyncPack.obj_orient.rvec.x = INTEL_INT((int)MySyncPack.obj_orient.rvec.x);
5204                                         MySyncPack.obj_orient.rvec.y = INTEL_INT((int)MySyncPack.obj_orient.rvec.y);
5205                                         MySyncPack.obj_orient.rvec.z = INTEL_INT((int)MySyncPack.obj_orient.rvec.z);
5206                                         MySyncPack.obj_orient.uvec.x = INTEL_INT((int)MySyncPack.obj_orient.uvec.x);
5207                                         MySyncPack.obj_orient.uvec.y = INTEL_INT((int)MySyncPack.obj_orient.uvec.y);
5208                                         MySyncPack.obj_orient.uvec.z = INTEL_INT((int)MySyncPack.obj_orient.uvec.z);
5209                                         MySyncPack.obj_orient.fvec.x = INTEL_INT((int)MySyncPack.obj_orient.fvec.x);
5210                                         MySyncPack.obj_orient.fvec.y = INTEL_INT((int)MySyncPack.obj_orient.fvec.y);
5211                                         MySyncPack.obj_orient.fvec.z = INTEL_INT((int)MySyncPack.obj_orient.fvec.z);
5212                                         
5213                                         MySyncPack.phys_velocity.x = INTEL_INT((int)MySyncPack.phys_velocity.x);
5214                                         MySyncPack.phys_velocity.y = INTEL_INT((int)MySyncPack.phys_velocity.y);
5215                                         MySyncPack.phys_velocity.z = INTEL_INT((int)MySyncPack.phys_velocity.z);
5216                                 
5217                                         MySyncPack.phys_rotvel.x = INTEL_INT((int)MySyncPack.phys_rotvel.x);
5218                                         MySyncPack.phys_rotvel.y = INTEL_INT((int)MySyncPack.phys_rotvel.y);
5219                                         MySyncPack.phys_rotvel.z = INTEL_INT((int)MySyncPack.phys_rotvel.z);
5220                                         
5221                                         MySyncPack.data_size = INTEL_SHORT(MySyncPack.data_size);
5222                                 }
5223                                 #endif
5224
5225                                 for (i=0; i<N_players; i++ )    {
5226                                         if ( (Players[i].connected) && (i!=Player_num ) )       {
5227                                                 if (Network_game_type == IPX_GAME)
5228                                                         MySyncPack.numpackets = INTEL_INT(Players[i].n_packets_sent);
5229                                                 #ifdef MACINTOSH
5230                                                 else
5231                                                         MySyncPack.numpackets = Players[i].n_packets_sent;
5232                                                 #endif
5233
5234                                                 Players[i].n_packets_sent++;
5235                                                 if (Network_game_type == IPX_GAME)
5236                                                         ipx_send_packet_data( (ubyte *)&MySyncPack, sizeof(frame_info)-MaxXDataSize+send_data_size, NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node,Players[i].net_address );
5237                                                 #ifdef MACINTOSH
5238                                                 else
5239                                                         appletalk_send_packet_data( (ubyte *)&MySyncPack, sizeof(frame_info)-MaxXDataSize+send_data_size, NetPlayers.players[i].network.appletalk.node, NetPlayers.players[i].network.appletalk.net, NetPlayers.players[i].network.appletalk.socket);
5240                                                 #endif
5241                                         }
5242                                 }
5243                         }
5244                                 
5245                         MySyncPack.data_size = 0;               // Start data over at 0 length.
5246                         if (Control_center_destroyed)
5247                         {
5248                                 if (Player_is_dead)
5249                                         Players[Player_num].connected=3;
5250                                 if (timer_get_approx_seconds() > (LastEndlevel+(F1_0/2)))
5251                                 {
5252                                         network_send_endlevel_packet();
5253                                         LastEndlevel=timer_get_approx_seconds();
5254                                 }
5255                         }
5256                         //mprintf( (0, "Packet has %d bytes appended (TS=%d)\n", MySyncPack.data_size, sizeof(frame_info)-MaxXDataSize+MySyncPack.data_size ));
5257                 }
5258         }
5259    
5260         if (!listen)
5261                 return;
5262
5263         if ((last_timeout_check > F1_0) && !(Control_center_destroyed))
5264         {
5265                 fix approx_time = timer_get_approx_seconds();
5266                 // Check for player timeouts
5267                 for (i = 0; i < N_players; i++)
5268                 {
5269                         if ((i != Player_num) && (Players[i].connected == 1))
5270                         {
5271                                 if ((LastPacketTime[i] == 0) || (LastPacketTime[i] > approx_time))
5272                                 {
5273                                         LastPacketTime[i] = approx_time;
5274                                         continue;
5275                                 }
5276                                 if ((approx_time - LastPacketTime[i]) > (15*F1_0))
5277                                         network_timeout_player(i);
5278                         }
5279                 }
5280                 last_timeout_check = 0;
5281         }
5282
5283 listen:
5284         if (!listen)
5285         {
5286                 MySyncPack.data_size = 0;
5287                 return;
5288         }
5289         network_listen();
5290
5291    if (VerifyPlayerJoined!=-1 && !(FrameCount & 63))
5292           resend_sync_due_to_packet_loss_for_allender(); // This will resend to network_player_rejoining
5293  
5294         if (Network_send_objects)
5295                 network_send_objects();
5296
5297         if (Network_sending_extras && VerifyPlayerJoined==-1)
5298         {
5299           network_send_extras();
5300           return;
5301     }
5302 }
5303
5304 int missed_packets = 0;
5305
5306 int ConsistencyCount = 0;
5307
5308 void network_consistency_error(void)
5309 {
5310         if (++ConsistencyCount < 10)
5311                 return;
5312
5313         Function_mode = FMODE_MENU;
5314         #ifndef MACINTOSH
5315         nm_messagebox(NULL, 1, TXT_OK, TXT_CONSISTENCY_ERROR);
5316         #else
5317         nm_messagebox(NULL, 1, TXT_OK, "Failed to join the netgame.\nYou are missing packets.  Check\nyour network connection and\ntry again.");
5318         #endif
5319         Function_mode = FMODE_GAME;
5320         ConsistencyCount = 0;
5321         multi_quit_game = 1;
5322         multi_leave_menu = 1;
5323         multi_reset_stuff();
5324         Function_mode = FMODE_MENU;
5325 }
5326
5327 void network_process_pdata (char *data)
5328  {
5329   Assert (Game_mode & GM_NETWORK);
5330  
5331   if (Netgame.ShortPackets)
5332         network_read_pdata_short_packet ((short_frame_info *)data);
5333   else
5334         network_read_pdata_packet ((frame_info *)data);
5335  }
5336
5337 void network_read_pdata_packet(frame_info *pd )
5338 {
5339         int TheirPlayernum;
5340         int TheirObjnum;
5341         object * TheirObj = NULL;
5342         
5343 // frame_info should be aligned...for mac, make the necessary adjustments
5344 #ifdef MACINTOSH
5345         if (Network_game_type == IPX_GAME) {
5346                 pd->numpackets = INTEL_INT(pd->numpackets);
5347                 pd->obj_pos.x = INTEL_INT(pd->obj_pos.x);
5348                 pd->obj_pos.y = INTEL_INT(pd->obj_pos.y);
5349                 pd->obj_pos.z = INTEL_INT(pd->obj_pos.z);
5350         
5351                 pd->obj_orient.rvec.x = (fix)INTEL_INT((int)pd->obj_orient.rvec.x);
5352                 pd->obj_orient.rvec.y = (fix)INTEL_INT((int)pd->obj_orient.rvec.y);
5353                 pd->obj_orient.rvec.z = (fix)INTEL_INT((int)pd->obj_orient.rvec.z);
5354                 pd->obj_orient.uvec.x = (fix)INTEL_INT((int)pd->obj_orient.uvec.x);
5355                 pd->obj_orient.uvec.y = (fix)INTEL_INT((int)pd->obj_orient.uvec.y);
5356                 pd->obj_orient.uvec.z = (fix)INTEL_INT((int)pd->obj_orient.uvec.z);
5357                 pd->obj_orient.fvec.x = (fix)INTEL_INT((int)pd->obj_orient.fvec.x);
5358                 pd->obj_orient.fvec.y = (fix)INTEL_INT((int)pd->obj_orient.fvec.y);
5359                 pd->obj_orient.fvec.z = (fix)INTEL_INT((int)pd->obj_orient.fvec.z);
5360         
5361                 pd->phys_velocity.x = (fix)INTEL_INT((int)pd->phys_velocity.x);
5362                 pd->phys_velocity.y = (fix)INTEL_INT((int)pd->phys_velocity.y);
5363                 pd->phys_velocity.z = (fix)INTEL_INT((int)pd->phys_velocity.z);
5364         
5365                 pd->phys_rotvel.x = (fix)INTEL_INT((int)pd->phys_rotvel.x);
5366                 pd->phys_rotvel.y = (fix)INTEL_INT((int)pd->phys_rotvel.y);
5367                 pd->phys_rotvel.z = (fix)INTEL_INT((int)pd->phys_rotvel.z);
5368                 
5369                 pd->obj_segnum = INTEL_SHORT(pd->obj_segnum);
5370                 pd->data_size = INTEL_SHORT(pd->data_size);
5371         }
5372 #endif
5373
5374         TheirPlayernum = pd->playernum;
5375         TheirObjnum = Players[pd->playernum].objnum;
5376         
5377         if (TheirPlayernum < 0) {
5378                 Int3(); // This packet is bogus!!
5379                 return;
5380         }
5381
5382    if (VerifyPlayerJoined!=-1 && TheirPlayernum==VerifyPlayerJoined)
5383          {
5384           // Hurray! Someone really really got in the game (I think).
5385      mprintf ((0,"Hurray! VPJ (%d) reset!\n",VerifyPlayerJoined));
5386      VerifyPlayerJoined=-1;
5387          }
5388  
5389         if (!multi_quit_game && (TheirPlayernum >= N_players)) {
5390                 if (Network_status!=NETSTAT_WAITING)
5391                  {
5392                         Int3(); // We missed an important packet!
5393                         network_consistency_error();
5394                         return;
5395                  }
5396                 else
5397                  return;
5398         }
5399         if (Endlevel_sequence || (Network_status == NETSTAT_ENDLEVEL) ) {
5400                 int old_Endlevel_sequence = Endlevel_sequence;
5401                 Endlevel_sequence = 1;
5402                 if ( pd->data_size>0 )  {
5403                         // pass pd->data to some parser function....
5404                         multi_process_bigdata( pd->data, pd->data_size );
5405                 }
5406                 Endlevel_sequence = old_Endlevel_sequence;
5407                 return;
5408         }
5409 //      mprintf((0, "Gametime = %d, Frametime = %d.\n", GameTime, FrameTime));
5410
5411         if ((byte)pd->level_num != Current_level_num)
5412         {
5413                 mprintf((0, "Got frame packet from player %d wrong level %d!\n", pd->playernum, pd->level_num));
5414                 return;
5415         }
5416
5417         TheirObj = &Objects[TheirObjnum];
5418
5419         //------------- Keep track of missed packets -----------------
5420         Players[TheirPlayernum].n_packets_got++;
5421         TotalPacketsGot++;
5422         LastPacketTime[TheirPlayernum] = timer_get_approx_seconds();
5423
5424         if  ( pd->numpackets != Players[TheirPlayernum].n_packets_got ) {
5425                 int missed_packets;
5426                 
5427                 missed_packets = pd->numpackets-Players[TheirPlayernum].n_packets_got;
5428                 if ((pd->numpackets-Players[TheirPlayernum].n_packets_got)>0)
5429                         TotalMissedPackets += pd->numpackets-Players[TheirPlayernum].n_packets_got;
5430
5431                         if ( missed_packets > 0 )       
5432                                 mprintf(( 0, "Missed %d packets from player #%d (%d total)\n", pd->numpackets-Players[TheirPlayernum].n_packets_got, TheirPlayernum, missed_packets ));
5433                         else
5434                                 mprintf( (0, "Got %d late packets from player #%d (%d total)\n", Players[TheirPlayernum].n_packets_got-pd->numpackets, TheirPlayernum, missed_packets ));
5435
5436                 #ifdef MACINTOSH
5437                 #ifdef APPLETALK_DEBUG
5438                 if (Network_game_type == APPLETALK_GAME) {
5439                         if ( missed_packets > 0 )       
5440                                 fprintf( at_fp, "Missed %d packets from player #%d (%d total)\n", pd->numpackets-Players[TheirPlayernum].n_packets_got, TheirPlayernum, missed_packets );
5441                         else
5442                                 fprintf( at_fp, "Got %d late packets from player #%d (%d total)\n", Players[TheirPlayernum].n_packets_got-pd->numpackets, TheirPlayernum, missed_packets );
5443                 }
5444                 #endif
5445                 
5446                 #ifdef IPX_DEBUG
5447                 if (Network_game_type == IPX_GAME) {
5448                         if ( missed_packets > 0 )       
5449                                 fprintf( ipx_fp, "Missed %d packets from player #%d (%d total)\n", pd->numpackets-Players[TheirPlayernum].n_packets_got, TheirPlayernum, missed_packets );
5450                         else
5451                                 fprintf( ipx_fp, "Got %d late packets from player #%d (%d total)\n", Players[TheirPlayernum].n_packets_got-pd->numpackets, TheirPlayernum, missed_packets );
5452                 }
5453                 #endif
5454                 #endif
5455
5456                 Players[TheirPlayernum].n_packets_got = pd->numpackets;
5457         }
5458
5459         //------------ Read the player's ship's object info ----------------------
5460         TheirObj->pos                           = pd->obj_pos;
5461         TheirObj->orient                        = pd->obj_orient;
5462         TheirObj->mtype.phys_info.velocity = pd->phys_velocity;
5463         TheirObj->mtype.phys_info.rotvel = pd->phys_rotvel;
5464
5465         if ((TheirObj->render_type != pd->obj_render_type) && (pd->obj_render_type == RT_POLYOBJ))
5466                 multi_make_ghost_player(TheirPlayernum);
5467
5468         obj_relink(TheirObjnum,pd->obj_segnum);
5469
5470         if (TheirObj->movement_type == MT_PHYSICS)
5471                 set_thrust_from_velocity(TheirObj);
5472
5473         //------------ Welcome them back if reconnecting --------------
5474         if (!Players[TheirPlayernum].connected) {
5475                 Players[TheirPlayernum].connected = 1;
5476
5477                 if (Newdemo_state == ND_STATE_RECORDING)
5478                         newdemo_record_multi_reconnect(TheirPlayernum);
5479
5480                 multi_make_ghost_player(TheirPlayernum);
5481
5482                 create_player_appearance_effect(&Objects[TheirObjnum]);
5483
5484                 digi_play_sample( SOUND_HUD_MESSAGE, F1_0);
5485                 
5486                 ClipRank (&NetPlayers.players[TheirPlayernum].rank);
5487
5488                 if (FindArg("-norankings"))      
5489                         HUD_init_message( "'%s' %s", Players[TheirPlayernum].callsign, TXT_REJOIN );
5490                 else
5491                         HUD_init_message( "%s'%s' %s", RankStrings[NetPlayers.players[TheirPlayernum].rank],Players[TheirPlayernum].callsign, TXT_REJOIN );
5492
5493
5494                 multi_send_score();
5495         }
5496
5497         //------------ Parse the extra data at the end ---------------
5498
5499         if ( pd->data_size>0 )  {
5500                 // pass pd->data to some parser function....
5501                 multi_process_bigdata( pd->data, pd->data_size );
5502         }
5503
5504 }
5505
5506 #ifdef MACINTOSH
5507 void get_short_frame_info(ubyte *old_info, short_frame_info *new_info)
5508 {
5509         int loc = 0;
5510         
5511         new_info->type = old_info[loc];                                                                 loc++;  loc += 3;               // skip three for pad byte
5512         memcpy(&(new_info->numpackets), &(old_info[loc]), 4);                   loc += 4;
5513         new_info->numpackets = INTEL_INT(new_info->numpackets);
5514         memcpy(new_info->thepos.bytemat, &(old_info[loc]), 9);                  loc += 9;
5515         memcpy(&(new_info->thepos.xo), &(old_info[loc]), 2);                    loc += 2;
5516         memcpy(&(new_info->thepos.yo), &(old_info[loc]), 2);                    loc += 2;
5517         memcpy(&(new_info->thepos.zo), &(old_info[loc]), 2);                    loc += 2;
5518         memcpy(&(new_info->thepos.segment), &(old_info[loc]), 2);               loc += 2;
5519         memcpy(&(new_info->thepos.velx), &(old_info[loc]), 2);                  loc += 2;
5520         memcpy(&(new_info->thepos.vely), &(old_info[loc]), 2);                  loc += 2;
5521         memcpy(&(new_info->thepos.velz), &(old_info[loc]), 2);                  loc += 2;
5522         new_info->thepos.xo = INTEL_SHORT(new_info->thepos.xo);
5523         new_info->thepos.yo = INTEL_SHORT(new_info->thepos.yo);
5524         new_info->thepos.zo = INTEL_SHORT(new_info->thepos.zo);
5525         new_info->thepos.segment = INTEL_SHORT(new_info->thepos.segment);
5526         new_info->thepos.velx = INTEL_SHORT(new_info->thepos.velx);
5527         new_info->thepos.vely = INTEL_SHORT(new_info->thepos.vely);
5528         new_info->thepos.velz = INTEL_SHORT(new_info->thepos.velz);
5529
5530         memcpy(&(new_info->data_size), &(old_info[loc]), 2);            loc += 2;
5531         new_info->data_size = INTEL_SHORT(new_info->data_size);
5532         new_info->playernum = old_info[loc];                                            loc++;
5533         new_info->obj_render_type = old_info[loc];                                      loc++;
5534         new_info->level_num = old_info[loc];                                            loc++;
5535         memcpy(new_info->data, &(old_info[loc]), new_info->data_size);
5536 }
5537 #endif
5538
5539 void network_read_pdata_short_packet(short_frame_info *pd )
5540 {
5541         int TheirPlayernum;
5542         int TheirObjnum;
5543         object * TheirObj = NULL;
5544         short_frame_info new_pd;
5545
5546 // short frame info is not aligned because of shortpos.  The mac
5547 // will call totally hacked and gross function to fix this up.
5548
5549         if (Network_game_type == IPX_GAME) {
5550                 #ifndef MACINTOSH
5551                 memcpy(&new_pd, (ubyte *)pd, sizeof(short_frame_info));
5552                 #else
5553                 get_short_frame_info((ubyte *)pd, &new_pd);
5554                 #endif
5555         } else {
5556                 memcpy(&new_pd, (ubyte *)pd, sizeof(short_frame_info));
5557         }
5558
5559         TheirPlayernum = new_pd.playernum;
5560         TheirObjnum = Players[new_pd.playernum].objnum;
5561
5562         if (TheirPlayernum < 0) {
5563                 Int3(); // This packet is bogus!!
5564                 return;
5565         }
5566         if (!multi_quit_game && (TheirPlayernum >= N_players)) {
5567                 if (Network_status!=NETSTAT_WAITING)
5568                  {
5569                         Int3(); // We missed an important packet!
5570                         network_consistency_error();
5571                         return;
5572                  }
5573                 else
5574                  return;
5575         }
5576
5577    if (VerifyPlayerJoined!=-1 && TheirPlayernum==VerifyPlayerJoined)
5578          {
5579           // Hurray! Someone really really got in the game (I think).
5580       mprintf ((0,"Hurray! VPJ (%d) reset!\n",VerifyPlayerJoined));
5581       VerifyPlayerJoined=-1;
5582          }
5583
5584         if (Endlevel_sequence || (Network_status == NETSTAT_ENDLEVEL) ) {
5585                 int old_Endlevel_sequence = Endlevel_sequence;
5586                 Endlevel_sequence = 1;
5587                 if ( new_pd.data_size>0 )       {
5588                         // pass pd->data to some parser function....
5589                         multi_process_bigdata( new_pd.data, new_pd.data_size );
5590                 }
5591                 Endlevel_sequence = old_Endlevel_sequence;
5592                 return;
5593         }
5594 //      mprintf((0, "Gametime = %d, Frametime = %d.\n", GameTime, FrameTime));
5595
5596         if ((byte)new_pd.level_num != Current_level_num)
5597         {
5598                 mprintf((0, "Got frame packet from player %d wrong level %d!\n", new_pd.playernum, new_pd.level_num));
5599                 return;
5600         }
5601
5602         TheirObj = &Objects[TheirObjnum];
5603
5604         //------------- Keep track of missed packets -----------------
5605         Players[TheirPlayernum].n_packets_got++;
5606         TotalPacketsGot++;
5607         LastPacketTime[TheirPlayernum] = timer_get_approx_seconds();
5608
5609         if  ( new_pd.numpackets != Players[TheirPlayernum].n_packets_got )      {
5610                 int missed_packets;
5611         
5612                 missed_packets = new_pd.numpackets-Players[TheirPlayernum].n_packets_got;
5613                 if ((new_pd.numpackets-Players[TheirPlayernum].n_packets_got)>0)
5614                         TotalMissedPackets += new_pd.numpackets-Players[TheirPlayernum].n_packets_got;
5615
5616                 if ( missed_packets > 0 )       
5617                         mprintf( (0, "Missed %d packets from player #%d (%d total)\n", new_pd.numpackets-Players[TheirPlayernum].n_packets_got, TheirPlayernum, missed_packets ));
5618                 else
5619                         mprintf( (0, "Got %d late packets from player #%d (%d total)\n", Players[TheirPlayernum].n_packets_got-new_pd.numpackets, TheirPlayernum, missed_packets ));
5620
5621                 Players[TheirPlayernum].n_packets_got = new_pd.numpackets;
5622         }
5623
5624         //------------ Read the player's ship's object info ----------------------
5625
5626         extract_shortpos(TheirObj, &new_pd.thepos, 0);
5627
5628         if ((TheirObj->render_type != new_pd.obj_render_type) && (new_pd.obj_render_type == RT_POLYOBJ))
5629                 multi_make_ghost_player(TheirPlayernum);
5630
5631         if (TheirObj->movement_type == MT_PHYSICS)
5632                 set_thrust_from_velocity(TheirObj);
5633
5634         //------------ Welcome them back if reconnecting --------------
5635         if (!Players[TheirPlayernum].connected) {
5636                 Players[TheirPlayernum].connected = 1;
5637
5638                 if (Newdemo_state == ND_STATE_RECORDING)
5639                         newdemo_record_multi_reconnect(TheirPlayernum);
5640
5641                 multi_make_ghost_player(TheirPlayernum);
5642
5643                 create_player_appearance_effect(&Objects[TheirObjnum]);
5644
5645                 digi_play_sample( SOUND_HUD_MESSAGE, F1_0);
5646                 ClipRank (&NetPlayers.players[TheirPlayernum].rank);
5647                 
5648                 if (FindArg("-norankings"))
5649                         HUD_init_message( "'%s' %s", Players[TheirPlayernum].callsign, TXT_REJOIN );
5650                 else
5651                         HUD_init_message( "%s'%s' %s", RankStrings[NetPlayers.players[TheirPlayernum].rank],Players[TheirPlayernum].callsign, TXT_REJOIN );
5652
5653
5654                 multi_send_score();
5655         }
5656
5657         //------------ Parse the extra data at the end ---------------
5658
5659         if ( new_pd.data_size>0 )       {
5660                 // pass pd->data to some parser function....
5661                 multi_process_bigdata( new_pd.data, new_pd.data_size );
5662         }
5663
5664 }
5665
5666   
5667 void network_set_power (void)
5668  {
5669   int opt=0,choice,opt_primary,opt_second,opt_power;
5670   newmenu_item m[40];
5671   
5672   opt_primary=opt;
5673   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Laser upgrade"; m[opt].value=Netgame.DoLaserUpgrade; opt++;
5674   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Super lasers"; m[opt].value=Netgame.DoSuperLaser; opt++;
5675   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Quad Lasers"; m[opt].value=Netgame.DoQuadLasers; opt++;
5676   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Vulcan cannon"; m[opt].value=Netgame.DoVulcan; opt++;
5677   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Spreadfire cannon"; m[opt].value=Netgame.DoSpread; opt++;
5678   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Plasma cannon"; m[opt].value=Netgame.DoPlasma; opt++;
5679   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Fusion cannon"; m[opt].value=Netgame.DoFusions; opt++;
5680   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Gauss cannon"; m[opt].value=Netgame.DoGauss; opt++;
5681   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Helix cannon"; m[opt].value=Netgame.DoHelix; opt++;
5682   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Phoenix cannon"; m[opt].value=Netgame.DoPhoenix; opt++;
5683   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Omega cannon"; m[opt].value=Netgame.DoOmega; opt++;
5684   
5685   opt_second=opt;   
5686   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Homing Missiles"; m[opt].value=Netgame.DoHoming; opt++;
5687   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Proximity Bombs"; m[opt].value=Netgame.DoProximity; opt++;
5688   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Smart Missiles"; m[opt].value=Netgame.DoSmarts; opt++;
5689   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Mega Missiles"; m[opt].value=Netgame.DoMegas; opt++;
5690   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Flash Missiles"; m[opt].value=Netgame.DoFlash; opt++;
5691   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Guided Missiles"; m[opt].value=Netgame.DoGuided; opt++;
5692   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Smart Mines"; m[opt].value=Netgame.DoSmartMine; opt++;
5693   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Mercury Missiles"; m[opt].value=Netgame.DoMercury; opt++;
5694   m[opt].type = NM_TYPE_CHECK; m[opt].text = "EarthShaker Missiles"; m[opt].value=Netgame.DoEarthShaker; opt++;
5695
5696   opt_power=opt;
5697   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Invulnerability"; m[opt].value=Netgame.DoInvulnerability; opt++;
5698   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Cloaking"; m[opt].value=Netgame.DoCloak; opt++;
5699   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Afterburners"; m[opt].value=Netgame.DoAfterburner; opt++;
5700   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Ammo rack"; m[opt].value=Netgame.DoAmmoRack; opt++;
5701   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Energy Converter"; m[opt].value=Netgame.DoConverter; opt++;
5702   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Headlight"; m[opt].value=Netgame.DoHeadlight; opt++;
5703   
5704   choice = newmenu_do(NULL, "Objects to allow", opt, m, NULL);
5705
5706   Netgame.DoLaserUpgrade=m[opt_primary].value; 
5707   Netgame.DoSuperLaser=m[opt_primary+1].value;
5708   Netgame.DoQuadLasers=m[opt_primary+2].value;  
5709   Netgame.DoVulcan=m[opt_primary+3].value;
5710   Netgame.DoSpread=m[opt_primary+4].value;
5711   Netgame.DoPlasma=m[opt_primary+5].value;
5712   Netgame.DoFusions=m[opt_primary+6].value;
5713   Netgame.DoGauss=m[opt_primary+7].value;
5714   Netgame.DoHelix=m[opt_primary+8].value;
5715   Netgame.DoPhoenix=m[opt_primary+9].value;
5716   Netgame.DoOmega=m[opt_primary+10].value;
5717   
5718   Netgame.DoHoming=m[opt_second].value;
5719   Netgame.DoProximity=m[opt_second+1].value;
5720   Netgame.DoSmarts=m[opt_second+2].value;
5721   Netgame.DoMegas=m[opt_second+3].value;
5722   Netgame.DoFlash=m[opt_second+4].value;
5723   Netgame.DoGuided=m[opt_second+5].value;
5724   Netgame.DoSmartMine=m[opt_second+6].value;
5725   Netgame.DoMercury=m[opt_second+7].value;
5726   Netgame.DoEarthShaker=m[opt_second+8].value;
5727
5728   Netgame.DoInvulnerability=m[opt_power].value;
5729   Netgame.DoCloak=m[opt_power+1].value;
5730   Netgame.DoAfterburner=m[opt_power+2].value;
5731   Netgame.DoAmmoRack=m[opt_power+3].value;
5732   Netgame.DoConverter=m[opt_power+4].value;     
5733   Netgame.DoHeadlight=m[opt_power+5].value;     
5734   
5735  }
5736
5737 void SetAllAllowablesTo (int on)
5738  {
5739   last_cinvul = control_invul_time = 0;   //default to zero
5740    
5741   Netgame.DoMegas=Netgame.DoSmarts=Netgame.DoFusions=Netgame.DoHelix=\
5742   Netgame.DoPhoenix=Netgame.DoCloak=Netgame.DoInvulnerability=\
5743   Netgame.DoAfterburner=Netgame.DoGauss=Netgame.DoVulcan=Netgame.DoPlasma=on;
5744
5745   Netgame.DoOmega=Netgame.DoSuperLaser=Netgame.DoProximity=\
5746   Netgame.DoSpread=Netgame.DoMercury=Netgame.DoSmartMine=Netgame.DoFlash=\
5747   Netgame.DoGuided=Netgame.DoEarthShaker=on;
5748   
5749   Netgame.DoConverter=Netgame.DoAmmoRack=Netgame.DoHeadlight=on;
5750   Netgame.DoHoming=Netgame.DoLaserUpgrade=Netgame.DoQuadLasers=on;
5751   Netgame.BrightPlayers=Netgame.invul=on;
5752  }
5753
5754 fix LastPTA;
5755 int LastKillGoal;
5756
5757 // Jeez -- mac compiler can't handle all of these on the same decl line.
5758 int opt_setpower,opt_playtime,opt_killgoal,opt_socket,opt_marker_view,opt_light,opt_show_on_map;
5759 int opt_difficulty,opt_packets,opt_short_packets, opt_bright,opt_start_invul;
5760 int opt_show_names;
5761
5762 void network_more_options_poll( int nitems, newmenu_item * menus, int * key, int citem );
5763   
5764 void network_more_game_options ()
5765  {
5766   int opt=0,i;
5767   char PlayText[80],KillText[80],srinvul[50],socket_string[5],packstring[5];
5768   newmenu_item m[21];
5769
5770   sprintf (socket_string,"%d",Network_socket);
5771   sprintf (packstring,"%d",Netgame.PacketsPerSec);
5772
5773   opt_difficulty = opt;
5774   m[opt].type = NM_TYPE_SLIDER; m[opt].value=netgame_difficulty; m[opt].text=TXT_DIFFICULTY; m[opt].min_value=0; m[opt].max_value=(NDL-1); opt++;
5775
5776   opt_cinvul = opt;
5777   sprintf( srinvul, "%s: %d %s", TXT_REACTOR_LIFE, control_invul_time*5, TXT_MINUTES_ABBREV );
5778   m[opt].type = NM_TYPE_SLIDER; m[opt].value=control_invul_time; m[opt].text= srinvul; m[opt].min_value=0; m[opt].max_value=10; opt++;
5779
5780   opt_playtime=opt;
5781   sprintf( PlayText, "Max time: %d %s", Netgame.PlayTimeAllowed*5, TXT_MINUTES_ABBREV );
5782   m[opt].type = NM_TYPE_SLIDER; m[opt].value=Netgame.PlayTimeAllowed; m[opt].text= PlayText; m[opt].min_value=0; m[opt].max_value=10; opt++;
5783
5784   opt_killgoal=opt;
5785   sprintf( KillText, "Kill Goal: %d kills", Netgame.KillGoal*5);
5786   m[opt].type = NM_TYPE_SLIDER; m[opt].value=Netgame.KillGoal; m[opt].text= KillText; m[opt].min_value=0; m[opt].max_value=10; opt++;
5787
5788   opt_start_invul=opt;
5789   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Invulnerable when reappearing"; m[opt].value=Netgame.invul; opt++;
5790         
5791   opt_marker_view = opt;
5792   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Allow camera views from Markers"; m[opt].value=Netgame.Allow_marker_view; opt++;
5793   opt_light = opt;
5794   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Indestructible lights"; m[opt].value=Netgame.AlwaysLighting; opt++;
5795
5796   opt_bright = opt;
5797   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Bright player ships"; m[opt].value=Netgame.BrightPlayers; opt++;
5798   
5799   opt_show_names=opt;
5800   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Show enemy names on HUD"; m[opt].value=Netgame.ShowAllNames; opt++;
5801
5802   opt_show_on_map=opt;
5803   m[opt].type = NM_TYPE_CHECK; m[opt].text = TXT_SHOW_ON_MAP; m[opt].value=(Netgame.game_flags & NETGAME_FLAG_SHOW_MAP); opt_show_on_map=opt; opt++;
5804
5805   opt_short_packets=opt;
5806   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Short packets"; m[opt].value=Netgame.ShortPackets; opt++;
5807
5808   opt_setpower = opt;
5809   m[opt].type = NM_TYPE_MENU;  m[opt].text = "Set Objects allowed..."; opt++;
5810
5811   if (Network_game_type == IPX_GAME) {
5812           m[opt].type = NM_TYPE_TEXT; m[opt].text = "Network socket"; opt++;
5813           opt_socket = opt;
5814           m[opt].type = NM_TYPE_INPUT; m[opt].text = socket_string; m[opt].text_len=4; opt++;
5815   }
5816
5817   m[opt].type = NM_TYPE_TEXT; m[opt].text = "Packets per second (2 - 20)"; opt++;
5818   opt_packets=opt;
5819   m[opt].type = NM_TYPE_INPUT; m[opt].text=packstring; m[opt].text_len=2; opt++;
5820
5821   LastKillGoal=Netgame.KillGoal;
5822   LastPTA=Netgame.PlayTimeAllowed;
5823
5824   menu:
5825
5826   ExtGameStatus=GAMESTAT_MORE_NETGAME_OPTIONS; 
5827   i = newmenu_do1( NULL, "Additional netgame options", opt, m, network_more_options_poll, 0 );
5828
5829    //control_invul_time = atoi( srinvul )*60*F1_0;
5830     control_invul_time = m[opt_cinvul].value;
5831     Netgame.control_invul_time = control_invul_time*5*F1_0*60;
5832
5833   if (i==opt_setpower)
5834    {
5835     network_set_power ();
5836     goto menu;
5837    }
5838
5839   Netgame.PacketsPerSec=atoi(packstring);
5840
5841   if (Netgame.PacketsPerSec>20)
5842         {
5843          Netgame.PacketsPerSec=20;
5844          nm_messagebox(TXT_ERROR, 1, TXT_OK, "Packet value out of range\nSetting value to 20");
5845         }
5846   if (Netgame.PacketsPerSec<2)
5847         {
5848           nm_messagebox(TXT_ERROR, 1, TXT_OK, "Packet value out of range\nSetting value to 2");
5849           Netgame.PacketsPerSec=2;      
5850         }
5851
5852   mprintf ((0,"Hey! Sending out %d packets per second\n",Netgame.PacketsPerSec));
5853
5854         if (Network_game_type == IPX_GAME) { 
5855                 if ((atoi(socket_string))!=Network_socket) {
5856                         Network_socket=atoi(socket_string);
5857                         ipx_change_default_socket( IPX_DEFAULT_SOCKET + Network_socket );
5858                 }
5859         }
5860
5861   Netgame.invul=m[opt_start_invul].value;       
5862   Netgame.BrightPlayers=m[opt_bright].value;
5863   Netgame.ShortPackets=m[opt_short_packets].value;
5864   Netgame.ShowAllNames=m[opt_show_names].value;
5865   network_AdjustMaxDataSize();
5866
5867   Netgame.Allow_marker_view=m[opt_marker_view].value;   
5868   Netgame.AlwaysLighting=m[opt_light].value;     
5869   netgame_difficulty=Difficulty_level = m[opt_difficulty].value;
5870   if (m[opt_show_on_map].value)
5871         Netgame.game_flags |= NETGAME_FLAG_SHOW_MAP;
5872         
5873         
5874  }
5875
5876 void network_more_options_poll( int nitems, newmenu_item * menus, int * key, int citem )
5877  {
5878    menus = menus;
5879    citem = citem;      // kills compile warnings
5880    nitems = nitems;
5881    key = key;
5882
5883    if ( last_cinvul != menus[opt_cinvul].value )   {
5884         sprintf( menus[opt_cinvul].text, "%s: %d %s", TXT_REACTOR_LIFE, menus[opt_cinvul].value*5, TXT_MINUTES_ABBREV );
5885         last_cinvul = menus[opt_cinvul].value;
5886         menus[opt_cinvul].redraw = 1;
5887    }
5888   
5889   if (menus[opt_playtime].value!=LastPTA)
5890    {
5891     #ifdef SHAREWARE
5892       LastPTA=0;
5893       nm_messagebox ("Sorry",1,TXT_OK,"Registered version only!");
5894       menus[opt_playtime].value=0;
5895       menus[opt_playtime].redraw=1;
5896       return;
5897     #endif  
5898
5899     if (Game_mode & GM_MULTI_COOP)
5900      {
5901       LastPTA=0;
5902       nm_messagebox ("Sorry",1,TXT_OK,"You can't change those for coop!");
5903       menus[opt_playtime].value=0;
5904       menus[opt_playtime].redraw=1;
5905       return;
5906      }
5907
5908     Netgame.PlayTimeAllowed=menus[opt_playtime].value;
5909     sprintf( menus[opt_playtime].text, "Max Time: %d %s", Netgame.PlayTimeAllowed*5, TXT_MINUTES_ABBREV );
5910     LastPTA=Netgame.PlayTimeAllowed;
5911     menus[opt_playtime].redraw=1;
5912    }
5913   if (menus[opt_killgoal].value!=LastKillGoal)
5914    {
5915     #ifdef SHAREWARE
5916       nm_messagebox ("Sorry",1,TXT_OK,"Registered version only!");
5917       menus[opt_killgoal].value=0;
5918       menus[opt_killgoal].redraw=1;
5919       LastKillGoal=0;
5920       return;
5921          #endif         
5922
5923
5924     if (Game_mode & GM_MULTI_COOP)
5925      {
5926       nm_messagebox ("Sorry",1,TXT_OK,"You can't change those for coop!");
5927       menus[opt_killgoal].value=0;
5928       menus[opt_killgoal].redraw=1;
5929       LastKillGoal=0;
5930       return;
5931      }
5932
5933     
5934     Netgame.KillGoal=menus[opt_killgoal].value;
5935     sprintf( menus[opt_killgoal].text, "Kill Goal: %d kills", Netgame.KillGoal*5);
5936     LastKillGoal=Netgame.KillGoal;
5937     menus[opt_killgoal].redraw=1;
5938    }
5939  }
5940
5941 extern void multi_send_light (int,ubyte);
5942 extern void multi_send_light_specific (int,int,ubyte);
5943
5944 void network_send_smash_lights (int pnum) 
5945  {
5946   // send the lights that have been blown out
5947
5948   int i;
5949
5950   pnum=pnum;
5951   
5952   for (i=0;i<=Highest_segment_index;i++)
5953    if (Light_subtracted[i])
5954     multi_send_light_specific(pnum,i,Light_subtracted[i]);
5955  }
5956
5957 extern int Num_triggers;
5958 extern void multi_send_trigger_specific (char pnum,char);
5959
5960 void network_send_fly_thru_triggers (int pnum) 
5961  {
5962   // send the fly thru triggers that have been disabled
5963
5964   int i;
5965
5966   for (i=0;i<Num_triggers;i++)
5967    if (Triggers[i].flags & TF_DISABLED)
5968     multi_send_trigger_specific(pnum,i);
5969  }
5970
5971 void network_send_player_flags()
5972  {
5973   int i;
5974
5975   for (i=0;i<N_players;i++)
5976         multi_send_flags(i);
5977  }
5978
5979 void network_ping (ubyte flag,int pnum)
5980 {
5981         ubyte mybuf[2];
5982
5983         mybuf[0]=flag;
5984         mybuf[1]=Player_num;
5985
5986         if (Network_game_type == IPX_GAME)
5987                 ipx_send_packet_data( (ubyte *)mybuf, 2, NetPlayers.players[pnum].network.ipx.server, NetPlayers.players[pnum].network.ipx.node,Players[pnum].net_address );
5988         #ifdef MACINTOSH
5989         else
5990                 appletalk_send_packet_data( (ubyte *)mybuf, 2, NetPlayers.players[pnum].network.appletalk.node, NetPlayers.players[pnum].network.appletalk.net, NetPlayers.players[pnum].network.appletalk.socket);
5991         #endif
5992 }
5993
5994 extern fix PingLaunchTime,PingReturnTime;
5995
5996 void network_handle_ping_return (ubyte pnum)
5997  {
5998   if (PingLaunchTime==0 || pnum>=N_players)
5999         {
6000          mprintf ((0,"Got invalid PING RETURN from %s!\n",Players[pnum].callsign));
6001     return;
6002    }
6003   
6004   PingReturnTime=timer_get_fixed_seconds();
6005
6006   HUD_init_message ("Ping time for %s is %d ms!",Players[pnum].callsign,
6007         f2i(fixmul(PingReturnTime-PingLaunchTime,i2f(1000))));
6008   PingLaunchTime=0;
6009  }
6010         
6011 void network_send_ping (ubyte pnum)
6012  {
6013   network_ping (PID_PING_SEND,pnum);
6014  }  
6015
6016 void DoRefuseStuff (sequence_packet *their)
6017  {
6018   int i,new_player_num;
6019
6020   ClipRank (&their->player.rank);
6021         
6022   for (i=0;i<MAX_PLAYERS;i++)
6023          if (!strcmp (their->player.callsign,Players[i].callsign))
6024         {
6025                 network_welcome_player(their);
6026                         return;
6027                 }
6028   
6029    if (!WaitForRefuseAnswer)    
6030     {
6031         for (i=0;i<MAX_PLAYERS;i++)
6032                  if (!strcmp (their->player.callsign,Players[i].callsign))
6033                 {
6034                         network_welcome_player(their);
6035                                 return;
6036                         }
6037    
6038       digi_play_sample (SOUND_HUD_JOIN_REQUEST,F1_0*2);           
6039   
6040       if (Game_mode & GM_TEAM)
6041                  {
6042         
6043                                         
6044       if (!FindArg("-norankings"))
6045               HUD_init_message ("%s %s wants to join",RankStrings[their->player.rank],their->player.callsign);
6046         #ifndef MACINTOSH
6047                 HUD_init_message ("%s joining. Alt-1 assigns to team %s. Alt-2 to team %s",their->player.callsign,Netgame.team_name[0],Netgame.team_name[1]);
6048                 #else
6049                 HUD_init_message ("%s joining. Opt-1 assigns to team %s. Opt-2 to team %s",their->player.callsign,Netgame.team_name[0],Netgame.team_name[1]);
6050                 #endif
6051 //                      HUD_init_message ("Alt-1 to place on team %s!",Netgame.team_name[0]);
6052 //                      HUD_init_message ("Alt-2 to place on team %s!",Netgame.team_name[1]);
6053                  }               
6054                 else    
6055                 HUD_init_message ("%s wants to join...press F6 to connect",their->player.callsign);
6056
6057            strcpy (RefusePlayerName,their->player.callsign);
6058            RefuseTimeLimit=timer_get_approx_seconds();   
6059                 RefuseThisPlayer=0;
6060                 WaitForRefuseAnswer=1;
6061          }
6062         else
6063          {      
6064         for (i=0;i<MAX_PLAYERS;i++)
6065                  if (!strcmp (their->player.callsign,Players[i].callsign))
6066                 {
6067                         network_welcome_player(their);
6068                                 return;
6069                         }
6070       
6071                 if (strcmp(their->player.callsign,RefusePlayerName))
6072                         return;
6073
6074                 if (RefuseThisPlayer)
6075                  {
6076                                 RefuseTimeLimit=0;
6077                                 RefuseThisPlayer=0;
6078                                 WaitForRefuseAnswer=0;
6079                                 if (Game_mode & GM_TEAM)
6080                                  {
6081                                         new_player_num=GetNewPlayerNumber (their);
6082                                         mprintf ((0,"Newplayernum=%d\n",new_player_num));
6083                 
6084                                         Assert (RefuseTeam==1 || RefuseTeam==2);        
6085                                 
6086                                         if (RefuseTeam==1)      
6087                                         Netgame.team_vector &=(~(1<<new_player_num));
6088                                         else
6089                                         Netgame.team_vector |=(1<<new_player_num);
6090                                         network_welcome_player(their);
6091                                         network_send_netgame_update (); 
6092                                  }
6093                                 else
6094                                         network_welcome_player(their);
6095                            return;
6096                  }
6097                                         
6098           if ((timer_get_approx_seconds()) > RefuseTimeLimit+REFUSE_INTERVAL)
6099                 {
6100                         RefuseTimeLimit=0;
6101                         RefuseThisPlayer=0;
6102                         WaitForRefuseAnswer=0;
6103                         if (!strcmp (their->player.callsign,RefusePlayerName)) {
6104                                 if (Network_game_type == IPX_GAME)
6105                                         network_dump_player(their->player.network.ipx.server,their->player.network.ipx.node, DUMP_DORK);
6106                                 #ifdef MACINTOSH
6107                                 else
6108                                         network_dump_appletalk_player(their->player.network.appletalk.node,their->player.network.appletalk.net, their->player.network.appletalk.socket, DUMP_DORK);
6109                                 #endif
6110                         }
6111                         return;
6112                 }
6113                                                         
6114     }
6115  }
6116
6117 int GetNewPlayerNumber (sequence_packet *their)
6118   {
6119          int i;
6120         
6121          their=their;
6122         
6123                 if ( N_players < MaxNumNetPlayers)
6124                         return (N_players);
6125                 
6126                 else
6127                 {
6128                         // Slots are full but game is open, see if anyone is
6129                         // disconnected and replace the oldest player with this new one
6130                 
6131                         int oldest_player = -1;
6132                         fix oldest_time = timer_get_approx_seconds();
6133
6134                         Assert(N_players == MaxNumNetPlayers);
6135
6136                         for (i = 0; i < N_players; i++)
6137                         {
6138                                 if ( (!Players[i].connected) && (LastPacketTime[i] < oldest_time))
6139                                 {
6140                                         oldest_time = LastPacketTime[i];
6141                                         oldest_player = i;
6142                                 }
6143                         }
6144             return (oldest_player);
6145           }
6146   }
6147
6148 void network_send_extras ()
6149  {
6150         Assert (Player_joining_extras>-1);
6151
6152    if (!network_i_am_master())
6153          {
6154           mprintf ((0,"Hey! I'm not the master and I was gonna send info!\n"));
6155          // Int3();     
6156          // Network_sending_extras=0;
6157          // return;
6158     }
6159
6160
6161    if (Network_sending_extras==40)
6162                 network_send_fly_thru_triggers(Player_joining_extras);
6163    if (Network_sending_extras==38)
6164         network_send_door_updates(Player_joining_extras);
6165    if (Network_sending_extras==35)
6166                 network_send_markers();
6167    if (Network_sending_extras==30 && (Game_mode & GM_MULTI_ROBOTS))
6168                 multi_send_stolen_items();
6169         if (Network_sending_extras==25 && (Netgame.PlayTimeAllowed || Netgame.KillGoal))
6170                 multi_send_kill_goal_counts();
6171    if (Network_sending_extras==20)
6172                 network_send_smash_lights(Player_joining_extras);
6173    if (Network_sending_extras==15)
6174                 network_send_player_flags();    
6175    if (Network_sending_extras==10)
6176                 multi_send_powerup_update();  
6177  //  if (Network_sending_extras==5)
6178 //              network_send_door_updates(Player_joining_extras); // twice!
6179
6180         Network_sending_extras--;
6181    if (!Network_sending_extras)
6182          Player_joining_extras=-1;
6183  }
6184
6185
6186 void network_send_naked_packet(char *buf, short len, int who)
6187 {
6188         if (!(Game_mode&GM_NETWORK)) return;
6189
6190    if (NakedPacketLen==0)
6191          {
6192            NakedBuf[0]=PID_NAKED_PDATA;
6193            NakedBuf[1]=Player_num;
6194                 NakedPacketLen=2;
6195          }
6196
6197    if (len+NakedPacketLen>MaxXDataSize)
6198     {
6199 //         mprintf ((0,"Sending a naked packet of %d bytes.\n",NakedPacketLen));
6200                 if (Network_game_type == IPX_GAME)
6201                         ipx_send_packet_data( (ubyte *)NakedBuf, NakedPacketLen, NetPlayers.players[who].network.ipx.server, NetPlayers.players[who].network.ipx.node,Players[who].net_address );
6202                 #ifdef MACINTOSH
6203                 else
6204                         appletalk_send_packet_data( (ubyte *)NakedBuf, NakedPacketLen, NetPlayers.players[who].network.appletalk.node, NetPlayers.players[who].network.appletalk.net, NetPlayers.players[who].network.appletalk.socket );
6205                 #endif
6206                 NakedPacketLen=2;
6207                 memcpy (&NakedBuf[NakedPacketLen],buf,len);     
6208                 NakedPacketLen+=len;
6209                 NakedPacketDestPlayer=who;
6210          }
6211    else
6212          {
6213                 memcpy (&NakedBuf[NakedPacketLen],buf,len);     
6214                 NakedPacketLen+=len;
6215                 NakedPacketDestPlayer=who;
6216          }
6217  }
6218
6219
6220 void network_process_naked_pdata (char *data,int len)
6221  {
6222    int pnum=data[1]; 
6223    Assert (data[0]=PID_NAKED_PDATA);
6224
6225 //   mprintf ((0,"Processing a naked packet of %d length.\n",len));
6226
6227         if (pnum < 0) {
6228            mprintf ((0,"Naked packet is bad!\n"));
6229                 Int3(); // This packet is bogus!!
6230                 return;
6231         }
6232
6233         if (!multi_quit_game && (pnum >= N_players)) {
6234                 if (Network_status!=NETSTAT_WAITING)
6235                  {
6236                         Int3(); // We missed an important packet!
6237                         network_consistency_error();
6238                         return;
6239                  }
6240                 else
6241                  return;
6242         }
6243
6244         if (Endlevel_sequence || (Network_status == NETSTAT_ENDLEVEL) ) {
6245                 int old_Endlevel_sequence = Endlevel_sequence;
6246                 Endlevel_sequence = 1;
6247                 multi_process_bigdata( data+2, len-2);
6248                 Endlevel_sequence = old_Endlevel_sequence;
6249                 return;
6250         }
6251
6252         multi_process_bigdata( data+2, len-2 );
6253  }
6254
6255 int ConnectionPacketLevel[]={0,1,1,1};
6256 int ConnectionSecLevel[]={12,3,5,7};
6257
6258 int AppletalkConnectionPacketLevel[]={0,1,0};
6259 int AppletalkConnectionSecLevel[]={10,3,8};
6260
6261 #if defined(RELEASE) && !defined(MACINTOSH)             // use the code below for mac appletalk games
6262 int network_choose_connect ()
6263  {
6264   return (1);
6265  }
6266 #else
6267 int network_choose_connect ()
6268  {
6269 #if 0
6270         newmenu_item m[16];
6271         int choice,opt=0;
6272 #endif
6273
6274         if (Network_game_type == IPX_GAME) {  
6275                 #if 0
6276            m[opt].type = NM_TYPE_MENU;  m[opt].text = "Local Subnet"; opt++;
6277            m[opt].type = NM_TYPE_MENU;  m[opt].text = "14.4 modem over Internet"; opt++;
6278            m[opt].type = NM_TYPE_MENU;  m[opt].text = "28.8 modem over Internet"; opt++;
6279            m[opt].type = NM_TYPE_MENU;  m[opt].text = "ISDN or T1 over Internet"; opt++;
6280
6281            choice = newmenu_do1( NULL, "Choose connection type", opt, m, NULL, 0 );
6282
6283                 if (choice<0)
6284                  return (NULL);
6285
6286            Assert (choice>=0 && choice<=3);
6287    
6288                 Netgame.ShortPackets=ConnectionPacketLevel[choice];
6289                 Netgame.PacketsPerSec=ConnectionSecLevel[choice];
6290                 #endif
6291            return (1);
6292         #ifdef MACINTOSH
6293         } else {
6294            m[opt].type = NM_TYPE_MENU;  m[opt].text = "EtherTalk"; opt++;
6295            m[opt].type = NM_TYPE_MENU;  m[opt].text = "LocalTalk"; opt++;
6296            m[opt].type = NM_TYPE_MENU;  m[opt].text = "Other"; opt++;
6297         
6298            choice = newmenu_do1( NULL, "Choose connection type", opt, m, NULL, 0 );
6299
6300                 if (choice<0)
6301                  return (NULL);
6302
6303                 Network_appletalk_type = choice;
6304                 
6305                 Assert (choice>=0 && choice<=2);
6306    
6307                 Netgame.ShortPackets=AppletalkConnectionPacketLevel[choice];
6308                 Netgame.PacketsPerSec=AppletalkConnectionSecLevel[choice];
6309            return (1);
6310         #endif
6311         }
6312   return (0);   
6313  }
6314 #endif
6315
6316
6317
6318 #ifdef NETPROFILING
6319 void OpenSendLog ()
6320  {
6321   int i;
6322   SendLogFile=(FILE *)fopen ("sendlog.net","w");
6323   for (i=0;i<100;i++)
6324         TTSent[i]=0;
6325  }
6326 void OpenRecieveLog ()
6327  {
6328   int i;
6329   RecieveLogFile=(FILE *)fopen ("recvlog.net","w");
6330   for (i=0;i<100;i++)
6331         TTRecv[i]=0;
6332  }
6333 #endif
6334
6335 int GetMyNetRanking ()
6336  {
6337   int rank;
6338   int eff;
6339
6340   if (Netlife_kills+Netlife_killed==0)
6341          return (1);
6342  
6343   rank=(int) (((float)Netlife_kills/3000.0)*8.0);
6344  
6345   eff=(int)((float)((float)Netlife_kills/((float)Netlife_killed+(float)Netlife_kills))*100.0);
6346
6347   if (rank>8)
6348    rank=8;
6349   
6350   if (eff<0)
6351          eff=0;
6352  
6353   if (eff<60)
6354         rank-=((59-eff)/10);
6355         
6356   if (rank<0)
6357         rank=0;
6358   if (rank>8)
6359         rank=8;
6360  
6361   mprintf ((0,"Rank is %d (%s)\n",rank+1,RankStrings[rank+1]));
6362   return (rank+1);
6363  }
6364
6365 void ClipRank (signed char *rank)
6366  {
6367   // This function insures no crashes when dealing with D2 1.0
6368
6369  
6370   if (*rank<0 || *rank>9)
6371         *rank=0;
6372  }
6373 void network_check_for_old_version (char pnum)
6374  {  
6375   if (NetPlayers.players[(int)pnum].version_major==1 && (NetPlayers.players[(int)pnum].version_minor & 0x0F)==0)
6376         NetPlayers.players[(int)pnum].rank=0;
6377  }
6378
6379 void network_request_player_names (int n)
6380  {
6381   network_send_all_info_request (PID_GAME_PLAYERS,Active_games[n].Security);
6382   NamesInfoSecurity=Active_games[n].Security;
6383  }
6384
6385 extern char already_showing_info;
6386 extern int newmenu_dotiny2( char * title, char * subtitle, int nitems, newmenu_item * item, void (*subfunction)(int nitems,newmenu_item * items, int * last_key, int citem));
6387
6388 void network_process_names_return (char *data)
6389  {
6390         newmenu_item m[15];
6391    char mtext[15][50],temp[50];
6392         int i,t,l,gnum,num=0,count=5,numplayers;
6393    
6394    if (NamesInfoSecurity!=(*(int *)(data+1)))
6395          {
6396           mprintf ((0,"Bad security on names return!\n"));
6397           mprintf ((0,"NIS=%d data=%d\n",NamesInfoSecurity,(*(int *)(data+1))));
6398           return;
6399          }
6400
6401    numplayers=data[count]; count++;
6402
6403    if (numplayers==255)
6404          {
6405                  SurfingNet=0;  
6406                  NamesInfoSecurity=-1;
6407                  nm_messagebox(NULL, 1, "OK", "That game is refusing\nname requests.\n");
6408                  SurfingNet=1;
6409                  return;
6410          }
6411
6412    Assert (numplayers>0 && numplayers<MAX_NUM_NET_PLAYERS);
6413         
6414    for (i=0;i<12;i++)
6415         {
6416          m[i].text=(char *)&mtext[i];
6417     m[i].type=NM_TYPE_TEXT;             
6418         }
6419
6420    for (gnum=-1,i=0;i<num_active_games;i++)
6421          {
6422           if (NamesInfoSecurity==Active_games[i].Security)
6423                 {
6424                  gnum=i;
6425                  break;
6426                 }
6427          }
6428         
6429         if (gnum==-1)
6430     {
6431        SurfingNet=0;
6432                  NamesInfoSecurity=-1;
6433                  nm_messagebox(NULL, 1, "OK", "The game you have requested\nnames from is gone.\n");
6434                  SurfingNet=1;
6435                  return;
6436          }
6437  
6438    sprintf (mtext[num],"Players of game '%s':",Active_games[gnum].game_name); num++;
6439    for (i=0;i<numplayers;i++)
6440          {
6441           l=data[count++];
6442
6443      mprintf ((0,"%s\n",data+count));
6444
6445           for (t=0;t<CALLSIGN_LEN+1;t++)
6446                  temp[t]=data[count++];   
6447      if (FindArg("-norankings"))        
6448              sprintf (mtext[num],"%s",temp);
6449           else
6450              sprintf (mtext[num],"%s%s",RankStrings[l],temp);
6451         
6452           num++;        
6453          }
6454
6455         if (data[count]==99)
6456         {
6457          sprintf (mtext[num++]," ");
6458          sprintf (mtext[num++],"Short packets: %s",data[count+1]?"On":"Off");
6459          sprintf (mtext[num++],"Packets Per Second: %d",data[count+2]);
6460    }
6461
6462         already_showing_info=1; 
6463         newmenu_dotiny2( NULL, NULL, num, m, NULL);
6464         already_showing_info=0; 
6465  }
6466
6467 char NameReturning=1;
6468
6469 void network_send_player_names (sequence_packet *their)
6470  {
6471   int numconnected=0,count=0,i,t;
6472   char buf[80];
6473
6474   if (!their)
6475    {
6476     mprintf ((0,"Got a player name without a return address! Get Jason\n"));
6477          return;
6478         }
6479
6480    buf[0]=PID_NAMES_RETURN; count++;
6481    (*(int *)(buf+1))=Netgame.Security; count+=4;
6482
6483    if (!NameReturning)
6484          {
6485      buf[count]=255; count++; 
6486           goto sendit;
6487          }
6488  
6489    mprintf ((0,"RealSec=%d DS=%d\n",Netgame.Security,*(int *)(buf+1)));
6490   
6491    for (i=0;i<N_players;i++)
6492          if (Players[i].connected)
6493                 numconnected++;
6494
6495    buf[count]=numconnected; count++; 
6496    for (i=0;i<N_players;i++)
6497          if (Players[i].connected)
6498           {
6499                 buf[count++]=NetPlayers.players[i].rank; 
6500                 
6501                 for (t=0;t<CALLSIGN_LEN+1;t++)
6502                  {
6503                   buf[count]=NetPlayers.players[i].callsign[t];
6504                   count++;
6505                  }
6506           }
6507
6508    buf[count++]=99;
6509         buf[count++]=Netgame.ShortPackets;              
6510         buf[count++]=Netgame.PacketsPerSec;
6511   
6512    sendit:
6513                                 ;               // empty statement allows compilation on mac which does not have the
6514                                                 // statement below and kills the compiler when there is no
6515                                                 // statement following the label "sendit"
6516            
6517    #ifndef MACINTOSH
6518            ipx_send_internetwork_packet_data((ubyte *)buf, count, their->player.network.ipx.server, their->player.network.ipx.node);
6519         #endif
6520  }
6521  
6522
6523 extern int file_exists (char *);
6524
6525 int HoardEquipped ()
6526 {
6527         static int checked=-1;
6528         
6529         #ifdef WINDOWS
6530                 return 0;
6531         #endif
6532
6533         if (checked==-1)
6534         {
6535                 if (file_exists ("hoard.ham"))
6536                         checked=1;
6537                 else
6538                         checked=0;
6539         }
6540         return (checked);
6541 }