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