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