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