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