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