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