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