2a6b4bd468000da5fda52e19d75627c791bd5bda
[btb/d2x.git] / main / gameseq.c
1 /* $Id: gameseq.c,v 1.34 2004-05-15 16:25:35 schaffner Exp $ */
2 /*
3 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
4 SOFTWARE CORPORATION ("PARALLAX").  PARALLAX, IN DISTRIBUTING THE CODE TO
5 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
6 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
7 IN USING, DISPLAYING,  AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
8 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
9 FREE PURPOSES.  IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
10 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES.  THE END-USER UNDERSTANDS
11 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
12 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION.  ALL RIGHTS RESERVED.
13 */
14
15 /*
16  *
17  * Routines for EndGame, EndLevel, etc.
18  *
19  * Old Log:
20  * Revision 1.1  1995/12/05  16:02:05  allender
21  * Initial revision
22  *
23  * Revision 1.14  1995/11/03  12:55:30  allender
24  * shareware changes
25  *
26  * Revision 1.13  1995/10/31  10:23:07  allender
27  * shareware stuff
28  *
29  * Revision 1.12  1995/10/18  18:25:02  allender
30  * call auto_select_weapon after initing ammo since that may
31  * change the secondary weapon status
32  *
33  * Revision 1.11  1995/10/17  13:17:11  allender
34  * added closebox when entering pilot name
35  *
36  * Revision 1.10  1995/09/24  10:56:59  allender
37  * new players must be looked for in Players directory
38  *
39  * Revision 1.9  1995/09/18  08:08:08  allender
40  * remove netgame binding if at endgame
41  *
42  * Revision 1.8  1995/09/14  14:13:01  allender
43  * initplayerobject have void return
44  *
45  * Revision 1.7  1995/08/31  12:54:42  allender
46  * try and fix bug
47  *
48  * Revision 1.6  1995/08/26  16:25:40  allender
49  * put return values on needed functions
50  *
51  * Revision 1.5  1995/08/14  09:26:28  allender
52  * added byteswap header files
53  *
54  * Revision 1.4  1995/08/01  13:57:42  allender
55  * macified player file stuff -- players stored in seperate folder
56  *
57  * Revision 1.3  1995/06/08  12:54:37  allender
58  * new function for calculating a segment based checksum since the old way
59  * is byte order dependent
60  *
61  * Revision 1.2  1995/06/02  07:42:10  allender
62  * removed duplicate extern for network_endlevel_poll2
63  *
64  * Revision 1.1  1995/05/16  15:25:56  allender
65  * Initial revision
66  *
67  * Revision 2.10  1995/12/19  15:48:25  john
68  * Made screen reset when loading new level.
69  *
70  * Revision 2.9  1995/07/07  16:47:52  john
71  * Fixed bug with reactor time..
72  *
73  * Revision 2.8  1995/06/15  12:14:18  john
74  * Made end game, win game and title sequences all go
75  * on after 5 minutes automatically.
76  *
77  * Revision 2.7  1995/05/26  16:16:25  john
78  * Split SATURN into define's for requiring cd, using cd, etc.
79  * Also started adding all the Rockwell stuff.
80  *
81  * Revision 2.6  1995/03/24  13:11:20  john
82  * Added save game during briefing screens.
83  *
84  * Revision 2.5  1995/03/23  17:56:20  allender
85  * added code to record old laser level and weapons when player gets
86  * new ship
87  *
88  * Revision 2.4  1995/03/21  08:39:14  john
89  * Ifdef'd out the NETWORK code.
90  *
91  * Revision 2.3  1995/03/15  14:33:33  john
92  * Added code to force the Descent CD-rom in the drive.
93  *
94  * Revision 2.2  1995/03/06  16:47:26  mike
95  * destination saturn
96  *
97  * Revision 2.1  1995/03/06  15:23:23  john
98  * New screen techniques.
99  *
100  * Revision 2.0  1995/02/27  11:28:53  john
101  * New version 2.0, which has no anonymous unions, builds with
102  * Watcom 10.0, and doesn't require parsing BITMAPS.TBL.
103  *
104  * Revision 1.310  1995/02/14  10:48:09  mike
105  * zero bonus if you are a cheater.
106  *
107  * Revision 1.309  1995/02/11  19:17:08  rob
108  * Fixed bug in laser fire rate after demo playback.
109  *
110  * Revision 1.308  1995/02/11  14:34:08  rob
111  * Added include of netmisc.c
112  *
113  * Revision 1.307  1995/02/11  14:29:04  rob
114  * Fixes for invul. controlcen.
115  *
116  * Revision 1.306  1995/02/11  13:47:00  mike
117  * fix cheats.
118  *
119  * Revision 1.305  1995/02/11  13:10:52  rob
120  * Fixed end of anarchy mission problems.
121  *
122  * Revision 1.304  1995/02/11  12:46:12  mike
123  * initialize Robot_firing_enabled, part of AHIMSA cheat.
124  *
125  * Revision 1.303  1995/02/11  12:42:03  john
126  * Added new song method, with FM bank switching..
127  *
128  * Revision 1.302  1995/02/10  17:39:29  matt
129  * Changed secret exit message to be centered
130  *
131  * Revision 1.301  1995/02/10  16:17:33  mike
132  * init Last_level_path_shown.
133  *
134  * Revision 1.300  1995/02/09  22:18:22  john
135  * Took out between level saves.
136  *
137  * Revision 1.299  1995/02/09  12:11:42  rob
138  * Get rid of high scores thing for multiplayer games.
139  *
140  * Revision 1.298  1995/02/08  20:34:24  rob
141  * Took briefing screens back OUT of coop games (per Interplay request)
142  *
143  * Revision 1.297  1995/02/08  19:20:09  rob
144  * Moved checksum calc.
145  *
146  * Revision 1.296  1995/02/05  14:39:24  rob
147  * Changed object mapping to be more efficient.
148  *
149  * Revision 1.295  1995/02/02  19:05:38  john
150  * Made end level menu for 27 not overwrite descent title..
151  *
152  * Revision 1.294  1995/02/02  16:36:42  adam
153  * *** empty log message ***
154  *
155  * Revision 1.293  1995/02/02  15:58:02  john
156  * Added turbo mode cheat.
157  *
158  * Revision 1.292  1995/02/02  15:29:34  matt
159  * Changed & localized secret level text
160  *
161  * Revision 1.291  1995/02/02  10:50:03  adam
162  * messed with secret level message
163  *
164  * Revision 1.290  1995/02/02  01:20:28  adam
165  * changed endgame song temporarily.
166  *
167  * Revision 1.289  1995/02/01  23:19:43  rob
168  * Fixed up endlevel stuff for multiplayer.
169  * Put in palette fades around areas that didn't have them before.
170  *
171  * Revision 1.288  1995/02/01  17:12:34  mike
172  * Make score come after endgame screens.
173  *
174  * Revision 1.287  1995/01/30  18:34:30  rob
175  * Put briefing screens back into coop games.
176  *
177  * Revision 1.286  1995/01/27  13:07:59  rob
178  * Removed erroneous warning message.
179  *
180  * Revision 1.285  1995/01/27  11:47:43  rob
181  * Removed new secret level menu from multiplayer games.
182  *
183  * Revision 1.284  1995/01/26  22:11:11  mike
184  * Purple chromo-blaster (ie, fusion cannon) spruce up (chromification)
185  *
186  * Revision 1.283  1995/01/26  16:55:13  rob
187  * Removed ship bonus from cooperative endgame.
188  *
189  * Revision 1.282  1995/01/26  16:45:24  mike
190  * Add autofire fusion cannon stuff.
191  *
192  * Revision 1.281  1995/01/26  14:44:44  rob
193  * Removed unnecessary #ifdefs around mprintfs.
194  * Changed NumNetPlayerPositions to be independant of MaxNumNetPlayers to
195  * accomodate 4-player robo-archy games with 8 start positions.
196  *
197  * Revision 1.280  1995/01/26  12:19:01  rob
198  * Changed network_do_frame call.
199  *
200  * Revision 1.279  1995/01/26  00:35:03  matt
201  * Changed numbering convention for HMP files for levels
202  *
203  * Revision 1.278  1995/01/25  16:07:59  matt
204  * Added message (prototype) when going to secret level
205  *
206  * Revision 1.277  1995/01/22  18:57:23  matt
207  * Made player highest level work with missions
208  *
209  * Revision 1.276  1995/01/21  23:13:08  matt
210  * Made high scores with (not work, really) with loaded missions
211  * Don't give player high score when quit game
212  *
213  * Revision 1.275  1995/01/21  17:17:39  john
214  * *** empty log message ***
215  *
216  * Revision 1.274  1995/01/21  17:15:38  john
217  * Added include for state.h
218  *
219  * Revision 1.273  1995/01/21  16:21:14  matt
220  * Fixed bugs in secret level sequencing
221  *
222  * Revision 1.272  1995/01/20  22:47:29  matt
223  * Mission system implemented, though imcompletely
224  *
225  * Revision 1.271  1995/01/19  17:00:48  john
226  * Made save game work between levels.
227  *
228  * Revision 1.270  1995/01/17  17:49:10  rob
229  * Added key syncing for coop.
230  *
231  * Revision 1.269  1995/01/17  14:27:37  john
232  * y
233  *
234  * Revision 1.268  1995/01/17  13:36:33  john
235  * Moved pig loading into StartNewLevelSub.
236  *
237  * Revision 1.267  1995/01/16  16:53:55  john
238  * Added code to save cheat state during save game.
239  *
240  * Revision 1.266  1995/01/15  19:42:10  matt
241  * Ripped out hostage faces for registered version
242  *
243  * Revision 1.265  1995/01/15  16:55:06  john
244  * Improved mine texture parsing.
245  *
246  * Revision 1.264  1995/01/15  11:56:24  john
247  * Working version of paging.
248  *
249  * Revision 1.263  1995/01/14  19:16:40  john
250  * First version of new bitmap paging code.
251  *
252  * Revision 1.262  1995/01/13  17:38:58  yuan
253  * Removed Int3() for number players check.
254  *
255  * Revision 1.261  1995/01/12  12:09:52  yuan
256  * Added coop object capability.
257  *
258  * Revision 1.260  1995/01/05  17:16:08  yuan
259  * Removed Int3s.
260  *
261  * Revision 1.259  1995/01/05  11:34:29  john
262  * Took out endlevel save stuff for registered.
263  *
264  * Revision 1.258  1995/01/04  19:00:16  rob
265  * Added some debugging for two bugs.
266  *
267  * Revision 1.257  1995/01/04  13:18:18  john
268  * Added cool 6 game save.
269  *
270  * Revision 1.256  1995/01/04  08:46:18  rob
271  * JOHN CHECKED IN FOR ROB !!!
272  *
273  * Revision 1.255  1995/01/02  20:07:35  rob
274  * Added score syncing.
275  * Get rid of endlevel score for coop games (put it back in elsewhere)
276  *
277  * Revision 1.254  1995/01/02  16:17:43  mike
278  * init super boss.
279  *
280  * Revision 1.253  1994/12/21  21:08:47  rob
281  * fixed a bug in coop player ship positions.
282  *
283  * Revision 1.252  1994/12/21  12:57:08  rob
284  * Handle additional player ships in mines.
285  *
286  *
287  */
288
289
290 #ifdef HAVE_CONFIG_H
291 #include <conf.h>
292 #endif
293
294 #ifdef RCS
295 char gameseq_rcsid[] = "$Id: gameseq.c,v 1.34 2004-05-15 16:25:35 schaffner Exp $";
296 #endif
297
298 #ifdef WINDOWS
299 #include "desw.h"
300 #endif
301
302
303 #include <stdio.h>
304 #include <stdlib.h>
305 #include <string.h>
306 #ifndef _MSC_VER
307 #include <unistd.h>
308 #endif
309 #include <time.h>
310
311 #ifdef OGL
312 #include "ogl_init.h"
313 #endif
314
315 #include "pa_enabl.h"                   //$$POLY_ACC
316 #include "inferno.h"
317 #include "game.h"
318 #include "player.h"
319 #include "key.h"
320 #include "object.h"
321 #include "physics.h"
322 #include "error.h"
323 #include "joy.h"
324 #include "mono.h"
325 #include "iff.h"
326 #include "pcx.h"
327 #include "timer.h"
328 #include "render.h"
329 #include "laser.h"
330 #include "screens.h"
331 #include "textures.h"
332 #include "slew.h"
333 #include "gauges.h"
334 #include "texmap.h"
335 #include "3d.h"
336 #include "effects.h"
337 #include "menu.h"
338 #include "gameseg.h"
339 #include "wall.h"
340 #include "ai.h"
341 #include "fuelcen.h"
342 #include "switch.h"
343 #include "digi.h"
344 #include "gamesave.h"
345 #include "scores.h"
346 #include "ibitblt.h"
347 #include "u_mem.h"
348 #include "palette.h"
349 #include "morph.h"
350 #include "lighting.h"
351 #include "newdemo.h"
352 #include "titles.h"
353 #include "collide.h"
354 #include "weapon.h"
355 #include "sounds.h"
356 #include "args.h"
357 #include "gameseq.h"
358 #include "gamefont.h"
359 #include "newmenu.h"
360 #include "endlevel.h"
361 #ifdef NETWORK
362 #  include "multi.h"
363 #  include "network.h"
364 #  include "netmisc.h"
365 #  include "modem.h"
366 #endif
367 #include "playsave.h"
368 #include "ctype.h"
369 #include "fireball.h"
370 #include "kconfig.h"
371 #include "config.h"
372 #include "robot.h"
373 #include "automap.h"
374 #include "cntrlcen.h"
375 #include "powerup.h"
376 #include "text.h"
377 #include "cfile.h"
378 #include "piggy.h"
379 #include "texmerge.h"
380 #include "paging.h"
381 #include "mission.h"
382 #include "state.h"
383 #include "songs.h"
384 #include "gamepal.h"
385 #include "movie.h"
386 #include "controls.h"
387 #include "credits.h"
388 #include "gamemine.h"
389
390 #if defined(POLY_ACC)
391 #include "poly_acc.h"
392 #endif
393 #if defined (TACTILE)
394  #include "tactile.h"
395 #endif
396
397 #ifdef EDITOR
398 #include "editor/editor.h"
399 #endif
400
401 #include "strutil.h"
402 #include "rle.h"
403
404 void StartNewLevelSecret(int level_num, int page_in_textures);
405 void InitPlayerPosition(int random_flag);
406 void load_stars();
407 void returning_to_level_message(void);
408 void advancing_to_level_message(void);
409 void DoEndGame(void);
410 void AdvanceLevel(int secret_flag);
411 void filter_objects_from_level();
412
413 // From allender -- you'll find these defines in state.c and cntrlcen.c
414 // since I couldn't think of a good place to put them and i wanted to
415 // fix this stuff fast!  Sorry about that...
416
417 #ifndef MACINTOSH
418 #define SECRETB_FILENAME        "secret.sgb"
419 #define SECRETC_FILENAME        "secret.sgc"
420 #else
421 #define SECRETB_FILENAME        ":Players:secret.sgb"
422 #define SECRETC_FILENAME        ":Players:secret.sgc"
423 #endif
424
425 //Current_level_num starts at 1 for the first level
426 //-1,-2,-3 are secret levels
427 //0 means not a real level loaded
428 int     Current_level_num=0,Next_level_num;
429 char    Current_level_name[LEVEL_NAME_LEN];
430
431 int Last_level, Last_secret_level;
432
433 // Global variables describing the player
434 int                             N_players=1;                                            // Number of players ( >1 means a net game, eh?)
435 int                             Player_num=0;                                           // The player number who is on the console.
436 player                  Players[MAX_PLAYERS+4];                   // Misc player info
437 obj_position    Player_init[MAX_PLAYERS];
438
439 // Global variables telling what sort of game we have
440 int MaxNumNetPlayers = -1;
441 int NumNetPlayerPositions = -1;
442
443 extern fix ThisLevelTime;
444
445 // Extern from game.c to fix a bug in the cockpit!
446
447 extern int last_drawn_cockpit[2];
448 extern int Last_level_path_created;
449
450 //      HUD_clear_messages external, declared in gauges.h
451 #ifndef _GAUGES_H
452 extern void HUD_clear_messages(); // From hud.c
453 #endif
454
455 //      Extra prototypes declared for the sake of LINT
456 void init_player_stats_new_ship(void);
457 void copy_defaults_to_robot_all(void);
458
459 int     Do_appearance_effect=0;
460
461 extern int Rear_view;
462
463 int     First_secret_visit = 1;
464
465 extern int descent_critical_error;
466
467 extern int Last_msg_ycrd;
468
469 //--------------------------------------------------------------------
470 void verify_console_object()
471 {
472         Assert( Player_num > -1 );
473         Assert( Players[Player_num].objnum > -1 );
474         ConsoleObject = &Objects[Players[Player_num].objnum];
475         Assert( ConsoleObject->type==OBJ_PLAYER );
476         Assert( ConsoleObject->id==Player_num );
477 }
478
479 int count_number_of_robots()
480 {
481         int robot_count;
482         int i;
483
484         robot_count = 0;
485         for (i=0;i<=Highest_object_index;i++) {
486                 if (Objects[i].type == OBJ_ROBOT)
487                         robot_count++;
488         }
489
490         return robot_count;
491 }
492
493
494 int count_number_of_hostages()
495 {
496         int count;
497         int i;
498
499         count = 0;
500         for (i=0;i<=Highest_object_index;i++) {
501                 if (Objects[i].type == OBJ_HOSTAGE)
502                         count++;
503         }
504
505         return count;
506 }
507
508 //added 10/12/95: delete buddy bot if coop game.  Probably doesn't really belong here. -MT
509 void
510 gameseq_init_network_players()
511 {
512         int i,k,j;
513
514         // Initialize network player start locations and object numbers
515
516         ConsoleObject = &Objects[0];
517         k = 0;
518         j = 0;
519         for (i=0;i<=Highest_object_index;i++) {
520
521                 if (( Objects[i].type==OBJ_PLAYER )     || (Objects[i].type == OBJ_GHOST) || (Objects[i].type == OBJ_COOP))
522                 {
523                         if ( (!(Game_mode & GM_MULTI_COOP) && ((Objects[i].type == OBJ_PLAYER)||(Objects[i].type==OBJ_GHOST))) ||
524                    ((Game_mode & GM_MULTI_COOP) && ((j == 0) || ( Objects[i].type==OBJ_COOP ))) )
525                         {
526                                 // -- mprintf((0, "Created Cooperative multiplayer object\n"));
527                                 Objects[i].type=OBJ_PLAYER;
528                                 // -- mprintf((0, "Player init %d is ship %d.\n", k, j));
529                                 Player_init[k].pos = Objects[i].pos;
530                                 Player_init[k].orient = Objects[i].orient;
531                                 Player_init[k].segnum = Objects[i].segnum;
532                                 Players[k].objnum = i;
533                                 Objects[i].id = k;
534                                 k++;
535                         }
536                         else
537                                 obj_delete(i);
538                         j++;
539                 }
540
541                 if ((Objects[i].type==OBJ_ROBOT) && (Robot_info[Objects[i].id].companion) && (Game_mode & GM_MULTI))
542                         obj_delete(i);          //kill the buddy in netgames
543
544         }
545         NumNetPlayerPositions = k;
546
547 #ifndef NDEBUG
548         if ( ((Game_mode & GM_MULTI_COOP) && (NumNetPlayerPositions != 4)) ||
549                   (!(Game_mode & GM_MULTI_COOP) && (NumNetPlayerPositions != 8)) )
550         {
551                 mprintf((1, "--NOT ENOUGH MULTIPLAYER POSITIONS IN THIS MINE!--\n"));
552                 //Int3(); // Not enough positions!!
553         }
554 #endif
555 #ifdef NETWORK
556         if (is_D2_OEM && (Game_mode & GM_MULTI) && Current_mission_num == Builtin_mission_num && Current_level_num==8)
557          {
558           for (i=0;i<N_players;i++)
559                  if (Players[i].connected && !(NetPlayers.players[i].version_minor & 0xF0))
560                         {
561                nm_messagebox ("Warning!",1,TXT_OK,"This special version of Descent II\nwill disconnect after this level.\nPlease purchase the full version\nto experience all the levels!");    
562                          return;
563                         }
564          }
565
566         if (is_MAC_SHARE && (Game_mode & GM_MULTI) && Current_mission_num == Builtin_mission_num && Current_level_num == 4)
567         {
568                 for (i = 0; i < N_players; i++)
569                         if (Players[i].connected && !(NetPlayers.players[i].version_minor & 0xF0))
570                         {
571                                 nm_messagebox ("Warning!", 1 ,TXT_OK, "This shareware version of Descent II\nwill disconnect after this level.\nPlease purchase the full version\nto experience all the levels!");
572                                 return;
573                         }
574         }
575 #endif // NETWORK
576 }
577
578 void gameseq_remove_unused_players()
579 {
580         int i;
581
582         // 'Remove' the unused players
583
584 #ifdef NETWORK
585         if (Game_mode & GM_MULTI)
586         {
587                 for (i=0; i < NumNetPlayerPositions; i++)
588                 {
589                         if ((!Players[i].connected) || (i >= N_players))
590                         {
591                                 #ifndef NDEBUG
592 //                              mprintf((0, "Ghosting player ship %d.\n", i+1));
593                                 #endif
594                                 multi_make_player_ghost(i);
595                         }
596                 }
597         }
598         else
599 #endif
600         {               // Note link to above if!!!
601                 #ifndef NDEBUG
602                 // -- mprintf((0, "Removing player objects numbered %d-%d.\n", 1, NumNetPlayerPositions));
603                 #endif
604                 for (i=1; i < NumNetPlayerPositions; i++)
605                 {
606                         obj_delete(Players[i].objnum);
607                 }
608         }
609 }
610
611 fix StartingShields=INITIAL_SHIELDS;
612
613 // Setup player for new game
614 void init_player_stats_game()
615 {
616         Players[Player_num].score = 0;
617         Players[Player_num].last_score = 0;
618         Players[Player_num].lives = INITIAL_LIVES;
619         Players[Player_num].level = 1;
620
621         Players[Player_num].time_level = 0;
622         Players[Player_num].time_total = 0;
623         Players[Player_num].hours_level = 0;
624         Players[Player_num].hours_total = 0;
625
626         Players[Player_num].energy = INITIAL_ENERGY;
627         Players[Player_num].shields = StartingShields;
628         Players[Player_num].killer_objnum = -1;
629
630         Players[Player_num].net_killed_total = 0;
631         Players[Player_num].net_kills_total = 0;
632
633         Players[Player_num].num_kills_level = 0;
634         Players[Player_num].num_kills_total = 0;
635         Players[Player_num].num_robots_level = 0;
636         Players[Player_num].num_robots_total = 0;
637         Players[Player_num].KillGoalCount = 0;
638         
639         Players[Player_num].hostages_rescued_total = 0;
640         Players[Player_num].hostages_level = 0;
641         Players[Player_num].hostages_total = 0;
642
643         Players[Player_num].laser_level = 0;
644         Players[Player_num].flags = 0;
645
646         init_player_stats_new_ship();
647
648         First_secret_visit = 1;
649 }
650
651 void init_ammo_and_energy(void)
652 {
653         if (Players[Player_num].energy < INITIAL_ENERGY)
654                 Players[Player_num].energy = INITIAL_ENERGY;
655         if (Players[Player_num].shields < StartingShields)
656                 Players[Player_num].shields = StartingShields;
657
658 //      for (i=0; i<MAX_PRIMARY_WEAPONS; i++)
659 //              if (Players[Player_num].primary_ammo[i] < Default_primary_ammo_level[i])
660 //                      Players[Player_num].primary_ammo[i] = Default_primary_ammo_level[i];
661
662 //      for (i=0; i<MAX_SECONDARY_WEAPONS; i++)
663 //              if (Players[Player_num].secondary_ammo[i] < Default_secondary_ammo_level[i])
664 //                      Players[Player_num].secondary_ammo[i] = Default_secondary_ammo_level[i];
665         if (Players[Player_num].secondary_ammo[0] < 2 + NDL - Difficulty_level)
666                 Players[Player_num].secondary_ammo[0] = 2 + NDL - Difficulty_level;
667 }
668
669 extern  ubyte   Last_afterburner_state;
670
671 // Setup player for new level (After completion of previous level)
672 void init_player_stats_level(int secret_flag)
673 {
674         // int  i;
675
676         Players[Player_num].last_score = Players[Player_num].score;
677
678         Players[Player_num].level = Current_level_num;
679
680 #ifdef NETWORK
681         if (!Network_rejoined) {
682 #endif
683                 Players[Player_num].time_level = 0;
684                 Players[Player_num].hours_level = 0;
685 #ifdef NETWORK
686         }
687 #endif
688
689         Players[Player_num].killer_objnum = -1;
690
691         Players[Player_num].num_kills_level = 0;
692         Players[Player_num].num_robots_level = count_number_of_robots();
693         Players[Player_num].num_robots_total += Players[Player_num].num_robots_level;
694
695         Players[Player_num].hostages_level = count_number_of_hostages();
696         Players[Player_num].hostages_total += Players[Player_num].hostages_level;
697         Players[Player_num].hostages_on_board = 0;
698
699         if (!secret_flag) {
700                 init_ammo_and_energy();
701
702                 Players[Player_num].flags &= (~KEY_BLUE);
703                 Players[Player_num].flags &= (~KEY_RED);
704                 Players[Player_num].flags &= (~KEY_GOLD);
705
706                 Players[Player_num].flags &=   ~(PLAYER_FLAGS_INVULNERABLE |
707                                                                                                         PLAYER_FLAGS_CLOAKED |
708                                                                                                         PLAYER_FLAGS_MAP_ALL);
709
710                 Players[Player_num].cloak_time = 0;
711                 Players[Player_num].invulnerable_time = 0;
712
713                 if ((Game_mode & GM_MULTI) && !(Game_mode & GM_MULTI_COOP))
714                         Players[Player_num].flags |= (KEY_BLUE | KEY_RED | KEY_GOLD);
715         }
716
717         Player_is_dead = 0; // Added by RH
718         Players[Player_num].homing_object_dist = -F1_0; // Added by RH
719
720         Last_laser_fired_time = Next_laser_fire_time = GameTime; // added by RH, solved demo playback bug
721
722         Controls.afterburner_state = 0;
723         Last_afterburner_state = 0;
724
725         digi_kill_sound_linked_to_object(Players[Player_num].objnum);
726
727         init_gauges();
728
729    #ifdef TACTILE
730                 if (TactileStick)
731                   tactile_set_button_jolt();
732         #endif
733
734         Missile_viewer = NULL;
735 }
736
737 extern  void init_ai_for_ship(void);
738
739 // Setup player for a brand-new ship
740 void init_player_stats_new_ship()
741 {
742         int     i;
743
744         if (Newdemo_state == ND_STATE_RECORDING) {
745                 newdemo_record_laser_level(Players[Player_num].laser_level, 0);
746                 newdemo_record_player_weapon(0, 0);
747                 newdemo_record_player_weapon(1, 0);
748         }
749
750         Players[Player_num].energy = INITIAL_ENERGY;
751         Players[Player_num].shields = StartingShields;
752         Players[Player_num].laser_level = 0;
753         Players[Player_num].killer_objnum = -1;
754         Players[Player_num].hostages_on_board = 0;
755
756         Afterburner_charge = 0;
757
758         for (i=0; i<MAX_PRIMARY_WEAPONS; i++) {
759                 Players[Player_num].primary_ammo[i] = 0;
760                 Primary_last_was_super[i] = 0;
761         }
762
763         for (i=1; i<MAX_SECONDARY_WEAPONS; i++) {
764                 Players[Player_num].secondary_ammo[i] = 0;
765                 Secondary_last_was_super[i] = 0;
766         }
767         Players[Player_num].secondary_ammo[0] = 2 + NDL - Difficulty_level;
768
769         Players[Player_num].primary_weapon_flags = HAS_LASER_FLAG;
770         Players[Player_num].secondary_weapon_flags = HAS_CONCUSSION_FLAG;
771
772         Primary_weapon = 0;
773         Secondary_weapon = 0;
774
775         Players[Player_num].flags &= ~( PLAYER_FLAGS_QUAD_LASERS |
776                                                                                                 PLAYER_FLAGS_AFTERBURNER |
777                                                                                                 PLAYER_FLAGS_CLOAKED |
778                                                                                                 PLAYER_FLAGS_INVULNERABLE |
779                                                                                                 PLAYER_FLAGS_MAP_ALL |
780                                                                                                 PLAYER_FLAGS_CONVERTER |
781                                                                                                 PLAYER_FLAGS_AMMO_RACK |
782                                                                                                 PLAYER_FLAGS_HEADLIGHT |
783                                                                                                 PLAYER_FLAGS_HEADLIGHT_ON |
784                                                                                                 PLAYER_FLAGS_FLAG);
785
786         Players[Player_num].cloak_time = 0;
787         Players[Player_num].invulnerable_time = 0;
788
789         Player_is_dead = 0;             //player no longer dead
790
791         Players[Player_num].homing_object_dist = -F1_0; // Added by RH
792
793         Controls.afterburner_state = 0;
794         Last_afterburner_state = 0;
795
796         digi_kill_sound_linked_to_object(Players[Player_num].objnum);
797
798         Missile_viewer=NULL;            ///reset missile camera if out there
799
800    #ifdef TACTILE
801                 if (TactileStick)
802                  {
803                   tactile_set_button_jolt();
804                  }
805         #endif
806
807
808         init_ai_for_ship();
809 }
810
811 extern void init_stuck_objects(void);
812
813 #ifdef EDITOR
814
815 extern int Slide_segs_computed;
816
817 //reset stuff so game is semi-normal when playing from editor
818 void editor_reset_stuff_on_level()
819 {
820         gameseq_init_network_players();
821         init_player_stats_level(0);
822         Viewer = ConsoleObject;
823         ConsoleObject = Viewer = &Objects[Players[Player_num].objnum];
824         ConsoleObject->id=Player_num;
825         ConsoleObject->control_type = CT_FLYING;
826         ConsoleObject->movement_type = MT_PHYSICS;
827         Game_suspended = 0;
828         verify_console_object();
829         Control_center_destroyed = 0;
830         if (Newdemo_state != ND_STATE_PLAYBACK)
831                 gameseq_remove_unused_players();
832         init_cockpit();
833         init_robots_for_level();
834         init_ai_objects();
835         init_morphs();
836         init_all_matcens();
837         init_player_stats_new_ship();
838         init_controlcen_for_level();
839         automap_clear_visited();
840         init_stuck_objects();
841         init_thief_for_level();
842
843         Slide_segs_computed = 0;
844 }
845 #endif
846
847 //do whatever needs to be done when a player dies in multiplayer
848
849 void DoGameOver()
850 {
851 //      nm_messagebox( TXT_GAME_OVER, 1, TXT_OK, "" );
852
853         if (Current_mission_num == Builtin_mission_num)
854                 scores_maybe_add_player(0);
855
856         Function_mode = FMODE_MENU;
857         Game_mode = GM_GAME_OVER;
858         longjmp( LeaveGame, 0 );                // Exit out of game loop
859
860 }
861
862 extern void do_save_game_menu();
863
864 //update various information about the player
865 void update_player_stats()
866 {
867                 Players[Player_num].time_level += FrameTime;    //the never-ending march of time...
868                 if ( Players[Player_num].time_level > i2f(3600) )       {
869                         Players[Player_num].time_level -= i2f(3600);
870                         Players[Player_num].hours_level++;
871                 }
872
873                 Players[Player_num].time_total += FrameTime;    //the never-ending march of time...
874                 if ( Players[Player_num].time_total > i2f(3600) )       {
875                         Players[Player_num].time_total -= i2f(3600);
876                         Players[Player_num].hours_total++;
877                 }
878 }
879
880 //hack to not start object when loading level
881 extern int Dont_start_sound_objects;
882
883 //go through this level and start any eclip sounds
884 void set_sound_sources()
885 {
886         int segnum,sidenum;
887         segment *seg;
888
889         digi_init_sounds();             //clear old sounds
890
891         Dont_start_sound_objects = 1;
892
893         for (seg=&Segments[0],segnum=0;segnum<=Highest_segment_index;seg++,segnum++)
894                 for (sidenum=0;sidenum<MAX_SIDES_PER_SEGMENT;sidenum++) {
895                         int tm,ec,sn;
896
897                         if (WALL_IS_DOORWAY(seg,sidenum) & WID_RENDER_FLAG)
898                                 if ((((tm=seg->sides[sidenum].tmap_num2) != 0) && ((ec=TmapInfo[tm&0x3fff].eclip_num)!=-1)) || ((ec=TmapInfo[seg->sides[sidenum].tmap_num].eclip_num)!=-1))
899                                         if ((sn=Effects[ec].sound_num)!=-1) {
900                                                 vms_vector pnt;
901                                                 int csegnum = seg->children[sidenum];
902
903                                                 //check for sound on other side of wall.  Don't add on
904                                                 //both walls if sound travels through wall.  If sound
905                                                 //does travel through wall, add sound for lower-numbered
906                                                 //segment.
907
908                                                 if (IS_CHILD(csegnum) && csegnum < segnum) {
909                                                         if (WALL_IS_DOORWAY(seg, sidenum) & (WID_FLY_FLAG+WID_RENDPAST_FLAG)) {
910                                                                 segment *csegp;
911                                                                 int csidenum;
912
913                                                                 csegp = &Segments[seg->children[sidenum]];
914                                                                 csidenum = find_connect_side(seg, csegp);
915
916                                                                 if (csegp->sides[csidenum].tmap_num2 == seg->sides[sidenum].tmap_num2)
917                                                                         continue;               //skip this one
918                                                         }
919                                                 }
920
921                                                 compute_center_point_on_side(&pnt,seg,sidenum);
922                                                 digi_link_sound_to_pos(sn,segnum,sidenum,&pnt,1, F1_0/2);
923                                         }
924                 }
925
926         Dont_start_sound_objects = 0;
927
928 }
929
930
931 //fix flash_dist=i2f(1);
932 fix flash_dist=fl2f(.9);
933
934 //create flash for player appearance
935 void create_player_appearance_effect(object *player_obj)
936 {
937         vms_vector pos;
938         object *effect_obj;
939
940 #ifndef NDEBUG
941         {
942                 int objnum = player_obj-Objects;
943                 if ( (objnum < 0) || (objnum > Highest_object_index) )
944                         Int3(); // See Rob, trying to track down weird network bug
945         }
946 #endif
947
948         if (player_obj == Viewer)
949                 vm_vec_scale_add(&pos, &player_obj->pos, &player_obj->orient.fvec, fixmul(player_obj->size,flash_dist));
950         else
951                 pos = player_obj->pos;
952
953         effect_obj = object_create_explosion(player_obj->segnum, &pos, player_obj->size, VCLIP_PLAYER_APPEARANCE );
954
955         if (effect_obj) {
956                 effect_obj->orient = player_obj->orient;
957
958                 if ( Vclip[VCLIP_PLAYER_APPEARANCE].sound_num > -1 )
959                         digi_link_sound_to_object( Vclip[VCLIP_PLAYER_APPEARANCE].sound_num, effect_obj-Objects, 0, F1_0);
960         }
961 }
962
963 //
964 // New Game sequencing functions
965 //
966
967 //pairs of chars describing ranges
968 char playername_allowed_chars[] = "azAZ09__--";
969
970 int MakeNewPlayerFile(int allow_abort)
971 {
972         int x;
973         char filename[14];
974         newmenu_item m;
975         char text[CALLSIGN_LEN+1]="";
976 #if 0
977         FILE *fp;
978 #endif
979
980         strncpy(text, Players[Player_num].callsign,CALLSIGN_LEN);
981
982 try_again:
983         m.type=NM_TYPE_INPUT; m.text_len = 8; m.text = text;
984
985         Newmenu_allowed_chars = playername_allowed_chars;
986         x = newmenu_do( NULL, TXT_ENTER_PILOT_NAME, 1, &m, NULL );
987         Newmenu_allowed_chars = NULL;
988
989         if ( x < 0 ) {
990                 if ( allow_abort ) return 0;
991                 goto try_again;
992         }
993
994         if (text[0]==0) //null string
995                 goto try_again;
996         sprintf( filename, "%s.plr", text );
997
998 #if 0
999         fp = fopen( filename, "rb" );
1000
1001 #ifndef MACINTOSH
1002         //if the callsign is the name of a tty device, prepend a char
1003         if (fp && isatty(fileno(fp))) {
1004                 fclose(fp);
1005                 sprintf(filename,"$%.7s.plr",text);
1006                 fp = fopen(filename,"rb");
1007         }
1008 #endif
1009         
1010         if ( fp )       {
1011                 nm_messagebox(NULL, 1, TXT_OK, "%s '%s' %s", TXT_PLAYER, text, TXT_ALREADY_EXISTS );
1012                 fclose(fp);
1013                 goto try_again;
1014         }
1015 #else
1016         if (cfexist(filename))
1017         {
1018                 nm_messagebox(NULL, 1, TXT_OK, "%s '%s' %s", TXT_PLAYER, text, TXT_ALREADY_EXISTS );
1019                 goto try_again;
1020         }
1021 #endif
1022
1023         if ( !new_player_config() )
1024                 goto try_again;                 // They hit Esc during New player config
1025
1026         strncpy(Players[Player_num].callsign, text, CALLSIGN_LEN);
1027
1028         write_player_file();
1029
1030         return 1;
1031 }
1032
1033 #ifdef WINDOWS
1034 #undef TXT_SELECT_PILOT
1035 #define TXT_SELECT_PILOT "Select pilot\n<Ctrl-D> or Right-click\nto delete"
1036 #endif
1037
1038 //Inputs the player's name, without putting up the background screen
1039 int RegisterPlayer()
1040 {
1041         int i,j;
1042         char filename[14];
1043         int allow_abort_flag = 1;
1044
1045         if ( Players[Player_num].callsign[0] == 0 )     {
1046                 //---------------------------------------------------------------------
1047                 // Set default config options in case there is no config file
1048                 // kc_keyboard, kc_joystick, kc_mouse are statically defined.
1049                 Config_joystick_sensitivity = 8;
1050                 Config_control_type =CONTROL_NONE;
1051                 for (i=0; i<CONTROL_MAX_TYPES; i++ )
1052                         for (j=0; j<MAX_CONTROLS; j++ )
1053                                 kconfig_settings[i][j] = default_kconfig_settings[i][j];
1054                 kc_set_controls();
1055                 //----------------------------------------------------------------
1056
1057                 // Read the last player's name from config file, not lastplr.txt
1058                 strncpy( Players[Player_num].callsign, config_last_player, CALLSIGN_LEN );
1059
1060                 if (config_last_player[0]==0)
1061                         allow_abort_flag = 0;
1062         }
1063
1064 do_menu_again:
1065         ;
1066
1067 #ifndef MACINTOSH
1068         if (!newmenu_get_filename( TXT_SELECT_PILOT, "*.plr", filename, allow_abort_flag ))     {
1069                 goto do_menu_again; //return 0;         // They hit Esc in file selector
1070         }
1071 #else
1072         #ifndef APPLE_DEMO
1073         if (!newmenu_get_filename( TXT_SELECT_PILOT, ".\\Players\\*.plr", filename, allow_abort_flag )) {
1074                 goto do_menu_again;             // They hit Esc in file selector
1075         }
1076         #else
1077         newmenu_get_filename( "Select Pilot", ".\\Players\\*.plr", filename, 0 );               // no abort allowed ever -- and change title of menubox
1078         #endif
1079 #endif
1080
1081         if ( filename[0] == '<' )       {
1082                 // They selected 'create new pilot'
1083                 if (!MakeNewPlayerFile(allow_abort_flag))
1084                         //return 0;             // They hit Esc during enter name stage
1085                         goto do_menu_again;
1086         } else {
1087                 strncpy(Players[Player_num].callsign,filename, CALLSIGN_LEN);
1088         }
1089
1090         if (read_player_file() != EZERO)
1091                 goto do_menu_again;
1092
1093         Auto_leveling_on = Default_leveling_on;
1094
1095         set_display_mode(Default_display_mode);
1096
1097         WriteConfigFile();              // Update lastplr
1098
1099         return 1;
1100 }
1101
1102
1103 void load_robot_replacements(char *level_name);
1104 int read_hamfile();
1105 extern int Robot_replacements_loaded;
1106
1107 //load a level off disk. level numbers start at 1.  Secret levels are -1,-2,-3
1108 void LoadLevel(int level_num,int page_in_textures)
1109 {
1110         char *level_name;
1111         player save_player;
1112         int load_ret;
1113
1114         save_player = Players[Player_num];      
1115
1116         Assert(level_num <= Last_level  && level_num >= Last_secret_level  && level_num != 0);
1117
1118         if (level_num<0)                //secret level
1119                 level_name = Secret_level_names[-level_num-1];
1120         else                                    //normal level
1121                 level_name = Level_names[level_num-1];
1122
1123         #ifdef WINDOWS
1124                 dd_gr_set_current_canvas(NULL);
1125                 dd_gr_clear_canvas(BM_XRGB(0,0,0));
1126         #else
1127                 gr_set_current_canvas(NULL);
1128                 gr_clear_canvas(BM_XRGB(0, 0, 0));              //so palette switching is less obvious
1129         #endif
1130
1131         Last_msg_ycrd = -1;             //so we don't restore backgound under msg
1132
1133 //      WIN(LoadCursorWin(MOUSE_WAIT_CURSOR));
1134 //      WIN(ShowCursorW());
1135
1136 #if 1 //defined(POLY_ACC) || defined(OGL)
1137     gr_palette_load(gr_palette);
1138     show_boxed_message(TXT_LOADING);
1139 #else
1140         show_boxed_message(TXT_LOADING);
1141         gr_palette_load(gr_palette);
1142 #endif
1143
1144         load_ret = load_level(level_name);              //actually load the data from disk!
1145
1146         if (load_ret)
1147                 Error("Couldn't load level file <%s>, error = %d",level_name,load_ret);
1148
1149         Current_level_num=level_num;
1150
1151 //      load_palette_pig(Current_level_palette);                //load just the pig
1152
1153         load_palette(Current_level_palette,1,1);                //don't change screen
1154
1155         load_endlevel_data(level_num);
1156
1157         if ( page_in_textures )
1158                 piggy_load_level_data();
1159
1160         if (Mission_list[Current_mission_num].descent_version == 1)
1161                 load_d1_bitmap_replacements();
1162         else
1163                 load_bitmap_replacements(level_name);
1164
1165         if (Robot_replacements_loaded) {
1166                 read_hamfile();         //load original data
1167                 Robot_replacements_loaded = 0;
1168         }
1169         load_robot_replacements(level_name);
1170
1171 #ifdef NETWORK
1172         my_segments_checksum = netmisc_calc_checksum(Segments, sizeof(segment)*(Highest_segment_index+1));
1173
1174         reset_network_objects();
1175 #endif
1176
1177         Players[Player_num] = save_player;
1178
1179         set_sound_sources();
1180
1181         songs_play_level_song( Current_level_num );
1182
1183         clear_boxed_message();          //remove message before new palette loaded
1184
1185         gr_palette_load(gr_palette);            //actually load the palette
1186
1187 //      WIN(HideCursorW());
1188 }
1189
1190 //sets up Player_num & ConsoleObject
1191 void InitPlayerObject()
1192 {
1193         Assert(Player_num>=0 && Player_num<MAX_PLAYERS);
1194
1195         if (Player_num != 0 )   {
1196                 Players[0] = Players[Player_num];
1197                 Player_num = 0;
1198         }
1199
1200         Players[Player_num].objnum = 0;
1201
1202         ConsoleObject = &Objects[Players[Player_num].objnum];
1203
1204         ConsoleObject->type                             = OBJ_PLAYER;
1205         ConsoleObject->id                                       = Player_num;
1206         ConsoleObject->control_type     = CT_FLYING;
1207         ConsoleObject->movement_type    = MT_PHYSICS;
1208 }
1209
1210 extern void game_disable_cheats();
1211 extern void turn_cheats_off();
1212 extern void init_seismic_disturbances(void);
1213
1214 //starts a new game on the given level
1215 void StartNewGame(int start_level)
1216 {
1217         Game_mode = GM_NORMAL;
1218         Function_mode = FMODE_GAME;
1219         
1220         Next_level_num = 0;
1221
1222         InitPlayerObject();                             //make sure player's object set up
1223
1224         init_player_stats_game();               //clear all stats
1225
1226         N_players = 1;
1227 #ifdef NETWORK
1228         Network_new_game = 0;
1229 #endif
1230
1231         if (start_level < 0)
1232                 StartNewLevelSecret(start_level, 0);
1233         else
1234                 StartNewLevel(start_level, 0);
1235
1236         Players[Player_num].starting_level = start_level;               // Mark where they started
1237
1238         game_disable_cheats();
1239
1240         init_seismic_disturbances();
1241 }
1242
1243 //@@//starts a resumed game loaded from disk
1244 //@@void ResumeSavedGame(int start_level)
1245 //@@{
1246 //@@    Game_mode = GM_NORMAL;
1247 //@@    Function_mode = FMODE_GAME;
1248 //@@
1249 //@@    N_players = 1;
1250 //@@    Network_new_game = 0;
1251 //@@
1252 //@@    InitPlayerObject();                             //make sure player's object set up
1253 //@@
1254 //@@    StartNewLevel(start_level, 0);
1255 //@@
1256 //@@    game_disable_cheats();
1257 //@@}
1258
1259 #ifndef _NETWORK_H
1260 extern int network_endlevel_poll2( int nitems, newmenu_item * menus, int * key, int citem ); // network.c
1261 #endif
1262
1263 extern int N_secret_levels;
1264
1265 #define STARS_BACKGROUND ((MenuHires && cfexist("starsb.pcx"))?"starsb.pcx":cfexist("stars.pcx")?"stars.pcx":"starsb.pcx")
1266
1267 //      -----------------------------------------------------------------------------
1268 //      Does the bonus scoring.
1269 //      Call with dead_flag = 1 if player died, but deserves some portion of bonus (only skill points), anyway.
1270 void DoEndLevelScoreGlitz(int network)
1271 {
1272         int level_points, skill_points, energy_points, shield_points, hostage_points;
1273         int     all_hostage_points;
1274         int     endgame_points;
1275         char    all_hostage_text[64];
1276         char    endgame_text[64];
1277         #define N_GLITZITEMS 11
1278         char                            m_str[N_GLITZITEMS][30];
1279         newmenu_item    m[N_GLITZITEMS+1];
1280         int                             i,c;
1281         char                            title[128];
1282         int                             is_last_level;
1283         int                             mine_level;
1284
1285         set_screen_mode(SCREEN_MENU);           //go into menu mode
1286
1287    #ifdef TACTILE
1288                 if (TactileStick)
1289                   ClearForces();
1290         #endif
1291
1292         mprintf((0,"DoEndLevelScoreGlitz\n"));
1293
1294         //      Compute level player is on, deal with secret levels (negative numbers)
1295         mine_level = Players[Player_num].level;
1296         if (mine_level < 0)
1297                 mine_level *= -(Last_level/N_secret_levels);
1298
1299         level_points = Players[Player_num].score-Players[Player_num].last_score;
1300
1301         if (!Cheats_enabled) {
1302                 if (Difficulty_level > 1) {
1303                         skill_points = level_points*(Difficulty_level)/4;
1304                         skill_points -= skill_points % 100;
1305                 } else
1306                         skill_points = 0;
1307
1308                 shield_points = f2i(Players[Player_num].shields) * 5 * mine_level;
1309                 energy_points = f2i(Players[Player_num].energy) * 2 * mine_level;
1310                 hostage_points = Players[Player_num].hostages_on_board * 500 * (Difficulty_level+1);
1311
1312                 shield_points -= shield_points % 50;
1313                 energy_points -= energy_points % 50;
1314         } else {
1315                 skill_points = 0;
1316                 shield_points = 0;
1317                 energy_points = 0;
1318                 hostage_points = 0;
1319         }
1320
1321         all_hostage_text[0] = 0;
1322         endgame_text[0] = 0;
1323
1324         if (!Cheats_enabled && (Players[Player_num].hostages_on_board == Players[Player_num].hostages_level)) {
1325                 all_hostage_points = Players[Player_num].hostages_on_board * 1000 * (Difficulty_level+1);
1326                 sprintf(all_hostage_text, "%s%i\n", TXT_FULL_RESCUE_BONUS, all_hostage_points);
1327         } else
1328                 all_hostage_points = 0;
1329
1330         if (!Cheats_enabled && !(Game_mode & GM_MULTI) && (Players[Player_num].lives) && (Current_level_num == Last_level)) {           //player has finished the game!
1331                 endgame_points = Players[Player_num].lives * 10000;
1332                 sprintf(endgame_text, "%s%i\n", TXT_SHIP_BONUS, endgame_points);
1333                 is_last_level=1;
1334         } else
1335                 endgame_points = is_last_level = 0;
1336
1337         mprintf((0,"adding bonus points\n"));
1338         add_bonus_points_to_score(skill_points + energy_points + shield_points + hostage_points + all_hostage_points + endgame_points);
1339
1340         c = 0;
1341         sprintf(m_str[c++], "%s%i", TXT_SHIELD_BONUS, shield_points);           // Return at start to lower menu...
1342         sprintf(m_str[c++], "%s%i", TXT_ENERGY_BONUS, energy_points);
1343         sprintf(m_str[c++], "%s%i", TXT_HOSTAGE_BONUS, hostage_points);
1344         sprintf(m_str[c++], "%s%i", TXT_SKILL_BONUS, skill_points);
1345
1346         sprintf(m_str[c++], "%s", all_hostage_text);
1347         if (!(Game_mode & GM_MULTI) && (Players[Player_num].lives) && (Current_level_num == Last_level))
1348                 sprintf(m_str[c++], "%s", endgame_text);
1349
1350         sprintf(m_str[c++], "%s%i\n", TXT_TOTAL_BONUS, shield_points+energy_points+hostage_points+skill_points+all_hostage_points+endgame_points);
1351         sprintf(m_str[c++], "%s%i", TXT_TOTAL_SCORE, Players[Player_num].score);
1352
1353         #ifdef WINDOWS
1354         sprintf(m_str[c++], "");
1355         sprintf(m_str[c++], "         Done");
1356         #endif
1357
1358         for (i=0; i<c; i++) {
1359                 m[i].type = NM_TYPE_TEXT;
1360                 m[i].text = m_str[i];
1361         }
1362
1363         #ifdef WINDOWS
1364         m[c-1].type = NM_TYPE_MENU;
1365         #endif
1366
1367         // m[c].type = NM_TYPE_MENU;    m[c++].text = "Ok";
1368
1369         if (Current_level_num < 0)
1370                 sprintf(title,"%s%s %d %s\n %s %s",is_last_level?"\n\n\n":"\n",TXT_SECRET_LEVEL, -Current_level_num, TXT_COMPLETE, Current_level_name, TXT_DESTROYED);
1371         else
1372                 sprintf(title,"%s%s %d %s\n%s %s",is_last_level?"\n\n\n":"\n",TXT_LEVEL, Current_level_num, TXT_COMPLETE, Current_level_name, TXT_DESTROYED);
1373
1374         Assert(c <= N_GLITZITEMS);
1375
1376         gr_palette_fade_out(gr_palette, 32, 0);
1377
1378         mprintf((0,"doing menu\n"));
1379
1380    PA_DFX (pa_alpha_always());
1381
1382 #ifdef NETWORK
1383         if ( network && (Game_mode & GM_NETWORK) )
1384                 newmenu_do2(NULL, title, c, m, (void (*))network_endlevel_poll2, 0, STARS_BACKGROUND);
1385         else
1386 #endif
1387                 // NOTE LINK TO ABOVE!!!
1388                 newmenu_do2(NULL, title, c, m, NULL, 0, STARS_BACKGROUND);
1389
1390         mprintf((0,"done DoEndLevelScoreGlitz\n"));
1391 }
1392
1393 //give the player the opportunity to save his game
1394 void DoEndlevelMenu()
1395 {
1396 //No between level saves......!!!       state_save_all(1);
1397 }
1398
1399 //      -----------------------------------------------------------------------------------------------------
1400 //called when the player is starting a level (new game or new ship)
1401 void StartSecretLevel()
1402 {
1403         Assert(!Player_is_dead);
1404
1405         InitPlayerPosition(0);
1406
1407         verify_console_object();
1408
1409         ConsoleObject->control_type     = CT_FLYING;
1410         ConsoleObject->movement_type    = MT_PHYSICS;
1411
1412         // -- WHY? -- disable_matcens();
1413         clear_transient_objects(0);             //0 means leave proximity bombs
1414
1415         // create_player_appearance_effect(ConsoleObject);
1416         Do_appearance_effect = 1;
1417
1418         ai_reset_all_paths();
1419         // -- NO? -- reset_time();
1420
1421         reset_rear_view();
1422         Auto_fire_fusion_cannon_time = 0;
1423         Fusion_charge = 0;
1424
1425         Robot_firing_enabled = 1;
1426 }
1427
1428 extern void set_pos_from_return_segment(void);
1429
1430 //      Returns true if secret level has been destroyed.
1431 int p_secret_level_destroyed(void)
1432 {
1433         if (First_secret_visit) {
1434                 return 0;               //      Never been there, can't have been destroyed.
1435         } else {
1436                 if (cfexist(SECRETC_FILENAME))
1437                 {
1438                         return 0;
1439                 } else {
1440                         return 1;
1441                 }
1442         }
1443 }
1444
1445 //      -----------------------------------------------------------------------------------------------------
1446 void do_secret_message(char *msg)
1447 {
1448         int     old_fmode;
1449
1450         load_stars();
1451
1452 #if defined(POLY_ACC)
1453         pa_save_clut();
1454         pa_update_clut(gr_palette, 0, 256, 0);
1455 #endif
1456
1457         old_fmode = Function_mode;
1458         Function_mode = FMODE_MENU;
1459         nm_messagebox(NULL, 1, TXT_OK, msg);
1460         Function_mode = old_fmode;
1461
1462 #if defined(POLY_ACC)
1463         pa_restore_clut();
1464 #endif
1465         
1466         WIN(DEFINE_SCREEN(NULL));
1467 }
1468
1469 //      -----------------------------------------------------------------------------------------------------
1470 // called when the player is starting a new level for normal game mode and restore state
1471 //      Need to deal with whether this is the first time coming to this level or not.  If not the
1472 //      first time, instead of initializing various things, need to do a game restore for all the
1473 //      robots, powerups, walls, doors, etc.
1474 void StartNewLevelSecret(int level_num, int page_in_textures)
1475 {
1476         newmenu_item    m[1];
1477         //int i;
1478
1479         ThisLevelTime=0;
1480
1481         m[0].type = NM_TYPE_TEXT;
1482         m[0].text = " ";
1483
1484         last_drawn_cockpit[0] = -1;
1485         last_drawn_cockpit[1] = -1;
1486
1487         if (Newdemo_state == ND_STATE_PAUSED)
1488                 Newdemo_state = ND_STATE_RECORDING;
1489
1490         if (Newdemo_state == ND_STATE_RECORDING) {
1491                 newdemo_set_new_level(level_num);
1492                 newdemo_record_start_frame(FrameCount, FrameTime );
1493         } else if (Newdemo_state != ND_STATE_PLAYBACK) {
1494
1495                 gr_palette_fade_out(gr_palette, 32, 0);
1496
1497                 set_screen_mode(SCREEN_MENU);           //go into menu mode
1498
1499                 if (First_secret_visit) {
1500                         do_secret_message(TXT_SECRET_EXIT);
1501                 } else {
1502                         if (cfexist(SECRETC_FILENAME))
1503                         {
1504                                 do_secret_message(TXT_SECRET_EXIT);
1505                         } else {
1506                                 char    text_str[128];
1507
1508                                 sprintf(text_str, "Secret level already destroyed.\nAdvancing to level %i.", Current_level_num+1);
1509                                 do_secret_message(text_str);
1510                         }
1511                 }
1512         }
1513
1514         LoadLevel(level_num,page_in_textures);
1515
1516         Assert(Current_level_num == level_num); //make sure level set right
1517
1518         Assert(Function_mode == FMODE_GAME);
1519
1520         gameseq_init_network_players(); // Initialize the Players array for
1521                                                                                           // this level
1522
1523         HUD_clear_messages();
1524
1525         automap_clear_visited();
1526
1527         // --   init_player_stats_level();
1528
1529         Viewer = &Objects[Players[Player_num].objnum];
1530
1531         gameseq_remove_unused_players();
1532
1533         Game_suspended = 0;
1534
1535         Control_center_destroyed = 0;
1536
1537         init_cockpit();
1538         reset_palette_add();
1539
1540         if (First_secret_visit || (Newdemo_state == ND_STATE_PLAYBACK)) {
1541                 init_robots_for_level();
1542                 init_ai_objects();
1543                 init_smega_detonates();
1544                 init_morphs();
1545                 init_all_matcens();
1546                 reset_special_effects();
1547                 StartSecretLevel();
1548         } else {
1549                 if (cfexist(SECRETC_FILENAME))
1550                 {
1551                         int     pw_save, sw_save;
1552
1553                         pw_save = Primary_weapon;
1554                         sw_save = Secondary_weapon;
1555                         state_restore_all(1, 1, SECRETC_FILENAME);
1556                         Primary_weapon = pw_save;
1557                         Secondary_weapon = sw_save;
1558                         reset_special_effects();
1559                         StartSecretLevel();
1560                         // -- No: This is only for returning to base level: set_pos_from_return_segment();
1561                 } else {
1562                         char    text_str[128];
1563
1564                         sprintf(text_str, "Secret level already destroyed.\nAdvancing to level %i.", Current_level_num+1);
1565                         do_secret_message(text_str);
1566                         return;
1567
1568                         // -- //        If file doesn't exist, it's because reactor was destroyed.
1569                         // -- mprintf((0, "secret.sgc doesn't exist.  Advancing to next level.\n"));
1570                         // -- // -- StartNewLevel(Secret_level_table[-Current_level_num-1]+1, 0);
1571                         // -- StartNewLevel(Secret_level_table[-Current_level_num-1]+1, 0);
1572                         // -- return;
1573                 }
1574         }
1575
1576         if (First_secret_visit) {
1577                 copy_defaults_to_robot_all();
1578         }
1579
1580         turn_cheats_off();
1581
1582         init_controlcen_for_level();
1583
1584         //      Say player can use FLASH cheat to mark path to exit.
1585         Last_level_path_created = -1;
1586
1587         First_secret_visit = 0;
1588 }
1589
1590 int     Entered_from_level;
1591
1592 // ---------------------------------------------------------------------------------------------------------------
1593 //      Called from switch.c when player is on a secret level and hits exit to return to base level.
1594 void ExitSecretLevel(void)
1595 {
1596         if (Newdemo_state == ND_STATE_PLAYBACK)
1597                 return;
1598
1599         if (!Control_center_destroyed) {
1600                 state_save_all(0, 2, SECRETC_FILENAME);
1601         }
1602
1603         if (cfexist(SECRETB_FILENAME))
1604         {
1605                 int     pw_save, sw_save;
1606
1607                 returning_to_level_message();
1608                 pw_save = Primary_weapon;
1609                 sw_save = Secondary_weapon;
1610                 state_restore_all(1, 1, SECRETB_FILENAME);
1611                 Primary_weapon = pw_save;
1612                 Secondary_weapon = sw_save;
1613         } else {
1614                 // File doesn't exist, so can't return to base level.  Advance to next one.
1615                 if (Entered_from_level == Last_level)
1616                         DoEndGame();
1617                 else {
1618                         advancing_to_level_message();
1619                         StartNewLevel(Entered_from_level+1, 0);
1620                 }
1621         }
1622 }
1623
1624 // ---------------------------------------------------------------------------------------------------------------
1625 //      Set invulnerable_time and cloak_time in player struct to preserve amount of time left to
1626 //      be invulnerable or cloaked.
1627 void do_cloak_invul_secret_stuff(fix old_gametime)
1628 {
1629         if (Players[Player_num].flags & PLAYER_FLAGS_INVULNERABLE) {
1630                 fix     time_used;
1631
1632                 time_used = old_gametime - Players[Player_num].invulnerable_time;
1633                 Players[Player_num].invulnerable_time = GameTime - time_used;
1634         }
1635
1636         if (Players[Player_num].flags & PLAYER_FLAGS_CLOAKED) {
1637                 fix     time_used;
1638
1639                 time_used = old_gametime - Players[Player_num].cloak_time;
1640                 Players[Player_num].cloak_time = GameTime - time_used;
1641         }
1642 }
1643
1644 // ---------------------------------------------------------------------------------------------------------------
1645 //      Called from switch.c when player passes through secret exit.  That means he was on a non-secret level and he
1646 //      is passing to the secret level.
1647 //      Do a savegame.
1648 void EnterSecretLevel(void)
1649 {
1650         fix     old_gametime;
1651         int     i;
1652
1653         Assert(! (Game_mode & GM_MULTI) );
1654
1655         Entered_from_level = Current_level_num;
1656
1657         if (Control_center_destroyed)
1658                 DoEndLevelScoreGlitz(0);
1659
1660         if (Newdemo_state != ND_STATE_PLAYBACK)
1661                 state_save_all(0, 1, NULL);     //      Not between levels (ie, save all), IS a secret level, NO filename override
1662
1663         //      Find secret level number to go to, stuff in Next_level_num.
1664         for (i=0; i<-Last_secret_level; i++)
1665                 if (Secret_level_table[i]==Current_level_num) {
1666                         Next_level_num = -(i+1);
1667                         break;
1668                 } else if (Secret_level_table[i] > Current_level_num) { //      Allows multiple exits in same group.
1669                         Next_level_num = -i;
1670                         break;
1671                 }
1672
1673         if (! (i<-Last_secret_level))           //didn't find level, so must be last
1674                 Next_level_num = Last_secret_level;
1675
1676         old_gametime = GameTime;
1677
1678         StartNewLevelSecret(Next_level_num, 1);
1679         
1680         // do_cloak_invul_stuff();
1681 }
1682
1683 //called when the player has finished a level
1684 void PlayerFinishedLevel(int secret_flag)
1685 {
1686         Assert(!secret_flag);
1687
1688         //credit the player for hostages
1689         Players[Player_num].hostages_rescued_total += Players[Player_num].hostages_on_board;
1690
1691         if (Game_mode & GM_NETWORK)
1692                 Players[Player_num].connected = 2; // Finished but did not die
1693
1694         last_drawn_cockpit[0] = -1;
1695         last_drawn_cockpit[1] = -1;
1696
1697         AdvanceLevel(secret_flag);                              //now go on to the next one (if one)
1698 }
1699
1700 #if defined(D2_OEM) || defined(COMPILATION)
1701 #define MOVIE_REQUIRED 0
1702 #else
1703 #define MOVIE_REQUIRED 1
1704 #endif
1705
1706 #ifdef D2_OEM
1707 #define ENDMOVIE "endo"
1708 #else
1709 #define ENDMOVIE "end"
1710 #endif
1711
1712 void show_order_form();
1713 extern void com_hangup(void);
1714
1715 //called when the player has finished the last level
1716 void DoEndGame(void)
1717 {
1718         mprintf((0,"DoEndGame\n"));
1719
1720         Function_mode = FMODE_MENU;
1721         if ((Newdemo_state == ND_STATE_RECORDING) || (Newdemo_state == ND_STATE_PAUSED))
1722                 newdemo_stop_recording();
1723
1724         set_screen_mode( SCREEN_MENU );
1725
1726         WINDOS(
1727                 dd_gr_set_current_canvas(NULL),
1728                 gr_set_current_canvas(NULL)
1729         );
1730
1731         key_flush();
1732
1733         if (Current_mission_num == Builtin_mission_num && !(Game_mode & GM_MULTI))
1734         { //only built-in mission, & not multi
1735                 int played=MOVIE_NOT_PLAYED;    //default is not played
1736
1737                 init_subtitles(ENDMOVIE ".tex");        //ingore errors
1738                 played = PlayMovie(ENDMOVIE,MOVIE_REQUIRED);
1739                 close_subtitles();
1740                 if (!played) {
1741                         if (is_D2_OEM)
1742                         {
1743                                 songs_play_song( SONG_TITLE, 0 );
1744                                 do_briefing_screens("end2oem.tex",1);
1745                         }
1746                         else
1747                         {
1748                                 songs_play_song( SONG_ENDGAME, 0 );
1749                                 mprintf((0,"doing briefing\n"));
1750                                 do_briefing_screens("ending2.tex",1);
1751                                 mprintf((0,"briefing done\n"));
1752                         }
1753                 }
1754    } else if (!(Game_mode & GM_MULTI)) {    //not multi
1755                 char tname[FILENAME_LEN];
1756                 sprintf(tname,"%s.tex",Current_mission_filename);
1757                 do_briefing_screens (tname,Last_level+1);   //level past last is endgame breifing
1758
1759                 //try doing special credits
1760                 sprintf(tname,"%s.ctb",Current_mission_filename);
1761                 credits_show(tname);
1762         }
1763
1764         key_flush();
1765
1766 #ifdef SHAREWARE
1767                 show_order_form();
1768 #endif
1769
1770 #ifdef NETWORK
1771         if (Game_mode & GM_MULTI)
1772                 multi_endlevel_score();
1773         else
1774 #endif
1775                 // NOTE LINK TO ABOVE
1776                 DoEndLevelScoreGlitz(0);
1777
1778         if (Current_mission_num == Builtin_mission_num && !((Game_mode & GM_MULTI) && !(Game_mode & GM_MULTI_COOP))) {
1779                 WINDOS(
1780                         dd_gr_set_current_canvas(NULL),
1781                         gr_set_current_canvas( NULL )
1782                 );
1783                 WINDOS(
1784                         dd_gr_clear_canvas(BM_XRGB(0,0,0)),
1785                         gr_clear_canvas(BM_XRGB(0,0,0))
1786                 );
1787                 gr_palette_clear();
1788                 load_palette(DEFAULT_PALETTE,0,1);
1789                 scores_maybe_add_player(0);
1790         }
1791
1792         Function_mode = FMODE_MENU;
1793
1794         if ((Game_mode & GM_SERIAL) || (Game_mode & GM_MODEM))
1795                 Game_mode |= GM_GAME_OVER;              //preserve modem setting so go back into modem menu
1796         else
1797                 Game_mode = GM_GAME_OVER;
1798
1799
1800         longjmp( LeaveGame, 0 );                // Exit out of game loop
1801 }
1802
1803 //from which level each do you get to each secret level
1804 int Secret_level_table[MAX_SECRET_LEVELS_PER_MISSION];
1805
1806 //called to go to the next level (if there is one)
1807 //if secret_flag is true, advance to secret level, else next normal one
1808 //      Return true if game over.
1809 void AdvanceLevel(int secret_flag)
1810 {
1811 #ifdef NETWORK
1812         int result;
1813 #endif
1814
1815         mprintf((0,"AdvanceLevel\n"));
1816
1817         Assert(!secret_flag);
1818
1819         if (Current_level_num != Last_level) {
1820 #ifdef NETWORK
1821                 if (Game_mode & GM_MULTI)
1822                         multi_endlevel_score();         
1823                 else
1824 #endif
1825                         // NOTE LINK TO ABOVE!!!
1826                         DoEndLevelScoreGlitz(0);                //give bonuses
1827         }
1828
1829         Control_center_destroyed = 0;
1830
1831         #ifdef EDITOR
1832         if (Current_level_num == 0)
1833                 return;         //not a real level
1834         #endif
1835
1836 #ifdef NETWORK
1837         if (Game_mode & GM_MULTI)       {
1838                 result = multi_endlevel(&secret_flag); // Wait for other players to reach this point
1839                 if (result) // failed to sync
1840                 {
1841                         if (Current_level_num == Last_level)            //player has finished the game!
1842                                 longjmp( LeaveGame, 0 );                // Exit out of game loop
1843                         else
1844                                 return;
1845                 }
1846         }
1847 #endif
1848
1849         if (Current_level_num == Last_level) {          //player has finished the game!
1850                 
1851                 mprintf((0,"Finished last level!\n"));
1852
1853                 DoEndGame();
1854
1855         } else {
1856
1857                 Next_level_num = Current_level_num+1;           //assume go to next normal level
1858
1859                 if (!(Game_mode & GM_MULTI))
1860                         DoEndlevelMenu(); // Let use save their game
1861
1862                 StartNewLevel(Next_level_num, 0);
1863
1864         }
1865 }
1866
1867 #ifdef MACINTOSH                // horrible hack of a routine to load just the palette from the stars.pcx file
1868
1869 extern char last_palette_loaded[];
1870
1871 void load_stars_palette()
1872 {
1873         int pcx_error;
1874         ubyte pal[256*3];
1875
1876         pcx_error = pcx_read_bitmap_palette(STARS_BACKGROUND,pal);
1877         Assert(pcx_error == PCX_ERROR_NONE);
1878
1879         //@@gr_remap_bitmap_good( bmp, pal, -1, -1 );
1880
1881
1882         {       //remap stuff. this code is kindof a hack
1883
1884                 //now, before we bring up the menu, we need to
1885                 //do some stuff to make sure the palette is ok.  First, we need to
1886                 //get our current palette into the 2d's array, so the remapping will
1887                 //work.  Second, we need to remap the fonts.  Third, we need to fill
1888                 //in part of the fade tables so the darkening of the menu edges works
1889
1890                 gr_copy_palette(gr_palette, pal, sizeof(gr_palette));
1891                 remap_fonts_and_menus(1);
1892
1893         }
1894
1895         strcpy(last_palette_loaded,"");         //force palette load next time
1896 }
1897 #endif
1898
1899 void nm_draw_background1(char * filename);
1900
1901 void load_stars()
1902 {
1903 //@@    int pcx_error;
1904 //@@    ubyte pal[256*3];
1905 //@@
1906 //@@    pcx_error = pcx_read_bitmap("STARS.PCX",&grd_curcanv->cv_bitmap,grd_curcanv->cv_bitmap.bm_type,pal);
1907 //@@    Assert(pcx_error == PCX_ERROR_NONE);
1908 //@@
1909 //@@    gr_remap_bitmap_good( &grd_curcanv->cv_bitmap, pal, -1, -1 );
1910
1911         WIN(DEFINE_SCREEN(STARS_BACKGROUND));
1912
1913         nm_draw_background1(STARS_BACKGROUND);
1914
1915 }
1916
1917
1918 void
1919 died_in_mine_message(void)
1920 {
1921         // Tell the player he died in the mine, explain why
1922         int old_fmode;
1923
1924         if (Game_mode & GM_MULTI)
1925                 return;
1926
1927         gr_palette_fade_out(gr_palette, 32, 0);
1928
1929         set_screen_mode(SCREEN_MENU);           //go into menu mode
1930
1931         WINDOS(
1932                 dd_gr_set_current_canvas(NULL),
1933                 gr_set_current_canvas(NULL)
1934         );
1935
1936         load_stars();
1937
1938 #if defined(POLY_ACC)
1939         pa_save_clut();
1940         pa_update_clut(gr_palette, 0, 256, 0);
1941 #endif
1942
1943         old_fmode = Function_mode;
1944         Function_mode = FMODE_MENU;
1945         nm_messagebox(NULL, 1, TXT_OK, TXT_DIED_IN_MINE);
1946         Function_mode = old_fmode;
1947
1948 #if defined(POLY_ACC)
1949         pa_restore_clut();
1950 #endif
1951
1952         WIN(DEFINE_SCREEN(NULL));
1953 }
1954
1955 //      Called when player dies on secret level.
1956 void returning_to_level_message(void)
1957 {
1958         char    msg[128];
1959
1960         int old_fmode;
1961
1962         if (Game_mode & GM_MULTI)
1963                 return;
1964
1965         gr_palette_fade_out(gr_palette, 32, 0);
1966
1967         set_screen_mode(SCREEN_MENU);           //go into menu mode
1968
1969         gr_set_current_canvas(NULL);
1970
1971         load_stars();
1972
1973 #if defined(POLY_ACC)
1974         pa_save_clut();
1975         pa_update_clut(gr_palette, 0, 256, 0);
1976 #endif
1977
1978         old_fmode = Function_mode;
1979         Function_mode = FMODE_MENU;
1980         sprintf(msg, "Returning to level %i", Entered_from_level);
1981         nm_messagebox(NULL, 1, TXT_OK, msg);
1982         Function_mode = old_fmode;
1983
1984 #if defined(POLY_ACC)
1985         pa_restore_clut();
1986 #endif
1987
1988         WIN(DEFINE_SCREEN(NULL));
1989 }
1990
1991 //      Called when player dies on secret level.
1992 void advancing_to_level_message(void)
1993 {
1994         char    msg[128];
1995
1996         int old_fmode;
1997
1998         //      Only supposed to come here from a secret level.
1999         Assert(Current_level_num < 0);
2000
2001         if (Game_mode & GM_MULTI)
2002                 return;
2003
2004         gr_palette_fade_out(gr_palette, 32, 0);
2005
2006         set_screen_mode(SCREEN_MENU);           //go into menu mode
2007
2008         gr_set_current_canvas(NULL);
2009         
2010         load_stars();
2011
2012 #if defined(POLY_ACC)
2013         pa_save_clut();
2014         pa_update_clut(gr_palette, 0, 256, 0);
2015 #endif
2016
2017         old_fmode = Function_mode;
2018         Function_mode = FMODE_MENU;
2019         sprintf(msg, "Base level destroyed.\nAdvancing to level %i", Entered_from_level+1);
2020         nm_messagebox(NULL, 1, TXT_OK, msg);
2021         Function_mode = old_fmode;
2022
2023 #if defined(POLY_ACC)
2024         pa_restore_clut();
2025 #endif
2026
2027         WIN(DEFINE_SCREEN(NULL));
2028 }
2029
2030 void digi_stop_digi_sounds();
2031
2032 void DoPlayerDead()
2033 {
2034         reset_palette_add();
2035
2036         gr_palette_load (gr_palette);
2037
2038 //      digi_pause_digi_sounds();               //kill any continuing sounds (eg. forcefield hum)
2039         digi_stop_digi_sounds();                //kill any continuing sounds (eg. forcefield hum)
2040
2041         dead_player_end();              //terminate death sequence (if playing)
2042
2043         #ifdef EDITOR
2044         if (Game_mode == GM_EDITOR) {                   //test mine, not real level
2045                 object * playerobj = &Objects[Players[Player_num].objnum];
2046                 //nm_messagebox( "You're Dead!", 1, "Continue", "Not a real game, though." );
2047                 load_level("gamesave.lvl");
2048                 init_player_stats_new_ship();
2049                 playerobj->flags &= ~OF_SHOULD_BE_DEAD;
2050                 StartLevel(0);
2051                 return;
2052         }
2053         #endif
2054
2055 #ifdef NETWORK
2056         if ( Game_mode&GM_MULTI )
2057         {
2058                 multi_do_death(Players[Player_num].objnum);
2059         }
2060         else
2061 #endif
2062         {                               //Note link to above else!
2063                 Players[Player_num].lives--;
2064                 if (Players[Player_num].lives == 0)
2065                 {       
2066                         DoGameOver();
2067                         return;
2068                 }
2069         }
2070                                 
2071         if ( Control_center_destroyed ) {
2072
2073                 //clear out stuff so no bonus
2074                 Players[Player_num].hostages_on_board = 0;
2075                 Players[Player_num].energy = 0;
2076                 Players[Player_num].shields = 0;
2077                 Players[Player_num].connected = 3;
2078
2079                 died_in_mine_message(); // Give them some indication of what happened
2080
2081                 if (Current_level_num < 0) {
2082                         if (cfexist(SECRETB_FILENAME))
2083                         {
2084                                 returning_to_level_message();
2085                                 state_restore_all(1, 2, SECRETB_FILENAME);                      //      2 means you died
2086                                 set_pos_from_return_segment();
2087                                 Players[Player_num].lives--;                                            //      re-lose the life, Players[Player_num].lives got written over in restore.
2088                         } else {
2089                                 advancing_to_level_message();
2090                                 StartNewLevel(Entered_from_level+1, 0);
2091                                 init_player_stats_new_ship();   //      New, MK, 05/29/96!, fix bug with dying in secret level, advance to next level, keep powerups!
2092                         }
2093                 } else {
2094
2095                         AdvanceLevel(0);                        //if finished, go on to next level
2096
2097                         init_player_stats_new_ship();
2098                         last_drawn_cockpit[0] = -1;
2099                         last_drawn_cockpit[1] = -1;
2100                 }
2101
2102         } else if (Current_level_num < 0) {
2103                 if (cfexist(SECRETB_FILENAME))
2104                 {
2105                         returning_to_level_message();
2106                         if (!Control_center_destroyed)
2107                                 state_save_all(0, 2, SECRETC_FILENAME);
2108                         state_restore_all(1, 2, SECRETB_FILENAME);
2109                         set_pos_from_return_segment();
2110                         Players[Player_num].lives--;                                            //      re-lose the life, Players[Player_num].lives got written over in restore.
2111                 } else {
2112                         died_in_mine_message(); // Give them some indication of what happened
2113                         advancing_to_level_message();
2114                         StartNewLevel(Entered_from_level+1, 0);
2115                         init_player_stats_new_ship();
2116                 }
2117         } else {
2118                 init_player_stats_new_ship();
2119                 StartLevel(1);
2120         }
2121
2122         digi_sync_sounds();
2123 }
2124
2125 extern int BigWindowSwitch;
2126
2127 //called when the player is starting a new level for normal game mode and restore state
2128 //      secret_flag set if came from a secret level
2129 void StartNewLevelSub(int level_num, int page_in_textures, int secret_flag)
2130 {
2131         if (!(Game_mode & GM_MULTI)) {
2132                 last_drawn_cockpit[0] = -1;
2133                 last_drawn_cockpit[1] = -1;
2134         }
2135    BigWindowSwitch=0;
2136
2137
2138         if (Newdemo_state == ND_STATE_PAUSED)
2139                 Newdemo_state = ND_STATE_RECORDING;
2140
2141         if (Newdemo_state == ND_STATE_RECORDING) {
2142                 newdemo_set_new_level(level_num);
2143                 newdemo_record_start_frame(FrameCount, FrameTime );
2144         }
2145
2146         if (Game_mode & GM_MULTI)
2147                 Function_mode = FMODE_MENU; // Cheap fix to prevent problems with errror dialogs in loadlevel.
2148
2149         LoadLevel(level_num,page_in_textures);
2150
2151         Assert(Current_level_num == level_num); //make sure level set right
2152
2153         gameseq_init_network_players(); // Initialize the Players array for
2154                                                                                           // this level
2155
2156         Viewer = &Objects[Players[Player_num].objnum];
2157
2158         Assert(N_players <= NumNetPlayerPositions);
2159                 //If this assert fails, there's not enough start positions
2160
2161 #ifdef NETWORK
2162         if (Game_mode & GM_NETWORK)
2163         {
2164                 if(network_level_sync()) // After calling this, Player_num is set
2165                         return;
2166         }
2167         if ((Game_mode & GM_SERIAL) || (Game_mode & GM_MODEM))
2168         {
2169                 if(com_level_sync())
2170                         return;
2171         }
2172 #endif
2173
2174         Assert(Function_mode == FMODE_GAME);
2175
2176         #ifndef NDEBUG
2177         //-- mprintf((0, "Player_num = %d, N_players = %d.\n", Player_num, N_players)); // DEBUG
2178         #endif
2179
2180         HUD_clear_messages();
2181
2182         automap_clear_visited();
2183
2184 #ifdef NETWORK
2185         if (Network_new_game == 1)
2186         {
2187                 Network_new_game = 0;
2188                 init_player_stats_new_ship();
2189         }
2190 #endif
2191         init_player_stats_level(secret_flag);
2192
2193 #ifdef NETWORK
2194         if ((Game_mode & GM_MULTI_COOP) && Network_rejoined)
2195         {
2196                 int i;
2197                 for (i = 0; i < N_players; i++)
2198                         Players[i].flags |= Netgame.player_flags[i];
2199         }
2200
2201         if (Game_mode & GM_MULTI)
2202         {
2203                 multi_prep_level(); // Removes robots from level if necessary
2204         }
2205 #endif
2206
2207         gameseq_remove_unused_players();
2208
2209         Game_suspended = 0;
2210
2211         Control_center_destroyed = 0;
2212
2213         set_screen_mode(SCREEN_GAME);
2214         init_cockpit();
2215         init_robots_for_level();
2216         init_ai_objects();
2217         init_smega_detonates();
2218         init_morphs();
2219         init_all_matcens();
2220         reset_palette_add();
2221         init_thief_for_level();
2222         init_stuck_objects();
2223         game_flush_inputs();            // clear out the keyboard
2224         if (!(Game_mode & GM_MULTI))
2225                 filter_objects_from_level();
2226
2227         turn_cheats_off();
2228
2229         if (!(Game_mode & GM_MULTI) && !Cheats_enabled)
2230                 set_highest_level(Current_level_num);
2231         else
2232                 read_player_file();             //get window sizes
2233
2234         reset_special_effects();
2235
2236 #ifdef OGL
2237         gr_remap_mono_fonts();
2238         ogl_cache_level_textures();
2239 #endif
2240
2241
2242 #ifdef NETWORK
2243         if (Network_rejoined == 1)
2244         {
2245                 #ifndef NDEBUG
2246                 mprintf((0, "Restarting - joining in random location.\n"));
2247                 #endif
2248                 Network_rejoined = 0;
2249                 StartLevel(1);
2250         }
2251         else
2252 #endif
2253                 StartLevel(0);          // Note link to above if!
2254
2255         copy_defaults_to_robot_all();
2256         init_controlcen_for_level();
2257
2258         //      Say player can use FLASH cheat to mark path to exit.
2259         Last_level_path_created = -1;
2260 }
2261
2262 #ifdef NETWORK
2263 extern char PowerupsInMine[MAX_POWERUP_TYPES], MaxPowerupsAllowed[MAX_POWERUP_TYPES];
2264 #endif
2265 void bash_to_shield (int i,char *s)
2266 {
2267 #ifdef NETWORK
2268         int type=Objects[i].id;
2269 #endif
2270
2271         mprintf((0, "Bashing %s object #%i to shield.\n",s, i));
2272
2273 #ifdef NETWORK
2274         PowerupsInMine[type]=MaxPowerupsAllowed[type]=0;
2275 #endif
2276
2277         Objects[i].id = POW_SHIELD_BOOST;
2278         Objects[i].rtype.vclip_info.vclip_num = Powerup_info[Objects[i].id].vclip_num;
2279         Objects[i].rtype.vclip_info.frametime = Vclip[Objects[i].rtype.vclip_info.vclip_num].frame_time;
2280 }
2281
2282
2283 void filter_objects_from_level()
2284  {
2285   int i;
2286
2287   mprintf ((0,"Highest object index=%d\n",Highest_object_index));
2288
2289   for (i=0;i<=Highest_object_index;i++)
2290         {
2291          if (Objects[i].type==OBJ_POWERUP)
2292      if (Objects[i].id==POW_FLAG_RED || Objects[i].id==POW_FLAG_BLUE)
2293            bash_to_shield (i,"Flag!!!!");
2294    }
2295
2296  }
2297
2298 struct {
2299         int     level_num;
2300         char    movie_name[FILENAME_LEN];
2301 } intro_movie[] = {     { 1,"pla"},
2302                                                         { 5,"plb"},
2303                                                         { 9,"plc"},
2304                                                         {13,"pld"},
2305                                                         {17,"ple"},
2306                                                         {21,"plf"},
2307                                                         {24,"plg"}};
2308
2309 #define NUM_INTRO_MOVIES (sizeof(intro_movie) / sizeof(*intro_movie))
2310
2311 extern int MenuHiresAvailable;
2312 extern int robot_movies;        //0 means none, 1 means lowres, 2 means hires
2313 extern int intro_played;        //true if big intro movie played
2314
2315 void ShowLevelIntro(int level_num)
2316 {
2317         //if shareware, show a briefing?
2318
2319         if (!(Game_mode & GM_MULTI)) {
2320                 int i;
2321
2322                 ubyte save_pal[sizeof(gr_palette)];
2323
2324                 memcpy(save_pal,gr_palette,sizeof(gr_palette));
2325
2326                 if (Current_mission_num == Builtin_mission_num) {
2327                         int movie=0;
2328
2329                         if (is_SHAREWARE)
2330                         {
2331                                 if (level_num==1)
2332                                         do_briefing_screens ("brief2.tex", 1);
2333                         }
2334                         else if (is_D2_OEM)
2335                         {
2336                                 if (level_num == 1 && !intro_played)
2337                                         do_briefing_screens("brief2o.tex", 1);
2338                         }
2339                         else // full version
2340                         {
2341                                 for (i=0;i<NUM_INTRO_MOVIES;i++)
2342                                 {
2343                                         if (intro_movie[i].level_num == level_num)
2344                                         {
2345                                                 Screen_mode = -1;
2346                                                 PlayMovie(intro_movie[i].movie_name,MOVIE_REQUIRED);
2347                                                 movie=1;
2348                                                 break;
2349                                         }
2350                                 }
2351
2352 #ifdef WINDOWS
2353                                 if (!movie) {                                   //must go before briefing
2354                                         dd_gr_init_screen();
2355                                         Screen_mode = -1;
2356                                 }
2357 #endif
2358
2359                                 if (robot_movies)
2360                                 {
2361                                         int hires_save=MenuHiresAvailable;
2362
2363                                         if (robot_movies == 1)          //lowres only
2364                                         {
2365                                                 MenuHiresAvailable = 0;         //pretend we can't do highres
2366
2367                                                 if (hires_save != MenuHiresAvailable)
2368                                                         Screen_mode = -1;               //force reset
2369
2370                                         }
2371                                         do_briefing_screens ("robot.tex",level_num);
2372                                         MenuHiresAvailable = hires_save;
2373                                 }
2374
2375                         }
2376                 }
2377                 else {  //not the built-in mission.  check for add-on briefing
2378                         if (Mission_list[Current_mission_num].descent_version == 1)
2379                                 do_briefing_screens(Briefing_text_filename, level_num);
2380                         else {
2381                                 char tname[FILENAME_LEN];
2382                                 sprintf(tname, "%s.tex", Current_mission_filename);
2383                                 do_briefing_screens(tname, level_num);
2384                         }
2385                 }
2386
2387
2388                 memcpy(gr_palette,save_pal,sizeof(gr_palette));
2389         }
2390 }
2391
2392 //      ---------------------------------------------------------------------------
2393 //      If starting a level which appears in the Secret_level_table, then set First_secret_visit.
2394 //      Reason: On this level, if player goes to a secret level, he will be going to a different
2395 //      secret level than he's ever been to before.
2396 //      Sets the global First_secret_visit if necessary.  Otherwise leaves it unchanged.
2397 void maybe_set_first_secret_visit(int level_num)
2398 {
2399         int     i;
2400
2401         for (i=0; i<N_secret_levels; i++) {
2402                 if (Secret_level_table[i] == level_num) {
2403                         First_secret_visit = 1;
2404                         mprintf((0, "Bashing First_secret_visit to 1 because entering level %i.\n", level_num));
2405                 }
2406         }
2407 }
2408
2409 //called when the player is starting a new level for normal game model
2410 //      secret_flag if came from a secret level
2411 void StartNewLevel(int level_num, int secret_flag)
2412 {
2413         ThisLevelTime=0;
2414
2415         if ((level_num > 0) && (!secret_flag)) {
2416                 maybe_set_first_secret_visit(level_num);
2417         }
2418
2419         ShowLevelIntro(level_num);
2420
2421         WIN(DEFINE_SCREEN(NULL));               // ALT-TAB: no restore of background.
2422         
2423         StartNewLevelSub(level_num, 1, secret_flag );
2424
2425 }
2426
2427 //initialize the player object position & orientation (at start of game, or new ship)
2428 void InitPlayerPosition(int random_flag)
2429 {
2430         int NewPlayer=0;
2431
2432 #ifdef NETWORK
2433         if (! ((Game_mode & GM_MULTI) && !(Game_mode&GM_MULTI_COOP)) ) // If not deathmatch
2434 #endif
2435                 NewPlayer = Player_num;
2436 #ifdef NETWORK
2437         else if (random_flag == 1)
2438         {
2439                 int i, closest = -1, trys=0;
2440                 fix closest_dist = 0x7ffffff, dist;
2441
2442                 d_srand(clock());
2443
2444 #ifndef NDEBUG
2445                 if (NumNetPlayerPositions != MAX_NUM_NET_PLAYERS)
2446                 {
2447                         mprintf((1, "WARNING: There are only %d start positions!\n"));
2448                         //Int3();
2449                 }
2450 #endif
2451
2452                 do {
2453                         if (trys > 0)   
2454                         {
2455                                 mprintf((0, "Can't start in location %d because its too close to player %d\n", NewPlayer, closest ));
2456                         }
2457                         trys++;
2458
2459                         NewPlayer = d_rand() % NumNetPlayerPositions;
2460
2461                         closest = -1;
2462                         closest_dist = 0x7fffffff;
2463         
2464                         for (i=0; i<N_players; i++ )    {
2465                                 if ( (i!=Player_num) && (Objects[Players[i].objnum].type == OBJ_PLAYER) )       {
2466                                         dist = find_connected_distance(&Objects[Players[i].objnum].pos, Objects[Players[i].objnum].segnum, &Player_init[NewPlayer].pos, Player_init[NewPlayer].segnum, 10, WID_FLY_FLAG );      //      Used to be 5, search up to 10 segments
2467                                         // -- mprintf((0, "Distance from start location %d to player %d is %f.\n", NewPlayer, i, f2fl(dist)));
2468                                         if ( (dist < closest_dist) && (dist >= 0) )     {
2469                                                 closest_dist = dist;
2470                                                 closest = i;
2471                                         }
2472                                 }
2473                         }
2474
2475                         // -- mprintf((0, "Closest from pos %d is %f to plr %d.\n", NewPlayer, f2fl(closest_dist), closest));
2476                 } while ( (closest_dist<i2f(15*20)) && (trys<MAX_NUM_NET_PLAYERS*2) );
2477         }
2478         else {
2479                 mprintf((0, "Starting position is not being changed.\n"));
2480                 goto done; // If deathmatch and not random, positions were already determined by sync packet
2481         }
2482         Assert(NewPlayer >= 0);
2483         Assert(NewPlayer < NumNetPlayerPositions);
2484 #endif
2485
2486         ConsoleObject->pos = Player_init[NewPlayer].pos;
2487         ConsoleObject->orient = Player_init[NewPlayer].orient;
2488 // -- mprintf((0, "Pos set to %8x %8x %8x\n", ConsoleObject->pos.x, ConsoleObject->pos.y, ConsoleObject->pos.z));
2489
2490         // -- mprintf((0, "Re-starting in location %d of %d.\n", NewPlayer+1, NumNetPlayerPositions));
2491
2492         obj_relink(ConsoleObject-Objects,Player_init[NewPlayer].segnum);
2493
2494 #ifdef NETWORK
2495 done:
2496 #endif
2497         reset_player_object();
2498         reset_cruise();
2499 }
2500
2501 //      -----------------------------------------------------------------------------------------------------
2502 //      Initialize default parameters for one robot, copying from Robot_info to *objp.
2503 //      What about setting size!?  Where does that come from?
2504 void copy_defaults_to_robot(object *objp)
2505 {
2506         robot_info      *robptr;
2507         int                     objid;
2508
2509         Assert(objp->type == OBJ_ROBOT);
2510         objid = objp->id;
2511         Assert(objid < N_robot_types);
2512
2513         robptr = &Robot_info[objid];
2514
2515         //      Boost shield for Thief and Buddy based on level.
2516         objp->shields = robptr->strength;
2517
2518         if ((robptr->thief) || (robptr->companion)) {
2519                 objp->shields = (objp->shields * (abs(Current_level_num)+7))/8;
2520
2521                 if (robptr->companion) {
2522                         //      Now, scale guide-bot hits by skill level
2523                         switch (Difficulty_level) {
2524                                 case 0: objp->shields = i2f(20000);     break;          //      Trainee, basically unkillable
2525                                 case 1: objp->shields *= 3;                             break;          //      Rookie, pretty dang hard
2526                                 case 2: objp->shields *= 2;                             break;          //      Hotshot, a bit tough
2527                                 default:        break;
2528                         }
2529                 }
2530         } else if (robptr->boss_flag)   //      MK, 01/16/95, make boss shields lower on lower diff levels.
2531                 objp->shields = objp->shields/(NDL+3) * (Difficulty_level+4);
2532
2533         //      Additional wimpification of bosses at Trainee
2534         if ((robptr->boss_flag) && (Difficulty_level == 0))
2535                 objp->shields /= 2;
2536 }
2537
2538 //      -----------------------------------------------------------------------------------------------------
2539 //      Copy all values from the robot info structure to all instances of robots.
2540 //      This allows us to change bitmaps.tbl and have these changes manifested in existing robots.
2541 //      This function should be called at level load time.
2542 void copy_defaults_to_robot_all()
2543 {
2544         int     i;
2545
2546         for (i=0; i<=Highest_object_index; i++)
2547                 if (Objects[i].type == OBJ_ROBOT)
2548                         copy_defaults_to_robot(&Objects[i]);
2549
2550 }
2551
2552 extern void clear_stuck_objects(void);
2553
2554 //      -----------------------------------------------------------------------------------------------------
2555 //called when the player is starting a level (new game or new ship)
2556 void StartLevel(int random_flag)
2557 {
2558         Assert(!Player_is_dead);
2559
2560         InitPlayerPosition(random_flag);
2561
2562         verify_console_object();
2563
2564         ConsoleObject->control_type     = CT_FLYING;
2565         ConsoleObject->movement_type    = MT_PHYSICS;
2566
2567         disable_matcens();
2568
2569         clear_transient_objects(0);             //0 means leave proximity bombs
2570
2571         // create_player_appearance_effect(ConsoleObject);
2572         Do_appearance_effect = 1;
2573
2574 #ifdef NETWORK
2575         if (Game_mode & GM_MULTI)
2576         {
2577                 if (Game_mode & GM_MULTI_COOP)
2578                         multi_send_score();
2579                 multi_send_position(Players[Player_num].objnum);
2580                 multi_send_reappear();
2581         }               
2582
2583         if (Game_mode & GM_NETWORK)
2584                 network_do_frame(1, 1);
2585 #endif
2586
2587         ai_reset_all_paths();
2588         ai_init_boss_for_ship();
2589         clear_stuck_objects();
2590
2591         #ifdef EDITOR
2592         //      Note, this is only done if editor builtin.  Calling this from here
2593         //      will cause it to be called after the player dies, resetting the
2594         //      hits for the buddy and thief.  This is ok, since it will work ok
2595         //      in a shipped version.
2596         init_ai_objects();
2597         #endif
2598
2599         reset_time();
2600
2601         reset_rear_view();
2602         Auto_fire_fusion_cannon_time = 0;
2603         Fusion_charge = 0;
2604
2605         Robot_firing_enabled = 1;
2606 }