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