]> icculus.org git repositories - taylor/freespace2.git/blob - src/asteroid/asteroid.cpp
last few struct changes
[taylor/freespace2.git] / src / asteroid / asteroid.cpp
1 /*
2  * Copyright (C) Volition, Inc. 1999.  All rights reserved.
3  *
4  * All source code herein is the property of Volition, Inc. You may not sell 
5  * or otherwise commercially exploit the source or things you created based on
6  * the source.
7  */
8
9 /*
10  * $Logfile: /Freespace2/code/Asteroid/Asteroid.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * C module for asteroid code
16  *
17  * $Log$
18  * Revision 1.4  2002/06/18 08:58:53  relnev
19  * last few struct changes
20  *
21  * Revision 1.3  2002/06/09 04:41:15  relnev
22  * added copyright header
23  *
24  * Revision 1.2  2002/05/07 03:16:43  theoddone33
25  * The Great Newline Fix
26  *
27  * Revision 1.1.1.1  2002/05/03 03:28:11  root
28  * Initial import.
29  *
30  * 
31  * 31    9/08/99 10:52a Mikek
32  * Reduce the number of asteroids that can be thrown at a target at
33  * Medium+.
34  * 
35  * 30    9/06/99 12:46a Andsager
36  * Add weapon_explosion_ani LOD
37  * 
38  * 29    9/05/99 3:13p Mikek
39  * Slightly decrease number of asteroids thrown at escorted ships.
40  * 
41  * 28    8/26/99 8:51p Dave
42  * Gave multiplayer TvT messaging a heavy dose of sanity. Cheat codes.
43  * 
44  * 27    7/30/99 7:01p Dave
45  * Dogfight escort gauge. Fixed up laser rendering in Glide.
46  * 
47  * 26    7/19/99 8:58p Andsager
48  * Don't try to throw at objnum -1
49  * 
50  * 25    7/15/99 9:20a Andsager
51  * FS2_DEMO initial checkin
52  * 
53  * 24    7/09/99 5:54p Dave
54  * Seperated cruiser types into individual types. Added tons of new
55  * briefing icons. Campaign screen.
56  * 
57  * 23    6/10/99 11:06a Andsager
58  * Mission designed selection of asteroid types.
59  * 
60  * 22    6/09/99 2:55p Andsager
61  * Allow multiple asteroid subtypes (of large, medium, small) and follow
62  * family.
63  * 
64  * 21    6/08/99 7:19p Dave
65  * Fixed asteroid lighting. Was because on non-darkening textures in Glide
66  * only. Dumb.
67  * 
68  * 20    6/07/99 1:18p Andsager
69  * Make asteroids choose consistent texture from large to small.  Modify
70  * fireball radius of dying asteroids.
71  * 
72  * 19    5/03/99 10:50p Andsager
73  * Make Asteroid_obj_list.  Change get_nearest_turret_objnum() to use
74  * Asteroid_obj_list, Ship_obj_list and Missile_obj_list vs.
75  * obj_used_list.
76  * 
77  * 18    4/23/99 12:01p Johnson
78  * Added SIF_HUGE_SHIP
79  * 
80  * 17    4/21/99 6:15p Dave
81  * Did some serious housecleaning in the beam code. Made it ready to go
82  * for anti-fighter "pulse" weapons. Fixed collision pair creation. Added
83  * a handy macro for recalculating collision pairs for a given object.
84  * 
85  * 16    4/16/99 2:34p Andsager
86  * Second pass on debris fields
87  * 
88  * 15    4/15/99 5:27p Andsager
89  * Fix explosion sound for Ships debris
90  * 
91  * 14    4/15/99 5:00p Andsager
92  * Frist pass on Debris field
93  * 
94  * 13    2/07/99 8:51p Andsager
95  * Add inner bound to asteroid field.  Inner bound tries to stay astroid
96  * free.  Wrap when within and don't throw at ships inside.
97  * 
98  * 12    1/20/99 6:04p Dave
99  * Another bit of stuff for beam weapons. Ships will properly use them
100  * now, although they're really deadly.
101  * 
102  * 11    1/06/99 2:24p Dave
103  * Stubs and release build fixes.
104  * 
105  * 10    12/03/98 3:14p Andsager
106  * Check in code that checks rotating submodel actually has ship subsystem
107  * 
108  * 9     11/19/98 11:07p Andsager
109  * Check in of physics and collision detection of rotating submodels
110  * 
111  * 8     11/13/98 10:12a Andsager
112  * simplify collision code
113  * 
114  * 7     11/05/98 5:55p Dave
115  * Big pass at reducing #includes
116  * 
117  * 6     10/23/98 3:51p Dave
118  * Full support for tstrings.tbl and foreign languages. All that remains
119  * is to make it active in Fred.
120  * 
121  * 5     10/23/98 1:11p Andsager
122  * Make ship sparks emit correctly from rotating structures.
123  * 
124  * 4     10/16/98 1:22p Andsager
125  * clean up header files
126  * 
127  * 3     10/13/98 9:28a Dave
128  * Started neatening up freespace.h. Many variables renamed and
129  * reorganized. Added AlphaColors.[h,cpp]
130  * 
131  * 2     10/07/98 10:52a Dave
132  * Initial checkin.
133  * 
134  * 1     10/07/98 10:48a Dave
135  * 
136  * 80    7/14/98 3:30p Dave
137  * 
138  * 79    5/18/98 12:05p Mike
139  * Make sm1-06a a little harder.
140  * 
141  * 78    5/06/98 12:36p Lawrance
142  * disable ambient asteroid sound for now
143  * 
144  * 77    4/30/98 12:49a Allender
145  * deal with asteroid problems in multiplayer
146  * 
147  * 76    4/27/98 1:46p Mike
148  * Make asteroid_density have no meaning.
149  * 
150  * 75    4/24/98 11:59a Dan
151  * fix bug where a null vector would occur when death_hit_pos was assinged
152  * to asteroid_pos
153  * 
154  * 74    4/23/98 4:43p Andsager
155  * Don't call   asteroid_update_collide() on creating asteroids since it
156  * creates sets of collisions pairs.  Pairs are created when objects are
157  * merged in obj_merge_created_list()
158  * 
159  * 73    4/21/98 1:23a Mike
160  * Tone down difficulty in asteroid toss missions.
161  * 
162  * 72    4/16/98 11:57a John
163  * Removed debug and unused registry values.
164  * 
165  * 71    4/08/98 1:27a Lawrance
166  * Fix typo.
167  * 
168  * 70    4/08/98 1:17a Lawrance
169  * Fix bug with red and white brackets being drawn on top of one another.
170  * 
171  * 69    4/02/98 6:28p Lawrance
172  * remove asteroid code from demo
173  * 
174  * 68    4/02/98 5:11p Mike
175  * Quick out of asteroid code if none present.
176  * 
177  * 67    4/02/98 1:34p Mike
178  * Minor difficulty balance, made a bit easier.
179  * 
180  * 66    4/02/98 1:29p Andsager
181  * 
182  * 65    4/01/98 5:34p John
183  * Made only the used POFs page in for a level.   Reduced some interp
184  * arrays.    Made custom detail level work differently.
185  * 
186  * 64    3/31/98 5:11p John
187  * Removed demo/save/restore.  Made NDEBUG defined compile.  Removed a
188  * bunch of debug stuff out of player file.  Made model code be able to
189  * unload models and malloc out only however many models are needed.
190  * 
191  * 63    3/30/98 4:02p John
192  * Made machines with < 32 MB of RAM use every other frame of certain
193  * bitmaps.   Put in code to keep track of how much RAM we've malloc'd.
194  * 
195  * 62    3/30/98 2:38p Mike
196  * Add asteroid_density to detail level support.
197  * No force explosion damage in training missions.
198  * Make cargo deathrolls shorter.
199  * 
200  * 61    3/30/98 10:07a Lawrance
201  * Um, make asteroids work again.
202  * 
203  * 60    3/29/98 12:55a Lawrance
204  * Get demo build working with limited set of data.
205  * 
206  * 59    3/26/98 9:19a Lawrance
207  * Support multiple asteroid pofs
208  * 
209  * 58    3/25/98 3:44p Andsager
210  * Fixed bug in asteroid_sub_create, where last_pos field was invalid in
211  * its creation frame but needed for collision in that frame.
212  * 
213  * 57    3/25/98 2:03p Sandeep
214  * Remove "f" from top of file.
215  * 
216  * 56    3/25/98 1:50p Mike
217  * Asteroid destruction (sm1-06a) balancing.
218  * 
219  * 55    3/25/98 10:43a Andsager
220  * Hack for ship_asteroid collisions when erroneous relative_vel >150
221  * 
222  * 54    3/23/98 12:20p Andsager
223  * Enable collision from rotation in ship_debris and ship_debris
224  * collisions.
225  * 
226  * 53    3/22/98 4:09p Andsager
227  * Make moment of inertia based on model.
228  * 
229  * 52    3/21/98 3:33p Lawrance
230  * When asteroid collides with an escort ship, make the sound carry
231  * farther
232  * 
233  * 51    3/19/98 12:09p John
234  * Fixed a bug using 6 characters.   r_heavy was using local coordinates
235  * instead of world so all asteroid-ship and debris-ship hitpos's were in
236  * the wrong spot.  Ok, I rearreanged some code to make it clearer also.
237  * 
238  * 50    3/17/98 5:55p Lawrance
239  * Support object linked sounds for asteroids.
240  * 
241  * 49    3/17/98 3:44p Mike
242  * Make asteroids-thrown-at-target not only happen when an asteroid wraps.
243  * 
244  * 48    3/17/98 9:53a Lawrance
245  * Asteroid area effect only affect ships
246  * 
247  * 47    3/17/98 9:25a Allender
248  * some minor asteroid changes for multiplayer
249  * 
250  * 46    3/17/98 12:16a Allender
251  * asteroids in multiplayer -- minor problems with position being correct
252  * 
253  * 45    3/14/98 1:44p Mike
254  * Todolist items 3365..3368.  Make child asteroids collide properly.
255  * Make asteroid throwing less bunchy, toss asteroids earlier, make
256  * facing-ness not break mission balance.
257  * 
258  * 44    3/13/98 9:06a John
259  * Made missile thrusters use a different min dist for scaling.   Made
260  * missilies not use lighting.
261  * 
262  * 43    3/12/98 4:01p Lawrance
263  * Only show warning brackets for cruiser/capital ships on the same team
264  * 
265  * $NoKeywords: $
266  */
267
268 #include "asteroid.h"
269 #include "object.h"
270 #include "objcollide.h"
271 #include "freespace.h"
272 #include "timer.h"
273 #include "3d.h"
274 #include "fireballs.h"
275 #include "gamesnd.h"
276 #include "bmpman.h"
277 #include "particle.h"
278 #include "linklist.h"
279 #include "hudescort.h"
280 #include "shiphit.h"
281 #include "multiutil.h"
282 #include "staticrand.h"
283 #include "multimsgs.h"
284 #include "systemvars.h"
285 #include "localize.h"
286 #include "multi.h"
287
288 #ifndef FS2_DEMO
289
290 #define                 ASTEROID_OBJ_USED       (1<<0)                          // flag used in asteroid_obj struct
291 #define                 MAX_ASTEROID_OBJS       MAX_ASTEROIDS           // max number of asteroids tracked in asteroid list
292 asteroid_obj    Asteroid_objs[MAX_ASTEROID_OBJS];       // array used to store asteroid object indexes
293 asteroid_obj    Asteroid_obj_list;                                              // head of linked list of asteroid_obj structs
294
295 // Asteroid editor requires first set of entries to be "None" and then "Asteroid XXX"
296 // Any changes to this will require changes to the asteroid editor
297 debris_struct Field_debris_info[] = {
298         { -1,                                                   "None", },
299         { ASTEROID_TYPE_SMALL,          "Asteroid Small", },
300         { ASTEROID_TYPE_MEDIUM, "Asteroid Medium", },
301         { ASTEROID_TYPE_BIG,            "Asteroid Large", },
302
303         { DEBRIS_TERRAN_SMALL,          "Terran Small", },
304         { DEBRIS_TERRAN_MEDIUM, "Terran Medium", },
305         { DEBRIS_TERRAN_LARGE,          "Terran Large", },
306
307         { DEBRIS_VASUDAN_SMALL, "Vasudan Small", },
308         { DEBRIS_VASUDAN_MEDIUM,        "Vasudan Medium", },
309         { DEBRIS_VASUDAN_LARGE, "Vasudan Large", },
310
311         { DEBRIS_SHIVAN_SMALL,          "Shivan Small", },
312         { DEBRIS_SHIVAN_MEDIUM, "Shivan Medium", },
313         { DEBRIS_SHIVAN_LARGE,          "Shivan Large" },
314 };
315
316 // used for randomly generating debris type when there are multiple sizes.
317 #define SMALL_DEBRIS_WEIGHT     8
318 #define MEDIUM_DEBRIS_WEIGHT    4
319 #define LARGE_DEBRIS_WEIGHT     1
320
321 int     Asteroids_enabled = 1;
322 int     Num_asteroid_types;
323 int     Num_asteroids = 0;
324 int     Asteroid_throw_objnum = -1;             //      Object index of ship to throw asteroids at.
325 int     Next_asteroid_throw;
326
327 asteroid_info   Asteroid_info[MAX_DEBRIS_TYPES];
328 asteroid                        Asteroids[MAX_ASTEROIDS];
329 asteroid_field  Asteroid_field;
330
331 static int              Asteroid_impact_explosion_ani;
332 static float    Asteroid_impact_explosion_radius;
333
334 #define ASTEROID_CHECK_WRAP_TIMESTAMP                   2000    // how often an asteroid gets checked for wrapping
335 #define ASTEROID_UPDATE_COLLIDE_TIMESTAMP       2000    // how often asteroid is checked for impending collisions with escort ships
336 #define ASTEROID_MIN_COLLIDE_TIME                               24              // time in seconds to check for asteroid colliding
337
338 //      Force updating of pair stuff for asteroid *objp.
339 void asteroid_update_collide(object *objp)
340 {
341         // Asteroid has wrapped, update collide objnum and flags
342         Asteroids[objp->instance].collide_objnum = -1;
343         Asteroids[objp->instance].collide_objsig = -1;
344         OBJ_RECALC_PAIRS(objp); 
345 }
346
347 // Clear out the Asteroid_obj_list
348 //
349 void asteroid_obj_list_init()
350 {
351         int i;
352
353         list_init(&Asteroid_obj_list);
354         for ( i = 0; i < MAX_ASTEROID_OBJS; i++ ) {
355                 Asteroid_objs[i].flags = 0;
356         }
357 }
358
359 // ---------------------------------------------------
360 // asteroid_obj_list_add()
361 //
362 // Function to add a node from the Asteroid_obj_list.  Only
363 // called from weapon_create()
364 int asteroid_obj_list_add(int objnum)
365 {
366         int index;
367
368         asteroid *cur_asteroid = &Asteroids[Objects[objnum].instance];
369         index = cur_asteroid - Asteroids;
370
371         Assert(index >= 0 && index < MAX_ASTEROID_OBJS);
372         Assert(!Asteroid_objs[index].flags & ASTEROID_OBJ_USED);
373
374         Asteroid_objs[index].flags = 0;
375         Asteroid_objs[index].objnum = objnum;
376         list_append(&Asteroid_obj_list, &Asteroid_objs[index]);
377         Asteroid_objs[index].flags |= ASTEROID_OBJ_USED;
378
379         return index;
380 }
381
382 // ---------------------------------------------------
383 // missle_obj_list_remove()
384 //
385 // Function to remove a node from the Asteroid_obj_list.  Only
386 // called from weapon_delete()
387 void asteroid_obj_list_remove(object * obj)
388 {
389         int index = obj->instance;
390
391         Assert(index >= 0 && index < MAX_ASTEROID_OBJS);
392         Assert(Asteroid_objs[index].flags & ASTEROID_OBJ_USED);
393
394         list_remove(&Asteroid_obj_list, &Asteroid_objs[index]); 
395         Asteroid_objs[index].flags = 0;
396 }
397
398
399 //      Prevent speed from getting too huge so it's hard to catch up to an asteroid.
400 float asteroid_cap_speed(int asteroid_info_index, float speed)
401 {
402         float max, double_max;
403
404         max = Asteroid_info[asteroid_info_index].max_speed;
405         double_max = max * 2;
406
407         while (speed > double_max){
408                 speed *= 0.5f;
409         }
410         
411         if (speed > max){
412                 speed *= 0.75f;
413         }
414
415         return speed;
416 }
417
418 // Returns whether position is inside inner bounding volume
419 // sum together the following: 1 inside x, 2 inside y, 4 inside z
420 // inside only when sum = 7
421 int asteroid_in_inner_bound_with_axes(asteroid_field *asfieldp, vector *pos, float delta)
422 {
423         Assert(asfieldp->has_inner_bound);
424
425         int rval = 0;
426         if ( (pos->xyz.x > asfieldp->inner_min_bound.xyz.x - delta) && (pos->xyz.x < asfieldp->inner_max_bound.xyz.x + delta) ) {
427                 rval += 1;
428         }
429
430         if ( (pos->xyz.y > asfieldp->inner_min_bound.xyz.y - delta) && (pos->xyz.y < asfieldp->inner_max_bound.xyz.y + delta) ) {
431                 rval += 2;
432         }
433
434         if ( (pos->xyz.z > asfieldp->inner_min_bound.xyz.z - delta) && (pos->xyz.z < asfieldp->inner_max_bound.xyz.z + delta) ) {
435                 rval += 4;
436         }
437
438         return rval;
439 }
440
441 // check if asteroid is within inner bound
442 // return 0 if not inside or no inner bound, 1 if inside inner bound
443 int asteroid_in_inner_bound(asteroid_field *asfieldp, vector *pos, float delta) {
444
445         if (!asfieldp->has_inner_bound) {
446                 return 0;
447         }
448
449         return (asteroid_in_inner_bound_with_axes(asfieldp, pos, delta) == 7);
450 }
451
452 // repositions asteroid outside the inner box on all 3 axes
453 // moves to the other side of the inner box a distance delta from edge of box
454 void inner_bound_pos_fixup(asteroid_field *asfieldp, vector *pos)
455 {
456         if (!asteroid_in_inner_bound(asfieldp, pos, 0)) {
457                 return;
458         }
459
460         float dist1, dist2;
461         int axis;
462
463         for (axis=0; axis<3; axis++) {
464                 dist1 = pos->a1d[axis] - asfieldp->inner_min_bound.a1d[axis];
465                 dist2 = asfieldp->inner_max_bound.a1d[axis] - pos->a1d[axis];
466                 Assert(dist1 >= 0 && dist2 >= 0);
467
468                 if (dist1 < dist2) {
469                         pos->a1d[axis] = asfieldp->inner_max_bound.a1d[axis] + dist1;
470                 } else {
471                         pos->a1d[axis] = asfieldp->inner_min_bound.a1d[axis] - dist2;
472                 }
473         }
474 }
475
476
477 // Create a single asteroid 
478 object *asteroid_create(asteroid_field *asfieldp, int asteroid_type, int asteroid_subtype)
479 {
480         int                             n, objnum;
481         matrix                  orient;
482         object                  *objp;
483         asteroid                        *asp;
484         asteroid_info   *asip;
485         vector                  pos, delta_bound;
486         angles                  angs;
487         float                           radius;
488         ushort                  signature;
489         int                             rand_base;
490
491         // bogus
492         if(asfieldp == NULL){
493                 return NULL;
494         }
495
496         for (n=0; n<MAX_ASTEROIDS; n++ ) {
497                 if ( !(Asteroids[n].flags & AF_USED) ){
498                         break;
499                 }
500         }
501
502         if (n >= MAX_ASTEROIDS) {
503                 nprintf(("Warning","Could not create asteroid, no more slots left\n"));
504                 return NULL;
505         }
506
507         if((asteroid_type < 0) || (asteroid_type >= Num_asteroid_types)){
508                 return NULL;
509         }
510
511         // HACK: multiplayer asteroid subtype always 0 to keep subtype in sync
512         if ( Game_mode & GM_MULTIPLAYER) {
513                 asteroid_subtype = 0;
514         }       
515
516         if( (asteroid_subtype < 0) || (asteroid_subtype >= MAX_ASTEROID_POFS)){
517                 return NULL;
518         }
519
520         asip = &Asteroid_info[asteroid_type];
521
522         // bogus
523         if(asip->modelp[asteroid_subtype] == NULL){
524                 return NULL;
525         }       
526
527         asp = &Asteroids[n];
528         asp->type = asteroid_type;
529         asp->asteroid_subtype = asteroid_subtype;
530         asp->flags = 0;
531         asp->flags |= AF_USED;
532         asp->check_for_wrap = timestamp_rand(0, ASTEROID_CHECK_WRAP_TIMESTAMP);
533         asp->check_for_collide = timestamp_rand(0, ASTEROID_UPDATE_COLLIDE_TIMESTAMP);
534         asp->final_death_time = timestamp(-1);
535         asp->collide_objnum = -1;
536         asp->collide_objsig = -1;
537         asp->target_objnum = -1;
538
539         radius = model_get_radius(asip->model_num[asteroid_subtype]);
540
541         vm_vec_sub(&delta_bound, &asfieldp->max_bound, &asfieldp->min_bound);
542
543         // for multiplayer, we want to do a static_rand so that everything behaves the same on all machines
544         signature = 0;
545         rand_base = 0;
546         if ( Game_mode & GM_NORMAL ) {
547                 pos.xyz.x = asfieldp->min_bound.xyz.x + delta_bound.xyz.x * frand();
548                 pos.xyz.y = asfieldp->min_bound.xyz.y + delta_bound.xyz.y * frand();
549                 pos.xyz.z = asfieldp->min_bound.xyz.z + delta_bound.xyz.z * frand();
550
551                 inner_bound_pos_fixup(asfieldp, &pos);
552                 // vm_set_identity(&orient);
553                 angs.p = frand() * 2*PI;
554                 angs.b = frand() * 2*PI;
555                 angs.h = frand() * 2*PI;
556         } else {
557                 signature = multi_assign_network_signature( MULTI_SIG_ASTEROID );
558                 rand_base = signature;
559
560                 pos.xyz.x = asfieldp->min_bound.xyz.x + delta_bound.xyz.x * static_randf( rand_base++ );
561                 pos.xyz.y = asfieldp->min_bound.xyz.y + delta_bound.xyz.y * static_randf( rand_base++ );
562                 pos.xyz.z = asfieldp->min_bound.xyz.z + delta_bound.xyz.z * static_randf( rand_base++ );
563
564                 inner_bound_pos_fixup(asfieldp, &pos);
565                 // vm_set_identity(&orient);
566                 angs.p = static_randf( rand_base++ ) * 2*PI;
567                 angs.b = static_randf( rand_base++ ) * 2*PI;
568                 angs.h = static_randf( rand_base++ ) * 2*PI;
569         }
570
571         vm_angles_2_matrix(&orient, &angs);
572
573         objnum = obj_create( OBJ_ASTEROID, -1, n, &orient, &pos, radius, OF_RENDERS | OF_PHYSICS | OF_COLLIDES);
574         // mprintf(("Framecount: %d asteroid create: obj = %d\n", Framecount, objnum));
575         
576         if ( (objnum == -1) || (objnum >= MAX_OBJECTS) ) {
577                 mprintf(("Couldn't create asteroid -- out of object slots\n"));
578                 return NULL;
579         }
580
581         asp->objnum = objnum;
582
583         // Add to Asteroid_used_list
584         asteroid_obj_list_add(objnum);
585
586         objp = &Objects[objnum];
587
588         if ( Game_mode & GM_MULTIPLAYER ){
589                 objp->net_signature = signature;
590         }
591
592         Num_asteroids++;
593
594         if (radius < 1.0) {
595                 radius = 1.0f;
596         }
597
598         vector rotvel;
599         if ( Game_mode & GM_NORMAL ) {
600                 vm_vec_rand_vec_quick(&rotvel);
601                 vm_vec_scale(&rotvel, frand()/4.0f + 0.1f);
602                 objp->phys_info.rotvel = rotvel;
603                 vm_vec_rand_vec_quick(&objp->phys_info.vel);
604         } else {
605                 static_randvec( rand_base++, &rotvel );
606                 vm_vec_scale(&rotvel, static_randf(rand_base++)/4.0f + 0.1f);
607                 objp->phys_info.rotvel = rotvel;
608                 static_randvec( rand_base++, &objp->phys_info.vel );
609         }
610
611
612         float speed;
613
614         if ( Game_mode & GM_NORMAL ) {
615                 speed = asteroid_cap_speed(asteroid_type, asfieldp->speed*frand_range(0.5f + (float) Game_skill_level/NUM_SKILL_LEVELS, 2.0f + (float) (2*Game_skill_level)/NUM_SKILL_LEVELS));
616         } else {
617                 speed = asteroid_cap_speed(asteroid_type, asfieldp->speed*static_randf_range(rand_base++, 0.5f + (float) Game_skill_level/NUM_SKILL_LEVELS, 2.0f + (float) (2*Game_skill_level)/NUM_SKILL_LEVELS));
618         }
619         
620         vm_vec_scale(&objp->phys_info.vel, speed);
621         objp->phys_info.desired_vel = objp->phys_info.vel;
622
623         // blow out his reverse thrusters. Or drag, same thing.
624         objp->phys_info.rotdamp = 10000.0f;
625         objp->phys_info.side_slip_time_const = 10000.0f;
626         objp->phys_info.flags |= (PF_REDUCED_DAMP | PF_DEAD_DAMP);      // set damping equal for all axis and not changable
627
628         // Fill in the max_vel field, so the collision pair stuff knows
629         // how fast this can move maximum in order to throw out collisions.
630         // This is in local coordinates, so Z is forward velocity.
631         objp->phys_info.max_vel.xyz.x = 0.0f;
632         objp->phys_info.max_vel.xyz.y = 0.0f;
633         objp->phys_info.max_vel.xyz.z = vm_vec_mag(&objp->phys_info.desired_vel);
634         
635         objp->phys_info.mass = asip->modelp[asteroid_subtype]->rad * 700.0f;
636         objp->phys_info.I_body_inv.v.rvec.xyz.x = 1.0f / (objp->phys_info.mass*asip->modelp[asteroid_subtype]->rad);
637         objp->phys_info.I_body_inv.v.uvec.xyz.y = objp->phys_info.I_body_inv.v.rvec.xyz.x;
638         objp->phys_info.I_body_inv.v.fvec.xyz.z = objp->phys_info.I_body_inv.v.rvec.xyz.x;
639         objp->hull_strength = asip->initial_hull_strength * (0.8f + (float)Game_skill_level/NUM_SKILL_LEVELS)/2.0f;
640
641         // ensure vel is valid
642         Assert( !vm_is_vec_nan(&objp->phys_info.vel) ); 
643
644         // assign a persistant sound to the asteroid
645 //      obj_snd_assign(objnum, SND_ASTEROID);
646
647         return objp;
648 }
649
650 //      Create asteroids when parent_objp blows up.
651 void asteroid_sub_create(object *parent_objp, int asteroid_type, vector *relvec)
652 {
653         object  *new_objp;
654         float speed;
655
656         Assert(parent_objp->type == OBJ_ASTEROID);
657         int subtype = Asteroids[parent_objp->instance].asteroid_subtype;
658         new_objp = asteroid_create(&Asteroid_field, asteroid_type, subtype);
659
660         if (new_objp == NULL)
661                 return;
662
663         if ( MULTIPLAYER_MASTER ){
664                 send_asteroid_create( new_objp, parent_objp, asteroid_type, relvec );
665         }
666
667         //      Now, bash some values.
668         vm_vec_scale_add(&new_objp->pos, &parent_objp->pos, relvec, 0.5f * parent_objp->radius);
669         float parent_speed = vm_vec_mag_quick(&parent_objp->phys_info.vel);
670
671         if ( parent_speed < 0.1f ) {
672                 parent_speed = vm_vec_mag_quick(&Asteroid_field.vel);
673         }
674
675         new_objp->phys_info.vel = parent_objp->phys_info.vel;
676         if ( Game_mode & GM_NORMAL )
677                 speed = asteroid_cap_speed(asteroid_type, (frand() + 2.0f) * parent_speed);
678         else
679                 speed = asteroid_cap_speed(asteroid_type, (static_randf(new_objp->net_signature)+2.0f) * parent_speed);
680
681         vm_vec_scale_add2(&new_objp->phys_info.vel, relvec, speed);
682         if (vm_vec_mag_quick(&new_objp->phys_info.vel) > 80.0f)
683                 vm_vec_scale(&new_objp->phys_info.vel, 0.5f);
684
685         new_objp->phys_info.desired_vel = new_objp->phys_info.vel;
686         vm_vec_scale_add(&new_objp->last_pos, &new_objp->pos, &new_objp->phys_info.vel, -flFrametime);
687         // DA: 4/22/98  We get next line for free when new object (in obj_create_list) is merged.
688         // this line gives too many collision pairs.
689         //      asteroid_update_collide(new_objp);
690 }
691
692 // Load in an asteroid model
693 void asteroid_load(int asteroid_info_index, int asteroid_subtype)
694 {
695         asteroid_info   *asip;
696 //      int                             pof_index;
697
698         asip = &Asteroid_info[asteroid_info_index];
699
700         // pick one of MAX_ASTEROID_POFS models
701         // LOAD ALL TEXTURES USED
702 //      static int asteroid_pof_index = rand() % MAX_ASTEROID_POFS;
703 //      if (Asteroid_field.debris_genre == DG_ASTEROID) {
704 //              pof_index = asteroid_pof_index;
705 //      } else {
706 //              // only 1 pof for ship debris type
707 //              pof_index = 0;
708 //      }
709
710         asip->model_num[asteroid_subtype] = model_load( asip->pof_files[asteroid_subtype], 0, NULL );
711
712         if (asip->model_num[asteroid_subtype] > -1) {
713                 asip->modelp[asteroid_subtype] = model_get(asip->model_num[asteroid_subtype]);
714                 
715                 // Stuff detail level distances.
716                 for (int i = 0; i < asip->num_detail_levels; i++) {
717                         asip->modelp[asteroid_subtype]->detail_depth[i] = i2fl(asip->detail_distance[i]);
718                 }
719         }
720 }
721
722 // randomly choose a debris model within the current group
723 int get_debris_from_same_group(int index) {
724         int group_base, group_offset;
725
726         group_base = (index / 3) * 3;
727         group_offset = index - group_base;
728
729         // group base + offset
730         // offset is formed by adding 1 or 2 (since 3 in model group) and mapping back in the 0-2 range
731         return group_base + ((group_offset + rand()%2 + 1) % 3);
732 }
733
734 // returns a weight that depends on asteroid size.
735 // the weight is then used to determine the frequencty of different sizes of ship debris
736 int get_debris_weight(int ship_debris_index)
737 {
738         switch (ship_debris_index) {
739         case DEBRIS_TERRAN_SMALL:
740         case DEBRIS_VASUDAN_SMALL:
741         case DEBRIS_SHIVAN_SMALL:
742                 return SMALL_DEBRIS_WEIGHT;
743                 break;
744
745         case DEBRIS_TERRAN_MEDIUM:
746         case DEBRIS_VASUDAN_MEDIUM:
747         case DEBRIS_SHIVAN_MEDIUM:
748                 return MEDIUM_DEBRIS_WEIGHT;
749                 break;
750
751         case DEBRIS_TERRAN_LARGE:
752         case DEBRIS_VASUDAN_LARGE:
753         case DEBRIS_SHIVAN_LARGE:
754                 return LARGE_DEBRIS_WEIGHT;
755                 break;
756
757         default:
758                 Int3();
759                 return 1;
760                 break;
761         }
762 }
763
764 // Create all the asteroids for the mission, called from 
765 void asteroid_create_all()
766 {
767         int i, idx;
768
769         // ship_debris_odds_table keeps track of debris type of the next debris piece
770         // each different type (size) of debris piece has a diffenent weight, smaller weighted more heavily than larger.
771         // choose next type from table ship_debris_odds_table by rand()%max_weighted_range,
772         //  the first column in ship_debris_odds_table random number *below* which the debris type in the second column is selected.
773         int ship_debris_odds_table[3][2];
774         int max_weighted_range = 0;
775
776         if (!Asteroids_enabled)
777                 return;
778
779         if (Asteroid_field.num_initial_asteroids <= 0 ) {
780                 return;
781         }
782
783         int max_asteroids = Asteroid_field.num_initial_asteroids; // * (1.0f - 0.1f*(MAX_DETAIL_LEVEL-Detail.asteroid_density)));
784
785         int num_debris_types = 0;
786
787         // get number of ship debris types
788         if (Asteroid_field.debris_genre == DG_SHIP) {
789                 for (idx=0; idx<3; idx++) {
790                         if (Asteroid_field.field_debris_type[idx] != -1) {
791                                 num_debris_types++;
792                         }
793                 }
794
795                 // Calculate the odds table
796                 for (idx=0; idx<num_debris_types; idx++) {
797                         int debris_weight = get_debris_weight(Asteroid_field.field_debris_type[idx]);
798                         ship_debris_odds_table[idx][0] = max_weighted_range + debris_weight;
799                         ship_debris_odds_table[idx][1] = Asteroid_field.field_debris_type[idx];
800                         max_weighted_range += debris_weight;
801                 }
802         }
803
804         // Load Asteroid/ship models
805         if (Asteroid_field.debris_genre == DG_SHIP) {
806                 for (idx=0; idx<num_debris_types; idx++) {
807                         asteroid_load(Asteroid_field.field_debris_type[idx], 0);
808                 }
809         } else {
810                 if (Asteroid_field.field_debris_type[0] != -1) {
811                         asteroid_load(ASTEROID_TYPE_SMALL, 0);
812                         asteroid_load(ASTEROID_TYPE_MEDIUM, 0);
813                         asteroid_load(ASTEROID_TYPE_BIG, 0);
814                 }
815
816                 if (Asteroid_field.field_debris_type[1] != -1) {
817                         asteroid_load(ASTEROID_TYPE_SMALL, 1);
818                         asteroid_load(ASTEROID_TYPE_MEDIUM, 1);
819                         asteroid_load(ASTEROID_TYPE_BIG, 1);
820                 }
821
822                 if (Asteroid_field.field_debris_type[2] != -1) {
823                         asteroid_load(ASTEROID_TYPE_SMALL, 2);
824                         asteroid_load(ASTEROID_TYPE_MEDIUM, 2);
825                         asteroid_load(ASTEROID_TYPE_BIG, 2);
826                 }
827         }
828
829         // load all the asteroid/debris pieces
830         for (i=0; i<max_asteroids; i++) {
831                 if (Asteroid_field.debris_genre == DG_ASTEROID) {
832                         // For asteroid, load only large asteroids
833
834                         // get a valid subtype
835                         int subtype = rand() % 3;
836                         while (Asteroid_field.field_debris_type[subtype] == -1) {
837                                 subtype = (subtype + 1) % 3;
838                         }
839
840                         asteroid_create(&Asteroid_field, ASTEROID_TYPE_BIG, subtype);
841                 } else {
842                         Assert(num_debris_types > 0);
843
844                         int rand_choice = rand() % max_weighted_range;
845
846                         for (idx=0; idx<3; idx++) {
847                                 // for ship debris, choose type according to odds table
848                                 if (rand_choice < ship_debris_odds_table[idx][0]) {
849                                         asteroid_create(&Asteroid_field, ship_debris_odds_table[idx][1], 0);
850                                         break;
851                                 }
852                         }
853                 }
854         }
855 }
856
857 // Init asteriod system for the level, called from game_level_init()
858 void asteroid_level_init()
859 {
860         Asteroid_field.num_initial_asteroids=0;
861         Num_asteroids = 0;
862         Next_asteroid_throw = timestamp(1);
863         asteroid_obj_list_init();
864 }
865
866 // return !0 if asteroid should be wrapped, 0 otherwise.  Multiplayer clients will always return
867 // 0 from this function.  We will force a wrap on the clients when server tells us
868 int asteroid_should_wrap(object *objp, asteroid_field *asfieldp)
869 {
870         if ( MULTIPLAYER_CLIENT )
871                 return 0;
872
873         if (objp->pos.xyz.x < asfieldp->min_bound.xyz.x) {
874                 return 1;
875         }
876
877         if (objp->pos.xyz.y < asfieldp->min_bound.xyz.y) {
878                 return 1;
879         }
880
881         if (objp->pos.xyz.z < asfieldp->min_bound.xyz.z) {
882                 return 1;
883         }
884
885         if (objp->pos.xyz.x > asfieldp->max_bound.xyz.x) {
886                 return 1;
887         }
888
889         if (objp->pos.xyz.y > asfieldp->max_bound.xyz.y) {
890                 return 1;
891         }
892
893         if (objp->pos.xyz.z > asfieldp->max_bound.xyz.z) {
894                 return 1;
895         }
896
897         // check against inner bound
898         if (asfieldp->has_inner_bound) {
899                 if ( (objp->pos.xyz.x > asfieldp->inner_min_bound.xyz.x) && (objp->pos.xyz.x < asfieldp->inner_max_bound.xyz.x)
900                   && (objp->pos.xyz.y > asfieldp->inner_min_bound.xyz.y) && (objp->pos.xyz.y < asfieldp->inner_max_bound.xyz.y)
901                   && (objp->pos.xyz.z > asfieldp->inner_min_bound.xyz.z) && (objp->pos.xyz.z < asfieldp->inner_max_bound.xyz.z) ) {
902
903                         return 1;
904                 }
905         }
906
907         return 0;
908 }
909
910 // Wrap an asteroid from one end of the asteroid field to the other
911 void asteroid_wrap_pos(object *objp, asteroid_field *asfieldp)
912 {
913         if (objp->pos.xyz.x < asfieldp->min_bound.xyz.x) {
914                 objp->pos.xyz.x = asfieldp->max_bound.xyz.x + (objp->pos.xyz.x - asfieldp->min_bound.xyz.x);
915         }
916
917         if (objp->pos.xyz.y < asfieldp->min_bound.xyz.y) {
918                 objp->pos.xyz.y = asfieldp->max_bound.xyz.y + (objp->pos.xyz.y - asfieldp->min_bound.xyz.y);
919         }
920         
921         if (objp->pos.xyz.z < asfieldp->min_bound.xyz.z) {
922                 objp->pos.xyz.z = asfieldp->max_bound.xyz.z + (objp->pos.xyz.z - asfieldp->min_bound.xyz.z);
923         }
924
925         if (objp->pos.xyz.x > asfieldp->max_bound.xyz.x) {
926                 objp->pos.xyz.x = asfieldp->min_bound.xyz.x + (objp->pos.xyz.x - asfieldp->max_bound.xyz.x);
927         }
928
929         if (objp->pos.xyz.y > asfieldp->max_bound.xyz.y) {
930                 objp->pos.xyz.y = asfieldp->min_bound.xyz.y + (objp->pos.xyz.y - asfieldp->max_bound.xyz.y);
931         }
932
933         if (objp->pos.xyz.z > asfieldp->max_bound.xyz.z) {
934                 objp->pos.xyz.z = asfieldp->min_bound.xyz.z + (objp->pos.xyz.z - asfieldp->max_bound.xyz.z);
935         }
936
937         // wrap on inner bound, check all 3 axes as needed, use of rand ok for multiplayer with send_asteroid_throw()
938         inner_bound_pos_fixup(asfieldp, &objp->pos);
939
940 }
941
942
943 // return !0 if this asteroid is a target for any ship, otherwise return 0
944 int asteroid_is_targeted(object *objp)
945 {
946         ship_obj        *so;
947         object  *ship_objp;
948         int             asteroid_obj_index;
949
950         asteroid_obj_index=OBJ_INDEX(objp);
951
952         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
953                 ship_objp = &Objects[so->objnum];
954                 if ( Ai_info[Ships[ship_objp->instance].ai_index].target_objnum == asteroid_obj_index ) {
955                         return 1;
956                 }
957         }
958         
959         return 0;
960 }
961
962 //      Create an asteroid that will hit object *objp in delta_time seconds
963 void asteroid_aim_at_target(object *objp, object *asteroid_objp, float delta_time)
964 {
965         vector  predicted_center_pos;
966         vector  rand_vec;
967         float           speed;
968
969         vm_vec_scale_add(&predicted_center_pos, &objp->pos, &objp->phys_info.vel, delta_time);
970         vm_vec_rand_vec_quick(&rand_vec);
971         vm_vec_scale_add2(&predicted_center_pos, &rand_vec, objp->radius/2.0f);
972
973         vm_vec_add2(&rand_vec, &objp->orient.v.fvec);
974         if (vm_vec_mag_quick(&rand_vec) < 0.1f)
975                 vm_vec_add2(&rand_vec, &objp->orient.v.rvec);
976         vm_vec_normalize(&rand_vec);
977
978         speed = Asteroid_info[0].max_speed * (frand()/2.0f + 0.5f);
979         
980         vm_vec_copy_scale(&asteroid_objp->phys_info.vel, &rand_vec, -speed);
981         asteroid_objp->phys_info.desired_vel = asteroid_objp->phys_info.vel;
982         vm_vec_scale_add(&asteroid_objp->pos, &predicted_center_pos, &asteroid_objp->phys_info.vel, -delta_time);
983         vm_vec_scale_add(&asteroid_objp->last_pos, &asteroid_objp->pos, &asteroid_objp->phys_info.vel, -flFrametime);
984 }
985
986 int     Max_incoming_asteroids[NUM_SKILL_LEVELS] = {3, 4, 5, 7, 10};
987
988 //      Call once per frame to maybe throw an asteroid at a ship.
989 //      "count" asteroids already targeted on 
990 void maybe_throw_asteroid(int count)
991 {
992         if (!timestamp_elapsed(Next_asteroid_throw)) {
993                 return;
994         }
995
996         if (Asteroid_throw_objnum == -1) {
997                 return;
998         }
999
1000         nprintf(("AI", "Incoming asteroids: %i\n", count));
1001
1002         if (count > Max_incoming_asteroids[Game_skill_level])
1003                 return;
1004
1005         Next_asteroid_throw = timestamp(1000 + 1200 * count/(Game_skill_level+1));
1006
1007         ship_obj        *so;
1008         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
1009                 object *A = &Objects[so->objnum];
1010                 if (so->objnum == Asteroid_throw_objnum) {
1011                         int subtype = rand() % 3;
1012                         while (Asteroid_field.field_debris_type[subtype] == -1) {
1013                                 subtype = (subtype + 1) % 3;
1014                         }
1015                         object *objp = asteroid_create(&Asteroid_field, ASTEROID_TYPE_BIG, subtype);
1016                         if (objp != NULL) {
1017                                 asteroid_aim_at_target(A, objp, ASTEROID_MIN_COLLIDE_TIME + frand() * 20.0f);
1018
1019                                 // if asteroid is inside inner bound, kill it
1020                                 if (asteroid_in_inner_bound(&Asteroid_field, &objp->pos, 0.0f)) {
1021                                         objp->flags |= OF_SHOULD_BE_DEAD;
1022                                 } else {
1023                                         Asteroids[objp->instance].target_objnum = so->objnum;
1024                                         // DA: 4/22/98  We get next line for free when new object (in obj_create_list) is merged.
1025                                         // this line gives too many collision pairs.
1026                                         // asteroid_update_collide(objp);
1027
1028                                         if ( MULTIPLAYER_MASTER ) {
1029                                                 send_asteroid_throw( objp );
1030                                         }
1031                                 }
1032                         }
1033
1034                         return;
1035                 }
1036         }
1037
1038 }
1039
1040 void asteroid_delete( object * obj )
1041 {
1042         int             num;
1043         asteroid        *asp;
1044
1045         num = obj->instance;
1046         Assert( Asteroids[num].objnum == OBJ_INDEX(obj));
1047
1048         asp = &Asteroids[num];
1049
1050         Assert( Num_asteroids >= 0 );
1051
1052         asp->flags = 0;
1053         Num_asteroids--;
1054
1055         // Delete asteroid from Asteroid_used_list
1056         asteroid_obj_list_remove( obj );
1057 }
1058
1059 // See if we should reposition the asteroid.  Only reposition if oustide the bounding volume and
1060 // the player isn't looking towards the asteroid.
1061 void asteroid_maybe_reposition(object *objp, asteroid_field *asfieldp)
1062 {
1063         // passive field does not wrap
1064         if (asfieldp->field_type == FT_PASSIVE) {
1065                 return;
1066         }
1067
1068         if ( asteroid_should_wrap(objp, asfieldp) ) {
1069                 vector  vec_to_asteroid, old_asteroid_pos, old_vel;
1070                 float           dot, dist;
1071
1072                 old_asteroid_pos = objp->pos;
1073                 old_vel = objp->phys_info.vel;
1074
1075                 //nprintf(("AI", "Frame %i, reposition #%i\n", Framecount, objp-Objects));
1076
1077                 // don't wrap asteroid if it is a target of some ship
1078                 if ( !asteroid_is_targeted(objp) ) {
1079
1080                         // only wrap if player won't see asteroid disappear/reverse direction
1081                         dist = vm_vec_normalized_dir(&vec_to_asteroid, &objp->pos, &Eye_position);
1082                         dot = vm_vec_dot(&Eye_matrix.v.fvec, &vec_to_asteroid);
1083                         
1084                         if ((dot < 0.7f) || (dist > 3000.0f)) {
1085                                 if (Num_asteroids > MAX_ASTEROIDS-10) {
1086                                         objp->flags |= OF_SHOULD_BE_DEAD;
1087                                 } else {
1088                                         // check to ensure player won't see asteroid appear either
1089                                         asteroid_wrap_pos(objp, asfieldp);
1090                                         Asteroids[objp->instance].target_objnum = -1;
1091
1092                                         vm_vec_normalized_dir(&vec_to_asteroid, &objp->pos, &Eye_position);
1093                                         dot = vm_vec_dot(&Eye_matrix.v.fvec, &vec_to_asteroid);
1094                                         dist = vm_vec_dist_quick(&objp->pos, &Eye_position);
1095                                         
1096                                         if (( dot > 0.7f) && (dist < 3000.0f)) {
1097                                                 // player would see asteroid pop out other side, so reverse velocity instead of wrapping
1098                                                 objp->pos = old_asteroid_pos;           
1099                                                 vm_vec_copy_scale(&objp->phys_info.vel, &old_vel, -1.0f);
1100                                                 objp->phys_info.desired_vel = objp->phys_info.vel;
1101                                                 Asteroids[objp->instance].target_objnum = -1;
1102                                         }
1103
1104                                         // update last pos (after vel is known)
1105                                         vm_vec_scale_add(&objp->last_pos, &objp->pos, &objp->phys_info.vel, -flFrametime);
1106
1107                                         asteroid_update_collide(objp);
1108
1109                                         if ( MULTIPLAYER_MASTER )
1110                                                 send_asteroid_throw( objp );
1111                                 }
1112                         }
1113                 }
1114         }
1115 }
1116
1117 void lerp(float *goal, float f1, float f2, float scale)
1118 {
1119         *goal = (f2 - f1) * scale + f1;
1120 }
1121
1122 void asteroid_process_pre( object *objp, float frame_time)
1123 {
1124         if (Asteroids_enabled) {
1125                 vector  *v, *vv;
1126
1127                 v = &objp->phys_info.vel;
1128                 vv = &objp->phys_info.desired_vel;
1129
1130                 //nprintf(("AI", "Frm %i: Obj #%2i: Hull: %5.1f Vel: %5.1f %5.1f %5.1f Des: %5.1f %5.1f %5.1f\n", Framecount, objp-Objects, objp->hull_strength, v->x, v->y, v->z, vv->x, vv->y, vv->z));
1131
1132                 //      Make vel chase desired_vel
1133                 lerp(&objp->phys_info.vel.xyz.x, objp->phys_info.vel.xyz.x, objp->phys_info.desired_vel.xyz.x, flFrametime);
1134                 lerp(&objp->phys_info.vel.xyz.y, objp->phys_info.vel.xyz.y, objp->phys_info.desired_vel.xyz.y, flFrametime);
1135                 lerp(&objp->phys_info.vel.xyz.z, objp->phys_info.vel.xyz.z, objp->phys_info.desired_vel.xyz.z, flFrametime);
1136         }
1137 }
1138
1139 #ifndef PLAT_UNIX
1140 #pragma warning ( push )
1141 #pragma warning ( disable : 4701 )
1142 #endif
1143 int asteroid_check_collision(object *pasteroid, object *other_obj, vector *hitpos, collision_info_struct *asteroid_hit_info)
1144 {
1145         if (!Asteroids_enabled) {
1146                 return 0;
1147         }
1148
1149         mc_info mc;
1150         int             num, asteroid_subtype;
1151
1152         Assert( pasteroid->type == OBJ_ASTEROID );
1153
1154         num = pasteroid->instance;
1155         Assert( num >= 0 );
1156
1157         Assert( Asteroids[num].objnum == OBJ_INDEX(pasteroid));
1158         asteroid_subtype = Asteroids[num].asteroid_subtype;
1159
1160         // asteroid_hit_info NULL  --  asteroid-weapon collision
1161         if ( asteroid_hit_info == NULL ) {
1162                 // asteroid weapon collision
1163                 Assert( other_obj->type == OBJ_WEAPON );
1164                 mc.model_num = Asteroid_info[Asteroids[num].type].model_num[asteroid_subtype];  // Fill in the model to check
1165                 model_clear_instance( mc.model_num );
1166                 mc.orient = &pasteroid->orient;                                 // The object's orient
1167                 mc.pos = &pasteroid->pos;                                                       // The object's position
1168                 mc.p0 = &other_obj->last_pos;                           // Point 1 of ray to check
1169                 mc.p1 = &other_obj->pos;                                        // Point 2 of ray to check
1170                 mc.flags = (MC_CHECK_MODEL);
1171
1172                 if (model_collide(&mc))
1173                         *hitpos = mc.hit_point_world;
1174
1175                 return mc.num_hits;
1176         }
1177
1178         // asteroid ship collision -- use asteroid_hit_info to calculate physics
1179         object *ship_obj = other_obj;
1180         Assert( ship_obj->type == OBJ_SHIP );
1181
1182         object* heavy = asteroid_hit_info->heavy;
1183         object* light = asteroid_hit_info->light;
1184         object *heavy_obj = heavy;
1185         object *light_obj = light;
1186
1187         vector zero, p0, p1;
1188         vm_vec_zero( &zero );
1189         vm_vec_sub( &p0, &light->last_pos, &heavy->last_pos );
1190         vm_vec_sub( &p1, &light->pos, &heavy->pos );
1191
1192         mc.pos = &zero;                                                         // The object's position
1193         mc.p0 = &p0;                                                                    // Point 1 of ray to check
1194         mc.p1 = &p1;                                                                    // Point 2 of ray to check
1195
1196         // find the light object's position in the heavy object's reference frame at last frame and also in this frame.
1197         vector p0_temp, p0_rotated;
1198                 
1199         // Collision detection from rotation enabled if at rotaion is less than 30 degree in frame
1200         // This should account for all ships
1201         if ( (vm_vec_mag_squared( &heavy->phys_info.rotvel ) * flFrametime*flFrametime) < (PI*PI/36) ) {
1202                 // collide_rotate calculate (1) start position and (2) relative velocity
1203                 asteroid_hit_info->collide_rotate = 1;
1204                 vm_vec_rotate( &p0_temp, &p0, &heavy->last_orient );
1205                 vm_vec_unrotate( &p0_rotated, &p0_temp, &heavy->orient );
1206                 mc.p0 = &p0_rotated;                            // Point 1 of ray to check
1207                 vm_vec_sub( &asteroid_hit_info->light_rel_vel, &p1, &p0_rotated );
1208                 vm_vec_scale( &asteroid_hit_info->light_rel_vel, 1/flFrametime );
1209                 // HACK - this applies to big ships warping in/out of asteroid fields - not sure what it does
1210                 if (vm_vec_mag(&asteroid_hit_info->light_rel_vel) > 300) {
1211                         // nprintf(("Physics", "Asteroid type %d\n", Asteroids[asteroid_hit_info->light->instance].type));
1212                         asteroid_hit_info->collide_rotate = 0;
1213                         vm_vec_sub( &asteroid_hit_info->light_rel_vel, &light->phys_info.vel, &heavy->phys_info.vel );
1214                 }
1215         } else {
1216                 asteroid_hit_info->collide_rotate = 0;
1217                 vm_vec_sub( &asteroid_hit_info->light_rel_vel, &light->phys_info.vel, &heavy->phys_info.vel );
1218         }
1219
1220         int mc_ret_val = 0;
1221
1222         if ( asteroid_hit_info->heavy == ship_obj ) {   // ship is heavier, so asteroid is sphere. Check sphere collision against ship poly model
1223                 mc.model_num = Ships[ship_obj->instance].modelnum;              // Fill in the model to check
1224                 mc.orient = &ship_obj->orient;                                                          // The object's orient
1225                 mc.radius = pasteroid->radius;
1226                 mc.flags = (MC_CHECK_MODEL | MC_CHECK_SPHERELINE);
1227
1228                 // copy important data
1229                 int copy_flags = mc.flags;  // make a copy of start end positions of sphere in  big ship RF
1230                 vector copy_p0, copy_p1;
1231                 copy_p0 = *mc.p0;
1232                 copy_p1 = *mc.p1;
1233
1234                 // first test against the sphere - if this fails then don't do any submodel tests
1235                 mc.flags = MC_ONLY_SPHERE | MC_CHECK_SPHERELINE;
1236
1237                 int submodel_list[MAX_ROTATING_SUBMODELS];
1238                 int num_rotating_submodels = 0;
1239                 polymodel *pm;
1240
1241                 ship_model_start(ship_obj);
1242
1243                 if (model_collide(&mc)) {
1244
1245                         // Set earliest hit time
1246                         asteroid_hit_info->hit_time = FLT_MAX;
1247
1248                         // Do collision the cool new way
1249                         if ( asteroid_hit_info->collide_rotate ) {
1250                                 // We collide with the sphere, find the list of rotating submodels and test one at a time
1251                                 model_get_rotating_submodel_list(submodel_list, &num_rotating_submodels, heavy_obj);
1252
1253                                 // Get polymodel and turn off all rotating submodels, collide against only 1 at a time.
1254                                 pm = model_get(Ships[heavy_obj->instance].modelnum);
1255
1256                                 // turn off all rotating submodels and test for collision
1257                                 for (int i=0; i<num_rotating_submodels; i++) {
1258                                         pm->submodel[submodel_list[i]].blown_off = 1;
1259                                 }
1260
1261                                 // reset flags to check MC_CHECK_MODEL | MC_CHECK_SPHERELINE and maybe MC_CHECK_INVISIBLE_FACES and MC_SUBMODEL_INSTANCE
1262                                 mc.flags = copy_flags | MC_SUBMODEL_INSTANCE;
1263
1264
1265                                 // check each submodel in turn
1266                                 for (int i=0; i<num_rotating_submodels; i++) {
1267                                         // turn on submodel for collision test
1268                                         pm->submodel[submodel_list[i]].blown_off = 0;
1269
1270                                         // set angles for last frame (need to set to prev to get p0)
1271                                         angles copy_angles = pm->submodel[submodel_list[i]].angs;
1272
1273                                         // find the start and end positions of the sphere in submodel RF
1274                                         pm->submodel[submodel_list[i]].angs = pm->submodel[submodel_list[i]].sii->prev_angs;
1275                                         world_find_model_point(&p0, &light_obj->last_pos, pm, submodel_list[i], &heavy_obj->last_orient, &heavy_obj->last_pos);
1276
1277                                         pm->submodel[submodel_list[i]].angs = copy_angles;
1278                                         world_find_model_point(&p1, &light_obj->pos, pm, submodel_list[i], &heavy_obj->orient, &heavy_obj->pos);
1279
1280                                         mc.p0 = &p0;
1281                                         mc.p1 = &p1;
1282                                         // mc.pos = zero        // in submodel RF
1283
1284                                         mc.orient = &vmd_identity_matrix;
1285                                         mc.submodel_num = submodel_list[i];
1286
1287                                         if ( model_collide(&mc) ) {
1288                                                 if ( mc.hit_dist < asteroid_hit_info->hit_time ) {
1289                                                         mc_ret_val = 1;
1290
1291                                                         // set up asteroid_hit_info common
1292                                                         set_hit_struct_info(asteroid_hit_info, &mc, SUBMODEL_ROT_HIT);
1293
1294                                                         // set up asteroid_hit_info for rotating submodel
1295                                                         if (asteroid_hit_info->edge_hit == 0) {
1296                                                                 model_find_obj_dir(&asteroid_hit_info->collision_normal, &mc.hit_normal, heavy_obj, mc.hit_submodel);
1297                                                         }
1298
1299                                                         // find position in submodel RF of light object at collison
1300                                                         vector int_light_pos, diff;
1301                                                         vm_vec_sub(&diff, mc.p1, mc.p0);
1302                                                         vm_vec_scale_add(&int_light_pos, mc.p0, &diff, mc.hit_dist);
1303                                                         model_find_world_point(&asteroid_hit_info->light_collision_cm_pos, &int_light_pos, mc.model_num, mc.hit_submodel, &heavy_obj->orient, &zero);
1304                                                 }
1305                                         }
1306                                         // Don't look at this submodel again
1307                                         pm->submodel[submodel_list[i]].blown_off = 1;
1308                                 }
1309
1310                         }
1311
1312                         // Recover and do usual ship_ship collision, but without rotating submodels
1313                         mc.flags = copy_flags;
1314                         *mc.p0 = copy_p0;
1315                         *mc.p1 = copy_p1;
1316                         mc.orient = &heavy_obj->orient;
1317
1318                         // usual ship_ship collision test
1319                         if ( model_collide(&mc) )       {
1320                                 // check if this is the earliest hit
1321                                 if (mc.hit_dist < asteroid_hit_info->hit_time) {
1322                                         mc_ret_val = 1;
1323
1324                                         set_hit_struct_info(asteroid_hit_info, &mc, SUBMODEL_NO_ROT_HIT);
1325
1326                                         // get collision normal if not edge hit
1327                                         if (asteroid_hit_info->edge_hit == 0) {
1328                                                 model_find_obj_dir(&asteroid_hit_info->collision_normal, &mc.hit_normal, heavy_obj, mc.hit_submodel);
1329                                         }
1330
1331                                         // find position in submodel RF of light object at collison
1332                                         vector diff;
1333                                         vm_vec_sub(&diff, mc.p1, mc.p0);
1334                                         vm_vec_scale_add(&asteroid_hit_info->light_collision_cm_pos, mc.p0, &diff, mc.hit_dist);
1335
1336                                 }
1337                         }
1338
1339                         ship_model_stop( ship_obj );
1340                 }
1341
1342         } else {
1343                 // Asteroid is heavier obj
1344                 mc.model_num = Asteroid_info[Asteroids[num].type].model_num[asteroid_subtype];          // Fill in the model to check
1345                 model_clear_instance( mc.model_num );
1346                 mc.orient = &pasteroid->orient;                         // The object's orient
1347                 mc.radius = model_get_core_radius( Ships[ship_obj->instance].modelnum );
1348
1349                 // check for collision between asteroid model and ship sphere
1350                 mc.flags = (MC_CHECK_MODEL | MC_CHECK_SPHERELINE);
1351
1352                 mc_ret_val = model_collide(&mc);
1353
1354                 if (mc_ret_val) {
1355                         set_hit_struct_info(asteroid_hit_info, &mc, SUBMODEL_NO_ROT_HIT);
1356
1357                         // set normal if not edge hit
1358                         if ( !asteroid_hit_info->edge_hit ) {
1359                                 vm_vec_unrotate(&asteroid_hit_info->collision_normal, &mc.hit_normal, &heavy->orient);
1360                         }
1361
1362                         // find position in submodel RF of light object at collison
1363                         vector diff;
1364                         vm_vec_sub(&diff, mc.p1, mc.p0);
1365                         vm_vec_scale_add(&asteroid_hit_info->light_collision_cm_pos, mc.p0, &diff, mc.hit_dist);
1366
1367                 }
1368         }
1369         
1370
1371         if ( mc_ret_val )       {
1372
1373                 // SET PHYSICS PARAMETERS
1374                 // already have (hitpos - heavy) and light_cm_pos
1375                 // get heavy cm pos - already have light_cm_pos
1376                 asteroid_hit_info->heavy_collision_cm_pos = zero;
1377
1378                 // get r_heavy and r_light
1379                 asteroid_hit_info->r_heavy = asteroid_hit_info->hit_pos;
1380                 vm_vec_sub(&asteroid_hit_info->r_light, &asteroid_hit_info->hit_pos, &asteroid_hit_info->light_collision_cm_pos);
1381
1382                 // set normal for edge hit
1383                 if ( asteroid_hit_info->edge_hit ) {
1384                         vm_vec_copy_normalize(&asteroid_hit_info->collision_normal, &asteroid_hit_info->r_light);
1385                         vm_vec_negate(&asteroid_hit_info->collision_normal);
1386                 }
1387
1388                 // get world hitpos
1389                 vm_vec_add(hitpos, &asteroid_hit_info->heavy->pos, &asteroid_hit_info->r_heavy);
1390
1391                 return 1;
1392         } else {
1393                 // no hit
1394                 return 0;
1395         }
1396 }
1397 #ifndef PLAT_UNIX
1398 #pragma warning ( pop )
1399 #endif
1400
1401
1402 void asteroid_render(object * obj)
1403 {
1404         if (Asteroids_enabled) {
1405                 int                     num;
1406                 polymodel       *pm;
1407                 asteroid                *asp;
1408
1409                 pm = NULL;      
1410                 num = obj->instance;
1411
1412                 Assert((num >= 0) && (num < MAX_ASTEROIDS));
1413                 asp = &Asteroids[num];
1414
1415                 Assert( asp->flags & AF_USED );
1416
1417                 model_clear_instance( Asteroid_info[asp->type].model_num[asp->asteroid_subtype]);
1418                 model_render(Asteroid_info[asp->type].model_num[asp->asteroid_subtype], &obj->orient, &obj->pos, MR_NORMAL|MR_IS_ASTEROID, OBJ_INDEX(obj) );    //      Replace MR_NORMAL with 0x07 for big yellow blobs
1419         }
1420 }
1421
1422 //      Create a normalized vector generally in the direction from *hitpos to other_obj->pos
1423 void asc_get_relvec(vector *relvec, object *other_obj, vector *hitpos)
1424 {
1425         vector  tvec, rand_vec;
1426         int             count = 0;
1427
1428         vm_vec_normalized_dir(&tvec, &other_obj->pos, hitpos);
1429
1430         //      Try up to three times to get a good vector.
1431         while (count++ < 3) {
1432                 vm_vec_rand_vec_quick(&rand_vec);
1433                 vm_vec_add(relvec, &tvec, &rand_vec);
1434                 float mag = vm_vec_mag_quick(relvec);
1435                 if ((mag > 0.2f) && (mag < 1.7f))
1436                         break;
1437         }
1438
1439         vm_vec_normalize_quick(relvec);
1440 }
1441
1442 // return multiplier on asteroid radius for fireball
1443 float asteroid_get_fireball_scale_multiplier(int num)
1444 {
1445         if (Asteroids[num].flags & AF_USED) {
1446
1447                 switch(Asteroids[num].type) {
1448                 case ASTEROID_TYPE_BIG:
1449                         return 1.5f;
1450                         break;
1451
1452                 default:
1453                         return 1.0f;
1454                         break;
1455                 }
1456         }
1457
1458         Int3(); // this should not happen.  asteroid should be used.
1459         return 1.0f;
1460 }
1461
1462
1463 // create asteroid explosion
1464 // exit: expected time for explosion anim to last, in seconds
1465 float asteroid_create_explosion(object *objp)
1466 {
1467         int     fireball_objnum;
1468         float   explosion_life, fireball_scale_multiplier;
1469
1470         fireball_scale_multiplier = asteroid_get_fireball_scale_multiplier(objp->instance);
1471
1472         fireball_objnum = fireball_create( &objp->pos, FIREBALL_ASTEROID, OBJ_INDEX(objp), objp->radius*fireball_scale_multiplier, 0, &objp->phys_info.vel );
1473         if ( fireball_objnum > -1 )     {
1474                 explosion_life = fireball_lifeleft(&Objects[fireball_objnum]);
1475         } else {
1476                 explosion_life = 0.0f;
1477         }
1478
1479         return explosion_life;
1480 }
1481
1482 // play sound when asteroid explodes
1483 void asteriod_explode_sound(object *objp, int type, int play_loud)
1484 {
1485         int     sound_index = -1;
1486         float range_factor = 1.0f;              // how many times sound should traver farther than normal
1487
1488         switch (type) {
1489         case ASTEROID_TYPE_SMALL:
1490         case ASTEROID_TYPE_MEDIUM:
1491         case DEBRIS_TERRAN_SMALL:
1492         case DEBRIS_TERRAN_MEDIUM:
1493         case DEBRIS_VASUDAN_SMALL:
1494         case DEBRIS_VASUDAN_MEDIUM:
1495         case DEBRIS_SHIVAN_SMALL:
1496         case DEBRIS_SHIVAN_MEDIUM:
1497                 sound_index = SND_ASTEROID_EXPLODE_SMALL;
1498                 range_factor = 5.0f;
1499                 break;
1500
1501         case ASTEROID_TYPE_BIG:
1502         case DEBRIS_TERRAN_LARGE:
1503         case DEBRIS_VASUDAN_LARGE:
1504         case DEBRIS_SHIVAN_LARGE:
1505                 sound_index = SND_ASTEROID_EXPLODE_BIG;
1506                 range_factor = 10.0f;
1507                 break;
1508
1509         default:
1510                 Int3();
1511                 return;
1512         }
1513
1514         Assert(sound_index != -1);
1515
1516         if ( !play_loud ) {
1517                 range_factor = 1.0f;
1518         }
1519
1520         snd_play_3d( &Snds[sound_index], &objp->pos, &Eye_position, objp->radius, NULL, 0, 1.0f, SND_PRIORITY_MUST_PLAY, NULL, range_factor );
1521 }
1522
1523 //      asteroid_do_area_effect()
1524 //
1525 // Do the area effect for an asteroid exploding
1526 //
1527 // input:       asteroid_objp   =>              object pointer to asteriod causing explosion
1528 void asteroid_do_area_effect(object *asteroid_objp)
1529 {
1530         object                  *ship_objp;
1531         float                           damage, blast;
1532         ship_obj                        *so;
1533         asteroid                        *asp;
1534         asteroid_info   *asip;
1535
1536         asp = &Asteroids[asteroid_objp->instance];
1537         asip = &Asteroid_info[asp->type];
1538
1539         if ( asip->damage <= 0 ) {              // do a quick out if there is no damage to apply
1540                 return;
1541         }
1542
1543         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
1544                 ship_objp = &Objects[so->objnum];
1545         
1546                 // don't blast navbuoys
1547                 if ( ship_get_SIF(ship_objp->instance) & SIF_NAVBUOY ) {
1548                         continue;
1549                 }
1550
1551                 if ( weapon_area_calc_damage(ship_objp, &asteroid_objp->pos, asip->inner_rad, asip->outer_rad, asip->blast, asip->damage, &blast, &damage, asip->outer_rad) == -1 )
1552                         continue;
1553
1554                 ship_apply_global_damage(ship_objp, asteroid_objp, &asteroid_objp->pos, damage );
1555                 weapon_area_apply_blast(NULL, ship_objp, &asteroid_objp->pos, blast, 0);
1556         }       // end for
1557 }
1558
1559 //      Asteroid asteroid_obj was hit.
1560 //      Apply damage.  Maybe make it break into smaller asteroids.
1561 // input:       asteroid_obj    =>              pointer to asteroid object getting hit
1562 //                              other_obj               =>              object that hit asteroid, can be NULL if asteroid hit by area effect
1563 //                              hitpos                  =>              world position asteroid was hit, can be NULL if hit by area effect
1564 //                              damage                  =>              amount of damage to apply to asteroid
1565 void asteroid_hit( object * asteroid_obj, object * other_obj, vector * hitpos, float damage )
1566 {
1567         float           explosion_life;
1568         asteroid        *asp;
1569
1570         asp = &Asteroids[asteroid_obj->instance];
1571
1572         if (asteroid_obj->flags & OF_SHOULD_BE_DEAD){
1573                 return;
1574         }
1575
1576         if ( MULTIPLAYER_MASTER ){
1577                 send_asteroid_hit( asteroid_obj, other_obj, hitpos, damage );
1578         }
1579
1580         asteroid_obj->hull_strength -= damage;
1581
1582         //nprintf(("AI", "Asteroid collided with %s, hull = %.2f\n", Object_type_names[other_obj->type], asteroid_obj->hull_strength));
1583
1584         if (asteroid_obj->hull_strength < 0.0f) {
1585                 if ( asp->final_death_time <= 0 ) {
1586                         int play_loud_collision = 0;
1587
1588                         explosion_life = asteroid_create_explosion(asteroid_obj);
1589                         if ( asp->collide_objnum == OBJ_INDEX(other_obj) ) {
1590 //                              play_loud_collision = 1;
1591                         }
1592                         asteriod_explode_sound(asteroid_obj, asp->type, play_loud_collision);
1593                         asteroid_do_area_effect(asteroid_obj);
1594
1595                         asp->final_death_time = timestamp( fl2i(explosion_life*1000.0f)/5 );    // Wait till 30% of vclip time before breaking the asteroid up.
1596                         if ( hitpos ) {
1597                                 asp->death_hit_pos = *hitpos;
1598                         } else {
1599                                 asp->death_hit_pos = asteroid_obj->pos;
1600                                 // randomize hit pos a bit, otherwise we will get a NULL vector when trying to find direction to toss child asteroids
1601                                 vector rand_vec;
1602                                 vm_vec_rand_vec_quick(&rand_vec);
1603                                 vm_vec_add2(&asp->death_hit_pos, &rand_vec);
1604                         }
1605                 }
1606         } else if ( other_obj ) {
1607                 if ( other_obj->type == OBJ_WEAPON ) {
1608                         weapon_info *wip;
1609                         wip = &Weapon_info[Weapons[other_obj->instance].weapon_info_index];
1610                         // If the weapon didn't play any impact animation, play custom asteroid impact animation
1611                         if ( wip->impact_weapon_expl_index < 0 ) {
1612                                 particle_create( hitpos, &vmd_zero_vector, 0.0f, Asteroid_impact_explosion_radius, PARTICLE_BITMAP, Asteroid_impact_explosion_ani );
1613                         }
1614                 }
1615         }
1616
1617         // evaluate any relevant player scoring implications
1618         scoring_eval_hit(asteroid_obj,other_obj);
1619 }
1620
1621 // De-init asteroids, called from game_level_close()
1622 void asteroid_level_close()
1623 {
1624         int     i;
1625
1626         for (i=0; i<MAX_ASTEROIDS; i++) {
1627                 if (Asteroids[i].flags & AF_USED) {
1628                         Asteroids[i].flags &= ~AF_USED;
1629                         Assert(Asteroids[i].objnum >=0 && Asteroids[i].objnum < MAX_OBJECTS);
1630                         Objects[Asteroids[i].objnum].flags |= OF_SHOULD_BE_DEAD;
1631                 }
1632         }
1633
1634         Asteroid_field.num_initial_asteroids=0;
1635 }
1636
1637 DCF(asteroids,"Turns asteroids on/off")
1638 {       
1639         if ( Dc_command )       {       
1640                 dc_get_arg(ARG_TRUE|ARG_FALSE|ARG_NONE);                
1641                 if ( Dc_arg_type & ARG_TRUE )   
1642                         Asteroids_enabled = 1;  
1643                 else if ( Dc_arg_type & ARG_FALSE ) 
1644                         Asteroids_enabled = 0;  
1645                 else if ( Dc_arg_type & ARG_NONE ) 
1646                         Asteroids_enabled ^= 1; 
1647         }       
1648         if ( Dc_help )  
1649                 dc_printf( "Usage: asteroids [bool]\nTurns asteroid system on/off.  If nothing passed, then toggles it.\n" );   
1650         
1651         if ( Dc_status )        
1652                 dc_printf( "asteroids are %s\n", (Asteroids_enabled?"ON":"OFF") );      
1653
1654 /*
1655         if ((old_asteroids_enabled == 0) && (Asteroids_enabled == 1)) {
1656                 asteroid_init();
1657         } else if ((old_asteroids_enabled == 1) && (Asteroids_enabled == 0)) {
1658                 asteroid_uninit();
1659         }
1660 */
1661 }
1662
1663 void hud_target_asteroid()
1664 {
1665         int     i;
1666         int     start_index = 0, end_index = MAX_ASTEROIDS;
1667
1668         if (Player_ai->target_objnum != -1) {
1669                 if (Objects[Player_ai->target_objnum].type == OBJ_ASTEROID) {
1670                         start_index = Objects[Player_ai->target_objnum].instance+1;
1671                         end_index = start_index-1;
1672                         if (end_index < 0)
1673                                 end_index = MAX_ASTEROIDS;
1674                 }
1675         }
1676
1677         i = start_index;
1678         while (i != end_index) {
1679                 if (i == MAX_ASTEROIDS)
1680                         i = 0;
1681
1682                 if (Asteroids[i].flags & AF_USED) {
1683                         Assert(Objects[Asteroids[i].objnum].type == OBJ_ASTEROID);
1684                         set_target_objnum( Player_ai, Asteroids[i].objnum);
1685                         break;
1686                 }
1687
1688                 i++;
1689         }
1690 }
1691
1692 // Return the number of active asteroids
1693 int asteroid_count()
1694 {
1695         return Num_asteroids;
1696 }
1697
1698 // See if asteroid should split up.  We delay splitting up to allow the explosion animation
1699 // to play for a bit.
1700 void asteroid_maybe_break_up(object *asteroid_obj)
1701 {
1702         asteroid *asp;
1703
1704         asp = &Asteroids[asteroid_obj->instance];
1705
1706         if ( timestamp_elapsed(asp->final_death_time) ) {
1707                 vector  relvec, vfh, tvec;
1708
1709                 asteroid_obj->flags |= OF_SHOULD_BE_DEAD;
1710
1711                 // multiplayer clients won't go through the following code.  asteroid_sub_create will send
1712                 // a create packet to the client in the above named function
1713                 if ( !MULTIPLAYER_CLIENT ) {
1714
1715                         switch (asp->type) {
1716                         case ASTEROID_TYPE_SMALL:
1717                                 break;
1718                         case ASTEROID_TYPE_MEDIUM:
1719                                 asc_get_relvec(&relvec, asteroid_obj, &asp->death_hit_pos);
1720                                 asteroid_sub_create(asteroid_obj, ASTEROID_TYPE_SMALL, &relvec);
1721                         
1722                                 vm_vec_normalized_dir(&vfh, &asteroid_obj->pos, &asp->death_hit_pos);
1723                                 vm_vec_copy_scale(&tvec, &vfh, 2.0f);
1724                                 vm_vec_sub2(&tvec, &relvec);
1725                                 asteroid_sub_create(asteroid_obj, ASTEROID_TYPE_SMALL, &tvec);
1726                                 
1727                                 break;
1728                         case ASTEROID_TYPE_BIG:
1729                                 asc_get_relvec(&relvec, asteroid_obj, &asp->death_hit_pos);
1730                                 asteroid_sub_create(asteroid_obj, ASTEROID_TYPE_MEDIUM, &relvec);
1731                         
1732                                 vm_vec_normalized_dir(&vfh, &asteroid_obj->pos, &asp->death_hit_pos);
1733                                 vm_vec_copy_scale(&tvec, &vfh, 2.0f);
1734                                 vm_vec_sub2(&tvec, &relvec);
1735                                 asteroid_sub_create(asteroid_obj, ASTEROID_TYPE_MEDIUM, &tvec);
1736
1737                                 while (frand() > 0.6f) {
1738                                         vector  rvec, tvec2;
1739                                         vm_vec_rand_vec_quick(&rvec);
1740                                         vm_vec_scale_add(&tvec2, &vfh, &rvec, 0.75f);
1741                                         asteroid_sub_create(asteroid_obj, ASTEROID_TYPE_SMALL, &tvec2);
1742                                 }
1743
1744                                 break;
1745
1746                         // ship debris does not break up
1747                         case    DEBRIS_TERRAN_SMALL:
1748                         case    DEBRIS_TERRAN_MEDIUM:
1749                         case    DEBRIS_TERRAN_LARGE:
1750                         case    DEBRIS_VASUDAN_SMALL:
1751                         case    DEBRIS_VASUDAN_MEDIUM:
1752                         case    DEBRIS_VASUDAN_LARGE:
1753                         case    DEBRIS_SHIVAN_SMALL:
1754                         case    DEBRIS_SHIVAN_MEDIUM:
1755                         case    DEBRIS_SHIVAN_LARGE:
1756                                 break;
1757
1758                         default:
1759                                 Int3();
1760                         }
1761                 }
1762
1763                 asp->final_death_time = timestamp(-1);
1764         }
1765 }
1766
1767 int asteroid_get_random_in_cone(vector *pos, vector *dir, float ang, int danger)
1768 {
1769         int idx;
1770         vector asteroid_dir;
1771
1772         // just pick the first asteroid which satisfies our condition
1773         for(idx=0; idx<Num_asteroids; idx++){
1774                 vm_vec_sub(&asteroid_dir, &Objects[Asteroids[idx].objnum].pos, pos);
1775                 vm_vec_normalize_quick(&asteroid_dir);
1776
1777                 // if it satisfies the condition
1778                 if(vm_vec_dot(dir, &asteroid_dir) >= ang){
1779                         return idx;
1780                 }
1781         }
1782
1783         return -1;
1784 }
1785
1786 void asteroid_test_collide(object *asteroid_obj, object *ship_obj, mc_info *mc)
1787 {
1788         float           asteroid_ray_dist;
1789         vector  asteroid_fvec, terminus;
1790
1791         // See if ray from asteroid intersects bounding box of escort ship
1792         asteroid_ray_dist = vm_vec_mag_quick(&asteroid_obj->phys_info.desired_vel) * ASTEROID_MIN_COLLIDE_TIME;
1793         asteroid_fvec = asteroid_obj->phys_info.desired_vel;    
1794
1795         if(IS_VEC_NULL(&asteroid_fvec)){
1796                 terminus = asteroid_obj->pos;
1797         } else {
1798                 vm_vec_normalize(&asteroid_fvec);
1799                 vm_vec_scale_add(&terminus, &asteroid_obj->pos, &asteroid_fvec, asteroid_ray_dist);
1800         }
1801
1802         Assert(ship_obj->type == OBJ_SHIP);
1803
1804         ship_model_start(ship_obj);
1805
1806         mc->model_num = Ships[ship_obj->instance].modelnum;                     // Fill in the model to check
1807         mc->orient = &ship_obj->orient;                                                                         // The object's orientation
1808         mc->pos = &ship_obj->pos;                                                                                               // The object's position
1809         mc->p0 = &asteroid_obj->pos;                                                                                    // Point 1 of ray to check
1810         mc->p1 = &terminus;                                                                                                             // Point 2 of ray to check
1811 //      mc->flags = MC_CHECK_MODEL | MC_ONLY_BOUND_BOX; 
1812         mc->flags = MC_CHECK_MODEL | MC_CHECK_SPHERELINE;       
1813         mc->radius = asteroid_obj->radius;
1814
1815         model_collide(mc);
1816
1817         ship_model_stop(ship_obj);
1818 }
1819
1820 // Return !0 is the asteroid will collide with the escort ship within ASTEROID_MIN_COLLIDE_TIME
1821 // seconds
1822 int asteroid_will_collide(object *asteroid_obj, object *escort_objp)
1823 {
1824         mc_info mc;
1825
1826         asteroid_test_collide(asteroid_obj, escort_objp, &mc);
1827
1828         if ( !mc.num_hits ) {
1829                 return 0;
1830         }       
1831
1832         return 1;
1833 }
1834
1835 // return !0 if we should warn about asteroid hitting ship, otherwise return 0
1836 int asteroid_valid_ship_to_warn_collide(ship *shipp)
1837 {
1838         if ( !(Ship_info[shipp->ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) ) {
1839                 return 0;
1840         }
1841
1842         if ( shipp->flags & (SF_DYING|SF_DEPART_WARP) ) {
1843                 return 0;
1844         }
1845
1846         if ( (shipp->team != Player_ship->team) || (Player_ship->team == TEAM_TRAITOR) ) {
1847                 return 0;
1848         }
1849
1850         return 1;
1851 }
1852
1853 // See if asteroid will collide with a large ship on the escort list in the next
1854 // ASTEROID_MIN_COLLIDE_TIME seconds.
1855 void asteroid_update_collide_flag(object *asteroid_objp)
1856 {
1857         int             i, num_escorts, escort_objnum, will_collide=0;
1858         ship            *escort_shipp;
1859         asteroid        *asp;
1860
1861         asp = &Asteroids[asteroid_objp->instance];
1862         asp->collide_objnum = -1;
1863         asp->collide_objsig = -1;
1864
1865         // multiplayer dogfight
1866         if((Game_mode & GM_MULTIPLAYER) && (Netgame.type_flags & NG_TYPE_DOGFIGHT)){
1867                 return;
1868         }
1869
1870         num_escorts = hud_escort_num_ships_on_list();
1871
1872         if ( num_escorts <= 0 ) {
1873                 return;
1874         }
1875
1876         for ( i = 0; i < num_escorts; i++ ) {
1877                 escort_objnum = hud_escort_return_objnum(i);
1878                 if ( escort_objnum >= 0 ) {
1879                         escort_shipp = &Ships[Objects[escort_objnum].instance];
1880                         if ( asteroid_valid_ship_to_warn_collide(escort_shipp) ) {
1881                                 will_collide = asteroid_will_collide(asteroid_objp, &Objects[escort_objnum]);
1882                                 if ( will_collide ) {
1883                                         asp->collide_objnum = escort_objnum;
1884                                         asp->collide_objsig = Objects[escort_objnum].signature;
1885                                 }
1886                         }
1887                 }
1888         }
1889 }
1890
1891 // ensure that the collide objnum for the asteroid is still valid
1892 void asteroid_verify_collide_objnum(asteroid *asp)
1893 {
1894         if ( asp->collide_objnum >= 0 ) {
1895                 if ( Objects[asp->collide_objnum].signature != asp->collide_objsig ) {
1896                         asp->collide_objnum = -1;
1897                         asp->collide_objsig = -1;
1898                 }
1899         }
1900 }
1901
1902 void asteroid_process_post(object * obj, float frame_time)
1903 {
1904         if (Asteroids_enabled) {
1905                 int num;
1906                 num = obj->instance;
1907                 
1908                 //Assert( Asteroids[num].objnum == objnum );
1909                 asteroid        *asp = &Asteroids[num];
1910
1911                 // Only wrap if active field
1912                 if (Asteroid_field.field_type == FT_ACTIVE) {
1913                         if ( timestamp_elapsed(asp->check_for_wrap) ) {
1914                                 asteroid_maybe_reposition(obj, &Asteroid_field);
1915                                 asp->check_for_wrap = timestamp(ASTEROID_CHECK_WRAP_TIMESTAMP);
1916                         }
1917                 }
1918
1919                 asteroid_verify_collide_objnum(asp);
1920
1921                 if ( timestamp_elapsed(asp->check_for_collide) ) {
1922                         asteroid_update_collide_flag(obj);
1923                         asp->check_for_collide = timestamp(ASTEROID_UPDATE_COLLIDE_TIMESTAMP);
1924                 }
1925
1926                 asteroid_maybe_break_up(obj);
1927         }
1928 }
1929
1930 // return the object number that the asteroid is about to impact
1931 int asteroid_collide_objnum(object *asteroid_objp)
1932 {
1933         return Asteroids[asteroid_objp->instance].collide_objnum;
1934 }
1935
1936 // return the time until the asteroid will impact its collide_objnum
1937 float asteroid_time_to_impact(object *asteroid_objp)
1938 {
1939         float           time=-1.0f, total_dist, speed;
1940         asteroid        *asp;
1941         mc_info mc;
1942
1943         asp = &Asteroids[asteroid_objp->instance];
1944
1945         if ( asp->collide_objnum < 0 ) {
1946                 return time;
1947         }
1948         
1949         asteroid_test_collide(asteroid_objp, &Objects[asp->collide_objnum], &mc);
1950
1951         if ( mc.num_hits ) {
1952                 total_dist = vm_vec_dist(&mc.hit_point_world, &asteroid_objp->pos) - asteroid_objp->radius;
1953                 if ( total_dist < 0 ) {
1954                         total_dist = 0.0f;
1955                 }
1956                 speed = vm_vec_mag(&asteroid_objp->phys_info.vel);
1957                 time = total_dist/speed;
1958         }       
1959
1960         return time;
1961 }
1962
1963 // read in a single asteroid section from asteroid.tbl
1964 void asteroid_parse_section()
1965 {
1966         asteroid_info   *asip;
1967         
1968         asip = &Asteroid_info[Num_asteroid_types];
1969
1970         required_string("$Name:");
1971         stuff_string(asip->name, F_NAME, NULL);
1972
1973         required_string( "$POF file1:" );
1974         stuff_string_white( asip->pof_files[0] );
1975
1976         required_string( "$POF file2:" );
1977         stuff_string_white( asip->pof_files[1] );
1978
1979         if ( (strstr(asip->name,"Asteroid") != NULL) || (strstr(asip->name, "asteroid") != NULL) ) {
1980                 required_string( "$POF file3:" );
1981                 stuff_string_white( asip->pof_files[2] );
1982         }
1983
1984         asip->num_detail_levels = 0;
1985
1986         required_string("$Detail distance:");
1987         asip->num_detail_levels = stuff_int_list(asip->detail_distance, MAX_SHIP_DETAIL_LEVELS, RAW_INTEGER_TYPE);
1988
1989         required_string("$Max Speed:");
1990         stuff_float(&asip->max_speed);
1991
1992         required_string("$Expl inner rad:");
1993         stuff_float(&asip->inner_rad);
1994
1995         required_string("$Expl outer rad:");
1996         stuff_float(&asip->outer_rad);
1997
1998         required_string("$Expl damage:");
1999         stuff_float(&asip->damage);
2000
2001         required_string("$Expl blast:");
2002         stuff_float(&asip->blast);
2003
2004         required_string("$Hitpoints:");
2005         stuff_float(&asip->initial_hull_strength);
2006 }
2007
2008 // read in data from asteroid.tbl into Asteroid_info[] array
2009 void asteroid_parse_tbl()
2010 {
2011         char impact_ani_file[FILESPEC_LENGTH];
2012
2013         Num_asteroid_types = 0;
2014
2015         // open localization
2016         lcl_ext_open();
2017
2018         read_file_text("asteroid.tbl");
2019         reset_parse();
2020
2021         required_string("#Asteroid Types");
2022
2023         while (required_string_either("#End","$Name:")) {
2024                 Assert( Num_asteroid_types < MAX_DEBRIS_TYPES );
2025                 asteroid_parse_section();
2026                 Num_asteroid_types++;
2027         }
2028
2029         required_string("#End");
2030
2031         // check all read in
2032         Assert(Num_asteroid_types == MAX_DEBRIS_TYPES);
2033
2034         Asteroid_impact_explosion_ani = -1;
2035         required_string("$Impact Explosion:");
2036         stuff_string(impact_ani_file, F_NAME, NULL);
2037         if ( stricmp(impact_ani_file,NOX("none")))      {
2038                 int num_frames;
2039                 Asteroid_impact_explosion_ani = bm_load_animation( impact_ani_file, &num_frames, NULL, 1);
2040         }
2041
2042         required_string("$Impact Explosion Radius:");
2043         stuff_float(&Asteroid_impact_explosion_radius);
2044
2045         // close localization
2046         lcl_ext_close();
2047 }
2048
2049 //      Return number of asteroids expected to collide with a ship.
2050 int count_incident_asteroids()
2051 {
2052         object  *asteroid_objp;
2053         int             count;
2054
2055         count = 0;
2056
2057         for ( asteroid_objp = GET_FIRST(&obj_used_list); asteroid_objp !=END_OF_LIST(&obj_used_list); asteroid_objp = GET_NEXT(asteroid_objp) ) {
2058                 if (asteroid_objp->type == OBJ_ASTEROID ) {
2059                         asteroid *asp = &Asteroids[asteroid_objp->instance];
2060
2061                         if ( asp->target_objnum >= 0 ) {
2062                                 count++;
2063                         }
2064                 }
2065         }
2066
2067         return count;
2068 }
2069
2070 //      Pick object to throw asteroids at.
2071 //      Pick any capital or big ship inside the bounds of the asteroid field.
2072 int set_asteroid_throw_objnum()
2073 {
2074         if (Asteroid_field.num_initial_asteroids < 1)
2075                 return -1;
2076
2077         ship_obj        *so;
2078         object  *ship_objp;
2079
2080         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2081                 ship_objp = &Objects[so->objnum];
2082                 float           radius = ship_objp->radius*2.0f;
2083
2084                 if (Ship_info[Ships[ship_objp->instance].ship_info_index].flags & (SIF_HUGE_SHIP | SIF_BIG_SHIP)) {
2085                         if (ship_objp->pos.xyz.x + radius > Asteroid_field.min_bound.xyz.x)
2086                                 if (ship_objp->pos.xyz.y + radius > Asteroid_field.min_bound.xyz.y)
2087                                 if (ship_objp->pos.xyz.z + radius > Asteroid_field.min_bound.xyz.z)
2088                                 if (ship_objp->pos.xyz.x - radius < Asteroid_field.max_bound.xyz.x)
2089                                 if (ship_objp->pos.xyz.y - radius < Asteroid_field.max_bound.xyz.y)
2090                                 if (ship_objp->pos.xyz.z - radius < Asteroid_field.max_bound.xyz.z)
2091                                 if (!asteroid_in_inner_bound(&Asteroid_field, &ship_objp->pos, radius))
2092                                         return so->objnum;
2093                 }
2094         }
2095         return -1;
2096
2097 }
2098
2099 void asteroid_frame()
2100 {
2101         if (Num_asteroids < 1)
2102                 return;
2103
2104         // Only throw if active field
2105         if (Asteroid_field.field_type == FT_PASSIVE) {
2106                 return;
2107         }
2108
2109         Asteroid_throw_objnum = set_asteroid_throw_objnum();
2110
2111         maybe_throw_asteroid(count_incident_asteroids());
2112 }
2113
2114 // Called once, at game start.  Do any one-time initializations here
2115 void asteroid_init()
2116 {
2117         asteroid_parse_tbl();
2118 }
2119
2120 // Draw brackets around on-screen asteroids that are about to collide, otherwise draw an offscreen indicator
2121 void asteroid_show_brackets()
2122 {
2123         vertex  asteroid_vertex;
2124         object  *asteroid_objp, *player_target;
2125         asteroid        *asp;
2126
2127         // get pointer to player target, so we don't need to take OBJ_INDEX() of asteroid_objp to compare to target_objnum
2128         if ( Player_ai->target_objnum >= 0 ) {
2129                 player_target = &Objects[Player_ai->target_objnum];
2130         } else {
2131                 player_target = NULL;
2132         }
2133
2134         for ( asteroid_objp = GET_FIRST(&obj_used_list); asteroid_objp !=END_OF_LIST(&obj_used_list); asteroid_objp = GET_NEXT(asteroid_objp) ) {
2135                 if (asteroid_objp->type != OBJ_ASTEROID ) {
2136                         continue;
2137                 }
2138
2139                 asp = &Asteroids[asteroid_objp->instance];
2140
2141                 if ( asp->collide_objnum < 0 ) {
2142                         continue;
2143                 }
2144
2145                 if ( asteroid_objp == player_target ) {
2146                         continue;
2147                 }
2148
2149                 g3_rotate_vertex(&asteroid_vertex,&asteroid_objp->pos);
2150                 g3_project_vertex(&asteroid_vertex);
2151
2152                 if (!(asteroid_vertex.flags & PF_OVERFLOW)) {
2153                         gr_set_color_fast(&IFF_colors[IFF_COLOR_SELECTION][1]);
2154                         hud_show_brackets(asteroid_objp, &asteroid_vertex);
2155                 }
2156
2157                 // if asteroid is not on screen, draw an offscreen indicator
2158                 if ( hud_gauge_active(HUD_OFFSCREEN_INDICATOR) ) {
2159                         if (asteroid_vertex.codes != 0) {
2160                                 float dist;
2161 //                              dist = vm_vec_dist_quick(&Player_obj->pos, &asteroid_objp->pos);
2162                                 dist = hud_find_target_distance( asteroid_objp, Player_obj );
2163                                 gr_set_color_fast(&IFF_colors[IFF_COLOR_SELECTION][1]);
2164                                 hud_draw_offscreen_indicator(&asteroid_vertex, &asteroid_objp->pos, dist);
2165                         }
2166                 }
2167         }
2168 }
2169
2170 // target the closest danger asteroid to the player
2171 void asteroid_target_closest_danger()
2172 {
2173         object  *asteroid_objp, *closest_asteroid_objp = NULL;
2174         asteroid        *asp;
2175         float           dist, closest_dist = 999999.0f;
2176
2177         for ( asteroid_objp = GET_FIRST(&obj_used_list); asteroid_objp !=END_OF_LIST(&obj_used_list); asteroid_objp = GET_NEXT(asteroid_objp) ) {
2178                 if (asteroid_objp->type != OBJ_ASTEROID ) {
2179                         continue;
2180                 }
2181
2182                 asp = &Asteroids[asteroid_objp->instance];
2183
2184                 if ( asp->collide_objnum < 0 ) {
2185                         continue;
2186                 }
2187
2188                 dist = vm_vec_dist_quick(&Player_obj->pos, &asteroid_objp->pos);
2189
2190                 if ( dist < closest_dist ) {
2191                         closest_dist = dist;
2192                         closest_asteroid_objp = asteroid_objp;
2193                 }
2194         }
2195
2196         if ( closest_asteroid_objp ) {
2197                 set_target_objnum( Player_ai, OBJ_INDEX(closest_asteroid_objp) );
2198         }
2199 }
2200
2201 void asteroid_page_in()
2202 {
2203         if (Asteroid_field.num_initial_asteroids > 0 ) {
2204                 int i, j, k;
2205
2206                 nprintf(( "Paging", "Paging in asteroids\n" ));
2207
2208
2209                 // max of 3 possible debris field models
2210                 for (i=0; i<3; i++) {
2211                         asteroid_info   *asip;
2212
2213                         if (Asteroid_field.debris_genre == DG_ASTEROID) {
2214                                 // asteroid
2215                                 asip = &Asteroid_info[i];
2216                         } else {
2217                                 // ship debris - always full until empty
2218                                 if (Asteroid_field.field_debris_type[i] != -1) {
2219                                         asip = &Asteroid_info[Asteroid_field.field_debris_type[i]];
2220                                 } else {
2221                                         break;
2222                                 }
2223                         }
2224
2225
2226                         for (k=0; k<3; k++) {
2227
2228                                 // SHIP DEBRIS - use subtype 0
2229                                 if (Asteroid_field.debris_genre == DG_SHIP) {
2230                                         if (k > 0) {
2231                                                 break;
2232                                         }
2233                                 } else {
2234                                         // ASTEROID DEBRIS - use subtype (Asteroid_field.field_debris_type[] != -1)
2235                                         if (Asteroid_field.field_debris_type[k] == -1) {
2236                                                 continue;
2237                                         }
2238                                 }
2239                                 
2240                                 asip->modelp[k] = model_get(asip->model_num[k]);
2241
2242                                 // Page in textures
2243                                 for (j=0; j<asip->modelp[k]->n_textures; j++ )  {
2244                                         int bitmap_num = asip->modelp[k]->original_textures[j];
2245
2246
2247                                         // if we're in Glide (and maybe later with D3D), use nondarkening textures
2248                                         if ( bitmap_num > -1 )  {
2249                                                 if(gr_screen.mode == GR_GLIDE){
2250                                                         bm_page_in_nondarkening_texture( bitmap_num );
2251                                                 } else {
2252                                                         bm_page_in_texture( bitmap_num );
2253                                                 }                               
2254                                         }                                       
2255                                 }
2256
2257                         }
2258                 } 
2259         }
2260 }
2261
2262 #else
2263
2264 // stubbed out functions not used in the demo
2265 void    asteroid_init() {}
2266 void    asteroid_level_init() {}
2267 void    asteroid_level_close() {}
2268 void    asteroid_create_all() {}
2269 void    asteroid_render( object *asteroid_objp ) {}
2270 void    asteroid_delete( object *asteroid_objp ) {}
2271 void    asteroid_process_pre( object *asteroid_objp, float frame_time) {}
2272 void    asteroid_process_post( object *asteroid_objp, float frame_time) {}
2273 int     asteroid_check_collision( object *asteroid_objp, object * other_obj, vector * hitpos, collision_info_struct *asteroid_hit_info ) {return 0;}
2274 void    asteroid_hit( object *asteroid_objp, object *other_objp, vector *hitpos, float damage ) {}
2275 void    asteroid_save_restore(CFILE *fp) {}
2276 int     asteroid_count() {return 0;}
2277 int     asteroid_collide_objnum(object *asteroid_objp) {return 0;}
2278 float asteroid_time_to_impact(object *asteroid_objp) {return 0.0f;}
2279 void    asteroid_show_brackets() {}
2280 void    asteroid_target_closest_danger() {}
2281 void    asteroid_page_in() {}
2282 void    asteroid_sub_create(object *parent_objp, int asteroid_type, vector *relvec) {}
2283 void    asteroid_frame() {}
2284
2285
2286 #endif
2287