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