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