rewrote endlevel stuff to reread exit model info every time
[btb/d2x.git] / main / endlevel.c
1 /* $ Id: $ */
2 /*
3 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
4 SOFTWARE CORPORATION ("PARALLAX").  PARALLAX, IN DISTRIBUTING THE CODE TO
5 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
6 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
7 IN USING, DISPLAYING,  AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
8 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
9 FREE PURPOSES.  IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
10 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES.  THE END-USER UNDERSTANDS
11 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
12 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION.  ALL RIGHTS RESERVED.
13 */
14
15 #ifdef HAVE_CONFIG_H
16 #include <conf.h>
17 #endif
18
19 #ifdef RCS
20 static char rcsid[] = "$Id: endlevel.c,v 1.13 2003-03-29 22:34:59 btb Exp $";
21 #endif
22
23 //#define SLEW_ON 1
24
25 //#define _MARK_ON
26
27 #include <stdlib.h>
28
29
30 #include <stdio.h>
31 #include <string.h>
32 #include <ctype.h> // for isspace
33
34 #include "fix.h"
35 #include "vecmat.h"
36 #include "gr.h"
37 #include "3d.h"
38 #include "error.h"
39 #include "palette.h"
40 #include "iff.h"
41 #include "mono.h"
42 #include "texmap.h"
43 #include "fvi.h"
44 #include "u_mem.h"
45 #include "sounds.h"
46
47 #include "inferno.h"
48 #include "endlevel.h"
49 #include "object.h"
50 #include "game.h"
51 #include "screens.h"
52 #include "gauges.h"
53 #include "wall.h"
54 #include "terrain.h"
55 #include "polyobj.h"
56 #include "bm.h"
57 #include "gameseq.h"
58 #include "newdemo.h"
59 #include "multi.h"
60 #include "vclip.h"
61 #include "fireball.h"
62 #ifdef NETWORK
63 #include "network.h"
64 #endif
65 #include "text.h"
66 #include "digi.h"
67 #include "cfile.h"
68 #include "compbit.h"
69 #include "songs.h"
70 #include "movie.h"
71 #include "render.h"
72
73 typedef struct flythrough_data {
74         object          *obj;
75         vms_angvec      angles;                 //orientation in angles
76         vms_vector      step;                           //how far in a second
77         vms_vector      angstep;                        //rotation per second
78         fix                     speed;                  //how fast object is moving
79         vms_vector      headvec;                        //where we want to be pointing
80         int                     first_time;             //flag for if first time through
81         fix                     offset_frac;    //how far off-center as portion of way
82         fix                     offset_dist;    //how far currently off-center
83 } flythrough_data;
84
85 //endlevel sequence states
86
87 #define EL_OFF                          0               //not in endlevel
88 #define EL_FLYTHROUGH   1               //auto-flythrough in tunnel
89 #define EL_LOOKBACK             2               //looking back at player
90 #define EL_OUTSIDE              3               //flying outside for a while
91 #define EL_STOPPED              4               //stopped, watching explosion
92 #define EL_PANNING              5               //panning around, watching player
93 #define EL_CHASING              6               //chasing player to station
94
95 #define SHORT_SEQUENCE  1               //if defined, end sequnce when panning starts
96 //#define STATION_ENABLED       1               //if defined, load & use space station model
97
98 int Endlevel_sequence = 0;
99
100 extern fix player_speed;
101
102 int transition_segnum,exit_segnum;
103
104 object *endlevel_camera;
105
106 #define FLY_SPEED i2f(50)
107
108 void do_endlevel_flythrough(int n);
109 void draw_stars();
110 int find_exit_side(object *obj);
111 void generate_starfield();
112 void start_endlevel_flythrough(int n,object *obj,fix speed);
113 void start_rendered_endlevel_sequence();
114
115 #ifdef D2_OEM
116 char movie_table[] =    {       'a','a','a','a','d','d','d','d' };
117 #else
118 char movie_table[] =    {       'a','b','c',
119                                                 #ifndef SHAREWARE
120                                                         'a',
121                                                         'd','f','d','f',
122                                                         'g','h','i','g',
123                                                         'j','k','l','j',
124                                                         'm','o','m','o',
125                                                         'p','q','p','q'
126                                                 #endif
127                                         };
128 #endif
129
130 #define N_MOVIES (sizeof(movie_table) / sizeof(*movie_table))
131
132 #ifndef SHAREWARE
133 #ifdef D2_OEM
134 char movie_table_secret[] = {'a','d'};
135 #else
136 char movie_table_secret[] = {'a','d','g','j','m','p'};
137 #endif
138 #define N_MOVIES_SECRET (sizeof(movie_table_secret) / sizeof(*movie_table_secret))
139 #else
140 #define N_MOVIES_SECRET 0
141 #endif
142
143
144 #define FLY_ACCEL i2f(5)
145
146 fix cur_fly_speed,desired_fly_speed;
147
148 extern int matt_find_connect_side(int seg0,int seg1);
149
150 grs_bitmap *satellite_bitmap,*station_bitmap,*terrain_bitmap;   //!!*exit_bitmap,
151 vms_vector satellite_pos,satellite_upvec;
152 //!!grs_bitmap **exit_bitmap_list[1];
153 int station_modelnum,exit_modelnum,destroyed_exit_modelnum;
154
155 vms_vector station_pos = {0xf8c4<<10,0x3c1c<<12,0x372<<10};
156
157 #ifdef STATION_ENABLED
158 grs_bitmap *station_bitmap;
159 grs_bitmap **station_bitmap_list[1];
160 int station_modelnum;
161 #endif
162
163 vms_vector mine_exit_point;
164 vms_vector mine_ground_exit_point;
165 vms_vector mine_side_exit_point;
166 vms_matrix mine_exit_orient;
167
168 int outside_mine;
169
170 grs_bitmap terrain_bm_instance;
171 grs_bitmap satellite_bm_instance;
172
173 //find delta between two angles
174 fixang delta_ang(fixang a,fixang b)
175 {
176         fixang delta0,delta1;
177
178         return (abs(delta0 = a - b) < abs(delta1 = b - a)) ? delta0 : delta1;
179
180 }
181
182 //return though which side of seg0 is seg1
183 int matt_find_connect_side(int seg0,int seg1)
184 {
185         segment *Seg=&Segments[seg0];
186         int i;
187
188         for (i=MAX_SIDES_PER_SEGMENT;i--;) if (Seg->children[i]==seg1) return i;
189
190         return -1;
191 }
192
193 extern int Kmatrix_nomovie_message;
194
195 #if defined(D2_OEM) || defined(COMPILATION)
196 #define MOVIE_REQUIRED 0
197 #else
198 #define MOVIE_REQUIRED 1
199 #endif
200
201 //returns movie played status.  see movie.h
202 int start_endlevel_movie()
203 {
204         char movie_name[] = "esa.mve";
205         int r;
206         ubyte save_pal[768];
207
208         //Assert(Current_mission_num == Builtin_mission_num);   //only play movie for built-in mission
209
210         //Assert(N_MOVIES >= Last_level);
211         //Assert(N_MOVIES_SECRET >= -Last_secret_level);
212
213         #ifndef D2_OEM
214         if (Current_level_num == Last_level)
215                 return 1;       //don't play movie
216         #endif
217
218         if (Current_level_num > 0)
219                 movie_name[2] = movie_table[Current_level_num-1];
220         else {
221                 #ifndef SHAREWARE
222                         return 0;       //no escapes for secret level
223                 #else
224                         Error("Invalid level number <%d>",Current_level_num);
225                 #endif
226         }
227
228         memcpy(save_pal,gr_palette,768);
229
230         #ifndef SHAREWARE
231                 r=PlayMovie(movie_name,(Game_mode & GM_MULTI)?0:MOVIE_REQUIRED);
232         #else
233                 return  0;      // movie not played for shareware
234         #endif
235
236         if (Newdemo_state == ND_STATE_PLAYBACK) {
237                 set_screen_mode(SCREEN_GAME);
238                 memcpy(gr_palette,save_pal,768);
239         }
240
241 #ifdef NETWORK
242    if (r==MOVIE_NOT_PLAYED && (Game_mode & GM_MULTI))
243           Kmatrix_nomovie_message=1;
244         else
245           Kmatrix_nomovie_message=0;
246 #endif
247
248         return (r);
249
250 }
251
252 void
253 free_endlevel_data()
254 {
255         if (terrain_bm_instance.bm_data)
256                 d_free(terrain_bm_instance.bm_data);
257
258         if (satellite_bm_instance.bm_data)
259                 d_free(satellite_bm_instance.bm_data);
260 }
261
262 void init_endlevel()
263 {
264         //##satellite_bitmap = bm_load("earth.bbm");
265         //##terrain_bitmap = bm_load("moon.bbm");
266         //##
267         //##load_terrain("matt5b.bbm");         //load bitmap as height array
268         //##//load_terrain("ttest2.bbm");               //load bitmap as height array
269
270         #ifdef STATION_ENABLED
271         station_bitmap = bm_load("steel3.bbm");
272         station_bitmap_list[0] = &station_bitmap;
273
274         station_modelnum = load_polygon_model("station.pof",1,station_bitmap_list,NULL);
275         #endif
276
277 //!!    exit_bitmap = bm_load("steel1.bbm");
278 //!!    exit_bitmap_list[0] = &exit_bitmap;
279
280 //!!    exit_modelnum = load_polygon_model("exit01.pof",1,exit_bitmap_list,NULL);
281 //!!    destroyed_exit_modelnum = load_polygon_model("exit01d.pof",1,exit_bitmap_list,NULL);
282
283         generate_starfield();
284
285         atexit(free_endlevel_data);
286
287         terrain_bm_instance.bm_data = satellite_bm_instance.bm_data = NULL;
288 }
289
290 object external_explosion;
291 int ext_expl_playing,mine_destroyed;
292
293 extern fix flash_scale;
294
295 vms_angvec exit_angles={-0xa00,0,0};
296
297 vms_matrix surface_orient;
298
299 int endlevel_data_loaded=0;
300 extern char last_palette_loaded[];
301
302 void start_endlevel_sequence()
303 {
304         int     i;
305         int movie_played = MOVIE_NOT_PLAYED;
306         int inited = 0;
307
308         if (!inited) {
309                 if (Piggy_hamfile_version >= 3)
310                         inited = load_exit_models();
311                 else
312                         inited = 1;
313         }
314
315         if (Newdemo_state == ND_STATE_RECORDING)                // stop demo recording
316                 Newdemo_state = ND_STATE_PAUSED;
317
318         if (Newdemo_state == ND_STATE_PLAYBACK) {               // don't do this if in playback mode
319                 if (Current_mission_num == Builtin_mission_num) //only play movie for built-in mission
320                         start_endlevel_movie();
321                 strcpy(last_palette_loaded,"");         //force palette load next time
322                 return;
323         }
324
325         if (Player_is_dead || ConsoleObject->flags&OF_SHOULD_BE_DEAD)
326                 return;                         //don't start if dead!
327
328         //      Dematerialize Buddy!
329         for (i=0; i<=Highest_object_index; i++)
330                 if (Objects[i].type == OBJ_ROBOT)
331                         if (Robot_info[Objects[i].id].companion) {
332                                 object_create_explosion(Objects[i].segnum, &Objects[i].pos, F1_0*7/2, VCLIP_POWERUP_DISAPPEARANCE );
333                                 Objects[i].flags |= OF_SHOULD_BE_DEAD;
334                         }
335
336         Players[Player_num].homing_object_dist = -F1_0; // Turn off homing sound.
337
338         reset_rear_view();              //turn off rear view if set
339
340 #ifdef NETWORK
341         if (Game_mode & GM_MULTI) {
342                 multi_send_endlevel_start(0);
343                 network_do_frame(1, 1);
344         }
345 #endif
346
347         if (Current_mission_num == Builtin_mission_num) {
348                 // only play movie for built-in mission
349                 if (!(Game_mode & GM_MULTI))
350                         movie_played = start_endlevel_movie();
351         }
352
353         if (inited && endlevel_data_loaded && (movie_played == MOVIE_NOT_PLAYED)) {
354                 //don't have movie.  Do rendered sequence, if available
355 #ifndef WINDOWS
356                 start_rendered_endlevel_sequence();
357 #endif
358                 return;
359         }
360
361         //don't have movie or rendered sequence, fade out
362         gr_palette_fade_out(gr_palette, 32, 0);
363
364         PlayerFinishedLevel(0);         //done with level
365 }
366
367 static int cockpit_mode_save;
368
369 void start_rendered_endlevel_sequence()
370 {
371         int last_segnum,exit_side,tunnel_length;
372
373         {
374                 int segnum,old_segnum,entry_side,i;
375
376                 //count segments in exit tunnel
377
378                 old_segnum = ConsoleObject->segnum;
379                 exit_side = find_exit_side(ConsoleObject);
380                 segnum = Segments[old_segnum].children[exit_side];
381                 tunnel_length = 0;
382                 do {
383                         entry_side = matt_find_connect_side(segnum,old_segnum);
384                         exit_side = Side_opposite[entry_side];
385                         old_segnum = segnum;
386                         segnum = Segments[segnum].children[exit_side];
387                         tunnel_length++;
388                 } while (segnum >= 0);
389
390                 if (segnum != -2) {
391                         PlayerFinishedLevel(0);         //don't do special sequence
392                         return;
393                 }
394
395                 last_segnum = old_segnum;
396
397                 //now pick transition segnum 1/3 of the way in
398
399                 old_segnum = ConsoleObject->segnum;
400                 exit_side = find_exit_side(ConsoleObject);
401                 segnum = Segments[old_segnum].children[exit_side];
402                 i=tunnel_length/3;
403                 while (i--) {
404
405                         entry_side = matt_find_connect_side(segnum,old_segnum);
406                         exit_side = Side_opposite[entry_side];
407                         old_segnum = segnum;
408                         segnum = Segments[segnum].children[exit_side];
409                 }
410                 transition_segnum = segnum;
411
412         }
413
414         cockpit_mode_save = Cockpit_mode;
415
416         #ifdef NETWORK
417         if (Game_mode & GM_MULTI) {
418                 multi_send_endlevel_start(0);
419                 network_do_frame(1, 1);
420         }
421         #endif
422
423         #ifdef SHAREWARE
424         Assert(last_segnum == exit_segnum);
425         //      songs_play_song( SONG_ENDLEVEL, 0 );    // JTS: Until we get an exit song, just don't worry
426         #endif
427
428         Endlevel_sequence = EL_FLYTHROUGH;
429
430         ConsoleObject->movement_type = MT_NONE;                 //movement handled by flythrough
431         ConsoleObject->control_type = CT_NONE;
432
433         Game_suspended |= SUSP_ROBOTS;          //robots don't move
434
435         cur_fly_speed = desired_fly_speed = FLY_SPEED;
436
437         start_endlevel_flythrough(0,ConsoleObject,cur_fly_speed);               //initialize
438
439         HUD_init_message( TXT_EXIT_SEQUENCE );
440
441         outside_mine = ext_expl_playing = 0;
442
443         flash_scale = f1_0;
444
445         //init_endlevel();
446
447         mine_destroyed=0;
448
449 }
450
451 extern flythrough_data fly_objects[];
452
453 extern object *slew_obj;
454
455 vms_angvec player_angles,player_dest_angles;
456 vms_angvec camera_desired_angles,camera_cur_angles;
457
458 #define CHASE_TURN_RATE (0x4000/4)              //max turn per second
459
460 //returns bitmask of which angles are at dest. bits 0,1,2 = p,b,h
461 int chase_angles(vms_angvec *cur_angles,vms_angvec *desired_angles)
462 {
463         vms_angvec delta_angs,alt_angles,alt_delta_angs;
464         fix total_delta,alt_total_delta;
465         fix frame_turn;
466         int mask=0;
467
468         delta_angs.p = desired_angles->p - cur_angles->p;
469         delta_angs.h = desired_angles->h - cur_angles->h;
470         delta_angs.b = desired_angles->b - cur_angles->b;
471 //delta_angs.b = 0;
472
473 //printf("chasing angles...desired = %x %x %x, cur = %x %x %x   ",desired_angles->p,desired_angles->b,desired_angles->h,cur_angles->p,cur_angles->b,cur_angles->h);
474
475         total_delta = abs(delta_angs.p) + abs(delta_angs.b) + abs(delta_angs.h);
476
477         alt_angles.p = f1_0/2 - cur_angles->p;
478         alt_angles.b = cur_angles->b + f1_0/2;
479         alt_angles.h = cur_angles->h + f1_0/2;
480
481         alt_delta_angs.p = desired_angles->p - alt_angles.p;
482         alt_delta_angs.h = desired_angles->h - alt_angles.h;
483         alt_delta_angs.b = desired_angles->b - alt_angles.b;
484 //alt_delta_angs.b = 0;
485
486         alt_total_delta = abs(alt_delta_angs.p) + abs(alt_delta_angs.b) + abs(alt_delta_angs.h);
487
488 //printf("Total delta = %x, alt total_delta = %x\n",total_delta,alt_total_delta);
489
490         if (alt_total_delta < total_delta) {
491                 //mprintf((0,"FLIPPING ANGLES!\n"));
492                 //printf("FLIPPING ANGLES!\n");
493                 *cur_angles = alt_angles;
494                 delta_angs = alt_delta_angs;
495         }
496
497         frame_turn = fixmul(FrameTime,CHASE_TURN_RATE);
498
499         if (abs(delta_angs.p) < frame_turn) {
500                 cur_angles->p = desired_angles->p;
501                 mask |= 1;
502         }
503         else
504                 if (delta_angs.p > 0)
505                         cur_angles->p += frame_turn;
506                 else
507                         cur_angles->p -= frame_turn;
508
509         if (abs(delta_angs.b) < frame_turn) {
510                 cur_angles->b = desired_angles->b;
511                 mask |= 2;
512         }
513         else
514                 if (delta_angs.b > 0)
515                         cur_angles->b += frame_turn;
516                 else
517                         cur_angles->b -= frame_turn;
518 //cur_angles->b = 0;
519
520         if (abs(delta_angs.h) < frame_turn) {
521                 cur_angles->h = desired_angles->h;
522                 mask |= 4;
523         }
524         else
525                 if (delta_angs.h > 0)
526                         cur_angles->h += frame_turn;
527                 else
528                         cur_angles->h -= frame_turn;
529
530         return mask;
531 }
532
533 void stop_endlevel_sequence()
534 {
535         Interpolation_method = 0;
536
537         gr_palette_fade_out(gr_palette, 32, 0);
538
539         select_cockpit(cockpit_mode_save);
540
541         Endlevel_sequence = EL_OFF;
542
543         PlayerFinishedLevel(0);
544
545 }
546
547 #define VCLIP_BIG_PLAYER_EXPLOSION      58
548
549 //--unused-- vms_vector upvec = {0,f1_0,0};
550
551 //find the angle between the player's heading & the station
552 void get_angs_to_object(vms_angvec *av,vms_vector *targ_pos,vms_vector *cur_pos)
553 {
554         vms_vector tv;
555
556         vm_vec_sub(&tv,targ_pos,cur_pos);
557
558         vm_extract_angles_vector(av,&tv);
559 }
560
561 void do_endlevel_frame()
562 {
563         static fix timer;
564         static fix bank_rate;
565         vms_vector save_last_pos;
566         static fix explosion_wait1=0;
567         static fix explosion_wait2=0;
568         static fix ext_expl_halflife;
569
570         save_last_pos = ConsoleObject->last_pos;        //don't let move code change this
571         object_move_all();
572         ConsoleObject->last_pos = save_last_pos;
573
574         if (ext_expl_playing) {
575
576                 external_explosion.lifeleft -= FrameTime;
577                 do_explosion_sequence(&external_explosion);
578
579                 if (external_explosion.lifeleft < ext_expl_halflife)
580                         mine_destroyed = 1;
581
582                 if (external_explosion.flags & OF_SHOULD_BE_DEAD)
583                         ext_expl_playing = 0;
584         }
585
586         if (cur_fly_speed != desired_fly_speed) {
587                 fix delta = desired_fly_speed - cur_fly_speed;
588                 fix frame_accel = fixmul(FrameTime,FLY_ACCEL);
589
590                 if (abs(delta) < frame_accel)
591                         cur_fly_speed = desired_fly_speed;
592                 else
593                         if (delta > 0)
594                                 cur_fly_speed += frame_accel;
595                         else
596                                 cur_fly_speed -= frame_accel;
597         }
598
599         //do big explosions
600         if (!outside_mine) {
601
602                 if (Endlevel_sequence==EL_OUTSIDE) {
603                         vms_vector tvec;
604
605                         vm_vec_sub(&tvec,&ConsoleObject->pos,&mine_side_exit_point);
606
607                         if (vm_vec_dot(&tvec,&mine_exit_orient.fvec) > 0) {
608                                 object *tobj;
609
610                                 outside_mine = 1;
611
612                                 tobj = object_create_explosion(exit_segnum,&mine_side_exit_point,i2f(50),VCLIP_BIG_PLAYER_EXPLOSION);
613
614                                 if (tobj) {
615                                         external_explosion = *tobj;
616
617                                         tobj->flags |= OF_SHOULD_BE_DEAD;
618
619                                         flash_scale = 0;        //kill lights in mine
620
621                                         ext_expl_halflife = tobj->lifeleft;
622
623                                         ext_expl_playing = 1;
624                                 }
625
626                                 digi_link_sound_to_pos( SOUND_BIG_ENDLEVEL_EXPLOSION, exit_segnum, 0, &mine_side_exit_point, 0, i2f(3)/4 );
627                         }
628                 }
629
630                 //do explosions chasing player
631                 if ((explosion_wait1-=FrameTime) < 0) {
632                         vms_vector tpnt;
633                         int segnum;
634                         object *expl;
635                         static int sound_count;
636
637                         vm_vec_scale_add(&tpnt,&ConsoleObject->pos,&ConsoleObject->orient.fvec,-ConsoleObject->size*5);
638                         vm_vec_scale_add2(&tpnt,&ConsoleObject->orient.rvec,(d_rand()-RAND_MAX/2)*15);
639                         vm_vec_scale_add2(&tpnt,&ConsoleObject->orient.uvec,(d_rand()-RAND_MAX/2)*15);
640
641                         segnum = find_point_seg(&tpnt,ConsoleObject->segnum);
642
643                         if (segnum != -1) {
644                                 expl = object_create_explosion(segnum,&tpnt,i2f(20),VCLIP_BIG_PLAYER_EXPLOSION);
645                                 if (d_rand()<10000 || ++sound_count==7) {               //pseudo-random
646                                         digi_link_sound_to_pos( SOUND_TUNNEL_EXPLOSION, segnum, 0, &tpnt, 0, F1_0 );
647                                         sound_count=0;
648                                 }
649                         }
650
651                         explosion_wait1 = 0x2000 + d_rand()/4;
652
653                 }
654         }
655
656         //do little explosions on walls
657         if (Endlevel_sequence >= EL_FLYTHROUGH && Endlevel_sequence < EL_OUTSIDE)
658                 if ((explosion_wait2-=FrameTime) < 0) {
659                         vms_vector tpnt;
660                         fvi_query fq;
661                         fvi_info hit_data;
662
663                         //create little explosion on wall
664
665                         vm_vec_copy_scale(&tpnt,&ConsoleObject->orient.rvec,(d_rand()-RAND_MAX/2)*100);
666                         vm_vec_scale_add2(&tpnt,&ConsoleObject->orient.uvec,(d_rand()-RAND_MAX/2)*100);
667                         vm_vec_add2(&tpnt,&ConsoleObject->pos);
668
669                         if (Endlevel_sequence == EL_FLYTHROUGH)
670                                 vm_vec_scale_add2(&tpnt,&ConsoleObject->orient.fvec,d_rand()*200);
671                         else
672                                 vm_vec_scale_add2(&tpnt,&ConsoleObject->orient.fvec,d_rand()*60);
673
674                         //find hit point on wall
675
676                         fq.p0 = &ConsoleObject->pos;
677                         fq.p1 = &tpnt;
678                         fq.startseg = ConsoleObject->segnum;
679                         fq.rad = 0;
680                         fq.thisobjnum = 0;
681                         fq.ignore_obj_list = NULL;
682                         fq.flags = 0;
683
684                         find_vector_intersection(&fq,&hit_data);
685
686                         if (hit_data.hit_type==HIT_WALL && hit_data.hit_seg!=-1)
687                                 object_create_explosion(hit_data.hit_seg,&hit_data.hit_pnt,i2f(3)+d_rand()*6,VCLIP_SMALL_EXPLOSION);
688
689                         explosion_wait2 = (0xa00 + d_rand()/8)/2;
690                 }
691
692         switch (Endlevel_sequence) {
693
694                 case EL_OFF: return;
695
696                 case EL_FLYTHROUGH: {
697
698                         do_endlevel_flythrough(0);
699
700                         if (ConsoleObject->segnum == transition_segnum) {
701
702                                 if ((Current_mission_num == Builtin_mission_num) &&
703                                         (start_endlevel_movie() != MOVIE_NOT_PLAYED))
704                                         stop_endlevel_sequence();
705                                 else {
706                                         int objnum;
707
708                                         //songs_play_song( SONG_ENDLEVEL, 0 );
709
710                                         Endlevel_sequence = EL_LOOKBACK;
711
712                                         objnum = obj_create(OBJ_CAMERA, 0,
713                                                             ConsoleObject->segnum,&ConsoleObject->pos,&ConsoleObject->orient,0,
714                                                             CT_NONE,MT_NONE,RT_NONE);
715
716                                         if (objnum == -1) { //can't get object, so abort
717                                                 mprintf((1, "Can't get object for endlevel sequence.  Aborting endlevel sequence.\n"));
718                                                 stop_endlevel_sequence();
719                                                 return;
720                                         }
721
722                                         Viewer = endlevel_camera = &Objects[objnum];
723
724                                         select_cockpit(CM_LETTERBOX);
725
726                                         fly_objects[1] = fly_objects[0];
727                                         fly_objects[1].obj = endlevel_camera;
728                                         fly_objects[1].speed = (5*cur_fly_speed)/4;
729                                         fly_objects[1].offset_frac = 0x4000;
730
731                                         vm_vec_scale_add2(&endlevel_camera->pos,&endlevel_camera->orient.fvec,i2f(7));
732
733                                         timer=0x20000;
734
735                                 }
736                         }
737
738                         break;
739                 }
740
741
742                 case EL_LOOKBACK: {
743
744                         do_endlevel_flythrough(0);
745                         do_endlevel_flythrough(1);
746
747                         if (timer>0) {
748
749                                 timer -= FrameTime;
750
751                                 if (timer < 0)          //reduce speed
752                                         fly_objects[1].speed = fly_objects[0].speed;
753                         }
754
755                         if (endlevel_camera->segnum == exit_segnum) {
756                                 vms_angvec cam_angles,exit_seg_angles;
757
758                                 Endlevel_sequence = EL_OUTSIDE;
759
760                                 timer = i2f(2);
761
762                                 vm_vec_negate(&endlevel_camera->orient.fvec);
763                                 vm_vec_negate(&endlevel_camera->orient.rvec);
764
765                                 vm_extract_angles_matrix(&cam_angles,&endlevel_camera->orient);
766                                 vm_extract_angles_matrix(&exit_seg_angles,&mine_exit_orient);
767                                 bank_rate = (-exit_seg_angles.b - cam_angles.b)/2;
768
769                                 ConsoleObject->control_type = endlevel_camera->control_type = CT_NONE;
770
771 #ifdef SLEW_ON
772  slew_obj = endlevel_camera;
773 #endif
774                         }
775
776                         break;
777                 }
778
779                 case EL_OUTSIDE: {
780                         #ifndef SLEW_ON
781                         vms_angvec cam_angles;
782                         #endif
783
784                         vm_vec_scale_add2(&ConsoleObject->pos,&ConsoleObject->orient.fvec,fixmul(FrameTime,cur_fly_speed));
785 #ifndef SLEW_ON
786                         vm_vec_scale_add2(&endlevel_camera->pos,&endlevel_camera->orient.fvec,fixmul(FrameTime,-2*cur_fly_speed));
787                         vm_vec_scale_add2(&endlevel_camera->pos,&endlevel_camera->orient.uvec,fixmul(FrameTime,-cur_fly_speed/10));
788
789                         vm_extract_angles_matrix(&cam_angles,&endlevel_camera->orient);
790                         cam_angles.b += fixmul(bank_rate,FrameTime);
791                         vm_angles_2_matrix(&endlevel_camera->orient,&cam_angles);
792 #endif
793
794                         timer -= FrameTime;
795
796                         if (timer < 0) {
797
798                                 Endlevel_sequence = EL_STOPPED;
799
800                                 vm_extract_angles_matrix(&player_angles,&ConsoleObject->orient);
801
802                                 timer = i2f(3);
803
804                         }
805
806                         break;
807                 }
808
809                 case EL_STOPPED: {
810
811                         get_angs_to_object(&player_dest_angles,&station_pos,&ConsoleObject->pos);
812                         chase_angles(&player_angles,&player_dest_angles);
813                         vm_angles_2_matrix(&ConsoleObject->orient,&player_angles);
814
815                         vm_vec_scale_add2(&ConsoleObject->pos,&ConsoleObject->orient.fvec,fixmul(FrameTime,cur_fly_speed));
816
817                         timer -= FrameTime;
818
819                         if (timer < 0) {
820
821                                 #ifdef SLEW_ON
822                                 slew_obj = endlevel_camera;
823                                 _do_slew_movement(endlevel_camera,1,1);
824                                 timer += FrameTime;             //make time stop
825                                 break;
826                                 #else
827
828                                 #ifdef SHORT_SEQUENCE
829
830                                 stop_endlevel_sequence();
831
832                                 #else
833                                 Endlevel_sequence = EL_PANNING;
834
835                                 vm_extract_angles_matrix(&camera_cur_angles,&endlevel_camera->orient);
836
837
838                                 timer = i2f(3);
839
840                                 if (Game_mode & GM_MULTI) { // try to skip part of the seq if multiplayer
841                                         stop_endlevel_sequence();
842                                         return;
843                                 }
844
845                                 //mprintf((0,"Switching to pan...\n"));
846                                 #endif          //SHORT_SEQUENCE
847                                 #endif          //SLEW_ON
848
849                         }
850                         break;
851                 }
852
853                 #ifndef SHORT_SEQUENCE
854                 case EL_PANNING: {
855                         #ifndef SLEW_ON
856                         int mask;
857                         #endif
858
859                         get_angs_to_object(&player_dest_angles,&station_pos,&ConsoleObject->pos);
860                         chase_angles(&player_angles,&player_dest_angles);
861                         vm_angles_2_matrix(&ConsoleObject->orient,&player_angles);
862                         vm_vec_scale_add2(&ConsoleObject->pos,&ConsoleObject->orient.fvec,fixmul(FrameTime,cur_fly_speed));
863
864                         #ifdef SLEW_ON
865                         _do_slew_movement(endlevel_camera,1,1);
866                         #else
867
868                         get_angs_to_object(&camera_desired_angles,&ConsoleObject->pos,&endlevel_camera->pos);
869                         mask = chase_angles(&camera_cur_angles,&camera_desired_angles);
870                         vm_angles_2_matrix(&endlevel_camera->orient,&camera_cur_angles);
871
872                         if ((mask&5) == 5) {
873
874                                 vms_vector tvec;
875
876                                 Endlevel_sequence = EL_CHASING;
877
878                                 vm_vec_normalized_dir_quick(&tvec,&station_pos,&ConsoleObject->pos);
879                                 vm_vector_2_matrix(&ConsoleObject->orient,&tvec,&surface_orient.uvec,NULL);
880
881                                 desired_fly_speed *= 2;
882
883                                 //mprintf((0,"Switching to chase...\n"));
884
885                         }
886                         #endif
887
888                         break;
889                 }
890
891                 case EL_CHASING: {
892                         fix d,speed_scale;
893
894                         #ifdef SLEW_ON
895                         _do_slew_movement(endlevel_camera,1,1);
896                         #endif
897
898                         get_angs_to_object(&camera_desired_angles,&ConsoleObject->pos,&endlevel_camera->pos);
899                         chase_angles(&camera_cur_angles,&camera_desired_angles);
900
901                         #ifndef SLEW_ON
902                         vm_angles_2_matrix(&endlevel_camera->orient,&camera_cur_angles);
903                         #endif
904
905                         d = vm_vec_dist_quick(&ConsoleObject->pos,&endlevel_camera->pos);
906
907                         speed_scale = fixdiv(d,i2f(0x20));
908                         if (d<f1_0) d=f1_0;
909
910                         get_angs_to_object(&player_dest_angles,&station_pos,&ConsoleObject->pos);
911                         chase_angles(&player_angles,&player_dest_angles);
912                         vm_angles_2_matrix(&ConsoleObject->orient,&player_angles);
913
914                         vm_vec_scale_add2(&ConsoleObject->pos,&ConsoleObject->orient.fvec,fixmul(FrameTime,cur_fly_speed));
915                         #ifndef SLEW_ON
916                         vm_vec_scale_add2(&endlevel_camera->pos,&endlevel_camera->orient.fvec,fixmul(FrameTime,fixmul(speed_scale,cur_fly_speed)));
917
918                         if (vm_vec_dist(&ConsoleObject->pos,&station_pos) < i2f(10))
919                                 stop_endlevel_sequence();
920                         #endif
921
922                         break;
923
924                 }
925                 #endif          //ifdef SHORT_SEQUENCE
926
927         }
928 }
929
930
931 #define MIN_D 0x100
932
933 //find which side to fly out of
934 int find_exit_side(object *obj)
935 {
936         int i;
937         vms_vector prefvec,segcenter,sidevec;
938         fix best_val=-f2_0;
939         int best_side;
940         segment *pseg = &Segments[obj->segnum];
941
942         //find exit side
943
944         vm_vec_normalized_dir_quick(&prefvec,&obj->pos,&obj->last_pos);
945
946         compute_segment_center(&segcenter,pseg);
947
948         best_side=-1;
949         for (i=MAX_SIDES_PER_SEGMENT;--i >= 0;) {
950                 fix d;
951
952                 if (pseg->children[i]!=-1) {
953
954                         compute_center_point_on_side(&sidevec,pseg,i);
955                         vm_vec_normalized_dir_quick(&sidevec,&sidevec,&segcenter);
956                         d = vm_vec_dotprod(&sidevec,&prefvec);
957
958                         if (labs(d) < MIN_D) d=0;
959
960                         if (d > best_val) {best_val=d; best_side=i;}
961
962                 }
963         }
964
965         Assert(best_side!=-1);
966
967         return best_side;
968 }
969
970 extern fix Render_zoom;                                                 //the player's zoom factor
971
972 extern vms_vector Viewer_eye;   //valid during render
973
974 void draw_exit_model()
975 {
976         vms_vector model_pos;
977         int f=15,u=0;   //21;
978
979         vm_vec_scale_add(&model_pos,&mine_exit_point,&mine_exit_orient.fvec,i2f(f));
980         vm_vec_scale_add2(&model_pos,&mine_exit_orient.uvec,i2f(u));
981
982         draw_polygon_model(&model_pos,&mine_exit_orient,NULL,(mine_destroyed)?destroyed_exit_modelnum:exit_modelnum,0,f1_0,NULL,NULL);
983
984 }
985
986 int exit_point_bmx,exit_point_bmy;
987
988 fix satellite_size = i2f(400);
989
990 #define SATELLITE_DIST          i2f(1024)
991 #define SATELLITE_WIDTH         satellite_size
992 #define SATELLITE_HEIGHT        ((satellite_size*9)/4)          //((satellite_size*5)/2)
993
994 void render_external_scene(fix eye_offset)
995 {
996
997         Viewer_eye = Viewer->pos;
998
999         if (eye_offset)
1000                 vm_vec_scale_add2(&Viewer_eye,&Viewer->orient.rvec,eye_offset);
1001
1002         g3_set_view_matrix(&Viewer->pos,&Viewer->orient,Render_zoom);
1003
1004         //g3_draw_horizon(BM_XRGB(0,0,0),BM_XRGB(16,16,16));            //,-1);
1005         gr_clear_canvas(BM_XRGB(0,0,0));
1006
1007         g3_start_instance_matrix(&vmd_zero_vector,&surface_orient);
1008         draw_stars();
1009         g3_done_instance();
1010
1011         {       //draw satellite
1012
1013                 vms_vector delta;
1014                 g3s_point p,top_pnt;
1015
1016                 g3_rotate_point(&p,&satellite_pos);
1017                 g3_rotate_delta_vec(&delta,&satellite_upvec);
1018
1019                 g3_add_delta_vec(&top_pnt,&p,&delta);
1020
1021                 if (! (p.p3_codes & CC_BEHIND)) {
1022                         int save_im = Interpolation_method;
1023                         //p.p3_flags &= ~PF_PROJECTED;
1024                         //g3_project_point(&p);
1025                         if (! (p.p3_flags & PF_OVERFLOW)) {
1026                                 Interpolation_method = 0;
1027                                 //gr_bitmapm(f2i(p.p3_sx)-32,f2i(p.p3_sy)-32,satellite_bitmap);
1028                                 g3_draw_rod_tmap(satellite_bitmap,&p,SATELLITE_WIDTH,&top_pnt,SATELLITE_WIDTH,f1_0);
1029                                 Interpolation_method = save_im;
1030                         }
1031                 }
1032         }
1033
1034         #ifdef STATION_ENABLED
1035         draw_polygon_model(&station_pos,&vmd_identity_matrix,NULL,station_modelnum,0,f1_0,NULL,NULL);
1036         #endif
1037
1038         render_terrain(&mine_ground_exit_point,exit_point_bmx,exit_point_bmy);
1039
1040         draw_exit_model();
1041         if (ext_expl_playing)
1042                 draw_fireball(&external_explosion);
1043
1044         Lighting_on=0;
1045         render_object(ConsoleObject);
1046         Lighting_on=1;
1047 }
1048
1049 #define MAX_STARS 500
1050
1051 vms_vector stars[MAX_STARS];
1052
1053 void generate_starfield()
1054 {
1055         int i;
1056
1057         for (i=0;i<MAX_STARS;i++) {
1058
1059                 stars[i].x = (d_rand() - RAND_MAX/2) << 14;
1060                 stars[i].z = (d_rand() - RAND_MAX/2) << 14;
1061                 stars[i].y = (d_rand()/2) << 14;
1062
1063         }
1064 }
1065
1066 void draw_stars()
1067 {
1068         int i;
1069         int intensity=31;
1070         g3s_point p;
1071
1072         for (i=0;i<MAX_STARS;i++) {
1073
1074                 if ((i&63) == 0) {
1075                         gr_setcolor(BM_XRGB(intensity,intensity,intensity));
1076                         intensity-=3;
1077                 }
1078
1079                 //g3_rotate_point(&p,&stars[i]);
1080                 g3_rotate_delta_vec(&p.p3_vec,&stars[i]);
1081                 g3_code_point(&p);
1082
1083                 if (p.p3_codes == 0) {
1084
1085                         p.p3_flags &= ~PF_PROJECTED;
1086
1087                         g3_project_point(&p);
1088
1089                         gr_pixel(f2i(p.p3_sx),f2i(p.p3_sy));
1090                 }
1091         }
1092
1093 //@@    {
1094 //@@            vms_vector delta;
1095 //@@            g3s_point top_pnt;
1096 //@@
1097 //@@            g3_rotate_point(&p,&satellite_pos);
1098 //@@            g3_rotate_delta_vec(&delta,&satellite_upvec);
1099 //@@
1100 //@@            g3_add_delta_vec(&top_pnt,&p,&delta);
1101 //@@
1102 //@@            if (! (p.p3_codes & CC_BEHIND)) {
1103 //@@                    int save_im = Interpolation_method;
1104 //@@                    Interpolation_method = 0;
1105 //@@                    //p.p3_flags &= ~PF_PROJECTED;
1106 //@@                    g3_project_point(&p);
1107 //@@                    if (! (p.p3_flags & PF_OVERFLOW))
1108 //@@                            //gr_bitmapm(f2i(p.p3_sx)-32,f2i(p.p3_sy)-32,satellite_bitmap);
1109 //@@                            g3_draw_rod_tmap(satellite_bitmap,&p,SATELLITE_WIDTH,&top_pnt,SATELLITE_WIDTH,f1_0);
1110 //@@                    Interpolation_method = save_im;
1111 //@@            }
1112 //@@    }
1113
1114 }
1115
1116 void endlevel_render_mine(fix eye_offset)
1117 {
1118         int start_seg_num;
1119
1120         Viewer_eye = Viewer->pos;
1121
1122         if (Viewer->type == OBJ_PLAYER )
1123                 vm_vec_scale_add2(&Viewer_eye,&Viewer->orient.fvec,(Viewer->size*3)/4);
1124
1125         if (eye_offset)
1126                 vm_vec_scale_add2(&Viewer_eye,&Viewer->orient.rvec,eye_offset);
1127
1128         #ifdef EDITOR
1129         if (Function_mode==FMODE_EDITOR)
1130                 Viewer_eye = Viewer->pos;
1131         #endif
1132
1133         if (Endlevel_sequence >= EL_OUTSIDE) {
1134
1135                 start_seg_num = exit_segnum;
1136         }
1137         else {
1138                 start_seg_num = find_point_seg(&Viewer_eye,Viewer->segnum);
1139
1140                 if (start_seg_num==-1)
1141                         start_seg_num = Viewer->segnum;
1142         }
1143
1144         if (Endlevel_sequence == EL_LOOKBACK) {
1145                 vms_matrix headm,viewm;
1146                 vms_angvec angles = {0,0,0x7fff};
1147
1148                 vm_angles_2_matrix(&headm,&angles);
1149                 vm_matrix_x_matrix(&viewm,&Viewer->orient,&headm);
1150                 g3_set_view_matrix(&Viewer_eye,&viewm,Render_zoom);
1151         }
1152         else
1153                 g3_set_view_matrix(&Viewer_eye,&Viewer->orient,Render_zoom);
1154
1155         render_mine(start_seg_num,eye_offset, 0);
1156 }
1157
1158 void render_endlevel_frame(fix eye_offset)
1159 {
1160
1161         g3_start_frame();
1162
1163         if (Endlevel_sequence < EL_OUTSIDE)
1164                 endlevel_render_mine(eye_offset);
1165         else
1166                 render_external_scene(eye_offset);
1167
1168         g3_end_frame();
1169
1170 }
1171
1172
1173 ///////////////////////// copy of flythrough code for endlevel
1174
1175
1176 #define MAX_FLY_OBJECTS 2
1177
1178 flythrough_data fly_objects[MAX_FLY_OBJECTS];
1179
1180 flythrough_data *flydata;
1181
1182 int matt_find_connect_side(int seg0,int seg1);
1183
1184 void compute_segment_center(vms_vector *vp,segment *sp);
1185
1186 fixang delta_ang(fixang a,fixang b);
1187 fixang interp_angle(fixang dest,fixang src,fixang step);
1188
1189 #define DEFAULT_SPEED i2f(16)
1190
1191 #define MIN_D 0x100
1192
1193 //if speed is zero, use default speed
1194 void start_endlevel_flythrough(int n,object *obj,fix speed)
1195 {
1196         flydata = &fly_objects[n];
1197
1198         flydata->obj = obj;
1199
1200         flydata->first_time = 1;
1201
1202         flydata->speed = speed?speed:DEFAULT_SPEED;
1203
1204         flydata->offset_frac = 0;
1205 }
1206
1207 static vms_angvec *angvec_add2_scale(vms_angvec *dest,vms_vector *src,fix s)
1208 {
1209         dest->p += fixmul(src->x,s);
1210         dest->b  += fixmul(src->z,s);
1211         dest->h  += fixmul(src->y,s);
1212
1213         return dest;
1214 }
1215
1216 #define MAX_ANGSTEP     0x4000          //max turn per second
1217
1218 #define MAX_SLIDE_PER_SEGMENT 0x10000
1219
1220 void do_endlevel_flythrough(int n)
1221 {
1222         object *obj;
1223         segment *pseg;
1224         int old_player_seg;
1225
1226         flydata = &fly_objects[n];
1227         obj = flydata->obj;
1228         
1229         old_player_seg = obj->segnum;
1230
1231         //move the player for this frame
1232
1233         if (!flydata->first_time) {
1234
1235                 vm_vec_scale_add2(&obj->pos,&flydata->step,FrameTime);
1236                 angvec_add2_scale(&flydata->angles,&flydata->angstep,FrameTime);
1237
1238                 vm_angles_2_matrix(&obj->orient,&flydata->angles);
1239         }
1240
1241         //check new player seg
1242
1243         update_object_seg(obj);
1244         pseg = &Segments[obj->segnum];
1245
1246         if (flydata->first_time || obj->segnum != old_player_seg) {             //moved into new seg
1247                 vms_vector curcenter,nextcenter;
1248                 fix step_size,seg_time;
1249                 short entry_side,exit_side = -1;//what sides we entry and leave through
1250                 vms_vector dest_point;          //where we are heading (center of exit_side)
1251                 vms_angvec dest_angles;         //where we want to be pointing
1252                 vms_matrix dest_orient;
1253                 int up_side=0;
1254
1255                 entry_side=0;
1256
1257                 //find new exit side
1258
1259                 if (!flydata->first_time) {
1260
1261                         entry_side = matt_find_connect_side(obj->segnum,old_player_seg);
1262                         exit_side = Side_opposite[entry_side];
1263                 }
1264
1265                 if (flydata->first_time || entry_side==-1 || pseg->children[exit_side]==-1)
1266                         exit_side = find_exit_side(obj);
1267
1268                 {                                                                               //find closest side to align to
1269                         fix d,largest_d=-f1_0;
1270                         int i;
1271
1272                         for (i=0;i<6;i++) {
1273                                 #ifdef COMPACT_SEGS
1274                                 vms_vector v1;
1275                                 get_side_normal(pseg, i, 0, &v1 );
1276                                 d = vm_vec_dot(&v1,&flydata->obj->orient.uvec);
1277                                 #else
1278                                 d = vm_vec_dot(&pseg->sides[i].normals[0],&flydata->obj->orient.uvec);
1279                                 #endif
1280                                 if (d > largest_d) {largest_d = d; up_side=i;}
1281                         }
1282
1283                 }
1284
1285                 //update target point & angles
1286
1287                 compute_center_point_on_side(&dest_point,pseg,exit_side);
1288
1289                 //update target point and movement points
1290
1291                 //offset object sideways
1292                 if (flydata->offset_frac) {
1293                         int s0=-1,s1=0,i;
1294                         vms_vector s0p,s1p;
1295                         fix dist;
1296
1297                         for (i=0;i<6;i++)
1298                                 if (i!=entry_side && i!=exit_side && i!=up_side && i!=Side_opposite[up_side])
1299                                  {
1300                                         if (s0==-1)
1301                                                 s0 = i;
1302                                         else
1303                                                 s1 = i;
1304                                  }
1305
1306                         compute_center_point_on_side(&s0p,pseg,s0);
1307                         compute_center_point_on_side(&s1p,pseg,s1);
1308                         dist = fixmul(vm_vec_dist(&s0p,&s1p),flydata->offset_frac);
1309
1310                         if (dist-flydata->offset_dist > MAX_SLIDE_PER_SEGMENT)
1311                                 dist = flydata->offset_dist + MAX_SLIDE_PER_SEGMENT;
1312
1313                         flydata->offset_dist = dist;
1314
1315                         vm_vec_scale_add2(&dest_point,&obj->orient.rvec,dist);
1316
1317                 }
1318
1319                 vm_vec_sub(&flydata->step,&dest_point,&obj->pos);
1320                 step_size = vm_vec_normalize_quick(&flydata->step);
1321                 vm_vec_scale(&flydata->step,flydata->speed);
1322
1323                 compute_segment_center(&curcenter,pseg);
1324                 compute_segment_center(&nextcenter,&Segments[pseg->children[exit_side]]);
1325                 vm_vec_sub(&flydata->headvec,&nextcenter,&curcenter);
1326
1327                 #ifdef COMPACT_SEGS
1328                 {
1329                         vms_vector _v1;
1330                         get_side_normal(pseg, up_side, 0, &_v1 );
1331                         vm_vector_2_matrix(&dest_orient,&flydata->headvec,&_v1,NULL);
1332                 }
1333                 #else
1334                 vm_vector_2_matrix(&dest_orient,&flydata->headvec,&pseg->sides[up_side].normals[0],NULL);
1335                 #endif
1336                 vm_extract_angles_matrix(&dest_angles,&dest_orient);
1337
1338                 if (flydata->first_time)
1339                         vm_extract_angles_matrix(&flydata->angles,&obj->orient);
1340
1341                 seg_time = fixdiv(step_size,flydata->speed);    //how long through seg
1342
1343                 if (seg_time) {
1344                         flydata->angstep.x = max(-MAX_ANGSTEP,min(MAX_ANGSTEP,fixdiv(delta_ang(flydata->angles.p,dest_angles.p),seg_time)));
1345                         flydata->angstep.z = max(-MAX_ANGSTEP,min(MAX_ANGSTEP,fixdiv(delta_ang(flydata->angles.b,dest_angles.b),seg_time)));
1346                         flydata->angstep.y = max(-MAX_ANGSTEP,min(MAX_ANGSTEP,fixdiv(delta_ang(flydata->angles.h,dest_angles.h),seg_time)));
1347
1348                 }
1349                 else {
1350                         flydata->angles = dest_angles;
1351                         flydata->angstep.x = flydata->angstep.y = flydata->angstep.z = 0;
1352                 }
1353         }
1354
1355         flydata->first_time=0;
1356 }
1357
1358 #define JOY_NULL 15
1359 #define ROT_SPEED 8             //rate of rotation while key held down
1360 #define VEL_SPEED (15)  //rate of acceleration while key held down
1361
1362 extern short old_joy_x,old_joy_y;       //position last time around
1363
1364 #include "key.h"
1365 #include "joy.h"
1366
1367 #ifdef SLEW_ON          //this is a special routine for slewing around external scene
1368 int _do_slew_movement(object *obj, int check_keys, int check_joy )
1369 {
1370         int moved = 0;
1371         vms_vector svel, movement;                              //scaled velocity (per this frame)
1372         vms_matrix rotmat,new_pm;
1373         int joy_x,joy_y,btns;
1374         int joyx_moved,joyy_moved;
1375         vms_angvec rotang;
1376
1377         if (keyd_pressed[KEY_PAD5])
1378                 vm_vec_zero(&obj->phys_info.velocity);
1379
1380         if (check_keys) {
1381                 obj->phys_info.velocity.x += VEL_SPEED * (key_down_time(KEY_PAD9) - key_down_time(KEY_PAD7));
1382                 obj->phys_info.velocity.y += VEL_SPEED * (key_down_time(KEY_PADMINUS) - key_down_time(KEY_PADPLUS));
1383                 obj->phys_info.velocity.z += VEL_SPEED * (key_down_time(KEY_PAD8) - key_down_time(KEY_PAD2));
1384
1385                 rotang.pitch =  (key_down_time(KEY_LBRACKET) - key_down_time(KEY_RBRACKET))/ROT_SPEED;
1386                 rotang.bank  = (key_down_time(KEY_PAD1) - key_down_time(KEY_PAD3))/ROT_SPEED;
1387                 rotang.head  = (key_down_time(KEY_PAD6) - key_down_time(KEY_PAD4))/ROT_SPEED;
1388         }
1389         else
1390                 rotang.pitch = rotang.bank  = rotang.head  = 0;
1391
1392         //check for joystick movement
1393
1394         if (check_joy && joy_present)   {
1395                 joy_get_pos(&joy_x,&joy_y);
1396                 btns=joy_get_btns();
1397
1398                 joyx_moved = (abs(joy_x - old_joy_x)>JOY_NULL);
1399                 joyy_moved = (abs(joy_y - old_joy_y)>JOY_NULL);
1400
1401                 if (abs(joy_x) < JOY_NULL) joy_x = 0;
1402                 if (abs(joy_y) < JOY_NULL) joy_y = 0;
1403
1404                 if (btns)
1405                         if (!rotang.pitch) rotang.pitch = fixmul(-joy_y * 512,FrameTime); else;
1406                 else
1407                         if (joyy_moved) obj->phys_info.velocity.z = -joy_y * 8192;
1408
1409                 if (!rotang.head) rotang.head = fixmul(joy_x * 512,FrameTime);
1410
1411                 if (joyx_moved) old_joy_x = joy_x;
1412                 if (joyy_moved) old_joy_y = joy_y;
1413         }
1414
1415         moved = rotang.pitch | rotang.bank | rotang.head;
1416
1417         vm_angles_2_matrix(&rotmat,&rotang);
1418         vm_matrix_x_matrix(&new_pm,&obj->orient,&rotmat);
1419         obj->orient = new_pm;
1420         vm_transpose_matrix(&new_pm);           //make those columns rows
1421
1422         moved |= obj->phys_info.velocity.x | obj->phys_info.velocity.y | obj->phys_info.velocity.z;
1423
1424         svel = obj->phys_info.velocity;
1425         vm_vec_scale(&svel,FrameTime);          //movement in this frame
1426         vm_vec_rotate(&movement,&svel,&new_pm);
1427
1428         vm_vec_add2(&obj->pos,&movement);
1429
1430         moved |= (movement.x || movement.y || movement.z);
1431
1432         return moved;
1433 }
1434 #endif
1435
1436 #define LINE_LEN        80
1437 #define NUM_VARS        8
1438
1439 #define STATION_DIST    i2f(1024)
1440
1441 int convert_ext( char *dest, char *ext )
1442 {
1443         char *t;
1444
1445         t = strchr(dest,'.');
1446
1447         if (t && (t-dest <= 8)) {
1448                 t[1] = ext[0];                  
1449                 t[2] = ext[1];                  
1450                 t[3] = ext[2];  
1451                 return 1;
1452         }
1453         else
1454                 return 0;
1455 }
1456
1457 //called for each level to load & setup the exit sequence
1458 void load_endlevel_data(int level_num)
1459 {
1460         char filename[13];
1461         char line[LINE_LEN],*p;
1462         CFILE *ifile;
1463         int var,segnum,sidenum;
1464         int exit_side=0, i;
1465         int have_binary = 0;
1466
1467         endlevel_data_loaded = 0;               //not loaded yet
1468
1469 try_again:
1470         ;
1471
1472         if (level_num<0)                //secret level
1473                 strcpy(filename,Secret_level_names[-level_num-1]);
1474         else                                    //normal level
1475                 strcpy(filename,Level_names[level_num-1]);
1476
1477         if (!convert_ext(filename,"END"))
1478                 Error("Error converting filename <%s> for endlevel data\n",filename);
1479
1480         ifile = cfopen(filename,"rb");
1481
1482         if (!ifile) {
1483
1484                 convert_ext(filename,"txb");
1485
1486                 ifile = cfopen(filename,"rb");
1487
1488                 if (!ifile) {
1489                         if (level_num==1) {
1490                                 con_printf(CON_DEBUG, "Cannot load file text of binary version of <%s>\n",filename);
1491                                 endlevel_data_loaded = 0;
1492                                 return;
1493                         }
1494                         else {
1495                                 level_num = 1;
1496                                 goto try_again;
1497                         }
1498                 }
1499
1500                 have_binary = 1;
1501         }
1502
1503         //ok...this parser is pretty simple.  It ignores comments, but
1504         //everything else must be in the right place
1505
1506         var = 0;
1507
1508         while (cfgets(line,LINE_LEN,ifile)) {
1509
1510                 if (have_binary) {
1511                         for (i = 0; i < strlen(line) - 1; i++) {
1512                                 encode_rotate_left(&(line[i]));
1513                                 line[i] = line[i] ^ BITMAP_TBL_XOR;
1514                                 encode_rotate_left(&(line[i]));
1515                         }
1516                         p = line;
1517                 }
1518
1519                 if ((p=strchr(line,';'))!=NULL)
1520                         *p = 0;         //cut off comment
1521
1522                 for (p=line+strlen(line)-1;p>line && isspace(*p);*p--=0);
1523                 for (p=line;isspace(*p);p++);
1524
1525                 if (!*p)                //empty line
1526                         continue;
1527
1528                 switch (var) {
1529
1530                         case 0: {                                               //ground terrain
1531                                 int iff_error;
1532                                 ubyte pal[768];
1533
1534                                 if (terrain_bm_instance.bm_data)
1535                                         d_free(terrain_bm_instance.bm_data);
1536
1537                                 Assert(terrain_bm_instance.bm_data == NULL);
1538
1539                                 iff_error = iff_read_bitmap(p,&terrain_bm_instance,BM_LINEAR,pal);
1540                                 if (iff_error != IFF_NO_ERROR) {
1541                                         Error("File %s - IFF error: %s",p,iff_errormsg(iff_error));
1542                                 }
1543
1544                                 terrain_bitmap = &terrain_bm_instance;
1545
1546                                 gr_remap_bitmap_good( terrain_bitmap, pal, iff_transparent_color, -1);
1547
1548                                 break;
1549                         }
1550
1551                         case 1:                                                 //height map
1552
1553                                 load_terrain(p);
1554                                 break;
1555
1556
1557                         case 2:
1558
1559                                 sscanf(p,"%d,%d",&exit_point_bmx,&exit_point_bmy);
1560                                 break;
1561
1562                         case 3:                                                 //exit heading
1563
1564                                 exit_angles.h = i2f(atoi(p))/360;
1565                                 break;
1566
1567                         case 4: {                                               //planet bitmap
1568                                 int iff_error;
1569                                 ubyte pal[768];
1570
1571                                 if (satellite_bm_instance.bm_data)
1572                                         d_free(satellite_bm_instance.bm_data);
1573
1574                                 iff_error = iff_read_bitmap(p,&satellite_bm_instance,BM_LINEAR,pal);
1575                                 if (iff_error != IFF_NO_ERROR) {
1576                                         mprintf((1, "File %s - IFF error: %s",p,iff_errormsg(iff_error)));
1577                                         Error("File %s - IFF error: %s",p,iff_errormsg(iff_error));
1578                                 }
1579
1580                                 satellite_bitmap = &satellite_bm_instance;
1581                                 gr_remap_bitmap_good( satellite_bitmap, pal, iff_transparent_color, -1);
1582
1583                                 break;
1584                         }
1585
1586                         case 5:                                                 //earth pos
1587                         case 7: {                                               //station pos
1588                                 vms_matrix tm;
1589                                 vms_angvec ta;
1590                                 int pitch,head;
1591
1592                                 sscanf(p,"%d,%d",&head,&pitch);
1593
1594                                 ta.h = i2f(head)/360;
1595                                 ta.p = -i2f(pitch)/360;
1596                                 ta.b = 0;
1597
1598                                 vm_angles_2_matrix(&tm,&ta);
1599
1600                                 if (var==5)
1601                                         satellite_pos = tm.fvec;
1602                                         //vm_vec_copy_scale(&satellite_pos,&tm.fvec,SATELLITE_DIST);
1603                                 else
1604                                         station_pos = tm.fvec;
1605
1606                                 break;
1607                         }
1608
1609                         case 6:                                         //planet size
1610                                 satellite_size = i2f(atoi(p));
1611                                 break;
1612                 }
1613
1614                 var++;
1615
1616         }
1617
1618         Assert(var == NUM_VARS);
1619
1620
1621         // OK, now the data is loaded.  Initialize everything
1622
1623         //find the exit sequence by searching all segments for a side with
1624         //children == -2
1625
1626         for (segnum=0,exit_segnum=-1;exit_segnum==-1 && segnum<=Highest_segment_index;segnum++)
1627                 for (sidenum=0;sidenum<6;sidenum++)
1628                         if (Segments[segnum].children[sidenum] == -2) {
1629                                 exit_segnum = segnum;
1630                                 exit_side = sidenum;
1631                                 break;
1632                         }
1633
1634         Assert(exit_segnum!=-1);
1635
1636         compute_segment_center(&mine_exit_point,&Segments[exit_segnum]);
1637         extract_orient_from_segment(&mine_exit_orient,&Segments[exit_segnum]);
1638         compute_center_point_on_side(&mine_side_exit_point,&Segments[exit_segnum],exit_side);
1639
1640         vm_vec_scale_add(&mine_ground_exit_point,&mine_exit_point,&mine_exit_orient.uvec,-i2f(20));
1641
1642         //compute orientation of surface
1643         {
1644                 vms_vector tv;
1645                 vms_matrix exit_orient,tm;
1646
1647                 vm_angles_2_matrix(&exit_orient,&exit_angles);
1648                 vm_transpose_matrix(&exit_orient);
1649                 vm_matrix_x_matrix(&surface_orient,&mine_exit_orient,&exit_orient);
1650
1651                 vm_copy_transpose_matrix(&tm,&surface_orient);
1652                 vm_vec_rotate(&tv,&station_pos,&tm);
1653                 vm_vec_scale_add(&station_pos,&mine_exit_point,&tv,STATION_DIST);
1654
1655                 vm_vec_rotate(&tv,&satellite_pos,&tm);
1656                 vm_vec_scale_add(&satellite_pos,&mine_exit_point,&tv,SATELLITE_DIST);
1657
1658                 vm_vector_2_matrix(&tm,&tv,&surface_orient.uvec,NULL);
1659                 vm_vec_copy_scale(&satellite_upvec,&tm.uvec,SATELLITE_HEIGHT);
1660
1661
1662         }
1663
1664         cfclose(ifile);
1665
1666         endlevel_data_loaded = 1;
1667
1668 }