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