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