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