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