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