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