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