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