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