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