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