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