833fbe2e9a6ef25d8c08e08a28cfbb9054718f76
[xonotic/darkplaces.git] / model_alias.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20
21 #include "quakedef.h"
22 #include "image.h"
23 #include "r_shadow.h"
24
25 cvar_t r_skeletal_debugbone = {0, "r_skeletal_debugbone", "-1", "development cvar for testing skeletal model code"};
26 cvar_t r_skeletal_debugbonecomponent = {0, "r_skeletal_debugbonecomponent", "3", "development cvar for testing skeletal model code"};
27 cvar_t r_skeletal_debugbonevalue = {0, "r_skeletal_debugbonevalue", "100", "development cvar for testing skeletal model code"};
28 cvar_t r_skeletal_debugtranslatex = {0, "r_skeletal_debugtranslatex", "1", "development cvar for testing skeletal model code"};
29 cvar_t r_skeletal_debugtranslatey = {0, "r_skeletal_debugtranslatey", "1", "development cvar for testing skeletal model code"};
30 cvar_t r_skeletal_debugtranslatez = {0, "r_skeletal_debugtranslatez", "1", "development cvar for testing skeletal model code"};
31
32 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->nummeshes;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 = 1;
510         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + sizeof(surfmesh_t *) + 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         loadmodel->meshlist[0] = (surfmesh_t *)data;data += sizeof(surfmesh_t);
515         loadmodel->surfacelist[0] = 0;
516
517         loadmodel->numskins = LittleLong(pinmodel->numskins);
518         BOUNDI(loadmodel->numskins,0,65536);
519         skinwidth = LittleLong (pinmodel->skinwidth);
520         BOUNDI(skinwidth,0,65536);
521         skinheight = LittleLong (pinmodel->skinheight);
522         BOUNDI(skinheight,0,65536);
523         numverts = LittleLong(pinmodel->numverts);
524         BOUNDI(numverts,0,65536);
525         loadmodel->meshlist[0]->num_triangles = LittleLong(pinmodel->numtris);
526         BOUNDI(loadmodel->meshlist[0]->num_triangles,0,65536);
527         loadmodel->numframes = LittleLong(pinmodel->numframes);
528         BOUNDI(loadmodel->numframes,0,65536);
529         loadmodel->synctype = (synctype_t)LittleLong (pinmodel->synctype);
530         BOUNDI(loadmodel->synctype,0,2);
531         loadmodel->flags = LittleLong (pinmodel->flags);
532
533         for (i = 0;i < 3;i++)
534         {
535                 scale[i] = LittleFloat (pinmodel->scale[i]);
536                 translate[i] = LittleFloat (pinmodel->scale_origin[i]);
537         }
538
539         startskins = datapointer;
540         totalskins = 0;
541         for (i = 0;i < loadmodel->numskins;i++)
542         {
543                 pinskintype = (daliasskintype_t *)datapointer;
544                 datapointer += sizeof(daliasskintype_t);
545                 if (LittleLong(pinskintype->type) == ALIAS_SKIN_SINGLE)
546                         groupskins = 1;
547                 else
548                 {
549                         pinskingroup = (daliasskingroup_t *)datapointer;
550                         datapointer += sizeof(daliasskingroup_t);
551                         groupskins = LittleLong(pinskingroup->numskins);
552                         datapointer += sizeof(daliasskininterval_t) * groupskins;
553                 }
554
555                 for (j = 0;j < groupskins;j++)
556                 {
557                         datapointer += skinwidth * skinheight;
558                         totalskins++;
559                 }
560         }
561
562         pinstverts = (stvert_t *)datapointer;
563         datapointer += sizeof(stvert_t) * numverts;
564
565         pintriangles = (dtriangle_t *)datapointer;
566         datapointer += sizeof(dtriangle_t) * loadmodel->meshlist[0]->num_triangles;
567
568         startframes = datapointer;
569         loadmodel->meshlist[0]->num_morphframes = 0;
570         for (i = 0;i < loadmodel->numframes;i++)
571         {
572                 pinframetype = (daliasframetype_t *)datapointer;
573                 datapointer += sizeof(daliasframetype_t);
574                 if (LittleLong (pinframetype->type) == ALIAS_SINGLE)
575                         groupframes = 1;
576                 else
577                 {
578                         pinframegroup = (daliasgroup_t *)datapointer;
579                         datapointer += sizeof(daliasgroup_t);
580                         groupframes = LittleLong(pinframegroup->numframes);
581                         datapointer += sizeof(daliasinterval_t) * groupframes;
582                 }
583
584                 for (j = 0;j < groupframes;j++)
585                 {
586                         datapointer += sizeof(daliasframe_t);
587                         datapointer += sizeof(trivertx_t) * numverts;
588                         loadmodel->meshlist[0]->num_morphframes++;
589                 }
590         }
591
592         // store texture coordinates into temporary array, they will be stored
593         // after usage is determined (triangle data)
594         vertst = (float *)Mem_Alloc(tempmempool, numverts * 2 * sizeof(float[2]));
595         vertremap = (int *)Mem_Alloc(tempmempool, numverts * 3 * sizeof(int));
596         vertonseam = vertremap + numverts * 2;
597
598         scales = 1.0 / skinwidth;
599         scalet = 1.0 / skinheight;
600         for (i = 0;i < numverts;i++)
601         {
602                 vertonseam[i] = LittleLong(pinstverts[i].onseam);
603                 vertst[i*2+0] = (LittleLong(pinstverts[i].s) + 0.5) * scales;
604                 vertst[i*2+1] = (LittleLong(pinstverts[i].t) + 0.5) * scalet;
605                 vertst[(i+numverts)*2+0] = vertst[i*2+0] + 0.5;
606                 vertst[(i+numverts)*2+1] = vertst[i*2+1];
607         }
608
609 // load triangle data
610         loadmodel->meshlist[0]->data_element3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * loadmodel->meshlist[0]->num_triangles);
611
612         // read the triangle elements
613         for (i = 0;i < loadmodel->meshlist[0]->num_triangles;i++)
614                 for (j = 0;j < 3;j++)
615                         loadmodel->meshlist[0]->data_element3i[i*3+j] = LittleLong(pintriangles[i].vertindex[j]);
616         // validate (note numverts is used because this is the original data)
617         Mod_ValidateElements(loadmodel->meshlist[0]->data_element3i, loadmodel->meshlist[0]->num_triangles, 0, numverts, __FILE__, __LINE__);
618         // now butcher the elements according to vertonseam and tri->facesfront
619         // and then compact the vertex set to remove duplicates
620         for (i = 0;i < loadmodel->meshlist[0]->num_triangles;i++)
621                 if (!LittleLong(pintriangles[i].facesfront)) // backface
622                         for (j = 0;j < 3;j++)
623                                 if (vertonseam[loadmodel->meshlist[0]->data_element3i[i*3+j]])
624                                         loadmodel->meshlist[0]->data_element3i[i*3+j] += numverts;
625         // count the usage
626         // (this uses vertremap to count usage to save some memory)
627         for (i = 0;i < numverts*2;i++)
628                 vertremap[i] = 0;
629         for (i = 0;i < loadmodel->meshlist[0]->num_triangles*3;i++)
630                 vertremap[loadmodel->meshlist[0]->data_element3i[i]]++;
631         // build remapping table and compact array
632         loadmodel->meshlist[0]->num_vertices = 0;
633         for (i = 0;i < numverts*2;i++)
634         {
635                 if (vertremap[i])
636                 {
637                         vertremap[i] = loadmodel->meshlist[0]->num_vertices;
638                         vertst[loadmodel->meshlist[0]->num_vertices*2+0] = vertst[i*2+0];
639                         vertst[loadmodel->meshlist[0]->num_vertices*2+1] = vertst[i*2+1];
640                         loadmodel->meshlist[0]->num_vertices++;
641                 }
642                 else
643                         vertremap[i] = -1; // not used at all
644         }
645         // remap the elements to the new vertex set
646         for (i = 0;i < loadmodel->meshlist[0]->num_triangles * 3;i++)
647                 loadmodel->meshlist[0]->data_element3i[i] = vertremap[loadmodel->meshlist[0]->data_element3i[i]];
648         // store the texture coordinates
649         loadmodel->meshlist[0]->data_texcoordtexture2f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[2]) * loadmodel->meshlist[0]->num_vertices);
650         for (i = 0;i < loadmodel->meshlist[0]->num_vertices;i++)
651         {
652                 loadmodel->meshlist[0]->data_texcoordtexture2f[i*2+0] = vertst[i*2+0];
653                 loadmodel->meshlist[0]->data_texcoordtexture2f[i*2+1] = vertst[i*2+1];
654         }
655
656 // load the frames
657         loadmodel->animscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numframes);
658         loadmodel->meshlist[0]->data_morphvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * loadmodel->meshlist[0]->num_morphframes * loadmodel->meshlist[0]->num_vertices);
659         loadmodel->meshlist[0]->data_neighbor3i = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->meshlist[0]->num_triangles * sizeof(int[3]));
660         Mod_MDL_LoadFrames (startframes, numverts, scale, translate, vertremap);
661         Mod_BuildTriangleNeighbors(loadmodel->meshlist[0]->data_neighbor3i, loadmodel->meshlist[0]->data_element3i, loadmodel->meshlist[0]->num_triangles);
662         Mod_CalcAliasModelBBoxes();
663         Mod_Alias_Mesh_CompileFrameZero(loadmodel->meshlist[0]);
664
665         Mem_Free(vertst);
666         Mem_Free(vertremap);
667
668         // load the skins
669         skinfiles = Mod_LoadSkinFiles();
670         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, loadmodel->numskins * sizeof(animscene_t));
671         loadmodel->num_textures = loadmodel->num_surfaces;
672         loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * totalskins * sizeof(texture_t));
673         if (skinfiles)
674         {
675                 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures, skinfiles, "default", "");
676                 Mod_FreeSkinFiles(skinfiles);
677                 for (i = 0;i < loadmodel->numskins;i++)
678                 {
679                         loadmodel->skinscenes[i].firstframe = i;
680                         loadmodel->skinscenes[i].framecount = 1;
681                         loadmodel->skinscenes[i].loop = true;
682                         loadmodel->skinscenes[i].framerate = 10;
683                 }
684         }
685         else
686         {
687                 totalskins = 0;
688                 datapointer = startskins;
689                 for (i = 0;i < loadmodel->numskins;i++)
690                 {
691                         pinskintype = (daliasskintype_t *)datapointer;
692                         datapointer += sizeof(daliasskintype_t);
693
694                         if (pinskintype->type == ALIAS_SKIN_SINGLE)
695                         {
696                                 groupskins = 1;
697                                 interval = 0.1f;
698                         }
699                         else
700                         {
701                                 pinskingroup = (daliasskingroup_t *)datapointer;
702                                 datapointer += sizeof(daliasskingroup_t);
703
704                                 groupskins = LittleLong (pinskingroup->numskins);
705
706                                 pinskinintervals = (daliasskininterval_t *)datapointer;
707                                 datapointer += sizeof(daliasskininterval_t) * groupskins;
708
709                                 interval = LittleFloat(pinskinintervals[0].interval);
710                                 if (interval < 0.01f)
711                                 {
712                                         Con_Printf("%s has an invalid interval %f, changing to 0.1\n", loadmodel->name, interval);
713                                         interval = 0.1f;
714                                 }
715                         }
716
717                         sprintf(loadmodel->skinscenes[i].name, "skin %i", i);
718                         loadmodel->skinscenes[i].firstframe = totalskins;
719                         loadmodel->skinscenes[i].framecount = groupskins;
720                         loadmodel->skinscenes[i].framerate = 1.0f / interval;
721                         loadmodel->skinscenes[i].loop = true;
722
723                         for (j = 0;j < groupskins;j++)
724                         {
725                                 if (groupskins > 1)
726                                         sprintf (name, "%s_%i_%i", loadmodel->name, i, j);
727                                 else
728                                         sprintf (name, "%s_%i", loadmodel->name, i);
729                                 if (!Mod_LoadSkinFrame(&tempskinframe, name, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PICMIP, true, true))
730                                         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);
731                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + totalskins * loadmodel->num_surfaces, &tempskinframe);
732                                 datapointer += skinwidth * skinheight;
733                                 totalskins++;
734                         }
735                 }
736                 // check for skins that don't exist in the model, but do exist as external images
737                 // (this was added because yummyluv kept pestering me about support for it)
738                 while (Mod_LoadSkinFrame(&tempskinframe, va("%s_%i", loadmodel->name, loadmodel->numskins), (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PICMIP, true, true))
739                 {
740                         // expand the arrays to make room
741                         tempskinscenes = loadmodel->skinscenes;
742                         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, (loadmodel->numskins + 1) * sizeof(animscene_t));
743                         memcpy(loadmodel->skinscenes, tempskinscenes, loadmodel->numskins * sizeof(animscene_t));
744                         Mem_Free(tempskinscenes);
745
746                         tempaliasskins = loadmodel->data_textures;
747                         loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * (totalskins + 1) * sizeof(texture_t));
748                         memcpy(loadmodel->data_textures, tempaliasskins, loadmodel->num_surfaces * totalskins * sizeof(texture_t));
749                         Mem_Free(tempaliasskins);
750
751                         // store the info about the new skin
752                         Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + totalskins * loadmodel->num_surfaces, &tempskinframe);
753                         strcpy(loadmodel->skinscenes[loadmodel->numskins].name, name);
754                         loadmodel->skinscenes[loadmodel->numskins].firstframe = totalskins;
755                         loadmodel->skinscenes[loadmodel->numskins].framecount = 1;
756                         loadmodel->skinscenes[loadmodel->numskins].framerate = 10.0f;
757                         loadmodel->skinscenes[loadmodel->numskins].loop = true;
758
759                         //increase skin counts
760                         loadmodel->numskins++;
761                         totalskins++;
762                 }
763         }
764
765         surface = loadmodel->data_surfaces;
766         surface->texture = loadmodel->data_textures;
767         surface->groupmesh = loadmodel->meshlist[0];
768         surface->num_firsttriangle = 0;
769         surface->num_triangles = surface->groupmesh->num_triangles;
770         surface->num_firstvertex = 0;
771         surface->num_vertices = surface->groupmesh->num_vertices;
772 }
773
774 static void Mod_MD2_ConvertVerts (vec3_t scale, vec3_t translate, trivertx_t *v, float *out3f, int numverts, int *vertremap)
775 {
776         int i;
777         trivertx_t *in;
778         for (i = 0;i < numverts;i++, out3f += 3)
779         {
780                 in = v + vertremap[i];
781                 out3f[0] = in->v[0] * scale[0] + translate[0];
782                 out3f[1] = in->v[1] * scale[1] + translate[1];
783                 out3f[2] = in->v[2] * scale[2] + translate[2];
784         }
785 }
786
787 void Mod_IDP2_Load(model_t *mod, void *buffer, void *bufferend)
788 {
789         int i, j, k, hashindex, num, numxyz, numst, xyz, st, skinwidth, skinheight, *vertremap, version, end, numverts;
790         float *stverts, s, t, scale[3], translate[3];
791         unsigned char *data;
792         msurface_t *surface;
793         md2_t *pinmodel;
794         unsigned char *base, *datapointer;
795         md2frame_t *pinframe;
796         char *inskin;
797         md2triangle_t *intri;
798         unsigned short *inst;
799         struct md2verthash_s
800         {
801                 struct md2verthash_s *next;
802                 int xyz;
803                 float st[2];
804         }
805         *hash, **md2verthash, *md2verthashdata;
806         skinframe_t tempskinframe;
807         skinfile_t *skinfiles;
808
809         pinmodel = (md2_t *)buffer;
810         base = (unsigned char *)buffer;
811
812         version = LittleLong (pinmodel->version);
813         if (version != MD2ALIAS_VERSION)
814                 Host_Error ("%s has wrong version number (%i should be %i)",
815                         loadmodel->name, version, MD2ALIAS_VERSION);
816
817         loadmodel->type = mod_alias;
818         loadmodel->DrawSky = NULL;
819         loadmodel->Draw = R_Q1BSP_Draw;
820         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
821         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
822         loadmodel->DrawLight = R_Q1BSP_DrawLight;
823         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
824
825         if (LittleLong(pinmodel->num_tris) < 1 || LittleLong(pinmodel->num_tris) > 65536)
826                 Host_Error ("%s has invalid number of triangles: %i", loadmodel->name, LittleLong(pinmodel->num_tris));
827         if (LittleLong(pinmodel->num_xyz) < 1 || LittleLong(pinmodel->num_xyz) > 65536)
828                 Host_Error ("%s has invalid number of vertices: %i", loadmodel->name, LittleLong(pinmodel->num_xyz));
829         if (LittleLong(pinmodel->num_frames) < 1 || LittleLong(pinmodel->num_frames) > 65536)
830                 Host_Error ("%s has invalid number of frames: %i", loadmodel->name, LittleLong(pinmodel->num_frames));
831         if (LittleLong(pinmodel->num_skins) < 0 || LittleLong(pinmodel->num_skins) > 256)
832                 Host_Error ("%s has invalid number of skins: %i", loadmodel->name, LittleLong(pinmodel->num_skins));
833
834         end = LittleLong(pinmodel->ofs_end);
835         if (LittleLong(pinmodel->num_skins) >= 1 && (LittleLong(pinmodel->ofs_skins) <= 0 || LittleLong(pinmodel->ofs_skins) >= end))
836                 Host_Error ("%s is not a valid model", loadmodel->name);
837         if (LittleLong(pinmodel->ofs_st) <= 0 || LittleLong(pinmodel->ofs_st) >= end)
838                 Host_Error ("%s is not a valid model", loadmodel->name);
839         if (LittleLong(pinmodel->ofs_tris) <= 0 || LittleLong(pinmodel->ofs_tris) >= end)
840                 Host_Error ("%s is not a valid model", loadmodel->name);
841         if (LittleLong(pinmodel->ofs_frames) <= 0 || LittleLong(pinmodel->ofs_frames) >= end)
842                 Host_Error ("%s is not a valid model", loadmodel->name);
843         if (LittleLong(pinmodel->ofs_glcmds) <= 0 || LittleLong(pinmodel->ofs_glcmds) >= end)
844                 Host_Error ("%s is not a valid model", loadmodel->name);
845
846         loadmodel->num_surfaces = 1;
847         loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
848         loadmodel->nummeshes = 1;
849         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + sizeof(surfmesh_t *) + sizeof(surfmesh_t));
850         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
851         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
852         loadmodel->meshlist = (surfmesh_t **)data;data += loadmodel->num_surfaces * sizeof(surfmesh_t *);
853         loadmodel->meshlist[0] = (surfmesh_t *)data;data += sizeof(surfmesh_t);
854         loadmodel->surfacelist[0] = 0;
855
856         loadmodel->numskins = LittleLong(pinmodel->num_skins);
857         numxyz = LittleLong(pinmodel->num_xyz);
858         numst = LittleLong(pinmodel->num_st);
859         loadmodel->meshlist[0]->num_triangles = LittleLong(pinmodel->num_tris);
860         loadmodel->numframes = LittleLong(pinmodel->num_frames);
861         loadmodel->meshlist[0]->num_morphframes = loadmodel->numframes;
862         loadmodel->animscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, loadmodel->numframes * sizeof(animscene_t));
863
864         loadmodel->flags = 0; // there are no MD2 flags
865         loadmodel->synctype = ST_RAND;
866
867         // load the skins
868         inskin = (char *)(base + LittleLong(pinmodel->ofs_skins));
869         skinfiles = Mod_LoadSkinFiles();
870         if (skinfiles)
871         {
872                 loadmodel->num_textures = loadmodel->num_surfaces;
873                 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
874                 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures, skinfiles, "default", "");
875                 Mod_FreeSkinFiles(skinfiles);
876         }
877         else if (loadmodel->numskins)
878         {
879                 // skins found (most likely not a player model)
880                 loadmodel->num_textures = loadmodel->num_surfaces;
881                 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
882                 for (i = 0;i < loadmodel->numskins;i++, inskin += MD2_SKINNAME)
883                 {
884                         if (Mod_LoadSkinFrame(&tempskinframe, inskin, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, true, true))
885                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i * loadmodel->num_surfaces, &tempskinframe);
886                         else
887                         {
888                                 Con_Printf("%s is missing skin \"%s\"\n", loadmodel->name, inskin);
889                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i * loadmodel->num_surfaces, NULL);
890                         }
891                 }
892         }
893         else
894         {
895                 // no skins (most likely a player model)
896                 loadmodel->numskins = 1;
897                 loadmodel->num_textures = loadmodel->num_surfaces;
898                 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
899                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures, NULL);
900         }
901
902         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
903         for (i = 0;i < loadmodel->numskins;i++)
904         {
905                 loadmodel->skinscenes[i].firstframe = i;
906                 loadmodel->skinscenes[i].framecount = 1;
907                 loadmodel->skinscenes[i].loop = true;
908                 loadmodel->skinscenes[i].framerate = 10;
909         }
910
911         // load the triangles and stvert data
912         inst = (unsigned short *)(base + LittleLong(pinmodel->ofs_st));
913         intri = (md2triangle_t *)(base + LittleLong(pinmodel->ofs_tris));
914         skinwidth = LittleLong(pinmodel->skinwidth);
915         skinheight = LittleLong(pinmodel->skinheight);
916
917         stverts = (float *)Mem_Alloc(tempmempool, numst * sizeof(float[2]));
918         s = 1.0f / skinwidth;
919         t = 1.0f / skinheight;
920         for (i = 0;i < numst;i++)
921         {
922                 j = (unsigned short) LittleShort(inst[i*2+0]);
923                 k = (unsigned short) LittleShort(inst[i*2+1]);
924                 if (j >= skinwidth || k >= skinheight)
925                 {
926                         Con_Printf("%s has an invalid skin coordinate (%i %i) on vert %i, changing to 0 0\n", loadmodel->name, j, k, i);
927                         j = 0;
928                         k = 0;
929                 }
930                 stverts[i*2+0] = j * s;
931                 stverts[i*2+1] = k * t;
932         }
933
934         md2verthash = (struct md2verthash_s **)Mem_Alloc(tempmempool, 256 * sizeof(hash));
935         md2verthashdata = (struct md2verthash_s *)Mem_Alloc(tempmempool, loadmodel->meshlist[0]->num_triangles * 3 * sizeof(*hash));
936         // swap the triangle list
937         num = 0;
938         loadmodel->meshlist[0]->data_element3i = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->meshlist[0]->num_triangles * sizeof(int[3]));
939         for (i = 0;i < loadmodel->meshlist[0]->num_triangles;i++)
940         {
941                 for (j = 0;j < 3;j++)
942                 {
943                         xyz = (unsigned short) LittleShort (intri[i].index_xyz[j]);
944                         st = (unsigned short) LittleShort (intri[i].index_st[j]);
945                         if (xyz >= numxyz)
946                         {
947                                 Con_Printf("%s has an invalid xyz index (%i) on triangle %i, resetting to 0\n", loadmodel->name, xyz, i);
948                                 xyz = 0;
949                         }
950                         if (st >= numst)
951                         {
952                                 Con_Printf("%s has an invalid st index (%i) on triangle %i, resetting to 0\n", loadmodel->name, st, i);
953                                 st = 0;
954                         }
955                         s = stverts[st*2+0];
956                         t = stverts[st*2+1];
957                         hashindex = (xyz * 17 + st) & 255;
958                         for (hash = md2verthash[hashindex];hash;hash = hash->next)
959                                 if (hash->xyz == xyz && hash->st[0] == s && hash->st[1] == t)
960                                         break;
961                         if (hash == NULL)
962                         {
963                                 hash = md2verthashdata + num++;
964                                 hash->xyz = xyz;
965                                 hash->st[0] = s;
966                                 hash->st[1] = t;
967                                 hash->next = md2verthash[hashindex];
968                                 md2verthash[hashindex] = hash;
969                         }
970                         loadmodel->meshlist[0]->data_element3i[i*3+j] = (hash - md2verthashdata);
971                 }
972         }
973
974         Mem_Free(stverts);
975
976         numverts = num;
977         loadmodel->meshlist[0]->num_vertices = numverts;
978         vertremap = (int *)Mem_Alloc(loadmodel->mempool, num * sizeof(int));
979         loadmodel->meshlist[0]->data_texcoordtexture2f = (float *)Mem_Alloc(loadmodel->mempool, num * sizeof(float[2]));
980         for (i = 0;i < num;i++)
981         {
982                 hash = md2verthashdata + i;
983                 vertremap[i] = hash->xyz;
984                 loadmodel->meshlist[0]->data_texcoordtexture2f[i*2+0] = hash->st[0];
985                 loadmodel->meshlist[0]->data_texcoordtexture2f[i*2+1] = hash->st[1];
986         }
987
988         Mem_Free(md2verthash);
989         Mem_Free(md2verthashdata);
990
991         // load the frames
992         datapointer = (base + LittleLong(pinmodel->ofs_frames));
993         loadmodel->meshlist[0]->data_morphvertex3f = (float *)Mem_Alloc(loadmodel->mempool, numverts * loadmodel->meshlist[0]->num_morphframes * sizeof(float[3]));
994         for (i = 0;i < loadmodel->meshlist[0]->num_morphframes;i++)
995         {
996                 pinframe = (md2frame_t *)datapointer;
997                 datapointer += sizeof(md2frame_t);
998                 for (j = 0;j < 3;j++)
999                 {
1000                         scale[j] = LittleFloat(pinframe->scale[j]);
1001                         translate[j] = LittleFloat(pinframe->translate[j]);
1002                 }
1003                 Mod_MD2_ConvertVerts(scale, translate, (trivertx_t *)datapointer, loadmodel->meshlist[0]->data_morphvertex3f + i * numverts * 3, numverts, vertremap);
1004                 datapointer += numxyz * sizeof(trivertx_t);
1005
1006                 strcpy(loadmodel->animscenes[i].name, pinframe->name);
1007                 loadmodel->animscenes[i].firstframe = i;
1008                 loadmodel->animscenes[i].framecount = 1;
1009                 loadmodel->animscenes[i].framerate = 10;
1010                 loadmodel->animscenes[i].loop = true;
1011         }
1012
1013         Mem_Free(vertremap);
1014
1015         loadmodel->meshlist[0]->data_neighbor3i = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->meshlist[0]->num_triangles * sizeof(int[3]));
1016         Mod_BuildTriangleNeighbors(loadmodel->meshlist[0]->data_neighbor3i, loadmodel->meshlist[0]->data_element3i, loadmodel->meshlist[0]->num_triangles);
1017         Mod_CalcAliasModelBBoxes();
1018         Mod_Alias_Mesh_CompileFrameZero(loadmodel->meshlist[0]);
1019
1020         surface = loadmodel->data_surfaces;
1021         surface->groupmesh = loadmodel->meshlist[0];
1022         surface->texture = loadmodel->data_textures;
1023         surface->num_firsttriangle = 0;
1024         surface->num_triangles = surface->groupmesh->num_triangles;
1025         surface->num_firstvertex = 0;
1026         surface->num_vertices = surface->groupmesh->num_vertices;
1027 }
1028
1029 void Mod_IDP3_Load(model_t *mod, void *buffer, void *bufferend)
1030 {
1031         int i, j, k, version, meshvertices, meshtriangles;
1032         unsigned char *data;
1033         msurface_t *surface;
1034         md3modelheader_t *pinmodel;
1035         md3frameinfo_t *pinframe;
1036         md3mesh_t *pinmesh;
1037         md3tag_t *pintag;
1038         skinfile_t *skinfiles;
1039
1040         pinmodel = (md3modelheader_t *)buffer;
1041
1042         if (memcmp(pinmodel->identifier, "IDP3", 4))
1043                 Host_Error ("%s is not a MD3 (IDP3) file", loadmodel->name);
1044         version = LittleLong (pinmodel->version);
1045         if (version != MD3VERSION)
1046                 Host_Error ("%s has wrong version number (%i should be %i)",
1047                         loadmodel->name, version, MD3VERSION);
1048
1049         skinfiles = Mod_LoadSkinFiles();
1050         if (loadmodel->numskins < 1)
1051                 loadmodel->numskins = 1;
1052
1053         loadmodel->type = mod_alias;
1054         loadmodel->DrawSky = NULL;
1055         loadmodel->Draw = R_Q1BSP_Draw;
1056         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
1057         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
1058         loadmodel->DrawLight = R_Q1BSP_DrawLight;
1059         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
1060         loadmodel->flags = LittleLong(pinmodel->flags);
1061         loadmodel->synctype = ST_RAND;
1062
1063         // set up some global info about the model
1064         loadmodel->numframes = LittleLong(pinmodel->num_frames);
1065         loadmodel->num_surfaces = LittleLong(pinmodel->num_meshes);
1066
1067         // make skinscenes for the skins (no groups)
1068         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
1069         for (i = 0;i < loadmodel->numskins;i++)
1070         {
1071                 loadmodel->skinscenes[i].firstframe = i;
1072                 loadmodel->skinscenes[i].framecount = 1;
1073                 loadmodel->skinscenes[i].loop = true;
1074                 loadmodel->skinscenes[i].framerate = 10;
1075         }
1076
1077         // load frameinfo
1078         loadmodel->animscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, loadmodel->numframes * sizeof(animscene_t));
1079         for (i = 0, pinframe = (md3frameinfo_t *)((unsigned char *)pinmodel + LittleLong(pinmodel->lump_frameinfo));i < loadmodel->numframes;i++, pinframe++)
1080         {
1081                 strcpy(loadmodel->animscenes[i].name, pinframe->name);
1082                 loadmodel->animscenes[i].firstframe = i;
1083                 loadmodel->animscenes[i].framecount = 1;
1084                 loadmodel->animscenes[i].framerate = 10;
1085                 loadmodel->animscenes[i].loop = true;
1086         }
1087
1088         // load tags
1089         loadmodel->num_tagframes = loadmodel->numframes;
1090         loadmodel->num_tags = LittleLong(pinmodel->num_tags);
1091         loadmodel->data_tags = (aliastag_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_tagframes * loadmodel->num_tags * sizeof(aliastag_t));
1092         for (i = 0, pintag = (md3tag_t *)((unsigned char *)pinmodel + LittleLong(pinmodel->lump_tags));i < loadmodel->num_tagframes * loadmodel->num_tags;i++, pintag++)
1093         {
1094                 strcpy(loadmodel->data_tags[i].name, pintag->name);
1095                 loadmodel->data_tags[i].matrix = identitymatrix;
1096                 for (j = 0;j < 3;j++)
1097                 {
1098                         for (k = 0;k < 3;k++)
1099                                 loadmodel->data_tags[i].matrix.m[j][k] = LittleFloat(pintag->rotationmatrix[k * 3 + j]);
1100                         loadmodel->data_tags[i].matrix.m[j][3] = LittleFloat(pintag->origin[j]);
1101                 }
1102                 //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);
1103         }
1104
1105         // load meshes
1106         meshvertices = 0;
1107         meshtriangles = 0;
1108         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)))
1109         {
1110                 if (memcmp(pinmesh->identifier, "IDP3", 4))
1111                         Host_Error("Mod_IDP3_Load: invalid mesh identifier (not IDP3)");
1112                 if (LittleLong(pinmesh->num_frames) != loadmodel->numframes)
1113                         Host_Error("Mod_IDP3_Load: mesh numframes differs from header");
1114                 meshvertices += LittleLong(pinmesh->num_vertices);
1115                 meshtriangles += LittleLong(pinmesh->num_triangles);
1116         }
1117
1118         loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
1119         loadmodel->num_textures = loadmodel->num_surfaces;
1120         loadmodel->nummeshes = 1;
1121         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + sizeof(surfmesh_t *) + sizeof(surfmesh_t) + meshtriangles * sizeof(int[6]) + meshvertices * sizeof(float[2]) + meshvertices * loadmodel->numframes * sizeof(float[3]));
1122         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
1123         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
1124         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
1125         loadmodel->meshlist = (surfmesh_t **)data;data += sizeof(surfmesh_t *);
1126         loadmodel->meshlist[0] = (surfmesh_t *)data;data += sizeof(surfmesh_t);
1127         loadmodel->meshlist[0]->num_vertices = meshvertices;
1128         loadmodel->meshlist[0]->num_triangles = meshtriangles;
1129         loadmodel->meshlist[0]->num_morphframes = loadmodel->numframes; // TODO: remove?
1130         loadmodel->meshlist[0]->data_element3i = (int *)data;data += meshtriangles * sizeof(int[3]);
1131         loadmodel->meshlist[0]->data_neighbor3i = (int *)data;data += meshtriangles * sizeof(int[3]);
1132         loadmodel->meshlist[0]->data_texcoordtexture2f = (float *)data;data += meshvertices * sizeof(float[2]);
1133         loadmodel->meshlist[0]->data_morphvertex3f = (float *)data;data += meshvertices * loadmodel->numframes * sizeof(float[3]);
1134
1135         meshvertices = 0;
1136         meshtriangles = 0;
1137         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)))
1138         {
1139                 if (memcmp(pinmesh->identifier, "IDP3", 4))
1140                         Host_Error("Mod_IDP3_Load: invalid mesh identifier (not IDP3)");
1141                 loadmodel->surfacelist[i] = i;
1142                 surface = loadmodel->data_surfaces + i;
1143                 surface->groupmesh = loadmodel->meshlist[0];
1144                 surface->texture = loadmodel->data_textures + i;
1145                 surface->num_firsttriangle = meshtriangles;
1146                 surface->num_triangles = LittleLong(pinmesh->num_triangles);
1147                 surface->num_firstvertex = meshvertices;
1148                 surface->num_vertices = LittleLong(pinmesh->num_vertices);
1149                 meshvertices += surface->num_vertices;
1150                 meshtriangles += surface->num_triangles;
1151
1152                 for (j = 0;j < surface->num_triangles * 3;j++)
1153                         surface->groupmesh->data_element3i[j + surface->num_firsttriangle * 3] = surface->num_firstvertex + LittleLong(((int *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_elements)))[j]);
1154                 for (j = 0;j < surface->num_vertices;j++)
1155                 {
1156                         surface->groupmesh->data_texcoordtexture2f[(j + surface->num_firstvertex) * 2 + 0] = LittleFloat(((float *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_texcoords)))[j * 2 + 0]);
1157                         surface->groupmesh->data_texcoordtexture2f[(j + surface->num_firstvertex) * 2 + 1] = LittleFloat(((float *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_texcoords)))[j * 2 + 1]);
1158                 }
1159                 for (j = 0;j < surface->num_vertices * loadmodel->numframes;j++)
1160                 {
1161                         surface->groupmesh->data_morphvertex3f[(j + surface->num_firstvertex) * 3 + 0] = LittleShort(((short *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_framevertices)))[j * 4 + 0]) * (1.0f / 64.0f);
1162                         surface->groupmesh->data_morphvertex3f[(j + surface->num_firstvertex) * 3 + 1] = LittleShort(((short *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_framevertices)))[j * 4 + 1]) * (1.0f / 64.0f);
1163                         surface->groupmesh->data_morphvertex3f[(j + surface->num_firstvertex) * 3 + 2] = LittleShort(((short *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_framevertices)))[j * 4 + 2]) * (1.0f / 64.0f);
1164                 }
1165
1166                 if (LittleLong(pinmesh->num_shaders) >= 1)
1167                         Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + i, skinfiles, pinmesh->name, ((md3shader_t *)((unsigned char *) pinmesh + LittleLong(pinmesh->lump_shaders)))->name);
1168                 else
1169                         for (j = 0;j < loadmodel->numskins;j++)
1170                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i + j * loadmodel->num_surfaces, NULL);
1171
1172                 Mod_ValidateElements(surface->groupmesh->data_element3i + surface->num_firsttriangle * 3, surface->num_triangles, surface->num_firstvertex, surface->num_vertices, __FILE__, __LINE__);
1173         }
1174         Mod_BuildTriangleNeighbors(loadmodel->meshlist[0]->data_neighbor3i, loadmodel->meshlist[0]->data_element3i, loadmodel->meshlist[0]->num_triangles);
1175         Mod_Alias_Mesh_CompileFrameZero(loadmodel->meshlist[0]);
1176         Mod_CalcAliasModelBBoxes();
1177         Mod_FreeSkinFiles(skinfiles);
1178 }
1179
1180 void Mod_ZYMOTICMODEL_Load(model_t *mod, void *buffer, void *bufferend)
1181 {
1182         zymtype1header_t *pinmodel, *pheader;
1183         unsigned char *pbase;
1184         int i, j, k, l, numposes, meshvertices, meshtriangles, numvertexboneweights, *bonecount, *vertbonecounts, count, *renderlist, *renderlistend, *outelements;
1185         float modelradius, corner[2], *poses, *intexcoord2f, *outtexcoord2f;
1186         zymvertex_t *verts, *vertdata;
1187         zymscene_t *scene;
1188         zymbone_t *bone;
1189         char *shadername;
1190         skinfile_t *skinfiles;
1191         unsigned char *data;
1192         msurface_t *surface;
1193
1194         pinmodel = (zymtype1header_t *)buffer;
1195         pbase = (unsigned char *)buffer;
1196         if (memcmp(pinmodel->id, "ZYMOTICMODEL", 12))
1197                 Host_Error ("Mod_ZYMOTICMODEL_Load: %s is not a zymotic model");
1198         if (BigLong(pinmodel->type) != 1)
1199                 Host_Error ("Mod_ZYMOTICMODEL_Load: only type 1 (skeletal pose) models are currently supported (name = %s)", loadmodel->name);
1200
1201         loadmodel->type = mod_alias;
1202         loadmodel->flags = 0; // there are no flags on zym models
1203         loadmodel->synctype = ST_RAND;
1204
1205         // byteswap header
1206         pheader = pinmodel;
1207         pheader->type = BigLong(pinmodel->type);
1208         pheader->filesize = BigLong(pinmodel->filesize);
1209         pheader->mins[0] = BigFloat(pinmodel->mins[0]);
1210         pheader->mins[1] = BigFloat(pinmodel->mins[1]);
1211         pheader->mins[2] = BigFloat(pinmodel->mins[2]);
1212         pheader->maxs[0] = BigFloat(pinmodel->maxs[0]);
1213         pheader->maxs[1] = BigFloat(pinmodel->maxs[1]);
1214         pheader->maxs[2] = BigFloat(pinmodel->maxs[2]);
1215         pheader->radius = BigFloat(pinmodel->radius);
1216         pheader->numverts = BigLong(pinmodel->numverts);
1217         pheader->numtris = BigLong(pinmodel->numtris);
1218         pheader->numshaders = BigLong(pinmodel->numshaders);
1219         pheader->numbones = BigLong(pinmodel->numbones);
1220         pheader->numscenes = BigLong(pinmodel->numscenes);
1221         pheader->lump_scenes.start = BigLong(pinmodel->lump_scenes.start);
1222         pheader->lump_scenes.length = BigLong(pinmodel->lump_scenes.length);
1223         pheader->lump_poses.start = BigLong(pinmodel->lump_poses.start);
1224         pheader->lump_poses.length = BigLong(pinmodel->lump_poses.length);
1225         pheader->lump_bones.start = BigLong(pinmodel->lump_bones.start);
1226         pheader->lump_bones.length = BigLong(pinmodel->lump_bones.length);
1227         pheader->lump_vertbonecounts.start = BigLong(pinmodel->lump_vertbonecounts.start);
1228         pheader->lump_vertbonecounts.length = BigLong(pinmodel->lump_vertbonecounts.length);
1229         pheader->lump_verts.start = BigLong(pinmodel->lump_verts.start);
1230         pheader->lump_verts.length = BigLong(pinmodel->lump_verts.length);
1231         pheader->lump_texcoords.start = BigLong(pinmodel->lump_texcoords.start);
1232         pheader->lump_texcoords.length = BigLong(pinmodel->lump_texcoords.length);
1233         pheader->lump_render.start = BigLong(pinmodel->lump_render.start);
1234         pheader->lump_render.length = BigLong(pinmodel->lump_render.length);
1235         pheader->lump_shaders.start = BigLong(pinmodel->lump_shaders.start);
1236         pheader->lump_shaders.length = BigLong(pinmodel->lump_shaders.length);
1237         pheader->lump_trizone.start = BigLong(pinmodel->lump_trizone.start);
1238         pheader->lump_trizone.length = BigLong(pinmodel->lump_trizone.length);
1239
1240         if (pheader->numtris < 1 || pheader->numverts < 3 || pheader->numshaders < 1)
1241         {
1242                 Con_Printf("%s has no geometry\n");
1243                 return;
1244         }
1245         if (pheader->numscenes < 1 || pheader->lump_poses.length < (int)sizeof(float[3][4]))
1246         {
1247                 Con_Printf("%s has no animations\n");
1248                 return;
1249         }
1250
1251         loadmodel->DrawSky = NULL;
1252         loadmodel->Draw = R_Q1BSP_Draw;
1253         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
1254         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
1255         loadmodel->DrawLight = R_Q1BSP_DrawLight;
1256         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
1257
1258         loadmodel->numframes = pheader->numscenes;
1259         loadmodel->num_surfaces = pheader->numshaders;
1260
1261         skinfiles = Mod_LoadSkinFiles();
1262         if (loadmodel->numskins < 1)
1263                 loadmodel->numskins = 1;
1264
1265         // make skinscenes for the skins (no groups)
1266         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
1267         for (i = 0;i < loadmodel->numskins;i++)
1268         {
1269                 loadmodel->skinscenes[i].firstframe = i;
1270                 loadmodel->skinscenes[i].framecount = 1;
1271                 loadmodel->skinscenes[i].loop = true;
1272                 loadmodel->skinscenes[i].framerate = 10;
1273         }
1274
1275         // model bbox
1276         modelradius = pheader->radius;
1277         for (i = 0;i < 3;i++)
1278         {
1279                 loadmodel->normalmins[i] = pheader->mins[i];
1280                 loadmodel->normalmaxs[i] = pheader->maxs[i];
1281                 loadmodel->rotatedmins[i] = -modelradius;
1282                 loadmodel->rotatedmaxs[i] = modelradius;
1283         }
1284         corner[0] = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
1285         corner[1] = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
1286         loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
1287         if (loadmodel->yawmaxs[0] > modelradius)
1288                 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelradius;
1289         loadmodel->yawmins[0] = loadmodel->yawmins[1] = -loadmodel->yawmaxs[0];
1290         loadmodel->yawmins[2] = loadmodel->normalmins[2];
1291         loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
1292         loadmodel->radius = modelradius;
1293         loadmodel->radius2 = modelradius * modelradius;
1294
1295         // go through the lumps, swapping things
1296
1297         //zymlump_t lump_scenes; // zymscene_t scene[numscenes]; // name and other information for each scene (see zymscene struct)
1298         loadmodel->animscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numframes);
1299         scene = (zymscene_t *) (pheader->lump_scenes.start + pbase);
1300         numposes = pheader->lump_poses.length / pheader->numbones / sizeof(float[3][4]);
1301         for (i = 0;i < pheader->numscenes;i++)
1302         {
1303                 memcpy(loadmodel->animscenes[i].name, scene->name, 32);
1304                 loadmodel->animscenes[i].firstframe = BigLong(scene->start);
1305                 loadmodel->animscenes[i].framecount = BigLong(scene->length);
1306                 loadmodel->animscenes[i].framerate = BigFloat(scene->framerate);
1307                 loadmodel->animscenes[i].loop = (BigLong(scene->flags) & ZYMSCENEFLAG_NOLOOP) == 0;
1308                 if ((unsigned int) loadmodel->animscenes[i].firstframe >= (unsigned int) numposes)
1309                         Host_Error("%s scene->firstframe (%i) >= numposes (%i)", loadmodel->name, loadmodel->animscenes[i].firstframe, numposes);
1310                 if ((unsigned int) loadmodel->animscenes[i].firstframe + (unsigned int) loadmodel->animscenes[i].framecount > (unsigned int) numposes)
1311                         Host_Error("%s scene->firstframe (%i) + framecount (%i) >= numposes (%i)", loadmodel->name, loadmodel->animscenes[i].firstframe, loadmodel->animscenes[i].framecount, numposes);
1312                 if (loadmodel->animscenes[i].framerate < 0)
1313                         Host_Error("%s scene->framerate (%f) < 0", loadmodel->name, loadmodel->animscenes[i].framerate);
1314                 scene++;
1315         }
1316
1317         //zymlump_t lump_bones; // zymbone_t bone[numbones];
1318         loadmodel->num_bones = pheader->numbones;
1319         loadmodel->data_bones = (aliasbone_t *)Mem_Alloc(loadmodel->mempool, pheader->numbones * sizeof(aliasbone_t));
1320         bone = (zymbone_t *) (pheader->lump_bones.start + pbase);
1321         for (i = 0;i < pheader->numbones;i++)
1322         {
1323                 memcpy(loadmodel->data_bones[i].name, bone[i].name, sizeof(bone[i].name));
1324                 loadmodel->data_bones[i].flags = BigLong(bone[i].flags);
1325                 loadmodel->data_bones[i].parent = BigLong(bone[i].parent);
1326                 if (loadmodel->data_bones[i].parent >= i)
1327                         Host_Error("%s bone[%i].parent >= %i", loadmodel->name, i, i);
1328         }
1329
1330         //zymlump_t lump_vertbonecounts; // int vertbonecounts[numvertices]; // how many bones influence each vertex (separate mainly to make this compress better)
1331         vertbonecounts = (int *)Mem_Alloc(loadmodel->mempool, pheader->numverts * sizeof(int));
1332         bonecount = (int *) (pheader->lump_vertbonecounts.start + pbase);
1333         for (i = 0;i < pheader->numverts;i++)
1334         {
1335                 vertbonecounts[i] = BigLong(bonecount[i]);
1336                 if (vertbonecounts[i] < 1)
1337                         Host_Error("%s bonecount[%i] < 1", loadmodel->name, i);
1338         }
1339
1340         loadmodel->num_poses = pheader->lump_poses.length / sizeof(float[3][4]);
1341
1342         meshvertices = pheader->numverts;
1343         meshtriangles = pheader->numtris;
1344         numvertexboneweights = pheader->lump_verts.length / sizeof(zymvertex_t);
1345
1346         loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
1347         loadmodel->num_textures = loadmodel->num_surfaces;
1348         loadmodel->nummeshes = 1;
1349         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + sizeof(surfmesh_t *) + sizeof(surfmesh_t) + meshtriangles * sizeof(int[6]) + meshvertices * sizeof(float[2]) + numvertexboneweights * sizeof(surfmeshvertexboneweight_t) + loadmodel->num_poses * sizeof(float[3][4]));
1350         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
1351         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
1352         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
1353         loadmodel->meshlist = (surfmesh_t **)data;data += sizeof(surfmesh_t *);
1354         loadmodel->meshlist[0] = (surfmesh_t *)data;data += sizeof(surfmesh_t);
1355         loadmodel->meshlist[0]->num_vertices = meshvertices;
1356         loadmodel->meshlist[0]->num_triangles = meshtriangles;
1357         loadmodel->meshlist[0]->num_vertexboneweights = numvertexboneweights;
1358         loadmodel->meshlist[0]->data_element3i = (int *)data;data += meshtriangles * sizeof(int[3]);
1359         loadmodel->meshlist[0]->data_neighbor3i = (int *)data;data += meshtriangles * sizeof(int[3]);
1360         loadmodel->meshlist[0]->data_texcoordtexture2f = (float *)data;data += meshvertices * sizeof(float[2]);
1361         loadmodel->meshlist[0]->data_vertexboneweights = (surfmeshvertexboneweight_t *)data;data += numvertexboneweights * sizeof(surfmeshvertexboneweight_t);
1362         loadmodel->data_poses = (float *)data;data += loadmodel->num_poses * sizeof(float[3][4]);
1363
1364         //zymlump_t lump_poses; // float pose[numposes][numbones][3][4]; // animation data
1365         poses = (float *) (pheader->lump_poses.start + pbase);
1366         for (i = 0;i < pheader->lump_poses.length / 4;i++)
1367                 loadmodel->data_poses[i] = BigFloat(poses[i]);
1368
1369         //zymlump_t lump_verts; // zymvertex_t vert[numvertices]; // see vertex struct
1370         verts = (zymvertex_t *)Mem_Alloc(loadmodel->mempool, pheader->lump_verts.length);
1371         vertdata = (zymvertex_t *) (pheader->lump_verts.start + pbase);
1372         l = 0;
1373         for (j = 0;j < pheader->numverts;j++)
1374         {
1375                 for (k = 0;k < vertbonecounts[j];k++, l++)
1376                 {
1377                         // this format really should have had a per vertexweight weight value...
1378                         float influence = 1.0f / vertbonecounts[j];
1379                         loadmodel->meshlist[0]->data_vertexboneweights[l].vertexindex = j;
1380                         loadmodel->meshlist[0]->data_vertexboneweights[l].boneindex = BigLong(vertdata[l].bonenum);
1381                         loadmodel->meshlist[0]->data_vertexboneweights[l].origin[0] = BigFloat(vertdata[l].origin[0]) * influence;
1382                         loadmodel->meshlist[0]->data_vertexboneweights[l].origin[1] = BigFloat(vertdata[l].origin[1]) * influence;
1383                         loadmodel->meshlist[0]->data_vertexboneweights[l].origin[2] = BigFloat(vertdata[l].origin[2]) * influence;
1384                         loadmodel->meshlist[0]->data_vertexboneweights[l].origin[3] = influence;
1385                 }
1386         }
1387
1388         //zymlump_t lump_texcoords; // float texcoords[numvertices][2];
1389         outtexcoord2f = loadmodel->meshlist[0]->data_texcoordtexture2f;
1390         intexcoord2f = (float *) (pheader->lump_texcoords.start + pbase);
1391         for (i = 0;i < pheader->numverts;i++)
1392         {
1393                 outtexcoord2f[i*2+0] = BigFloat(intexcoord2f[i*2+0]);
1394                 // flip T coordinate for OpenGL
1395                 outtexcoord2f[i*2+1] = 1 - BigFloat(intexcoord2f[i*2+1]);
1396         }
1397
1398         //zymlump_t lump_trizone; // byte trizone[numtris]; // see trizone explanation
1399         //loadmodel->alias.zymdata_trizone = Mem_Alloc(loadmodel->mempool, pheader->numtris);
1400         //memcpy(loadmodel->alias.zymdata_trizone, (void *) (pheader->lump_trizone.start + pbase), pheader->numtris);
1401
1402         //zymlump_t lump_shaders; // char shadername[numshaders][32]; // shaders used on this model
1403         //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)
1404         // byteswap, validate, and swap winding order of tris
1405         count = pheader->numshaders * sizeof(int) + pheader->numtris * sizeof(int[3]);
1406         if (pheader->lump_render.length != count)
1407                 Host_Error("%s renderlist is wrong size (%i bytes, should be %i bytes)", loadmodel->name, pheader->lump_render.length, count);
1408         renderlist = (int *) (pheader->lump_render.start + pbase);
1409         renderlistend = (int *) ((unsigned char *) renderlist + pheader->lump_render.length);
1410         meshtriangles = 0;
1411         for (i = 0;i < loadmodel->num_surfaces;i++)
1412         {
1413                 int lastvertex;
1414                 if (renderlist >= renderlistend)
1415                         Host_Error("%s corrupt renderlist (wrong size)", loadmodel->name);
1416                 count = BigLong(*renderlist);renderlist++;
1417                 if (renderlist + count * 3 > renderlistend || (i == pheader->numshaders - 1 && renderlist + count * 3 != renderlistend))
1418                         Host_Error("%s corrupt renderlist (wrong size)", loadmodel->name);
1419
1420                 loadmodel->surfacelist[i] = i;
1421                 surface = loadmodel->data_surfaces + i;
1422                 surface->groupmesh = loadmodel->meshlist[0];
1423                 surface->texture = loadmodel->data_textures + i;
1424                 surface->num_firsttriangle = meshtriangles;
1425                 surface->num_triangles = count;
1426                 surface->num_firstvertex = meshvertices;
1427                 surface->num_vertices = meshvertices;
1428
1429                 // load the elements and find the used vertex range
1430                 lastvertex = 0;
1431                 outelements = surface->groupmesh->data_element3i + surface->num_firsttriangle * 3;
1432                 for (j = 0;j < surface->num_triangles;j++)
1433                 {
1434                         outelements[2] = BigLong(renderlist[0]);
1435                         outelements[1] = BigLong(renderlist[1]);
1436                         outelements[0] = BigLong(renderlist[2]);
1437                         if ((unsigned int)outelements[0] >= (unsigned int)pheader->numverts
1438                          || (unsigned int)outelements[1] >= (unsigned int)pheader->numverts
1439                          || (unsigned int)outelements[2] >= (unsigned int)pheader->numverts)
1440                                 Host_Error("%s corrupt renderlist (out of bounds index)", loadmodel->name);
1441                         if (vertbonecounts[outelements[0]] == 0 || vertbonecounts[outelements[1]] == 0 || vertbonecounts[outelements[2]] == 0)
1442                                 Host_Error("%s corrupt renderlist (references vertex with no bone weights", loadmodel->name);
1443                         surface->num_firstvertex = min(surface->num_firstvertex, outelements[0]);
1444                         surface->num_firstvertex = min(surface->num_firstvertex, outelements[1]);
1445                         surface->num_firstvertex = min(surface->num_firstvertex, outelements[2]);
1446                         lastvertex = max(lastvertex, outelements[0]);
1447                         lastvertex = max(lastvertex, outelements[1]);
1448                         lastvertex = max(lastvertex, outelements[2]);
1449                         renderlist += 3;
1450                         outelements += 3;
1451                 }
1452                 surface->num_vertices = lastvertex + 1 - surface->num_firstvertex;
1453
1454                 // since zym models do not have named sections, reuse their shader
1455                 // name as the section name
1456                 shadername = (char *) (pheader->lump_shaders.start + pbase) + i * 32;
1457                 if (shadername[0])
1458                         Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + i, skinfiles, shadername, shadername);
1459                 else
1460                         for (j = 0;j < loadmodel->numskins;j++)
1461                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i + j * loadmodel->num_surfaces, NULL);
1462
1463                 Mod_ValidateElements(surface->groupmesh->data_element3i + surface->num_firsttriangle * 3, surface->num_triangles, surface->num_firstvertex, surface->num_vertices, __FILE__, __LINE__);
1464         }
1465         Mod_BuildTriangleNeighbors(loadmodel->meshlist[0]->data_neighbor3i, loadmodel->meshlist[0]->data_element3i, loadmodel->meshlist[0]->num_triangles);
1466         Mod_Alias_Mesh_CompileFrameZero(loadmodel->meshlist[0]);
1467         Mod_FreeSkinFiles(skinfiles);
1468         Mem_Free(vertbonecounts);
1469         Mem_Free(verts);
1470 }
1471
1472 void Mod_DARKPLACESMODEL_Load(model_t *mod, void *buffer, void *bufferend)
1473 {
1474         dpmheader_t *pheader;
1475         dpmframe_t *frame;
1476         dpmbone_t *bone;
1477         dpmmesh_t *dpmmesh;
1478         unsigned char *pbase;
1479         int i, j, k, meshvertices, meshtriangles, numvertexboneweights;
1480         skinfile_t *skinfiles;
1481         unsigned char *data;
1482
1483         pheader = (dpmheader_t *)buffer;
1484         pbase = (unsigned char *)buffer;
1485         if (memcmp(pheader->id, "DARKPLACESMODEL\0", 16))
1486                 Host_Error ("Mod_DARKPLACESMODEL_Load: %s is not a darkplaces model");
1487         if (BigLong(pheader->type) != 2)
1488                 Host_Error ("Mod_DARKPLACESMODEL_Load: only type 2 (hierarchical skeletal pose) models are currently supported (name = %s)", loadmodel->name);
1489
1490         loadmodel->type = mod_alias;
1491         loadmodel->flags = 0; // there are no flags on zym models
1492         loadmodel->synctype = ST_RAND;
1493
1494         // byteswap header
1495         pheader->type = BigLong(pheader->type);
1496         pheader->filesize = BigLong(pheader->filesize);
1497         pheader->mins[0] = BigFloat(pheader->mins[0]);
1498         pheader->mins[1] = BigFloat(pheader->mins[1]);
1499         pheader->mins[2] = BigFloat(pheader->mins[2]);
1500         pheader->maxs[0] = BigFloat(pheader->maxs[0]);
1501         pheader->maxs[1] = BigFloat(pheader->maxs[1]);
1502         pheader->maxs[2] = BigFloat(pheader->maxs[2]);
1503         pheader->yawradius = BigFloat(pheader->yawradius);
1504         pheader->allradius = BigFloat(pheader->allradius);
1505         pheader->num_bones = BigLong(pheader->num_bones);
1506         pheader->num_meshs = BigLong(pheader->num_meshs);
1507         pheader->num_frames = BigLong(pheader->num_frames);
1508         pheader->ofs_bones = BigLong(pheader->ofs_bones);
1509         pheader->ofs_meshs = BigLong(pheader->ofs_meshs);
1510         pheader->ofs_frames = BigLong(pheader->ofs_frames);
1511
1512         if (pheader->num_bones < 1 || pheader->num_meshs < 1)
1513         {
1514                 Con_Printf("%s has no geometry\n");
1515                 return;
1516         }
1517         if (pheader->num_frames < 1)
1518         {
1519                 Con_Printf("%s has no frames\n");
1520                 return;
1521         }
1522
1523         loadmodel->DrawSky = NULL;
1524         loadmodel->Draw = R_Q1BSP_Draw;
1525         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
1526         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
1527         loadmodel->DrawLight = R_Q1BSP_DrawLight;
1528         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
1529
1530         // model bbox
1531         for (i = 0;i < 3;i++)
1532         {
1533                 loadmodel->normalmins[i] = pheader->mins[i];
1534                 loadmodel->normalmaxs[i] = pheader->maxs[i];
1535                 loadmodel->yawmins[i] = i != 2 ? -pheader->yawradius : pheader->mins[i];
1536                 loadmodel->yawmaxs[i] = i != 2 ? pheader->yawradius : pheader->maxs[i];
1537                 loadmodel->rotatedmins[i] = -pheader->allradius;
1538                 loadmodel->rotatedmaxs[i] = pheader->allradius;
1539         }
1540         loadmodel->radius = pheader->allradius;
1541         loadmodel->radius2 = pheader->allradius * pheader->allradius;
1542
1543         // load external .skin files if present
1544         skinfiles = Mod_LoadSkinFiles();
1545         if (loadmodel->numskins < 1)
1546                 loadmodel->numskins = 1;
1547
1548         meshvertices = 0;
1549         meshtriangles = 0;
1550         numvertexboneweights = 0;
1551
1552         // load the meshes now
1553         dpmmesh = (dpmmesh_t *) (pbase + pheader->ofs_meshs);
1554         for (i = 0;i < loadmodel->num_surfaces;i++)
1555         {
1556                 int numverts = BigLong(dpmmesh->num_verts);
1557                 meshvertices += numverts;;
1558                 meshtriangles += BigLong(dpmmesh->num_tris);
1559
1560                 // to find out how many weights exist we two a two-stage load...
1561                 data = (unsigned char *) (pbase + BigLong(dpmmesh->ofs_verts));
1562                 for (j = 0;j < numverts;j++)
1563                 {
1564                         int numweights = BigLong(((dpmvertex_t *)data)->numbones);
1565                         numvertexboneweights += numweights;
1566                         data += sizeof(dpmvertex_t);
1567                         data += numweights * sizeof(dpmbonevert_t);
1568                 }
1569                 dpmmesh++;
1570         }
1571
1572         loadmodel->numframes = pheader->num_frames;
1573         loadmodel->num_bones = pheader->num_bones;
1574         loadmodel->num_poses = loadmodel->num_bones * loadmodel->numframes;
1575         loadmodel->num_textures = loadmodel->nummodelsurfaces = loadmodel->num_surfaces = pheader->num_meshs;
1576         loadmodel->nummeshes = 1;
1577         // do most allocations as one merged chunk
1578         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + sizeof(surfmesh_t *) + sizeof(surfmesh_t) + meshtriangles * sizeof(int[3]) + meshtriangles * sizeof(int[3]) + meshvertices * sizeof(float[2]) + numvertexboneweights * sizeof(surfmeshvertexboneweight_t) + loadmodel->num_poses * sizeof(float[3][4]) + loadmodel->numskins * sizeof(animscene_t) + loadmodel->num_bones * sizeof(aliasbone_t) + loadmodel->numframes * sizeof(animscene_t));
1579         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
1580         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
1581         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
1582         loadmodel->meshlist = (surfmesh_t **)data;data += sizeof(surfmesh_t *);
1583         loadmodel->meshlist[0] = (surfmesh_t *)data;data += sizeof(surfmesh_t);
1584         loadmodel->meshlist[0]->num_vertices = meshvertices;
1585         loadmodel->meshlist[0]->num_triangles = meshtriangles;
1586         loadmodel->meshlist[0]->num_vertexboneweights = numvertexboneweights;
1587         loadmodel->meshlist[0]->data_element3i = (int *)data;data += meshtriangles * sizeof(int[3]);
1588         loadmodel->meshlist[0]->data_neighbor3i = (int *)data;data += meshtriangles * sizeof(int[3]);
1589         loadmodel->meshlist[0]->data_texcoordtexture2f = (float *)data;data += meshvertices * sizeof(float[2]);
1590         loadmodel->meshlist[0]->data_vertexboneweights = (surfmeshvertexboneweight_t *)data;data += numvertexboneweights * sizeof(surfmeshvertexboneweight_t);
1591         loadmodel->data_poses = (float *)data;data += loadmodel->num_poses * sizeof(float[3][4]);
1592         loadmodel->skinscenes = (animscene_t *)data;data += loadmodel->numskins * sizeof(animscene_t);
1593         loadmodel->data_bones = (aliasbone_t *)data;data += loadmodel->num_bones * sizeof(aliasbone_t);
1594         loadmodel->animscenes = (animscene_t *)data;data += loadmodel->numframes * sizeof(animscene_t);
1595
1596         for (i = 0;i < loadmodel->numskins;i++)
1597         {
1598                 loadmodel->skinscenes[i].firstframe = i;
1599                 loadmodel->skinscenes[i].framecount = 1;
1600                 loadmodel->skinscenes[i].loop = true;
1601                 loadmodel->skinscenes[i].framerate = 10;
1602         }
1603
1604         // load the bone info
1605         bone = (dpmbone_t *) (pbase + pheader->ofs_bones);
1606         for (i = 0;i < loadmodel->num_bones;i++)
1607         {
1608                 memcpy(loadmodel->data_bones[i].name, bone[i].name, sizeof(bone[i].name));
1609                 loadmodel->data_bones[i].flags = BigLong(bone[i].flags);
1610                 loadmodel->data_bones[i].parent = BigLong(bone[i].parent);
1611                 if (loadmodel->data_bones[i].parent >= i)
1612                         Host_Error("%s bone[%i].parent >= %i", loadmodel->name, i, i);
1613         }
1614
1615         // load the frames
1616         frame = (dpmframe_t *) (pbase + pheader->ofs_frames);
1617         for (i = 0;i < loadmodel->numframes;i++)
1618         {
1619                 const float *poses;
1620                 memcpy(loadmodel->animscenes[i].name, frame->name, sizeof(frame->name));
1621                 loadmodel->animscenes[i].firstframe = i;
1622                 loadmodel->animscenes[i].framecount = 1;
1623                 loadmodel->animscenes[i].loop = true;
1624                 loadmodel->animscenes[i].framerate = 10;
1625                 // load the bone poses for this frame
1626                 poses = (float *) (pbase + BigLong(frame->ofs_bonepositions));
1627                 for (j = 0;j < loadmodel->num_bones*12;j++)
1628                         loadmodel->data_poses[i * loadmodel->num_bones*12 + j] = BigFloat(poses[j]);
1629                 // stuff not processed here: mins, maxs, yawradius, allradius
1630                 frame++;
1631         }
1632
1633         // load the meshes now
1634         dpmmesh = (dpmmesh_t *) (pbase + pheader->ofs_meshs);
1635         meshvertices = 0;
1636         meshtriangles = 0;
1637         numvertexboneweights = 0;
1638         for (i = 0;i < loadmodel->num_surfaces;i++, dpmmesh++)
1639         {
1640                 const int *inelements;
1641                 int *outelements;
1642                 const float *intexcoord;
1643                 msurface_t *surface;
1644
1645                 loadmodel->surfacelist[i] = i;
1646                 surface = loadmodel->data_surfaces + i;
1647                 surface->groupmesh = loadmodel->meshlist[0];
1648                 surface->texture = loadmodel->data_textures + i;
1649                 surface->num_firsttriangle = meshtriangles;
1650                 surface->num_triangles = BigLong(dpmmesh->num_tris);
1651                 surface->num_firstvertex = meshvertices;
1652                 surface->num_vertices = BigLong(dpmmesh->num_verts);
1653                 meshvertices += surface->num_vertices;
1654                 meshtriangles += surface->num_triangles;
1655
1656                 inelements = (int *) (pbase + BigLong(dpmmesh->ofs_indices));
1657                 outelements = surface->groupmesh->data_element3i + surface->num_firsttriangle * 3;
1658                 for (j = 0;j < surface->num_triangles;j++)
1659                 {
1660                         // swap element order to flip triangles, because Quake uses clockwise (rare) and dpm uses counterclockwise (standard)
1661                         outelements[0] = surface->num_firstvertex + BigLong(inelements[2]);
1662                         outelements[1] = surface->num_firstvertex + BigLong(inelements[1]);
1663                         outelements[2] = surface->num_firstvertex + BigLong(inelements[0]);
1664                         inelements += 3;
1665                         outelements += 3;
1666                 }
1667
1668                 intexcoord = (float *) (pbase + BigLong(dpmmesh->ofs_texcoords));
1669                 for (j = 0;j < surface->num_vertices*2;j++)
1670                         surface->groupmesh->data_texcoordtexture2f[j + surface->num_firstvertex * 2] = BigFloat(intexcoord[j]);
1671
1672                 data = (unsigned char *) (pbase + BigLong(dpmmesh->ofs_verts));
1673                 for (j = 0;j < surface->num_vertices;j++)
1674                 {
1675                         int numweights = BigLong(((dpmvertex_t *)data)->numbones);
1676                         data += sizeof(dpmvertex_t);
1677                         for (k = 0;k < numweights;k++)
1678                         {
1679                                 const dpmbonevert_t *vert = (dpmbonevert_t *) data;
1680                                 // stuff not processed here: normal
1681                                 surface->groupmesh->data_vertexboneweights[numvertexboneweights].vertexindex = j;
1682                                 surface->groupmesh->data_vertexboneweights[numvertexboneweights].boneindex = BigLong(vert->bonenum);
1683                                 surface->groupmesh->data_vertexboneweights[numvertexboneweights].origin[0] = BigFloat(vert->origin[0]);
1684                                 surface->groupmesh->data_vertexboneweights[numvertexboneweights].origin[1] = BigFloat(vert->origin[1]);
1685                                 surface->groupmesh->data_vertexboneweights[numvertexboneweights].origin[2] = BigFloat(vert->origin[2]);
1686                                 surface->groupmesh->data_vertexboneweights[numvertexboneweights].origin[3] = BigFloat(vert->influence);
1687                                 numvertexboneweights++;
1688                                 data += sizeof(dpmbonevert_t);
1689                         }
1690                 }
1691
1692                 // since dpm models do not have named sections, reuse their shader name as the section name
1693                 if (dpmmesh->shadername[0])
1694                         Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + i, skinfiles, dpmmesh->shadername, dpmmesh->shadername);
1695                 else
1696                         for (j = 0;j < loadmodel->numskins;j++)
1697                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i + j * loadmodel->num_surfaces, NULL);
1698
1699                 Mod_ValidateElements(surface->groupmesh->data_element3i + surface->num_firsttriangle * 3, surface->num_triangles, surface->num_firstvertex, surface->num_vertices, __FILE__, __LINE__);
1700         }
1701         Mod_BuildTriangleNeighbors(loadmodel->meshlist[0]->data_neighbor3i, loadmodel->meshlist[0]->data_element3i, loadmodel->meshlist[0]->num_triangles);
1702         Mod_Alias_Mesh_CompileFrameZero(loadmodel->meshlist[0]);
1703         Mod_FreeSkinFiles(skinfiles);
1704 }
1705
1706 static void Mod_PSKMODEL_AnimKeyToMatrix(float *origin, float *quat, matrix4x4_t *m)
1707 {
1708         float x = quat[0], y = quat[1], z = quat[2], w = quat[3];
1709         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];
1710         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];
1711         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];
1712         m->m[3][0]=  0          ;m->m[3][1]=  0          ;m->m[3][2]=  0          ;m->m[3][3]=1;
1713 }
1714
1715 // no idea why PSK/PSA files contain weird quaternions but they do...
1716 #define PSKQUATNEGATIONS
1717 void Mod_PSKMODEL_Load(model_t *mod, void *buffer, void *bufferend)
1718 {
1719         int i, j, index, version, recordsize, numrecords, meshvertices, meshtriangles, numvertexboneweights;
1720         int numpnts, numvtxw, numfaces, nummatts, numbones, numrawweights, numanimbones, numanims, numanimkeys;
1721         fs_offset_t filesize;
1722         pskpnts_t *pnts;
1723         pskvtxw_t *vtxw;
1724         pskface_t *faces;
1725         pskmatt_t *matts;
1726         pskboneinfo_t *bones;
1727         pskrawweights_t *rawweights;
1728         pskboneinfo_t *animbones;
1729         pskaniminfo_t *anims;
1730         pskanimkeys_t *animkeys;
1731         void *animfilebuffer, *animbuffer, *animbufferend;
1732         unsigned char *data;
1733         pskchunk_t *pchunk;
1734         skinfile_t *skinfiles;
1735         char animname[MAX_QPATH];
1736
1737         pchunk = (pskchunk_t *)buffer;
1738         if (strcmp(pchunk->id, "ACTRHEAD"))
1739                 Host_Error ("Mod_PSKMODEL_Load: %s is not an Unreal Engine ActorX (.psk + .psa) model");
1740
1741         loadmodel->type = mod_alias;
1742         loadmodel->DrawSky = NULL;
1743         loadmodel->Draw = R_Q1BSP_Draw;
1744         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
1745         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
1746         loadmodel->DrawLight = R_Q1BSP_DrawLight;
1747         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
1748         loadmodel->flags = 0; // there are no flags on zym models
1749         loadmodel->synctype = ST_RAND;
1750
1751         FS_StripExtension(loadmodel->name, animname, sizeof(animname));
1752         strlcat(animname, ".psa", sizeof(animname));
1753         animbuffer = animfilebuffer = FS_LoadFile(animname, loadmodel->mempool, false, &filesize);
1754         animbufferend = (void *)((unsigned char*)animbuffer + (int)filesize);
1755         if (animbuffer == NULL)
1756                 Host_Error("%s: can't find .psa file (%s)", loadmodel->name, animname);
1757
1758         numpnts = 0;
1759         pnts = NULL;
1760         numvtxw = 0;
1761         vtxw = NULL;
1762         numfaces = 0;
1763         faces = NULL;
1764         nummatts = 0;
1765         matts = NULL;
1766         numbones = 0;
1767         bones = NULL;
1768         numrawweights = 0;
1769         rawweights = NULL;
1770         numanims = 0;
1771         anims = NULL;
1772         numanimkeys = 0;
1773         animkeys = NULL;
1774
1775         while (buffer < bufferend)
1776         {
1777                 pchunk = (pskchunk_t *)buffer;
1778                 buffer = (void *)((unsigned char *)buffer + sizeof(pskchunk_t));
1779                 version = LittleLong(pchunk->version);
1780                 recordsize = LittleLong(pchunk->recordsize);
1781                 numrecords = LittleLong(pchunk->numrecords);
1782                 if (developer.integer >= 100)
1783                         Con_Printf("%s: %s %x: %i * %i = %i\n", loadmodel->name, pchunk->id, version, recordsize, numrecords, recordsize * numrecords);
1784                 if (version != 0x1e83b9 && version != 0x1e9179 && version != 0x2e && version != 0x12f2bc && version != 0x12f2f0)
1785                         Con_Printf ("%s: chunk %s has unknown version %x (0x1e83b9, 0x1e9179, 0x2e, 0x12f2bc, 0x12f2f0 are currently supported), trying to load anyway!\n", loadmodel->name, pchunk->id, version);
1786                 if (!strcmp(pchunk->id, "ACTRHEAD"))
1787                 {
1788                         // nothing to do
1789                 }
1790                 else if (!strcmp(pchunk->id, "PNTS0000"))
1791                 {
1792                         pskpnts_t *p;
1793                         if (recordsize != sizeof(*p))
1794                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
1795                         // byteswap in place and keep the pointer
1796                         numpnts = numrecords;
1797                         pnts = (pskpnts_t *)buffer;
1798                         for (index = 0, p = (pskpnts_t *)buffer;index < numrecords;index++, p++)
1799                         {
1800                                 p->origin[0] = LittleFloat(p->origin[0]);
1801                                 p->origin[1] = LittleFloat(p->origin[1]);
1802                                 p->origin[2] = LittleFloat(p->origin[2]);
1803                         }
1804                         buffer = p;
1805                 }
1806                 else if (!strcmp(pchunk->id, "VTXW0000"))
1807                 {
1808                         pskvtxw_t *p;
1809                         if (recordsize != sizeof(*p))
1810                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
1811                         // byteswap in place and keep the pointer
1812                         numvtxw = numrecords;
1813                         vtxw = (pskvtxw_t *)buffer;
1814                         for (index = 0, p = (pskvtxw_t *)buffer;index < numrecords;index++, p++)
1815                         {
1816                                 p->pntsindex = LittleShort(p->pntsindex);
1817                                 p->texcoord[0] = LittleFloat(p->texcoord[0]);
1818                                 p->texcoord[1] = LittleFloat(p->texcoord[1]);
1819                                 if (p->pntsindex >= numpnts)
1820                                 {
1821                                         Con_Printf("%s: vtxw->pntsindex %i >= numpnts %i\n", loadmodel->name, p->pntsindex, numpnts);
1822                                         p->pntsindex = 0;
1823                                 }
1824                         }
1825                         buffer = p;
1826                 }
1827                 else if (!strcmp(pchunk->id, "FACE0000"))
1828                 {
1829                         pskface_t *p;
1830                         if (recordsize != sizeof(*p))
1831                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
1832                         // byteswap in place and keep the pointer
1833                         numfaces = numrecords;
1834                         faces = (pskface_t *)buffer;
1835                         for (index = 0, p = (pskface_t *)buffer;index < numrecords;index++, p++)
1836                         {
1837                                 p->vtxwindex[0] = LittleShort(p->vtxwindex[0]);
1838                                 p->vtxwindex[1] = LittleShort(p->vtxwindex[1]);
1839                                 p->vtxwindex[2] = LittleShort(p->vtxwindex[2]);
1840                                 p->group = LittleLong(p->group);
1841                                 if (p->vtxwindex[0] >= numvtxw)
1842                                 {
1843                                         Con_Printf("%s: face->vtxwindex[0] %i >= numvtxw %i\n", loadmodel->name, p->vtxwindex[0], numvtxw);
1844                                         p->vtxwindex[0] = 0;
1845                                 }
1846                                 if (p->vtxwindex[1] >= numvtxw)
1847                                 {
1848                                         Con_Printf("%s: face->vtxwindex[1] %i >= numvtxw %i\n", loadmodel->name, p->vtxwindex[1], numvtxw);
1849                                         p->vtxwindex[1] = 0;
1850                                 }
1851                                 if (p->vtxwindex[2] >= numvtxw)
1852                                 {
1853                                         Con_Printf("%s: face->vtxwindex[2] %i >= numvtxw %i\n", loadmodel->name, p->vtxwindex[2], numvtxw);
1854                                         p->vtxwindex[2] = 0;
1855                                 }
1856                         }
1857                         buffer = p;
1858                 }
1859                 else if (!strcmp(pchunk->id, "MATT0000"))
1860                 {
1861                         pskmatt_t *p;
1862                         if (recordsize != sizeof(*p))
1863                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
1864                         // byteswap in place and keep the pointer
1865                         nummatts = numrecords;
1866                         matts = (pskmatt_t *)buffer;
1867                         for (index = 0, p = (pskmatt_t *)buffer;index < numrecords;index++, p++)
1868                         {
1869                         }
1870                         buffer = p;
1871                 }
1872                 else if (!strcmp(pchunk->id, "REFSKELT"))
1873                 {
1874                         pskboneinfo_t *p;
1875                         if (recordsize != sizeof(*p))
1876                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
1877                         // byteswap in place and keep the pointer
1878                         numbones = numrecords;
1879                         bones = (pskboneinfo_t *)buffer;
1880                         for (index = 0, p = (pskboneinfo_t *)buffer;index < numrecords;index++, p++)
1881                         {
1882                                 p->numchildren = LittleLong(p->numchildren);
1883                                 p->parent = LittleLong(p->parent);
1884                                 p->basepose.quat[0] = LittleFloat(p->basepose.quat[0]);
1885                                 p->basepose.quat[1] = LittleFloat(p->basepose.quat[1]);
1886                                 p->basepose.quat[2] = LittleFloat(p->basepose.quat[2]);
1887                                 p->basepose.quat[3] = LittleFloat(p->basepose.quat[3]);
1888                                 p->basepose.origin[0] = LittleFloat(p->basepose.origin[0]);
1889                                 p->basepose.origin[1] = LittleFloat(p->basepose.origin[1]);
1890                                 p->basepose.origin[2] = LittleFloat(p->basepose.origin[2]);
1891                                 p->basepose.unknown = LittleFloat(p->basepose.unknown);
1892                                 p->basepose.size[0] = LittleFloat(p->basepose.size[0]);
1893                                 p->basepose.size[1] = LittleFloat(p->basepose.size[1]);
1894                                 p->basepose.size[2] = LittleFloat(p->basepose.size[2]);
1895 #ifdef PSKQUATNEGATIONS
1896                                 if (index)
1897                                 {
1898                                         p->basepose.quat[0] *= -1;
1899                                         p->basepose.quat[1] *= -1;
1900                                         p->basepose.quat[2] *= -1;
1901                                 }
1902                                 else
1903                                 {
1904                                         p->basepose.quat[0] *=  1;
1905                                         p->basepose.quat[1] *= -1;
1906                                         p->basepose.quat[2] *=  1;
1907                                 }
1908 #endif
1909                                 if (p->parent < 0 || p->parent >= numbones)
1910                                 {
1911                                         Con_Printf("%s: bone->parent %i >= numbones %i\n", loadmodel->name, p->parent, numbones);
1912                                         p->parent = 0;
1913                                 }
1914                         }
1915                         buffer = p;
1916                 }
1917                 else if (!strcmp(pchunk->id, "RAWWEIGHTS"))
1918                 {
1919                         pskrawweights_t *p;
1920                         if (recordsize != sizeof(*p))
1921                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
1922                         // byteswap in place and keep the pointer
1923                         numrawweights = numrecords;
1924                         rawweights = (pskrawweights_t *)buffer;
1925                         for (index = 0, p = (pskrawweights_t *)buffer;index < numrecords;index++, p++)
1926                         {
1927                                 p->weight = LittleFloat(p->weight);
1928                                 p->pntsindex = LittleLong(p->pntsindex);
1929                                 p->boneindex = LittleLong(p->boneindex);
1930                                 if (p->pntsindex < 0 || p->pntsindex >= numpnts)
1931                                 {
1932                                         Con_Printf("%s: weight->pntsindex %i >= numpnts %i\n", loadmodel->name, p->pntsindex, numpnts);
1933                                         p->pntsindex = 0;
1934                                 }
1935                                 if (p->boneindex < 0 || p->boneindex >= numbones)
1936                                 {
1937                                         Con_Printf("%s: weight->boneindex %i >= numbones %i\n", loadmodel->name, p->boneindex, numbones);
1938                                         p->boneindex = 0;
1939                                 }
1940                         }
1941                         buffer = p;
1942                 }
1943         }
1944
1945         while (animbuffer < animbufferend)
1946         {
1947                 pchunk = (pskchunk_t *)animbuffer;
1948                 animbuffer = (void *)((unsigned char *)animbuffer + sizeof(pskchunk_t));
1949                 version = LittleLong(pchunk->version);
1950                 recordsize = LittleLong(pchunk->recordsize);
1951                 numrecords = LittleLong(pchunk->numrecords);
1952                 if (developer.integer >= 100)
1953                         Con_Printf("%s: %s %x: %i * %i = %i\n", animname, pchunk->id, version, recordsize, numrecords, recordsize * numrecords);
1954                 if (version != 0x1e83b9 && version != 0x1e9179 && version != 0x2e && version != 0x12f2bc && version != 0x12f2f0)
1955                         Con_Printf ("%s: chunk %s has unknown version %x (0x1e83b9, 0x1e9179, 0x2e, 0x12f2bc, 0x12f2f0 are currently supported), trying to load anyway!\n", animname, pchunk->id, version);
1956                 if (!strcmp(pchunk->id, "ANIMHEAD"))
1957                 {
1958                         // nothing to do
1959                 }
1960                 else if (!strcmp(pchunk->id, "BONENAMES"))
1961                 {
1962                         pskboneinfo_t *p;
1963                         if (recordsize != sizeof(*p))
1964                                 Host_Error("%s: %s has unsupported recordsize", animname, pchunk->id);
1965                         // byteswap in place and keep the pointer
1966                         numanimbones = numrecords;
1967                         animbones = (pskboneinfo_t *)animbuffer;
1968                         // NOTE: supposedly psa does not need to match the psk model, the
1969                         // bones missing from the psa would simply use their base
1970                         // positions from the psk, but this is hard for me to implement
1971                         // and people can easily make animations that match.
1972                         if (numanimbones != numbones)
1973                                 Host_Error("%s: this loader only supports animations with the same bones as the mesh");
1974                         for (index = 0, p = (pskboneinfo_t *)animbuffer;index < numrecords;index++, p++)
1975                         {
1976                                 p->numchildren = LittleLong(p->numchildren);
1977                                 p->parent = LittleLong(p->parent);
1978                                 p->basepose.quat[0] = LittleFloat(p->basepose.quat[0]);
1979                                 p->basepose.quat[1] = LittleFloat(p->basepose.quat[1]);
1980                                 p->basepose.quat[2] = LittleFloat(p->basepose.quat[2]);
1981                                 p->basepose.quat[3] = LittleFloat(p->basepose.quat[3]);
1982                                 p->basepose.origin[0] = LittleFloat(p->basepose.origin[0]);
1983                                 p->basepose.origin[1] = LittleFloat(p->basepose.origin[1]);
1984                                 p->basepose.origin[2] = LittleFloat(p->basepose.origin[2]);
1985                                 p->basepose.unknown = LittleFloat(p->basepose.unknown);
1986                                 p->basepose.size[0] = LittleFloat(p->basepose.size[0]);
1987                                 p->basepose.size[1] = LittleFloat(p->basepose.size[1]);
1988                                 p->basepose.size[2] = LittleFloat(p->basepose.size[2]);
1989 #ifdef PSKQUATNEGATIONS
1990                                 if (index)
1991                                 {
1992                                         p->basepose.quat[0] *= -1;
1993                                         p->basepose.quat[1] *= -1;
1994                                         p->basepose.quat[2] *= -1;
1995                                 }
1996                                 else
1997                                 {
1998                                         p->basepose.quat[0] *=  1;
1999                                         p->basepose.quat[1] *= -1;
2000                                         p->basepose.quat[2] *=  1;
2001                                 }
2002 #endif
2003                                 if (p->parent < 0 || p->parent >= numanimbones)
2004                                 {
2005                                         Con_Printf("%s: bone->parent %i >= numanimbones %i\n", animname, p->parent, numanimbones);
2006                                         p->parent = 0;
2007                                 }
2008                                 // check that bones are the same as in the base
2009                                 if (strcmp(p->name, bones[index].name) || p->parent != bones[index].parent)
2010                                         Host_Error("%s: this loader only supports animations with the same bones as the mesh", animname);
2011                         }
2012                         animbuffer = p;
2013                 }
2014                 else if (!strcmp(pchunk->id, "ANIMINFO"))
2015                 {
2016                         pskaniminfo_t *p;
2017                         if (recordsize != sizeof(*p))
2018                                 Host_Error("%s: %s has unsupported recordsize", animname, pchunk->id);
2019                         // byteswap in place and keep the pointer
2020                         numanims = numrecords;
2021                         anims = (pskaniminfo_t *)animbuffer;
2022                         for (index = 0, p = (pskaniminfo_t *)animbuffer;index < numrecords;index++, p++)
2023                         {
2024                                 p->numbones = LittleLong(p->numbones);
2025                                 p->playtime = LittleFloat(p->playtime);
2026                                 p->fps = LittleFloat(p->fps);
2027                                 p->firstframe = LittleLong(p->firstframe);
2028                                 p->numframes = LittleLong(p->numframes);
2029                                 if (p->numbones != numbones)
2030                                 {
2031                                         Con_Printf("%s: animinfo->numbones != numbones, trying to load anyway!\n", animname);
2032                                 }
2033                         }
2034                         animbuffer = p;
2035                 }
2036                 else if (!strcmp(pchunk->id, "ANIMKEYS"))
2037                 {
2038                         pskanimkeys_t *p;
2039                         if (recordsize != sizeof(*p))
2040                                 Host_Error("%s: %s has unsupported recordsize", animname, pchunk->id);
2041                         numanimkeys = numrecords;
2042                         animkeys = (pskanimkeys_t *)animbuffer;
2043                         for (index = 0, p = (pskanimkeys_t *)animbuffer;index < numrecords;index++, p++)
2044                         {
2045                                 p->origin[0] = LittleFloat(p->origin[0]);
2046                                 p->origin[1] = LittleFloat(p->origin[1]);
2047                                 p->origin[2] = LittleFloat(p->origin[2]);
2048                                 p->quat[0] = LittleFloat(p->quat[0]);
2049                                 p->quat[1] = LittleFloat(p->quat[1]);
2050                                 p->quat[2] = LittleFloat(p->quat[2]);
2051                                 p->quat[3] = LittleFloat(p->quat[3]);
2052                                 p->frametime = LittleFloat(p->frametime);
2053 #ifdef PSKQUATNEGATIONS
2054                                 if (index % numbones)
2055                                 {
2056                                         p->quat[0] *= -1;
2057                                         p->quat[1] *= -1;
2058                                         p->quat[2] *= -1;
2059                                 }
2060                                 else
2061                                 {
2062                                         p->quat[0] *=  1;
2063                                         p->quat[1] *= -1;
2064                                         p->quat[2] *=  1;
2065                                 }
2066 #endif
2067                         }
2068                         animbuffer = p;
2069                         // TODO: allocate bonepose stuff
2070                 }
2071                 else
2072                         Con_Printf("%s: unknown chunk ID \"%s\"\n", animname, pchunk->id);
2073         }
2074
2075         if (!numpnts || !pnts || !numvtxw || !vtxw || !numfaces || !faces || !nummatts || !matts || !numbones || !bones || !numrawweights || !rawweights || !numanims || !anims || !numanimkeys || !animkeys)
2076                 Host_Error("%s: missing required chunks", loadmodel->name);
2077
2078         // FIXME: model bbox
2079         // model bbox
2080         for (i = 0;i < 3;i++)
2081         {
2082                 loadmodel->normalmins[i] = -128;
2083                 loadmodel->normalmaxs[i] = 128;
2084                 loadmodel->yawmins[i] = -128;
2085                 loadmodel->yawmaxs[i] = 128;
2086                 loadmodel->rotatedmins[i] = -128;
2087                 loadmodel->rotatedmaxs[i] = 128;
2088         }
2089         loadmodel->radius = 128;
2090         loadmodel->radius2 = loadmodel->radius * loadmodel->radius;
2091
2092         loadmodel->numframes = 0;
2093         for (index = 0;index < numanims;index++)
2094                 loadmodel->numframes += anims[index].numframes;
2095
2096         if (numanimkeys != numbones * loadmodel->numframes)
2097                 Host_Error("%s: %s has incorrect number of animation keys", animname, pchunk->id);
2098
2099         meshvertices = numvtxw;
2100         meshtriangles = numfaces;
2101         numvertexboneweights = 0;
2102         for (index = 0;index < numvtxw;index++)
2103                 for (j = 0;j < numrawweights;j++)
2104                         if (rawweights[j].pntsindex == vtxw[index].pntsindex)
2105                                 numvertexboneweights++;
2106
2107         // load external .skin files if present
2108         skinfiles = Mod_LoadSkinFiles();
2109         if (loadmodel->numskins < 1)
2110                 loadmodel->numskins = 1;
2111         loadmodel->num_bones = numbones;
2112         loadmodel->num_poses = loadmodel->num_bones * loadmodel->numframes;
2113         loadmodel->num_textures = loadmodel->nummodelsurfaces = loadmodel->num_surfaces = nummatts;
2114         loadmodel->nummeshes = 1;
2115         // do most allocations as one merged chunk
2116         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + sizeof(surfmesh_t *) + sizeof(surfmesh_t) + meshtriangles * sizeof(int[3]) + meshtriangles * sizeof(int[3]) + meshvertices * sizeof(float[2]) + numvertexboneweights * sizeof(surfmeshvertexboneweight_t) + loadmodel->num_poses * sizeof(float[3][4]) + loadmodel->numskins * sizeof(animscene_t) + loadmodel->num_bones * sizeof(aliasbone_t) + loadmodel->numframes * sizeof(animscene_t));
2117         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
2118         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
2119         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
2120         loadmodel->meshlist = (surfmesh_t **)data;data += sizeof(surfmesh_t *);
2121         loadmodel->meshlist[0] = (surfmesh_t *)data;data += sizeof(surfmesh_t);
2122         loadmodel->meshlist[0]->num_vertices = meshvertices;
2123         loadmodel->meshlist[0]->num_triangles = meshtriangles;
2124         loadmodel->meshlist[0]->num_vertexboneweights = numvertexboneweights;
2125         loadmodel->meshlist[0]->data_element3i = (int *)data;data += meshtriangles * sizeof(int[3]);
2126         loadmodel->meshlist[0]->data_neighbor3i = (int *)data;data += meshtriangles * sizeof(int[3]);
2127         loadmodel->meshlist[0]->data_texcoordtexture2f = (float *)data;data += meshvertices * sizeof(float[2]);
2128         loadmodel->meshlist[0]->data_vertexboneweights = (surfmeshvertexboneweight_t *)data;data += numvertexboneweights * sizeof(surfmeshvertexboneweight_t);
2129         loadmodel->data_poses = (float *)data;data += loadmodel->num_poses * sizeof(float[3][4]);
2130         loadmodel->skinscenes = (animscene_t *)data;data += loadmodel->numskins * sizeof(animscene_t);
2131         loadmodel->data_bones = (aliasbone_t *)data;data += loadmodel->num_bones * sizeof(aliasbone_t);
2132         loadmodel->animscenes = (animscene_t *)data;data += loadmodel->numframes * sizeof(animscene_t);
2133
2134         for (i = 0;i < loadmodel->numskins;i++)
2135         {
2136                 loadmodel->skinscenes[i].firstframe = i;
2137                 loadmodel->skinscenes[i].framecount = 1;
2138                 loadmodel->skinscenes[i].loop = true;
2139                 loadmodel->skinscenes[i].framerate = 10;
2140         }
2141
2142         // create surfaces
2143         for (index = 0, i = 0;index < nummatts;index++)
2144         {
2145                 // since psk models do not have named sections, reuse their shader name as the section name
2146                 if (matts[index].name[0])
2147                         Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + index, skinfiles, matts[index].name, matts[index].name);
2148                 else
2149                         for (j = 0;j < loadmodel->numskins;j++)
2150                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + index + j * loadmodel->num_surfaces, NULL);
2151                 loadmodel->surfacelist[index] = index;
2152                 loadmodel->data_surfaces[index].groupmesh = loadmodel->meshlist[0];
2153                 loadmodel->data_surfaces[index].texture = loadmodel->data_textures + index;
2154                 loadmodel->data_surfaces[index].num_firstvertex = 0;
2155                 loadmodel->data_surfaces[index].num_vertices = loadmodel->meshlist[0]->num_vertices;
2156         }
2157
2158         // copy over the texcoords
2159         for (index = 0;index < numvtxw;index++)
2160         {
2161                 loadmodel->meshlist[0]->data_texcoordtexture2f[index*2+0] = vtxw[index].texcoord[0];
2162                 loadmodel->meshlist[0]->data_texcoordtexture2f[index*2+1] = vtxw[index].texcoord[1];
2163         }
2164
2165         // loading the faces is complicated because we need to sort them into surfaces by mattindex
2166         for (index = 0;index < numfaces;index++)
2167                 loadmodel->data_surfaces[faces[index].mattindex].num_triangles++;
2168         for (index = 0, i = 0;index < nummatts;index++)
2169         {
2170                 loadmodel->data_surfaces[index].num_firsttriangle = i;
2171                 i += loadmodel->data_surfaces[index].num_triangles;
2172                 loadmodel->data_surfaces[index].num_triangles = 0;
2173         }
2174         for (index = 0;index < numfaces;index++)
2175         {
2176                 i = (loadmodel->data_surfaces[faces[index].mattindex].num_firsttriangle + loadmodel->data_surfaces[faces[index].mattindex].num_triangles++)*3;
2177                 loadmodel->meshlist[0]->data_element3i[i+0] = faces[index].vtxwindex[0];
2178                 loadmodel->meshlist[0]->data_element3i[i+1] = faces[index].vtxwindex[1];
2179                 loadmodel->meshlist[0]->data_element3i[i+2] = faces[index].vtxwindex[2];
2180         }
2181
2182         // copy over the bones
2183         for (index = 0;index < numbones;index++)
2184         {
2185                 strlcpy(loadmodel->data_bones[index].name, bones[index].name, sizeof(loadmodel->data_bones[index].name));
2186                 loadmodel->data_bones[index].parent = (index || bones[index].parent > 0) ? bones[index].parent : -1;
2187                 if (loadmodel->data_bones[index].parent >= index)
2188                         Host_Error("%s bone[%i].parent >= %i", loadmodel->name, index, index);
2189         }
2190
2191         // build bone-relative vertex weights from the psk point weights
2192         numvertexboneweights = 0;
2193         for (index = 0;index < numvtxw;index++)
2194         {
2195                 for (j = 0;j < numrawweights;j++)
2196                 {
2197                         if (rawweights[j].pntsindex == vtxw[index].pntsindex)
2198                         {
2199                                 matrix4x4_t matrix, inversematrix;
2200                                 loadmodel->meshlist[0]->data_vertexboneweights[numvertexboneweights].vertexindex = index;
2201                                 loadmodel->meshlist[0]->data_vertexboneweights[numvertexboneweights].boneindex = rawweights[j].boneindex;
2202                                 loadmodel->meshlist[0]->data_vertexboneweights[numvertexboneweights].weight = rawweights[j].weight;
2203                                 matrix = identitymatrix;
2204                                 for (i = rawweights[j].boneindex;i >= 0;i = loadmodel->data_bones[i].parent)
2205                                 {
2206                                         matrix4x4_t childmatrix, tempmatrix;
2207                                         Mod_PSKMODEL_AnimKeyToMatrix(bones[i].basepose.origin, bones[i].basepose.quat, &tempmatrix);
2208                                         childmatrix = matrix;
2209                                         Matrix4x4_Concat(&matrix, &tempmatrix, &childmatrix);
2210                                 }
2211                                 Matrix4x4_Invert_Simple(&inversematrix, &matrix);
2212                                 Matrix4x4_Transform(&inversematrix, pnts[rawweights[j].pntsindex].origin, loadmodel->meshlist[0]->data_vertexboneweights[numvertexboneweights].origin);
2213                                 VectorScale(loadmodel->meshlist[0]->data_vertexboneweights[numvertexboneweights].origin, loadmodel->meshlist[0]->data_vertexboneweights[numvertexboneweights].weight, loadmodel->meshlist[0]->data_vertexboneweights[numvertexboneweights].origin);
2214                                 numvertexboneweights++;
2215                         }
2216                 }
2217         }
2218
2219         // set up the animscenes based on the anims
2220         for (index = 0, i = 0;index < numanims;index++)
2221         {
2222                 for (j = 0;j < anims[index].numframes;j++, i++)
2223                 {
2224                         dpsnprintf(loadmodel->animscenes[i].name, sizeof(loadmodel->animscenes[i].name), "%s_%d", anims[index].name, j);
2225                         loadmodel->animscenes[i].firstframe = i;
2226                         loadmodel->animscenes[i].framecount = 1;
2227                         loadmodel->animscenes[i].loop = true;
2228                         loadmodel->animscenes[i].framerate = 10;
2229                 }
2230         }
2231
2232         // load the poses from the animkeys
2233         for (index = 0;index < numanimkeys;index++)
2234         {
2235                 matrix4x4_t matrix;
2236                 Mod_PSKMODEL_AnimKeyToMatrix(animkeys[index].origin, animkeys[index].quat, &matrix);
2237                 loadmodel->data_poses[index*12+0] = matrix.m[0][0];
2238                 loadmodel->data_poses[index*12+1] = matrix.m[0][1];
2239                 loadmodel->data_poses[index*12+2] = matrix.m[0][2];
2240                 loadmodel->data_poses[index*12+3] = matrix.m[0][3];
2241                 loadmodel->data_poses[index*12+4] = matrix.m[1][0];
2242                 loadmodel->data_poses[index*12+5] = matrix.m[1][1];
2243                 loadmodel->data_poses[index*12+6] = matrix.m[1][2];
2244                 loadmodel->data_poses[index*12+7] = matrix.m[1][3];
2245                 loadmodel->data_poses[index*12+8] = matrix.m[2][0];
2246                 loadmodel->data_poses[index*12+9] = matrix.m[2][1];
2247                 loadmodel->data_poses[index*12+10] = matrix.m[2][2];
2248                 loadmodel->data_poses[index*12+11] = matrix.m[2][3];
2249         }
2250
2251         // compile extra data we want
2252         Mod_ValidateElements(loadmodel->meshlist[0]->data_element3i, loadmodel->meshlist[0]->num_triangles, 0, loadmodel->meshlist[0]->num_vertices, __FILE__, __LINE__);
2253         Mod_BuildTriangleNeighbors(loadmodel->meshlist[0]->data_neighbor3i, loadmodel->meshlist[0]->data_element3i, loadmodel->meshlist[0]->num_triangles);
2254         Mod_Alias_Mesh_CompileFrameZero(loadmodel->meshlist[0]);
2255         Mod_FreeSkinFiles(skinfiles);
2256
2257         Mem_Free(animfilebuffer);
2258 }
2259