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