added DP_SV_MODELFLAGS_AS_EFFECTS extension, this adds EF_ROCKET and
[xonotic/darkplaces.git] / model_alias.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20
21 #include "quakedef.h"
22 #include "image.h"
23 #include "r_shadow.h"
24
25 cvar_t r_skeletal_debugbone = {0, "r_skeletal_debugbone", "-1", "development cvar for testing skeletal model code"};
26 cvar_t r_skeletal_debugbonecomponent = {0, "r_skeletal_debugbonecomponent", "3", "development cvar for testing skeletal model code"};
27 cvar_t r_skeletal_debugbonevalue = {0, "r_skeletal_debugbonevalue", "100", "development cvar for testing skeletal model code"};
28 cvar_t r_skeletal_debugtranslatex = {0, "r_skeletal_debugtranslatex", "1", "development cvar for testing skeletal model code"};
29 cvar_t r_skeletal_debugtranslatey = {0, "r_skeletal_debugtranslatey", "1", "development cvar for testing skeletal model code"};
30 cvar_t r_skeletal_debugtranslatez = {0, "r_skeletal_debugtranslatez", "1", "development cvar for testing skeletal model code"};
31
32 float mod_md3_sin[320];
33
34 void Mod_AliasInit (void)
35 {
36         int i;
37         Cvar_RegisterVariable(&r_skeletal_debugbone);
38         Cvar_RegisterVariable(&r_skeletal_debugbonecomponent);
39         Cvar_RegisterVariable(&r_skeletal_debugbonevalue);
40         Cvar_RegisterVariable(&r_skeletal_debugtranslatex);
41         Cvar_RegisterVariable(&r_skeletal_debugtranslatey);
42         Cvar_RegisterVariable(&r_skeletal_debugtranslatez);
43         for (i = 0;i < 320;i++)
44                 mod_md3_sin[i] = sin(i * M_PI * 2.0f / 256.0);
45 }
46
47 void Mod_Alias_GetMesh_Vertices(const model_t *model, const frameblend_t *frameblend, float *vertex3f, float *normal3f, float *svector3f, float *tvector3f)
48 {
49 #define MAX_BONES 256
50         if (model->surfmesh.data_vertexweightindex4i)
51         {
52                 // vertex weighted skeletal
53                 int i, k;
54                 float boneposerelative[MAX_BONES][12];
55                 // interpolate matrices and concatenate them to their parents
56                 for (i = 0;i < model->num_bones;i++)
57                 {
58                         int blends;
59                         float *matrix, m[12], bonepose[MAX_BONES][12];
60                         for (k = 0;k < 12;k++)
61                                 m[k] = 0;
62                         for (blends = 0;blends < 4 && frameblend[blends].lerp > 0;blends++)
63                         {
64                                 matrix = model->data_poses + (frameblend[blends].frame * model->num_bones + i) * 12;
65                                 for (k = 0;k < 12;k++)
66                                         m[k] += matrix[k] * frameblend[blends].lerp;
67                         }
68                         if (i == r_skeletal_debugbone.integer)
69                                 m[r_skeletal_debugbonecomponent.integer % 12] += r_skeletal_debugbonevalue.value;
70                         m[3] *= r_skeletal_debugtranslatex.value;
71                         m[7] *= r_skeletal_debugtranslatey.value;
72                         m[11] *= r_skeletal_debugtranslatez.value;
73                         if (model->data_bones[i].parent >= 0)
74                                 R_ConcatTransforms(bonepose[model->data_bones[i].parent], m, bonepose[i]);
75                         else
76                                 for (k = 0;k < 12;k++)
77                                         bonepose[i][k] = m[k];
78                         // create a relative deformation matrix to describe displacement
79                         // from the base mesh, which is used by the actual weighting
80                         R_ConcatTransforms(bonepose[i], model->data_baseboneposeinverse + i * 12, boneposerelative[i]);
81                 }
82                 // blend the vertex bone weights
83                 // special case for the extremely common wf[0] == 1 because it saves 3 multiplies per array when compared to the other case (w[0] is always 1 if only one bone controls this vertex, artists only use multiple bones for certain special cases)
84                 // special case for the first bone because it avoids the need to memset the arrays before filling
85                 {
86                         const float *v = model->surfmesh.data_vertex3f;
87                         const int *wi = model->surfmesh.data_vertexweightindex4i;
88                         const float *wf = model->surfmesh.data_vertexweightinfluence4f;
89                         memset(vertex3f, 0, sizeof(float[3]) * model->surfmesh.num_vertices);
90                         for (i = 0;i < model->surfmesh.num_vertices;i++, v += 3, wi += 4, wf += 4, vertex3f += 3)
91                         {
92                                 if (wf[0] == 1)
93                                 {
94                                         const float *m = boneposerelative[wi[0]];
95                                         vertex3f[0] = (v[0] * m[0] + v[1] * m[1] + v[2] * m[ 2] + m[ 3]);
96                                         vertex3f[1] = (v[0] * m[4] + v[1] * m[5] + v[2] * m[ 6] + m[ 7]);
97                                         vertex3f[2] = (v[0] * m[8] + v[1] * m[9] + v[2] * m[10] + m[11]);
98                                 }
99                                 else
100                                 {
101                                         const float *m = boneposerelative[wi[0]];
102                                         float f = wf[0];
103                                         vertex3f[0] = f * (v[0] * m[0] + v[1] * m[1] + v[2] * m[ 2] + m[ 3]);
104                                         vertex3f[1] = f * (v[0] * m[4] + v[1] * m[5] + v[2] * m[ 6] + m[ 7]);
105                                         vertex3f[2] = f * (v[0] * m[8] + v[1] * m[9] + v[2] * m[10] + m[11]);
106                                         for (k = 1;k < 4 && wf[k];k++)
107                                         {
108                                                 const float *m = boneposerelative[wi[k]];
109                                                 float f = wf[k];
110                                                 vertex3f[0] += f * (v[0] * m[0] + v[1] * m[1] + v[2] * m[ 2] + m[ 3]);
111                                                 vertex3f[1] += f * (v[0] * m[4] + v[1] * m[5] + v[2] * m[ 6] + m[ 7]);
112                                                 vertex3f[2] += f * (v[0] * m[8] + v[1] * m[9] + v[2] * m[10] + m[11]);
113                                         }
114                                 }
115                         }
116                 }
117                 if (normal3f)
118                 {
119                         const float *n = model->surfmesh.data_normal3f;
120                         const int *wi = model->surfmesh.data_vertexweightindex4i;
121                         const float *wf = model->surfmesh.data_vertexweightinfluence4f;
122                         memset(normal3f, 0, sizeof(float[3]) * model->surfmesh.num_vertices);
123                         for (i = 0;i < model->surfmesh.num_vertices;i++, n += 3, wi += 4, wf += 4, normal3f += 3)
124                         {
125                                 if (wf[0] == 1)
126                                 {
127                                         const float *m = boneposerelative[wi[0]];
128                                         normal3f[0] = (n[0] * m[0] + n[1] * m[1] + n[2] * m[ 2]);
129                                         normal3f[1] = (n[0] * m[4] + n[1] * m[5] + n[2] * m[ 6]);
130                                         normal3f[2] = (n[0] * m[8] + n[1] * m[9] + n[2] * m[10]);
131                                 }
132                                 else
133                                 {
134                                         const float *m = boneposerelative[wi[0]];
135                                         float f = wf[0];
136                                         normal3f[0] = f * (n[0] * m[0] + n[1] * m[1] + n[2] * m[ 2]);
137                                         normal3f[1] = f * (n[0] * m[4] + n[1] * m[5] + n[2] * m[ 6]);
138                                         normal3f[2] = f * (n[0] * m[8] + n[1] * m[9] + n[2] * m[10]);
139                                         for (k = 1;k < 4 && wf[k];k++)
140                                         {
141                                                 const float *m = boneposerelative[wi[k]];
142                                                 float f = wf[k];
143                                                 normal3f[0] += f * (n[0] * m[0] + n[1] * m[1] + n[2] * m[ 2]);
144                                                 normal3f[1] += f * (n[0] * m[4] + n[1] * m[5] + n[2] * m[ 6]);
145                                                 normal3f[2] += f * (n[0] * m[8] + n[1] * m[9] + n[2] * m[10]);
146                                         }
147                                 }
148                         }
149                 }
150                 if (svector3f)
151                 {
152                         const float *sv = model->surfmesh.data_svector3f;
153                         const int *wi = model->surfmesh.data_vertexweightindex4i;
154                         const float *wf = model->surfmesh.data_vertexweightinfluence4f;
155                         memset(svector3f, 0, sizeof(float[3]) * model->surfmesh.num_vertices);
156                         for (i = 0;i < model->surfmesh.num_vertices;i++, sv += 3, wi += 4, wf += 4, svector3f += 3)
157                         {
158                                 if (wf[0] == 1)
159                                 {
160                                         const float *m = boneposerelative[wi[0]];
161                                         svector3f[0] = (sv[0] * m[0] + sv[1] * m[1] + sv[2] * m[ 2]);
162                                         svector3f[1] = (sv[0] * m[4] + sv[1] * m[5] + sv[2] * m[ 6]);
163                                         svector3f[2] = (sv[0] * m[8] + sv[1] * m[9] + sv[2] * m[10]);
164                                 }
165                                 else
166                                 {
167                                         const float *m = boneposerelative[wi[0]];
168                                         float f = wf[0];
169                                         svector3f[0] = f * (sv[0] * m[0] + sv[1] * m[1] + sv[2] * m[ 2]);
170                                         svector3f[1] = f * (sv[0] * m[4] + sv[1] * m[5] + sv[2] * m[ 6]);
171                                         svector3f[2] = f * (sv[0] * m[8] + sv[1] * m[9] + sv[2] * m[10]);
172                                         for (k = 1;k < 4 && wf[k];k++)
173                                         {
174                                                 const float *m = boneposerelative[wi[k]];
175                                                 float f = wf[k];
176                                                 svector3f[0] += f * (sv[0] * m[0] + sv[1] * m[1] + sv[2] * m[ 2]);
177                                                 svector3f[1] += f * (sv[0] * m[4] + sv[1] * m[5] + sv[2] * m[ 6]);
178                                                 svector3f[2] += f * (sv[0] * m[8] + sv[1] * m[9] + sv[2] * m[10]);
179                                         }
180                                 }
181                         }
182                 }
183                 if (tvector3f)
184                 {
185                         const float *tv = model->surfmesh.data_tvector3f;
186                         const int *wi = model->surfmesh.data_vertexweightindex4i;
187                         const float *wf = model->surfmesh.data_vertexweightinfluence4f;
188                         memset(tvector3f, 0, sizeof(float[3]) * model->surfmesh.num_vertices);
189                         for (i = 0;i < model->surfmesh.num_vertices;i++, tv += 3, wi += 4, wf += 4, tvector3f += 3)
190                         {
191                                 if (wf[0] == 1)
192                                 {
193                                         const float *m = boneposerelative[wi[0]];
194                                         tvector3f[0] = (tv[0] * m[0] + tv[1] * m[1] + tv[2] * m[ 2]);
195                                         tvector3f[1] = (tv[0] * m[4] + tv[1] * m[5] + tv[2] * m[ 6]);
196                                         tvector3f[2] = (tv[0] * m[8] + tv[1] * m[9] + tv[2] * m[10]);
197                                 }
198                                 else
199                                 {
200                                         const float *m = boneposerelative[wi[0]];
201                                         float f = wf[0];
202                                         tvector3f[0] = f * (tv[0] * m[0] + tv[1] * m[1] + tv[2] * m[ 2]);
203                                         tvector3f[1] = f * (tv[0] * m[4] + tv[1] * m[5] + tv[2] * m[ 6]);
204                                         tvector3f[2] = f * (tv[0] * m[8] + tv[1] * m[9] + tv[2] * m[10]);
205                                         for (k = 1;k < 4 && wf[k];k++)
206                                         {
207                                                 const float *m = boneposerelative[wi[k]];
208                                                 float f = wf[k];
209                                                 tvector3f[0] += f * (tv[0] * m[0] + tv[1] * m[1] + tv[2] * m[ 2]);
210                                                 tvector3f[1] += f * (tv[0] * m[4] + tv[1] * m[5] + tv[2] * m[ 6]);
211                                                 tvector3f[2] += f * (tv[0] * m[8] + tv[1] * m[9] + tv[2] * m[10]);
212                                         }
213                                 }
214                         }
215                 }
216         }
217         else if (model->surfmesh.data_morphmd3vertex)
218         {
219                 // vertex morph
220                 int i, numblends, blendnum;
221                 int numverts = model->surfmesh.num_vertices;
222                 numblends = 0;
223                 for (blendnum = 0;blendnum < 4;blendnum++)
224                 {
225                         //VectorMA(translate, model->surfmesh.num_morphmdlframetranslate, frameblend[blendnum].lerp, translate);
226                         if (frameblend[blendnum].lerp > 0)
227                                 numblends = blendnum + 1;
228                 }
229                 // special case for the first blend because it avoids some adds and the need to memset the arrays first
230                 for (blendnum = 0;blendnum < numblends;blendnum++)
231                 {
232                         const md3vertex_t *verts = model->surfmesh.data_morphmd3vertex + numverts * frameblend[blendnum].frame;
233                         float scale = frameblend[blendnum].lerp * (1.0f / 64.0f);
234                         if (blendnum == 0)
235                         {
236                                 for (i = 0;i < numverts;i++)
237                                 {
238                                         vertex3f[i * 3 + 0] = verts[i].origin[0] * scale;
239                                         vertex3f[i * 3 + 1] = verts[i].origin[1] * scale;
240                                         vertex3f[i * 3 + 2] = verts[i].origin[2] * scale;
241                                 }
242                         }
243                         else
244                         {
245                                 for (i = 0;i < numverts;i++)
246                                 {
247                                         vertex3f[i * 3 + 0] += verts[i].origin[0] * scale;
248                                         vertex3f[i * 3 + 1] += verts[i].origin[1] * scale;
249                                         vertex3f[i * 3 + 2] += verts[i].origin[2] * scale;
250                                 }
251                         }
252                         // the yaw and pitch stored in md3 models are 8bit quantized angles
253                         // (0-255), and as such a lookup table is very well suited to
254                         // decoding them, and since cosine is equivilant to sine with an
255                         // extra 45 degree rotation, this uses one lookup table for both
256                         // sine and cosine with a +64 bias to get cosine.
257                         if (normal3f)
258                         {
259                                 float lerp = frameblend[blendnum].lerp;
260                                 if (blendnum == 0)
261                                 {
262                                         for (i = 0;i < numverts;i++)
263                                         {
264                                                 normal3f[i * 3 + 0] = mod_md3_sin[verts[i].yaw + 64] * mod_md3_sin[verts[i].pitch     ] * lerp;
265                                                 normal3f[i * 3 + 1] = mod_md3_sin[verts[i].yaw     ] * mod_md3_sin[verts[i].pitch     ] * lerp;
266                                                 normal3f[i * 3 + 2] =                                  mod_md3_sin[verts[i].pitch + 64] * lerp;
267                                         }
268                                 }
269                                 else
270                                 {
271                                         for (i = 0;i < numverts;i++)
272                                         {
273                                                 normal3f[i * 3 + 0] += mod_md3_sin[verts[i].yaw + 64] * mod_md3_sin[verts[i].pitch     ] * lerp;
274                                                 normal3f[i * 3 + 1] += mod_md3_sin[verts[i].yaw     ] * mod_md3_sin[verts[i].pitch     ] * lerp;
275                                                 normal3f[i * 3 + 2] +=                                  mod_md3_sin[verts[i].pitch + 64] * lerp;
276                                         }
277                                 }
278                         }
279                 }
280                 // md3 model vertices do not include tangents, so we have to generate them (extremely slow)
281                 if (normal3f)
282                         if (svector3f)
283                                 Mod_BuildTextureVectorsFromNormals(0, model->surfmesh.num_vertices, model->surfmesh.num_triangles, vertex3f, model->surfmesh.data_texcoordtexture2f, normal3f, model->surfmesh.data_element3i, svector3f, tvector3f, r_smoothnormals_areaweighting.integer);
284         }
285         else if (model->surfmesh.data_morphmdlvertex)
286         {
287                 // vertex morph
288                 int i, numblends, blendnum;
289                 int numverts = model->surfmesh.num_vertices;
290                 float translate[3];
291                 VectorClear(translate);
292                 numblends = 0;
293                 // blend the frame translates to avoid redundantly doing so on each vertex
294                 // (a bit of a brain twister but it works)
295                 for (blendnum = 0;blendnum < 4;blendnum++)
296                 {
297                         if (model->surfmesh.data_morphmd2framesize6f)
298                                 VectorMA(translate, frameblend[blendnum].lerp, model->surfmesh.data_morphmd2framesize6f + frameblend[blendnum].frame * 6 + 3, translate);
299                         else
300                                 VectorMA(translate, frameblend[blendnum].lerp, model->surfmesh.num_morphmdlframetranslate, translate);
301                         if (frameblend[blendnum].lerp > 0)
302                                 numblends = blendnum + 1;
303                 }
304                 // special case for the first blend because it avoids some adds and the need to memset the arrays first
305                 for (blendnum = 0;blendnum < numblends;blendnum++)
306                 {
307                         const trivertx_t *verts = model->surfmesh.data_morphmdlvertex + numverts * frameblend[blendnum].frame;
308                         float scale[3];
309                         if (model->surfmesh.data_morphmd2framesize6f)
310                                 VectorScale(model->surfmesh.data_morphmd2framesize6f + frameblend[blendnum].frame * 6, frameblend[blendnum].lerp, scale);
311                         else
312                                 VectorScale(model->surfmesh.num_morphmdlframescale, frameblend[blendnum].lerp, scale);
313                         if (blendnum == 0)
314                         {
315                                 for (i = 0;i < numverts;i++)
316                                 {
317                                         vertex3f[i * 3 + 0] = translate[0] + verts[i].v[0] * scale[0];
318                                         vertex3f[i * 3 + 1] = translate[1] + verts[i].v[1] * scale[1];
319                                         vertex3f[i * 3 + 2] = translate[2] + verts[i].v[2] * scale[2];
320                                 }
321                         }
322                         else
323                         {
324                                 for (i = 0;i < numverts;i++)
325                                 {
326                                         vertex3f[i * 3 + 0] += verts[i].v[0] * scale[0];
327                                         vertex3f[i * 3 + 1] += verts[i].v[1] * scale[1];
328                                         vertex3f[i * 3 + 2] += verts[i].v[2] * scale[2];
329                                 }
330                         }
331                         // the vertex normals in mdl models are an index into a table of
332                         // 162 unique values, this very crude quantization reduces the
333                         // vertex normal to only one byte, which saves a lot of space but
334                         // also makes lighting pretty coarse
335                         if (normal3f)
336                         {
337                                 float lerp = frameblend[blendnum].lerp;
338                                 if (blendnum == 0)
339                                 {
340                                         for (i = 0;i < numverts;i++)
341                                         {
342                                                 const float *vn = m_bytenormals[verts[i].lightnormalindex];
343                                                 VectorScale(vn, lerp, normal3f + i*3);
344                                         }
345                                 }
346                                 else
347                                 {
348                                         for (i = 0;i < numverts;i++)
349                                         {
350                                                 const float *vn = m_bytenormals[verts[i].lightnormalindex];
351                                                 VectorMA(normal3f + i*3, lerp, vn, normal3f + i*3);
352                                         }
353                                 }
354                         }
355                 }
356                 if (normal3f)
357                         if (svector3f)
358                                 Mod_BuildTextureVectorsFromNormals(0, model->surfmesh.num_vertices, model->surfmesh.num_triangles, vertex3f, model->surfmesh.data_texcoordtexture2f, normal3f, model->surfmesh.data_element3i, svector3f, tvector3f, r_smoothnormals_areaweighting.integer);
359         }
360         else
361                 Host_Error("model %s has no skeletal or vertex morph animation data", model->name);
362 }
363
364 int Mod_Alias_GetTagMatrix(const model_t *model, int poseframe, int tagindex, matrix4x4_t *outmatrix)
365 {
366         const float *boneframe;
367         float tempbonematrix[12], bonematrix[12];
368         *outmatrix = identitymatrix;
369         if (model->num_bones)
370         {
371                 if (tagindex < 0 || tagindex >= model->num_bones)
372                         return 4;
373                 if (poseframe >= model->num_poses)
374                         return 6;
375                 boneframe = model->data_poses + poseframe * model->num_bones * 12;
376                 memcpy(bonematrix, boneframe + tagindex * 12, sizeof(float[12]));
377                 while (model->data_bones[tagindex].parent >= 0)
378                 {
379                         memcpy(tempbonematrix, bonematrix, sizeof(float[12]));
380                         R_ConcatTransforms(boneframe + model->data_bones[tagindex].parent * 12, tempbonematrix, bonematrix);
381                         tagindex = model->data_bones[tagindex].parent;
382                 }
383                 Matrix4x4_FromArray12FloatD3D(outmatrix, bonematrix);
384         }
385         else if (model->num_tags)
386         {
387                 if (tagindex < 0 || tagindex >= model->num_tags)
388                         return 4;
389                 if (poseframe >= model->num_tagframes)
390                         return 6;
391                 Matrix4x4_FromArray12FloatGL(outmatrix, model->data_tags[poseframe * model->num_tags + tagindex].matrixgl);
392         }
393         return 0;
394 }
395
396 int Mod_Alias_GetTagIndexForName(const model_t *model, unsigned int skin, const char *tagname)
397 {
398         int i;
399         if (model->data_overridetagnamesforskin && skin < (unsigned int)model->numskins && model->data_overridetagnamesforskin[(unsigned int)skin].num_overridetagnames)
400                 for (i = 0;i < model->data_overridetagnamesforskin[skin].num_overridetagnames;i++)
401                         if (!strcasecmp(tagname, model->data_overridetagnamesforskin[skin].data_overridetagnames[i].name))
402                                 return i + 1;
403         if (model->num_bones)
404                 for (i = 0;i < model->num_bones;i++)
405                         if (!strcasecmp(tagname, model->data_bones[i].name))
406                                 return i + 1;
407         if (model->num_tags)
408                 for (i = 0;i < model->num_tags;i++)
409                         if (!strcasecmp(tagname, model->data_tags[i].name))
410                                 return i + 1;
411         return 0;
412 }
413
414 static void Mod_BuildBaseBonePoses(void)
415 {
416         int i, k;
417         double scale;
418         float *basebonepose = Mem_Alloc(tempmempool, loadmodel->num_bones * sizeof(float[12]));
419         float *in12f = loadmodel->data_poses;
420         float *out12f = basebonepose;
421         float *outinv12f = loadmodel->data_baseboneposeinverse;
422         for (i = 0;i < loadmodel->num_bones;i++, in12f += 12, out12f += 12, outinv12f += 12)
423         {
424                 if (loadmodel->data_bones[i].parent >= 0)
425                         R_ConcatTransforms(basebonepose + 12 * loadmodel->data_bones[i].parent, in12f, out12f);
426                 else
427                         for (k = 0;k < 12;k++)
428                                 out12f[k] = in12f[k];
429
430                 // invert The Matrix
431
432                 // we only support uniform scaling, so assume the first row is enough
433                 // (note the lack of sqrt here, because we're trying to undo the scaling,
434                 // this means multiplying by the inverse scale twice - squaring it, which
435                 // makes the sqrt a waste of time)
436                 scale = 1.0 / (out12f[ 0] * out12f[ 0] + out12f[ 1] * out12f[ 1] + out12f[ 2] * out12f[ 2]);
437
438                 // invert the rotation by transposing and multiplying by the squared
439                 // recipricol of the input matrix scale as described above
440                 outinv12f[ 0] = (float)(out12f[ 0] * scale);
441                 outinv12f[ 1] = (float)(out12f[ 4] * scale);
442                 outinv12f[ 2] = (float)(out12f[ 8] * scale);
443                 outinv12f[ 4] = (float)(out12f[ 1] * scale);
444                 outinv12f[ 5] = (float)(out12f[ 5] * scale);
445                 outinv12f[ 6] = (float)(out12f[ 9] * scale);
446                 outinv12f[ 8] = (float)(out12f[ 2] * scale);
447                 outinv12f[ 9] = (float)(out12f[ 6] * scale);
448                 outinv12f[10] = (float)(out12f[10] * scale);
449
450                 // invert the translate
451                 outinv12f[ 3] = -(out12f[ 3] * outinv12f[ 0] + out12f[ 7] * outinv12f[ 1] + out12f[11] * outinv12f[ 2]);
452                 outinv12f[ 7] = -(out12f[ 3] * outinv12f[ 4] + out12f[ 7] * outinv12f[ 5] + out12f[11] * outinv12f[ 6]);
453                 outinv12f[11] = -(out12f[ 3] * outinv12f[ 8] + out12f[ 7] * outinv12f[ 9] + out12f[11] * outinv12f[10]);
454         }
455         Mem_Free(basebonepose);
456 }
457
458 static void Mod_Alias_CalculateBoundingBox(void)
459 {
460         int i, j;
461         int vnum;
462         qboolean firstvertex = true;
463         float dist, yawradius, radius;
464         float *v;
465         float *vertex3f;
466         frameblend_t frameblend[4];
467         memset(frameblend, 0, sizeof(frameblend));
468         frameblend[0].lerp = 1;
469         vertex3f = Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_vertices * sizeof(float[3]));
470         VectorClear(loadmodel->normalmins);
471         VectorClear(loadmodel->normalmaxs);
472         yawradius = 0;
473         radius = 0;
474         for (i = 0;i < loadmodel->numframes;i++)
475         {
476                 for (j = 0, frameblend[0].frame = loadmodel->animscenes[i].firstframe;j < loadmodel->animscenes[i].framecount;j++, frameblend[0].frame++)
477                 {
478                         Mod_Alias_GetMesh_Vertices(loadmodel, frameblend, vertex3f, NULL, NULL, NULL);
479                         for (vnum = 0, v = vertex3f;vnum < loadmodel->surfmesh.num_vertices;vnum++, v += 3)
480                         {
481                                 if (firstvertex)
482                                 {
483                                         firstvertex = false;
484                                         VectorCopy(v, loadmodel->normalmins);
485                                         VectorCopy(v, loadmodel->normalmaxs);
486                                 }
487                                 else
488                                 {
489                                         if (loadmodel->normalmins[0] > v[0]) loadmodel->normalmins[0] = v[0];
490                                         if (loadmodel->normalmins[1] > v[1]) loadmodel->normalmins[1] = v[1];
491                                         if (loadmodel->normalmins[2] > v[2]) loadmodel->normalmins[2] = v[2];
492                                         if (loadmodel->normalmaxs[0] < v[0]) loadmodel->normalmaxs[0] = v[0];
493                                         if (loadmodel->normalmaxs[1] < v[1]) loadmodel->normalmaxs[1] = v[1];
494                                         if (loadmodel->normalmaxs[2] < v[2]) loadmodel->normalmaxs[2] = v[2];
495                                 }
496                                 dist = v[0] * v[0] + v[1] * v[1];
497                                 if (yawradius < dist)
498                                         yawradius = dist;
499                                 dist += v[2] * v[2];
500                                 if (radius < dist)
501                                         radius = dist;
502                         }
503                 }
504         }
505         Mem_Free(vertex3f);
506         radius = sqrt(radius);
507         yawradius = sqrt(yawradius);
508         loadmodel->yawmins[0] = loadmodel->yawmins[1] = -yawradius;
509         loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = yawradius;
510         loadmodel->yawmins[2] = loadmodel->normalmins[2];
511         loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
512         loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -radius;
513         loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = radius;
514         loadmodel->radius = radius;
515         loadmodel->radius2 = radius * radius;
516 }
517
518 static void Mod_Alias_Mesh_CompileFrameZero(void)
519 {
520         frameblend_t frameblend[4] = {{0, 1}, {0, 0}, {0, 0}, {0, 0}};
521         loadmodel->surfmesh.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_vertices * sizeof(float[3][4]));
522         loadmodel->surfmesh.data_svector3f = loadmodel->surfmesh.data_vertex3f + loadmodel->surfmesh.num_vertices * 3;
523         loadmodel->surfmesh.data_tvector3f = loadmodel->surfmesh.data_vertex3f + loadmodel->surfmesh.num_vertices * 6;
524         loadmodel->surfmesh.data_normal3f = loadmodel->surfmesh.data_vertex3f + loadmodel->surfmesh.num_vertices * 9;
525         Mod_Alias_GetMesh_Vertices(loadmodel, frameblend, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f);
526 }
527
528 static void Mod_MDLMD2MD3_TraceBox(model_t *model, int frame, trace_t *trace, const vec3_t start, const vec3_t boxmins, const vec3_t boxmaxs, const vec3_t end, int hitsupercontentsmask)
529 {
530         int i;
531         float segmentmins[3], segmentmaxs[3];
532         frameblend_t frameblend[4];
533         msurface_t *surface;
534         static int maxvertices = 0;
535         static float *vertex3f = NULL;
536         memset(trace, 0, sizeof(*trace));
537         trace->fraction = 1;
538         trace->realfraction = 1;
539         trace->hitsupercontentsmask = hitsupercontentsmask;
540         memset(frameblend, 0, sizeof(frameblend));
541         frameblend[0].frame = frame;
542         frameblend[0].lerp = 1;
543         if (maxvertices < model->surfmesh.num_vertices)
544         {
545                 if (vertex3f)
546                         Z_Free(vertex3f);
547                 maxvertices = (model->surfmesh.num_vertices + 255) & ~255;
548                 vertex3f = (float *)Z_Malloc(maxvertices * sizeof(float[3]));
549         }
550         if (VectorLength2(boxmins) + VectorLength2(boxmaxs) == 0)
551         {
552                 // line trace
553                 segmentmins[0] = min(start[0], end[0]) - 1;
554                 segmentmins[1] = min(start[1], end[1]) - 1;
555                 segmentmins[2] = min(start[2], end[2]) - 1;
556                 segmentmaxs[0] = max(start[0], end[0]) + 1;
557                 segmentmaxs[1] = max(start[1], end[1]) + 1;
558                 segmentmaxs[2] = max(start[2], end[2]) + 1;
559                 for (i = 0, surface = model->data_surfaces;i < model->num_surfaces;i++, surface++)
560                 {
561                         Mod_Alias_GetMesh_Vertices(model, frameblend, vertex3f, NULL, NULL, NULL);
562                         Collision_TraceLineTriangleMeshFloat(trace, start, end, model->surfmesh.num_triangles, model->surfmesh.data_element3i, vertex3f, SUPERCONTENTS_SOLID, 0, surface->texture, segmentmins, segmentmaxs);
563                 }
564         }
565         else
566         {
567                 // box trace, performed as brush trace
568                 colbrushf_t *thisbrush_start, *thisbrush_end;
569                 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
570                 segmentmins[0] = min(start[0], end[0]) + boxmins[0] - 1;
571                 segmentmins[1] = min(start[1], end[1]) + boxmins[1] - 1;
572                 segmentmins[2] = min(start[2], end[2]) + boxmins[2] - 1;
573                 segmentmaxs[0] = max(start[0], end[0]) + boxmaxs[0] + 1;
574                 segmentmaxs[1] = max(start[1], end[1]) + boxmaxs[1] + 1;
575                 segmentmaxs[2] = max(start[2], end[2]) + boxmaxs[2] + 1;
576                 VectorAdd(start, boxmins, boxstartmins);
577                 VectorAdd(start, boxmaxs, boxstartmaxs);
578                 VectorAdd(end, boxmins, boxendmins);
579                 VectorAdd(end, boxmaxs, boxendmaxs);
580                 thisbrush_start = Collision_BrushForBox(&identitymatrix, boxstartmins, boxstartmaxs, 0, 0, NULL);
581                 thisbrush_end = Collision_BrushForBox(&identitymatrix, boxendmins, boxendmaxs, 0, 0, NULL);
582                 for (i = 0, surface = model->data_surfaces;i < model->num_surfaces;i++, surface++)
583                 {
584                         if (maxvertices < model->surfmesh.num_vertices)
585                         {
586                                 if (vertex3f)
587                                         Z_Free(vertex3f);
588                                 maxvertices = (model->surfmesh.num_vertices + 255) & ~255;
589                                 vertex3f = (float *)Z_Malloc(maxvertices * sizeof(float[3]));
590                         }
591                         Mod_Alias_GetMesh_Vertices(model, frameblend, vertex3f, NULL, NULL, NULL);
592                         Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, model->surfmesh.num_triangles, model->surfmesh.data_element3i, vertex3f, SUPERCONTENTS_SOLID, 0, surface->texture, segmentmins, segmentmaxs);
593                 }
594         }
595 }
596
597 static void Mod_ConvertAliasVerts (int inverts, trivertx_t *v, trivertx_t *out, int *vertremap)
598 {
599         int i, j;
600         for (i = 0;i < inverts;i++)
601         {
602                 if (vertremap[i] < 0 && vertremap[i+inverts] < 0) // only used vertices need apply...
603                         continue;
604                 j = vertremap[i]; // not onseam
605                 if (j >= 0)
606                         out[j] = v[i];
607                 j = vertremap[i+inverts]; // onseam
608                 if (j >= 0)
609                         out[j] = v[i];
610         }
611 }
612
613 static void Mod_MDL_LoadFrames (unsigned char* datapointer, int inverts, int *vertremap)
614 {
615         int i, f, pose, groupframes;
616         float interval;
617         daliasframetype_t *pframetype;
618         daliasframe_t *pinframe;
619         daliasgroup_t *group;
620         daliasinterval_t *intervals;
621         animscene_t *scene;
622         pose = 0;
623         scene = loadmodel->animscenes;
624         for (f = 0;f < loadmodel->numframes;f++)
625         {
626                 pframetype = (daliasframetype_t *)datapointer;
627                 datapointer += sizeof(daliasframetype_t);
628                 if (LittleLong (pframetype->type) == ALIAS_SINGLE)
629                 {
630                         // a single frame is still treated as a group
631                         interval = 0.1f;
632                         groupframes = 1;
633                 }
634                 else
635                 {
636                         // read group header
637                         group = (daliasgroup_t *)datapointer;
638                         datapointer += sizeof(daliasgroup_t);
639                         groupframes = LittleLong (group->numframes);
640
641                         // intervals (time per frame)
642                         intervals = (daliasinterval_t *)datapointer;
643                         datapointer += sizeof(daliasinterval_t) * groupframes;
644
645                         interval = LittleFloat (intervals->interval); // FIXME: support variable framerate groups
646                         if (interval < 0.01f)
647                         {
648                                 Con_Printf("%s has an invalid interval %f, changing to 0.1\n", loadmodel->name, interval);
649                                 interval = 0.1f;
650                         }
651                 }
652
653                 // get scene name from first frame
654                 pinframe = (daliasframe_t *)datapointer;
655
656                 strlcpy(scene->name, pinframe->name, sizeof(scene->name));
657                 scene->firstframe = pose;
658                 scene->framecount = groupframes;
659                 scene->framerate = 1.0f / interval;
660                 scene->loop = true;
661                 scene++;
662
663                 // read frames
664                 for (i = 0;i < groupframes;i++)
665                 {
666                         pinframe = (daliasframe_t *)datapointer;
667                         datapointer += sizeof(daliasframe_t);
668                         Mod_ConvertAliasVerts(inverts, (trivertx_t *)datapointer, loadmodel->surfmesh.data_morphmdlvertex + pose * loadmodel->surfmesh.num_vertices, vertremap);
669                         datapointer += sizeof(trivertx_t) * inverts;
670                         pose++;
671                 }
672         }
673 }
674
675 static void Mod_BuildAliasSkinFromSkinFrame(texture_t *texture, skinframe_t *skinframe)
676 {
677         if (cls.state == ca_dedicated)
678                 return;
679         // hack
680         if (!skinframe)
681                 skinframe = R_SkinFrame_LoadMissing();
682         texture->currentframe = texture;
683         texture->numskinframes = 1;
684         texture->skinframerate = 1;
685         texture->skinframes[0] = skinframe;
686         texture->currentskinframe = skinframe;
687
688         texture->basematerialflags = MATERIALFLAG_WALL;
689         if (texture->currentskinframe->fog)
690                 texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
691         texture->currentmaterialflags = texture->basematerialflags;
692 }
693
694 static void Mod_BuildAliasSkinsFromSkinFiles(texture_t *skin, skinfile_t *skinfile, char *meshname, char *shadername)
695 {
696         int i;
697         skinfileitem_t *skinfileitem;
698         skinframe_t *tempskinframe;
699         if (skinfile)
700         {
701                 // the skin += loadmodel->num_surfaces part of this is because data_textures on alias models is arranged as [numskins][numsurfaces]
702                 for (i = 0;skinfile;skinfile = skinfile->next, i++, skin += loadmodel->num_surfaces)
703                 {
704                         memset(skin, 0, sizeof(*skin));
705                         Mod_BuildAliasSkinFromSkinFrame(skin, NULL);
706                         // don't render unmentioned meshes
707                         skin->basematerialflags = skin->currentmaterialflags = 0;
708                         // see if a mesh
709                         for (skinfileitem = skinfile->items;skinfileitem;skinfileitem = skinfileitem->next)
710                         {
711                                 // leave the skin unitialized (nodraw) if the replacement is "common/nodraw" or "textures/common/nodraw"
712                                 if (!strcmp(skinfileitem->name, meshname) && strcmp(skinfileitem->replacement, "common/nodraw") && strcmp(skinfileitem->replacement, "textures/common/nodraw"))
713                                 {
714                                         tempskinframe = R_SkinFrame_LoadExternal(skinfileitem->replacement, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP);
715                                         if (!tempskinframe)
716                                                 if (cls.state != ca_dedicated)
717                                                         Con_DPrintf("mesh \"%s\": failed to load skin #%i \"%s\"\n", meshname, i, skinfileitem->replacement);
718                                         Mod_BuildAliasSkinFromSkinFrame(skin, tempskinframe);
719                                         break;
720                                 }
721                         }
722                 }
723         }
724         else
725         {
726                 tempskinframe = R_SkinFrame_LoadExternal(shadername, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP);
727                 if (!tempskinframe)
728                         if (cls.state != ca_dedicated)
729                                 Con_Printf("Can't find texture \"%s\" for mesh \"%s\", using grey checkerboard\n", shadername, meshname);
730                 Mod_BuildAliasSkinFromSkinFrame(skin, tempskinframe);
731         }
732 }
733
734 #define BOUNDI(VALUE,MIN,MAX) if (VALUE < MIN || VALUE >= MAX) Host_Error("model %s has an invalid ##VALUE (%d exceeds %d - %d)", loadmodel->name, VALUE, MIN, MAX);
735 #define BOUNDF(VALUE,MIN,MAX) if (VALUE < MIN || VALUE >= MAX) Host_Error("model %s has an invalid ##VALUE (%f exceeds %f - %f)", loadmodel->name, VALUE, MIN, MAX);
736 void Mod_IDP0_Load(model_t *mod, void *buffer, void *bufferend)
737 {
738         int i, j, version, totalskins, skinwidth, skinheight, groupframes, groupskins, numverts;
739         float scales, scalet, interval;
740         msurface_t *surface;
741         unsigned char *data;
742         mdl_t *pinmodel;
743         stvert_t *pinstverts;
744         dtriangle_t *pintriangles;
745         daliasskintype_t *pinskintype;
746         daliasskingroup_t *pinskingroup;
747         daliasskininterval_t *pinskinintervals;
748         daliasframetype_t *pinframetype;
749         daliasgroup_t *pinframegroup;
750         unsigned char *datapointer, *startframes, *startskins;
751         char name[MAX_QPATH];
752         skinframe_t *tempskinframe;
753         animscene_t *tempskinscenes;
754         texture_t *tempaliasskins;
755         float *vertst;
756         int *vertonseam, *vertremap;
757         skinfile_t *skinfiles;
758
759         datapointer = (unsigned char *)buffer;
760         pinmodel = (mdl_t *)datapointer;
761         datapointer += sizeof(mdl_t);
762
763         version = LittleLong (pinmodel->version);
764         if (version != ALIAS_VERSION)
765                 Host_Error ("%s has wrong version number (%i should be %i)",
766                                  loadmodel->name, version, ALIAS_VERSION);
767
768         loadmodel->type = mod_alias;
769         loadmodel->DrawSky = NULL;
770         loadmodel->Draw = R_Q1BSP_Draw;
771         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
772         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
773         loadmodel->DrawLight = R_Q1BSP_DrawLight;
774         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
775
776         loadmodel->num_surfaces = 1;
777         loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
778         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int));
779         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
780         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
781         loadmodel->surfacelist[0] = 0;
782
783         loadmodel->numskins = LittleLong(pinmodel->numskins);
784         BOUNDI(loadmodel->numskins,0,65536);
785         skinwidth = LittleLong (pinmodel->skinwidth);
786         BOUNDI(skinwidth,0,65536);
787         skinheight = LittleLong (pinmodel->skinheight);
788         BOUNDI(skinheight,0,65536);
789         numverts = LittleLong(pinmodel->numverts);
790         BOUNDI(numverts,0,65536);
791         loadmodel->surfmesh.num_triangles = LittleLong(pinmodel->numtris);
792         BOUNDI(loadmodel->surfmesh.num_triangles,0,65536);
793         loadmodel->numframes = LittleLong(pinmodel->numframes);
794         BOUNDI(loadmodel->numframes,0,65536);
795         loadmodel->synctype = (synctype_t)LittleLong (pinmodel->synctype);
796         BOUNDI(loadmodel->synctype,0,2);
797         // convert model flags to EF flags (MF_ROCKET becomes EF_ROCKET, etc)
798         i = LittleLong (pinmodel->flags);
799         loadmodel->effects = ((i & 255) << 24) | (i & 0x00FFFF00);
800
801         for (i = 0;i < 3;i++)
802         {
803                 loadmodel->surfmesh.num_morphmdlframescale[i] = LittleFloat (pinmodel->scale[i]);
804                 loadmodel->surfmesh.num_morphmdlframetranslate[i] = LittleFloat (pinmodel->scale_origin[i]);
805         }
806
807         startskins = datapointer;
808         totalskins = 0;
809         for (i = 0;i < loadmodel->numskins;i++)
810         {
811                 pinskintype = (daliasskintype_t *)datapointer;
812                 datapointer += sizeof(daliasskintype_t);
813                 if (LittleLong(pinskintype->type) == ALIAS_SKIN_SINGLE)
814                         groupskins = 1;
815                 else
816                 {
817                         pinskingroup = (daliasskingroup_t *)datapointer;
818                         datapointer += sizeof(daliasskingroup_t);
819                         groupskins = LittleLong(pinskingroup->numskins);
820                         datapointer += sizeof(daliasskininterval_t) * groupskins;
821                 }
822
823                 for (j = 0;j < groupskins;j++)
824                 {
825                         datapointer += skinwidth * skinheight;
826                         totalskins++;
827                 }
828         }
829
830         pinstverts = (stvert_t *)datapointer;
831         datapointer += sizeof(stvert_t) * numverts;
832
833         pintriangles = (dtriangle_t *)datapointer;
834         datapointer += sizeof(dtriangle_t) * loadmodel->surfmesh.num_triangles;
835
836         startframes = datapointer;
837         loadmodel->surfmesh.num_morphframes = 0;
838         for (i = 0;i < loadmodel->numframes;i++)
839         {
840                 pinframetype = (daliasframetype_t *)datapointer;
841                 datapointer += sizeof(daliasframetype_t);
842                 if (LittleLong (pinframetype->type) == ALIAS_SINGLE)
843                         groupframes = 1;
844                 else
845                 {
846                         pinframegroup = (daliasgroup_t *)datapointer;
847                         datapointer += sizeof(daliasgroup_t);
848                         groupframes = LittleLong(pinframegroup->numframes);
849                         datapointer += sizeof(daliasinterval_t) * groupframes;
850                 }
851
852                 for (j = 0;j < groupframes;j++)
853                 {
854                         datapointer += sizeof(daliasframe_t);
855                         datapointer += sizeof(trivertx_t) * numverts;
856                         loadmodel->surfmesh.num_morphframes++;
857                 }
858         }
859
860         // store texture coordinates into temporary array, they will be stored
861         // after usage is determined (triangle data)
862         vertst = (float *)Mem_Alloc(tempmempool, numverts * 2 * sizeof(float[2]));
863         vertremap = (int *)Mem_Alloc(tempmempool, numverts * 3 * sizeof(int));
864         vertonseam = vertremap + numverts * 2;
865
866         scales = 1.0 / skinwidth;
867         scalet = 1.0 / skinheight;
868         for (i = 0;i < numverts;i++)
869         {
870                 vertonseam[i] = LittleLong(pinstverts[i].onseam);
871                 vertst[i*2+0] = (LittleLong(pinstverts[i].s) + 0.5) * scales;
872                 vertst[i*2+1] = (LittleLong(pinstverts[i].t) + 0.5) * scalet;
873                 vertst[(i+numverts)*2+0] = vertst[i*2+0] + 0.5;
874                 vertst[(i+numverts)*2+1] = vertst[i*2+1];
875         }
876
877 // load triangle data
878         loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * loadmodel->surfmesh.num_triangles);
879
880         // read the triangle elements
881         for (i = 0;i < loadmodel->surfmesh.num_triangles;i++)
882                 for (j = 0;j < 3;j++)
883                         loadmodel->surfmesh.data_element3i[i*3+j] = LittleLong(pintriangles[i].vertindex[j]);
884         // validate (note numverts is used because this is the original data)
885         Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, numverts, __FILE__, __LINE__);
886         // now butcher the elements according to vertonseam and tri->facesfront
887         // and then compact the vertex set to remove duplicates
888         for (i = 0;i < loadmodel->surfmesh.num_triangles;i++)
889                 if (!LittleLong(pintriangles[i].facesfront)) // backface
890                         for (j = 0;j < 3;j++)
891                                 if (vertonseam[loadmodel->surfmesh.data_element3i[i*3+j]])
892                                         loadmodel->surfmesh.data_element3i[i*3+j] += numverts;
893         // count the usage
894         // (this uses vertremap to count usage to save some memory)
895         for (i = 0;i < numverts*2;i++)
896                 vertremap[i] = 0;
897         for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
898                 vertremap[loadmodel->surfmesh.data_element3i[i]]++;
899         // build remapping table and compact array
900         loadmodel->surfmesh.num_vertices = 0;
901         for (i = 0;i < numverts*2;i++)
902         {
903                 if (vertremap[i])
904                 {
905                         vertremap[i] = loadmodel->surfmesh.num_vertices;
906                         vertst[loadmodel->surfmesh.num_vertices*2+0] = vertst[i*2+0];
907                         vertst[loadmodel->surfmesh.num_vertices*2+1] = vertst[i*2+1];
908                         loadmodel->surfmesh.num_vertices++;
909                 }
910                 else
911                         vertremap[i] = -1; // not used at all
912         }
913         // remap the elements to the new vertex set
914         for (i = 0;i < loadmodel->surfmesh.num_triangles * 3;i++)
915                 loadmodel->surfmesh.data_element3i[i] = vertremap[loadmodel->surfmesh.data_element3i[i]];
916         // store the texture coordinates
917         loadmodel->surfmesh.data_texcoordtexture2f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[2]) * loadmodel->surfmesh.num_vertices);
918         for (i = 0;i < loadmodel->surfmesh.num_vertices;i++)
919         {
920                 loadmodel->surfmesh.data_texcoordtexture2f[i*2+0] = vertst[i*2+0];
921                 loadmodel->surfmesh.data_texcoordtexture2f[i*2+1] = vertst[i*2+1];
922         }
923
924 // load the frames
925         loadmodel->animscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numframes);
926         loadmodel->surfmesh.data_morphmdlvertex = (trivertx_t *)Mem_Alloc(loadmodel->mempool, sizeof(trivertx_t) * loadmodel->surfmesh.num_morphframes * loadmodel->surfmesh.num_vertices);
927         loadmodel->surfmesh.data_neighbor3i = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_triangles * sizeof(int[3]));
928         Mod_MDL_LoadFrames (startframes, numverts, vertremap);
929         Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
930         Mod_Alias_CalculateBoundingBox();
931         Mod_Alias_Mesh_CompileFrameZero();
932
933         Mem_Free(vertst);
934         Mem_Free(vertremap);
935
936         // load the skins
937         skinfiles = Mod_LoadSkinFiles();
938         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, loadmodel->numskins * sizeof(animscene_t));
939         loadmodel->num_textures = loadmodel->num_surfaces;
940         loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * totalskins * sizeof(texture_t));
941         if (skinfiles)
942         {
943                 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures, skinfiles, "default", "");
944                 Mod_FreeSkinFiles(skinfiles);
945                 for (i = 0;i < loadmodel->numskins;i++)
946                 {
947                         loadmodel->skinscenes[i].firstframe = i;
948                         loadmodel->skinscenes[i].framecount = 1;
949                         loadmodel->skinscenes[i].loop = true;
950                         loadmodel->skinscenes[i].framerate = 10;
951                 }
952         }
953         else
954         {
955                 totalskins = 0;
956                 datapointer = startskins;
957                 for (i = 0;i < loadmodel->numskins;i++)
958                 {
959                         pinskintype = (daliasskintype_t *)datapointer;
960                         datapointer += sizeof(daliasskintype_t);
961
962                         if (pinskintype->type == ALIAS_SKIN_SINGLE)
963                         {
964                                 groupskins = 1;
965                                 interval = 0.1f;
966                         }
967                         else
968                         {
969                                 pinskingroup = (daliasskingroup_t *)datapointer;
970                                 datapointer += sizeof(daliasskingroup_t);
971
972                                 groupskins = LittleLong (pinskingroup->numskins);
973
974                                 pinskinintervals = (daliasskininterval_t *)datapointer;
975                                 datapointer += sizeof(daliasskininterval_t) * groupskins;
976
977                                 interval = LittleFloat(pinskinintervals[0].interval);
978                                 if (interval < 0.01f)
979                                 {
980                                         Con_Printf("%s has an invalid interval %f, changing to 0.1\n", loadmodel->name, interval);
981                                         interval = 0.1f;
982                                 }
983                         }
984
985                         sprintf(loadmodel->skinscenes[i].name, "skin %i", i);
986                         loadmodel->skinscenes[i].firstframe = totalskins;
987                         loadmodel->skinscenes[i].framecount = groupskins;
988                         loadmodel->skinscenes[i].framerate = 1.0f / interval;
989                         loadmodel->skinscenes[i].loop = true;
990
991                         for (j = 0;j < groupskins;j++)
992                         {
993                                 if (groupskins > 1)
994                                         sprintf (name, "%s_%i_%i", loadmodel->name, i, j);
995                                 else
996                                         sprintf (name, "%s_%i", loadmodel->name, i);
997                                 tempskinframe = R_SkinFrame_LoadExternal(name, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PICMIP);
998                                 if (!tempskinframe)
999                                         tempskinframe = R_SkinFrame_LoadInternal(name, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_PICMIP, true, r_fullbrights.integer, (unsigned char *)datapointer, skinwidth, skinheight, 8, NULL, NULL);
1000                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + totalskins * loadmodel->num_surfaces, tempskinframe);
1001                                 datapointer += skinwidth * skinheight;
1002                                 totalskins++;
1003                         }
1004                 }
1005                 // check for skins that don't exist in the model, but do exist as external images
1006                 // (this was added because yummyluv kept pestering me about support for it)
1007                 while ((tempskinframe = R_SkinFrame_LoadExternal(va("%s_%i", loadmodel->name, loadmodel->numskins), (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PICMIP)))
1008                 {
1009                         // expand the arrays to make room
1010                         tempskinscenes = loadmodel->skinscenes;
1011                         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, (loadmodel->numskins + 1) * sizeof(animscene_t));
1012                         memcpy(loadmodel->skinscenes, tempskinscenes, loadmodel->numskins * sizeof(animscene_t));
1013                         Mem_Free(tempskinscenes);
1014
1015                         tempaliasskins = loadmodel->data_textures;
1016                         loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * (totalskins + 1) * sizeof(texture_t));
1017                         memcpy(loadmodel->data_textures, tempaliasskins, loadmodel->num_surfaces * totalskins * sizeof(texture_t));
1018                         Mem_Free(tempaliasskins);
1019
1020                         // store the info about the new skin
1021                         Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + totalskins * loadmodel->num_surfaces, tempskinframe);
1022                         strlcpy(loadmodel->skinscenes[loadmodel->numskins].name, name, sizeof(loadmodel->skinscenes[loadmodel->numskins].name));
1023                         loadmodel->skinscenes[loadmodel->numskins].firstframe = totalskins;
1024                         loadmodel->skinscenes[loadmodel->numskins].framecount = 1;
1025                         loadmodel->skinscenes[loadmodel->numskins].framerate = 10.0f;
1026                         loadmodel->skinscenes[loadmodel->numskins].loop = true;
1027
1028                         //increase skin counts
1029                         loadmodel->numskins++;
1030                         totalskins++;
1031
1032                         // fix up the pointers since they are pointing at the old textures array
1033                         // FIXME: this is a hack!
1034                         for (j = 0;j < loadmodel->numskins * loadmodel->num_surfaces;j++)
1035                                 loadmodel->data_textures[j].currentframe = &loadmodel->data_textures[j];
1036                 }
1037         }
1038
1039         surface = loadmodel->data_surfaces;
1040         surface->texture = loadmodel->data_textures;
1041         surface->num_firsttriangle = 0;
1042         surface->num_triangles = loadmodel->surfmesh.num_triangles;
1043         surface->num_firstvertex = 0;
1044         surface->num_vertices = loadmodel->surfmesh.num_vertices;
1045
1046         loadmodel->surfmesh.isanimated = loadmodel->numframes > 1 || loadmodel->animscenes[0].framecount > 1;
1047 }
1048
1049 void Mod_IDP2_Load(model_t *mod, void *buffer, void *bufferend)
1050 {
1051         int i, j, hashindex, numxyz, numst, xyz, st, skinwidth, skinheight, *vertremap, version, end;
1052         float iskinwidth, iskinheight;
1053         unsigned char *data;
1054         msurface_t *surface;
1055         md2_t *pinmodel;
1056         unsigned char *base, *datapointer;
1057         md2frame_t *pinframe;
1058         char *inskin;
1059         md2triangle_t *intri;
1060         unsigned short *inst;
1061         struct md2verthash_s
1062         {
1063                 struct md2verthash_s *next;
1064                 unsigned short xyz;
1065                 unsigned short st;
1066         }
1067         *hash, **md2verthash, *md2verthashdata;
1068         skinframe_t *tempskinframe;
1069         skinfile_t *skinfiles;
1070
1071         pinmodel = (md2_t *)buffer;
1072         base = (unsigned char *)buffer;
1073
1074         version = LittleLong (pinmodel->version);
1075         if (version != MD2ALIAS_VERSION)
1076                 Host_Error ("%s has wrong version number (%i should be %i)",
1077                         loadmodel->name, version, MD2ALIAS_VERSION);
1078
1079         loadmodel->type = mod_alias;
1080         loadmodel->DrawSky = NULL;
1081         loadmodel->Draw = R_Q1BSP_Draw;
1082         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
1083         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
1084         loadmodel->DrawLight = R_Q1BSP_DrawLight;
1085         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
1086
1087         if (LittleLong(pinmodel->num_tris) < 1 || LittleLong(pinmodel->num_tris) > 65536)
1088                 Host_Error ("%s has invalid number of triangles: %i", loadmodel->name, LittleLong(pinmodel->num_tris));
1089         if (LittleLong(pinmodel->num_xyz) < 1 || LittleLong(pinmodel->num_xyz) > 65536)
1090                 Host_Error ("%s has invalid number of vertices: %i", loadmodel->name, LittleLong(pinmodel->num_xyz));
1091         if (LittleLong(pinmodel->num_frames) < 1 || LittleLong(pinmodel->num_frames) > 65536)
1092                 Host_Error ("%s has invalid number of frames: %i", loadmodel->name, LittleLong(pinmodel->num_frames));
1093         if (LittleLong(pinmodel->num_skins) < 0 || LittleLong(pinmodel->num_skins) > 256)
1094                 Host_Error ("%s has invalid number of skins: %i", loadmodel->name, LittleLong(pinmodel->num_skins));
1095
1096         end = LittleLong(pinmodel->ofs_end);
1097         if (LittleLong(pinmodel->num_skins) >= 1 && (LittleLong(pinmodel->ofs_skins) <= 0 || LittleLong(pinmodel->ofs_skins) >= end))
1098                 Host_Error ("%s is not a valid model", loadmodel->name);
1099         if (LittleLong(pinmodel->ofs_st) <= 0 || LittleLong(pinmodel->ofs_st) >= end)
1100                 Host_Error ("%s is not a valid model", loadmodel->name);
1101         if (LittleLong(pinmodel->ofs_tris) <= 0 || LittleLong(pinmodel->ofs_tris) >= end)
1102                 Host_Error ("%s is not a valid model", loadmodel->name);
1103         if (LittleLong(pinmodel->ofs_frames) <= 0 || LittleLong(pinmodel->ofs_frames) >= end)
1104                 Host_Error ("%s is not a valid model", loadmodel->name);
1105         if (LittleLong(pinmodel->ofs_glcmds) <= 0 || LittleLong(pinmodel->ofs_glcmds) >= end)
1106                 Host_Error ("%s is not a valid model", loadmodel->name);
1107
1108         loadmodel->numskins = LittleLong(pinmodel->num_skins);
1109         numxyz = LittleLong(pinmodel->num_xyz);
1110         numst = LittleLong(pinmodel->num_st);
1111         loadmodel->surfmesh.num_triangles = LittleLong(pinmodel->num_tris);
1112         loadmodel->numframes = LittleLong(pinmodel->num_frames);
1113         loadmodel->surfmesh.num_morphframes = loadmodel->numframes;
1114         skinwidth = LittleLong(pinmodel->skinwidth);
1115         skinheight = LittleLong(pinmodel->skinheight);
1116         iskinwidth = 1.0f / skinwidth;
1117         iskinheight = 1.0f / skinheight;
1118
1119         loadmodel->num_surfaces = 1;
1120         loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
1121         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->numframes * sizeof(animscene_t) + loadmodel->numframes * sizeof(float[6]) + loadmodel->surfmesh.num_triangles * sizeof(int[3]) + loadmodel->surfmesh.num_triangles * sizeof(int[3]));
1122         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
1123         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
1124         loadmodel->surfacelist[0] = 0;
1125         loadmodel->animscenes = (animscene_t *)data;data += loadmodel->numframes * sizeof(animscene_t);
1126         loadmodel->surfmesh.data_morphmd2framesize6f = (float *)data;data += loadmodel->numframes * sizeof(float[6]);
1127         loadmodel->surfmesh.data_element3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
1128         loadmodel->surfmesh.data_neighbor3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
1129
1130         loadmodel->synctype = ST_RAND;
1131
1132         // load the skins
1133         inskin = (char *)(base + LittleLong(pinmodel->ofs_skins));
1134         skinfiles = Mod_LoadSkinFiles();
1135         if (skinfiles)
1136         {
1137                 loadmodel->num_textures = loadmodel->num_surfaces;
1138                 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
1139                 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures, skinfiles, "default", "");
1140                 Mod_FreeSkinFiles(skinfiles);
1141         }
1142         else if (loadmodel->numskins)
1143         {
1144                 // skins found (most likely not a player model)
1145                 loadmodel->num_textures = loadmodel->num_surfaces;
1146                 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
1147                 for (i = 0;i < loadmodel->numskins;i++, inskin += MD2_SKINNAME)
1148                 {
1149                         tempskinframe = R_SkinFrame_LoadExternal(inskin, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP);
1150                         if (!tempskinframe)
1151                                 Con_Printf("%s is missing skin \"%s\"\n", loadmodel->name, inskin);
1152                         Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i * loadmodel->num_surfaces, tempskinframe);
1153                 }
1154         }
1155         else
1156         {
1157                 // no skins (most likely a player model)
1158                 loadmodel->numskins = 1;
1159                 loadmodel->num_textures = loadmodel->num_surfaces;
1160                 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
1161                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures, NULL);
1162         }
1163
1164         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
1165         for (i = 0;i < loadmodel->numskins;i++)
1166         {
1167                 loadmodel->skinscenes[i].firstframe = i;
1168                 loadmodel->skinscenes[i].framecount = 1;
1169                 loadmodel->skinscenes[i].loop = true;
1170                 loadmodel->skinscenes[i].framerate = 10;
1171         }
1172
1173         // load the triangles and stvert data
1174         inst = (unsigned short *)(base + LittleLong(pinmodel->ofs_st));
1175         intri = (md2triangle_t *)(base + LittleLong(pinmodel->ofs_tris));
1176         md2verthash = (struct md2verthash_s **)Mem_Alloc(tempmempool, 65536 * sizeof(hash));
1177         md2verthashdata = (struct md2verthash_s *)Mem_Alloc(tempmempool, loadmodel->surfmesh.num_triangles * 3 * sizeof(*hash));
1178         // swap the triangle list
1179         loadmodel->surfmesh.num_vertices = 0;
1180         for (i = 0;i < loadmodel->surfmesh.num_triangles;i++)
1181         {
1182                 for (j = 0;j < 3;j++)
1183                 {
1184                         xyz = (unsigned short) LittleShort (intri[i].index_xyz[j]);
1185                         st = (unsigned short) LittleShort (intri[i].index_st[j]);
1186                         if (xyz >= numxyz)
1187                         {
1188                                 Con_Printf("%s has an invalid xyz index (%i) on triangle %i, resetting to 0\n", loadmodel->name, xyz, i);
1189                                 xyz = 0;
1190                         }
1191                         if (st >= numst)
1192                         {
1193                                 Con_Printf("%s has an invalid st index (%i) on triangle %i, resetting to 0\n", loadmodel->name, st, i);
1194                                 st = 0;
1195                         }
1196                         hashindex = (xyz * 256 + st) & 65535;
1197                         for (hash = md2verthash[hashindex];hash;hash = hash->next)
1198                                 if (hash->xyz == xyz && hash->st == st)
1199                                         break;
1200                         if (hash == NULL)
1201                         {
1202                                 hash = md2verthashdata + loadmodel->surfmesh.num_vertices++;
1203                                 hash->xyz = xyz;
1204                                 hash->st = st;
1205                                 hash->next = md2verthash[hashindex];
1206                                 md2verthash[hashindex] = hash;
1207                         }
1208                         loadmodel->surfmesh.data_element3i[i*3+j] = (hash - md2verthashdata);
1209                 }
1210         }
1211
1212         vertremap = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_vertices * sizeof(int));
1213         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_vertices * sizeof(float[2]) + loadmodel->surfmesh.num_vertices * loadmodel->surfmesh.num_morphframes * sizeof(trivertx_t));
1214         loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
1215         loadmodel->surfmesh.data_morphmdlvertex = (trivertx_t *)data;data += loadmodel->surfmesh.num_vertices * loadmodel->surfmesh.num_morphframes * sizeof(trivertx_t);
1216         for (i = 0;i < loadmodel->surfmesh.num_vertices;i++)
1217         {
1218                 int sts, stt;
1219                 hash = md2verthashdata + i;
1220                 vertremap[i] = hash->xyz;
1221                 sts = LittleShort(inst[hash->st*2+0]);
1222                 stt = LittleShort(inst[hash->st*2+1]);
1223                 if (sts < 0 || sts >= skinwidth || stt < 0 || stt >= skinheight)
1224                 {
1225                         Con_Printf("%s has an invalid skin coordinate (%i %i) on vert %i, changing to 0 0\n", loadmodel->name, sts, stt, i);
1226                         sts = 0;
1227                         stt = 0;
1228                 }
1229                 loadmodel->surfmesh.data_texcoordtexture2f[i*2+0] = sts * iskinwidth;
1230                 loadmodel->surfmesh.data_texcoordtexture2f[i*2+1] = stt * iskinheight;
1231         }
1232
1233         Mem_Free(md2verthash);
1234         Mem_Free(md2verthashdata);
1235
1236         // load the frames
1237         datapointer = (base + LittleLong(pinmodel->ofs_frames));
1238         for (i = 0;i < loadmodel->surfmesh.num_morphframes;i++)
1239         {
1240                 int k;
1241                 trivertx_t *v;
1242                 trivertx_t *out;
1243                 pinframe = (md2frame_t *)datapointer;
1244                 datapointer += sizeof(md2frame_t);
1245                 // store the frame scale/translate into the appropriate array
1246                 for (j = 0;j < 3;j++)
1247                 {
1248                         loadmodel->surfmesh.data_morphmd2framesize6f[i*6+j] = LittleFloat(pinframe->scale[j]);
1249                         loadmodel->surfmesh.data_morphmd2framesize6f[i*6+3+j] = LittleFloat(pinframe->translate[j]);
1250                 }
1251                 // convert the vertices
1252                 v = (trivertx_t *)datapointer;
1253                 out = loadmodel->surfmesh.data_morphmdlvertex + i * loadmodel->surfmesh.num_vertices;
1254                 for (k = 0;k < loadmodel->surfmesh.num_vertices;k++)
1255                         out[k] = v[vertremap[k]];
1256                 datapointer += numxyz * sizeof(trivertx_t);
1257
1258                 strlcpy(loadmodel->animscenes[i].name, pinframe->name, sizeof(loadmodel->animscenes[i].name));
1259                 loadmodel->animscenes[i].firstframe = i;
1260                 loadmodel->animscenes[i].framecount = 1;
1261                 loadmodel->animscenes[i].framerate = 10;
1262                 loadmodel->animscenes[i].loop = true;
1263         }
1264
1265         Mem_Free(vertremap);
1266
1267         Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
1268         Mod_Alias_CalculateBoundingBox();
1269         Mod_Alias_Mesh_CompileFrameZero();
1270
1271         surface = loadmodel->data_surfaces;
1272         surface->texture = loadmodel->data_textures;
1273         surface->num_firsttriangle = 0;
1274         surface->num_triangles = loadmodel->surfmesh.num_triangles;
1275         surface->num_firstvertex = 0;
1276         surface->num_vertices = loadmodel->surfmesh.num_vertices;
1277
1278         loadmodel->surfmesh.isanimated = loadmodel->numframes > 1 || loadmodel->animscenes[0].framecount > 1;
1279 }
1280
1281 void Mod_IDP3_Load(model_t *mod, void *buffer, void *bufferend)
1282 {
1283         int i, j, k, version, meshvertices, meshtriangles;
1284         unsigned char *data;
1285         msurface_t *surface;
1286         md3modelheader_t *pinmodel;
1287         md3frameinfo_t *pinframe;
1288         md3mesh_t *pinmesh;
1289         md3tag_t *pintag;
1290         skinfile_t *skinfiles;
1291
1292         pinmodel = (md3modelheader_t *)buffer;
1293
1294         if (memcmp(pinmodel->identifier, "IDP3", 4))
1295                 Host_Error ("%s is not a MD3 (IDP3) file", loadmodel->name);
1296         version = LittleLong (pinmodel->version);
1297         if (version != MD3VERSION)
1298                 Host_Error ("%s has wrong version number (%i should be %i)",
1299                         loadmodel->name, version, MD3VERSION);
1300
1301         skinfiles = Mod_LoadSkinFiles();
1302         if (loadmodel->numskins < 1)
1303                 loadmodel->numskins = 1;
1304
1305         loadmodel->type = mod_alias;
1306         loadmodel->DrawSky = NULL;
1307         loadmodel->Draw = R_Q1BSP_Draw;
1308         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
1309         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
1310         loadmodel->DrawLight = R_Q1BSP_DrawLight;
1311         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
1312         loadmodel->synctype = ST_RAND;
1313         // convert model flags to EF flags (MF_ROCKET becomes EF_ROCKET, etc)
1314         i = LittleLong (pinmodel->flags);
1315         loadmodel->effects = ((i & 255) << 24) | (i & 0x00FFFF00);
1316
1317         // set up some global info about the model
1318         loadmodel->numframes = LittleLong(pinmodel->num_frames);
1319         loadmodel->num_surfaces = LittleLong(pinmodel->num_meshes);
1320
1321         // make skinscenes for the skins (no groups)
1322         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
1323         for (i = 0;i < loadmodel->numskins;i++)
1324         {
1325                 loadmodel->skinscenes[i].firstframe = i;
1326                 loadmodel->skinscenes[i].framecount = 1;
1327                 loadmodel->skinscenes[i].loop = true;
1328                 loadmodel->skinscenes[i].framerate = 10;
1329         }
1330
1331         // load frameinfo
1332         loadmodel->animscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, loadmodel->numframes * sizeof(animscene_t));
1333         for (i = 0, pinframe = (md3frameinfo_t *)((unsigned char *)pinmodel + LittleLong(pinmodel->lump_frameinfo));i < loadmodel->numframes;i++, pinframe++)
1334         {
1335                 strlcpy(loadmodel->animscenes[i].name, pinframe->name, sizeof(loadmodel->animscenes[i].name));
1336                 loadmodel->animscenes[i].firstframe = i;
1337                 loadmodel->animscenes[i].framecount = 1;
1338                 loadmodel->animscenes[i].framerate = 10;
1339                 loadmodel->animscenes[i].loop = true;
1340         }
1341
1342         // load tags
1343         loadmodel->num_tagframes = loadmodel->numframes;
1344         loadmodel->num_tags = LittleLong(pinmodel->num_tags);
1345         loadmodel->data_tags = (aliastag_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_tagframes * loadmodel->num_tags * sizeof(aliastag_t));
1346         for (i = 0, pintag = (md3tag_t *)((unsigned char *)pinmodel + LittleLong(pinmodel->lump_tags));i < loadmodel->num_tagframes * loadmodel->num_tags;i++, pintag++)
1347         {
1348                 strlcpy(loadmodel->data_tags[i].name, pintag->name, sizeof(loadmodel->data_tags[i].name));
1349                 for (j = 0;j < 9;j++)
1350                         loadmodel->data_tags[i].matrixgl[j] = LittleFloat(pintag->rotationmatrix[j]);
1351                 for (j = 0;j < 3;j++)
1352                         loadmodel->data_tags[i].matrixgl[9+j] = LittleFloat(pintag->origin[j]);
1353                 //Con_Printf("model \"%s\" frame #%i tag #%i \"%s\"\n", loadmodel->name, i / loadmodel->num_tags, i % loadmodel->num_tags, loadmodel->data_tags[i].name);
1354         }
1355
1356         // load meshes
1357         meshvertices = 0;
1358         meshtriangles = 0;
1359         for (i = 0, pinmesh = (md3mesh_t *)((unsigned char *)pinmodel + LittleLong(pinmodel->lump_meshes));i < loadmodel->num_surfaces;i++, pinmesh = (md3mesh_t *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_end)))
1360         {
1361                 if (memcmp(pinmesh->identifier, "IDP3", 4))
1362                         Host_Error("Mod_IDP3_Load: invalid mesh identifier (not IDP3)");
1363                 if (LittleLong(pinmesh->num_frames) != loadmodel->numframes)
1364                         Host_Error("Mod_IDP3_Load: mesh numframes differs from header");
1365                 meshvertices += LittleLong(pinmesh->num_vertices);
1366                 meshtriangles += LittleLong(pinmesh->num_triangles);
1367         }
1368
1369         loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
1370         loadmodel->num_textures = loadmodel->num_surfaces;
1371         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + meshtriangles * sizeof(int[3]) + meshtriangles * sizeof(int[3]) + meshvertices * sizeof(float[2]) + meshvertices * loadmodel->numframes * sizeof(md3vertex_t));
1372         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
1373         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
1374         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
1375         loadmodel->surfmesh.num_vertices = meshvertices;
1376         loadmodel->surfmesh.num_triangles = meshtriangles;
1377         loadmodel->surfmesh.num_morphframes = loadmodel->numframes; // TODO: remove?
1378         loadmodel->surfmesh.data_element3i = (int *)data;data += meshtriangles * sizeof(int[3]);
1379         loadmodel->surfmesh.data_neighbor3i = (int *)data;data += meshtriangles * sizeof(int[3]);
1380         loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += meshvertices * sizeof(float[2]);
1381         loadmodel->surfmesh.data_morphmd3vertex = (md3vertex_t *)data;data += meshvertices * loadmodel->numframes * sizeof(md3vertex_t);
1382
1383         meshvertices = 0;
1384         meshtriangles = 0;
1385         for (i = 0, pinmesh = (md3mesh_t *)((unsigned char *)pinmodel + LittleLong(pinmodel->lump_meshes));i < loadmodel->num_surfaces;i++, pinmesh = (md3mesh_t *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_end)))
1386         {
1387                 if (memcmp(pinmesh->identifier, "IDP3", 4))
1388                         Host_Error("Mod_IDP3_Load: invalid mesh identifier (not IDP3)");
1389                 loadmodel->surfacelist[i] = i;
1390                 surface = loadmodel->data_surfaces + i;
1391                 surface->texture = loadmodel->data_textures + i;
1392                 surface->num_firsttriangle = meshtriangles;
1393                 surface->num_triangles = LittleLong(pinmesh->num_triangles);
1394                 surface->num_firstvertex = meshvertices;
1395                 surface->num_vertices = LittleLong(pinmesh->num_vertices);
1396                 meshvertices += surface->num_vertices;
1397                 meshtriangles += surface->num_triangles;
1398
1399                 for (j = 0;j < surface->num_triangles * 3;j++)
1400                         loadmodel->surfmesh.data_element3i[j + surface->num_firsttriangle * 3] = surface->num_firstvertex + LittleLong(((int *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_elements)))[j]);
1401                 for (j = 0;j < surface->num_vertices;j++)
1402                 {
1403                         loadmodel->surfmesh.data_texcoordtexture2f[(j + surface->num_firstvertex) * 2 + 0] = LittleFloat(((float *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_texcoords)))[j * 2 + 0]);
1404                         loadmodel->surfmesh.data_texcoordtexture2f[(j + surface->num_firstvertex) * 2 + 1] = LittleFloat(((float *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_texcoords)))[j * 2 + 1]);
1405                 }
1406                 for (j = 0;j < loadmodel->numframes;j++)
1407                 {
1408                         const md3vertex_t *in = (md3vertex_t *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_framevertices)) + j * surface->num_vertices;
1409                         md3vertex_t *out = loadmodel->surfmesh.data_morphmd3vertex + surface->num_firstvertex + j * loadmodel->surfmesh.num_vertices;
1410                         for (k = 0;k < surface->num_vertices;k++, in++, out++)
1411                         {
1412                                 out->origin[0] = LittleShort(in->origin[0]);
1413                                 out->origin[1] = LittleShort(in->origin[1]);
1414                                 out->origin[2] = LittleShort(in->origin[2]);
1415                                 out->pitch = in->pitch;
1416                                 out->yaw = in->yaw;
1417                         }
1418                 }
1419
1420                 if (LittleLong(pinmesh->num_shaders) >= 1)
1421                         Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + i, skinfiles, pinmesh->name, ((md3shader_t *)((unsigned char *) pinmesh + LittleLong(pinmesh->lump_shaders)))->name);
1422                 else
1423                         for (j = 0;j < loadmodel->numskins;j++)
1424                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i + j * loadmodel->num_surfaces, NULL);
1425
1426                 Mod_ValidateElements(loadmodel->surfmesh.data_element3i + surface->num_firsttriangle * 3, surface->num_triangles, surface->num_firstvertex, surface->num_vertices, __FILE__, __LINE__);
1427         }
1428         Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
1429         Mod_Alias_Mesh_CompileFrameZero();
1430         Mod_Alias_CalculateBoundingBox();
1431         Mod_FreeSkinFiles(skinfiles);
1432
1433         loadmodel->surfmesh.isanimated = loadmodel->numframes > 1 || loadmodel->animscenes[0].framecount > 1;
1434 }
1435
1436 void Mod_ZYMOTICMODEL_Load(model_t *mod, void *buffer, void *bufferend)
1437 {
1438         zymtype1header_t *pinmodel, *pheader;
1439         unsigned char *pbase;
1440         int i, j, k, numposes, meshvertices, meshtriangles, *bonecount, *vertbonecounts, count, *renderlist, *renderlistend, *outelements;
1441         float modelradius, corner[2], *poses, *intexcoord2f, *outtexcoord2f, *bonepose;
1442         zymvertex_t *verts, *vertdata;
1443         zymscene_t *scene;
1444         zymbone_t *bone;
1445         char *shadername;
1446         skinfile_t *skinfiles;
1447         unsigned char *data;
1448         msurface_t *surface;
1449
1450         pinmodel = (zymtype1header_t *)buffer;
1451         pbase = (unsigned char *)buffer;
1452         if (memcmp(pinmodel->id, "ZYMOTICMODEL", 12))
1453                 Host_Error ("Mod_ZYMOTICMODEL_Load: %s is not a zymotic model", loadmodel->name);
1454         if (BigLong(pinmodel->type) != 1)
1455                 Host_Error ("Mod_ZYMOTICMODEL_Load: only type 1 (skeletal pose) models are currently supported (name = %s)", loadmodel->name);
1456
1457         loadmodel->type = mod_alias;
1458         loadmodel->synctype = ST_RAND;
1459
1460         // byteswap header
1461         pheader = pinmodel;
1462         pheader->type = BigLong(pinmodel->type);
1463         pheader->filesize = BigLong(pinmodel->filesize);
1464         pheader->mins[0] = BigFloat(pinmodel->mins[0]);
1465         pheader->mins[1] = BigFloat(pinmodel->mins[1]);
1466         pheader->mins[2] = BigFloat(pinmodel->mins[2]);
1467         pheader->maxs[0] = BigFloat(pinmodel->maxs[0]);
1468         pheader->maxs[1] = BigFloat(pinmodel->maxs[1]);
1469         pheader->maxs[2] = BigFloat(pinmodel->maxs[2]);
1470         pheader->radius = BigFloat(pinmodel->radius);
1471         pheader->numverts = BigLong(pinmodel->numverts);
1472         pheader->numtris = BigLong(pinmodel->numtris);
1473         pheader->numshaders = BigLong(pinmodel->numshaders);
1474         pheader->numbones = BigLong(pinmodel->numbones);
1475         pheader->numscenes = BigLong(pinmodel->numscenes);
1476         pheader->lump_scenes.start = BigLong(pinmodel->lump_scenes.start);
1477         pheader->lump_scenes.length = BigLong(pinmodel->lump_scenes.length);
1478         pheader->lump_poses.start = BigLong(pinmodel->lump_poses.start);
1479         pheader->lump_poses.length = BigLong(pinmodel->lump_poses.length);
1480         pheader->lump_bones.start = BigLong(pinmodel->lump_bones.start);
1481         pheader->lump_bones.length = BigLong(pinmodel->lump_bones.length);
1482         pheader->lump_vertbonecounts.start = BigLong(pinmodel->lump_vertbonecounts.start);
1483         pheader->lump_vertbonecounts.length = BigLong(pinmodel->lump_vertbonecounts.length);
1484         pheader->lump_verts.start = BigLong(pinmodel->lump_verts.start);
1485         pheader->lump_verts.length = BigLong(pinmodel->lump_verts.length);
1486         pheader->lump_texcoords.start = BigLong(pinmodel->lump_texcoords.start);
1487         pheader->lump_texcoords.length = BigLong(pinmodel->lump_texcoords.length);
1488         pheader->lump_render.start = BigLong(pinmodel->lump_render.start);
1489         pheader->lump_render.length = BigLong(pinmodel->lump_render.length);
1490         pheader->lump_shaders.start = BigLong(pinmodel->lump_shaders.start);
1491         pheader->lump_shaders.length = BigLong(pinmodel->lump_shaders.length);
1492         pheader->lump_trizone.start = BigLong(pinmodel->lump_trizone.start);
1493         pheader->lump_trizone.length = BigLong(pinmodel->lump_trizone.length);
1494
1495         if (pheader->numtris < 1 || pheader->numverts < 3 || pheader->numshaders < 1)
1496         {
1497                 Con_Printf("%s has no geometry\n", loadmodel->name);
1498                 return;
1499         }
1500         if (pheader->numscenes < 1 || pheader->lump_poses.length < (int)sizeof(float[3][4]))
1501         {
1502                 Con_Printf("%s has no animations\n", loadmodel->name);
1503                 return;
1504         }
1505
1506         loadmodel->DrawSky = NULL;
1507         loadmodel->Draw = R_Q1BSP_Draw;
1508         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
1509         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
1510         loadmodel->DrawLight = R_Q1BSP_DrawLight;
1511         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
1512
1513         loadmodel->numframes = pheader->numscenes;
1514         loadmodel->num_surfaces = pheader->numshaders;
1515
1516         skinfiles = Mod_LoadSkinFiles();
1517         if (loadmodel->numskins < 1)
1518                 loadmodel->numskins = 1;
1519
1520         // make skinscenes for the skins (no groups)
1521         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
1522         for (i = 0;i < loadmodel->numskins;i++)
1523         {
1524                 loadmodel->skinscenes[i].firstframe = i;
1525                 loadmodel->skinscenes[i].framecount = 1;
1526                 loadmodel->skinscenes[i].loop = true;
1527                 loadmodel->skinscenes[i].framerate = 10;
1528         }
1529
1530         // model bbox
1531         modelradius = pheader->radius;
1532         for (i = 0;i < 3;i++)
1533         {
1534                 loadmodel->normalmins[i] = pheader->mins[i];
1535                 loadmodel->normalmaxs[i] = pheader->maxs[i];
1536                 loadmodel->rotatedmins[i] = -modelradius;
1537                 loadmodel->rotatedmaxs[i] = modelradius;
1538         }
1539         corner[0] = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
1540         corner[1] = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
1541         loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
1542         if (loadmodel->yawmaxs[0] > modelradius)
1543                 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelradius;
1544         loadmodel->yawmins[0] = loadmodel->yawmins[1] = -loadmodel->yawmaxs[0];
1545         loadmodel->yawmins[2] = loadmodel->normalmins[2];
1546         loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
1547         loadmodel->radius = modelradius;
1548         loadmodel->radius2 = modelradius * modelradius;
1549
1550         // go through the lumps, swapping things
1551
1552         //zymlump_t lump_scenes; // zymscene_t scene[numscenes]; // name and other information for each scene (see zymscene struct)
1553         loadmodel->animscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numframes);
1554         scene = (zymscene_t *) (pheader->lump_scenes.start + pbase);
1555         numposes = pheader->lump_poses.length / pheader->numbones / sizeof(float[3][4]);
1556         for (i = 0;i < pheader->numscenes;i++)
1557         {
1558                 memcpy(loadmodel->animscenes[i].name, scene->name, 32);
1559                 loadmodel->animscenes[i].firstframe = BigLong(scene->start);
1560                 loadmodel->animscenes[i].framecount = BigLong(scene->length);
1561                 loadmodel->animscenes[i].framerate = BigFloat(scene->framerate);
1562                 loadmodel->animscenes[i].loop = (BigLong(scene->flags) & ZYMSCENEFLAG_NOLOOP) == 0;
1563                 if ((unsigned int) loadmodel->animscenes[i].firstframe >= (unsigned int) numposes)
1564                         Host_Error("%s scene->firstframe (%i) >= numposes (%i)", loadmodel->name, loadmodel->animscenes[i].firstframe, numposes);
1565                 if ((unsigned int) loadmodel->animscenes[i].firstframe + (unsigned int) loadmodel->animscenes[i].framecount > (unsigned int) numposes)
1566                         Host_Error("%s scene->firstframe (%i) + framecount (%i) >= numposes (%i)", loadmodel->name, loadmodel->animscenes[i].firstframe, loadmodel->animscenes[i].framecount, numposes);
1567                 if (loadmodel->animscenes[i].framerate < 0)
1568                         Host_Error("%s scene->framerate (%f) < 0", loadmodel->name, loadmodel->animscenes[i].framerate);
1569                 scene++;
1570         }
1571
1572         //zymlump_t lump_bones; // zymbone_t bone[numbones];
1573         loadmodel->num_bones = pheader->numbones;
1574         loadmodel->data_bones = (aliasbone_t *)Mem_Alloc(loadmodel->mempool, pheader->numbones * sizeof(aliasbone_t));
1575         bone = (zymbone_t *) (pheader->lump_bones.start + pbase);
1576         for (i = 0;i < pheader->numbones;i++)
1577         {
1578                 memcpy(loadmodel->data_bones[i].name, bone[i].name, sizeof(bone[i].name));
1579                 loadmodel->data_bones[i].flags = BigLong(bone[i].flags);
1580                 loadmodel->data_bones[i].parent = BigLong(bone[i].parent);
1581                 if (loadmodel->data_bones[i].parent >= i)
1582                         Host_Error("%s bone[%i].parent >= %i", loadmodel->name, i, i);
1583         }
1584
1585         //zymlump_t lump_vertbonecounts; // int vertbonecounts[numvertices]; // how many bones influence each vertex (separate mainly to make this compress better)
1586         vertbonecounts = (int *)Mem_Alloc(loadmodel->mempool, pheader->numverts * sizeof(int));
1587         bonecount = (int *) (pheader->lump_vertbonecounts.start + pbase);
1588         for (i = 0;i < pheader->numverts;i++)
1589         {
1590                 vertbonecounts[i] = BigLong(bonecount[i]);
1591                 if (vertbonecounts[i] != 1)
1592                         Host_Error("%s bonecount[%i] != 1 (vertex weight support is impossible in this format)", loadmodel->name, i);
1593         }
1594
1595         loadmodel->num_poses = pheader->lump_poses.length / sizeof(float[3][4]);
1596
1597         meshvertices = pheader->numverts;
1598         meshtriangles = pheader->numtris;
1599
1600         loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
1601         loadmodel->num_textures = loadmodel->num_surfaces;
1602         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + meshtriangles * sizeof(int[3]) + meshtriangles * sizeof(int[3]) + meshvertices * sizeof(float[14]) + meshvertices * sizeof(int[4]) + meshvertices * sizeof(float[4]) + loadmodel->num_poses * sizeof(float[12]) + loadmodel->num_bones * sizeof(float[12]));
1603         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
1604         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
1605         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
1606         loadmodel->surfmesh.num_vertices = meshvertices;
1607         loadmodel->surfmesh.num_triangles = meshtriangles;
1608         loadmodel->surfmesh.data_element3i = (int *)data;data += meshtriangles * sizeof(int[3]);
1609         loadmodel->surfmesh.data_neighbor3i = (int *)data;data += meshtriangles * sizeof(int[3]);
1610         loadmodel->surfmesh.data_vertex3f = (float *)data;data += meshvertices * sizeof(float[3]);
1611         loadmodel->surfmesh.data_svector3f = (float *)data;data += meshvertices * sizeof(float[3]);
1612         loadmodel->surfmesh.data_tvector3f = (float *)data;data += meshvertices * sizeof(float[3]);
1613         loadmodel->surfmesh.data_normal3f = (float *)data;data += meshvertices * sizeof(float[3]);
1614         loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += meshvertices * sizeof(float[2]);
1615         loadmodel->surfmesh.data_vertexweightindex4i = (int *)data;data += meshvertices * sizeof(int[4]);
1616         loadmodel->surfmesh.data_vertexweightinfluence4f = (float *)data;data += meshvertices * sizeof(float[4]);
1617         loadmodel->data_poses = (float *)data;data += loadmodel->num_poses * sizeof(float[12]);
1618         loadmodel->data_baseboneposeinverse = (float *)data;data += loadmodel->num_bones * sizeof(float[12]);
1619
1620         //zymlump_t lump_poses; // float pose[numposes][numbones][3][4]; // animation data
1621         poses = (float *) (pheader->lump_poses.start + pbase);
1622         for (i = 0;i < pheader->lump_poses.length / 4;i++)
1623                 loadmodel->data_poses[i] = BigFloat(poses[i]);
1624
1625         //zymlump_t lump_verts; // zymvertex_t vert[numvertices]; // see vertex struct
1626         verts = (zymvertex_t *)Mem_Alloc(loadmodel->mempool, pheader->lump_verts.length);
1627         vertdata = (zymvertex_t *) (pheader->lump_verts.start + pbase);
1628         // reconstruct frame 0 matrices to allow reconstruction of the base mesh
1629         // (converting from weight-blending skeletal animation to
1630         //  deformation-based skeletal animation)
1631         bonepose = (float *)Z_Malloc(loadmodel->num_bones * sizeof(float[12]));
1632         for (i = 0;i < loadmodel->num_bones;i++)
1633         {
1634                 const float *m = loadmodel->data_poses + i * 12;
1635                 if (loadmodel->data_bones[i].parent >= 0)
1636                         R_ConcatTransforms(bonepose + 12 * loadmodel->data_bones[i].parent, m, bonepose + 12 * i);
1637                 else
1638                         for (k = 0;k < 12;k++)
1639                                 bonepose[12*i+k] = m[k];
1640         }
1641         for (j = 0;j < pheader->numverts;j++)
1642         {
1643                 // this format really should have had a per vertexweight weight value...
1644                 // but since it does not, the weighting is completely ignored and
1645                 // only one weight is allowed per vertex
1646                 int boneindex = BigLong(vertdata[j].bonenum);
1647                 const float *m = bonepose + 12 * boneindex;
1648                 float relativeorigin[3];
1649                 relativeorigin[0] = BigFloat(vertdata[j].origin[0]);
1650                 relativeorigin[1] = BigFloat(vertdata[j].origin[1]);
1651                 relativeorigin[2] = BigFloat(vertdata[j].origin[2]);
1652                 // transform the vertex bone weight into the base mesh
1653                 loadmodel->surfmesh.data_vertex3f[j*3+0] = relativeorigin[0] * m[0] + relativeorigin[1] * m[1] + relativeorigin[2] * m[ 2] + m[ 3];
1654                 loadmodel->surfmesh.data_vertex3f[j*3+1] = relativeorigin[0] * m[4] + relativeorigin[1] * m[5] + relativeorigin[2] * m[ 6] + m[ 7];
1655                 loadmodel->surfmesh.data_vertex3f[j*3+2] = relativeorigin[0] * m[8] + relativeorigin[1] * m[9] + relativeorigin[2] * m[10] + m[11];
1656                 // store the weight as the primary weight on this vertex
1657                 loadmodel->surfmesh.data_vertexweightindex4i[j*4+0] = boneindex;
1658                 loadmodel->surfmesh.data_vertexweightinfluence4f[j*4+0] = 1;
1659         }
1660         Z_Free(bonepose);
1661         // normals and tangents are calculated after elements are loaded
1662
1663         //zymlump_t lump_texcoords; // float texcoords[numvertices][2];
1664         outtexcoord2f = loadmodel->surfmesh.data_texcoordtexture2f;
1665         intexcoord2f = (float *) (pheader->lump_texcoords.start + pbase);
1666         for (i = 0;i < pheader->numverts;i++)
1667         {
1668                 outtexcoord2f[i*2+0] = BigFloat(intexcoord2f[i*2+0]);
1669                 // flip T coordinate for OpenGL
1670                 outtexcoord2f[i*2+1] = 1 - BigFloat(intexcoord2f[i*2+1]);
1671         }
1672
1673         //zymlump_t lump_trizone; // byte trizone[numtris]; // see trizone explanation
1674         //loadmodel->alias.zymdata_trizone = Mem_Alloc(loadmodel->mempool, pheader->numtris);
1675         //memcpy(loadmodel->alias.zymdata_trizone, (void *) (pheader->lump_trizone.start + pbase), pheader->numtris);
1676
1677         //zymlump_t lump_shaders; // char shadername[numshaders][32]; // shaders used on this model
1678         //zymlump_t lump_render; // int renderlist[rendersize]; // sorted by shader with run lengths (int count), shaders are sequentially used, each run can be used with glDrawElements (each triangle is 3 int indices)
1679         // byteswap, validate, and swap winding order of tris
1680         count = pheader->numshaders * sizeof(int) + pheader->numtris * sizeof(int[3]);
1681         if (pheader->lump_render.length != count)
1682                 Host_Error("%s renderlist is wrong size (%i bytes, should be %i bytes)", loadmodel->name, pheader->lump_render.length, count);
1683         renderlist = (int *) (pheader->lump_render.start + pbase);
1684         renderlistend = (int *) ((unsigned char *) renderlist + pheader->lump_render.length);
1685         meshtriangles = 0;
1686         for (i = 0;i < loadmodel->num_surfaces;i++)
1687         {
1688                 int firstvertex, lastvertex;
1689                 if (renderlist >= renderlistend)
1690                         Host_Error("%s corrupt renderlist (wrong size)", loadmodel->name);
1691                 count = BigLong(*renderlist);renderlist++;
1692                 if (renderlist + count * 3 > renderlistend || (i == pheader->numshaders - 1 && renderlist + count * 3 != renderlistend))
1693                         Host_Error("%s corrupt renderlist (wrong size)", loadmodel->name);
1694
1695                 loadmodel->surfacelist[i] = i;
1696                 surface = loadmodel->data_surfaces + i;
1697                 surface->texture = loadmodel->data_textures + i;
1698                 surface->num_firsttriangle = meshtriangles;
1699                 surface->num_triangles = count;
1700                 meshtriangles += surface->num_triangles;
1701
1702                 // load the elements
1703                 outelements = loadmodel->surfmesh.data_element3i + surface->num_firsttriangle * 3;
1704                 for (j = 0;j < surface->num_triangles;j++, renderlist += 3)
1705                 {
1706                         outelements[j*3+2] = BigLong(renderlist[0]);
1707                         outelements[j*3+1] = BigLong(renderlist[1]);
1708                         outelements[j*3+0] = BigLong(renderlist[2]);
1709                 }
1710                 // validate the elements and find the used vertex range
1711                 firstvertex = meshvertices;
1712                 lastvertex = 0;
1713                 for (j = 0;j < surface->num_triangles * 3;j++)
1714                 {
1715                         if ((unsigned int)outelements[j] >= (unsigned int)meshvertices)
1716                                 Host_Error("%s corrupt renderlist (out of bounds index)", loadmodel->name);
1717                         firstvertex = min(firstvertex, outelements[j]);
1718                         lastvertex = max(lastvertex, outelements[j]);
1719                 }
1720                 surface->num_firstvertex = firstvertex;
1721                 surface->num_vertices = lastvertex + 1 - firstvertex;
1722
1723                 // since zym models do not have named sections, reuse their shader
1724                 // name as the section name
1725                 shadername = (char *) (pheader->lump_shaders.start + pbase) + i * 32;
1726                 if (shadername[0])
1727                         Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + i, skinfiles, shadername, shadername);
1728                 else
1729                         for (j = 0;j < loadmodel->numskins;j++)
1730                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i + j * loadmodel->num_surfaces, NULL);
1731         }
1732         Mod_FreeSkinFiles(skinfiles);
1733         Mem_Free(vertbonecounts);
1734         Mem_Free(verts);
1735
1736         // compute all the mesh information that was not loaded from the file
1737         Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
1738         Mod_BuildBaseBonePoses();
1739         Mod_BuildNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_normal3f, true);
1740         Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, true);
1741         Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
1742
1743         loadmodel->surfmesh.isanimated = loadmodel->numframes > 1 || loadmodel->animscenes[0].framecount > 1;
1744 }
1745
1746 void Mod_DARKPLACESMODEL_Load(model_t *mod, void *buffer, void *bufferend)
1747 {
1748         dpmheader_t *pheader;
1749         dpmframe_t *frame;
1750         dpmbone_t *bone;
1751         dpmmesh_t *dpmmesh;
1752         unsigned char *pbase;
1753         int i, j, k, meshvertices, meshtriangles;
1754         skinfile_t *skinfiles;
1755         unsigned char *data;
1756         float *bonepose;
1757
1758         pheader = (dpmheader_t *)buffer;
1759         pbase = (unsigned char *)buffer;
1760         if (memcmp(pheader->id, "DARKPLACESMODEL\0", 16))
1761                 Host_Error ("Mod_DARKPLACESMODEL_Load: %s is not a darkplaces model", loadmodel->name);
1762         if (BigLong(pheader->type) != 2)
1763                 Host_Error ("Mod_DARKPLACESMODEL_Load: only type 2 (hierarchical skeletal pose) models are currently supported (name = %s)", loadmodel->name);
1764
1765         loadmodel->type = mod_alias;
1766         loadmodel->synctype = ST_RAND;
1767
1768         // byteswap header
1769         pheader->type = BigLong(pheader->type);
1770         pheader->filesize = BigLong(pheader->filesize);
1771         pheader->mins[0] = BigFloat(pheader->mins[0]);
1772         pheader->mins[1] = BigFloat(pheader->mins[1]);
1773         pheader->mins[2] = BigFloat(pheader->mins[2]);
1774         pheader->maxs[0] = BigFloat(pheader->maxs[0]);
1775         pheader->maxs[1] = BigFloat(pheader->maxs[1]);
1776         pheader->maxs[2] = BigFloat(pheader->maxs[2]);
1777         pheader->yawradius = BigFloat(pheader->yawradius);
1778         pheader->allradius = BigFloat(pheader->allradius);
1779         pheader->num_bones = BigLong(pheader->num_bones);
1780         pheader->num_meshs = BigLong(pheader->num_meshs);
1781         pheader->num_frames = BigLong(pheader->num_frames);
1782         pheader->ofs_bones = BigLong(pheader->ofs_bones);
1783         pheader->ofs_meshs = BigLong(pheader->ofs_meshs);
1784         pheader->ofs_frames = BigLong(pheader->ofs_frames);
1785
1786         if (pheader->num_bones < 1 || pheader->num_meshs < 1)
1787         {
1788                 Con_Printf("%s has no geometry\n", loadmodel->name);
1789                 return;
1790         }
1791         if (pheader->num_frames < 1)
1792         {
1793                 Con_Printf("%s has no frames\n", loadmodel->name);
1794                 return;
1795         }
1796
1797         loadmodel->DrawSky = NULL;
1798         loadmodel->Draw = R_Q1BSP_Draw;
1799         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
1800         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
1801         loadmodel->DrawLight = R_Q1BSP_DrawLight;
1802         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
1803
1804         // model bbox
1805         for (i = 0;i < 3;i++)
1806         {
1807                 loadmodel->normalmins[i] = pheader->mins[i];
1808                 loadmodel->normalmaxs[i] = pheader->maxs[i];
1809                 loadmodel->yawmins[i] = i != 2 ? -pheader->yawradius : pheader->mins[i];
1810                 loadmodel->yawmaxs[i] = i != 2 ? pheader->yawradius : pheader->maxs[i];
1811                 loadmodel->rotatedmins[i] = -pheader->allradius;
1812                 loadmodel->rotatedmaxs[i] = pheader->allradius;
1813         }
1814         loadmodel->radius = pheader->allradius;
1815         loadmodel->radius2 = pheader->allradius * pheader->allradius;
1816
1817         // load external .skin files if present
1818         skinfiles = Mod_LoadSkinFiles();
1819         if (loadmodel->numskins < 1)
1820                 loadmodel->numskins = 1;
1821
1822         meshvertices = 0;
1823         meshtriangles = 0;
1824
1825         // gather combined statistics from the meshes
1826         dpmmesh = (dpmmesh_t *) (pbase + pheader->ofs_meshs);
1827         for (i = 0;i < (int)pheader->num_meshs;i++)
1828         {
1829                 int numverts = BigLong(dpmmesh->num_verts);
1830                 meshvertices += numverts;;
1831                 meshtriangles += BigLong(dpmmesh->num_tris);
1832                 dpmmesh++;
1833         }
1834
1835         loadmodel->numframes = pheader->num_frames;
1836         loadmodel->num_bones = pheader->num_bones;
1837         loadmodel->num_poses = loadmodel->num_bones * loadmodel->numframes;
1838         loadmodel->num_textures = loadmodel->nummodelsurfaces = loadmodel->num_surfaces = pheader->num_meshs;
1839         // do most allocations as one merged chunk
1840         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + meshtriangles * sizeof(int[3]) + meshtriangles * sizeof(int[3]) + meshvertices * (sizeof(float[14]) + sizeof(int[4]) + sizeof(float[4])) + loadmodel->num_poses * sizeof(float[12]) + loadmodel->num_bones * sizeof(float[12]) + loadmodel->numskins * sizeof(animscene_t) + loadmodel->num_bones * sizeof(aliasbone_t) + loadmodel->numframes * sizeof(animscene_t));
1841         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
1842         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
1843         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
1844         loadmodel->surfmesh.num_vertices = meshvertices;
1845         loadmodel->surfmesh.num_triangles = meshtriangles;
1846         loadmodel->surfmesh.data_element3i = (int *)data;data += meshtriangles * sizeof(int[3]);
1847         loadmodel->surfmesh.data_neighbor3i = (int *)data;data += meshtriangles * sizeof(int[3]);
1848         loadmodel->surfmesh.data_vertex3f = (float *)data;data += meshvertices * sizeof(float[3]);
1849         loadmodel->surfmesh.data_svector3f = (float *)data;data += meshvertices * sizeof(float[3]);
1850         loadmodel->surfmesh.data_tvector3f = (float *)data;data += meshvertices * sizeof(float[3]);
1851         loadmodel->surfmesh.data_normal3f = (float *)data;data += meshvertices * sizeof(float[3]);
1852         loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += meshvertices * sizeof(float[2]);
1853         loadmodel->surfmesh.data_vertexweightindex4i = (int *)data;data += meshvertices * sizeof(int[4]);
1854         loadmodel->surfmesh.data_vertexweightinfluence4f = (float *)data;data += meshvertices * sizeof(float[4]);
1855         loadmodel->data_poses = (float *)data;data += loadmodel->num_poses * sizeof(float[12]);
1856         loadmodel->data_baseboneposeinverse = (float *)data;data += loadmodel->num_bones * sizeof(float[12]);
1857         loadmodel->skinscenes = (animscene_t *)data;data += loadmodel->numskins * sizeof(animscene_t);
1858         loadmodel->data_bones = (aliasbone_t *)data;data += loadmodel->num_bones * sizeof(aliasbone_t);
1859         loadmodel->animscenes = (animscene_t *)data;data += loadmodel->numframes * sizeof(animscene_t);
1860
1861         for (i = 0;i < loadmodel->numskins;i++)
1862         {
1863                 loadmodel->skinscenes[i].firstframe = i;
1864                 loadmodel->skinscenes[i].framecount = 1;
1865                 loadmodel->skinscenes[i].loop = true;
1866                 loadmodel->skinscenes[i].framerate = 10;
1867         }
1868
1869         // load the bone info
1870         bone = (dpmbone_t *) (pbase + pheader->ofs_bones);
1871         for (i = 0;i < loadmodel->num_bones;i++)
1872         {
1873                 memcpy(loadmodel->data_bones[i].name, bone[i].name, sizeof(bone[i].name));
1874                 loadmodel->data_bones[i].flags = BigLong(bone[i].flags);
1875                 loadmodel->data_bones[i].parent = BigLong(bone[i].parent);
1876                 if (loadmodel->data_bones[i].parent >= i)
1877                         Host_Error("%s bone[%i].parent >= %i", loadmodel->name, i, i);
1878         }
1879
1880         // load the frames
1881         frame = (dpmframe_t *) (pbase + pheader->ofs_frames);
1882         for (i = 0;i < loadmodel->numframes;i++)
1883         {
1884                 const float *poses;
1885                 memcpy(loadmodel->animscenes[i].name, frame->name, sizeof(frame->name));
1886                 loadmodel->animscenes[i].firstframe = i;
1887                 loadmodel->animscenes[i].framecount = 1;
1888                 loadmodel->animscenes[i].loop = true;
1889                 loadmodel->animscenes[i].framerate = 10;
1890                 // load the bone poses for this frame
1891                 poses = (float *) (pbase + BigLong(frame->ofs_bonepositions));
1892                 for (j = 0;j < loadmodel->num_bones*12;j++)
1893                         loadmodel->data_poses[i * loadmodel->num_bones*12 + j] = BigFloat(poses[j]);
1894                 // stuff not processed here: mins, maxs, yawradius, allradius
1895                 frame++;
1896         }
1897
1898         // load the meshes now
1899         dpmmesh = (dpmmesh_t *) (pbase + pheader->ofs_meshs);
1900         meshvertices = 0;
1901         meshtriangles = 0;
1902         // reconstruct frame 0 matrices to allow reconstruction of the base mesh
1903         // (converting from weight-blending skeletal animation to
1904         //  deformation-based skeletal animation)
1905         bonepose = (float *)Z_Malloc(loadmodel->num_bones * sizeof(float[12]));
1906         for (i = 0;i < loadmodel->num_bones;i++)
1907         {
1908                 const float *m = loadmodel->data_poses + i * 12;
1909                 if (loadmodel->data_bones[i].parent >= 0)
1910                         R_ConcatTransforms(bonepose + 12 * loadmodel->data_bones[i].parent, m, bonepose + 12 * i);
1911                 else
1912                         for (k = 0;k < 12;k++)
1913                                 bonepose[12*i+k] = m[k];
1914         }
1915         for (i = 0;i < loadmodel->num_surfaces;i++, dpmmesh++)
1916         {
1917                 const int *inelements;
1918                 int *outelements;
1919                 const float *intexcoord;
1920                 msurface_t *surface;
1921
1922                 loadmodel->surfacelist[i] = i;
1923                 surface = loadmodel->data_surfaces + i;
1924                 surface->texture = loadmodel->data_textures + i;
1925                 surface->num_firsttriangle = meshtriangles;
1926                 surface->num_triangles = BigLong(dpmmesh->num_tris);
1927                 surface->num_firstvertex = meshvertices;
1928                 surface->num_vertices = BigLong(dpmmesh->num_verts);
1929                 meshvertices += surface->num_vertices;
1930                 meshtriangles += surface->num_triangles;
1931
1932                 inelements = (int *) (pbase + BigLong(dpmmesh->ofs_indices));
1933                 outelements = loadmodel->surfmesh.data_element3i + surface->num_firsttriangle * 3;
1934                 for (j = 0;j < surface->num_triangles;j++)
1935                 {
1936                         // swap element order to flip triangles, because Quake uses clockwise (rare) and dpm uses counterclockwise (standard)
1937                         outelements[0] = surface->num_firstvertex + BigLong(inelements[2]);
1938                         outelements[1] = surface->num_firstvertex + BigLong(inelements[1]);
1939                         outelements[2] = surface->num_firstvertex + BigLong(inelements[0]);
1940                         inelements += 3;
1941                         outelements += 3;
1942                 }
1943
1944                 intexcoord = (float *) (pbase + BigLong(dpmmesh->ofs_texcoords));
1945                 for (j = 0;j < surface->num_vertices*2;j++)
1946                         loadmodel->surfmesh.data_texcoordtexture2f[j + surface->num_firstvertex * 2] = BigFloat(intexcoord[j]);
1947
1948                 data = (unsigned char *) (pbase + BigLong(dpmmesh->ofs_verts));
1949                 for (j = surface->num_firstvertex;j < surface->num_firstvertex + surface->num_vertices;j++)
1950                 {
1951                         float sum;
1952                         int l;
1953                         int numweights = BigLong(((dpmvertex_t *)data)->numbones);
1954                         data += sizeof(dpmvertex_t);
1955                         for (k = 0;k < numweights;k++)
1956                         {
1957                                 const dpmbonevert_t *vert = (dpmbonevert_t *) data;
1958                                 int boneindex = BigLong(vert->bonenum);
1959                                 const float *m = bonepose + 12 * boneindex;
1960                                 float influence = BigFloat(vert->influence);
1961                                 float relativeorigin[3], relativenormal[3];
1962                                 relativeorigin[0] = BigFloat(vert->origin[0]);
1963                                 relativeorigin[1] = BigFloat(vert->origin[1]);
1964                                 relativeorigin[2] = BigFloat(vert->origin[2]);
1965                                 relativenormal[0] = BigFloat(vert->normal[0]);
1966                                 relativenormal[1] = BigFloat(vert->normal[1]);
1967                                 relativenormal[2] = BigFloat(vert->normal[2]);
1968                                 // blend the vertex bone weights into the base mesh
1969                                 loadmodel->surfmesh.data_vertex3f[j*3+0] += relativeorigin[0] * m[0] + relativeorigin[1] * m[1] + relativeorigin[2] * m[ 2] + influence * m[ 3];
1970                                 loadmodel->surfmesh.data_vertex3f[j*3+1] += relativeorigin[0] * m[4] + relativeorigin[1] * m[5] + relativeorigin[2] * m[ 6] + influence * m[ 7];
1971                                 loadmodel->surfmesh.data_vertex3f[j*3+2] += relativeorigin[0] * m[8] + relativeorigin[1] * m[9] + relativeorigin[2] * m[10] + influence * m[11];
1972                                 loadmodel->surfmesh.data_normal3f[j*3+0] += relativenormal[0] * m[0] + relativenormal[1] * m[1] + relativenormal[2] * m[ 2];
1973                                 loadmodel->surfmesh.data_normal3f[j*3+1] += relativenormal[0] * m[4] + relativenormal[1] * m[5] + relativenormal[2] * m[ 6];
1974                                 loadmodel->surfmesh.data_normal3f[j*3+2] += relativenormal[0] * m[8] + relativenormal[1] * m[9] + relativenormal[2] * m[10];
1975                                 if (!k)
1976                                 {
1977                                         // store the first (and often only) weight
1978                                         loadmodel->surfmesh.data_vertexweightinfluence4f[j*4+0] = influence;
1979                                         loadmodel->surfmesh.data_vertexweightindex4i[j*4+0] = boneindex;
1980                                 }
1981                                 else
1982                                 {
1983                                         // sort the new weight into this vertex's weight table
1984                                         // (which only accepts up to 4 bones per vertex)
1985                                         for (l = 0;l < 4;l++)
1986                                         {
1987                                                 if (loadmodel->surfmesh.data_vertexweightinfluence4f[j*4+l] < influence)
1988                                                 {
1989                                                         // move weaker influence weights out of the way first
1990                                                         int l2;
1991                                                         for (l2 = 3;l2 > l;l2--)
1992                                                         {
1993                                                                 loadmodel->surfmesh.data_vertexweightinfluence4f[j*4+l2] = loadmodel->surfmesh.data_vertexweightinfluence4f[j*4+l2-1];
1994                                                                 loadmodel->surfmesh.data_vertexweightindex4i[j*4+l2] = loadmodel->surfmesh.data_vertexweightindex4i[j*4+l2-1];
1995                                                         }
1996                                                         // store the new weight
1997                                                         loadmodel->surfmesh.data_vertexweightinfluence4f[j*4+l] = influence;
1998                                                         loadmodel->surfmesh.data_vertexweightindex4i[j*4+l] = boneindex;
1999                                                         break;
2000                                                 }
2001                                         }
2002                                 }
2003                                 data += sizeof(dpmbonevert_t);
2004                         }
2005                         sum = 0;
2006                         for (l = 0;l < 4;l++)
2007                                 sum += loadmodel->surfmesh.data_vertexweightinfluence4f[j*4+l];
2008                         if (sum && fabs(sum - 1) > (1.0f / 256.0f))
2009                         {
2010                                 float f = 1.0f / sum;
2011                                 for (l = 0;l < 4;l++)
2012                                         loadmodel->surfmesh.data_vertexweightinfluence4f[j*4+l] *= f;
2013                         }
2014                 }
2015
2016                 // since dpm models do not have named sections, reuse their shader name as the section name
2017                 if (dpmmesh->shadername[0])
2018                         Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + i, skinfiles, dpmmesh->shadername, dpmmesh->shadername);
2019                 else
2020                         for (j = 0;j < loadmodel->numskins;j++)
2021                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i + j * loadmodel->num_surfaces, NULL);
2022
2023                 Mod_ValidateElements(loadmodel->surfmesh.data_element3i + surface->num_firsttriangle * 3, surface->num_triangles, surface->num_firstvertex, surface->num_vertices, __FILE__, __LINE__);
2024         }
2025         Z_Free(bonepose);
2026         Mod_FreeSkinFiles(skinfiles);
2027
2028         // compute all the mesh information that was not loaded from the file
2029         Mod_BuildBaseBonePoses();
2030         Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, true);
2031         Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
2032
2033         loadmodel->surfmesh.isanimated = loadmodel->numframes > 1 || loadmodel->animscenes[0].framecount > 1;
2034 }
2035
2036 // no idea why PSK/PSA files contain weird quaternions but they do...
2037 #define PSKQUATNEGATIONS
2038 void Mod_PSKMODEL_Load(model_t *mod, void *buffer, void *bufferend)
2039 {
2040         int i, j, index, version, recordsize, numrecords, meshvertices, meshtriangles;
2041         int numpnts, numvtxw, numfaces, nummatts, numbones, numrawweights, numanimbones, numanims, numanimkeys;
2042         fs_offset_t filesize;
2043         pskpnts_t *pnts;
2044         pskvtxw_t *vtxw;
2045         pskface_t *faces;
2046         pskmatt_t *matts;
2047         pskboneinfo_t *bones;
2048         pskrawweights_t *rawweights;
2049         pskboneinfo_t *animbones;
2050         pskaniminfo_t *anims;
2051         pskanimkeys_t *animkeys;
2052         void *animfilebuffer, *animbuffer, *animbufferend;
2053         unsigned char *data;
2054         pskchunk_t *pchunk;
2055         skinfile_t *skinfiles;
2056         char animname[MAX_QPATH];
2057
2058         pchunk = (pskchunk_t *)buffer;
2059         if (strcmp(pchunk->id, "ACTRHEAD"))
2060                 Host_Error ("Mod_PSKMODEL_Load: %s is not an Unreal Engine ActorX (.psk + .psa) model", loadmodel->name);
2061
2062         loadmodel->type = mod_alias;
2063         loadmodel->DrawSky = NULL;
2064         loadmodel->Draw = R_Q1BSP_Draw;
2065         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
2066         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
2067         loadmodel->DrawLight = R_Q1BSP_DrawLight;
2068         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
2069         loadmodel->synctype = ST_RAND;
2070
2071         FS_StripExtension(loadmodel->name, animname, sizeof(animname));
2072         strlcat(animname, ".psa", sizeof(animname));
2073         animbuffer = animfilebuffer = FS_LoadFile(animname, loadmodel->mempool, false, &filesize);
2074         animbufferend = (void *)((unsigned char*)animbuffer + (int)filesize);
2075         if (animbuffer == NULL)
2076                 Host_Error("%s: can't find .psa file (%s)", loadmodel->name, animname);
2077
2078         numpnts = 0;
2079         pnts = NULL;
2080         numvtxw = 0;
2081         vtxw = NULL;
2082         numfaces = 0;
2083         faces = NULL;
2084         nummatts = 0;
2085         matts = NULL;
2086         numbones = 0;
2087         bones = NULL;
2088         numrawweights = 0;
2089         rawweights = NULL;
2090         numanims = 0;
2091         anims = NULL;
2092         numanimkeys = 0;
2093         animkeys = NULL;
2094
2095         while (buffer < bufferend)
2096         {
2097                 pchunk = (pskchunk_t *)buffer;
2098                 buffer = (void *)((unsigned char *)buffer + sizeof(pskchunk_t));
2099                 version = LittleLong(pchunk->version);
2100                 recordsize = LittleLong(pchunk->recordsize);
2101                 numrecords = LittleLong(pchunk->numrecords);
2102                 if (developer.integer >= 100)
2103                         Con_Printf("%s: %s %x: %i * %i = %i\n", loadmodel->name, pchunk->id, version, recordsize, numrecords, recordsize * numrecords);
2104                 if (version != 0x1e83b9 && version != 0x1e9179 && version != 0x2e && version != 0x12f2bc && version != 0x12f2f0)
2105                         Con_Printf ("%s: chunk %s has unknown version %x (0x1e83b9, 0x1e9179, 0x2e, 0x12f2bc, 0x12f2f0 are currently supported), trying to load anyway!\n", loadmodel->name, pchunk->id, version);
2106                 if (!strcmp(pchunk->id, "ACTRHEAD"))
2107                 {
2108                         // nothing to do
2109                 }
2110                 else if (!strcmp(pchunk->id, "PNTS0000"))
2111                 {
2112                         pskpnts_t *p;
2113                         if (recordsize != sizeof(*p))
2114                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
2115                         // byteswap in place and keep the pointer
2116                         numpnts = numrecords;
2117                         pnts = (pskpnts_t *)buffer;
2118                         for (index = 0, p = (pskpnts_t *)buffer;index < numrecords;index++, p++)
2119                         {
2120                                 p->origin[0] = LittleFloat(p->origin[0]);
2121                                 p->origin[1] = LittleFloat(p->origin[1]);
2122                                 p->origin[2] = LittleFloat(p->origin[2]);
2123                         }
2124                         buffer = p;
2125                 }
2126                 else if (!strcmp(pchunk->id, "VTXW0000"))
2127                 {
2128                         pskvtxw_t *p;
2129                         if (recordsize != sizeof(*p))
2130                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
2131                         // byteswap in place and keep the pointer
2132                         numvtxw = numrecords;
2133                         vtxw = (pskvtxw_t *)buffer;
2134                         for (index = 0, p = (pskvtxw_t *)buffer;index < numrecords;index++, p++)
2135                         {
2136                                 p->pntsindex = LittleShort(p->pntsindex);
2137                                 p->texcoord[0] = LittleFloat(p->texcoord[0]);
2138                                 p->texcoord[1] = LittleFloat(p->texcoord[1]);
2139                                 if (p->pntsindex >= numpnts)
2140                                 {
2141                                         Con_Printf("%s: vtxw->pntsindex %i >= numpnts %i\n", loadmodel->name, p->pntsindex, numpnts);
2142                                         p->pntsindex = 0;
2143                                 }
2144                         }
2145                         buffer = p;
2146                 }
2147                 else if (!strcmp(pchunk->id, "FACE0000"))
2148                 {
2149                         pskface_t *p;
2150                         if (recordsize != sizeof(*p))
2151                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
2152                         // byteswap in place and keep the pointer
2153                         numfaces = numrecords;
2154                         faces = (pskface_t *)buffer;
2155                         for (index = 0, p = (pskface_t *)buffer;index < numrecords;index++, p++)
2156                         {
2157                                 p->vtxwindex[0] = LittleShort(p->vtxwindex[0]);
2158                                 p->vtxwindex[1] = LittleShort(p->vtxwindex[1]);
2159                                 p->vtxwindex[2] = LittleShort(p->vtxwindex[2]);
2160                                 p->group = LittleLong(p->group);
2161                                 if (p->vtxwindex[0] >= numvtxw)
2162                                 {
2163                                         Con_Printf("%s: face->vtxwindex[0] %i >= numvtxw %i\n", loadmodel->name, p->vtxwindex[0], numvtxw);
2164                                         p->vtxwindex[0] = 0;
2165                                 }
2166                                 if (p->vtxwindex[1] >= numvtxw)
2167                                 {
2168                                         Con_Printf("%s: face->vtxwindex[1] %i >= numvtxw %i\n", loadmodel->name, p->vtxwindex[1], numvtxw);
2169                                         p->vtxwindex[1] = 0;
2170                                 }
2171                                 if (p->vtxwindex[2] >= numvtxw)
2172                                 {
2173                                         Con_Printf("%s: face->vtxwindex[2] %i >= numvtxw %i\n", loadmodel->name, p->vtxwindex[2], numvtxw);
2174                                         p->vtxwindex[2] = 0;
2175                                 }
2176                         }
2177                         buffer = p;
2178                 }
2179                 else if (!strcmp(pchunk->id, "MATT0000"))
2180                 {
2181                         pskmatt_t *p;
2182                         if (recordsize != sizeof(*p))
2183                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
2184                         // byteswap in place and keep the pointer
2185                         nummatts = numrecords;
2186                         matts = (pskmatt_t *)buffer;
2187                         for (index = 0, p = (pskmatt_t *)buffer;index < numrecords;index++, p++)
2188                         {
2189                                 // nothing to do
2190                         }
2191                         buffer = p;
2192                 }
2193                 else if (!strcmp(pchunk->id, "REFSKELT"))
2194                 {
2195                         pskboneinfo_t *p;
2196                         if (recordsize != sizeof(*p))
2197                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
2198                         // byteswap in place and keep the pointer
2199                         numbones = numrecords;
2200                         bones = (pskboneinfo_t *)buffer;
2201                         for (index = 0, p = (pskboneinfo_t *)buffer;index < numrecords;index++, p++)
2202                         {
2203                                 p->numchildren = LittleLong(p->numchildren);
2204                                 p->parent = LittleLong(p->parent);
2205                                 p->basepose.quat[0] = LittleFloat(p->basepose.quat[0]);
2206                                 p->basepose.quat[1] = LittleFloat(p->basepose.quat[1]);
2207                                 p->basepose.quat[2] = LittleFloat(p->basepose.quat[2]);
2208                                 p->basepose.quat[3] = LittleFloat(p->basepose.quat[3]);
2209                                 p->basepose.origin[0] = LittleFloat(p->basepose.origin[0]);
2210                                 p->basepose.origin[1] = LittleFloat(p->basepose.origin[1]);
2211                                 p->basepose.origin[2] = LittleFloat(p->basepose.origin[2]);
2212                                 p->basepose.unknown = LittleFloat(p->basepose.unknown);
2213                                 p->basepose.size[0] = LittleFloat(p->basepose.size[0]);
2214                                 p->basepose.size[1] = LittleFloat(p->basepose.size[1]);
2215                                 p->basepose.size[2] = LittleFloat(p->basepose.size[2]);
2216 #ifdef PSKQUATNEGATIONS
2217                                 if (index)
2218                                 {
2219                                         p->basepose.quat[0] *= -1;
2220                                         p->basepose.quat[1] *= -1;
2221                                         p->basepose.quat[2] *= -1;
2222                                 }
2223                                 else
2224                                 {
2225                                         p->basepose.quat[0] *=  1;
2226                                         p->basepose.quat[1] *= -1;
2227                                         p->basepose.quat[2] *=  1;
2228                                 }
2229 #endif
2230                                 if (p->parent < 0 || p->parent >= numbones)
2231                                 {
2232                                         Con_Printf("%s: bone->parent %i >= numbones %i\n", loadmodel->name, p->parent, numbones);
2233                                         p->parent = 0;
2234                                 }
2235                         }
2236                         buffer = p;
2237                 }
2238                 else if (!strcmp(pchunk->id, "RAWWEIGHTS"))
2239                 {
2240                         pskrawweights_t *p;
2241                         if (recordsize != sizeof(*p))
2242                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
2243                         // byteswap in place and keep the pointer
2244                         numrawweights = numrecords;
2245                         rawweights = (pskrawweights_t *)buffer;
2246                         for (index = 0, p = (pskrawweights_t *)buffer;index < numrecords;index++, p++)
2247                         {
2248                                 p->weight = LittleFloat(p->weight);
2249                                 p->pntsindex = LittleLong(p->pntsindex);
2250                                 p->boneindex = LittleLong(p->boneindex);
2251                                 if (p->pntsindex < 0 || p->pntsindex >= numpnts)
2252                                 {
2253                                         Con_Printf("%s: weight->pntsindex %i >= numpnts %i\n", loadmodel->name, p->pntsindex, numpnts);
2254                                         p->pntsindex = 0;
2255                                 }
2256                                 if (p->boneindex < 0 || p->boneindex >= numbones)
2257                                 {
2258                                         Con_Printf("%s: weight->boneindex %i >= numbones %i\n", loadmodel->name, p->boneindex, numbones);
2259                                         p->boneindex = 0;
2260                                 }
2261                         }
2262                         buffer = p;
2263                 }
2264         }
2265
2266         while (animbuffer < animbufferend)
2267         {
2268                 pchunk = (pskchunk_t *)animbuffer;
2269                 animbuffer = (void *)((unsigned char *)animbuffer + sizeof(pskchunk_t));
2270                 version = LittleLong(pchunk->version);
2271                 recordsize = LittleLong(pchunk->recordsize);
2272                 numrecords = LittleLong(pchunk->numrecords);
2273                 if (developer.integer >= 100)
2274                         Con_Printf("%s: %s %x: %i * %i = %i\n", animname, pchunk->id, version, recordsize, numrecords, recordsize * numrecords);
2275                 if (version != 0x1e83b9 && version != 0x1e9179 && version != 0x2e && version != 0x12f2bc && version != 0x12f2f0)
2276                         Con_Printf ("%s: chunk %s has unknown version %x (0x1e83b9, 0x1e9179, 0x2e, 0x12f2bc, 0x12f2f0 are currently supported), trying to load anyway!\n", animname, pchunk->id, version);
2277                 if (!strcmp(pchunk->id, "ANIMHEAD"))
2278                 {
2279                         // nothing to do
2280                 }
2281                 else if (!strcmp(pchunk->id, "BONENAMES"))
2282                 {
2283                         pskboneinfo_t *p;
2284                         if (recordsize != sizeof(*p))
2285                                 Host_Error("%s: %s has unsupported recordsize", animname, pchunk->id);
2286                         // byteswap in place and keep the pointer
2287                         numanimbones = numrecords;
2288                         animbones = (pskboneinfo_t *)animbuffer;
2289                         // NOTE: supposedly psa does not need to match the psk model, the
2290                         // bones missing from the psa would simply use their base
2291                         // positions from the psk, but this is hard for me to implement
2292                         // and people can easily make animations that match.
2293                         if (numanimbones != numbones)
2294                                 Host_Error("%s: this loader only supports animations with the same bones as the mesh", loadmodel->name);
2295                         for (index = 0, p = (pskboneinfo_t *)animbuffer;index < numrecords;index++, p++)
2296                         {
2297                                 p->numchildren = LittleLong(p->numchildren);
2298                                 p->parent = LittleLong(p->parent);
2299                                 p->basepose.quat[0] = LittleFloat(p->basepose.quat[0]);
2300                                 p->basepose.quat[1] = LittleFloat(p->basepose.quat[1]);
2301                                 p->basepose.quat[2] = LittleFloat(p->basepose.quat[2]);
2302                                 p->basepose.quat[3] = LittleFloat(p->basepose.quat[3]);
2303                                 p->basepose.origin[0] = LittleFloat(p->basepose.origin[0]);
2304                                 p->basepose.origin[1] = LittleFloat(p->basepose.origin[1]);
2305                                 p->basepose.origin[2] = LittleFloat(p->basepose.origin[2]);
2306                                 p->basepose.unknown = LittleFloat(p->basepose.unknown);
2307                                 p->basepose.size[0] = LittleFloat(p->basepose.size[0]);
2308                                 p->basepose.size[1] = LittleFloat(p->basepose.size[1]);
2309                                 p->basepose.size[2] = LittleFloat(p->basepose.size[2]);
2310 #ifdef PSKQUATNEGATIONS
2311                                 if (index)
2312                                 {
2313                                         p->basepose.quat[0] *= -1;
2314                                         p->basepose.quat[1] *= -1;
2315                                         p->basepose.quat[2] *= -1;
2316                                 }
2317                                 else
2318                                 {
2319                                         p->basepose.quat[0] *=  1;
2320                                         p->basepose.quat[1] *= -1;
2321                                         p->basepose.quat[2] *=  1;
2322                                 }
2323 #endif
2324                                 if (p->parent < 0 || p->parent >= numanimbones)
2325                                 {
2326                                         Con_Printf("%s: bone->parent %i >= numanimbones %i\n", animname, p->parent, numanimbones);
2327                                         p->parent = 0;
2328                                 }
2329                                 // check that bones are the same as in the base
2330                                 if (strcmp(p->name, bones[index].name) || p->parent != bones[index].parent)
2331                                         Host_Error("%s: this loader only supports animations with the same bones as the mesh", animname);
2332                         }
2333                         animbuffer = p;
2334                 }
2335                 else if (!strcmp(pchunk->id, "ANIMINFO"))
2336                 {
2337                         pskaniminfo_t *p;
2338                         if (recordsize != sizeof(*p))
2339                                 Host_Error("%s: %s has unsupported recordsize", animname, pchunk->id);
2340                         // byteswap in place and keep the pointer
2341                         numanims = numrecords;
2342                         anims = (pskaniminfo_t *)animbuffer;
2343                         for (index = 0, p = (pskaniminfo_t *)animbuffer;index < numrecords;index++, p++)
2344                         {
2345                                 p->numbones = LittleLong(p->numbones);
2346                                 p->playtime = LittleFloat(p->playtime);
2347                                 p->fps = LittleFloat(p->fps);
2348                                 p->firstframe = LittleLong(p->firstframe);
2349                                 p->numframes = LittleLong(p->numframes);
2350                                 if (p->numbones != numbones)
2351                                         Con_Printf("%s: animinfo->numbones != numbones, trying to load anyway!\n", animname);
2352                         }
2353                         animbuffer = p;
2354                 }
2355                 else if (!strcmp(pchunk->id, "ANIMKEYS"))
2356                 {
2357                         pskanimkeys_t *p;
2358                         if (recordsize != sizeof(*p))
2359                                 Host_Error("%s: %s has unsupported recordsize", animname, pchunk->id);
2360                         numanimkeys = numrecords;
2361                         animkeys = (pskanimkeys_t *)animbuffer;
2362                         for (index = 0, p = (pskanimkeys_t *)animbuffer;index < numrecords;index++, p++)
2363                         {
2364                                 p->origin[0] = LittleFloat(p->origin[0]);
2365                                 p->origin[1] = LittleFloat(p->origin[1]);
2366                                 p->origin[2] = LittleFloat(p->origin[2]);
2367                                 p->quat[0] = LittleFloat(p->quat[0]);
2368                                 p->quat[1] = LittleFloat(p->quat[1]);
2369                                 p->quat[2] = LittleFloat(p->quat[2]);
2370                                 p->quat[3] = LittleFloat(p->quat[3]);
2371                                 p->frametime = LittleFloat(p->frametime);
2372 #ifdef PSKQUATNEGATIONS
2373                                 if (index % numbones)
2374                                 {
2375                                         p->quat[0] *= -1;
2376                                         p->quat[1] *= -1;
2377                                         p->quat[2] *= -1;
2378                                 }
2379                                 else
2380                                 {
2381                                         p->quat[0] *=  1;
2382                                         p->quat[1] *= -1;
2383                                         p->quat[2] *=  1;
2384                                 }
2385 #endif
2386                         }
2387                         animbuffer = p;
2388                         // TODO: allocate bonepose stuff
2389                 }
2390                 else
2391                         Con_Printf("%s: unknown chunk ID \"%s\"\n", animname, pchunk->id);
2392         }
2393
2394         if (!numpnts || !pnts || !numvtxw || !vtxw || !numfaces || !faces || !nummatts || !matts || !numbones || !bones || !numrawweights || !rawweights || !numanims || !anims || !numanimkeys || !animkeys)
2395                 Host_Error("%s: missing required chunks", loadmodel->name);
2396
2397         loadmodel->numframes = 0;
2398         for (index = 0;index < numanims;index++)
2399                 loadmodel->numframes += anims[index].numframes;
2400
2401         if (numanimkeys != numbones * loadmodel->numframes)
2402                 Host_Error("%s: %s has incorrect number of animation keys", animname, pchunk->id);
2403
2404         meshvertices = numvtxw;
2405         meshtriangles = numfaces;
2406
2407         // load external .skin files if present
2408         skinfiles = Mod_LoadSkinFiles();
2409         if (loadmodel->numskins < 1)
2410                 loadmodel->numskins = 1;
2411         loadmodel->num_bones = numbones;
2412         loadmodel->num_poses = loadmodel->num_bones * loadmodel->numframes;
2413         loadmodel->num_textures = loadmodel->nummodelsurfaces = loadmodel->num_surfaces = nummatts;
2414         // do most allocations as one merged chunk
2415         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + meshtriangles * sizeof(int[3]) + meshtriangles * sizeof(int[3]) + meshvertices * (sizeof(float[14]) + sizeof(int[4]) + sizeof(float[4])) + loadmodel->num_poses * sizeof(float[12]) + loadmodel->num_bones * sizeof(float[12]) + loadmodel->numskins * sizeof(animscene_t) + loadmodel->num_bones * sizeof(aliasbone_t) + loadmodel->numframes * sizeof(animscene_t));
2416         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
2417         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
2418         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
2419         loadmodel->surfmesh.num_vertices = meshvertices;
2420         loadmodel->surfmesh.num_triangles = meshtriangles;
2421         loadmodel->surfmesh.data_element3i = (int *)data;data += meshtriangles * sizeof(int[3]);
2422         loadmodel->surfmesh.data_neighbor3i = (int *)data;data += meshtriangles * sizeof(int[3]);
2423         loadmodel->surfmesh.data_vertex3f = (float *)data;data += meshvertices * sizeof(float[3]);
2424         loadmodel->surfmesh.data_svector3f = (float *)data;data += meshvertices * sizeof(float[3]);
2425         loadmodel->surfmesh.data_tvector3f = (float *)data;data += meshvertices * sizeof(float[3]);
2426         loadmodel->surfmesh.data_normal3f = (float *)data;data += meshvertices * sizeof(float[3]);
2427         loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += meshvertices * sizeof(float[2]);
2428         loadmodel->surfmesh.data_vertexweightindex4i = (int *)data;data += meshvertices * sizeof(int[4]);
2429         loadmodel->surfmesh.data_vertexweightinfluence4f = (float *)data;data += meshvertices * sizeof(float[4]);
2430         loadmodel->data_poses = (float *)data;data += loadmodel->num_poses * sizeof(float[12]);
2431         loadmodel->data_baseboneposeinverse = (float *)data;data += loadmodel->num_bones * sizeof(float[12]);
2432         loadmodel->skinscenes = (animscene_t *)data;data += loadmodel->numskins * sizeof(animscene_t);
2433         loadmodel->data_bones = (aliasbone_t *)data;data += loadmodel->num_bones * sizeof(aliasbone_t);
2434         loadmodel->animscenes = (animscene_t *)data;data += loadmodel->numframes * sizeof(animscene_t);
2435
2436         for (i = 0;i < loadmodel->numskins;i++)
2437         {
2438                 loadmodel->skinscenes[i].firstframe = i;
2439                 loadmodel->skinscenes[i].framecount = 1;
2440                 loadmodel->skinscenes[i].loop = true;
2441                 loadmodel->skinscenes[i].framerate = 10;
2442         }
2443
2444         // create surfaces
2445         for (index = 0, i = 0;index < nummatts;index++)
2446         {
2447                 // since psk models do not have named sections, reuse their shader name as the section name
2448                 if (matts[index].name[0])
2449                         Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + index, skinfiles, matts[index].name, matts[index].name);
2450                 else
2451                         for (j = 0;j < loadmodel->numskins;j++)
2452                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + index + j * loadmodel->num_surfaces, NULL);
2453                 loadmodel->surfacelist[index] = index;
2454                 loadmodel->data_surfaces[index].texture = loadmodel->data_textures + index;
2455                 loadmodel->data_surfaces[index].num_firstvertex = 0;
2456                 loadmodel->data_surfaces[index].num_vertices = loadmodel->surfmesh.num_vertices;
2457         }
2458
2459         // copy over the vertex locations and texcoords
2460         for (index = 0;index < numvtxw;index++)
2461         {
2462                 loadmodel->surfmesh.data_vertex3f[index*3+0] = pnts[vtxw[index].pntsindex].origin[0];
2463                 loadmodel->surfmesh.data_vertex3f[index*3+1] = pnts[vtxw[index].pntsindex].origin[1];
2464                 loadmodel->surfmesh.data_vertex3f[index*3+2] = pnts[vtxw[index].pntsindex].origin[2];
2465                 loadmodel->surfmesh.data_texcoordtexture2f[index*2+0] = vtxw[index].texcoord[0];
2466                 loadmodel->surfmesh.data_texcoordtexture2f[index*2+1] = vtxw[index].texcoord[1];
2467         }
2468
2469         // loading the faces is complicated because we need to sort them into surfaces by mattindex
2470         for (index = 0;index < numfaces;index++)
2471                 loadmodel->data_surfaces[faces[index].mattindex].num_triangles++;
2472         for (index = 0, i = 0;index < nummatts;index++)
2473         {
2474                 loadmodel->data_surfaces[index].num_firsttriangle = i;
2475                 i += loadmodel->data_surfaces[index].num_triangles;
2476                 loadmodel->data_surfaces[index].num_triangles = 0;
2477         }
2478         for (index = 0;index < numfaces;index++)
2479         {
2480                 i = (loadmodel->data_surfaces[faces[index].mattindex].num_firsttriangle + loadmodel->data_surfaces[faces[index].mattindex].num_triangles++)*3;
2481                 loadmodel->surfmesh.data_element3i[i+0] = faces[index].vtxwindex[0];
2482                 loadmodel->surfmesh.data_element3i[i+1] = faces[index].vtxwindex[1];
2483                 loadmodel->surfmesh.data_element3i[i+2] = faces[index].vtxwindex[2];
2484         }
2485
2486         // copy over the bones
2487         for (index = 0;index < numbones;index++)
2488         {
2489                 strlcpy(loadmodel->data_bones[index].name, bones[index].name, sizeof(loadmodel->data_bones[index].name));
2490                 loadmodel->data_bones[index].parent = (index || bones[index].parent > 0) ? bones[index].parent : -1;
2491                 if (loadmodel->data_bones[index].parent >= index)
2492                         Host_Error("%s bone[%i].parent >= %i", loadmodel->name, index, index);
2493         }
2494
2495         // sort the psk point weights into the vertex weight tables
2496         // (which only accept up to 4 bones per vertex)
2497         for (index = 0;index < numvtxw;index++)
2498         {
2499                 int l;
2500                 float sum;
2501                 for (j = 0;j < numrawweights;j++)
2502                 {
2503                         if (rawweights[j].pntsindex == vtxw[index].pntsindex)
2504                         {
2505                                 int boneindex = rawweights[j].boneindex;
2506                                 float influence = rawweights[j].weight;
2507                                 for (l = 0;l < 4;l++)
2508                                 {
2509                                         if (loadmodel->surfmesh.data_vertexweightinfluence4f[index*4+l] < influence)
2510                                         {
2511                                                 // move lower influence weights out of the way first
2512                                                 int l2;
2513                                                 for (l2 = 3;l2 > l;l2--)
2514                                                 {
2515                                                         loadmodel->surfmesh.data_vertexweightinfluence4f[index*4+l2] = loadmodel->surfmesh.data_vertexweightinfluence4f[index*4+l2-1];
2516                                                         loadmodel->surfmesh.data_vertexweightindex4i[index*4+l2] = loadmodel->surfmesh.data_vertexweightindex4i[index*4+l2-1];
2517                                                 }
2518                                                 // store the new weight
2519                                                 loadmodel->surfmesh.data_vertexweightinfluence4f[index*4+l] = influence;
2520                                                 loadmodel->surfmesh.data_vertexweightindex4i[index*4+l] = boneindex;
2521                                                 break;
2522                                         }
2523                                 }
2524                         }
2525                 }
2526                 sum = 0;
2527                 for (l = 0;l < 4;l++)
2528                         sum += loadmodel->surfmesh.data_vertexweightinfluence4f[index*4+l];
2529                 if (sum && fabs(sum - 1) > (1.0f / 256.0f))
2530                 {
2531                         float f = 1.0f / sum;
2532                         for (l = 0;l < 4;l++)
2533                                 loadmodel->surfmesh.data_vertexweightinfluence4f[index*4+l] *= f;
2534                 }
2535         }
2536
2537         // set up the animscenes based on the anims
2538         for (index = 0, i = 0;index < numanims;index++)
2539         {
2540                 for (j = 0;j < anims[index].numframes;j++, i++)
2541                 {
2542                         dpsnprintf(loadmodel->animscenes[i].name, sizeof(loadmodel->animscenes[i].name), "%s_%d", anims[index].name, j);
2543                         loadmodel->animscenes[i].firstframe = i;
2544                         loadmodel->animscenes[i].framecount = 1;
2545                         loadmodel->animscenes[i].loop = true;
2546                         loadmodel->animscenes[i].framerate = 10;
2547                 }
2548         }
2549
2550         // load the poses from the animkeys
2551         for (index = 0;index < numanimkeys;index++)
2552         {
2553                 pskanimkeys_t *k = animkeys + index;
2554                 matrix4x4_t matrix;
2555                 Matrix4x4_FromOriginQuat(&matrix, k->origin[0], k->origin[1], k->origin[2], k->quat[0], k->quat[1], k->quat[2], k->quat[3]);
2556                 Matrix4x4_ToArray12FloatD3D(&matrix, loadmodel->data_poses + index*12);
2557         }
2558         Mod_FreeSkinFiles(skinfiles);
2559         Mem_Free(animfilebuffer);
2560
2561         // compute all the mesh information that was not loaded from the file
2562         // TODO: honor smoothing groups somehow?
2563         Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
2564         Mod_BuildBaseBonePoses();
2565         Mod_BuildNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_normal3f, true);
2566         Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, true);
2567         Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
2568         Mod_Alias_CalculateBoundingBox();
2569
2570         loadmodel->surfmesh.isanimated = loadmodel->numframes > 1 || loadmodel->animscenes[0].framecount > 1;
2571 }
2572