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