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