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