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