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