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