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