]> icculus.org git repositories - taylor/freespace2.git/blob - src/model/modelread.cpp
ryan's struct patch for gcc 2.95
[taylor/freespace2.git] / src / model / modelread.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/Model/ModelRead.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * file which reads and deciphers POF information
16  *
17  * $Log$
18  * Revision 1.6  2002/06/17 06:33:09  relnev
19  * ryan's struct patch for gcc 2.95
20  *
21  * Revision 1.5  2002/06/09 04:41:23  relnev
22  * added copyright header
23  *
24  * Revision 1.4  2002/06/09 03:16:04  relnev
25  * added _splitpath.
26  *
27  * removed unneeded asm, old sdl 2d setup.
28  *
29  * fixed crash caused by opengl_get_region.
30  *
31  * Revision 1.3  2002/06/01 07:12:33  relnev
32  * a few NDEBUG updates.
33  *
34  * removed a few warnings.
35  *
36  * Revision 1.2  2002/05/07 03:16:47  theoddone33
37  * The Great Newline Fix
38  *
39  * Revision 1.1.1.1  2002/05/03 03:28:10  root
40  * Initial import.
41  *
42  * 
43  * 36    7/22/99 2:26p Mattk
44  * DA: don't show engine wash error if no subsystems.  (ie, Pofview...)
45  * 
46  * 35    7/19/99 12:02p Andsager
47  * Allow AWACS on any ship subsystem. Fix sexp_set_subsystem_strength to
48  * only blow up subsystem if its strength is > 0
49  * 
50  * 34    7/07/99 5:00p Andsager
51  * Fixed bug in stepped rotation
52  * 
53  * 33    7/06/99 4:42p Anoop
54  * Add MiniCap hack for engine wash
55  * 
56  * 32    7/06/99 3:52p Andsager
57  * That wacky model_subsystem name vs. subobj_name thing bites us in the
58  * ass again.
59  * 
60  * 31    7/06/99 3:15p Anoop
61  * Better debug info for engine wash error.
62  * 
63  * 30    7/06/99 11:37a Andsager
64  * Fix warning message.
65  * 
66  * 29    7/06/99 10:45a Andsager
67  * Modify engine wash to work on any ship that is not small.  Add AWACS
68  * ask for help.
69  * 
70  * 28    7/01/99 4:23p Dave
71  * Full support for multiple linked ambient engine sounds. Added "big
72  * damage" flag.
73  * 
74  * 27    6/08/99 2:33p Dave
75  * Fixed release build warning. Put in hud config stuff.
76  * 
77  * 26    6/01/99 8:35p Dave
78  * Finished lockarm weapons. Added proper supercap weapons/damage. Added
79  * awacs-set-radius sexpression.
80  * 
81  * 25    5/28/99 1:51p Andsager
82  * Allow models to rotate in both direction on an axis, specifying a
83  * negative rotation time in submodel properties.
84  * 
85  * 24    5/27/99 3:48p Andsager
86  * Add assert to model_read code to not allow overwrite of memory
87  * 
88  * 23    5/27/99 12:11p Andsager
89  * Allow more than 1 subsystem to have live debris on any ship
90  * 
91  * 22    5/27/99 10:57a Mattk
92  * Put in a warning about too many firing points per turret.
93  * 
94  * 21    5/24/99 5:45p Dave
95  * Added detail levels to the nebula, with a decent speedup. Split nebula
96  * lightning into its own section.
97  * 
98  * 20    5/19/99 11:09a Andsager
99  * Turn on engine wash.  Check every 1/4 sec.
100  * 
101  * 19    5/11/99 10:16p Andsager
102  * First pass on engine wash effect.  Rotation (control input), damage,
103  * shake.  
104  * 
105  * 18    4/09/99 11:38a Andsager
106  * Change POF format for Freespace2
107  * 
108  * 17    3/23/99 5:17p Dave
109  * Changed model file format somewhat to account for LOD's on insignias
110  * 
111  * 16    3/20/99 3:46p Dave
112  * Added support for model-based background nebulae. Added 3 new
113  * sexpressions.
114  * 
115  * 15    3/19/99 6:15p Dave
116  * Put in checks for insignia bitmaps for having too many faces or
117  * vertices
118  * 
119  * 14    2/21/99 6:01p Dave
120  * Fixed standalone WSS packets. 
121  * 
122  * 13    2/19/99 11:42a Dave
123  * Put in model rendering autocentering.
124  * 
125  * 12    2/10/99 3:52p Enricco
126  * Fix stupid assert
127  * 
128  * 11    1/14/99 6:06p Dave
129  * 100% full squad logo support for single player and multiplayer.
130  * 
131  * 10    1/11/99 12:42p Andsager
132  * Add live debris - debris which is created from a destroyed subsystem,
133  * when the ship is still alive
134  * 
135  * 9     1/08/99 2:08p Dave
136  * Fixed software rendering for pofview. Super early support for AWACS and
137  * beam weapons.
138  * 
139  * 8     1/06/99 2:24p Dave
140  * Stubs and release build fixes.
141  * 
142  * 7     12/23/98 2:53p Andsager
143  * Added stepped rotation support
144  * 
145  * 6     12/04/98 3:34p Andsager
146  * Handle norotating submodels
147  * 
148  * 5     12/03/98 3:14p Andsager
149  * Check in code that checks rotating submodel actually has ship subsystem
150  * 
151  * 4     11/19/98 11:07p Andsager
152  * Check in of physics and collision detection of rotating submodels
153  * 
154  * 3     10/23/98 3:03p Andsager
155  * Initial support for changing rotation rate.
156  * 
157  * 2     10/07/98 10:53a Dave
158  * Initial checkin.
159  * 
160  * 1     10/07/98 10:50a Dave
161  * 
162  * 177   8/28/98 3:29p Dave
163  * EMP effect done. AI effects may need some tweaking as required.
164  * 
165  * 176   5/19/98 8:31p Andsager
166  * Added split planes (for big ship explosions)
167  * 
168  * 175   5/07/98 5:39p Andsager
169  * Changes to model to hold cross section info
170  * 
171  * 174   4/30/98 4:53p John
172  * Restructured and cleaned up cfile code.  Added capability to read off
173  * of CD-ROM drive and out of multiple pack files.
174  * 
175  * 173   4/22/98 9:43p John
176  * Added code to allow checking of invisible faces, flagged by any texture
177  * name with invisible in it.
178  * 
179  * 172   4/14/98 11:11p John
180  * Made ships with < 50% hull left show electrical damage arcs.
181  * 
182  * 171   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  * 170   4/01/98 9:14a Mike
187  * Fixed free bug
188  * 
189  * 169   3/31/98 5:18p John
190  * Removed demo/save/restore.  Made NDEBUG defined compile.  Removed a
191  * bunch of debug stuff out of player file.  Made model code be able to
192  * unload models and malloc out only however many models are needed.
193  *  
194  * 
195  * 168   3/17/98 2:46p Allender
196  * Copy subsystem name when copying model subsystems
197  * 
198  * 167   3/02/98 5:42p John
199  * Removed WinAVI stuff from Freespace.  Made all HUD gauges wriggle from
200  * afterburner.  Made gr_set_clip work good with negative x &y.  Made
201  * model_caching be on by default.  Made each cached model have it's own
202  * bitmap id.  Made asteroids not rotate when model_caching is on.  
203  * 
204  * 166   2/24/98 5:04p Allender
205  * allow different ship classes to use the same model.  Lot's of subsystem
206  * stuff to deal with
207  * 
208  * 165   2/16/98 3:46p John
209  * Made mass be proportional to area in newer pofs
210  * 
211  * 164   2/13/98 5:19p John
212  * First rev of new model caching system.  Needs to be ripped out and
213  * moved into ship stuff.
214  * 
215  * 163   1/29/98 5:52p John
216  * new version of electrical arcing code
217  * 
218  * 162   1/29/98 8:39a Andsager
219  * Changed mass and moment of intertia based area vs. volume
220  * 
221  * 161   1/28/98 2:15p Mike
222  * Convert volume to surface area at runtime.  Write note to John to
223  * cleanup if he modifies bspgen.
224  * 
225  * 160   1/27/98 11:02a John
226  * Added first rev of sparks.   Made all code that calls model_render call
227  * clear_instance first.   Made debris pieces not render by default when
228  * clear_instance is called.
229  * 
230  * 159   1/19/98 6:15p John
231  * Fixed all my Optimized Build compiler warnings
232  * 
233  * 158   1/09/98 11:25a John
234  * Took the thruster animation stuff out of the model.
235  * 
236  * 157   12/31/97 4:47p John
237  * Made all the eye points fit inside core radius
238  * 
239  * 156   12/31/97 2:35p John
240  * Added code for core_radius
241  * 
242  * 155   12/17/97 2:41p John
243  * made target bounding box be on hull only.
244  * 
245  * 154   12/17/97 9:54a John
246  * added code for precalculated weapon flash lighting.
247  * 
248  * 153   11/29/97 2:05p John
249  * made g3_draw_bitmap and g3_draw_rotated bitmap take w&h, not w/2 & h/2,
250  * like they used to incorrectly assume.   Added code to model to read in
251  * thruster radius's.
252  * 
253  * 152   11/25/97 11:41a John
254  * added code to read in pof v20.05, which adds radius to thrusters.
255  * 
256  * 151   10/28/97 12:34a Mike
257  * Set useful values of mass and inertia matrix if values not otherwise
258  * set.  Generate Warnings for unexpected ones.
259  * 
260  * 150   10/22/97 5:54p Lawrance
261  * get rid of leading '$' when storing parent_name for paths
262  * 
263  * 149   10/20/97 5:57p Lawrance
264  * have index to polymodel->paths[] within the model_subsystem struct.
265  * 
266  * 148   9/15/97 5:45p John
267  * took out chunk stuff.
268  * made pofview display thrusters as blue polies.
269  * 
270  * 147   9/09/97 3:39p Sandeep
271  * warning level 4 bugs
272  * 
273  * 146   9/04/97 5:09p Andsager
274  * implement physics using moment of inertia and mass (from BSPgen).
275  * Added to phys_info struct.  Updated ship_info, polymodel structs.
276  * Updated weapon ($Mass and $Force) and ship ($Mass -> $Density) tables
277  * 
278  * 145   9/03/97 5:57p Lawrance
279  * take out warning
280  * 
281  * 144   9/03/97 4:32p John
282  * changed bmpman to only accept ani and pcx's.  made passing .pcx or .ani
283  * to bm_load functions not needed.   Made bmpman keep track of palettes
284  * for bitmaps not mapped into game palettes.
285  * 
286  * 143   8/19/97 11:49p Lawrance
287  * using atan2_safe() in place of atan2()
288  * 
289  * 142   8/19/97 8:44a John
290  * Initial hooks for thruster stuff.
291  * 
292  * 141   8/15/97 4:10p John
293  * new code to use the new octrees style bsp trees
294  * 
295  * 140   8/14/97 5:46p John
296  * added code to read in mass,center of mass, and moment of interia from
297  * the pof.  Also added code to display green center of mass dot when Show
298  * debug points is on in pofview.
299  * 
300  * 139   7/10/97 8:34a John
301  * Added code to read TGA files.
302  * 
303  * 138   6/26/97 3:18p Mike
304  * Recognize "turret", etc. in a subsystem field anywhere in name.
305  * Generate warning for bogus subsystem names.
306  * 
307  * 137   6/25/97 5:11p John
308  * added foundation for model octants.
309  * 
310  * 136   6/25/97 10:28a John
311  * Made debris chunks radius be set correctly to the submodel size, not
312  * hardcoded to 10.0f.
313  * 
314  * 135   6/06/97 11:55a Mike
315  * Fix firing direction for zero piece turrets.
316  * 
317  * 134   5/31/97 2:36p Mike
318  * Comment out mprintfs pertaining to debris.
319  * 
320  * 133   5/30/97 4:41p Hoffoss
321  * Made some additions required for Fred.
322  * 
323  * 132   5/30/97 3:42p Mike
324  * Shield mesh and hit system.
325  * 
326  * 131   5/30/97 10:40a Hoffoss
327  * Added a function for Fred to get docking point names.
328  * 
329  * 130   5/29/97 4:34p Allender
330  * removed Int3 from model_find_dock_index.
331  * 
332  * 129   4/30/97 10:41a Allender
333  * don't dump out token 'none' when dumping out subsystem information
334  * 
335  * 128   4/17/97 6:06p John
336  * New code/data for v19 of BSPGEN with smoothing and zbuffer
337  * optimizations.
338  * 
339  * 127   4/09/97 3:31p Lawrance
340  * if any points of bounding box don't project, return project fail code
341  * in model_find_2d_bound_min()
342  * 
343  * 126   4/07/97 10:37a John
344  * Took out limits on number of children a submodel can have.    (So now
345  * capital ships can have tons of children on them).
346  * 
347  * 125   4/03/97 3:18p Allender
348  * 
349  * 124   4/03/97 1:29p Allender
350  * subsystem enhancement.  Initial work on making subsystem status
351  * meaningful
352  * 
353  * 123   3/28/97 2:49p John
354  * added code to fix targetting of debris chunks to draw bounding boxes
355  * right.
356  * 
357  * 122   3/28/97 1:19p John
358  * Made TestCode not show damaged submodels.
359  * 
360  * 121   3/28/97 11:17a John
361  * added code for linking lower detail submodels to the highest one; added
362  * code to pofview to view these.
363  * 
364  * 120   3/17/97 11:24a John
365  * 
366  * 119   3/15/97 5:06p John
367  * added bounding boxes for each subobject and code to display them.
368  * 
369  * 118   3/13/97 10:32a John
370  * Added code for tiled 256x256 textures in certain models.
371  * 
372  * 117   3/06/97 5:36p Mike
373  * Change vec_normalize_safe() back to vec_normalize().
374  * Spruce up docking a bit.
375  * 
376  * 116   3/06/97 1:06p Allender
377  * more docking stuff.  docking points now specified by strings in mission
378  * file.  Changes to builtin missions and code to reflect this change.
379  * 
380  * 115   3/06/97 10:56a Mike
381  * Write error checking version of vm_vec_normalize().
382  * Fix resultant problems.
383  * 
384  * 114   3/06/97 10:05a Lawrance
385  * added missing cfclose's
386  * 
387  * 113   3/05/97 5:27p John
388  * more work with turret stuff
389  * 
390  * 112   3/05/97 12:49p John
391  * added Viewer_obj.  Took out the interp_??? variables for turning
392  * outline,etc on and put them in flags you pass to model_render.
393  * Cleaned up model_interp code to fit new coding styles.
394  * 
395  * 111   3/05/97 12:42p Adam
396  * john: fixed bug while model transversel code that assumed the root
397  * subobject was 0.   
398  * 
399  * 110   3/05/97 11:09a Allender
400  * DOH!  MAX_SLOTS just way too low.  Upped to 25 and Asserts put in to
401  * check bounds.
402  * 
403  * 109   3/04/97 5:08p John
404  * Started adding debug code to make it so you can view from a turret's
405  * view.
406  * 
407  * 108   3/04/97 3:36p John
408  * took out old debug "h' key.   Made zbuffer flag bit bit field so you
409  * can turn on/off each value.   Fixed a bug with turret rotation where
410  * different handedness turrets wouldn't work.   Fixed a bug with two
411  * large ships within each other's radius not rendering correctly.
412  * 
413  * 107   3/04/97 12:52p Allender
414  * docking styff.  Added dock type to docking structure in model code.
415  * Renamed structure member in ai_goals.  Temporary checkin.  (i.e.
416  * rearming will use rearm dock points)
417  * 
418  * 106   3/03/97 5:47p John
419  * fixed some rotating object discrepencies.   Took out the gun firing
420  * point average beause it was inconsitent and wsn't as correct as using
421  * the pivot point.
422  * 
423  * 105   3/03/97 4:20p Hoffoss
424  * Fixed bug in bug I just fixed. :)
425  * 
426  * 104   3/03/97 4:00p Hoffoss
427  * fixed bug that caused docking bays without a name to be garbage when
428  * loaded.
429  * 
430  * 103   3/03/97 8:58a Lawrance
431  * replaced a fprintf() with a cfputs()
432  * 
433  * 102   3/01/97 2:12p Lawrance
434  * made to work with new cfile changes
435  * 
436  * 101   2/28/97 10:57a John
437  * Made so you can blow off any subsystems, not just radars.
438  * 
439  * 
440  * 100   2/27/97 3:45p John
441  * Added a tree dialog to pofview that shows a model's tree.
442  * 
443  * 99    2/27/97 12:07p John
444  * Added code to suppord debris chunks after a ship is exploded..
445  * 
446  * 98    2/26/97 5:28p John
447  * Fixed a bunch of chunked model bugs.  Basically they almost work better
448  * than non-chunked objects!
449  * 
450  * 97    2/24/97 1:13p Allender
451  * support for multiple eye positions.  Still some kinks to be worked out
452  * though....
453  * 
454  * 96    2/20/97 4:06p Allender
455  * allow for multiple spline paths to lead to a docking bay
456  * 
457  * 95    2/20/97 3:25p Allender
458  * change to docking bay structure -- added a name (for use in Fred
459  * mainly), and index into spline paths to reach this docking point
460  * 
461  * 94    2/19/97 4:03p Allender
462  * dump a 0.0 instead of a 0 when dumping out missing subsystem
463  * information
464  * 
465  * 93    2/19/97 2:52p Allender
466  * added crewspot name to subsystems (used only with turrets).  Will be
467  * used by fred for ai class stuff for turrets
468  * 
469  * 92    2/17/97 4:30p John
470  * Added code to automatically rotate any subsystems with the $rotate
471  * value set (except for turrets)
472  * 
473  * 91    2/17/97 12:03p John
474  * Added code to set the angles of a subobject.
475  * 
476  * 90    2/14/97 4:02p John
477  * changed a vector being passed as value to reference.
478  * 
479  * 89    2/14/97 3:16p Mike
480  * Start on AI path garbage collection
481  * 
482  * 88    2/14/97 1:06p John
483  * upped bspgen version number.
484  * 
485  * 87    2/13/97 10:17a John
486  * INCORPORATED THE FOLLOWING CHANGES:
487  * ???    2/13/97 9:49a John
488  * added code for geometric centers of objects.
489  *  ???   2/12/97 6:30p John
490  *  upped model version number.
491  *  
492  * 
493  * 86    2/13/97 9:49a John
494  * ROLLEDBACK TO ALLENDER'S 85 
495  * 
496  * 85    2/12/97 5:34p Allender
497  * added a ton of debug code to help recify the subsystems in ships.tbl
498  * with subsystems in the models.   Fixed a bug with subsystems not being
499  * given the correct type.
500  * 
501  * 84    2/11/97 4:10p Allender
502  * major change of subsystem stuff.  obj_subsystem renamed to
503  * model_subsystem.  Dyamically allocate space in ship_info for
504  * subsystems.
505  * 
506  * 83    2/10/97 4:20p Allender
507  * added distance to closest geometry to spline points
508  * 
509  * 82    2/10/97 10:58a John
510  * Added back in sparks for where laser bolts hit.
511  * Added code to red damaged objects and replace then.
512  * 
513  * 81    2/07/97 1:24p Allender
514  * added turret lists for spline points
515  * 
516  * 80    2/06/97 2:56p John
517  * Added a "blown-off" field to the instance of a model.  Also took out
518  * the model_set_angles functions and replaced with the more general
519  * model_set_instance functions.
520  * 
521  * 79    2/04/97 7:37p John
522  * Finally!!! Turret stuff working!
523  * 
524  * 78    1/31/97 12:51p John
525  * Added turret_fov and turret_fov_cos
526  * 
527  * 77    1/31/97 12:43p John
528  * Turrets working nicely, finally!
529  * 
530  * 76    1/31/97 11:36a John
531  * 
532  * 75    1/29/97 4:46p John
533  * Code to read $crewpoint flag on turrets and store it in obj_subsystem
534  * info.
535  * 
536  * 74    1/29/97 3:14p John
537  * Added field to ships.tbl to control how fast turret rotates.
538  * 
539  * 73    1/28/97 11:23a John
540  * added functions to get/set model angles.
541  * 
542  * 72    1/28/97 10:07a John
543  * More turret stuff, still not working, though.
544  * 
545  * 71    1/27/97 2:46p John
546  * more turret stuff
547  * 
548  * 70    1/27/97 11:35a Allender
549  * upped compatible object version
550  * 
551  * 69    1/24/97 5:25p John
552  * More turret stuff.   Not working yet, though.
553  * 
554  * 68    1/24/97 4:55p John
555  * Started adding code for turning turrets.
556  * Had to change POF format to 18.0
557  * 
558  * 67    1/20/97 2:16p Allender
559  * new shield structures being used
560  * 
561  * 66    1/15/97 5:19p Allender
562  * new POF version.  old version obsolete.  Added shield and eye stuff.
563  * New format for gun/missile/docking points
564  * 
565  * 65    1/10/97 5:15p Mike
566  * Moved ship-specific parameters from obj_subsystem to ship_subsys.
567  * 
568  * Added turret code to AI system.
569  * 
570  * 64    1/10/97 2:25p John
571  * Added code to support detail level distances.
572  * 
573  * 63    1/02/97 11:45a Allender
574  * changed turret code to have > 1 firing point as well as fixing the
575  * problems of turrets being multiple subobjects.  Turret norms should be
576  * getting stuffed correctly now.
577  * 
578  * 62    12/31/96 4:14p Mike
579  * Turret firing.
580  * Correct bug in HUDtarget.cpp, showing wrong target.
581  * 
582  * 61    12/27/96 4:09p Mike
583  * Integrate John's new model code.
584  * 
585  * 60    12/26/96 1:42p John
586  * Changed function ordering to put model_init at top.
587  * 
588  * 59    12/23/96 3:56p John
589  * Changed POF code to support pof 15.0.
590  * 
591  * 58    12/23/96 11:00a John
592  * Restructured POF stuff to support LOD in one pof.
593  * 
594  * 57    12/20/96 11:55a Allender
595  * removed debug code
596  * 
597  * 56    12/20/96 11:40a Allender
598  * modifed subsystem stuff to do correct hit percentages and other cool
599  * stuff
600  * 
601  * 55    12/18/96 4:04p Allender
602  * added "unknown" subsystem type for subsystems which aren't recognized.
603  * 
604  * 54    12/17/96 11:37a Mike
605  * Big ship AI.
606  * 
607  * 53    12/17/96 8:59a Mike
608  * Path-extraction-from-mdoel test code.
609  * 
610  * 52    12/13/96 5:27p John
611  * fixed my sloppy code that didn't free model data.
612  * 
613  * 51    12/13/96 3:54p Mike
614  * Major improvement to model_draw_paths -- connect the dots!  Uses
615  * sophisticated connect-to-next algorithm.
616  * 
617  * 50    12/13/96 2:59p John
618  * Added some code to test spline paths.
619  * 
620  * 49    12/13/96 2:41p John
621  * Added code to read in spline paths on models.
622  * 
623  * 48    12/13/96 10:29a Adam
624  * from allender:  fixed up linked list walking when checking for turrets
625  * in subsystems
626  * 
627  * 47    12/12/96 3:38p Allender
628  * fix up docking special object names.  Added $thruster stuff to model
629  * and code
630  * 
631  * 46    12/12/96 2:35p Mike
632  * Subsystem support
633  * 
634  * 45    12/12/96 12:29p Lawrance
635  * added function to find the 2d bound for a subobject
636  * 
637  * 44    12/11/96 5:35p John
638  * Added variables for viewer eye.
639  * 
640  * 43    12/11/96 5:15p John
641  * Made the dist for detail level be calculated before the object is
642  * instanced.
643  * 
644  * 42    12/11/96 4:50p John
645  * Added detail levels to the non-chunky ships.
646  * 
647  * 41    12/11/96 4:33p Mike
648  * Temporary version so other people can build.
649  * 
650  * 40    12/11/96 4:24p Mike
651  * Fix broken code...oops! clumsy in editor!
652  * 
653  * 39    12/11/96 4:17p Adam
654  * 
655  * 38    12/11/96 12:57p Mike
656  * Support for "Big Ship" AI behavior.
657  * More turret stuff.
658  * 
659  * 37    12/11/96 12:43p Allender
660  * $gun and $missile don't get appended to models gun/missile list if the
661  * gun/missile belongs to a turret.  Turrets are special instances of
662  * these
663  * 
664  * 36    12/11/96 11:57a Allender
665  * added objnum reference to obj_subsystems so that $gun and $missile
666  * special polygons can refernce a particular subsystem if needed (i.e. to
667  * get the norms, etc).
668  * 
669  * 35    12/11/96 10:33a Allender
670  * added stuff for FOV for turrets
671  * 
672  * 34    12/10/96 3:27p Allender
673  * 
674  * 33    12/09/96 5:05p Allender
675  * made subsystem lists and model_special lists as seperate entities.
676  * 
677  * 32    12/09/96 1:16p Allender
678  * made seperate lists for guns/missiles/subsystems, etc
679  * 
680  * 31    12/09/96 11:01a Allender
681  * added special polygon information to models.  Linked list contains
682  * gun/missile/docking/subsystem/etc information.
683  *
684  * $NoKeywords: $
685  */
686
687 #include <string.h>
688 #include <ctype.h>
689
690 #define MODEL_LIB
691
692 #include "cfile.h"
693 #include "model.h"
694 #include "bmpman.h"
695 #include "floating.h"
696 #include "3d.h"
697 #include "ship.h"
698 #include "modelsinc.h"
699 #include "key.h"
700 #include "2d.h"
701 #include "3dinternal.h"
702 #include "linklist.h"
703 #include "timer.h"
704 #include "freespace.h"          // For flFrameTime
705 #include "fvi.h"
706
707 #define MAX_SUBMODEL_COLLISION_ROT_ANGLE (PI / 6.0f)    // max 30 degrees per frame
708
709 // info for special polygon lists
710
711 polymodel *Polygon_models[MAX_POLYGON_MODELS];
712
713 static int model_initted = 0;
714
715 #ifndef NDEBUG
716 CFILE *ss_fp;                   // file pointer used to dump subsystem information
717 char  model_filename[_MAX_PATH];                // temp used to store filename
718 char    debug_name[_MAX_PATH];
719 int ss_warning_shown;           // have we shown the warning dialog concerning the subsystems?
720 char    Global_filename[256];
721 int Model_ram = 0;                      // How much RAM the models use total
722 #endif
723
724
725
726 // Anything less than this is considered incompatible.
727 #define PM_COMPATIBLE_VERSION 1900
728
729 // Anything greater than or equal to PM_COMPATIBLE_VERSION and 
730 // whose major version is less than or equal to this is considered
731 // compatible.  
732 #define PM_OBJFILE_MAJOR_VERSION 21
733
734 static int Model_signature = 0;
735
736 // Free up a model, getting rid of all its memory
737 // Can't be called from outside of model code because more
738 // than one person might be using this model so we can't free 
739 // it.
740 static void model_unload(int modelnum)
741 {
742         int i,j;
743
744         if ( (modelnum < 0) || (modelnum>MAX_POLYGON_MODELS))   {
745                 return;
746         }
747
748         polymodel *pm = Polygon_models[modelnum];
749
750         if ( !pm )      {
751                 return;
752         }
753
754 #ifndef NDEBUG
755         Model_ram -= pm->ram_used;
756 #endif
757         
758         if (pm->paths)  {
759                 for (i=0; i<pm->n_paths; i++ )  {
760                         for (j=0; j<pm->paths[i].nverts; j++ )  {
761                                 if ( pm->paths[i].verts[j].turret_ids ) {
762                                         free(pm->paths[i].verts[j].turret_ids);
763                                 }
764                         }
765                         if (pm->paths[i].verts) {
766                                 free(pm->paths[i].verts);
767                         }
768                 }
769                 free(pm->paths);
770         }
771
772         if ( pm->shield.verts ) {
773                 free( pm->shield.verts );
774         }
775
776         if ( pm->shield.tris )  {
777                 free(pm->shield.tris);
778         }
779
780         if ( pm->missile_banks )        {
781                 free(pm->missile_banks);
782         }
783
784         if ( pm->docking_bays ) {
785                 for (i=0; i<pm->n_docks; i++ )  {
786                         if ( pm->docking_bays[i].splines )      {
787                                 free( pm->docking_bays[i].splines );
788                         }
789                 }
790                 free(pm->docking_bays);
791         }
792
793
794         if ( pm->thrusters )    {
795                 free(pm->thrusters);
796         }
797
798 #ifndef NDEBUG
799         if ( pm->debug_info )   {
800                 free(pm->debug_info);
801         }
802 #endif
803
804         model_octant_free( pm );
805
806         if (pm->submodel)       {
807                 for (i=0; i<pm->n_models; i++ ) {
808                         if ( pm->submodel[i].bsp_data ) {
809                                 free(pm->submodel[i].bsp_data);
810                         }
811                 }
812                 free(pm->submodel);
813         }
814
815         if ( pm->xc ) {
816                 free(pm->xc);
817         }
818
819         if ( pm->lights )       {
820                 free(pm->lights);
821         }
822
823         if ( pm->gun_banks )    {
824                 free(pm->gun_banks);
825         }
826
827         pm->id = 0;
828         memset( pm, 0, sizeof(polymodel));
829         free( pm );
830
831         Polygon_models[modelnum] = NULL;        
832 }
833
834 void model_free_all()
835 {
836         int i;
837
838         if ( !model_initted)    {
839                 model_init();
840                 return;
841         }
842
843         mprintf(( "Freeing all existing models...\n" ));
844
845         for (i=0;i<MAX_POLYGON_MODELS;i++) {
846                 model_unload(i);                
847         }
848
849 }
850
851 void model_init()
852 {
853         int i;
854
855         if ( model_initted )            {
856                 Int3();         // Model_init shouldn't be called twice!
857                 return;
858         }
859
860 #ifndef NDEBUG
861         Model_ram = 0;
862 #endif
863
864         for (i=0;i<MAX_POLYGON_MODELS;i++) {
865                 Polygon_models[i] = NULL;
866         }
867
868         // Init the model caching system
869         model_cache_init();
870
871         atexit( model_free_all );
872         model_initted = 1;
873 }
874
875 // routine to parse out values from a user property field of an object
876 void get_user_prop_value(char *buf, char *value)
877 {
878         char *p, *p1, c;
879
880         p = buf;
881         while ( isspace(*p) || (*p == '=') )            // skip white space and equal sign
882                 p++;
883         p1 = p;
884         while ( !iscntrl(*p1) )
885                 p1++;
886         c = *p1;
887         *p1 = '\0';
888         strcpy(value, p);
889         *p1 = c;
890 }
891
892 // funciton to copy model data from one subsystem set to another subsystem set.  This function
893 // is called when two ships use the same model data, but since the model only gets read in one time,
894 // the subsystem data is only present in one location.  The ship code will call this routine to fix
895 // this situation by copying stuff from the source subsystem set to the dest subsystem set.
896 void model_copy_subsystems( int n_subsystems, model_subsystem *d_sp, model_subsystem *s_sp )
897 {
898         int i, j;
899         model_subsystem *source, *dest;
900
901         for (i = 0; i < n_subsystems; i++ ) {
902                 source = &s_sp[i];
903                 for ( j = 0; j < n_subsystems; j++ ) {
904                         dest = &d_sp[j];
905                         if ( !stricmp( source->subobj_name, dest->subobj_name) ) {
906                                 dest->flags = source->flags;
907                                 dest->subobj_num = source->subobj_num;
908                                 dest->model_num = source->model_num;
909                                 dest->pnt = source->pnt;
910                                 dest->radius = source->radius;
911                                 dest->type = source->type;
912                                 dest->turn_rate = source->turn_rate;
913                                 dest->turret_gun_sobj = source->turret_gun_sobj;
914
915                                 strcpy( dest->name, source->name );
916
917                                 if ( dest->type == SUBSYSTEM_TURRET ) {
918                                         int nfp;
919
920                                         dest->turret_fov = source->turret_fov;
921                                         dest->turret_num_firing_points = source->turret_num_firing_points;
922                                         dest->turret_norm = source->turret_norm;
923                                         dest->turret_matrix = source->turret_matrix;
924
925                                         for (nfp = 0; nfp < dest->turret_num_firing_points; nfp++ )
926                                                 dest->turret_firing_point[nfp] = source->turret_firing_point[nfp];
927
928                                         if ( dest->flags & MSS_FLAG_CREWPOINT )
929                                                 strcpy(dest->crewspot, source->crewspot);
930                                 }
931                                 break;
932                         }
933                 }
934                 if ( j == n_subsystems )
935                         Int3();                                                 // get allender -- something is amiss with models
936
937         }
938 }
939
940 // routine to get/set subsystem information
941 static void set_subsystem_info( model_subsystem *subsystemp, char *props, char *dname )
942 {
943         char *p;
944         char buf[32];
945         char    lcdname[256];
946
947         if ( (p = strstr(props, "$name")) != NULL)
948                 get_user_prop_value(p+5, subsystemp->name);
949         else
950                 strcpy( subsystemp->name, dname );
951
952         strcpy(lcdname, dname);
953         strlwr(lcdname);
954
955         // check the name for it's specific type
956         if ( strstr(lcdname, "engine") ) {
957                 subsystemp->type = SUBSYSTEM_ENGINE;
958         } else if ( strstr(lcdname, "radar") ) {
959                 subsystemp->type = SUBSYSTEM_RADAR;
960         } else if ( strstr(lcdname, "turret") ) {
961                 float angle;
962
963                 subsystemp->type = SUBSYSTEM_TURRET;
964                 if ( (p = strstr(props, "$fov")) != NULL )
965                         get_user_prop_value(p+4, buf);                  // get the value of the fov
966                 else
967                         strcpy(buf,"180");
968                 angle = ANG_TO_RAD(atoi(buf))/2.0f;
969                 subsystemp->turret_fov = (float)cos(angle);
970                 subsystemp->turret_num_firing_points = 0;
971
972                 if ( (p = strstr(props, "$crewspot")) != NULL) {
973                         subsystemp->flags |= MSS_FLAG_CREWPOINT;
974                         get_user_prop_value(p+9, subsystemp->crewspot);
975                 }
976
977         } else if ( strstr(lcdname, "navigation") ) {
978                 subsystemp->type = SUBSYSTEM_NAVIGATION;
979         } else if ( strstr(lcdname, "communication") )  {
980                 subsystemp->type = SUBSYSTEM_COMMUNICATION;
981         } else if ( strstr(lcdname, "weapons") ) {
982                 subsystemp->type = SUBSYSTEM_WEAPONS;
983         } else if ( strstr(lcdname, "sensors") ) {
984                 subsystemp->type = SUBSYSTEM_SENSORS;
985         } else if ( strstr(lcdname, "solar") ) {
986                 subsystemp->type = SUBSYSTEM_SOLAR;
987         } else if ( strstr(lcdname, "gas") ) {
988                 subsystemp->type = SUBSYSTEM_GAS_COLLECT;
989         } else if ( strstr(lcdname, "activator") ) {
990                 subsystemp->type = SUBSYSTEM_ACTIVATION;
991         }  else { // If unrecognized type, set to unknown so artist can continue working...
992                 subsystemp->type = SUBSYSTEM_UNKNOWN;
993                 mprintf(("Warning: Ignoring unrecognized subsystem %s, believed to be in ship %s\n", dname, Global_filename));
994         }
995
996         // Rotating subsystem
997         if ( (p = strstr(props, "$rotate")) != NULL)    {
998                 subsystemp->flags |= MSS_FLAG_ROTATES;
999
1000                 // get time for (a) complete rotation (b) step (c) activation
1001                 float turn_time;
1002                 get_user_prop_value(p+7, buf);
1003                 turn_time = (float)atof(buf);
1004
1005                 // CASE OF STEPPED ROTATION
1006                 if ( (p = strstr(props, "$stepped")) != NULL) {
1007
1008                         subsystemp->stepped_rotation = new(stepped_rotation);
1009                         subsystemp->flags |= MSS_FLAG_STEPPED_ROTATE;
1010
1011                         // get number of steps
1012                         if ( (p = strstr(props, "$steps")) != NULL) {
1013                                 get_user_prop_value(p+6, buf);
1014                            subsystemp->stepped_rotation->num_steps = atoi(buf);
1015                          } else {
1016                             subsystemp->stepped_rotation->num_steps = 8;
1017                          }
1018
1019                         // get pause time
1020                         if ( (p = strstr(props, "$t_paused")) != NULL) {
1021                                 get_user_prop_value(p+9, buf);
1022                            subsystemp->stepped_rotation->t_pause = (float)atof(buf);
1023                          } else {
1024                             subsystemp->stepped_rotation->t_pause = 2.0f;
1025                          }
1026
1027                         // get transition time - time to go between steps
1028                         if ( (p = strstr(props, "$t_transit")) != NULL) {
1029                                 get_user_prop_value(p+10, buf);
1030                             subsystemp->stepped_rotation->t_transit = (float)atof(buf);
1031                         } else {
1032                             subsystemp->stepped_rotation->t_transit = 2.0f;
1033                         }
1034
1035                         // get fraction of time spent in accel
1036                         if ( (p = strstr(props, "$fraction_accel")) != NULL) {
1037                                 get_user_prop_value(p+15, buf);
1038                             subsystemp->stepped_rotation->fraction = (float)atof(buf);
1039                            Assert(subsystemp->stepped_rotation->fraction > 0 && subsystemp->stepped_rotation->fraction < 0.5);
1040                         } else {
1041                             subsystemp->stepped_rotation->fraction = 0.3f;
1042                         }
1043
1044                         int num_steps = subsystemp->stepped_rotation->num_steps;
1045                         float t_trans = subsystemp->stepped_rotation->t_transit;
1046                         float fraction = subsystemp->stepped_rotation->fraction;
1047
1048                         subsystemp->stepped_rotation->max_turn_accel = PI2 / (fraction*(1.0f - fraction) * num_steps * t_trans*t_trans);
1049                         subsystemp->stepped_rotation->max_turn_rate =  PI2 / ((1.0f - fraction) * num_steps *t_trans);
1050
1051                 }
1052
1053                 // CASE OF AI ROTATION
1054                 else if ( (p = strstr(props, "$ai")) != NULL) {
1055                         get_user_prop_value(p+8, buf);
1056                         subsystemp->flags |= MSS_FLAG_AI_ROTATE;
1057
1058                         // get parameters - ie, speed / dist / other ??
1059                         // time to activate
1060                         // condition
1061                 }
1062
1063                 // CASE OF NORMAL CONTINUOUS ROTATION
1064                 else {
1065                         if ( fabs(turn_time) < 1 ) {                            
1066                                 // Warning(LOCATION, "%s has subsystem %s with rotation time less than 1 sec", dname, Global_filename );
1067                                 subsystemp->flags &= ~MSS_FLAG_ROTATES;
1068                                 subsystemp->turn_rate = 0.0f;
1069                         } else {
1070                                 subsystemp->turn_rate = PI2 / turn_time;
1071                         }
1072                 }
1073         }
1074
1075 }
1076
1077 // used in collision code to check if submode rotates too far
1078 float get_submodel_delta_angle(submodel_instance_info *sii)
1079 {
1080         vector diff;
1081         vm_vec_sub(&diff, (vector*)&sii->angs, (vector*)&sii->prev_angs);
1082
1083         // find the angle
1084         float delta_angle = vm_vec_mag(&diff);
1085
1086         // make sure we get the short way around
1087         if (delta_angle > PI) {
1088                 delta_angle = (PI2 - delta_angle);
1089         }
1090
1091         return delta_angle;
1092 }
1093
1094 void do_new_subsystem( int n_subsystems, model_subsystem *slist, int subobj_num, float rad, vector *pnt, char *props, char *subobj_name, int model_num )
1095 {
1096         int i;
1097         model_subsystem *subsystemp;
1098
1099
1100         if ( slist==NULL ) return;                      // For TestCode, POFView, etc don't bother
1101         
1102         // try to find the name of the subsystem passed here on the list of subsystems currently on the
1103         // ship.  Assign the values only when the right subsystem is found
1104
1105         for (i = 0; i < n_subsystems; i++ ) {
1106                 subsystemp = &slist[i];
1107                 if ( !stricmp(subobj_name, subsystemp->subobj_name) ) {
1108                         subsystemp->flags = 0;
1109                         subsystemp->subobj_num = subobj_num;
1110                         subsystemp->turret_gun_sobj = -1;
1111                         subsystemp->model_num = model_num;
1112                         subsystemp->pnt = *pnt;                         // use the offset to get the center point of the subsystem
1113                         subsystemp->radius = rad;
1114                         set_subsystem_info( subsystemp, props, subobj_name);
1115                         strcpy(subsystemp->subobj_name, subobj_name);                                           // copy the object name
1116                         return;
1117                 }
1118         }
1119 #ifndef NDEBUG
1120         if ( !ss_warning_shown) {
1121                 char bname[_MAX_FNAME];
1122
1123                 _splitpath(model_filename, NULL, NULL, bname, NULL);
1124                 Warning(LOCATION, "A subsystem was found in model %s that does not have a record in ships.tbl.\nA list of subsystems for this ship will be dumped to:\n\ndata\\tables\\%s.subsystems for inclusion\n into ships.tbl.", model_filename, bname);
1125
1126                 ss_warning_shown = 1;
1127         } else
1128 #endif
1129         nprintf(("warning", "Subsystem %s in ships.tbl not found in model!\n", subobj_name));
1130 #ifndef NDEBUG
1131         if ( ss_fp )    {
1132                 char tmp_buffer[128];
1133                 sprintf(tmp_buffer, "$Subsystem:\t\t\t%s,1,0.0\n", subobj_name);
1134                 cfputs(tmp_buffer, ss_fp);
1135         }
1136 #endif
1137
1138 }
1139
1140 void print_family_tree( polymodel *obj, int modelnum, char * ident, int islast )        
1141 {
1142         char temp[50];
1143
1144         if ( modelnum < 0 ) return;
1145         if (obj==NULL) return;
1146
1147         if (strlen(ident)==0 )  {
1148                 mprintf(( " %s", obj->submodel[modelnum].name ));
1149                 sprintf( temp, " " );
1150         } else if ( islast )    {
1151                 mprintf(( "%sÀÄ%s", ident, obj->submodel[modelnum].name ));
1152                 sprintf( temp, "%s  ", ident );
1153         } else {
1154                 mprintf(( "%sÃÄ%s", ident, obj->submodel[modelnum].name ));
1155                 sprintf( temp, "%s³ ", ident );
1156         }
1157
1158         mprintf(( "\n" ));
1159
1160         int child = obj->submodel[modelnum].first_child;
1161         while( child > -1 )     {
1162                 if ( obj->submodel[child].next_sibling < 0 )
1163                         print_family_tree( obj, child, temp,1 );
1164                 else
1165                         print_family_tree( obj, child, temp,0 );
1166                 child = obj->submodel[child].next_sibling;
1167         }
1168 }
1169
1170 void dump_object_tree(polymodel *obj)
1171 {
1172         print_family_tree( obj, 0, "", 0 );
1173         key_getch();
1174 }
1175
1176 void create_family_tree(polymodel *obj)
1177 {
1178         int i;
1179         for (i=0; i<obj->n_models; i++ )        {
1180                 obj->submodel[i].num_children = 0;
1181                 obj->submodel[i].first_child = -1;
1182                 obj->submodel[i].next_sibling = -1;
1183         }
1184
1185         for (i=0; i<obj->n_models; i++ )        {
1186                 int pn;
1187                 pn = obj->submodel[i].parent;
1188                 if ( pn > -1 )  {
1189                         obj->submodel[pn].num_children++;
1190                         int tmp = obj->submodel[pn].first_child;
1191                         obj->submodel[pn].first_child = i;
1192                         obj->submodel[i].next_sibling = tmp;
1193                 }
1194         }
1195 }
1196
1197 void model_calc_bound_box( vector *box, vector *big_mn, vector *big_mx)
1198 {
1199         box[0].xyz.x = big_mn->xyz.x; box[0].xyz.y = big_mn->xyz.y; box[0].xyz.z = big_mn->xyz.z;
1200         box[1].xyz.x = big_mx->xyz.x; box[1].xyz.y = big_mn->xyz.y; box[1].xyz.z = big_mn->xyz.z;
1201         box[2].xyz.x = big_mx->xyz.x; box[2].xyz.y = big_mx->xyz.y; box[2].xyz.z = big_mn->xyz.z;
1202         box[3].xyz.x = big_mn->xyz.x; box[3].xyz.y = big_mx->xyz.y; box[3].xyz.z = big_mn->xyz.z;
1203
1204
1205         box[4].xyz.x = big_mn->xyz.x; box[4].xyz.y = big_mn->xyz.y; box[4].xyz.z = big_mx->xyz.z;
1206         box[5].xyz.x = big_mx->xyz.x; box[5].xyz.y = big_mn->xyz.y; box[5].xyz.z = big_mx->xyz.z;
1207         box[6].xyz.x = big_mx->xyz.x; box[6].xyz.y = big_mx->xyz.y; box[6].xyz.z = big_mx->xyz.z;
1208         box[7].xyz.x = big_mn->xyz.x; box[7].xyz.y = big_mx->xyz.y; box[7].xyz.z = big_mx->xyz.z;
1209 }
1210
1211
1212 //      Debug thing so we don't repeatedly show warning messages.
1213 #ifndef NDEBUG
1214 int Bogus_warning_flag_1903 = 0;
1215 #endif
1216
1217 //reads a binary file containing a 3d model
1218 int read_model_file(polymodel * pm, char *filename, int n_subsystems, model_subsystem *subsystems)
1219 {
1220         CFILE *fp;
1221         int version;
1222         int id, len, next_chunk;
1223         int i,j;
1224
1225 #ifndef NDEBUG
1226         strcpy(Global_filename, filename);
1227 #endif
1228
1229         fp = cfopen(filename,"rb");
1230         if (!fp){
1231                 Error( LOCATION, "Can't open file <%s>",filename);
1232                 return 0;
1233         }               
1234
1235         // code to get a filename to write out subsystem information for each model that
1236         // is read.  This info is essentially debug stuff that is used to help get models
1237         // into the game quicker
1238 #if 0
1239         {
1240                 char bname[_MAX_FNAME];
1241
1242                 _splitpath(filename, NULL, NULL, bname, NULL);
1243                 sprintf(debug_name, "%s.subsystems", bname);
1244                 ss_fp = cfopen(debug_name, "wb", CFILE_NORMAL, CF_TYPE_TABLES );
1245                 if ( !ss_fp )   {
1246                         mprintf(( "Can't open debug file for writing subsystems for %s\n", filename));
1247                 } else {
1248                         strcpy(model_filename, filename);
1249                         ss_warning_shown = 0;
1250                 }
1251         }
1252 #endif
1253
1254         id = cfread_int(fp);
1255
1256         if (id!='OPSP')
1257                 Error( LOCATION, "Bad ID in model file <%s>",filename);
1258
1259         // Version is major*100+minor
1260         // So, major = version / 100;
1261         //     minor = version % 100;
1262         version = cfread_int(fp);
1263
1264         //Warning( LOCATION, "POF Version = %d", version );
1265         
1266         if (version < PM_COMPATIBLE_VERSION || (version/100) > PM_OBJFILE_MAJOR_VERSION)        {
1267                 Warning(LOCATION,"Bad version (%d) in model file <%s>",version,filename);
1268                 return 0;
1269         }
1270
1271         pm->version = version;
1272         Assert( strlen(filename) < FILENAME_LEN );
1273         strncpy(pm->filename, filename, FILENAME_LEN);
1274
1275         memset( &pm->view_positions, 0, sizeof(pm->view_positions) );
1276
1277         // reset insignia counts
1278         pm->num_ins = 0;
1279
1280         id = cfread_int(fp);
1281         len = cfread_int(fp);
1282         next_chunk = cftell(fp) + len;
1283
1284         while (!cfeof(fp)) {
1285
1286 //              mprintf(("Processing chunk <%c%c%c%c>, len = %d\n",id,id>>8,id>>16,id>>24,len));
1287 //              key_getch();
1288
1289                 switch (id) {
1290
1291                         case ID_OHDR: {         //Object header
1292                                 //vector v;
1293
1294                                 //mprintf(0,"Got chunk OHDR, len=%d\n",len);
1295
1296 #if defined( FREESPACE1_FORMAT )
1297                                 pm->n_models = cfread_int(fp);
1298 //                              mprintf(( "Num models = %d\n", pm->n_models ));
1299                                 pm->rad = cfread_float(fp);
1300                                 pm->flags = cfread_int(fp);     // 1=Allow tiling
1301 #elif defined( FREESPACE2_FORMAT )
1302                                 pm->rad = cfread_float(fp);
1303                                 pm->flags = cfread_int(fp);     // 1=Allow tiling
1304                                 pm->n_models = cfread_int(fp);
1305 //                              mprintf(( "Num models = %d\n", pm->n_models ));
1306 #endif
1307                                 
1308                                 pm->submodel = (bsp_info *)malloc( sizeof(bsp_info)*pm->n_models );
1309                                 Assert(pm->submodel != NULL );
1310                                 memset( pm->submodel, 0, sizeof(bsp_info)*pm->n_models );
1311
1312                                 //Assert(pm->n_models <= MAX_SUBMODELS);
1313
1314                                 cfread_vector(&pm->mins,fp);
1315                                 cfread_vector(&pm->maxs,fp);
1316                                 model_calc_bound_box(pm->bounding_box,&pm->mins,&pm->maxs);
1317                                 
1318                                 pm->n_detail_levels = cfread_int(fp);
1319                         //      mprintf(( "There are %d detail levels\n", pm->n_detail_levels ));
1320                                 for (i=0; i<pm->n_detail_levels;i++ )   {
1321                                         pm->detail[i] = cfread_int(fp);
1322                                         pm->detail_depth[i] = 0.0f;
1323                         ///             mprintf(( "Detail level %d is model %d.\n", i, pm->detail[i] ));
1324                                 }
1325
1326                                 pm->num_debris_objects = cfread_int(fp);
1327                                 Assert( pm->num_debris_objects <= MAX_DEBRIS_OBJECTS );
1328                                 // mprintf(( "There are %d debris objects\n", pm->num_debris_objects ));
1329                                 for (i=0; i<pm->num_debris_objects;i++ )        {
1330                                         pm->debris_objects[i] = cfread_int(fp);
1331                                         // mprintf(( "Debris object %d is model %d.\n", i, pm->debris_objects[i] ));
1332                                 }
1333
1334                                 if ( pm->version >= 1903 )      {
1335         
1336                                         if ( pm->version >= 2009 )      {
1337                                                                                                                                         
1338                                                 pm->mass = cfread_float(fp);
1339                                                 cfread_vector( &pm->center_of_mass, fp );
1340                                                 cfread_vector( &pm->moment_of_inertia.v.rvec, fp );
1341                                                 cfread_vector( &pm->moment_of_inertia.v.uvec, fp );
1342                                                 cfread_vector( &pm->moment_of_inertia.v.fvec, fp );
1343                                         } else {
1344                                                 // old code where mass wasn't based on area, so do the calculation manually
1345
1346                                                 float vol_mass = cfread_float(fp);
1347                                                 //      Attn: John Slagel:  The following is better done in bspgen.
1348                                                 // Convert volume (cubic) to surface area (quadratic) and scale so 100 -> 100
1349                                                 float area_mass = (float) pow(vol_mass, 0.6667f) * 4.65f;
1350
1351                                                 pm->mass = area_mass;
1352                                                 float mass_ratio = vol_mass / area_mass; 
1353                                                         
1354                                                 cfread_vector( &pm->center_of_mass, fp );
1355                                                 cfread_vector( &pm->moment_of_inertia.v.rvec, fp );
1356                                                 cfread_vector( &pm->moment_of_inertia.v.uvec, fp );
1357                                                 cfread_vector( &pm->moment_of_inertia.v.fvec, fp );
1358
1359                                                 // John remove this with change to bspgen
1360                                                 vm_vec_scale( &pm->moment_of_inertia.v.rvec, mass_ratio );
1361                                                 vm_vec_scale( &pm->moment_of_inertia.v.uvec, mass_ratio );
1362                                                 vm_vec_scale( &pm->moment_of_inertia.v.fvec, mass_ratio );
1363                                         }       
1364                                 } else {
1365 #ifndef NDEBUG
1366                                         if (stricmp("fighter04.pof", filename)) {
1367                                                 if (Bogus_warning_flag_1903 == 0) {
1368                                                         Warning(LOCATION, "Ship %s is old.  Cannot compute mass.\nSetting to 50.0f.  Talk to John.", filename);
1369                                                         Bogus_warning_flag_1903 = 1;
1370                                                 }
1371                                         }
1372 #endif
1373                                         pm->mass = 50.0f;
1374                                         vm_vec_zero( &pm->center_of_mass );
1375                                         vm_set_identity( &pm->moment_of_inertia );
1376                                         vm_vec_scale(&pm->moment_of_inertia.v.rvec, 0.001f);
1377                                         vm_vec_scale(&pm->moment_of_inertia.v.uvec, 0.001f);
1378                                         vm_vec_scale(&pm->moment_of_inertia.v.fvec, 0.001f);
1379                                 }
1380
1381                                 // read in cross section info
1382                                 pm->xc = NULL;
1383                                 if ( pm->version >= 2014 ) {
1384                                         pm->num_xc = cfread_int(fp);
1385                                         if (pm->num_xc > 0) {
1386                                                 pm->xc = (cross_section*) malloc(pm->num_xc*sizeof(cross_section));
1387                                                 for (int i=0; i<pm->num_xc; i++) {
1388                                                         pm->xc[i].z = cfread_float(fp);
1389                                                         pm->xc[i].radius = cfread_float(fp);
1390                                                 }
1391                                         }
1392                                 } else {
1393                                         pm->num_xc = 0;
1394                                 }
1395
1396                                 if ( pm->version >= 2007 )      {
1397                                         pm->num_lights = cfread_int(fp);
1398                                         //mprintf(( "Found %d lights!\n", pm->num_lights ));
1399
1400                                         pm->lights = (bsp_light *)malloc( sizeof(bsp_light)*pm->num_lights );
1401                                         for (i=0; i<pm->num_lights; i++ )       {                       
1402                                                 cfread_vector(&pm->lights[i].pos,fp);
1403                                                 pm->lights[i].type = cfread_int(fp);
1404                                                 pm->lights[i].value = 0.0f;
1405                                         }                                                               
1406                                 } else {
1407                                         pm->num_lights = 0;
1408                                         pm->lights = NULL;
1409                                 }
1410
1411                                 break;
1412                         }
1413                         
1414                         case ID_SOBJ: {         //Subobject header
1415                                 int n;
1416                                 char *p, props[MAX_PROP_LEN];
1417 //                              float d;
1418
1419                                 //mprintf(0,"Got chunk SOBJ, len=%d\n",len);
1420
1421                                 n = cfread_int(fp);
1422
1423                                 Assert(n < pm->n_models );
1424
1425 #if defined( FREESPACE2_FORMAT )        
1426                                 pm->submodel[n].rad = cfread_float(fp);         //radius
1427 #endif
1428
1429                                 pm->submodel[n].parent = cfread_int(fp);
1430
1431 //                              cfread_vector(&pm->submodel[n].norm,fp);
1432 //                              d = cfread_float(fp);                           
1433 //                              cfread_vector(&pm->submodel[n].pnt,fp);
1434                                 cfread_vector(&pm->submodel[n].offset,fp);
1435
1436 //                      mprintf(( "Subobj %d, offs = %.1f, %.1f, %.1f\n", n, pm->submodel[n].offset.xyz.x, pm->submodel[n].offset.xyz.y, pm->submodel[n].offset.xyz.z ));
1437         
1438 #if defined ( FREESPACE1_FORMAT )
1439                                 pm->submodel[n].rad = cfread_float(fp);         //radius
1440 #endif
1441
1442 //                              pm->submodel[n].tree_offset = cfread_int(fp);   //offset
1443 //                              pm->submodel[n].data_offset = cfread_int(fp);   //offset
1444
1445                                 cfread_vector(&pm->submodel[n].geometric_center,fp);
1446
1447                                 cfread_vector(&pm->submodel[n].min,fp);
1448                                 cfread_vector(&pm->submodel[n].max,fp);
1449
1450                                 model_calc_bound_box(pm->submodel[n].bounding_box,&pm->submodel[n].min,&pm->submodel[n].max);
1451
1452                                 pm->submodel[n].name[0] = '\0';
1453
1454                                 cfread_string_len( pm->submodel[n].name, MAX_NAME_LEN, fp);             // get the name
1455                                 cfread_string_len(props, MAX_PROP_LEN, fp);                     // and the user properites
1456
1457                                 pm->submodel[n].movement_type = cfread_int(fp);
1458                                 pm->submodel[n].movement_axis = cfread_int(fp);
1459
1460                                 // change turret movement type to MOVEMENT_TYPE_ROT_SPECIAL
1461                                 if (pm->submodel[n].movement_type == MOVEMENT_TYPE_ROT) {
1462                                         if ( strstr(pm->submodel[n].name, "turret") || strstr(pm->submodel[n].name, "gun") || strstr(pm->submodel[n].name, "cannon")) {
1463                                                 pm->submodel[n].movement_type = MOVEMENT_TYPE_ROT_SPECIAL;
1464                                         } else if (strstr(pm->submodel[n].name, "thruster")) {
1465                                                 // Int3();
1466                                                 pm->submodel[n].movement_type = MOVEMENT_TYPE_NONE;
1467                                                 pm->submodel[n].movement_axis = MOVEMENT_AXIS_NONE;
1468                                         }
1469                                 }
1470
1471                                 if ( pm->submodel[n].name[0] == '\0' ) {
1472                                         strcpy(pm->submodel[n].name, "unknown object name");
1473                                 }
1474
1475                                 bool rotating_submodel_has_subsystem = !(pm->submodel[n].movement_type == MOVEMENT_TYPE_ROT);
1476                                 if ( ( p = strstr(props, "$special"))!= NULL ) {
1477                                         char type[32];
1478
1479                                         get_user_prop_value(p+9, type);
1480                                         if ( !stricmp(type, "subsystem") ) {    // if we have a subsystem, put it into the list!
1481                                                 do_new_subsystem( n_subsystems, subsystems, n, pm->submodel[n].rad, &pm->submodel[n].offset, props, pm->submodel[n].name, pm->id );
1482                                                 rotating_submodel_has_subsystem = true;
1483                                         } else if ( !stricmp(type, "no_rotate") ) {
1484                                                 // mark those submodels which should not rotate - ie, those with no subsystem
1485                                                 pm->submodel[n].movement_type = MOVEMENT_TYPE_NONE;
1486                                                 pm->submodel[n].movement_axis = MOVEMENT_AXIS_NONE;
1487                                         } else {
1488                                                 // if submodel rotates (via bspgen), then there is either a subsys or special=no_rotate
1489                                                 Assert( pm->submodel[n].movement_type != MOVEMENT_TYPE_ROT );
1490                                         }
1491                                 }
1492
1493                                 if ( !rotating_submodel_has_subsystem ) {
1494                                         nprintf(("Model", "Model %s: Rotating Submodel without subsystem: %s\n", pm->filename, pm->submodel[n].name));
1495
1496                                         // mark those submodels which should not rotate - ie, those with no subsystem
1497                                         pm->submodel[n].movement_type = MOVEMENT_TYPE_NONE;
1498                                         pm->submodel[n].movement_axis = MOVEMENT_AXIS_NONE;
1499                                 }
1500
1501
1502                                 pm->submodel[n].angs.p = 0.0f;
1503                                 pm->submodel[n].angs.b = 0.0f;
1504                                 pm->submodel[n].angs.h = 0.0f;
1505
1506                                 {
1507                                         int nchunks = cfread_int( fp );         // Throw away nchunks
1508                                         if ( nchunks > 0 )      {
1509                                                 Error( LOCATION, "Model '%s' is chunked.  See John or Adam!\n", pm->filename );
1510                                         }
1511                                 }
1512                                 pm->submodel[n].bsp_data_size = cfread_int(fp);
1513                                 if ( pm->submodel[n].bsp_data_size > 0 )        {
1514                                         pm->submodel[n].bsp_data = (ubyte *)malloc(pm->submodel[n].bsp_data_size);
1515                                         cfread(pm->submodel[n].bsp_data,1,pm->submodel[n].bsp_data_size,fp);
1516                                 } else {
1517                                         pm->submodel[n].bsp_data = NULL;
1518                                 }
1519
1520                                 if ( strstr( pm->submodel[n].name, "thruster") )        
1521                                         pm->submodel[n].is_thruster=1;
1522                                 else
1523                                         pm->submodel[n].is_thruster=0;
1524
1525                                 if ( strstr( pm->submodel[n].name, "-destroyed") )      
1526                                         pm->submodel[n].is_damaged=1;
1527                                 else
1528                                         pm->submodel[n].is_damaged=0;
1529                                         
1530                                 //mprintf(( "Submodel %d, name '%s', parent = %d\n", n, pm->submodel[n].name, pm->submodel[n].parent ));
1531                                 //key_getch();
1532
1533                 //mprintf(( "Submodel %d, tree offset %d\n", n, pm->submodel[n].tree_offset ));
1534                 //mprintf(( "Submodel %d, data offset %d\n", n, pm->submodel[n].data_offset ));
1535                 //key_getch();
1536
1537
1538                                 break;
1539
1540                         }
1541
1542                         case ID_SHLD:
1543                                 {
1544                                         int nverts, ntris;                                      
1545
1546                                         nverts = cfread_int( fp );              // get the number of vertices in the list
1547                                         pm->shield.nverts = nverts;
1548                                         pm->shield.verts = (shield_vertex *)malloc(nverts * sizeof(shield_vertex) );
1549                                         Assert( pm->shield.verts );
1550                                         for ( i = 0; i < nverts; i++ )                                                  // read in the vertex list
1551                                                 cfread_vector( &(pm->shield.verts[i].pos), fp );
1552
1553                                         ntris = cfread_int( fp );               // get the number of triangles that compose the shield
1554                                         pm->shield.ntris = ntris;
1555                                         pm->shield.tris = (shield_tri *)malloc(ntris * sizeof(shield_tri) );
1556                                         Assert( pm->shield.tris );
1557                                         for ( i = 0; i < ntris; i++ ) {
1558                                                 cfread_vector( &(pm->shield.tris[i].norm), fp );
1559                                                 for ( j = 0; j < 3; j++ ) {
1560                                                         pm->shield.tris[i].verts[j] = cfread_int( fp );         // read in the indices into the shield_vertex list
1561                                                         /*
1562 #ifndef NDEBUG
1563                                                         if (pm->shield.tris[i].verts[j] >= nverts)
1564                                                                 if (!warning_displayed) {
1565                                                                         warning_displayed = 1;
1566                                                                         Warning(LOCATION, "Ship %s has a bogus shield mesh.\nOnly %i vertices, index %i found.\n", filename, nverts, pm->shield.tris[i].verts[j]);
1567                                                                 }
1568 #endif
1569                                                                 */
1570                                                 }
1571                                                 for ( j = 0; j < 3; j++ )
1572                                                         pm->shield.tris[i].neighbors[j] = cfread_int( fp );     // read in the neighbor indices -- indexes into tri list
1573                                         }
1574                                         break;
1575
1576
1577                                         
1578                                 }
1579                                 break;
1580
1581                         case ID_GPNT:
1582                                 pm->n_guns = cfread_int(fp);
1583                                 pm->gun_banks = (w_bank *)malloc(sizeof(w_bank) * pm->n_guns);
1584                                 Assert( pm->gun_banks != NULL );
1585
1586                                 for (i = 0; i < pm->n_guns; i++ ) {
1587                                         w_bank *bank = &pm->gun_banks[i];
1588
1589                                         bank->num_slots = cfread_int(fp);
1590                                         Assert ( bank->num_slots < MAX_SLOTS );
1591                                         for (j = 0; j < bank->num_slots; j++) {
1592                                                 cfread_vector( &(bank->pnt[j]), fp );
1593                                                 cfread_vector( &(bank->norm[j]), fp );
1594                                         }
1595                                 }
1596                                 break;
1597                         
1598                         case ID_MPNT:
1599                                 pm->n_missiles = cfread_int(fp);
1600                                 pm->missile_banks = (w_bank *)malloc(sizeof(w_bank) * pm->n_missiles);
1601                                 Assert( pm->missile_banks != NULL );
1602
1603                                 for (i = 0; i < pm->n_missiles; i++ ) {
1604                                         w_bank *bank = &pm->missile_banks[i];
1605
1606                                         bank->num_slots = cfread_int(fp);
1607                                         Assert ( bank->num_slots < MAX_SLOTS );
1608                                         for (j = 0; j < bank->num_slots; j++) {
1609                                                 cfread_vector( &(bank->pnt[j]), fp );
1610                                                 cfread_vector( &(bank->norm[j]), fp );
1611                                         }
1612                                 }
1613                                 break;
1614
1615                         case ID_DOCK: {
1616                                 char props[MAX_PROP_LEN];
1617
1618                                 pm->n_docks = cfread_int(fp);
1619                                 pm->docking_bays = (dock_bay *)malloc(sizeof(dock_bay) * pm->n_docks);
1620                                 Assert( pm->docking_bays != NULL );
1621
1622                                 for (i = 0; i < pm->n_docks; i++ ) {
1623                                         char *p;
1624                                         dock_bay *bay = &pm->docking_bays[i];
1625
1626                                         cfread_string_len( props, MAX_PROP_LEN, fp );
1627                                         if ( (p = strstr(props, "$name"))!= NULL )
1628                                                 get_user_prop_value(p+5, bay->name);
1629                                         else
1630                                                 sprintf(bay->name, "<unnamed bay %c>", 'A' + i);
1631                                         bay->num_spline_paths = cfread_int( fp );
1632                                         if ( bay->num_spline_paths > 0 ) {
1633                                                 bay->splines = (int *)malloc(sizeof(int) * bay->num_spline_paths);
1634                                                 for ( j = 0; j < bay->num_spline_paths; j++ )
1635                                                         bay->splines[j] = cfread_int(fp);
1636                                         } else {
1637                                                 bay->splines = NULL;
1638                                         }
1639
1640                                         // determine what this docking bay can be used for
1641                                         if ( !strnicmp(bay->name, "cargo", 5) )
1642                                                 bay->type_flags = DOCK_TYPE_CARGO;
1643                                         else
1644                                                 bay->type_flags = (DOCK_TYPE_REARM | DOCK_TYPE_GENERIC);
1645
1646                                         bay->num_slots = cfread_int(fp);
1647                                         Assert( bay->num_slots == 2 );                                  // Get Allender if Asserted!
1648                                         for (j = 0; j < bay->num_slots; j++) {
1649                                                 cfread_vector( &(bay->pnt[j]), fp );
1650                                                 cfread_vector( &(bay->norm[j]), fp );
1651                                         }
1652                                 }
1653                                 break;
1654                         }
1655
1656                         case ID_FUEL:
1657                                 char props[MAX_PROP_LEN];
1658                                 pm->n_thrusters = cfread_int(fp);
1659                                 pm->thrusters = (thruster_bank *)malloc(sizeof(thruster_bank) * pm->n_thrusters);
1660                                 Assert( pm->thrusters != NULL );
1661
1662                                 for (i = 0; i < pm->n_thrusters; i++ ) {
1663                                         thruster_bank *bank = &pm->thrusters[i];
1664
1665                                         bank->num_slots = cfread_int(fp);
1666
1667                                         if (pm->version < 2117) {
1668                                                 bank->wash_info_index = -1;
1669                                         } else {
1670                                                 cfread_string_len( props, MAX_PROP_LEN, fp );
1671                                                 // look for $engine_subsystem=xxx
1672                                                 int length = strlen(props);
1673                                                 if (length > 0) {
1674                                                         int base_length = strlen("$engine_subsystem=");
1675                                                         Assert( strstr( (const char *)&props, "$engine_subsystem=") != NULL );
1676                                                         Assert( length > base_length );
1677                                                         char *engine_subsys_name = props + base_length;
1678                                                         if (engine_subsys_name[0] == '$') {
1679                                                                 engine_subsys_name++;
1680                                                         }
1681
1682                                                         nprintf(("wash", "Ship %s with engine wash associated with subsys %s\n", filename, engine_subsys_name));
1683
1684                                                         // set wash_info_index to invalid
1685                                                         int table_error = 1;
1686                                                         bank->wash_info_index = -1;
1687                                                         for (int k=0; k<n_subsystems; k++) {
1688                                                                 if ( 0 == stricmp(subsystems[k].subobj_name, engine_subsys_name) ) {
1689                                                                         bank->wash_info_index = subsystems[k].engine_wash_index;
1690                                                                         if (bank->wash_info_index >= 0) {
1691                                                                                 table_error = 0;
1692                                                                         }
1693                                                                         break;
1694                                                                 }
1695                                                         }
1696
1697                                                         if ( (bank->wash_info_index == -1) && (n_subsystems > 0) ) {
1698                                                                 if (table_error) {
1699                                                                         Warning(LOCATION, "No engine wash table entry in ships.tbl for ship model %s", filename);
1700                                                                 } else {
1701                                                                         Warning(LOCATION, "Inconsistent model: Engine wash engine subsystem does not match any ship subsytem names for ship model %s", filename);
1702                                                                 }
1703                                                         }
1704                                                 } else {
1705                                                         bank->wash_info_index = -1;
1706                                                 }
1707                                         }
1708
1709                                         for (j = 0; j < bank->num_slots; j++) {
1710
1711                                                 cfread_vector( &(bank->pnt[j]), fp );
1712                                                 cfread_vector( &(bank->norm[j]), fp );
1713                                                 if ( pm->version > 2004 )       {
1714                                                         bank->radius[j] = cfread_float( fp );
1715                                                         //mprintf(( "Rad = %.2f\n", rad ));
1716                                                 } else {
1717                                                         bank->radius[j] = 1.0f;
1718                                                 }
1719                                         }
1720                                         //mprintf(( "Num slots = %d\n", bank->num_slots ));
1721
1722                                 }
1723                                 break;
1724
1725                         case ID_TGUN:
1726                         case ID_TMIS: {
1727                                 int n_banks, n_slots, parent;
1728                                 model_subsystem *subsystemp;
1729                                 int i, j, snum=-1;
1730         
1731                                 n_banks = cfread_int(fp);                               // number of turret points
1732                                 for ( i = 0; i < n_banks; i++ ) {
1733                                         int physical_parent;                    // who are we attached to?
1734                                         parent = cfread_int( fp );                      // get the turret parent of the object
1735
1736                                         physical_parent = cfread_int(fp);       // The parent subobj that this is physically attached to
1737
1738                                         if ( subsystems ) {
1739                                                 for ( snum = 0; snum < n_subsystems; snum++ ) {
1740                                                         subsystemp = &subsystems[snum];
1741
1742                                                         if ( parent == subsystemp->subobj_num ) {
1743                                                                 cfread_vector( &subsystemp->turret_norm, fp );
1744                                                                 vm_vector_2_matrix(&subsystemp->turret_matrix,&subsystemp->turret_norm,NULL,NULL);
1745
1746                                                                 n_slots = cfread_int( fp );
1747                                                                 subsystemp->turret_gun_sobj = physical_parent;
1748                                                                 Assert(n_slots < MAX_TFP);              // only MAX_TFP firing points per model_subsystem
1749                                                                 for (j = 0; j < n_slots; j++ )  {
1750                                                                         cfread_vector( &subsystemp->turret_firing_point[j], fp );
1751                                                                 }
1752                                                                 Assert( n_slots > 0 );
1753
1754                                                                 subsystemp->turret_num_firing_points = n_slots;
1755
1756                                                                 break;
1757                                                         }
1758                                                 }
1759                                         }
1760
1761 //turret_gun_sobj
1762
1763                                         if ( (n_subsystems == 0) || (snum == n_subsystems) ) {
1764                                                 vector bogus;
1765
1766                                                 nprintf(("Warning", "Turret object not found for turret firing point in model %s\n", model_filename));
1767                                                 cfread_vector( &bogus, fp );
1768                                                 n_slots = cfread_int( fp );
1769                                                 for (j = 0; j < n_slots; j++ )
1770                                                         cfread_vector( &bogus, fp );
1771                                         }
1772                                 }
1773                                 break;
1774                         }
1775
1776                         case ID_SPCL: {
1777                                 char name[MAX_NAME_LEN], props[MAX_PROP_LEN], *p;
1778                                 int n_specials;
1779                                 float radius;
1780                                 vector pnt;
1781
1782                                 n_specials = cfread_int(fp);            // get the number of special subobjects we have
1783                                 for (i = 0; i < n_specials; i++) {
1784
1785                                         // get the next free object of the subobject list.  Flag error if no more room
1786
1787                                         cfread_string_len(name, MAX_NAME_LEN, fp);                      // get the name of this special polygon
1788
1789                                         cfread_string_len(props, MAX_PROP_LEN, fp);             // will definately have properties as well!
1790                                         cfread_vector( &pnt, fp );
1791                                         radius = cfread_float( fp );
1792
1793                                         // check if $Split
1794                                         p = strstr(name, "$split");
1795                                         if (p != NULL) {
1796                                                 pm->split_plane[pm->num_split_plane] = pnt.xyz.z;
1797                                                 pm->num_split_plane++;
1798                                                 Assert(pm->num_split_plane <= MAX_SPLIT_PLANE);
1799                                         } else if ( ( p = strstr(props, "$special"))!= NULL ) {
1800                                                 char type[32];
1801
1802                                                 get_user_prop_value(p+9, type);
1803                                                 if ( !stricmp(type, "subsystem") )                                              // if we have a subsystem, put it into the list!
1804                                                         do_new_subsystem( n_subsystems, subsystems, -1, radius, &pnt, props, &name[1], pm->id );                // skip the first '$' character of the name
1805                                         } else if ( strstr(name, "$enginelarge") || strstr(name, "$enginehuge") ){
1806                                                 do_new_subsystem( n_subsystems, subsystems, -1, radius, &pnt, props, &name[1], pm->id );                // skip the first '$' character of the name
1807                                         } else {
1808                                                 nprintf(("Warning", "Unknown special object type %s while reading model %s\n", name, pm->filename));
1809                                         }                                       
1810                                 }
1811                                 break;
1812                         }
1813                         
1814                         case ID_TXTR: {         //Texture filename list
1815                                 int i,n;
1816 //                              char name_buf[128];
1817
1818                                 //mprintf(0,"Got chunk TXTR, len=%d\n",len);
1819
1820                                 n = cfread_int(fp);
1821                                 pm->n_textures = n;
1822                                 // Dont overwrite memory!!
1823                                 Assert(n <= MAX_MODEL_TEXTURES);
1824                                 //mprintf(0,"  num textures = %d\n",n);
1825                                 for (i=0; i<n; i++ )    {
1826                                         char tmp_name[256];
1827                                         cfread_string_len(tmp_name,127,fp);
1828
1829                                         if ( strstr(tmp_name, "thruster") || strstr(tmp_name, "invisible") )    {
1830                                                 // Don't load textures for thruster animations or invisible textures
1831                                                 pm->textures[i] = -1;
1832                                         } else {
1833                                                 pm->textures[i] = bm_load( tmp_name );
1834                                                 if (pm->textures[i]<0)  {
1835                                                         Error( LOCATION, "Couldn't open texture '%s'\nreferenced by model '%s'\n", tmp_name, pm->filename );
1836                                                 }
1837                                         }
1838                                         pm->original_textures[i] = pm->textures[i];
1839                                         //mprintf(0,"<%s>\n",name_buf);
1840                                 }
1841
1842                                 break;
1843                         }
1844                         
1845 /*                      case ID_IDTA:           //Interpreter data
1846                                 //mprintf(0,"Got chunk IDTA, len=%d\n",len);
1847
1848                                 pm->model_data = (ubyte *)malloc(len);
1849                                 pm->model_data_size = len;
1850                                 Assert(pm->model_data != NULL );
1851                         
1852                                 cfread(pm->model_data,1,len,fp);
1853                         
1854                                 break;
1855 */
1856
1857                         case ID_INFO:           // don't need to do anything with info stuff
1858
1859                                 #ifndef NDEBUG
1860                                         pm->debug_info_size = len;
1861                                         pm->debug_info = (char *)malloc(pm->debug_info_size+1);
1862                                         Assert(pm->debug_info!=NULL);
1863                                         memset(pm->debug_info,0,len+1);
1864                                         cfread( pm->debug_info, 1, len, fp );
1865                                 #endif
1866                                 break;
1867
1868                         case ID_GRID:
1869                                 break;
1870
1871                         case ID_PATH:
1872                                 pm->n_paths = cfread_int( fp );
1873                                 pm->paths = (model_path *)malloc(sizeof(model_path)*pm->n_paths);
1874                                 Assert( pm->paths != NULL );
1875                                         
1876                                 for (i=0; i<pm->n_paths; i++ )  {
1877                                         cfread_string_len(pm->paths[i].name , MAX_NAME_LEN-1, fp);
1878                                         if ( pm->version >= 2002 ) {
1879                                                 // store the sub_model name number of the parent
1880                                                 cfread_string_len(pm->paths[i].parent_name , MAX_NAME_LEN-1, fp);
1881                                                 // get rid of leading '$' char in name
1882                                                 if ( pm->paths[i].parent_name[0] == '$' ) {
1883                                                         char tmpbuf[MAX_NAME_LEN];
1884                                                         strcpy(tmpbuf, pm->paths[i].parent_name+1);
1885                                                         strcpy(pm->paths[i].parent_name, tmpbuf);
1886                                                 }
1887                                                 // store the sub_model index (ie index into pm->submodel) of the parent
1888                                                 pm->paths[i].parent_submodel = -1;
1889                                                 for ( j = 0; j < pm->n_models; j++ ) {
1890                                                         if ( !stricmp( pm->submodel[j].name, pm->paths[i].parent_name) ) {
1891                                                                 pm->paths[i].parent_submodel = j;
1892                                                         }
1893                                                 }
1894                                         } else {
1895                                                 pm->paths[i].parent_name[0] = 0;
1896                                                 pm->paths[i].parent_submodel = -1;
1897                                         }
1898                                         pm->paths[i].nverts = cfread_int( fp );
1899                                         pm->paths[i].verts = (mp_vert *)malloc( sizeof(mp_vert) * pm->paths[i].nverts );
1900                                         pm->paths[i].goal = pm->paths[i].nverts - 1;
1901                                         pm->paths[i].type = MP_TYPE_UNUSED;
1902                                         pm->paths[i].value = 0;
1903                                         Assert(pm->paths[i].verts!=NULL);
1904                                         for (j=0; j<pm->paths[i].nverts; j++ )  {
1905                                                 cfread_vector(&pm->paths[i].verts[j].pos,fp );
1906                                                 pm->paths[i].verts[j].radius = cfread_float( fp );
1907                                                 
1908                                                 {                                       // version 1802 added turret stuff
1909                                                         int nturrets, k;
1910
1911                                                         nturrets = cfread_int( fp );
1912                                                         pm->paths[i].verts[j].nturrets = nturrets;
1913                                                         pm->paths[i].verts[j].turret_ids = (int *)malloc( sizeof(int) * nturrets );
1914                                                         for ( k = 0; k < nturrets; k++ )
1915                                                                 pm->paths[i].verts[j].turret_ids[k] = cfread_int( fp );
1916                                                 } 
1917                                                 
1918                                         }
1919                                 }
1920                                 break;
1921
1922                         case ID_EYE:                                    // an eye position(s)
1923                                 {
1924                                         int num_eyes, i;
1925
1926                                         // all eyes points are stored simply as vectors and their normals.
1927                                         // 0th element is used as usual player view position.
1928
1929                                         num_eyes = cfread_int( fp );
1930                                         pm->n_view_positions = num_eyes;
1931                                         Assert ( num_eyes < MAX_EYES );
1932                                         for (i = 0; i < num_eyes; i++ ) {
1933                                                 pm->view_positions[i].parent = cfread_int( fp );
1934                                                 cfread_vector( &pm->view_positions[i].pnt, fp );
1935                                                 cfread_vector( &pm->view_positions[i].norm, fp );
1936                                         }
1937                                 }
1938                                 break;                  
1939
1940                         case ID_INSG:                           
1941                                 int num_ins, num_verts, num_faces, idx, idx2, idx3;                     
1942                                 
1943                                 // get the # of insignias
1944                                 num_ins = cfread_int(fp);
1945                                 pm->num_ins = num_ins;
1946                                 
1947                                 // read in the insignias
1948                                 for(idx=0; idx<num_ins; idx++){
1949                                         // get the detail level
1950                                         pm->ins[idx].detail_level = cfread_int(fp);
1951
1952                                         // # of faces
1953                                         num_faces = cfread_int(fp);
1954                                         pm->ins[idx].num_faces = num_faces;
1955                                         Assert(num_faces <= MAX_INS_FACES);
1956
1957                                         // # of vertices
1958                                         num_verts = cfread_int(fp);
1959                                         Assert(num_verts <= MAX_INS_VECS);
1960
1961                                         // read in all the vertices
1962                                         for(idx2=0; idx2<num_verts; idx2++){
1963                                                 cfread_vector(&pm->ins[idx].vecs[idx2], fp);
1964                                         }
1965
1966                                         // read in world offset
1967                                         cfread_vector(&pm->ins[idx].offset, fp);
1968
1969                                         // read in all the faces
1970                                         for(idx2=0; idx2<pm->ins[idx].num_faces; idx2++){                                               
1971                                                 // read in 3 vertices
1972                                                 for(idx3=0; idx3<3; idx3++){
1973                                                         pm->ins[idx].faces[idx2][idx3] = cfread_int(fp);
1974                                                         pm->ins[idx].u[idx2][idx3] = cfread_float(fp);
1975                                                         pm->ins[idx].v[idx2][idx3] = cfread_float(fp);
1976                                                 }
1977                                         }
1978                                 }                                       
1979                                 break;
1980
1981                         // autocentering info
1982                         case ID_ACEN:
1983                                 cfread_vector(&pm->autocenter, fp);
1984                                 pm->flags |= PM_FLAG_AUTOCEN;
1985                                 break;
1986
1987                         default:
1988                                 mprintf(("Unknown chunk <%c%c%c%c>, len = %d\n",id,id>>8,id>>16,id>>24,len));
1989                                 cfseek(fp,len,SEEK_CUR);
1990                                 break;
1991
1992                 }
1993                 cfseek(fp,next_chunk,SEEK_SET);
1994
1995                 id = cfread_int(fp);
1996                 len = cfread_int(fp);
1997                 next_chunk = cftell(fp) + len;
1998
1999         }
2000
2001 #ifndef NDEBUG
2002         if ( ss_fp) {
2003                 int size;
2004                 
2005                 cfclose(ss_fp);
2006                 ss_fp = cfopen(debug_name, "rb");
2007                 if ( ss_fp )    {
2008                         size = cfilelength(ss_fp);
2009                         cfclose(ss_fp);
2010                         if ( size <= 0 )        {
2011                                 _unlink(debug_name);
2012                         }
2013                 }
2014         }
2015 #endif
2016
2017         cfclose(fp);
2018         // mprintf(("Done processing chunks\n"));
2019         return 1;
2020 }
2021
2022
2023
2024 //returns the number of this model
2025 int model_load(char *filename, int n_subsystems, model_subsystem *subsystems)
2026 {
2027         int i, num, arc_idx;
2028
2029         if ( !model_initted )
2030                 model_init();
2031
2032 //      int Model_ram = 0;
2033
2034 #ifndef NDEBUG
2035         int ram_before = TotalRam;
2036 #endif
2037
2038         //Assert(strlen(filename) <= 12);
2039
2040         num = -1;
2041
2042         for (i=0; i< MAX_POLYGON_MODELS; i++)   {
2043                 if ( Polygon_models[i] )        {
2044                         if (!stricmp(filename, Polygon_models[i]->filename))            {
2045                                 // Model already loaded; just return.
2046                                 return Polygon_models[i]->id;
2047                         }
2048                 } else if ( num == -1 ) {
2049                         // This is the first empty slot
2050                         num = i;
2051                 }
2052         }
2053
2054         // No empty slot
2055         if ( num == -1 )        {
2056                 Error( LOCATION, "Too many models" );
2057                 return -1;
2058         }       
2059
2060         mprintf(( "Loading model '%s'\n", filename ));
2061
2062         polymodel * pm = (polymodel *)malloc( sizeof(polymodel) );
2063         
2064         Polygon_models[num] = pm;
2065         
2066         memset(pm, 0, sizeof(polymodel));
2067
2068         pm->n_paths = 0;
2069         pm->paths = NULL;
2070
2071         int org_sig = Model_signature;
2072         Model_signature+=MAX_POLYGON_MODELS;
2073         if ( Model_signature < org_sig )        {
2074                 Model_signature = 0;
2075         }
2076         Assert( (Model_signature % MAX_POLYGON_MODELS) == 0 );
2077         pm->id = Model_signature + num;
2078
2079         if (!read_model_file(pm, filename, n_subsystems, subsystems))   {
2080                 return -1;
2081         }
2082
2083 //mprintf(( "Loading model '%s'\n", filename ));
2084 //key_getch();
2085
2086 //=============================
2087 // Find the destroyed replacement models
2088
2089         // Set up the default values
2090         for (i=0; i<pm->n_models; i++ ) {
2091                 pm->submodel[i].my_replacement = -1;    // assume nothing replaces this
2092                 pm->submodel[i].i_replace = -1;         // assume this doesn't replaces anything
2093         }
2094
2095         // Search for models that have destroyed versions
2096         for (i=0; i<pm->n_models; i++ ) {
2097                 int j;
2098                 char destroyed_name[128];
2099
2100                 strcpy( destroyed_name, pm->submodel[i].name );
2101                 strcat( destroyed_name, "-destroyed" );
2102                 for (j=0; j<pm->n_models; j++ ) {
2103                         if ( !stricmp( pm->submodel[j].name, destroyed_name ))  {
2104                                 // mprintf(( "Found destroyed model for '%s'\n", pm->submodel[i].name ));
2105                                 pm->submodel[i].my_replacement = j;
2106                                 pm->submodel[j].i_replace = i;
2107                         }
2108                 }
2109
2110                 // Search for models with live debris
2111                 // This debris comes from a destroyed subsystem when ship is still alive
2112                 char live_debris_name[128];
2113
2114                 strcpy( live_debris_name, "debris-" );
2115                 strcat( live_debris_name, pm->submodel[i].name );
2116
2117
2118                 pm->submodel[i].num_live_debris = 0;
2119                 for (j=0; j<pm->n_models; j++ ) {
2120                         // check if current model name is substring of destroyed
2121                         if ( strstr( pm->submodel[j].name, live_debris_name ))  {
2122                                 mprintf(( "Found live debris model for '%s'\n", pm->submodel[i].name ));
2123                                 Assert(pm->submodel[i].num_live_debris < MAX_LIVE_DEBRIS);
2124                                 pm->submodel[i].live_debris[pm->submodel[i].num_live_debris++] = j;
2125                                 pm->submodel[j].is_live_debris = 1;
2126                         }
2127                 }
2128
2129         }
2130
2131         create_family_tree(pm);
2132 //      dump_object_tree(pm);
2133
2134 //==============================
2135 // Find all the lower detail versions of the hires model
2136         for (i=0; i<pm->n_models; i++ ) {
2137                 int j, l1;
2138                 bsp_info * sm1 = &pm->submodel[i];
2139
2140                 // set all arc types to be default              
2141                 for(arc_idx=0; arc_idx < MAX_ARC_EFFECTS; arc_idx++){
2142                         sm1->arc_type[arc_idx] = MARC_TYPE_NORMAL;
2143                 }
2144
2145                 sm1->num_details = 0;
2146                 l1 = strlen(sm1->name);
2147
2148                 for (j=0; j<pm->num_debris_objects;j++ )        {
2149                         if ( i == pm->debris_objects[j] )       {
2150                                 sm1->is_damaged = 1;
2151                         } 
2152                 }
2153
2154
2155                 for (j=0; j<MAX_MODEL_DETAIL_LEVELS; j++ )      {
2156                         sm1->details[j] = -1;
2157                 }
2158
2159                 for (j=0; j<pm->n_models; j++ ) {
2160                         int k;
2161                         bsp_info * sm2 = &pm->submodel[j];
2162
2163                         if ( i==j ) continue;
2164                         
2165                         // set all arc types to be default              
2166                         for(arc_idx=0; arc_idx < MAX_ARC_EFFECTS; arc_idx++){
2167                                 sm2->arc_type[arc_idx] = MARC_TYPE_NORMAL;
2168                         }
2169
2170                         // if sm2 is a detail of sm1 and sm1 is a high detail, then add it to sm1's list
2171                         if ((int)strlen(sm2->name)!=l1) continue;
2172         
2173                         int ndiff = 0;
2174                         int first_diff = 0;
2175                         for ( k=0; k<l1; k++)   {
2176                                 if (sm1->name[k] != sm2->name[k] )      {
2177                                         if (ndiff==0) first_diff = k;
2178                                         ndiff++;
2179                                 }
2180                         }
2181                         if (ndiff==1)   {               // They only differ by one character!
2182                                 int dl1, dl2;
2183                                 dl1 = tolower(sm1->name[first_diff]) - 'a';
2184                                 dl2 = tolower(sm2->name[first_diff]) - 'a';
2185
2186                                 if ( (dl1<0) || (dl2<0) || (dl1>=MAX_MODEL_DETAIL_LEVELS) || (dl2>=MAX_MODEL_DETAIL_LEVELS) ) continue; // invalid detail levels
2187
2188                                 if ( dl1 == 0 ) {
2189                                         dl2--;  // Start from 1 up...
2190                                         if (dl2 >= sm1->num_details ) sm1->num_details = dl2+1;
2191                                         sm1->details[dl2] = j;
2192                                         //mprintf(( "Submodel '%s' is detail level %d of '%s'\n", sm2->name, dl2, sm1->name ));
2193                                 }
2194                         }
2195                 }
2196
2197                 for (j=0; j<sm1->num_details; j++ )     {
2198                         if ( sm1->details[j] == -1 )    {
2199                                 Warning( LOCATION, "Model '%s' could find all detail levels for submodel '%s'", pm->filename, sm1->name );
2200                                 sm1->num_details = 0;
2201                         }
2202                 }
2203
2204         }
2205
2206
2207         model_octant_create( pm );
2208
2209         // Find the core_radius... the minimum of 
2210         float rx, ry, rz;
2211         rx = fl_abs( pm->submodel[pm->detail[0]].max.xyz.x - pm->submodel[pm->detail[0]].min.xyz.x );
2212         ry = fl_abs( pm->submodel[pm->detail[0]].max.xyz.y - pm->submodel[pm->detail[0]].min.xyz.y );
2213         rz = fl_abs( pm->submodel[pm->detail[0]].max.xyz.z - pm->submodel[pm->detail[0]].min.xyz.z );
2214
2215         pm->core_radius = min( rx, min(ry, rz) ) / 2.0f;
2216
2217         for (i=0; i<pm->n_view_positions; i++ ) {
2218                 if ( pm->view_positions[i].parent == pm->detail[0] )    {
2219                         float d = vm_vec_mag( &pm->view_positions[i].pnt );
2220
2221                         d += 0.1f;              // Make the eye 1/10th of a meter inside the sphere.
2222
2223                         if ( d > pm->core_radius )      {
2224                                 //mprintf(( "Model %s core radius increased from %.1f to %.1f to fit eye\n", pm->filename, pm->core_radius, d ));
2225                                 pm->core_radius = d;
2226                         }               
2227                 }
2228         }
2229
2230 #ifndef NDEBUG
2231         int ram_after = TotalRam;
2232
2233         pm->ram_used = ram_after - ram_before;
2234         Model_ram += pm->ram_used;
2235         //mprintf(( "Model RAM = %d KB\n", Model_ram ));
2236 #endif
2237
2238         return pm->id;
2239 }
2240
2241 // Get "parent" submodel for live debris submodel
2242 int model_get_parent_submodel_for_live_debris( int model_num, int live_debris_model_num )
2243 {
2244         polymodel *pm = model_get(model_num);
2245
2246         Assert(pm->submodel[live_debris_model_num].is_live_debris == 1);
2247
2248         int mn;
2249         bsp_info *child;
2250
2251         // Start with the high level of detail hull 
2252         // Check all its children until we find the submodel to which the live debris belongs
2253         child = &pm->submodel[pm->detail[0]];
2254         mn = child->first_child;
2255
2256         while (mn > 0) {
2257                 child = &pm->submodel[mn];
2258
2259                 if (child->num_live_debris > 0) {
2260                         // check all live debris submodels for the current child
2261                         for (int idx=0; idx<child->num_live_debris; idx++) {
2262                                 if (child->live_debris[idx] == live_debris_model_num) {
2263                                         return mn;
2264                                 }
2265                         }
2266                         // DKA 5/26/99: can multiple live debris subsystems with each ship
2267                         // NO LONGER TRUE Can only be 1 submodel with live debris
2268                         // Error( LOCATION, "Could not find parent submodel for live debris.  Possible model error");
2269                 }
2270
2271                 // get next child
2272                 mn = child->next_sibling;
2273         }
2274         Error( LOCATION, "Could not find parent submodel for live debris");
2275         return -1;
2276 }
2277
2278
2279 float model_get_radius( int modelnum )
2280 {
2281         polymodel *pm;
2282
2283         pm = model_get(modelnum);
2284
2285         return pm->rad;
2286 }
2287
2288 float model_get_core_radius( int modelnum )
2289 {
2290         polymodel *pm;
2291
2292         pm = model_get(modelnum);
2293
2294         return pm->core_radius;
2295 }
2296
2297 float submodel_get_radius( int modelnum, int submodelnum )
2298 {
2299         polymodel *pm;
2300
2301         pm = model_get(modelnum);
2302
2303         return pm->submodel[submodelnum].rad;
2304 }
2305
2306
2307
2308 polymodel * model_get(int model_num)
2309 {
2310         Assert( model_num > -1 );
2311
2312         int num = model_num % MAX_POLYGON_MODELS;
2313         
2314         Assert( num > -1 );
2315         Assert( num < MAX_POLYGON_MODELS );
2316         Assert( Polygon_models[num]->id == model_num );
2317
2318         return Polygon_models[num];
2319 }
2320
2321
2322 /*
2323 // Finds the 3d bounding box of a model.  If submodel_num is -1,
2324 // then it starts from the root object.   If inc_children is non-zero, 
2325 // then this will recurse and find the bounding box for all children
2326 // also.
2327 void model_find_bound_box_3d(int model_num,int submodel_num, int inc_children, matrix *orient, vector * pos, vector * box )
2328 {
2329         polymodel * pm;
2330         vector to_root_xlat;
2331         matrix to_root_rotate;
2332         int n_steps, steps[16];
2333         int tmp_sobj;
2334         
2335         if ( (model_num < 0) || (model_num >= N_polygon_models) ) return;
2336
2337         pm = &Polygon_models[model_num];
2338
2339         if ( submodel_num < 0 ) submodel_num = pm->detail[0];
2340
2341         // traverse up the model tree to a root object.
2342         // Store this path in n_steps,
2343         n_steps = 0;
2344         tmp_sobj = submodel_num;
2345         while( tmp_sobj > -1 )  {
2346                 steps[n_steps++] = tmp_sobj;
2347                 tmp_sobj = pm->submodel[tmp_sobj].parent;
2348         }
2349         
2350         
2351
2352 //      vm_copy_transpose_matrix(&to_world_rotate, orient );
2353 //      to_world_xlat = *pos;
2354
2355 }
2356 */
2357
2358
2359
2360 // Returns zero is x1,y1,x2,y2 are valid
2361 // returns 1 for invalid model, 2 for point offscreen.
2362 // note that x1,y1,x2,y2 aren't clipped to 2d screen coordinates!
2363 int model_find_2d_bound_min(int model_num,matrix *orient, vector * pos,int *x1, int *y1, int *x2, int *y2 )
2364 {
2365         polymodel * po;
2366         int n_valid_pts;
2367         int i, x,y,min_x, min_y, max_x, max_y;
2368         int rval = 0;
2369
2370         po = model_get(model_num);
2371
2372         g3_start_instance_matrix(pos,orient);
2373         
2374         n_valid_pts = 0;
2375
2376         int hull = po->detail[0];
2377
2378         min_x = min_y = max_x = max_y = 0;
2379
2380         for (i=0; i<8; i++ )    {
2381                 vertex pt;
2382                 ubyte flags;
2383
2384                 flags = g3_rotate_vertex(&pt,&po->submodel[hull].bounding_box[i]);
2385                 if ( !(flags&CC_BEHIND) ) {
2386                         g3_project_vertex(&pt);
2387
2388                         if (!(pt.flags & PF_OVERFLOW)) {
2389                                 x = fl2i(pt.sx);
2390                                 y = fl2i(pt.sy);
2391                                 if ( n_valid_pts == 0 ) {
2392                                         min_x = x;
2393                                         min_y = y;
2394                                         max_x = x;
2395                                         max_y = y;
2396                                 } else {
2397                                         if ( x < min_x ) min_x = x;
2398                                         if ( y < min_y ) min_y = y;
2399
2400                                         if ( x > max_x ) max_x = x;
2401                                         if ( y > max_y ) max_y = y;
2402                                 }
2403                                 n_valid_pts++;
2404                         }
2405                 }
2406         }
2407
2408         if ( n_valid_pts < 8 )  {
2409                 rval = 2;
2410         }
2411
2412         if (x1) *x1 = min_x;
2413         if (y1) *y1 = min_y;
2414
2415         if (x2) *x2 = max_x;
2416         if (y2) *y2 = max_y;
2417
2418         g3_done_instance();
2419
2420         return rval;
2421 }
2422
2423
2424 // Returns zero is x1,y1,x2,y2 are valid
2425 // returns 1 for invalid model, 2 for point offscreen.
2426 // note that x1,y1,x2,y2 aren't clipped to 2d screen coordinates!
2427 int submodel_find_2d_bound_min(int model_num,int submodel, matrix *orient, vector * pos,int *x1, int *y1, int *x2, int *y2 )
2428 {
2429         polymodel * po;
2430         int n_valid_pts;
2431         int i, x,y,min_x, min_y, max_x, max_y;
2432         bsp_info * sm;
2433
2434         po = model_get(model_num);
2435         if ( (submodel < 0) || (submodel >= po->n_models ) ) return 1;
2436         sm = &po->submodel[submodel];
2437         
2438         g3_start_instance_matrix(pos,orient);
2439         
2440         n_valid_pts = 0;
2441
2442         min_x = min_y = max_x = max_y = 0;
2443
2444         for (i=0; i<8; i++ )    {
2445                 vertex pt;
2446                 ubyte flags;
2447
2448                 flags = g3_rotate_vertex(&pt,&sm->bounding_box[i]);
2449                 if ( !(flags&CC_BEHIND) ) {
2450                         g3_project_vertex(&pt);
2451
2452                         if (!(pt.flags & PF_OVERFLOW)) {
2453                                 x = fl2i(pt.sx);
2454                                 y = fl2i(pt.sy);
2455                                 if ( n_valid_pts == 0 ) {
2456                                         min_x = x;
2457                                         min_y = y;
2458                                         max_x = x;
2459                                         max_y = y;
2460                                 } else {
2461                                         if ( x < min_x ) min_x = x;
2462                                         if ( y < min_y ) min_y = y;
2463
2464                                         if ( x > max_x ) max_x = x;
2465                                         if ( y > max_y ) max_y = y;
2466                                 }
2467                                 n_valid_pts++;
2468                         }
2469                 }
2470         }
2471
2472         if ( n_valid_pts == 0 ) {
2473                 return 2;
2474         }
2475
2476         if (x1) *x1 = min_x;
2477         if (y1) *y1 = min_y;
2478
2479         if (x2) *x2 = max_x;
2480         if (y2) *y2 = max_y;
2481
2482         g3_done_instance();
2483
2484         return 0;
2485 }
2486
2487
2488 // Returns zero is x1,y1,x2,y2 are valid
2489 // returns 1 for invalid model, 2 for point offscreen.
2490 // note that x1,y1,x2,y2 aren't clipped to 2d screen coordinates!
2491 int model_find_2d_bound(int model_num,matrix *orient, vector * pos,int *x1, int *y1, int *x2, int *y2 )
2492 {
2493         float t,w,h;
2494         vertex pnt;
2495         ubyte flags;
2496         polymodel * po;
2497
2498         po = model_get(model_num);
2499         float width = po->rad;
2500         float height = po->rad;
2501
2502         flags = g3_rotate_vertex(&pnt,pos);
2503
2504         if ( pnt.flags & CC_BEHIND ) 
2505                 return 2;
2506
2507         if (!(pnt.flags&PF_PROJECTED))
2508                 g3_project_vertex(&pnt);
2509
2510         if (pnt.flags & PF_OVERFLOW)
2511                 return 2;
2512
2513         t = (width * Canv_w2)/pnt.z;
2514         w = t*Matrix_scale.xyz.x;
2515
2516         t = (height*Canv_h2)/pnt.z;
2517         h = t*Matrix_scale.xyz.y;
2518
2519         if (x1) *x1 = fl2i(pnt.sx - w);
2520         if (y1) *y1 = fl2i(pnt.sy - h);
2521
2522         if (x2) *x2 = fl2i(pnt.sx + w);
2523         if (y2) *y2 = fl2i(pnt.sy + h);
2524
2525         return 0;
2526 }
2527
2528 // Returns zero is x1,y1,x2,y2 are valid
2529 // returns 2 for point offscreen.
2530 // note that x1,y1,x2,y2 aren't clipped to 2d screen coordinates!
2531 int subobj_find_2d_bound(float radius ,matrix *orient, vector * pos,int *x1, int *y1, int *x2, int *y2 )
2532 {
2533         float t,w,h;
2534         vertex pnt;
2535         ubyte flags;
2536
2537         float width = radius;
2538         float height = radius;
2539
2540         flags = g3_rotate_vertex(&pnt,pos);
2541
2542         if ( pnt.flags & CC_BEHIND ) 
2543                 return 2;
2544
2545         if (!(pnt.flags&PF_PROJECTED))
2546                 g3_project_vertex(&pnt);
2547
2548         if (pnt.flags & PF_OVERFLOW)
2549                 return 2;
2550
2551         t = (width * Canv_w2)/pnt.z;
2552         w = t*Matrix_scale.xyz.x;
2553
2554         t = (height*Canv_h2)/pnt.z;
2555         h = t*Matrix_scale.xyz.y;
2556
2557         if (x1) *x1 = fl2i(pnt.sx - w);
2558         if (y1) *y1 = fl2i(pnt.sy - h);
2559
2560         if (x2) *x2 = fl2i(pnt.sx + w);
2561         if (y2) *y2 = fl2i(pnt.sy + h);
2562
2563         return 0;
2564 }
2565
2566
2567 // Given a vector that is in sub_model_num's frame of
2568 // reference, and given the object's orient and position,
2569 // return the vector in the model's frame of reference.
2570 void model_find_obj_dir(vector *w_vec, vector *m_vec, object *ship_obj, int sub_model_num)
2571 {
2572         vector tvec, vec;
2573         matrix m;
2574         int mn;
2575
2576         Assert(ship_obj->type == OBJ_SHIP);
2577
2578         polymodel *pm = model_get(Ships[ship_obj->instance].modelnum);
2579         vec = *m_vec;
2580         mn = sub_model_num;
2581
2582         // instance up the tree for this point
2583         while ((mn>-1) && (pm->submodel[mn].parent > -1)) {
2584                 
2585                 vm_angles_2_matrix(&m, &pm->submodel[mn].angs);
2586                 vm_vec_unrotate(&tvec, &vec, &m);
2587                 vec = tvec;
2588
2589                 mn = pm->submodel[mn].parent;
2590         }
2591
2592         // now instance for the entire object
2593         vm_vec_unrotate(w_vec, &vec, &ship_obj->orient);
2594 }
2595
2596
2597 // Given a point (pnt) that is in sub_model_num's frame of
2598 // reference, return the point in in the object's frame of reference
2599 void model_rot_sub_into_obj(vector * outpnt, vector *mpnt,polymodel *pm, int sub_model_num)
2600 {
2601         vector pnt;
2602         vector tpnt;
2603         matrix m;
2604         int mn;
2605
2606         pnt = *mpnt;
2607         mn = sub_model_num;
2608
2609         //instance up the tree for this point
2610         while ((mn>-1) && (pm->submodel[mn].parent > -1) ) {
2611                 
2612                 vm_angles_2_matrix(&m,&pm->submodel[mn].angs );
2613                 vm_transpose_matrix(&m);
2614                 vm_vec_rotate(&tpnt,&pnt,&m);
2615
2616                 vm_vec_add(&pnt,&tpnt,&pm->submodel[mn].offset );
2617
2618                 mn = pm->submodel[mn].parent;
2619         }
2620
2621         //now instance for the entire object
2622         *outpnt = pnt;
2623 }
2624
2625
2626 // Given a rotating submodel, find the ship and world axes or rotatation.
2627 void model_get_rotating_submodel_axis(vector *model_axis, vector *world_axis, int modelnum, int submodel_num, object *obj)
2628 {
2629         polymodel *pm = model_get(modelnum);
2630
2631         bsp_info *sm = &pm->submodel[submodel_num];
2632         Assert(sm->movement_type == MOVEMENT_TYPE_ROT);
2633
2634         if (sm->movement_axis == MOVEMENT_AXIS_X) {
2635                 vm_vec_make(model_axis, 1.0f, 0.0f, 0.0f);
2636         } else if (sm->movement_axis == MOVEMENT_AXIS_Y) {
2637                 vm_vec_make(model_axis, 0.0f, 1.0f, 0.0f);
2638         } else {
2639                 Assert(sm->movement_axis == MOVEMENT_AXIS_Z);
2640                 vm_vec_make(model_axis, 0.0f, 0.0f, 1.0f);
2641         }
2642
2643         model_find_obj_dir(world_axis, model_axis, obj, submodel_num);
2644 }
2645
2646
2647 // Does stepped rotation of a submodel
2648 #ifndef PLAT_UNIX
2649 #pragma warning ( push )
2650 #pragma warning (disable : 4701)
2651 #endif
2652 void submodel_stepped_rotate(model_subsystem *psub, submodel_instance_info *sii)
2653 {
2654         Assert(psub->flags & MSS_FLAG_STEPPED_ROTATE);
2655
2656         if ( psub->subobj_num < 0 ) return;
2657
2658         polymodel *pm = model_get(psub->model_num);
2659         bsp_info *sm = &pm->submodel[psub->subobj_num];
2660
2661         if ( sm->movement_type != MOVEMENT_TYPE_ROT ) return;
2662
2663         // get active rotation time this frame
2664         int end_stamp = timestamp();
2665         float rotation_time = 0.001f * (end_stamp - sii->step_zero_timestamp);
2666         Assert(rotation_time >= 0);
2667
2668         // save last angles
2669         sii->prev_angs = sii->angs;
2670
2671         // float pointer into struct to get angle (either p,b,h)
2672         float *ang_prev, *ang_next;
2673         switch( sm->movement_axis ) {
2674         case MOVEMENT_AXIS_X:
2675                 ang_prev = &sii->prev_angs.p;
2676                 ang_next = &sii->angs.p;
2677                 break;
2678
2679         case MOVEMENT_AXIS_Y:   
2680                 ang_prev = &sii->prev_angs.h;
2681                 ang_next = &sii->angs.h;
2682                 break;
2683
2684         case MOVEMENT_AXIS_Z:   
2685                 ang_prev = &sii->prev_angs.b;
2686                 ang_next = &sii->angs.b;
2687                 break;
2688         }
2689         
2690         // angular displacement of one step
2691         float step_size = (PI2 / psub->stepped_rotation->num_steps);
2692
2693         // get time to complete one step, including pause
2694         float step_time = psub->stepped_rotation->t_transit + psub->stepped_rotation->t_pause;
2695
2696         // cur_step is step number relative to zero (0 - num_steps)
2697         // step_offset_time is TIME into current step
2698         float step_offset_time = (float)fmod(rotation_time, step_time);
2699         // subtract off fractional step part, round up  (ie, 1.999999 -> 2)
2700         int cur_step = int( ((rotation_time - step_offset_time) / step_time) + 0.5f);
2701         // mprintf(("cur step %d\n", cur_step));
2702         // Assert(step_offset_time >= 0);
2703
2704         if (cur_step >= psub->stepped_rotation->num_steps) {
2705                 // I don;t know why, but removing this line makes it all good.
2706                 // sii->step_zero_timestamp += int(1000.0f * (psub->stepped_rotation->num_steps * step_time) + 0.5f);
2707
2708                 // reset cur_step (use mod to handle physics/ai pause)
2709                 cur_step = cur_step % psub->stepped_rotation->num_steps;
2710         }
2711
2712         // get base angle
2713         *ang_next = cur_step * step_size;
2714
2715         // determine which phase of rotation we're in
2716         float coast_start_time = psub->stepped_rotation->fraction * psub->stepped_rotation->t_transit;
2717         float decel_start_time = psub->stepped_rotation->t_transit * (1.0f - psub->stepped_rotation->fraction);
2718         float pause_start_time = psub->stepped_rotation->t_transit;
2719
2720         float start_coast_angle = 0.5f * psub->stepped_rotation->max_turn_accel * coast_start_time * coast_start_time;
2721
2722         if (step_offset_time < coast_start_time) {
2723                 // do accel
2724                 float accel_time = step_offset_time;
2725                 *ang_next += 0.5f * psub->stepped_rotation->max_turn_accel * accel_time * accel_time;
2726                 sii->cur_turn_rate = psub->stepped_rotation->max_turn_accel * accel_time;
2727         } else if (step_offset_time < decel_start_time) {
2728                 // do coast
2729                 float coast_time = step_offset_time - coast_start_time;
2730                 *ang_next += start_coast_angle + psub->stepped_rotation->max_turn_rate * coast_time;
2731                 sii->cur_turn_rate = psub->stepped_rotation->max_turn_rate;
2732         } else if (step_offset_time < pause_start_time) {
2733                 // do decel
2734                 float time_to_pause = psub->stepped_rotation->t_transit - step_offset_time;
2735                 *ang_next += (step_size - 0.5f * psub->stepped_rotation->max_turn_accel * time_to_pause * time_to_pause);
2736                 sii->cur_turn_rate = psub->stepped_rotation->max_turn_rate * time_to_pause;
2737         } else {
2738                 // do pause
2739                 *ang_next += step_size;
2740                 sii->cur_turn_rate = 0.0f;
2741         }
2742 }
2743 #ifndef PLAT_UNIX
2744 #pragma warning ( pop )
2745 #endif
2746
2747 // Rotates the angle of a submodel.  Use this so the right unlocked axis
2748 // gets stuffed.
2749 void submodel_rotate(model_subsystem *psub, submodel_instance_info *sii)
2750 {
2751         bsp_info * sm;
2752
2753         if ( psub->subobj_num < 0 ) return;
2754
2755         polymodel *pm = model_get(psub->model_num);
2756         sm = &pm->submodel[psub->subobj_num];
2757
2758         if ( sm->movement_type != MOVEMENT_TYPE_ROT ) return;
2759
2760         // save last angles
2761         sii->prev_angs = sii->angs;
2762
2763         // probably send in a calculated desired turn rate
2764         float diff = sii->desired_turn_rate - sii->cur_turn_rate;
2765
2766         float final_turn_rate;
2767         if (diff > 0) {
2768                 final_turn_rate = sii->cur_turn_rate + sii->turn_accel * flFrametime;
2769                 if (final_turn_rate > sii->desired_turn_rate) {
2770                         final_turn_rate = sii->desired_turn_rate;
2771                 }
2772         } else if (diff < 0) {
2773                 final_turn_rate = sii->cur_turn_rate - sii->turn_accel * flFrametime;
2774                 if (final_turn_rate < sii->desired_turn_rate) {
2775                         final_turn_rate = sii->desired_turn_rate;
2776                 }
2777         } else {
2778                 final_turn_rate = sii->desired_turn_rate;
2779         }
2780
2781         float delta = (sii->cur_turn_rate + final_turn_rate) * 0.5f * flFrametime;
2782         sii->cur_turn_rate = final_turn_rate;
2783
2784
2785         //float delta = psub->turn_rate * flFrametime;
2786
2787         switch( sm->movement_axis )     {
2788         case MOVEMENT_AXIS_X:   
2789                 sii->angs.p += delta;
2790                 if (sii->angs.p > PI2 )
2791                         sii->angs.p -= PI2;
2792                 else if (sii->angs.p < 0.0f )
2793                         sii->angs.p += PI2;
2794                 break;
2795         case MOVEMENT_AXIS_Y:   
2796                 sii->angs.h += delta;
2797                 if (sii->angs.h > PI2 )
2798                         sii->angs.h -= PI2;
2799                 else if (sii->angs.h < 0.0f )
2800                         sii->angs.h += PI2;
2801                 break;
2802         case MOVEMENT_AXIS_Z:   
2803                 sii->angs.b += delta;
2804                 if (sii->angs.b > PI2 )
2805                         sii->angs.b -= PI2;
2806                 else if (sii->angs.b < 0.0f )
2807                         sii->angs.b += PI2;
2808                 break;
2809         }
2810 }
2811
2812
2813 //=========================================================================
2814 // Make a turret's correct orientation matrix.   This should be done when 
2815 // the model is read, but I wasn't sure at what point all the data that I
2816 // needed was read, so I just check a flag and call this routine when
2817 // I determine I need the correct matrix.   In this code, you can't use
2818 // vm_vec_2_matrix or anything, since these turrets could be either 
2819 // right handed or left handed.
2820 void model_make_turrent_matrix(int model_num, model_subsystem * turret )
2821 {
2822         polymodel * pm;
2823         vector fvec, uvec, rvec;
2824
2825         pm = model_get(model_num);
2826         bsp_info * sm = &pm->submodel[turret->turret_gun_sobj];
2827         bsp_info * sm_parent = &pm->submodel[turret->subobj_num];
2828
2829
2830         model_clear_instance(model_num);
2831         model_find_world_dir(&fvec, &turret->turret_norm, model_num, turret->turret_gun_sobj, &vmd_identity_matrix, NULL );
2832
2833         sm_parent->angs.h = -PI/2.0f;
2834         sm->angs.p = -PI/2.0f;
2835         model_find_world_dir(&rvec, &turret->turret_norm, model_num, turret->turret_gun_sobj, &vmd_identity_matrix, NULL );
2836
2837         sm_parent->angs.h = 0.0f;
2838         sm->angs.p = -PI/2.0f;
2839         model_find_world_dir(&uvec, &turret->turret_norm, model_num, turret->turret_gun_sobj, &vmd_identity_matrix, NULL );
2840                                                                         
2841         vm_vec_normalize(&fvec);
2842         vm_vec_normalize(&rvec);
2843         vm_vec_normalize(&uvec);
2844
2845         turret->turret_matrix.v.fvec = fvec;
2846         turret->turret_matrix.v.rvec = rvec;
2847         turret->turret_matrix.v.uvec = uvec;
2848
2849 //      vm_vector_2_matrix(&turret->turret_matrix,&turret->turret_norm,NULL,NULL);
2850
2851         // HACK!! WARNING!!!
2852         // I'm doing nothing to verify that this matrix is orthogonal!!
2853         // In other words, there's no guarantee that the vectors are 90 degrees
2854         // from each other.
2855         // I'm not doing this because I don't know how to do it without ruining
2856         // the handedness of the matrix... however, I'm not too worried about   
2857         // this because I am creating these 3 vectors by making them 90 degrees
2858         // apart, so this should be close enough.  I think this will start 
2859         // causing weird errors when we view from turrets. -John
2860         turret->flags |= MSS_FLAG_TURRET_MATRIX;
2861 }
2862
2863 // Tries to move joints so that the turrent points to the point dst.
2864 // turret1 is the angles of the turret, turret2 is the angles of the gun from turret
2865 //      Returns 1 if rotated gun, 0 if no gun to rotate (rotation handled by AI)
2866 int model_rotate_gun(int model_num, model_subsystem *turret, matrix *orient, angles *turret1, angles *turret2, vector *pos, vector *dst)
2867 {
2868         polymodel * pm;
2869
2870         pm = model_get(model_num);
2871         bsp_info * sm = &pm->submodel[turret->turret_gun_sobj];
2872         bsp_info * sm_parent = &pm->submodel[turret->subobj_num];
2873
2874         // Check for a valid turret
2875         Assert( turret->turret_num_firing_points > 0 );
2876
2877
2878         if ( sm_parent == sm ) {
2879                 return 0;
2880         }
2881
2882         // Build the correct turret matrix if there isn't already one
2883         if ( !(turret->flags & MSS_FLAG_TURRET_MATRIX) )
2884                 model_make_turrent_matrix(model_num, turret );
2885
2886         Assert( turret->flags & MSS_FLAG_TURRET_MATRIX);
2887 //      Assert( sm->movement_axis == MOVEMENT_AXIS_X );                         // Gun must be able to change pitch
2888 //      Assert( sm_parent->movement_axis == MOVEMENT_AXIS_Z );  // Parent must be able to change heading
2889
2890 //======================================================
2891 // DEBUG code to draw the normal out of this gun and a circle
2892 // at the gun point.
2893 #if 0
2894         {
2895                 vector tmp;
2896                 vector tmp1;
2897                 vertex dpnt1, dpnt2;
2898
2899                 model_clear_instance(model_num);
2900                 sm->angs.p = turret2->p;
2901                 sm_parent->angs.h = turret1->h;
2902
2903                 model_find_world_point(&tmp, &vmd_zero_vector, model_num, turret->turret_gun_sobj, orient, pos );
2904                 gr_set_color(255,0,0);
2905                 g3_rotate_vertex( &dpnt1, &tmp );
2906
2907                 gr_set_color(255,0,0);
2908                 g3_draw_sphere(&dpnt1,1.0f);
2909
2910                 vm_vec_copy_scale( &tmp1, &turret->turret_matrix.v.fvec, 10.0f );
2911                 model_find_world_point(&tmp, &tmp1, model_num, turret->turret_gun_sobj, orient, pos );
2912                 g3_rotate_vertex( &dpnt2, &tmp );
2913
2914                 gr_set_color(0,255,0);
2915                 g3_draw_line(&dpnt1,&dpnt2);
2916                 gr_set_color(0,128,0);
2917                 g3_draw_sphere(&dpnt2,0.2f);
2918
2919                 vm_vec_copy_scale( &tmp1, &turret->turret_matrix.v.rvec, 10.0f );
2920                 model_find_world_point(&tmp, &tmp1, model_num, turret->turret_gun_sobj, orient, pos );
2921                 g3_rotate_vertex( &dpnt2, &tmp );
2922
2923                 gr_set_color(0,0,255);
2924                 g3_draw_line(&dpnt1,&dpnt2);
2925
2926                 vm_vec_copy_scale( &tmp1, &turret->turret_matrix.v.uvec, 10.0f );
2927                 model_find_world_point(&tmp, &tmp1, model_num, turret->turret_gun_sobj, orient, pos );
2928                 g3_rotate_vertex( &dpnt2, &tmp );
2929
2930                 gr_set_color(255,0,0);
2931                 g3_draw_line(&dpnt1,&dpnt2);
2932         }
2933 #endif
2934
2935         //------------  
2936         // rotate the dest point into the turret gun normal's frame of
2937         // reference, but not using the turret's angles.
2938         // Call this vector of_dst
2939         vector of_dst;                                                  
2940         matrix world_to_turret_matrix;          // converts world coordinates to turret's FOR
2941         vector world_to_turret_translate;       // converts world coordinates to turret's FOR
2942         vector tempv;
2943
2944         vm_vec_unrotate( &tempv, &sm_parent->offset, orient);
2945         vm_vec_add( &world_to_turret_translate, pos, &tempv );
2946
2947         vm_matrix_x_matrix( &world_to_turret_matrix, orient, &turret->turret_matrix );
2948
2949         vm_vec_sub( &tempv, dst, &world_to_turret_translate );
2950         vm_vec_rotate( &of_dst, &tempv, &world_to_turret_matrix );
2951
2952         vm_vec_normalize(&of_dst);      
2953
2954         //------------  
2955         // Find the heading and pitch that the gun needs to turn to
2956         // by extracting them from the of_dst vector.
2957         // Call this the desired_angles
2958         angles desired_angles;
2959
2960         desired_angles.p = (float)acos(of_dst.xyz.z);
2961         desired_angles.h = PI - atan2_safe(of_dst.xyz.x, of_dst.xyz.y);
2962         desired_angles.b = 0.0f;
2963
2964         //      mprintf(( "Z = %.1f, atan= %.1f\n", of_dst.xyz.z, desired_angles.p ));
2965
2966         //------------  
2967         // Gradually turn the turret towards the desired angles
2968         float step_size = turret->turret_turning_rate * flFrametime;
2969
2970         vm_interp_angle(&turret1->h,desired_angles.h,step_size);
2971         vm_interp_angle(&turret2->p,desired_angles.p,step_size);
2972
2973 //      turret1->h -= step_size*(key_down_timef(KEY_1)-key_down_timef(KEY_2) );
2974 //      turret2->p += step_size*(key_down_timef(KEY_3)-key_down_timef(KEY_4) );
2975
2976         return 1;
2977
2978 }
2979
2980
2981 // Given a point (pnt) that is in sub_model_num's frame of
2982 // reference, and given the object's orient and position, 
2983 // return the point in 3-space in outpnt.
2984 void model_find_world_point(vector * outpnt, vector *mpnt,int model_num,int sub_model_num, matrix * objorient, vector * objpos )
2985 {
2986         vector pnt;
2987         vector tpnt;
2988         matrix m;
2989         int mn;
2990         polymodel *pm = model_get(model_num);
2991
2992         pnt = *mpnt;
2993         mn = sub_model_num;
2994
2995         //instance up the tree for this point
2996         while ((mn>-1) && (pm->submodel[mn].parent > -1) ) {
2997                 
2998                 vm_angles_2_matrix(&m,&pm->submodel[mn].angs );
2999                 vm_vec_unrotate(&tpnt,&pnt,&m);
3000
3001                 vm_vec_add(&pnt,&tpnt,&pm->submodel[mn].offset );
3002
3003                 mn = pm->submodel[mn].parent;
3004         }
3005
3006         //now instance for the entire object
3007         vm_vec_unrotate(outpnt,&pnt,objorient);
3008         vm_vec_add2(outpnt,objpos);
3009 }
3010
3011 // Given a point in the world RF, find the corresponding point in the model RF.
3012 // This is special purpose code, specific for model collision.
3013 // NOTE - this code ASSUMES submodel is 1 level down from hull (detail[0])
3014 //
3015 // out - point in model RF
3016 // world_pt - point in world RF
3017 // pm - polygon model
3018 // submodel_num - submodel in whose RF we're trying to find the corresponding world point
3019 // orient - orient matrix of ship
3020 // pos - pos vector of ship
3021 void world_find_model_point(vector *out, vector *world_pt, polymodel *pm, int submodel_num, matrix *orient, vector *pos)
3022 {
3023         Assert( (pm->submodel[submodel_num].parent == pm->detail[0]) || (pm->submodel[submodel_num].parent == -1) );
3024
3025         vector tempv1, tempv2;
3026         matrix m;
3027
3028         // get into ship RF
3029         vm_vec_sub(&tempv1, world_pt, pos);
3030         vm_vec_rotate(&tempv2, &tempv1, orient);
3031
3032         if (pm->submodel[submodel_num].parent == -1) {
3033                 *out  = tempv2;
3034                 return;
3035         }
3036
3037         // put into submodel RF
3038         vm_vec_sub2(&tempv2, &pm->submodel[submodel_num].offset);
3039         vm_angles_2_matrix(&m, &pm->submodel[submodel_num].angs);
3040         vm_vec_rotate(out, &tempv2, &m);
3041 }
3042
3043 // Verify rotating submodel has corresponding ship subsystem -- info in which to store rotation angle
3044 int rotating_submodel_has_ship_subsys(int submodel, ship *shipp)
3045 {
3046         model_subsystem *psub;
3047         ship_subsys                     *pss;
3048
3049         int found = 0;
3050
3051         // Go through all subsystems and look for submodel
3052         // the subsystems that need it.
3053         for ( pss = GET_FIRST(&shipp->subsys_list); pss != END_OF_LIST(&shipp->subsys_list); pss = GET_NEXT(pss) ) {
3054                 psub = pss->system_info;
3055                 if (psub->subobj_num == submodel) {
3056                         found = 1;
3057                         break;
3058                 }
3059         }
3060         
3061         return found;
3062 }
3063
3064 void model_get_rotating_submodel_list(int *submodel_list, int *num_rotating_submodels, object *objp)
3065 {
3066         Assert(objp->type == OBJ_SHIP);
3067
3068         // Check if not currently rotating - then treat as part of superstructure.
3069         int modelnum = Ships[objp->instance].modelnum;
3070         polymodel *pm = model_get(modelnum);
3071         bsp_info *child_submodel;
3072
3073         *num_rotating_submodels = 0;
3074         child_submodel = &pm->submodel[pm->detail[0]];
3075
3076         int i = child_submodel->first_child;
3077         while ( i>-1 )  {
3078                 child_submodel = &pm->submodel[i];
3079
3080                 // Don't check it or its children if it is destroyed or it is a replacement (non-moving)
3081                 if ( !child_submodel->blown_off && (child_submodel->i_replace == -1) )  {
3082
3083                         // Only look for submodels that rotate
3084                         if (child_submodel->movement_type == MOVEMENT_TYPE_ROT) {
3085
3086                                 // find ship subsys and check submodel rotation is less than max allowed.
3087                                 ship *pship = &Ships[objp->instance];
3088                                 ship_subsys *subsys;
3089
3090                                 for ( subsys = GET_FIRST(&pship->subsys_list); subsys !=END_OF_LIST(&pship->subsys_list); subsys = GET_NEXT(subsys) ) {
3091                                         Assert(subsys->system_info->model_num == modelnum);
3092                                         if (i == subsys->system_info->subobj_num) {
3093                                                 // found the correct subsystem - now check delta rotation angle not too large
3094                                                 float delta_angle = get_submodel_delta_angle(&subsys->submodel_info_1);
3095                                                 if (delta_angle < MAX_SUBMODEL_COLLISION_ROT_ANGLE) {
3096                                                         Assert(*num_rotating_submodels < MAX_ROTATING_SUBMODELS-1);
3097                                                         submodel_list[(*num_rotating_submodels)++] = i;
3098                                                 }
3099                                                 break;
3100                                         }
3101                                 }
3102                         }
3103                 }
3104                 i = child_submodel->next_sibling;
3105         }
3106
3107         // error checking
3108 //#define MODEL_CHECK
3109 #ifdef MODEL_CHECK
3110         ship *pship = &Ships[objp->instance];
3111         for (int idx=0; idx<*num_rotating_submodels; idx++) {
3112                 int valid = rotating_submodel_has_ship_subsys(submodel_list[idx], pship);
3113 //              Assert( valid );
3114                 if ( !valid ) {
3115
3116                         Warning( LOCATION, "Ship %s has rotating submodel [%s] without ship subsystem\n", pship->ship_name, pm->submodel[submodel_list[idx]].name );
3117                         pm->submodel[submodel_list[idx]].movement_type &= ~MOVEMENT_TYPE_ROT;
3118                         *num_rotating_submodels = 0;
3119                 }
3120         }
3121 #endif
3122
3123 }
3124
3125
3126 // Given a direction (pnt) that is in sub_model_num's frame of
3127 // reference, and given the object's orient and position, 
3128 // return the point in 3-space in outpnt.
3129 void model_find_world_dir(vector * out_dir, vector *in_dir,int model_num, int sub_model_num, matrix * objorient, vector * objpos )
3130 {
3131         vector pnt;
3132         vector tpnt;
3133         matrix m;
3134         int mn;
3135         polymodel *pm = model_get(model_num);
3136
3137         pnt = *in_dir;
3138         mn = sub_model_num;
3139
3140         //instance up the tree for this point
3141         while ((mn>-1) && (pm->submodel[mn].parent > -1) ) {
3142                 
3143                 vm_angles_2_matrix(&m,&pm->submodel[mn].angs );
3144                 vm_vec_unrotate(&tpnt,&pnt,&m);
3145                 pnt = tpnt;
3146
3147                 mn = pm->submodel[mn].parent;
3148         }
3149
3150         //now instance for the entire object
3151         vm_vec_unrotate(out_dir,&pnt,objorient);
3152 }
3153
3154
3155
3156 // Clears all the submodel instances stored in a model to their defaults.
3157 void model_clear_instance(int model_num)
3158 {
3159         polymodel * pm;
3160         int i;
3161
3162         pm = model_get(model_num);
3163
3164         // reset textures to original ones
3165         for (i=0; i<pm->n_textures; i++ )       {
3166                 pm->textures[i] = pm->original_textures[i];
3167         }
3168         
3169         for (i=0; i<pm->n_models; i++ ) {
3170                 bsp_info *sm = &pm->submodel[i];
3171                 
3172                 if ( pm->submodel[i].is_damaged )       {
3173                         sm->blown_off = 1;
3174                 } else {
3175                         sm->blown_off = 0;
3176                 }
3177                 sm->angs.p = 0.0f;
3178                 sm->angs.b = 0.0f;
3179                 sm->angs.h = 0.0f;
3180
3181                 // set pointer to other ship subsystem info [turn rate, accel, moment, axis, ...]
3182                 sm->sii = NULL;
3183
3184                 sm->num_arcs = 0;               // Turn off any electric arcing effects
3185         }
3186
3187         for (i=0; i<pm->num_lights; i++ )       {
3188                 pm->lights[i].value = 0.0f;
3189         }
3190
3191         interp_clear_instance();
3192
3193 //      if ( keyd_pressed[KEY_1] ) pm->lights[0].value = 1.0f/255.0f;
3194 //      if ( keyd_pressed[KEY_2] ) pm->lights[1].value = 1.0f/255.0f;
3195 //      if ( keyd_pressed[KEY_3] ) pm->lights[2].value = 1.0f/255.0f;
3196 //      if ( keyd_pressed[KEY_4] ) pm->lights[3].value = 1.0f/255.0f;
3197 //      if ( keyd_pressed[KEY_5] ) pm->lights[4].value = 1.0f/255.0f;
3198 //      if ( keyd_pressed[KEY_6] ) pm->lights[5].value = 1.0f/255.0f;
3199
3200
3201 }
3202
3203 // initialization during ship set
3204 void model_clear_instance_info( submodel_instance_info * sii )
3205 {
3206         sii->blown_off = 0;
3207         sii->angs.p = 0.0f;
3208         sii->angs.b = 0.0f;
3209         sii->angs.h = 0.0f;
3210         sii->prev_angs.p = 0.0f;
3211         sii->prev_angs.b = 0.0f;
3212         sii->prev_angs.h = 0.0f;
3213
3214         sii->cur_turn_rate = 0.0f;
3215         sii->desired_turn_rate = 0.0f;
3216         sii->turn_accel = 0.0f;
3217 }
3218
3219 // initialization during ship set
3220 void model_set_instance_info(submodel_instance_info *sii, float turn_rate, float turn_accel)
3221 {
3222         sii->blown_off = 0;
3223         sii->angs.p = 0.0f;
3224         sii->angs.b = 0.0f;
3225         sii->angs.h = 0.0f;
3226         sii->prev_angs.p = 0.0f;
3227         sii->prev_angs.b = 0.0f;
3228         sii->prev_angs.h = 0.0f;
3229
3230         sii->cur_turn_rate = turn_rate * 0.0f;
3231         sii->desired_turn_rate = turn_rate;
3232         sii->turn_accel = turn_accel;
3233         sii->axis_set = 0;
3234         sii->step_zero_timestamp = timestamp();
3235 }
3236
3237
3238
3239 // Sets the submodel instance data in a submodel (for all detail levels)
3240 void model_set_instance(int model_num, int sub_model_num, submodel_instance_info * sii)
3241 {
3242         int i;
3243         polymodel * pm;
3244
3245         pm = model_get(model_num);
3246
3247         Assert( sub_model_num >= 0 );
3248         Assert( sub_model_num < pm->n_models );
3249
3250         if ( sub_model_num < 0 ) return;
3251         if ( sub_model_num >= pm->n_models ) return;
3252         bsp_info *sm = &pm->submodel[sub_model_num];
3253
3254         // Set the "blown out" flags    
3255         sm->blown_off = sii->blown_off;
3256
3257         if ( sm->blown_off )    {
3258                 if ( sm->my_replacement > -1 )  {
3259                         pm->submodel[sm->my_replacement].blown_off = 0;
3260                         pm->submodel[sm->my_replacement].angs = sii->angs;
3261                         pm->submodel[sm->my_replacement].sii = sii;
3262                 }
3263         } else {
3264                 if ( sm->my_replacement > -1 )  {
3265                         pm->submodel[sm->my_replacement].blown_off = 1;
3266                 }
3267         }
3268
3269         // Set the angles
3270         sm->angs = sii->angs;
3271         sm->sii = sii;
3272
3273         // For all the detail levels of this submodel, set them also.
3274         for (i=0; i<sm->num_details; i++ )      {
3275                 model_set_instance(model_num, sm->details[i], sii );
3276         }
3277 }
3278
3279
3280 // Finds a point on the rotation axis of a submodel, used in collision, generally find rotational velocity
3281 void model_init_submodel_axis_pt(submodel_instance_info *sii, int model_num, int submodel_num)
3282 {
3283         vector axis;
3284         vector *mpoint1, *mpoint2;
3285         vector p1, v1, p2, v2, int1;
3286
3287         polymodel *pm = model_get(model_num);
3288         Assert(pm->submodel[submodel_num].movement_type == MOVEMENT_TYPE_ROT);
3289         Assert(sii);
3290
3291         mpoint1 = NULL;
3292         mpoint2 = NULL;
3293
3294         // find 2 fixed points in submodel RF
3295         // these will be rotated to about the axis an angle of 0 and PI and we'll find the intersection of the
3296         // two lines to find a point on the axis
3297         if (pm->submodel[submodel_num].movement_axis == MOVEMENT_AXIS_X) {
3298                 axis = vmd_x_vector;
3299                 mpoint1 = &vmd_y_vector;
3300                 mpoint2 = &vmd_z_vector;
3301         } else if (pm->submodel[submodel_num].movement_axis == MOVEMENT_AXIS_Y) {
3302                 mpoint1 = &vmd_x_vector;
3303                 axis = vmd_z_vector;            // rotation about y is a change in heading (p,b,h), so we need z
3304                 mpoint2 = &vmd_z_vector;
3305         } else if (pm->submodel[submodel_num].movement_axis == MOVEMENT_AXIS_Z) {
3306                 mpoint1 = &vmd_x_vector;
3307                 mpoint2 = &vmd_y_vector;
3308                 axis = vmd_y_vector;            // rotation about z is a change in bank (p,b,h), so we need y
3309         } else {
3310                 // must be one of these axes or submodel_rot_hit is incorrectly set
3311                 Int3();
3312         }
3313
3314         // copy submodel angs
3315         angles copy_angs = pm->submodel[submodel_num].angs;
3316
3317         // find two points rotated into model RF when angs set to 0
3318         vm_vec_copy_scale((vector*)&pm->submodel[submodel_num].angs, &axis, 0.0f);
3319         model_find_world_point(&p1, mpoint1, model_num, submodel_num, &vmd_identity_matrix, &vmd_zero_vector);
3320         model_find_world_point(&p2, mpoint2, model_num, submodel_num, &vmd_identity_matrix, &vmd_zero_vector);
3321
3322         // find two points rotated into model RF when angs set to PI
3323         vm_vec_copy_scale((vector*)&pm->submodel[submodel_num].angs, &axis, PI);
3324         model_find_world_point(&v1, mpoint1, model_num, submodel_num, &vmd_identity_matrix, &vmd_zero_vector);
3325         model_find_world_point(&v2, mpoint2, model_num, submodel_num, &vmd_identity_matrix, &vmd_zero_vector);
3326
3327         // reset submodel angs
3328         pm->submodel[submodel_num].angs = copy_angs;
3329
3330         // find direction vectors of the two lines
3331         vm_vec_sub2(&v1, &p1);
3332         vm_vec_sub2(&v2, &p2);
3333
3334         // find the intersection of the two lines
3335         float s, t;
3336         fvi_two_lines_in_3space(&p1, &v1, &p2, &v2, &s, &t);
3337
3338         // find the actual intersection points
3339         vm_vec_scale_add(&int1, &p1, &v1, s);
3340
3341         // set flag to init
3342         sii->pt_on_axis = int1;
3343         sii->axis_set = 1;
3344 }
3345
3346
3347 // Adds an electrical arcing effect to a submodel
3348 void model_add_arc(int model_num, int sub_model_num, vector *v1, vector *v2, int arc_type )
3349 {
3350         polymodel * pm;
3351
3352         pm = model_get(model_num);
3353
3354         if ( sub_model_num == -1 )      {
3355                 sub_model_num = pm->detail[0];
3356         }
3357
3358         Assert( sub_model_num >= 0 );
3359         Assert( sub_model_num < pm->n_models );
3360
3361         if ( sub_model_num < 0 ) return;
3362         if ( sub_model_num >= pm->n_models ) return;
3363         bsp_info *sm = &pm->submodel[sub_model_num];
3364
3365         if ( sm->num_arcs < MAX_ARC_EFFECTS )   {
3366                 sm->arc_type[sm->num_arcs] = (ubyte)arc_type;
3367                 sm->arc_pts[sm->num_arcs][0] = *v1;
3368                 sm->arc_pts[sm->num_arcs][1] = *v2;
3369                 sm->num_arcs++;
3370         }
3371 }
3372
3373 // function to return an index into the docking_bays array which matches the criteria passed
3374 // to this function.  dock_type is one of the DOCK_TYPE_XXX defines in model.h
3375 int model_find_dock_index(int modelnum, int dock_type)
3376 {
3377         int i;
3378
3379         polymodel *pm;
3380
3381         pm = model_get(modelnum);
3382
3383         // no docking points -- return -1
3384         if ( pm->n_docks <= 0 )
3385                 return -1;
3386
3387         for (i = 0; i < pm->n_docks; i++ ) {
3388                 if ( dock_type & pm->docking_bays[i].type_flags )
3389                         return i;
3390         }
3391
3392         return -1;
3393 }
3394
3395 int model_get_dock_index_type(int modelnum, int index)
3396 {
3397         polymodel *pm = model_get(modelnum);                            
3398
3399         return pm->docking_bays[index].type_flags;
3400 }
3401
3402 // get all the different docking point types on a model
3403 int model_get_dock_types(int modelnum)
3404 {
3405         int i, type = 0;
3406         polymodel *pm;
3407
3408         pm = model_get(modelnum);
3409         for (i=0; i<pm->n_docks; i++)
3410                 type |= pm->docking_bays[i].type_flags;
3411
3412         return type;
3413 }
3414
3415 // function to return an index into the docking_bays array which matches the string passed
3416 // Fred uses strings to identify docking positions.  This functin also accepts generic strings
3417 // so that a desginer doesn't have to know exact names if building a mission from hand.
3418 int model_find_dock_name_index( int modelnum, char *name )
3419 {
3420         int i;
3421         polymodel *pm;
3422
3423         pm = model_get(modelnum);
3424         if ( pm->n_docks <= 0 )
3425                 return -1;
3426
3427         // check the generic names and call previous function to find first dock point of
3428         // the specified type
3429         if ( !stricmp(name, "cargo") )
3430                 return model_find_dock_index( modelnum, DOCK_TYPE_CARGO );
3431         else if (!stricmp( name, "rearm") )
3432                 return model_find_dock_index( modelnum, DOCK_TYPE_REARM );
3433         else if (!stricmp( name, "generic") )
3434                 return model_find_dock_index( modelnum, DOCK_TYPE_GENERIC );
3435
3436         for (i = 0; i < pm->n_docks; i++ ) {
3437                 if ( !stricmp(pm->docking_bays[i].name, name) )
3438                         return i;
3439         }
3440
3441         // if we get here, name wasn't found -- return -1 and hope for the best
3442         return -1;
3443 }
3444
3445 // returns the actual name of a docking point on a model, needed by Fred.
3446 char *model_get_dock_name(int modelnum, int index)
3447 {
3448         polymodel *pm;
3449
3450         pm = model_get(modelnum);
3451         Assert((index >= 0) && (index < pm->n_docks));
3452         return pm->docking_bays[index].name;
3453 }
3454
3455 int model_get_num_dock_points(int modelnum)
3456 {
3457         polymodel *pm;
3458
3459         pm = model_get(modelnum);
3460         return pm->n_docks;
3461 }
3462