]> icculus.org git repositories - btb/d2x.git/blob - main/game.c
add command to load player
[btb/d2x.git] / main / game.c
1 /* $Id: game.c,v 1.44 2006-11-26 01:05:24 chris 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  * Game loop for Inferno
18  *
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #include <conf.h>
23 #endif
24
25 #ifdef RCS
26 char game_rcsid[] = "$Id: game.c,v 1.44 2006-11-26 01:05:24 chris Exp $";
27 #endif
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <stdarg.h>
33 #include <ctype.h>
34 #include <time.h>
35 #include <math.h>
36
37 #ifdef MACINTOSH
38 #include <Files.h>
39 #include <StandardFile.h>
40 #include <Quickdraw.h>
41 #include <Script.h>
42 #include <Strings.h>
43 #endif
44
45 #ifdef OGL
46 #include "ogl_init.h"
47 #endif
48
49 #include "pstypes.h"
50 #include "console.h"
51 #include "gr.h"
52 #include "inferno.h"
53 #include "game.h"
54 #include "key.h"
55 #include "object.h"
56 #include "physics.h"
57 #include "error.h"
58 #include "joy.h"
59 #include "mono.h"
60 #include "iff.h"
61 #include "pcx.h"
62 #include "timer.h"
63 #include "render.h"
64 #include "laser.h"
65 #include "screens.h"
66 #include "textures.h"
67 #include "slew.h"
68 #include "gauges.h"
69 #include "texmap.h"
70 #include "3d.h"
71 #include "effects.h"
72 #include "menu.h"
73 #include "gameseg.h"
74 #include "wall.h"
75 #include "ai.h"
76 #include "fuelcen.h"
77 #include "digi.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 "collide.h"
85 #include "weapon.h"
86 #include "sounds.h"
87 #include "args.h"
88 #include "gameseq.h"
89 #include "automap.h"
90 #include "text.h"
91 #include "powerup.h"
92 #include "fireball.h"
93 #include "newmenu.h"
94 #ifdef NETWORK
95 #include "network.h"
96 #endif
97 #include "gamefont.h"
98 #include "endlevel.h"
99 #include "joydefs.h"
100 #include "kconfig.h"
101 #include "mouse.h"
102 #include "switch.h"
103 #include "controls.h"
104 #include "songs.h"
105 #include "gamepal.h"
106
107 #include "multi.h"
108 #include "desc_id.h"
109 #include "cntrlcen.h"
110 #include "pcx.h"
111 #include "state.h"
112 #include "piggy.h"
113 #include "multibot.h"
114 #include "ai.h"
115 #include "robot.h"
116 #include "playsave.h"
117 #include "fix.h"
118 #include "hudmsg.h"
119
120 int VGA_current_mode;
121
122 #ifdef MWPROFILER
123 #include <profiler.h>
124 #endif
125
126 //#define TEST_TIMER    1               //if this is set, do checking on timer
127
128 #define SHOW_EXIT_PATH  1
129
130 #ifdef EDITOR
131 #include "editor/editor.h"
132 #endif
133
134 //#define _MARK_ON 1
135 #ifdef __WATCOMC__
136 #if __WATCOMC__ < 1000
137 #include <wsample.h>            //should come after inferno.h to get mark setting
138 #endif
139 #endif
140
141
142 extern void ReadControls(void);         // located in gamecntl.c
143 extern void do_final_boss_frame(void);
144
145 int     Speedtest_on = 0;
146
147 #ifndef NDEBUG
148 int     Mark_count = 0;                 // number of debugging marks set
149 int     Speedtest_start_time;
150 int     Speedtest_segnum;
151 int     Speedtest_sidenum;
152 int     Speedtest_frame_start;
153 int     Speedtest_count=0;                              //      number of times to do the debug test.
154 #endif
155
156 static fix last_timer_value=0;
157 fix ThisLevelTime=0;
158
159 #if defined(TIMER_TEST) && !defined(NDEBUG)
160 fix _timer_value,actual_last_timer_value,_last_frametime;
161 int stop_count,start_count;
162 int time_stopped,time_started;
163 #endif
164
165 int                     VR_screen_mode                  = 0;
166
167 ubyte                   VR_screen_flags = 0;            //see values in screens.h
168 ubyte                   VR_current_page = 0;
169 fix                     VR_eye_width            = F1_0;
170 int                     VR_render_mode          = VR_NONE;
171 int                     VR_low_res                      = 3;                            // Default to low res
172 int                     VR_show_hud = 1;
173 int                     VR_sensitivity     = 1;         // 0 - 2
174
175 //NEWVR
176 int                     VR_eye_offset            = 0;
177 int                     VR_eye_switch            = 0;
178 int                     VR_eye_offset_changed = 0;
179 int                     VR_use_reg_code         = 0;
180
181 grs_canvas  *VR_offscreen_buffer        = NULL;         // The offscreen data buffer
182 grs_canvas      VR_render_buffer[2];                                    //  Two offscreen buffers for left/right eyes.
183 grs_canvas      VR_render_sub_buffer[2];                        //  Two sub buffers for left/right eyes.
184 grs_canvas      VR_screen_pages[2];                                     //  Two pages of VRAM if paging is available
185 grs_canvas      VR_editor_canvas;                                               //  The canvas that the editor writes to.
186
187 //do menus work in 640x480 or 320x200?
188 //PC version sets this in main().  Mac versios is always high-res, so set to 1 here
189 int MenuHiresAvailable = 1;             //can we do highres menus?
190 int MenuHires = 1;                              //are we currently in highres menus?
191
192 int Debug_pause=0;                              //John's debugging pause system
193
194 int Cockpit_mode=CM_FULL_COCKPIT;               //set game.h for values
195
196 int Cockpit_mode_save=-1;                                       //set while in letterbox or rear view, or -1
197 int force_cockpit_redraw=0;
198
199 float oldfov;
200 cvar_t r_framerate = {"show_fps", "0"};
201 cvar_t cg_fov = {"fov", "30"};
202
203 int PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd;
204
205 //      Toggle_var points at a variable which gets !ed on ctrl-alt-T press.
206 int     Dummy_var;
207 int     *Toggle_var = &Dummy_var;
208
209 #ifdef EDITOR
210 //flag for whether initial fade-in has been done
211 char faded_in;
212 #endif
213
214 #ifndef NDEBUG                          //these only exist if debugging
215
216 int Game_double_buffer = 1;     //double buffer by default
217 fix fixed_frametime=0;          //if non-zero, set frametime to this
218
219 #endif
220
221 int Game_suspended=0;           //if non-zero, nothing moves but player
222
223 fix     RealFrameTime;
224 fix     Auto_fire_fusion_cannon_time = 0;
225 fix     Fusion_charge = 0;
226 fix     Fusion_next_sound_time = 0;
227 fix     Fusion_last_sound_time = 0;
228
229 int Debug_spew = 1;
230 int Game_turbo_mode = 0;
231
232 int Game_mode = GM_GAME_OVER;
233
234 int     Global_laser_firing_count = 0;
235 int     Global_missile_firing_count = 0;
236
237 grs_bitmap background_bitmap;
238
239 int Game_aborted;
240
241 #define BACKGROUND_NAME "statback.pcx"
242
243 //      Function prototypes for GAME.C exclusively.
244
245 void GameLoop(int RenderFlag, int ReadControlsFlag);
246 void FireLaser(void);
247 void slide_textures(void);
248 void powerup_grab_cheat_all(void);
249
250 //      Other functions
251 extern void multi_check_for_killgoal_winner();
252 extern void RestoreGameSurfaces();
253
254 // window functions
255
256 void grow_window(void);
257 void shrink_window(void);
258
259 // text functions
260
261 void fill_background();
262
263 #ifndef RELEASE
264 void show_framerate(void);
265 void ftoa(char *string, fix f);
266 #endif
267
268 extern ubyte DefiningMarkerMessage;
269 extern char Marker_input[];
270
271 //      ==============================================================================================
272
273 extern char john_head_on;
274
275 void load_background_bitmap()
276 {
277         ubyte pal[256*3];
278         int pcx_error;
279
280         if (background_bitmap.bm_data)
281                 d_free(background_bitmap.bm_data);
282
283         background_bitmap.bm_data=NULL;
284         pcx_error = pcx_read_bitmap(john_head_on?"johnhead.pcx":BACKGROUND_NAME,&background_bitmap,BM_LINEAR,pal);
285         if (pcx_error != PCX_ERROR_NONE)
286                 Error("File %s - PCX error: %s",BACKGROUND_NAME,pcx_errormsg(pcx_error));
287         gr_remap_bitmap_good( &background_bitmap, pal, -1, -1 );
288 }
289
290
291 /* load player */
292 void game_cmd_player(int argc, char **argv)
293 {
294         if (argc < 2)
295                 return;
296
297         strncpy(Players[Player_num].callsign, argv[1], CALLSIGN_LEN);
298
299         if (read_player_file() != EZERO) {
300                 con_printf(CON_CRITICAL, "player: unable to load player file");
301                 return;
302         }
303
304         WriteConfigFile();              // Update lastplr
305 }
306
307
308 /* load mission */
309 void game_cmd_map(int argc, char **argv)
310 {
311         int level_num = 1;
312
313         if (argc < 2)
314                 return;
315
316         if (!strlen(Players[Player_num].callsign)) {
317                 con_printf(CON_CRITICAL, "map: no player selected, not starting level\n");
318                 return;
319         }
320
321         load_mission_by_name(argv[1]);
322
323         if (argc > 2)
324                 level_num = atoi(argv[2]);
325
326         if (level_num == 0)
327                 level_num = 1;
328         if (level_num > Last_level)
329                 level_num = Last_level;
330         if (level_num < Last_secret_level)
331                 level_num = Last_secret_level;
332
333         StartNewGame(level_num);
334 }
335
336
337 //this is called once per game
338 void init_game()
339 {
340         atexit(close_game);             //for cleanup
341
342         init_objects();
343
344         init_special_effects();
345
346         init_ai_system();
347
348         init_exploding_walls();
349
350         load_background_bitmap();
351
352         Clear_window = 2;               //      do portal only window clear.
353
354         set_detail_level_parameters(Detail_level);
355
356         /* Register cvars */
357         cvar_registervariable(&r_framerate);
358         cvar_registervariable(&cg_fov);
359
360         /* Register cmds */
361         cmd_addcommand("map", game_cmd_map);
362         cmd_addcommand("player", game_cmd_player);
363 }
364
365
366 void reset_palette_add()
367 {
368         PaletteRedAdd           = 0;
369         PaletteGreenAdd = 0;
370         PaletteBlueAdd          = 0;
371         //gr_palette_step_up( PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd );
372 }
373
374
375 void game_show_warning(char *s)
376 {
377
378         if (!((Game_mode & GM_MULTI) && (Function_mode == FMODE_GAME)))
379                 stop_time();
380
381         nm_messagebox( TXT_WARNING, 1, TXT_OK, s );
382
383         if (!((Game_mode & GM_MULTI) && (Function_mode == FMODE_GAME)))
384                 start_time();
385 }
386
387
388 //these should be in gr.h
389 #define cv_w  cv_bitmap.bm_w
390 #define cv_h  cv_bitmap.bm_h
391
392 //added 3/24/99 by Owen Evans for screen res changing
393 u_int32_t Game_screen_mode = 0;
394 //end added - OE
395 int Game_window_x = 0;
396 int Game_window_y = 0;
397 int Game_window_w = 0;
398 int Game_window_h = 0;
399 int max_window_w = 0;
400 int max_window_h = 0;
401
402 extern void newdemo_record_cockpit_change(int);
403
404 //initialize the various canvases on the game screen
405 //called every time the screen mode or cockpit changes
406 void init_cockpit()
407 {
408 //      int minx, maxx, miny, maxy;
409
410         //Initialize the on-screen canvases
411
412         if (Newdemo_state==ND_STATE_RECORDING) {
413                 newdemo_record_cockpit_change(Cockpit_mode);
414         }
415
416         if ( VR_render_mode != VR_NONE )
417                 Cockpit_mode = CM_FULL_SCREEN;
418
419         if (!(VR_screen_flags & VRF_ALLOW_COCKPIT) && (Cockpit_mode==CM_FULL_COCKPIT || Cockpit_mode==CM_STATUS_BAR || Cockpit_mode==CM_REAR_VIEW) )
420                 Cockpit_mode = CM_FULL_SCREEN;
421
422         if ( Screen_mode == SCREEN_EDITOR )
423                 Cockpit_mode = CM_FULL_SCREEN;
424
425         gr_set_current_canvas(NULL);
426         gr_set_curfont( GAME_FONT );
427
428         switch( Cockpit_mode ) {
429         case CM_FULL_COCKPIT:
430         case CM_REAR_VIEW: {
431 #if 0
432                 grs_bitmap *bm = &GameBitmaps[cockpit_bitmap[Cockpit_mode+(SM_HIRES?(Num_cockpits/2):0)].index];
433
434                 PIGGY_PAGE_IN(cockpit_bitmap[Cockpit_mode+(SM_HIRES?(Num_cockpits/2):0)]);
435
436                 gr_set_current_canvas(VR_offscreen_buffer);
437
438                 gr_bitmap( 0, 0, bm );
439                 bm = &VR_offscreen_buffer->cv_bitmap;
440                 bm->bm_flags = BM_FLAG_TRANSPARENT;
441                 gr_ibitblt_find_hole_size ( bm, &minx, &miny, &maxx, &maxy );
442 #endif
443
444                 if (Cockpit_mode == CM_FULL_COCKPIT)
445                         game_init_render_sub_buffers(0, 0, grd_curscreen->sc_w, (grd_curscreen->sc_h*2)/3);
446                 else if (Cockpit_mode == CM_REAR_VIEW)
447                         game_init_render_sub_buffers((16*grd_curscreen->sc_w)/640, (89*grd_curscreen->sc_h)/480, (604*grd_curscreen->sc_w)/640, (209*grd_curscreen->sc_h)/480);
448                 break;
449         }
450
451         case CM_FULL_SCREEN:
452
453                 max_window_h = grd_curscreen->sc_h;
454
455                 if (Game_window_h > max_window_h || VR_screen_flags&VRF_ALLOW_COCKPIT)
456                         Game_window_h = max_window_h;
457
458                 if (Game_window_w > max_window_w || VR_screen_flags&VRF_ALLOW_COCKPIT)
459                         Game_window_w = max_window_w;
460
461                 Game_window_x = (max_window_w - Game_window_w)/2;
462                 Game_window_y = (max_window_h - Game_window_h)/2;
463
464                 game_init_render_sub_buffers( Game_window_x, Game_window_y, Game_window_w, Game_window_h );
465                 break;
466
467         case CM_STATUS_BAR:
468
469                 max_window_h = grd_curscreen->sc_h - GameBitmaps[cockpit_bitmap[CM_STATUS_BAR+(SM_HIRES?(Num_cockpits/2):0)].index].bm_h;
470
471                 if (Game_window_h > max_window_h)
472                         Game_window_h = max_window_h;
473
474                 if (Game_window_w > max_window_w)
475                         Game_window_w = max_window_w;
476
477                 Game_window_x = (max_window_w - Game_window_w)/2;
478                 Game_window_y = (max_window_h - Game_window_h)/2;
479
480                 game_init_render_sub_buffers( Game_window_x, Game_window_y, Game_window_w, Game_window_h );
481                 break;
482
483         case CM_LETTERBOX:      {
484                 int x,y,w,h;
485
486                 x = 0; w = VR_render_buffer[0].cv_bitmap.bm_w;          //VR_render_width;
487                 h = (VR_render_buffer[0].cv_bitmap.bm_h * 7) / 10;
488                 y = (VR_render_buffer[0].cv_bitmap.bm_h-h)/2;
489
490                 game_init_render_sub_buffers( x, y, w, h );
491                 break;
492                 }
493
494         }
495
496         gr_set_current_canvas(NULL);
497 }
498
499 //selects a given cockpit (or lack of one).  See types in game.h
500 void select_cockpit(int mode)
501 {
502         if (mode != Cockpit_mode) {             //new mode
503                 Cockpit_mode=mode;
504                 init_cockpit();
505         }
506 }
507
508 extern int last_drawn_cockpit[2];
509
510 //force cockpit redraw next time. call this if you've trashed the screen
511 void reset_cockpit()
512 {
513         force_cockpit_redraw=1;
514         last_drawn_cockpit[0] = -1;
515         last_drawn_cockpit[1] = -1;
516 }
517
518 // void HUD_clear_messages();                           //Already declared in gauges.h
519
520 //NEWVR
521 void VR_reset_params()
522 {
523         VR_eye_width = VR_SEPARATION;
524         VR_eye_offset = VR_PIXEL_SHIFT;
525         VR_eye_offset_changed = 2;
526 }
527
528 void game_init_render_sub_buffers( int x, int y, int w, int h )
529 {
530         gr_init_sub_canvas( &VR_render_sub_buffer[0], &VR_render_buffer[0], x, y, w, h );
531         gr_init_sub_canvas( &VR_render_sub_buffer[1], &VR_render_buffer[1], x, y, w, h );
532 }
533
534
535 // Sets up the canvases we will be rendering to (NORMAL VERSION)
536 void game_init_render_buffers(int screen_mode, int render_w, int render_h, int render_method, int flags )
537 {
538 //      if (vga_check_mode(screen_mode) != 0)
539 //              Error("Cannot set requested video mode");
540
541         VR_screen_mode          =       screen_mode;
542
543         VR_screen_flags =  flags;
544
545 //NEWVR
546         VR_reset_params();
547         VR_render_mode  = render_method;
548
549         Game_window_w           = render_w;
550         Game_window_h           = render_h;
551
552         if (VR_offscreen_buffer) {
553                 gr_free_canvas(VR_offscreen_buffer);
554         }
555
556         if ( (VR_render_mode==VR_AREA_DET) || (VR_render_mode==VR_INTERLACED ) )        {
557                 if ( render_h*2 < 200 ) {
558                         VR_offscreen_buffer = gr_create_canvas( render_w, 200 );
559                 }
560                 else {
561                         VR_offscreen_buffer = gr_create_canvas( render_w, render_h*2 );
562                 }
563
564                 gr_init_sub_canvas( &VR_render_buffer[0], VR_offscreen_buffer, 0, 0, render_w, render_h );
565                 gr_init_sub_canvas( &VR_render_buffer[1], VR_offscreen_buffer, 0, render_h, render_w, render_h );
566         }
567         else {
568                 if ( render_h < 200 ) {
569                         VR_offscreen_buffer = gr_create_canvas( render_w, 200 );
570                 }
571                 else {
572             VR_offscreen_buffer = gr_create_canvas( render_w, render_h );
573         }
574
575 #ifdef OGL
576                 VR_offscreen_buffer->cv_bitmap.bm_type = BM_OGL;
577 #endif
578
579                 gr_init_sub_canvas( &VR_render_buffer[0], VR_offscreen_buffer, 0, 0, render_w, render_h );
580                 gr_init_sub_canvas( &VR_render_buffer[1], VR_offscreen_buffer, 0, 0, render_w, render_h );
581         }
582
583         game_init_render_sub_buffers( 0, 0, render_w, render_h );
584 }
585
586 //called to get the screen in a mode compatible with popup menus.
587 //if we can't have popups over the game screen, switch to menu mode.
588 void set_popup_screen(void)
589 {
590         //WIN(LoadCursorWin(MOUSE_DEFAULT_CURSOR));
591
592 #ifndef OGL // always have to switch to menu mode
593         if (! (VR_screen_flags & VRF_COMPATIBLE_MENUS))
594 #endif
595         {
596                 set_screen_mode(SCREEN_MENU);           //must switch to menu mode
597         }
598 }
599
600
601 //called to change the screen mode. Parameter sm is the new mode, one of
602 //SMODE_GAME or SMODE_EDITOR. returns mode acutally set (could be other
603 //mode if cannot init requested mode)
604 int set_screen_mode(int sm)
605 {
606 #if 0 //def EDITOR
607         if ( (sm==SCREEN_MENU) && (Screen_mode==SCREEN_EDITOR) )        {
608                 gr_set_current_canvas( Canv_editor );
609                 return 1;
610         }
611 #endif
612
613         if ( Screen_mode == sm && VGA_current_mode == VR_screen_mode) {
614                 gr_set_current_canvas( &VR_screen_pages[VR_current_page] );
615                 return 1;
616         }
617
618 #ifdef OGL
619         if ((Screen_mode == sm) && !((sm==SCREEN_GAME) && (grd_curscreen->sc_mode != VR_screen_mode) && (Screen_mode == SCREEN_GAME))) {
620                 gr_set_current_canvas( &VR_screen_pages[VR_current_page] );
621                 ogl_set_screen_mode();
622                 return 1;
623         }
624 #endif
625
626 #ifdef EDITOR
627         Canv_editor = NULL;
628 #endif
629
630         Screen_mode = sm;
631
632         switch( Screen_mode )
633         {
634                 case SCREEN_MENU:
635                 {
636                         int menu_mode;
637
638                         MenuHires = MenuHiresAvailable;         //do highres if we can
639
640             menu_mode = MenuHires?SM(640,480):SM(320,200);
641
642                         if (VGA_current_mode != menu_mode) {
643                                 if (gr_set_mode(menu_mode))
644                                         Error("Cannot set screen mode for menu");
645                                 if (!gr_palette_faded_out)
646                                         gr_palette_load(gr_palette);
647                         }
648
649                         gr_init_sub_canvas( &VR_screen_pages[0], &grd_curscreen->sc_canvas, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h );
650                         gr_init_sub_canvas( &VR_screen_pages[1], &grd_curscreen->sc_canvas, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h );
651
652                         FontHires = FontHiresAvailable && MenuHires;
653
654                 }
655                 break;
656
657         case SCREEN_GAME:
658                 if (VGA_current_mode != VR_screen_mode) {
659                         if (gr_set_mode(VR_screen_mode))        {
660                                 Error("Cannot set desired screen mode for game!");
661                                 //we probably should do something else here, like select a standard mode
662                         }
663                         #ifdef MACINTOSH
664                         if ( (Config_control_type == 1) && (Function_mode == FMODE_GAME) )
665                                 joydefs_calibrate();
666                         #endif
667                         reset_cockpit();
668                 }
669
670                 if ( VR_render_mode == VR_NONE )
671                 {
672                         max_window_w = grd_curscreen->sc_w;
673                         max_window_h = grd_curscreen->sc_h;
674
675                         if (VR_screen_flags & VRF_ALLOW_COCKPIT) {
676                                 if (Cockpit_mode == CM_STATUS_BAR)
677                                         max_window_h = grd_curscreen->sc_h - GameBitmaps[cockpit_bitmap[CM_STATUS_BAR+(SM_HIRES?(Num_cockpits/2):0)].index].bm_h;
678                         }
679                         else if (Cockpit_mode != CM_LETTERBOX)
680                                 Cockpit_mode = CM_FULL_SCREEN;
681
682               if (Game_window_h==0 || Game_window_h > max_window_h || Game_window_w==0 || Game_window_w > max_window_w) {
683                                 Game_window_w = max_window_w;
684                                 Game_window_h = max_window_h;
685               }
686
687                 }
688                 else
689                         Cockpit_mode = CM_FULL_SCREEN;
690
691         //      Define screen pages for game mode
692         // If we designate through screen_flags to use paging, then do so.
693                 gr_init_sub_canvas( &VR_screen_pages[0], &grd_curscreen->sc_canvas, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h );
694
695                 if ( VR_screen_flags&VRF_USE_PAGING )
696                         gr_init_sub_canvas( &VR_screen_pages[1], &grd_curscreen->sc_canvas, 0, grd_curscreen->sc_h, grd_curscreen->sc_w, grd_curscreen->sc_h );
697                 else
698                         gr_init_sub_canvas( &VR_screen_pages[1], &grd_curscreen->sc_canvas, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h );
699
700                 init_cockpit();
701
702                 FontHires = FontHiresAvailable && (MenuHires = SM_HIRES2);
703
704                 if ( VR_render_mode != VR_NONE )        {
705                         // for 640x480 or higher, use hires font.
706                         if (FontHiresAvailable && (grd_curscreen->sc_h > 400))
707                                 FontHires = 1;
708                         else
709                                 FontHires = 0;
710                 }
711
712                 CON_InitGFX(grd_curscreen->sc_w, grd_curscreen->sc_h / 2);
713
714                 break;
715         #ifdef EDITOR
716         case SCREEN_EDITOR:
717                 if (grd_curscreen->sc_mode != SM(800,600))      {
718                         int gr_error;
719                         if ((gr_error=gr_set_mode(SM(800,600)))!=0) { //force into game scrren
720                                 Warning("Cannot init editor screen (error=%d)",gr_error);
721                                 return 0;
722                         }
723                 }
724                 gr_palette_load( gr_palette );
725
726                 gr_init_sub_canvas( &VR_editor_canvas, &grd_curscreen->sc_canvas, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h );
727                 Canv_editor = &VR_editor_canvas;
728                 gr_init_sub_canvas( &VR_screen_pages[0], Canv_editor, 0, 0, Canv_editor->cv_w, Canv_editor->cv_h );
729                 gr_init_sub_canvas( &VR_screen_pages[1], Canv_editor, 0, 0, Canv_editor->cv_w, Canv_editor->cv_h );
730                 gr_set_current_canvas( Canv_editor );
731                 init_editor_screen();   //setup other editor stuff
732                 break;
733         #endif
734         default:
735                 Error("Invalid screen mode %d",sm);
736         }
737
738         VR_current_page = 0;
739
740                 gr_set_current_canvas( &VR_screen_pages[VR_current_page] );
741
742         if ( VR_screen_flags&VRF_USE_PAGING )
743                 gr_show_canvas( &VR_screen_pages[VR_current_page] );
744 #ifdef OGL
745         ogl_set_screen_mode();
746 #endif
747
748         return 1;
749 }
750
751 int gr_toggle_fullscreen_game(void){
752 #ifdef GR_SUPPORTS_FULLSCREEN_TOGGLE
753         int i;
754         hud_message(MSGC_GAME_FEEDBACK, "toggling fullscreen mode %s",(i=gr_toggle_fullscreen())?"on":"off" );
755         //added 2000/06/19 Matthew Mueller - hack to fix "infinite toggle" problem
756         //it seems to be that the screen mode change takes long enough that the key has already sent repeat codes, or that its unpress event gets dropped, etc.  This is a somewhat ugly fix, but it works.
757 //      generic_key_handler(KEY_PADENTER,0);
758 //      generic_key_handler(KEY_ENTER, 0);
759         key_flush();
760         //end addition -MM
761         return i;
762 #else
763         hud_message(MSGC_GAME_FEEDBACK, "fullscreen toggle not supported by this target");
764         return -1;
765 #endif
766 }
767
768 int arch_toggle_fullscreen_menu(void);
769
770 int gr_toggle_fullscreen_menu(void){
771 #ifdef GR_SUPPORTS_FULLSCREEN_MENU_TOGGLE
772         int i;
773         i=arch_toggle_fullscreen_menu();
774
775 //      generic_key_handler(KEY_PADENTER,0);
776 //      generic_key_handler(KEY_ENTER, 0);
777         key_flush();
778
779         return i;
780 #else
781         return -1;
782 #endif
783 }
784
785 static int timer_paused=0;
786
787 void stop_time()
788 {
789         if (timer_paused==0) {
790                 fix time;
791                 time = timer_get_fixed_seconds();
792                 last_timer_value = time - last_timer_value;
793                 if (last_timer_value < 0) {
794                         #if defined(TIMER_TEST) && !defined(NDEBUG)
795                         Int3();         //get Matt!!!!
796                         #endif
797                         last_timer_value = 0;
798                 }
799                 #if defined(TIMER_TEST) && !defined(NDEBUG)
800                 time_stopped = time;
801                 #endif
802         }
803         timer_paused++;
804
805         #if defined(TIMER_TEST) && !defined(NDEBUG)
806         stop_count++;
807         #endif
808 }
809
810 void start_time()
811 {
812         timer_paused--;
813         Assert(timer_paused >= 0);
814         if (timer_paused==0) {
815                 fix time;
816                 time = timer_get_fixed_seconds();
817                 #if defined(TIMER_TEST) && !defined(NDEBUG)
818                 if (last_timer_value < 0)
819                         Int3();         //get Matt!!!!
820                 #endif
821                 last_timer_value = time - last_timer_value;
822                 #if defined(TIMER_TEST) && !defined(NDEBUG)
823                 time_started = time;
824                 #endif
825         }
826
827         #if defined(TIMER_TEST) && !defined(NDEBUG)
828         start_count++;
829         #endif
830 }
831
832 MAC(extern ubyte joydefs_calibrating;)
833
834 void game_flush_inputs()
835 {
836         int dx,dy;
837         key_flush();
838         joy_flush();
839         mouse_flush();
840         #ifdef MACINTOSH
841         if ( (Function_mode != FMODE_MENU) && !joydefs_calibrating )            // only reset mouse when not in menu or not calibrating
842         #endif
843                 mouse_get_delta( &dx, &dy );    // Read mouse
844         memset(&Controls,0,sizeof(control_info));
845 }
846
847 void reset_time()
848 {
849         last_timer_value = timer_get_fixed_seconds();
850
851 }
852
853 #ifndef RELEASE
854 extern int Saving_movie_frames;
855 int Movie_fixed_frametime;
856 #else
857 #define Saving_movie_frames     0
858 #define Movie_fixed_frametime   0
859 #endif
860
861 //added on 8/18/98 by Victor Rachels to add maximum framerate
862 int maxfps = MAX_FPS;
863 //end this section
864
865 void calc_frame_time()
866 {
867         fix timer_value,last_frametime = FrameTime;
868
869         #if defined(TIMER_TEST) && !defined(NDEBUG)
870         _last_frametime = last_frametime;
871         #endif
872
873         timer_value = timer_get_fixed_seconds();
874         FrameTime = timer_value - last_timer_value;
875
876         while (FrameTime < f1_0 / maxfps)
877         {
878                 timer_delay(f1_0 / maxfps - FrameTime);
879                 timer_value = timer_get_fixed_seconds();
880                 FrameTime = timer_value - last_timer_value;
881         }
882
883         #if defined(TIMER_TEST) && !defined(NDEBUG)
884         _timer_value = timer_value;
885         #endif
886
887         #ifndef NDEBUG
888         if (!(((FrameTime > 0) && (FrameTime <= F1_0)) || (Function_mode == FMODE_EDITOR) || (Newdemo_state == ND_STATE_PLAYBACK))) {
889                 mprintf((1,"Bad FrameTime - value = %x\n",FrameTime));
890                 if (FrameTime == 0)
891                         Int3(); //      Call Mike or Matt or John!  Your interrupts are probably trashed!
892 //              if ( !dpmi_virtual_memory )
893 //                      Int3();         //Get MATT if hit this!
894         }
895         #endif
896
897         #if defined(TIMER_TEST) && !defined(NDEBUG)
898         actual_last_timer_value = last_timer_value;
899         #endif
900
901         if ( Game_turbo_mode )
902                 FrameTime *= 2;
903
904         // Limit frametime to be between 5 and 150 fps.
905         RealFrameTime = FrameTime;
906         if ( FrameTime < F1_0/150 ) FrameTime = F1_0/150;
907         if ( FrameTime > F1_0/5 ) FrameTime = F1_0/5;
908
909         last_timer_value = timer_value;
910
911         if (FrameTime < 0)                                              //if bogus frametime...
912                 FrameTime = last_frametime;             //...then use time from last frame
913
914         #ifndef NDEBUG
915         if (fixed_frametime) FrameTime = fixed_frametime;
916         #endif
917
918         #ifndef NDEBUG
919         // Pause here!!!
920         if ( Debug_pause )      {
921                 int c;
922                 c = 0;
923                 while( c==0 )
924                         c = key_peekkey();
925
926                 if ( c == KEY_P )       {
927                         Debug_pause = 0;
928                         c = key_inkey();
929                 }
930                 last_timer_value = timer_get_fixed_seconds();
931         }
932         #endif
933
934         #if Arcade_mode
935                 FrameTime /= 2;
936         #endif
937
938         #if defined(TIMER_TEST) && !defined(NDEBUG)
939         stop_count = start_count = 0;
940         #endif
941
942         //      Set value to determine whether homing missile can see target.
943         //      The lower frametime is, the more likely that it can see its target.
944         if (FrameTime <= F1_0/64)
945                 Min_trackable_dot = MIN_TRACKABLE_DOT;  // -- 3*(F1_0 - MIN_TRACKABLE_DOT)/4 + MIN_TRACKABLE_DOT;
946         else if (FrameTime < F1_0/32)
947                 Min_trackable_dot = MIN_TRACKABLE_DOT + F1_0/64 - 2*FrameTime;  // -- fixmul(F1_0 - MIN_TRACKABLE_DOT, F1_0-4*FrameTime) + MIN_TRACKABLE_DOT;
948         else if (FrameTime < F1_0/4)
949                 Min_trackable_dot = MIN_TRACKABLE_DOT + F1_0/64 - F1_0/16 - FrameTime;  // -- fixmul(F1_0 - MIN_TRACKABLE_DOT, F1_0-4*FrameTime) + MIN_TRACKABLE_DOT;
950         else
951                 Min_trackable_dot = MIN_TRACKABLE_DOT + F1_0/64 - F1_0/8;
952
953 }
954
955 //--unused-- int Auto_flythrough=0;  //if set, start flythough automatically
956
957 void move_player_2_segment(segment *seg,int side)
958 {
959         vms_vector vp;
960
961         compute_segment_center(&ConsoleObject->pos,seg);
962         compute_center_point_on_side(&vp,seg,side);
963         vm_vec_sub2(&vp,&ConsoleObject->pos);
964         vm_vector_2_matrix(&ConsoleObject->orient,&vp,NULL,NULL);
965
966         obj_relink( OBJECT_NUMBER(ConsoleObject), SEG_PTR_2_NUM(seg) );
967
968 }
969
970 #ifdef NETWORK
971 void game_draw_time_left()
972 {
973         char temp_string[30];
974         fix timevar;
975         int i;
976
977         gr_set_curfont( GAME_FONT );    //GAME_FONT
978         gr_set_fontcolor(gr_getcolor(0,63,0), -1 );
979
980         timevar=i2f (Netgame.PlayTimeAllowed*5*60);
981         i=f2i(timevar-ThisLevelTime);
982         i++;
983
984         sprintf( temp_string, "Time left: %d secs", i );
985
986         if (i>=0)
987          gr_string(0, 32, temp_string );
988 }
989 #endif
990
991
992 extern int Game_pause;
993
994 void do_photos();
995 void level_with_floor();
996
997 void modex_clear_box(int x,int y,int w,int h)
998 {
999         grs_canvas *temp_canv,*save_canv;
1000
1001         save_canv = grd_curcanv;
1002         temp_canv = gr_create_canvas(w,h);
1003         gr_set_current_canvas(temp_canv);
1004         gr_clear_canvas(BM_XRGB(0,0,0));
1005         gr_set_current_canvas(save_canv);
1006         gr_bitmapm(x,y,&temp_canv->cv_bitmap);
1007         gr_free_canvas(temp_canv);
1008
1009 }
1010
1011 extern void modex_printf(int x,int y,char *s,grs_font *font,int color);
1012
1013 // mac routine to drop contents of screen to a pict file using copybits
1014 // save a PICT to a file
1015 #ifdef MACINTOSH
1016
1017 void SavePictScreen(int multiplayer)
1018 {
1019         OSErr err;
1020         int parid, i, count;
1021         char *pfilename, filename[50], buf[512], cwd[FILENAME_MAX];
1022         short fd;
1023         FSSpec spec;
1024         PicHandle pict_handle;
1025         static int multi_count = 0;
1026         StandardFileReply sf_reply;
1027         
1028 // dump the contents of the GameWindow into a picture using copybits
1029
1030         pict_handle = OpenPicture(&GameWindow->portRect);
1031         if (pict_handle == NULL)
1032                 return;
1033                 
1034         CopyBits(&GameWindow->portBits, &GameWindow->portBits, &GameWindow->portRect, &GameWindow->portRect, srcBic, NULL);
1035         ClosePicture();
1036
1037 // get the cwd to restore with chdir when done -- this keeps the mac world sane
1038         if (!getcwd(cwd, FILENAME_MAX))
1039                 Int3();
1040 // create the fsspec
1041
1042         sprintf(filename, "screen%d", multi_count++);
1043         pfilename = c2pstr(filename);
1044         if (!multiplayer) {
1045                 show_cursor();
1046                 StandardPutFile("\pSave PICT as:", pfilename, &sf_reply);
1047                 if (!sf_reply.sfGood)
1048                         goto end;
1049                 memcpy( &spec, &(sf_reply.sfFile), sizeof(FSSpec) );
1050                 if (sf_reply.sfReplacing)
1051                         FSpDelete(&spec);
1052                 err = FSpCreate( &spec, 'ttxt', 'PICT', smSystemScript );
1053                 if (err)
1054                         goto end;
1055         } else {
1056 //              parid = GetAppDirId();
1057                 err = FSMakeFSSpec(0, 0, pfilename, &spec);
1058                 if (err == nsvErr)
1059                         goto end;
1060                 if (err != fnfErr)
1061                         FSpDelete(&spec);
1062                 err = FSpCreate(&spec, 'ttxt', 'PICT', smSystemScript);
1063                 if (err != 0)
1064                         goto end;
1065         }
1066
1067 // write the PICT file
1068         if ( FSpOpenDF(&spec, fsRdWrPerm, &fd) )
1069                 goto end;
1070         memset(buf, 0, sizeof(buf));
1071         count = 512;
1072         if ( FSWrite(fd, &count, buf) )
1073                 goto end;
1074         count = GetHandleSize((Handle)pict_handle);
1075         HLock((Handle)pict_handle);
1076         if ( FSWrite(fd, &count, *pict_handle) ) {
1077                 FSClose(fd);
1078                 FSpDelete(&spec);
1079         }
1080
1081 end:
1082         HUnlock((Handle)pict_handle);
1083         DisposeHandle((Handle)pict_handle);
1084         FSClose(fd);
1085         hide_cursor();
1086         chdir(cwd);
1087 }
1088
1089 #endif
1090
1091 //automap_flag is now unused, since we just check if the screen we're
1092 //writing to is modex
1093 //if called from automap, current canvas is set to visible screen
1094 #ifndef OGL
1095 void save_screen_shot(int automap_flag)
1096 {
1097 #if !defined(MACINTOSH)
1098         fix t1;
1099         char message[100];
1100         grs_canvas *screen_canv=&grd_curscreen->sc_canvas;
1101         grs_font *save_font;
1102         static int savenum=0;
1103         static int stereo_savenum=0;
1104         grs_canvas *temp_canv,*temp_canv2,*save_canv;
1105         char savename[FILENAME_LEN],savename2[FILENAME_LEN];
1106         ubyte pal[768];
1107         int w,h,aw,x,y;
1108         int modex_flag;
1109         int stereo=0;
1110
1111         temp_canv2=NULL;
1112
1113 //      // Can't do screen shots in VR modes.
1114 //      if ( VR_render_mode != VR_NONE )
1115 //              return;
1116
1117         stop_time();
1118
1119         save_canv = grd_curcanv;
1120
1121         if ( VR_render_mode != VR_NONE && !automap_flag && Function_mode==FMODE_GAME && Screen_mode==SCREEN_GAME)
1122                 stereo = 1;
1123
1124         if ( stereo ) {
1125                 temp_canv = gr_create_canvas(VR_render_buffer[0].cv_bitmap.bm_w,VR_render_buffer[0].cv_bitmap.bm_h);
1126                 gr_set_current_canvas(temp_canv);
1127                 gr_ubitmap(0,0,&VR_render_buffer[0].cv_bitmap);
1128
1129                 temp_canv2 = gr_create_canvas(VR_render_buffer[1].cv_bitmap.bm_w,VR_render_buffer[1].cv_bitmap.bm_h);
1130                 gr_set_current_canvas(temp_canv2);
1131                 gr_ubitmap(0,0,&VR_render_buffer[1].cv_bitmap);
1132         }
1133         else {
1134                 temp_canv = gr_create_canvas(screen_canv->cv_bitmap.bm_w,screen_canv->cv_bitmap.bm_h);
1135                 gr_set_current_canvas(temp_canv);
1136                 gr_ubitmap(0,0,&screen_canv->cv_bitmap);
1137         }
1138
1139         gr_set_current_canvas(save_canv);
1140
1141         if ( savenum > 99 ) savenum = 0;
1142         if ( stereo_savenum > 99 ) stereo_savenum = 0;
1143
1144         if ( stereo ) {
1145                 sprintf(savename,"left%02d.pcx",stereo_savenum);
1146                 sprintf(savename2,"right%02d.pcx",stereo_savenum);
1147                 if (VR_eye_switch) {char t[FILENAME_LEN]; strcpy(t,savename); strcpy(savename,savename2); strcpy(savename2,t);}
1148                 stereo_savenum++;
1149                 sprintf( message, "%s '%s' & '%s'", TXT_DUMPING_SCREEN, savename, savename2 );
1150         }
1151         else {
1152                 sprintf(savename,"screen%02d.pcx",savenum++);
1153                 sprintf( message, "%s '%s'", TXT_DUMPING_SCREEN, savename );
1154         }
1155
1156         if (!automap_flag)              //if from automap, curcanv is already visible canv
1157                 gr_set_current_canvas(NULL);
1158         modex_flag = (grd_curcanv->cv_bitmap.bm_type==BM_MODEX);
1159         if (!automap_flag && modex_flag)
1160                 gr_set_current_canvas(&VR_screen_pages[VR_current_page]);
1161
1162         save_font = grd_curcanv->cv_font;
1163         gr_set_curfont(GAME_FONT);
1164         gr_set_fontcolor(gr_find_closest_color_current(0,31,0),-1);
1165         gr_get_string_size(message,&w,&h,&aw);
1166
1167         if (modex_flag)
1168                 h *= 2;
1169
1170         //I changed how these coords were calculated for the high-res automap. -MT
1171         //x = (VR_screen_pages[VR_current_page].cv_w-w)/2;
1172         //y = (VR_screen_pages[VR_current_page].cv_h-h)/2;
1173         x = (grd_curcanv->cv_w-w)/2;
1174         y = (grd_curcanv->cv_h-h)/2;
1175
1176         if (modex_flag) {
1177                 modex_clear_box(x-2,y-2,w+4,h+4);
1178                 modex_printf(x, y, message,GAME_FONT,gr_find_closest_color_current(0,31,0));
1179         } else {
1180                 gr_setcolor(gr_find_closest_color_current(0,0,0));
1181                 gr_rect(x-2,y-2,x+w+2,y+h+2);
1182                 gr_printf(x,y,message);
1183                 gr_set_curfont(save_font);
1184         }
1185         t1 = timer_get_fixed_seconds() + F1_0;
1186
1187         gr_palette_read(pal);           //get actual palette from the hardware
1188         pcx_write_bitmap(savename,&temp_canv->cv_bitmap,pal);
1189         if ( stereo )
1190                 pcx_write_bitmap(savename2,&temp_canv2->cv_bitmap,pal);
1191
1192         while ( timer_get_fixed_seconds() < t1 );               // Wait so that messag stays up at least 1 second.
1193
1194         gr_set_current_canvas(screen_canv);
1195
1196         if (grd_curcanv->cv_bitmap.bm_type!=BM_MODEX && !stereo)
1197                 gr_ubitmap(0,0,&temp_canv->cv_bitmap);
1198
1199         gr_free_canvas(temp_canv);
1200         if ( stereo )
1201                 gr_free_canvas(temp_canv2);
1202
1203         gr_set_current_canvas(save_canv);
1204         key_flush();
1205         start_time();
1206         
1207 #else
1208
1209         grs_canvas *screen_canv = &grd_curscreen->sc_canvas;
1210         grs_canvas *temp_canv, *save_canv;
1211         
1212         // Can't do screen shots in VR modes.
1213         if ( VR_render_mode != VR_NONE )
1214                 return;
1215
1216         stop_time();
1217
1218         save_canv = grd_curcanv;        
1219         temp_canv = gr_create_canvas( screen_canv->cv_bitmap.bm_w, screen_canv->cv_bitmap.bm_h );
1220         if (!temp_canv)
1221                 goto shot_done;
1222         gr_set_current_canvas( temp_canv );
1223         gr_ubitmap( 0, 0, &screen_canv->cv_bitmap );
1224         gr_set_current_canvas( &VR_screen_pages[VR_current_page] );
1225
1226         show_cursor();
1227         key_close();
1228         if (Game_mode & GM_MULTI)
1229                 SavePictScreen(1);
1230         else
1231                 SavePictScreen(0);
1232         key_init();
1233         hide_cursor();
1234
1235         gr_set_current_canvas(screen_canv);
1236         
1237 //      if (!automap_flag)
1238                 gr_ubitmap( 0, 0, &temp_canv->cv_bitmap);
1239
1240         gr_free_canvas(temp_canv);
1241 shot_done:
1242         gr_set_current_canvas(save_canv);
1243         key_flush();
1244         start_time();
1245         #endif
1246 }
1247
1248 #endif
1249
1250 //initialize flying
1251 void fly_init(object *obj)
1252 {
1253         obj->control_type = CT_FLYING;
1254         obj->movement_type = MT_PHYSICS;
1255
1256         vm_vec_zero(&obj->mtype.phys_info.velocity);
1257         vm_vec_zero(&obj->mtype.phys_info.thrust);
1258         vm_vec_zero(&obj->mtype.phys_info.rotvel);
1259         vm_vec_zero(&obj->mtype.phys_info.rotthrust);
1260 }
1261
1262 //void morph_test(), morph_step();
1263
1264
1265 //      ------------------------------------------------------------------------------------
1266
1267 void test_anim_states();
1268
1269 #include "fvi.h"
1270
1271 //put up the help message
1272 void do_show_help()
1273 {
1274         show_help();
1275 }
1276
1277
1278 extern int been_in_editor;
1279
1280 //      ------------------------------------------------------------------------------------
1281 void do_cloak_stuff(void)
1282 {
1283         int i;
1284         for (i = 0; i < N_players; i++)
1285                 if (Players[i].flags & PLAYER_FLAGS_CLOAKED) {
1286                         // mprintf(0, "Cloak time left: %7.3f\n", f2fl(CLOAK_TIME_MAX - (GameTime - Players[Player_num].cloak_time)));
1287                         if (GameTime - Players[i].cloak_time > CLOAK_TIME_MAX) {
1288                                 Players[i].flags &= ~PLAYER_FLAGS_CLOAKED;
1289                                 if (i == Player_num) {
1290                                         digi_play_sample( SOUND_CLOAK_OFF, F1_0);
1291                                         #ifdef NETWORK
1292                                         if (Game_mode & GM_MULTI)
1293                                                 multi_send_play_sound(SOUND_CLOAK_OFF, F1_0);
1294                                         maybe_drop_net_powerup(POW_CLOAK);
1295                                         multi_send_decloak(); // For demo recording
1296                                         #endif
1297 //                                      mprintf((0, " --- You have been DE-CLOAKED! ---\n"));
1298                                 }
1299                         }
1300                 }
1301 }
1302
1303 int FakingInvul=0;
1304
1305 //      ------------------------------------------------------------------------------------
1306 void do_invulnerable_stuff(void)
1307 {
1308         if (Players[Player_num].flags & PLAYER_FLAGS_INVULNERABLE) {
1309                 if (GameTime - Players[Player_num].invulnerable_time > INVULNERABLE_TIME_MAX) {
1310                         Players[Player_num].flags ^= PLAYER_FLAGS_INVULNERABLE;
1311                         if (FakingInvul==0)
1312                         {
1313                                 digi_play_sample( SOUND_INVULNERABILITY_OFF, F1_0);
1314                                 #ifdef NETWORK
1315                                 if (Game_mode & GM_MULTI)
1316                                 {
1317                                         multi_send_play_sound(SOUND_INVULNERABILITY_OFF, F1_0);
1318                                         maybe_drop_net_powerup(POW_INVULNERABILITY);
1319                                 }
1320                                 #endif
1321                                 mprintf((0, " --- You have been DE-INVULNERABLEIZED! ---\n"));
1322                         }
1323                         FakingInvul=0;
1324                 }
1325         }
1326 }
1327
1328 ubyte   Last_afterburner_state = 0;
1329 fix Last_afterburner_charge = 0;
1330
1331 #define AFTERBURNER_LOOP_START  ((digi_sample_rate==SAMPLE_RATE_22K)?32027:(32027/2))           //20098
1332 #define AFTERBURNER_LOOP_END            ((digi_sample_rate==SAMPLE_RATE_22K)?48452:(48452/2))           //25776
1333
1334 int     Ab_scale = 4;
1335
1336 //@@//  ------------------------------------------------------------------------------------
1337 //@@void afterburner_shake(void)
1338 //@@{
1339 //@@    int     rx, rz;
1340 //@@
1341 //@@    rx = (Ab_scale * fixmul(d_rand() - 16384, F1_0/8 + (((GameTime + 0x4000)*4) & 0x3fff)))/16;
1342 //@@    rz = (Ab_scale * fixmul(d_rand() - 16384, F1_0/2 + ((GameTime*4) & 0xffff)))/16;
1343 //@@
1344 //@@    // -- mprintf((0, "AB: %8x %8x\n", rx, rz));
1345 //@@    ConsoleObject->mtype.phys_info.rotvel.x += rx;
1346 //@@    ConsoleObject->mtype.phys_info.rotvel.z += rz;
1347 //@@
1348 //@@}
1349
1350 //      ------------------------------------------------------------------------------------
1351 #ifdef NETWORK
1352 extern void multi_send_sound_function (char,char);
1353 #endif
1354
1355 void do_afterburner_stuff(void)
1356 {
1357    if (!(Players[Player_num].flags & PLAYER_FLAGS_AFTERBURNER))
1358                 Afterburner_charge=0;
1359
1360         if (Endlevel_sequence || Player_is_dead)
1361                 {
1362                  digi_kill_sound_linked_to_object( Players[Player_num].objnum);
1363 #ifdef NETWORK
1364                  multi_send_sound_function (0,0);
1365 #endif
1366                 }
1367
1368         if ((Controls.afterburner_state != Last_afterburner_state && Last_afterburner_charge) || (Last_afterburner_state && Last_afterburner_charge && !Afterburner_charge)) {
1369
1370                 if (Afterburner_charge && Controls.afterburner_state && (Players[Player_num].flags & PLAYER_FLAGS_AFTERBURNER)) {
1371                         digi_link_sound_to_object3( SOUND_AFTERBURNER_IGNITE, Players[Player_num].objnum, 1, F1_0, i2f(256), AFTERBURNER_LOOP_START, AFTERBURNER_LOOP_END );
1372 #ifdef NETWORK
1373                         if (Game_mode & GM_MULTI)
1374                                 multi_send_sound_function (3,SOUND_AFTERBURNER_IGNITE);
1375 #endif
1376                 } else {
1377                         digi_kill_sound_linked_to_object( Players[Player_num].objnum);
1378                         digi_link_sound_to_object2( SOUND_AFTERBURNER_PLAY, Players[Player_num].objnum, 0, F1_0, i2f(256));
1379 #ifdef NETWORK
1380                         if (Game_mode & GM_MULTI)
1381                                 multi_send_sound_function (0,0);
1382 #endif
1383                         mprintf((0,"Killing afterburner sound\n"));
1384                 }
1385         }
1386
1387         //@@if (Controls.afterburner_state && Afterburner_charge)
1388         //@@    afterburner_shake();
1389
1390         Last_afterburner_state = Controls.afterburner_state;
1391         Last_afterburner_charge = Afterburner_charge;
1392 }
1393
1394 // -- //        ------------------------------------------------------------------------------------
1395 // -- //        if energy < F1_0/2, recharge up to F1_0/2
1396 // -- void recharge_energy_frame(void)
1397 // -- {
1398 // --   if (Players[Player_num].energy < Weapon_info[0].energy_usage) {
1399 // --           Players[Player_num].energy += FrameTime/4;
1400 // --
1401 // --           if (Players[Player_num].energy > Weapon_info[0].energy_usage)
1402 // --                   Players[Player_num].energy = Weapon_info[0].energy_usage;
1403 // --   }
1404 // -- }
1405
1406 //      Amount to diminish guns towards normal, per second.
1407 #define DIMINISH_RATE   16              //      gots to be a power of 2, else change the code in diminish_palette_towards_normal
1408
1409 extern fix Flash_effect;
1410
1411  //adds to rgb values for palette flash
1412 void PALETTE_FLASH_ADD(int _dr,int _dg,int _db)
1413 {
1414         int     maxval;
1415
1416         PaletteRedAdd += _dr;
1417         PaletteGreenAdd += _dg;
1418         PaletteBlueAdd += _db;
1419
1420         // -- mprintf((0, "Palette add: %3i %3i %3i\n", PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd));
1421
1422         if (Flash_effect)
1423                 maxval = 60;
1424         else
1425                 maxval = MAX_PALETTE_ADD;
1426
1427         if (PaletteRedAdd > maxval)
1428                 PaletteRedAdd = maxval;
1429
1430         if (PaletteGreenAdd > maxval)
1431                 PaletteGreenAdd = maxval;
1432
1433         if (PaletteBlueAdd > maxval)
1434                 PaletteBlueAdd = maxval;
1435
1436         if (PaletteRedAdd < -maxval)
1437                 PaletteRedAdd = -maxval;
1438
1439         if (PaletteGreenAdd < -maxval)
1440                 PaletteGreenAdd = -maxval;
1441
1442         if (PaletteBlueAdd < -maxval)
1443                 PaletteBlueAdd = -maxval;
1444 }
1445
1446 fix     Time_flash_last_played;
1447
1448
1449 void game_palette_step_up( int r, int g, int b );
1450 //      ------------------------------------------------------------------------------------
1451 //      Diminish palette effects towards normal.
1452 void diminish_palette_towards_normal(void)
1453 {
1454         int     dec_amount = 0;
1455
1456         //      Diminish at DIMINISH_RATE units/second.
1457         //      For frame rates > DIMINISH_RATE Hz, use randomness to achieve this.
1458         if (FrameTime < F1_0/DIMINISH_RATE) {
1459                 if (d_rand() < FrameTime*DIMINISH_RATE/2)       //      Note: d_rand() is in 0..32767, and 8 Hz means decrement every frame
1460                         dec_amount = 1;
1461         } else {
1462                 dec_amount = f2i(FrameTime*DIMINISH_RATE);              // one second = DIMINISH_RATE counts
1463                 if (dec_amount == 0)
1464                         dec_amount++;                                           // make sure we decrement by something
1465         }
1466
1467         if (Flash_effect) {
1468                 int     force_do = 0;
1469
1470                 //      Part of hack system to force update of palette after exiting a menu.
1471                 if (Time_flash_last_played) {
1472                         force_do = 1;
1473                         PaletteRedAdd ^= 1;     //      Very Tricky!  In gr_palette_step_up, if all stepups same as last time, won't do anything!
1474                 }
1475
1476                 if ((Time_flash_last_played + F1_0/8 < GameTime) || (Time_flash_last_played > GameTime)) {
1477                         digi_play_sample( SOUND_CLOAK_OFF, Flash_effect/4);
1478                         Time_flash_last_played = GameTime;
1479                 }
1480
1481                 Flash_effect -= FrameTime;
1482                 if (Flash_effect < 0)
1483                         Flash_effect = 0;
1484
1485                 if (force_do || (d_rand() > 4096 )) {
1486         if ( (Newdemo_state==ND_STATE_RECORDING) && (PaletteRedAdd || PaletteGreenAdd || PaletteBlueAdd) )
1487                 newdemo_record_palette_effect(PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd);
1488
1489                         game_palette_step_up( PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd );
1490
1491                         return;
1492                 }
1493
1494         }
1495
1496         if (PaletteRedAdd > 0 ) { PaletteRedAdd -= dec_amount; if (PaletteRedAdd < 0 ) PaletteRedAdd = 0; }
1497         if (PaletteRedAdd < 0 ) { PaletteRedAdd += dec_amount; if (PaletteRedAdd > 0 ) PaletteRedAdd = 0; }
1498
1499         if (PaletteGreenAdd > 0 ) { PaletteGreenAdd -= dec_amount; if (PaletteGreenAdd < 0 ) PaletteGreenAdd = 0; }
1500         if (PaletteGreenAdd < 0 ) { PaletteGreenAdd += dec_amount; if (PaletteGreenAdd > 0 ) PaletteGreenAdd = 0; }
1501
1502         if (PaletteBlueAdd > 0 ) { PaletteBlueAdd -= dec_amount; if (PaletteBlueAdd < 0 ) PaletteBlueAdd = 0; }
1503         if (PaletteBlueAdd < 0 ) { PaletteBlueAdd += dec_amount; if (PaletteBlueAdd > 0 ) PaletteBlueAdd = 0; }
1504
1505         if ( (Newdemo_state==ND_STATE_RECORDING) && (PaletteRedAdd || PaletteGreenAdd || PaletteBlueAdd) )
1506                 newdemo_record_palette_effect(PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd);
1507
1508         game_palette_step_up( PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd );
1509
1510         //mprintf(0, "%2i %2i %2i\n", PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd);
1511 }
1512
1513 int     Redsave, Bluesave, Greensave;
1514
1515 void palette_save(void)
1516 {
1517         Redsave = PaletteRedAdd; Bluesave = PaletteBlueAdd; Greensave = PaletteGreenAdd;
1518 }
1519
1520 extern void gr_palette_step_up_vr( int r, int g, int b, int white, int black );
1521
1522 void game_palette_step_up( int r, int g, int b )
1523 {
1524         if ( VR_use_reg_code )  {
1525 //              gr_palette_step_up_vr( r, g, b, VR_WHITE_INDEX, VR_BLACK_INDEX );
1526         } else {
1527                 gr_palette_step_up( r, g, b );
1528         }
1529 }
1530
1531 void palette_restore(void)
1532 {
1533         PaletteRedAdd = Redsave; PaletteBlueAdd = Bluesave; PaletteGreenAdd = Greensave;
1534         game_palette_step_up( PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd );
1535
1536         //      Forces flash effect to fixup palette next frame.
1537         Time_flash_last_played = 0;
1538 }
1539
1540 extern void dead_player_frame(void);
1541
1542
1543 //      --------------------------------------------------------------------------------------------------
1544 int allowed_to_fire_laser(void)
1545 {
1546         if (Player_is_dead) {
1547                 Global_missile_firing_count = 0;
1548                 return 0;
1549         }
1550
1551         //      Make sure enough time has elapsed to fire laser, but if it looks like it will
1552         //      be a long while before laser can be fired, then there must be some mistake!
1553         if (Next_laser_fire_time > GameTime)
1554                 if (Next_laser_fire_time < GameTime + 2*F1_0)
1555                         return 0;
1556
1557         return 1;
1558 }
1559
1560 fix     Next_flare_fire_time = 0;
1561 #define FLARE_BIG_DELAY (F1_0*2)
1562
1563 int allowed_to_fire_flare(void)
1564 {
1565         if (Next_flare_fire_time > GameTime)
1566                 if (Next_flare_fire_time < GameTime + FLARE_BIG_DELAY)  //      In case time is bogus, never wait > 1 second.
1567                         return 0;
1568
1569         if (Players[Player_num].energy >= Weapon_info[FLARE_ID].energy_usage)
1570                 Next_flare_fire_time = GameTime + F1_0/4;
1571         else
1572                 Next_flare_fire_time = GameTime + FLARE_BIG_DELAY;
1573
1574         return 1;
1575 }
1576
1577 int allowed_to_fire_missile(void)
1578 {
1579 // mprintf(0, "Next fire = %7.3f, Cur time = %7.3f\n", f2fl(Next_missile_fire_time), f2fl(GameTime));
1580         //      Make sure enough time has elapsed to fire missile, but if it looks like it will
1581         //      be a long while before missile can be fired, then there must be some mistake!
1582         if (Next_missile_fire_time > GameTime)
1583                 if (Next_missile_fire_time < GameTime + 5*F1_0)
1584                         return 0;
1585
1586         return 1;
1587 }
1588
1589 void full_palette_save(void)
1590 {
1591         palette_save();
1592         apply_modified_palette();
1593         reset_palette_add();
1594         gr_palette_load( gr_palette );
1595 }
1596
1597 extern int Death_sequence_aborted;
1598 extern int newmenu_dotiny2( char * title, char * subtitle, int nitems, newmenu_item * item, void (*subfunction)(int nitems,newmenu_item * items, int * last_key, int citem) );
1599
1600 void show_help()
1601 {
1602         int nitems = 0;
1603         newmenu_item m[25];
1604 #ifdef MACINTOSH
1605         char pixel_double_help[64];
1606 #endif
1607 #ifdef __APPLE__
1608         char command_help[64], save_help[64], restore_help[64];
1609 #endif
1610
1611         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_ESC;
1612 #ifndef __APPLE__
1613         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_ALT_F2;
1614         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_ALT_F3;
1615 #else
1616         sprintf(save_help, "OPT-F2 (%c-s)\t Save Game", 133);
1617         sprintf(restore_help, "OPT-F3 (%c-o)\t Load Game", 133);
1618         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = save_help;
1619         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = restore_help;
1620 #endif
1621         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_F2;
1622         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_F3;
1623         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_F4;
1624         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_F5;
1625         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "F6\t Fast Save";
1626 #ifndef __APPLE__
1627         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_PAUSE;
1628 #else
1629         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Pause (F15)\t  Pause";
1630 #endif
1631         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_MINUSPLUS;
1632 #ifndef __APPLE__
1633         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_PRTSCN;
1634 #else
1635         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "printscrn (F13)\t  save screen shot";
1636 #endif
1637         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_1TO5;
1638         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_6TO10;
1639         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Shift-F1\t  Cycle left window";
1640         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Shift-F2\t  Cycle right window";
1641         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Shift-F4\t  GuideBot menu";
1642 #ifndef __APPLE__
1643         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Alt-Shift-F4\t  Rename GuideBot";
1644 #else
1645         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Opt-Shift-F4\t  Rename GuideBot";
1646 #endif
1647         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Shift-F5\t  Drop primary";
1648         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Shift-F6\t  Drop secondary";
1649         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Shift-F7\t  Calibrate joystick";
1650         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Shift-number\t  GuideBot commands";
1651 #ifdef MACINTOSH
1652         sprintf(pixel_double_help, "%c-D\t  Toggle Pixel Double Mode", 133);
1653         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = pixel_double_help;
1654 #endif
1655 #ifdef __APPLE__
1656         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "";
1657         sprintf(command_help, "(Use %c-# for F#. i.e. %c-1 for F1)", 133, 133);
1658         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = command_help;
1659 #endif
1660
1661         full_palette_save();
1662
1663         newmenu_dotiny2( NULL, TXT_KEYS, nitems, m, NULL );
1664
1665         palette_restore();
1666 }
1667
1668 //temp function until Matt cleans up game sequencing
1669 extern void temp_reset_stuff_on_level();
1670
1671 fix Rear_view_leave_time = 0x1000;   // how long until we decide key is down (Used to be 0x4000)
1672
1673 //deal with rear view - switch it on, or off, or whatever
1674 void check_rear_view()
1675 {
1676         static int leave_mode;
1677         static fix entry_time;
1678
1679         if ( Controls.rear_view_down_count )    {               //key/button has gone down
1680
1681                 if (Rear_view) {
1682                         Rear_view = 0;
1683                         if (Cockpit_mode==CM_REAR_VIEW) {
1684                                 select_cockpit(Cockpit_mode_save);
1685                                 Cockpit_mode_save = -1;
1686                         }
1687                         if (Newdemo_state == ND_STATE_RECORDING)
1688                                 newdemo_record_restore_rearview();
1689                 }
1690                 else {
1691                         Rear_view = 1;
1692                         if (Rear_view_leave_time <= 0)
1693                         {
1694                                 leave_mode = 1; // set leave mode on here otherwise we will always have to hold for at least 1 frame to get leave_mode on
1695                         }
1696                         else
1697                         {
1698                                 leave_mode = 0; // means wait for another key
1699                                 entry_time = timer_get_fixed_seconds();
1700                         }
1701                         if (Cockpit_mode == CM_FULL_COCKPIT) {
1702                                 Cockpit_mode_save = Cockpit_mode;
1703                                 select_cockpit(CM_REAR_VIEW);
1704                         }
1705                         if (Newdemo_state == ND_STATE_RECORDING)
1706                                 newdemo_record_rearview();
1707                 }
1708         }
1709         else
1710                 if (Controls.rear_view_down_state) {
1711
1712                         if (leave_mode == 0 && (timer_get_fixed_seconds() - entry_time) > Rear_view_leave_time)
1713                                 leave_mode = 1;
1714                 }
1715                 else {
1716
1717                         //@@if (leave_mode==1 && Cockpit_mode==CM_REAR_VIEW) {
1718
1719                         if (leave_mode==1 && Rear_view) {
1720                                 Rear_view = 0;
1721                                 if (Cockpit_mode==CM_REAR_VIEW) {
1722                                         select_cockpit(Cockpit_mode_save);
1723                                         Cockpit_mode_save = -1;
1724                                 }
1725                                 if (Newdemo_state == ND_STATE_RECORDING)
1726                                         newdemo_record_restore_rearview();
1727                         }
1728                 }
1729 }
1730
1731 void reset_rear_view(void)
1732 {
1733         if (Rear_view) {
1734                 if (Newdemo_state == ND_STATE_RECORDING)
1735                         newdemo_record_restore_rearview();
1736         }
1737
1738         Rear_view = 0;
1739
1740         if (!(Cockpit_mode == CM_FULL_COCKPIT || Cockpit_mode == CM_STATUS_BAR || Cockpit_mode == CM_FULL_SCREEN)) {
1741                 if (!(Cockpit_mode_save == CM_FULL_COCKPIT || Cockpit_mode_save == CM_STATUS_BAR || Cockpit_mode_save == CM_FULL_SCREEN))
1742                         Cockpit_mode_save = CM_FULL_COCKPIT;
1743                 select_cockpit(Cockpit_mode_save);
1744                 Cockpit_mode_save       = -1;
1745         }
1746
1747 }
1748
1749 int Automap_flag;
1750 int Config_menu_flag;
1751
1752 jmp_buf LeaveGame;
1753
1754 int gr_renderstats = 0;
1755 // need to define "cheat" for renderstats
1756 int gr_badtexture = 0;
1757 // need to define "cheat" for badtexture
1758
1759 int Cheats_enabled=0;
1760
1761 extern int Laser_rapid_fire;
1762 extern void do_lunacy_on(), do_lunacy_off();
1763
1764 extern int Physics_cheat_flag,Robots_kill_robots_cheat;
1765 extern char BounceCheat,HomingCheat,OldHomingState[20];
1766 extern char AcidCheatOn,old_IntMethod, Monster_mode;
1767 extern int Buddy_dude_cheat;
1768
1769 //turns off active cheats
1770 void turn_cheats_off()
1771 {
1772         int i;
1773
1774         if (HomingCheat)
1775                 for (i=0;i<20;i++)
1776                         Weapon_info[i].homing_flag=OldHomingState[i];
1777
1778         if (AcidCheatOn)
1779         {
1780                 AcidCheatOn=0;
1781                 Interpolation_method=old_IntMethod;
1782         }
1783
1784         Buddy_dude_cheat = 0;
1785         BounceCheat=0;
1786    HomingCheat=0;
1787         do_lunacy_off();
1788         Laser_rapid_fire = 0;
1789         Physics_cheat_flag = 0;
1790         Monster_mode = 0;
1791         Robots_kill_robots_cheat=0;
1792         Robot_firing_enabled = 1;
1793 }
1794
1795 //turns off all cheats & resets cheater flag    
1796 void game_disable_cheats()
1797 {
1798         turn_cheats_off();
1799         Cheats_enabled=0;
1800 }
1801
1802
1803 //      game_setup()
1804 // ----------------------------------------------------------------------------
1805
1806 void game_setup(void)
1807 {
1808         //@@int demo_playing=0;
1809         //@@int multi_game=0;
1810
1811         do_lunacy_on();         //      Copy values for insane into copy buffer in ai.c
1812         do_lunacy_off();                //      Restore true insane mode.
1813
1814         Game_aborted = 0;
1815         last_drawn_cockpit[0] = -1;                             // Force cockpit to redraw next time a frame renders.
1816         last_drawn_cockpit[1] = -1;                             // Force cockpit to redraw next time a frame renders.
1817         Endlevel_sequence = 0;
1818
1819         //@@if ( Newdemo_state == ND_STATE_PLAYBACK )
1820         //@@    demo_playing = 1;
1821         //@@if ( Game_mode & GM_MULTI )
1822         //@@    multi_game = 1;
1823
1824         set_screen_mode(SCREEN_GAME);
1825         reset_palette_add();
1826
1827         set_warn_func(game_show_warning);
1828
1829         init_cockpit();
1830         init_gauges();
1831         //digi_init_sounds();
1832
1833         //keyd_repeat = 0;                // Don't allow repeat in game
1834         keyd_repeat = 1;                // Do allow repeat in game
1835
1836 #ifdef __MSDOS__
1837         //_MARK_("start of game");
1838 #endif
1839
1840         #ifdef EDITOR
1841                 if (Segments[ConsoleObject->segnum].segnum == -1)      //segment no longer exists
1842                         obj_relink( OBJECT_NUMBER(ConsoleObject), SEG_PTR_2_NUM(Cursegp) );
1843
1844                 if (!check_obj_seg(ConsoleObject))
1845                         move_player_2_segment(Cursegp,Curside);
1846         #endif
1847
1848         Viewer = ConsoleObject;
1849         fly_init(ConsoleObject);
1850
1851         Game_suspended = 0;
1852
1853         reset_time();
1854         FrameTime = 0;                  //make first frame zero
1855
1856         #ifdef EDITOR
1857         if (Current_level_num == 0) {                   //not a real level
1858                 init_player_stats_game();
1859                 init_ai_objects();
1860         }
1861         #endif
1862
1863         fix_object_segs();
1864
1865         game_flush_inputs();
1866
1867 }
1868
1869
1870 #ifdef NETWORK
1871 extern char IWasKicked;
1872 #endif
1873
1874
1875 //      ------------------------------------------------------------------------------------
1876 //this function is the game.  called when game mode selected.  runs until
1877 //editor mode or exit selected
1878 void game()
1879 {
1880         game_setup();                                                           // Replaces what was here earlier.
1881                                                                                                         // Good for Windows Sake.
1882
1883 #ifdef MWPROFILE
1884         ProfilerSetStatus(1);
1885 #endif
1886
1887         if ( setjmp(LeaveGame)==0 )     {
1888                 while (1) {
1889                         int player_shields;
1890
1891                         // GAME LOOP!
1892                         Automap_flag = 0;
1893                         Config_menu_flag = 0;
1894
1895                         if ( ConsoleObject != &Objects[Players[Player_num].objnum] )
1896                           {
1897                             mprintf ((0,"Player_num=%d objnum=%d",Player_num,Players[Player_num].objnum));
1898                             //Assert( ConsoleObject == &Objects[Players[Player_num].objnum] );
1899                           }
1900
1901                         player_shields = Players[Player_num].shields;
1902
1903                         ExtGameStatus=GAMESTAT_RUNNING;
1904                         GameLoop( 1, 1 );               // Do game loop with rendering and reading controls.
1905
1906                         if (oldfov != cg_fov.value)
1907                         {
1908                                 oldfov = cg_fov.value;
1909                                 if (cg_fov.value < 1)
1910                                         cvar_set("fov", "1");
1911                                 if (cg_fov.value > 170)
1912                                         cvar_set("fov", "170");
1913                                 Render_zoom = fl2f(cg_fov.value * M_PI / 180); // convert to radians
1914                                 con_printf(CON_VERBOSE, "FOV set to %f (0x%08x)\n", cg_fov.value, Render_zoom);
1915                         }
1916
1917                         //if the player is taking damage, give up guided missile control
1918                         if (Players[Player_num].shields != player_shields)
1919                                 release_guided_missile(Player_num);
1920
1921                         //see if redbook song needs to be restarted
1922                         songs_check_redbook_repeat();   // Handle RedBook Audio Repeating.
1923
1924                         if (Config_menu_flag)   {
1925                                 if (!(Game_mode&GM_MULTI)) {palette_save(); reset_palette_add();        apply_modified_palette(); gr_palette_load( gr_palette ); }
1926                                 do_options_menu();
1927                                 if (!(Game_mode&GM_MULTI)) palette_restore();
1928                         }
1929
1930                         if (Automap_flag) {
1931                                 int save_w=Game_window_w,save_h=Game_window_h;
1932                                 do_automap(0);
1933                                 Screen_mode=-1; set_screen_mode(SCREEN_GAME);
1934                                 Game_window_w=save_w; Game_window_h=save_h;
1935                                 init_cockpit();
1936                                 last_drawn_cockpit[0] = -1;
1937                                 last_drawn_cockpit[1] = -1;
1938                         }
1939
1940                         if ( (Function_mode != FMODE_GAME) && Auto_demo && (Newdemo_state != ND_STATE_NORMAL) ) {
1941                                 int choice, fmode;
1942                                 fmode = Function_mode;
1943                                 Function_mode = FMODE_GAME;
1944                                 palette_save();
1945                                 apply_modified_palette();
1946                                 reset_palette_add();
1947                                 gr_palette_load( gr_palette );
1948                                 choice=nm_messagebox( NULL, 2, TXT_YES, TXT_NO, TXT_ABORT_AUTODEMO );
1949                                 palette_restore();
1950                                 Function_mode = fmode;
1951                                 if (choice==0)  {
1952                                         Auto_demo = 0;
1953                                         newdemo_stop_playback();
1954                                         Function_mode = FMODE_MENU;
1955                                 } else {
1956                                         Function_mode = FMODE_GAME;
1957                                 }
1958                         }
1959
1960                         if ( (Function_mode != FMODE_GAME ) && (Newdemo_state != ND_STATE_PLAYBACK ) && (Function_mode!=FMODE_EDITOR)
1961 #ifdef NETWORK
1962                                         && !IWasKicked
1963 #endif
1964                            )            {
1965                                 int choice, fmode;
1966                                 fmode = Function_mode;
1967                                 Function_mode = FMODE_GAME;
1968                                 palette_save();
1969                                 apply_modified_palette();
1970                                 reset_palette_add();
1971                                 gr_palette_load( gr_palette );
1972                                 ExtGameStatus=GAMESTAT_ABORT_GAME;
1973                                 choice=nm_messagebox( NULL, 2, TXT_YES, TXT_NO, TXT_ABORT_GAME );
1974                                 palette_restore();
1975                                 Function_mode = fmode;
1976                                 if (choice != 0)
1977                                         Function_mode = FMODE_GAME;
1978                         }
1979
1980 #ifdef NETWORK
1981                         IWasKicked=0;
1982 #endif
1983                         if (Function_mode != FMODE_GAME)
1984                                 longjmp(LeaveGame,0);
1985
1986                         #ifdef APPLE_DEMO
1987                         if ( (keyd_time_when_last_pressed + (F1_0 * 60)) < timer_get_fixed_seconds() )          // idle in game for 1 minutes means exit
1988                                 longjmp(LeaveGame,0);
1989                         #endif
1990                 }
1991         }
1992
1993 #ifdef MWPROFILE
1994         ProfilerSetStatus(0);
1995 #endif
1996
1997         digi_stop_all();
1998
1999         if ( (Newdemo_state == ND_STATE_RECORDING) || (Newdemo_state == ND_STATE_PAUSED) )
2000                 newdemo_stop_recording();
2001
2002         #ifdef NETWORK
2003         multi_leave_game();
2004         #endif
2005
2006         if ( Newdemo_state == ND_STATE_PLAYBACK )
2007                 newdemo_stop_playback();
2008
2009    if (Cockpit_mode_save!=-1)
2010          {
2011                 Cockpit_mode=Cockpit_mode_save;
2012                 Cockpit_mode_save=-1;           
2013          }
2014
2015         if (Function_mode != FMODE_EDITOR)
2016                 gr_palette_fade_out(gr_palette,32,0);                   // Fade out before going to menu
2017
2018 //@@    if ( (!demo_playing) && (!multi_game) && (Function_mode != FMODE_EDITOR))       {
2019 //@@            scores_maybe_add_player(Game_aborted);
2020 //@@    }
2021
2022 #ifdef __MSDOS__
2023         //_MARK_("end of game");
2024 #endif
2025
2026         clear_warn_func(game_show_warning);     //don't use this func anymore
2027
2028         game_disable_cheats();
2029
2030         #ifdef APPLE_DEMO
2031         Function_mode = FMODE_EXIT;             // get out of game in Apple OEM version
2032         #endif
2033 }
2034
2035 //called at the end of the program
2036 void close_game()
2037 {
2038         if (VR_offscreen_buffer)        {
2039                 gr_free_canvas(VR_offscreen_buffer);
2040                 VR_offscreen_buffer = NULL;
2041         }
2042
2043         close_gauge_canvases();
2044
2045         restore_effect_bitmap_icons();
2046
2047         if (background_bitmap.bm_data)
2048                 d_free(background_bitmap.bm_data);
2049
2050         clear_warn_func(game_show_warning);     //don't use this func anymore
2051 }
2052
2053 grs_canvas * get_current_game_screen()
2054 {
2055         return &VR_screen_pages[VR_current_page];
2056 }
2057
2058
2059 extern void kconfig_center_headset();
2060
2061
2062 #ifndef NDEBUG
2063 void    speedtest_frame(void);
2064 int     Debug_slowdown=0;
2065 #endif
2066
2067 #ifdef EDITOR
2068 extern void player_follow_path(object *objp);
2069 extern void check_create_player_path(void);
2070
2071 #endif
2072
2073 extern  int     Do_appearance_effect;
2074
2075 object *Missile_viewer=NULL;
2076
2077 int Missile_view_enabled = 1;
2078
2079 int Marker_viewer_num[2]={-1,-1};
2080 int Coop_view_player[2]={-1,-1};
2081 int Cockpit_3d_view[2]={CV_NONE,CV_NONE};
2082
2083 //returns ptr to escort robot, or NULL
2084 object *find_escort()
2085 {
2086         int i;
2087
2088         for (i=0; i<=Highest_object_index; i++)
2089                 if (Objects[i].type == OBJ_ROBOT)
2090                         if (Robot_info[Objects[i].id].companion)
2091                                 return &Objects[i];
2092
2093         return NULL;
2094 }
2095
2096 extern void process_super_mines_frame(void);
2097 extern void do_seismic_stuff(void);
2098
2099 #ifndef RELEASE
2100 int Saving_movie_frames=0;
2101 int __Movie_frame_num=0;
2102
2103 #define MAX_MOVIE_BUFFER_FRAMES 250
2104 #define MOVIE_FRAME_SIZE        (320 * 200)
2105
2106 ubyte *Movie_frame_buffer;
2107 int Movie_frame_counter;
2108 ubyte Movie_pal[768];
2109 char movie_path[50] = ".\\";
2110
2111 grs_bitmap Movie_bm;
2112
2113 void flush_movie_buffer()
2114 {
2115         char savename[128];
2116         int f;
2117
2118         stop_time();
2119
2120         mprintf((0,"Flushing movie buffer..."));
2121
2122         Movie_bm.bm_data = Movie_frame_buffer;
2123
2124         for (f=0;f<Movie_frame_counter;f++) {
2125                 sprintf(savename, "%sfrm%04d.pcx",movie_path,__Movie_frame_num);
2126                 __Movie_frame_num++;
2127                 pcx_write_bitmap(savename,&Movie_bm,Movie_pal);
2128                 Movie_bm.bm_data += MOVIE_FRAME_SIZE;
2129
2130                 if (f % 5 == 0)
2131                         mprintf((0,"%3d/%3d\10\10\10\10\10\10\10",f,Movie_frame_counter));
2132         }
2133
2134         Movie_frame_counter=0;
2135
2136         mprintf((0,"done   \n"));
2137
2138         start_time();
2139 }
2140
2141 void toggle_movie_saving()
2142 {
2143         int exit;
2144
2145         Saving_movie_frames = !Saving_movie_frames;
2146
2147         if (Saving_movie_frames) {
2148                 newmenu_item m[1];
2149
2150                 m[0].type=NM_TYPE_INPUT; m[0].text_len = 50; m[0].text = movie_path;
2151                 exit = newmenu_do( NULL, "Directory for movie frames?" , 1, &(m[0]), NULL );
2152
2153                 if (exit==-1) {
2154                         Saving_movie_frames = 0;
2155                         return;
2156                 }
2157
2158                 while (isspace(movie_path[strlen(movie_path)-1]))
2159                         movie_path[strlen(movie_path)-1] = 0;
2160                 if (movie_path[strlen(movie_path)-1]!='\\' && movie_path[strlen(movie_path)-1]!=':')
2161                         strcat(movie_path,"\\");
2162
2163
2164                 if (!Movie_frame_buffer) {
2165                         Movie_frame_buffer = d_malloc(MAX_MOVIE_BUFFER_FRAMES * MOVIE_FRAME_SIZE);
2166                         if (!Movie_frame_buffer) {
2167                                 Int3();
2168                                 Saving_movie_frames=0;
2169                         }
2170
2171                         Movie_frame_counter=0;
2172
2173                         Movie_bm.bm_x = Movie_bm.bm_y = 0;
2174                         Movie_bm.bm_w = 320;
2175                         Movie_bm.bm_h = 200;
2176                         Movie_bm.bm_type = BM_LINEAR;
2177                         Movie_bm.bm_flags = 0;
2178                         Movie_bm.bm_rowsize = 320;
2179                         Movie_bm.bm_handle = 0;
2180
2181                         gr_palette_read(Movie_pal);             //get actual palette from the hardware
2182
2183                         if (Newdemo_state == ND_STATE_PLAYBACK)
2184                                 Newdemo_do_interpolate = 0;
2185                 }
2186         }
2187         else {
2188                 flush_movie_buffer();
2189
2190                 if (Newdemo_state == ND_STATE_PLAYBACK)
2191                         Newdemo_do_interpolate = 1;
2192         }
2193
2194 }
2195
2196 void save_movie_frame()
2197 {
2198         memcpy(Movie_frame_buffer+Movie_frame_counter*MOVIE_FRAME_SIZE,grd_curscreen->sc_canvas.cv_bitmap.bm_data,MOVIE_FRAME_SIZE);
2199
2200         Movie_frame_counter++;
2201
2202         if (Movie_frame_counter == MAX_MOVIE_BUFFER_FRAMES)
2203                 flush_movie_buffer();
2204
2205 }
2206
2207 #endif
2208
2209 extern int Level_shake_duration;
2210
2211 //if water or fire level, make occasional sound
2212 void do_ambient_sounds()
2213 {
2214         int has_water,has_lava;
2215         int sound;
2216
2217         has_lava = (Segment2s[ConsoleObject->segnum].s2_flags & S2F_AMBIENT_LAVA);
2218         has_water = (Segment2s[ConsoleObject->segnum].s2_flags & S2F_AMBIENT_WATER);
2219
2220         if (has_lava) {                                                 //has lava
2221                 sound = SOUND_AMBIENT_LAVA;
2222                 if (has_water && (d_rand() & 1))        //both, pick one
2223                         sound = SOUND_AMBIENT_WATER;
2224         }
2225         else if (has_water)                                             //just water
2226                 sound = SOUND_AMBIENT_WATER;
2227         else
2228                 return;
2229
2230         if (((d_rand() << 3) < FrameTime)) {                                            //play the sound
2231                 fix volume = d_rand() + f1_0/2;
2232                 digi_play_sample(sound,volume);
2233         }
2234 }
2235
2236 // -- extern void lightning_frame(void);
2237
2238 void game_render_frame();
2239 extern void omega_charge_frame(void);
2240
2241 extern time_t t_current_time, t_saved_time;
2242
2243 void flicker_lights();
2244
2245 void GameLoop(int RenderFlag, int ReadControlsFlag )
2246 {
2247         #ifndef NDEBUG
2248         //      Used to slow down frame rate for testing things.
2249         //      RenderFlag = 1; // DEBUG
2250         if (Debug_slowdown) {
2251                 int     h, i, j=0;
2252
2253                 for (h=0; h<Debug_slowdown; h++)
2254                         for (i=0; i<1000; i++)
2255                                 j += i;
2256         }
2257         #endif
2258
2259         cmd_queue_process();
2260
2261                 #ifndef RELEASE
2262                 if (FindArg("-invulnerability"))
2263                         Players[Player_num].flags |= PLAYER_FLAGS_INVULNERABLE;
2264                 #endif
2265
2266
2267                 update_player_stats();
2268                 diminish_palette_towards_normal();              //      Should leave palette effect up for as long as possible by putting right before render.
2269                 do_afterburner_stuff();
2270                 do_cloak_stuff();
2271                 do_invulnerable_stuff();
2272                 remove_obsolete_stuck_objects();
2273                 init_ai_frame();
2274                 do_final_boss_frame();
2275                 // -- lightning_frame();
2276                 // -- recharge_energy_frame();
2277
2278                 if ((Players[Player_num].flags & PLAYER_FLAGS_HEADLIGHT) && (Players[Player_num].flags & PLAYER_FLAGS_HEADLIGHT_ON)) {
2279                         static int turned_off=0;
2280                         Players[Player_num].energy -= (FrameTime*3/8);
2281                         if (Players[Player_num].energy < i2f(10)) {
2282                                 if (!turned_off) {
2283                                         Players[Player_num].flags &= ~PLAYER_FLAGS_HEADLIGHT_ON;
2284                                         turned_off = 1;
2285 #ifdef NETWORK
2286                                         if (Game_mode & GM_MULTI)
2287                                                 multi_send_flags(Player_num);           
2288 #endif
2289                                 }
2290                         }
2291                         else
2292                                 turned_off = 0;
2293
2294                         if (Players[Player_num].energy <= 0) {
2295                                 Players[Player_num].energy = 0;
2296                                 Players[Player_num].flags &= ~PLAYER_FLAGS_HEADLIGHT_ON;
2297 #ifdef NETWORK
2298                                 if (Game_mode & GM_MULTI)
2299                                         multi_send_flags(Player_num);           
2300 #endif
2301                         }
2302                 }
2303
2304
2305                 #ifdef EDITOR
2306                 check_create_player_path();
2307                 player_follow_path(ConsoleObject);
2308                 #endif
2309
2310                 #ifdef NETWORK
2311                 if (Game_mode & GM_MULTI)
2312         {
2313          multi_do_frame();
2314          if (Netgame.PlayTimeAllowed && ThisLevelTime>=i2f((Netgame.PlayTimeAllowed*5*60)))
2315              multi_check_for_killgoal_winner();
2316         }
2317
2318                 #endif
2319
2320                 if (RenderFlag) {
2321                         if (force_cockpit_redraw) {                     //screen need redrawing?
2322                                 init_cockpit();
2323                                 force_cockpit_redraw=0;
2324                         }
2325                         game_render_frame();
2326                         //show_extra_views();           //missile view, buddy bot, etc.
2327
2328                         #ifndef RELEASE
2329                         if (Saving_movie_frames)
2330                                 save_movie_frame();
2331                         #endif
2332
2333                 }
2334
2335
2336                 //mprintf(0,"Velocity %2.2f\n", f2fl(vm_vec_mag(&ConsoleObject->phys_info.velocity)));
2337
2338                 calc_frame_time();
2339
2340                 dead_player_frame();
2341                 if (Newdemo_state != ND_STATE_PLAYBACK)
2342                         do_controlcen_dead_frame();
2343
2344                 process_super_mines_frame();
2345                 do_seismic_stuff();
2346                 do_ambient_sounds();
2347
2348                 #ifndef NDEBUG
2349                 if (Speedtest_on)
2350                         speedtest_frame();
2351                 #endif
2352
2353                 if (ReadControlsFlag)
2354                         ReadControls();
2355                 else
2356                         memset(&Controls, 0, sizeof(Controls));
2357
2358                 GameTime += FrameTime;
2359
2360                 if (f2i(GameTime)/10 != f2i(GameTime-FrameTime)/10)
2361                         mprintf((0,"Gametime = %d secs\n",f2i(GameTime)));
2362
2363                 if (GameTime < 0 || GameTime > i2f(0x7fff - 600)) {
2364                         GameTime = FrameTime;   //wrap when goes negative, or gets within 10 minutes
2365                         mprintf((0,"GameTime reset to 0\n"));
2366                 }
2367
2368                 #ifndef NDEBUG
2369                 if (FindArg("-checktime") != 0)
2370                         if (GameTime >= i2f(600))               //wrap after 10 minutes
2371                                 GameTime = FrameTime;
2372                 #endif
2373
2374 #ifdef NETWORK
2375       if ((Game_mode & GM_MULTI) && Netgame.PlayTimeAllowed)
2376           ThisLevelTime +=FrameTime;
2377 #endif
2378
2379                 digi_sync_sounds();
2380
2381                 if (Endlevel_sequence) {
2382                         do_endlevel_frame();
2383                         powerup_grab_cheat_all();
2384                         do_special_effects();
2385                         return;                                 //skip everything else
2386                 }
2387
2388                 if (Newdemo_state != ND_STATE_PLAYBACK)
2389                         do_exploding_wall_frame();
2390                 if ((Newdemo_state != ND_STATE_PLAYBACK) || (Newdemo_vcr_state != ND_STATE_PAUSED)) {
2391                         do_special_effects();
2392                         wall_frame_process();
2393                         triggers_frame_process();
2394                 }
2395
2396
2397                 if (Control_center_destroyed)   {
2398                         if (Newdemo_state==ND_STATE_RECORDING )
2399                                 newdemo_record_control_center_destroyed();
2400                 }
2401
2402                 flash_frame();
2403
2404                 if ( Newdemo_state == ND_STATE_PLAYBACK )       {
2405                         newdemo_playback_one_frame();
2406                         if ( Newdemo_state != ND_STATE_PLAYBACK )               {
2407                                 longjmp( LeaveGame, 0 );                // Go back to menu
2408                         }
2409                 } else
2410                 { // Note the link to above!
2411
2412                         Players[Player_num].homing_object_dist = -1;            //      Assume not being tracked.  Laser_do_weapon_sequence modifies this.
2413
2414                         object_move_all();
2415                         powerup_grab_cheat_all();
2416
2417                         if (Endlevel_sequence)  //might have been started during move
2418                                 return;
2419
2420                         fuelcen_update_all();
2421
2422                         do_ai_frame_all();
2423
2424                         if (allowed_to_fire_laser())
2425                                 FireLaser();                            // Fire Laser!
2426
2427                         if (Auto_fire_fusion_cannon_time) {
2428                                 if (Primary_weapon != FUSION_INDEX)
2429                                         Auto_fire_fusion_cannon_time = 0;
2430                                 else if (GameTime + FrameTime/2 >= Auto_fire_fusion_cannon_time) {
2431                                         Auto_fire_fusion_cannon_time = 0;
2432                                         Global_laser_firing_count = 1;
2433                                 } else {
2434                                         vms_vector      rand_vec;
2435                                         fix                     bump_amount;
2436
2437                                         Global_laser_firing_count = 0;
2438
2439                                         ConsoleObject->mtype.phys_info.rotvel.x += (d_rand() - 16384)/8;
2440                                         ConsoleObject->mtype.phys_info.rotvel.z += (d_rand() - 16384)/8;
2441                                         make_random_vector(&rand_vec);
2442
2443                                         bump_amount = F1_0*4;
2444
2445                                         if (Fusion_charge > F1_0*2)
2446                                                 bump_amount = Fusion_charge*4;
2447
2448                                         bump_one_object(ConsoleObject, &rand_vec, bump_amount);
2449                                 }
2450                         }
2451
2452                         if (Global_laser_firing_count) {
2453                                 //      Don't cap here, gets capped in Laser_create_new and is based on whether in multiplayer mode, MK, 3/27/95
2454                                 // if (Fusion_charge > F1_0*2)
2455                                 //      Fusion_charge = F1_0*2;
2456                                 Global_laser_firing_count -= do_laser_firing_player();  //do_laser_firing(Players[Player_num].objnum, Primary_weapon);
2457                         }
2458
2459                         if (Global_laser_firing_count < 0)
2460                                 Global_laser_firing_count = 0;
2461                 }
2462
2463         if (Do_appearance_effect) {
2464                 create_player_appearance_effect(ConsoleObject);
2465                 Do_appearance_effect = 0;
2466 #ifdef NETWORK
2467                 if ((Game_mode & GM_MULTI) && Netgame.invul)
2468                 {
2469                         Players[Player_num].flags |= PLAYER_FLAGS_INVULNERABLE;
2470                         Players[Player_num].invulnerable_time = GameTime-i2f(27);
2471                         FakingInvul=1;
2472                 }
2473 #endif
2474                         
2475         }
2476
2477         omega_charge_frame();
2478         slide_textures();
2479         flicker_lights();
2480
2481         //!!hoard_light_pulse();                //do cool hoard light pulsing
2482
2483 }
2484
2485 //!!extern int Goal_blue_segnum,Goal_red_segnum;
2486 //!!extern int Hoard_goal_eclip;
2487 //!!
2488 //!!//do cool pulsing lights in hoard goals
2489 //!!hoard_light_pulse()
2490 //!!{
2491 //!!    if (Game_mode & GM_HOARD) {
2492 //!!            fix light;
2493 //!!            int frame;
2494 //!!
2495 //!!            frame = Effects[Hoard_goal_eclip].frame_count;
2496 //!!
2497 //!!            frame++;
2498 //!!
2499 //!!            if (frame >= Effects[Hoard_goal_eclip].vc.num_frames)
2500 //!!                    frame = 0;
2501 //!!
2502 //!!            light = abs(frame - 5) * f1_0 / 5;
2503 //!!
2504 //!!            Segment2s[Goal_red_segnum].static_light = Segment2s[Goal_blue_segnum].static_light = light;
2505 //!!    }
2506 //!!}
2507
2508
2509 ubyte   Slide_segs[MAX_SEGMENTS];
2510 int     Slide_segs_computed;
2511
2512 void compute_slide_segs(void)
2513 {
2514         int     segnum, sidenum;
2515
2516         for (segnum=0;segnum<=Highest_segment_index;segnum++) {
2517                 Slide_segs[segnum] = 0;
2518                 for (sidenum=0;sidenum<6;sidenum++) {
2519                         int tmn = Segments[segnum].sides[sidenum].tmap_num;
2520                         if (TmapInfo[tmn].slide_u != 0 || TmapInfo[tmn].slide_v != 0)
2521                                 Slide_segs[segnum] |= 1 << sidenum;
2522                 }
2523         }
2524
2525         Slide_segs_computed = 1;
2526 }
2527
2528 //      -----------------------------------------------------------------------------
2529 void slide_textures(void)
2530 {
2531         int segnum,sidenum,i;
2532
2533         if (!Slide_segs_computed)
2534                 compute_slide_segs();
2535
2536         for (segnum=0;segnum<=Highest_segment_index;segnum++) {
2537                 if (Slide_segs[segnum]) {
2538                         for (sidenum=0;sidenum<6;sidenum++) {
2539                                 if (Slide_segs[segnum] & (1 << sidenum)) {
2540                                         int tmn = Segments[segnum].sides[sidenum].tmap_num;
2541                                         if (TmapInfo[tmn].slide_u != 0 || TmapInfo[tmn].slide_v != 0) {
2542                                                 for (i=0;i<4;i++) {
2543                                                         Segments[segnum].sides[sidenum].uvls[i].u += fixmul(FrameTime,TmapInfo[tmn].slide_u<<8);
2544                                                         Segments[segnum].sides[sidenum].uvls[i].v += fixmul(FrameTime,TmapInfo[tmn].slide_v<<8);
2545                                                         if (Segments[segnum].sides[sidenum].uvls[i].u > f2_0) {
2546                                                                 int j;
2547                                                                 for (j=0;j<4;j++)
2548                                                                         Segments[segnum].sides[sidenum].uvls[j].u -= f1_0;
2549                                                         }
2550                                                         if (Segments[segnum].sides[sidenum].uvls[i].v > f2_0) {
2551                                                                 int j;
2552                                                                 for (j=0;j<4;j++)
2553                                                                         Segments[segnum].sides[sidenum].uvls[j].v -= f1_0;
2554                                                         }
2555                                                         if (Segments[segnum].sides[sidenum].uvls[i].u < -f2_0) {
2556                                                                 int j;
2557                                                                 for (j=0;j<4;j++)
2558                                                                         Segments[segnum].sides[sidenum].uvls[j].u += f1_0;
2559                                                         }
2560                                                         if (Segments[segnum].sides[sidenum].uvls[i].v < -f2_0) {
2561                                                                 int j;
2562                                                                 for (j=0;j<4;j++)
2563                                                                         Segments[segnum].sides[sidenum].uvls[j].v += f1_0;
2564                                                         }
2565                                                 }
2566                                         }
2567                                 }
2568                         }
2569                 }
2570         }
2571 }
2572
2573 flickering_light Flickering_lights[MAX_FLICKERING_LIGHTS];
2574
2575 int Num_flickering_lights=0;
2576
2577 void flicker_lights()
2578 {
2579         int l;
2580         flickering_light *f;
2581
2582         f = Flickering_lights;
2583
2584         for (l=0;l<Num_flickering_lights;l++,f++) {
2585                 segment *segp = &Segments[f->segnum];
2586
2587                 //make sure this is actually a light
2588                 if (! (WALL_IS_DOORWAY(segp, f->sidenum) & WID_RENDER_FLAG))
2589                         continue;
2590                 if (! (TmapInfo[segp->sides[f->sidenum].tmap_num].lighting | TmapInfo[segp->sides[f->sidenum].tmap_num2 & 0x3fff].lighting))
2591                         continue;
2592
2593                 if (f->timer == 0x80000000)             //disabled
2594                         continue;
2595
2596                 if ((f->timer -= FrameTime) < 0) {
2597
2598                         while (f->timer < 0)
2599                                 f->timer += f->delay;
2600
2601                         f->mask = ((f->mask&0x80000000)?1:0) + (f->mask<<1);
2602
2603                         if (f->mask & 1)
2604                                 add_light(f->segnum,f->sidenum);
2605                         else
2606                                 subtract_light(f->segnum,f->sidenum);
2607                 }
2608         }
2609 }
2610
2611 //returns ptr to flickering light structure, or NULL if can't find
2612 flickering_light *find_flicker(int segnum,int sidenum)
2613 {
2614         int l;
2615         flickering_light *f;
2616
2617         //see if there's already an entry for this seg/side
2618
2619         f = Flickering_lights;
2620
2621         for (l=0;l<Num_flickering_lights;l++,f++)
2622                 if (f->segnum == segnum && f->sidenum == sidenum)       //found it!
2623                         return f;
2624
2625         return NULL;
2626 }
2627
2628 //turn flickering off (because light has been turned off)
2629 void disable_flicker(int segnum,int sidenum)
2630 {
2631         flickering_light *f;
2632
2633         if ((f=find_flicker(segnum,sidenum)) != NULL)
2634                 f->timer = 0x80000000;
2635 }
2636
2637 //turn flickering off (because light has been turned on)
2638 void enable_flicker(int segnum,int sidenum)
2639 {
2640         flickering_light *f;
2641
2642         if ((f=find_flicker(segnum,sidenum)) != NULL)
2643                 f->timer = 0;
2644 }
2645
2646
2647 #ifdef EDITOR
2648
2649 //returns 1 if ok, 0 if error
2650 int add_flicker(int segnum, int sidenum, fix delay, unsigned long mask)
2651 {
2652         int l;
2653         flickering_light *f;
2654
2655         mprintf((0,"add_flicker: %d:%d %x %x\n",segnum,sidenum,delay,mask));
2656
2657         //see if there's already an entry for this seg/side
2658
2659         f = Flickering_lights;
2660
2661         for (l=0;l<Num_flickering_lights;l++,f++)
2662                 if (f->segnum == segnum && f->sidenum == sidenum)       //found it!
2663                         break;
2664
2665         if (mask==0) {          //clearing entry
2666                 if (l == Num_flickering_lights)
2667                         return 0;
2668                 else {
2669                         int i;
2670                         for (i=l;i<Num_flickering_lights-1;i++)
2671                                 Flickering_lights[i] = Flickering_lights[i+1];
2672                         Num_flickering_lights--;
2673                         return 1;
2674                 }
2675         }
2676
2677         if (l == Num_flickering_lights) {
2678                 if (Num_flickering_lights == MAX_FLICKERING_LIGHTS)
2679                         return 0;
2680                 else
2681                         Num_flickering_lights++;
2682         }
2683
2684         f->segnum = segnum;
2685         f->sidenum = sidenum;
2686         f->delay = f->timer = delay;
2687         f->mask = mask;
2688
2689         return 1;
2690 }
2691
2692 #endif
2693
2694 //      -----------------------------------------------------------------------------
2695 //      Fire Laser:  Registers a laser fire, and performs special stuff for the fusion
2696 //                                  cannon.
2697 void FireLaser()
2698 {
2699
2700         Global_laser_firing_count = Weapon_info[Primary_weapon_to_weapon_info[Primary_weapon]].fire_count * (Controls.fire_primary_state || Controls.fire_primary_down_count);
2701
2702         if ((Primary_weapon == FUSION_INDEX) && (Global_laser_firing_count)) {
2703                 if ((Players[Player_num].energy < F1_0*2) && (Auto_fire_fusion_cannon_time == 0)) {
2704                         Global_laser_firing_count = 0;
2705                 } else {
2706                         if (Fusion_charge == 0)
2707                                 Players[Player_num].energy -= F1_0*2;
2708
2709                         Fusion_charge += FrameTime;
2710                         Players[Player_num].energy -= FrameTime;
2711
2712                         if (Players[Player_num].energy <= 0) {
2713                                 Players[Player_num].energy = 0;
2714                                 Auto_fire_fusion_cannon_time = GameTime -1;     //      Fire now!
2715                         } else
2716                                 Auto_fire_fusion_cannon_time = GameTime + FrameTime/2 + 1;
2717                                                                                                 //      Fire the fusion cannon at this time in the future.
2718
2719                         if (Fusion_charge < F1_0*2)
2720                                 PALETTE_FLASH_ADD(Fusion_charge >> 11, 0, Fusion_charge >> 11);
2721                         else
2722                                 PALETTE_FLASH_ADD(Fusion_charge >> 11, Fusion_charge >> 11, 0);
2723
2724                         if (GameTime < Fusion_last_sound_time)          //gametime has wrapped
2725                                 Fusion_next_sound_time = Fusion_last_sound_time = GameTime;
2726
2727                         if (Fusion_next_sound_time < GameTime) {
2728                                 if (Fusion_charge > F1_0*2) {
2729                                         digi_play_sample( 11, F1_0 );
2730                                         apply_damage_to_player(ConsoleObject, ConsoleObject, d_rand() * 4);
2731                                 } else {
2732                                         create_awareness_event(ConsoleObject, PA_WEAPON_ROBOT_COLLISION);
2733                                         digi_play_sample( SOUND_FUSION_WARMUP, F1_0 );
2734                                         #ifdef NETWORK
2735                                         if (Game_mode & GM_MULTI)
2736                                                 multi_send_play_sound(SOUND_FUSION_WARMUP, F1_0);
2737                                         #endif
2738                                 }
2739                                 Fusion_last_sound_time = GameTime;
2740                                 Fusion_next_sound_time = GameTime + F1_0/8 + d_rand()/4;
2741                         }
2742                 }
2743         }
2744
2745 }
2746
2747
2748 //      -------------------------------------------------------------------------------------------------------
2749 //      If player is close enough to objnum, which ought to be a powerup, pick it up!
2750 //      This could easily be made difficulty level dependent.
2751 void powerup_grab_cheat(object *player, int objnum)
2752 {
2753         fix     powerup_size;
2754         fix     player_size;
2755         fix     dist;
2756
2757         Assert(Objects[objnum].type == OBJ_POWERUP);
2758
2759         powerup_size = Objects[objnum].size;
2760         player_size = player->size;
2761
2762         dist = vm_vec_dist_quick(&Objects[objnum].pos, &player->pos);
2763
2764         if ((dist < 2*(powerup_size + player_size)) && !(Objects[objnum].flags & OF_SHOULD_BE_DEAD)) {
2765                 vms_vector      collision_point;
2766
2767                 vm_vec_avg(&collision_point, &Objects[objnum].pos, &player->pos);
2768                 collide_player_and_powerup(player, &Objects[objnum], &collision_point);
2769         }
2770 }
2771
2772 //      -------------------------------------------------------------------------------------------------------
2773 //      Make it easier to pick up powerups.
2774 //      For all powerups in this segment, pick them up at up to twice pickuppable distance based on dot product
2775 //      from player to powerup and player's forward vector.
2776 //      This has the effect of picking them up more easily left/right and up/down, but not making them disappear
2777 //      way before the player gets there.
2778 void powerup_grab_cheat_all(void)
2779 {
2780         segment *segp;
2781         int             objnum;
2782
2783         segp = &Segments[ConsoleObject->segnum];
2784         objnum = segp->objects;
2785
2786         while (objnum != -1) {
2787                 if (Objects[objnum].type == OBJ_POWERUP)
2788                         powerup_grab_cheat(ConsoleObject, objnum);
2789                 objnum = Objects[objnum].next;
2790         }
2791
2792 }
2793
2794 int     Last_level_path_created = -1;
2795
2796 #ifdef SHOW_EXIT_PATH
2797
2798 //      ------------------------------------------------------------------------------------------------------------------
2799 //      Create path for player from current segment to goal segment.
2800 //      Return true if path created, else return false.
2801 int mark_player_path_to_segment(int segnum)
2802 {
2803         int             i;
2804         object  *objp = ConsoleObject;
2805         short           player_path_length=0;
2806         int             player_hide_index=-1;
2807
2808         if (Last_level_path_created == Current_level_num) {
2809                 return 0;
2810         }
2811
2812         Last_level_path_created = Current_level_num;
2813
2814         if (create_path_points(objp, objp->segnum, segnum, Point_segs_free_ptr, &player_path_length, 100, 0, 0, -1) == -1) {
2815                 mprintf((0, "Unable to form path of length %i for myself\n", 100));
2816                 return 0;
2817         }
2818
2819         player_hide_index = Point_segs_free_ptr - Point_segs;
2820         Point_segs_free_ptr += player_path_length;
2821
2822         if (Point_segs_free_ptr - Point_segs + MAX_PATH_LENGTH*2 > MAX_POINT_SEGS) {
2823                 mprintf((1, "Can't create path.  Not enough point_segs.\n"));
2824                 ai_reset_all_paths();
2825                 return 0;
2826         }
2827
2828         for (i=1; i<player_path_length; i++) {
2829                 int                     segnum, objnum;
2830                 vms_vector      seg_center;
2831                 object          *obj;
2832
2833                 segnum = Point_segs[player_hide_index+i].segnum;
2834                 mprintf((0, "%3i ", segnum));
2835                 seg_center = Point_segs[player_hide_index+i].point;
2836
2837                 objnum = obj_create( OBJ_POWERUP, POW_ENERGY, segnum, &seg_center, &vmd_identity_matrix, Powerup_info[POW_ENERGY].size, CT_POWERUP, MT_NONE, RT_POWERUP);
2838                 if (objnum == -1) {
2839                         Int3();         //      Unable to drop energy powerup for path
2840                         return 1;
2841                 }
2842
2843                 obj = &Objects[objnum];
2844                 obj->rtype.vclip_info.vclip_num = Powerup_info[obj->id].vclip_num;
2845                 obj->rtype.vclip_info.frametime = Vclip[obj->rtype.vclip_info.vclip_num].frame_time;
2846                 obj->rtype.vclip_info.framenum = 0;
2847                 obj->lifeleft = F1_0*100 + d_rand() * 4;
2848         }
2849
2850         mprintf((0, "\n"));
2851         return 1;
2852 }
2853
2854 //      Return true if it happened, else return false.
2855 int create_special_path(void)
2856 {
2857         int     i,j;
2858
2859         //      ---------- Find exit doors ----------
2860         for (i=0; i<=Highest_segment_index; i++)
2861                 for (j=0; j<MAX_SIDES_PER_SEGMENT; j++)
2862                         if (Segments[i].children[j] == -2) {
2863                                 mprintf((0, "Exit at segment %i\n", i));
2864                                 return mark_player_path_to_segment(i);
2865                         }
2866
2867         return 0;
2868 }
2869
2870 #endif
2871
2872
2873 #ifndef RELEASE
2874 int     Max_obj_count_mike = 0;
2875
2876 //      Shows current number of used objects.
2877 void show_free_objects(void)
2878 {
2879         if (!(FrameCount & 8)) {
2880                 int     i;
2881                 int     count=0;
2882
2883                 mprintf((0, "Highest_object_index = %3i, MAX_OBJECTS = %3i, now used = ", Highest_object_index, MAX_OBJECTS));
2884
2885                 for (i=0; i<=Highest_object_index; i++)
2886                         if (Objects[i].type != OBJ_NONE)
2887                                 count++;
2888
2889                 mprintf((0, "%3i", count));
2890
2891                 if (count > Max_obj_count_mike) {
2892                         Max_obj_count_mike = count;
2893                         mprintf((0, " ***"));
2894                 }
2895
2896                 mprintf((0, "\n"));
2897         }
2898
2899 }
2900
2901 #endif
2902
2903 /*
2904  * reads a flickering_light structure from a CFILE
2905  */
2906 void flickering_light_read(flickering_light *fl, CFILE *fp)
2907 {
2908         fl->segnum = cfile_read_short(fp);
2909         fl->sidenum = cfile_read_short(fp);
2910         fl->mask = cfile_read_int(fp);
2911         fl->timer = cfile_read_fix(fp);
2912         fl->delay = cfile_read_fix(fp);
2913 }
2914
2915 void flickering_light_write(flickering_light *fl, PHYSFS_file *fp)
2916 {
2917         PHYSFS_writeSLE16(fp, fl->segnum);
2918         PHYSFS_writeSLE16(fp, fl->sidenum);
2919         PHYSFS_writeULE32(fp, fl->mask);
2920         PHYSFSX_writeFix(fp, fl->timer);
2921         PHYSFSX_writeFix(fp, fl->delay);
2922 }