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