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