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