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