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