]> icculus.org git repositories - divverent/darkplaces.git/blob - model_shared.c
0ef5f31ee41e76f5370a202e0349c5cc9b23f588
[divverent/darkplaces.git] / model_shared.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 // models.c -- model loading and caching
21
22 // models are the only shared resource between a client and server running
23 // on the same machine.
24
25 #include "quakedef.h"
26 #include "image.h"
27 #include "r_shadow.h"
28
29 model_t *loadmodel;
30
31 // LordHavoc: increased from 512 to 2048
32 #define MAX_MOD_KNOWN   2048
33 static model_t mod_known[MAX_MOD_KNOWN];
34
35 rtexturepool_t *mod_shared_texturepool;
36 rtexture_t *r_notexture;
37 rtexture_t *mod_shared_detailtextures[NUM_DETAILTEXTURES];
38
39 void Mod_BuildDetailTextures (void)
40 {
41         int i, x, y, light;
42         float vc[3], vx[3], vy[3], vn[3], lightdir[3];
43 #define DETAILRESOLUTION 256
44         qbyte data[DETAILRESOLUTION][DETAILRESOLUTION][4], noise[DETAILRESOLUTION][DETAILRESOLUTION];
45         lightdir[0] = 0.5;
46         lightdir[1] = 1;
47         lightdir[2] = -0.25;
48         VectorNormalize(lightdir);
49         for (i = 0;i < NUM_DETAILTEXTURES;i++)
50         {
51                 fractalnoise(&noise[0][0], DETAILRESOLUTION, DETAILRESOLUTION >> 4);
52                 for (y = 0;y < DETAILRESOLUTION;y++)
53                 {
54                         for (x = 0;x < DETAILRESOLUTION;x++)
55                         {
56                                 vc[0] = x;
57                                 vc[1] = y;
58                                 vc[2] = noise[y][x] * (1.0f / 32.0f);
59                                 vx[0] = x + 1;
60                                 vx[1] = y;
61                                 vx[2] = noise[y][(x + 1) % DETAILRESOLUTION] * (1.0f / 32.0f);
62                                 vy[0] = x;
63                                 vy[1] = y + 1;
64                                 vy[2] = noise[(y + 1) % DETAILRESOLUTION][x] * (1.0f / 32.0f);
65                                 VectorSubtract(vx, vc, vx);
66                                 VectorSubtract(vy, vc, vy);
67                                 CrossProduct(vx, vy, vn);
68                                 VectorNormalize(vn);
69                                 light = 128 - DotProduct(vn, lightdir) * 128;
70                                 light = bound(0, light, 255);
71                                 data[y][x][0] = data[y][x][1] = data[y][x][2] = light;
72                                 data[y][x][3] = 255;
73                         }
74                 }
75                 mod_shared_detailtextures[i] = R_LoadTexture2D(mod_shared_texturepool, va("detailtexture%i", i), DETAILRESOLUTION, DETAILRESOLUTION, &data[0][0][0], TEXTYPE_RGBA, TEXF_MIPMAP | TEXF_PRECACHE, NULL);
76         }
77 }
78
79 texture_t r_surf_notexture;
80
81 void Mod_SetupNoTexture(void)
82 {
83         int x, y;
84         qbyte pix[16][16][4];
85
86         // this makes a light grey/dark grey checkerboard texture
87         for (y = 0;y < 16;y++)
88         {
89                 for (x = 0;x < 16;x++)
90                 {
91                         if ((y < 8) ^ (x < 8))
92                         {
93                                 pix[y][x][0] = 128;
94                                 pix[y][x][1] = 128;
95                                 pix[y][x][2] = 128;
96                                 pix[y][x][3] = 255;
97                         }
98                         else
99                         {
100                                 pix[y][x][0] = 64;
101                                 pix[y][x][1] = 64;
102                                 pix[y][x][2] = 64;
103                                 pix[y][x][3] = 255;
104                         }
105                 }
106         }
107
108         r_notexture = R_LoadTexture2D(mod_shared_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_RGBA, TEXF_MIPMAP, NULL);
109 }
110
111 static void mod_start(void)
112 {
113         int i;
114         for (i = 0;i < MAX_MOD_KNOWN;i++)
115                 if (mod_known[i].name[0])
116                         Mod_UnloadModel(&mod_known[i]);
117         Mod_LoadModels();
118
119         mod_shared_texturepool = R_AllocTexturePool();
120         Mod_SetupNoTexture();
121         Mod_BuildDetailTextures();
122 }
123
124 static void mod_shutdown(void)
125 {
126         int i;
127         for (i = 0;i < MAX_MOD_KNOWN;i++)
128                 if (mod_known[i].name[0])
129                         Mod_UnloadModel(&mod_known[i]);
130
131         R_FreeTexturePool(&mod_shared_texturepool);
132 }
133
134 static void mod_newmap(void)
135 {
136 }
137
138 /*
139 ===============
140 Mod_Init
141 ===============
142 */
143 static void Mod_Print (void);
144 void Mod_Init (void)
145 {
146         Mod_BrushInit();
147         Mod_AliasInit();
148         Mod_SpriteInit();
149
150         Cmd_AddCommand ("modellist", Mod_Print);
151 }
152
153 void Mod_RenderInit(void)
154 {
155         R_RegisterModule("Models", mod_start, mod_shutdown, mod_newmap);
156 }
157
158 void Mod_FreeModel (model_t *mod)
159 {
160         R_FreeTexturePool(&mod->texturepool);
161         Mem_FreePool(&mod->mempool);
162
163         // clear the struct to make it available
164         memset(mod, 0, sizeof(model_t));
165 }
166
167 void Mod_UnloadModel (model_t *mod)
168 {
169         char name[MAX_QPATH];
170         qboolean isworldmodel;
171         strcpy(name, mod->name);
172         isworldmodel = mod->isworldmodel;
173         Mod_FreeModel(mod);
174         strcpy(mod->name, name);
175         mod->isworldmodel = isworldmodel;
176         mod->needload = true;
177 }
178
179 /*
180 ==================
181 Mod_LoadModel
182
183 Loads a model
184 ==================
185 */
186 static model_t *Mod_LoadModel (model_t *mod, qboolean crash, qboolean checkdisk, qboolean isworldmodel)
187 {
188         unsigned int crc;
189         void *buf;
190
191         mod->used = true;
192
193         if (mod->name[0] == '*') // submodel
194                 return mod;
195
196         crc = 0;
197         buf = NULL;
198         if (!mod->needload)
199         {
200                 if (checkdisk)
201                 {
202                         buf = FS_LoadFile (mod->name, false);
203                         if (!buf)
204                         {
205                                 if (crash)
206                                         Host_Error ("Mod_LoadModel: %s not found", mod->name); // LordHavoc: Sys_Error was *ANNOYING*
207                                 return NULL;
208                         }
209
210                         crc = CRC_Block(buf, fs_filesize);
211                 }
212                 else
213                         crc = mod->crc;
214
215                 if (mod->crc == crc && mod->isworldmodel == isworldmodel)
216                 {
217                         if (buf)
218                                 Mem_Free(buf);
219                         return mod; // already loaded
220                 }
221         }
222
223         Con_DPrintf("loading model %s\n", mod->name);
224
225         if (!buf)
226         {
227                 buf = FS_LoadFile (mod->name, false);
228                 if (!buf)
229                 {
230                         if (crash)
231                                 Host_Error ("Mod_LoadModel: %s not found", mod->name);
232                         return NULL;
233                 }
234                 crc = CRC_Block(buf, fs_filesize);
235         }
236
237         // allocate a new model
238         loadmodel = mod;
239
240         // LordHavoc: unload the existing model in this slot (if there is one)
241         Mod_UnloadModel(mod);
242         mod->isworldmodel = isworldmodel;
243         mod->needload = false;
244         mod->used = true;
245         mod->crc = crc;
246         // errors can prevent the corresponding mod->error = false;
247         mod->error = true;
248
249         // all models use memory, so allocate a memory pool
250         mod->mempool = Mem_AllocPool(mod->name);
251         // all models load textures, so allocate a texture pool
252         if (cls.state != ca_dedicated)
253                 mod->texturepool = R_AllocTexturePool();
254
255         // call the apropriate loader
256              if (!memcmp(buf, "IDPO"    , 4)) Mod_LoadQ1AliasModel(mod, buf);
257         else if (!memcmp(buf, "IDP2"    , 4)) Mod_LoadQ2AliasModel(mod, buf);
258         else if (!memcmp(buf, "IDP3"    , 4)) Mod_LoadQ3AliasModel(mod, buf);
259         else if (!memcmp(buf, "ZYMOTIC" , 7)) Mod_LoadZymoticModel(mod, buf);
260         else if (!memcmp(buf, "IDSP"    , 4)) Mod_LoadSpriteModel (mod, buf);
261         else if (!memcmp(buf, "IBSP"    , 4)) Mod_LoadBrushModelIBSP (mod, buf);
262         else                                  Mod_LoadBrushModelQ1orHL (mod, buf);
263
264         Mem_Free(buf);
265
266         // no errors occurred
267         mod->error = false;
268         return mod;
269 }
270
271 void Mod_CheckLoaded (model_t *mod)
272 {
273         if (mod)
274         {
275                 if (mod->needload)
276                         Mod_LoadModel(mod, true, true, mod->isworldmodel);
277                 else
278                 {
279                         if (mod->type == mod_invalid)
280                                 Host_Error("Mod_CheckLoaded: invalid model\n");
281                         mod->used = true;
282                         return;
283                 }
284         }
285 }
286
287 /*
288 ===================
289 Mod_ClearAll
290 ===================
291 */
292 void Mod_ClearAll (void)
293 {
294 }
295
296 void Mod_ClearErrorModels (void)
297 {
298         int i;
299         model_t *mod;
300
301         for (i = 0, mod = mod_known;i < MAX_MOD_KNOWN;i++, mod++)
302                 if (mod->error)
303                         Mod_FreeModel(mod);
304 }
305
306 void Mod_ClearUsed(void)
307 {
308         int i;
309         model_t *mod;
310
311         for (i = 0, mod = mod_known;i < MAX_MOD_KNOWN;i++, mod++)
312                 if (mod->name[0])
313                         mod->used = false;
314 }
315
316 void Mod_PurgeUnused(void)
317 {
318         int i;
319         model_t *mod;
320
321         for (i = 0, mod = mod_known;i < MAX_MOD_KNOWN;i++, mod++)
322                 if (mod->name[0])
323                         if (!mod->used)
324                                 Mod_FreeModel(mod);
325 }
326
327 void Mod_LoadModels(void)
328 {
329         int i;
330         model_t *mod;
331
332         for (i = 0, mod = mod_known;i < MAX_MOD_KNOWN;i++, mod++)
333                 if (mod->name[0])
334                         if (mod->used)
335                                 Mod_CheckLoaded(mod);
336 }
337
338 /*
339 ==================
340 Mod_FindName
341
342 ==================
343 */
344 model_t *Mod_FindName (const char *name)
345 {
346         int i;
347         model_t *mod, *freemod;
348
349         if (!name[0])
350                 Host_Error ("Mod_ForName: NULL name");
351
352 // search the currently loaded models
353         freemod = NULL;
354         for (i = 0, mod = mod_known;i < MAX_MOD_KNOWN;i++, mod++)
355         {
356                 if (mod->name[0])
357                 {
358                         if (!strcmp (mod->name, name))
359                         {
360                                 mod->used = true;
361                                 return mod;
362                         }
363                 }
364                 else if (freemod == NULL)
365                         freemod = mod;
366         }
367
368         if (freemod)
369         {
370                 mod = freemod;
371                 strcpy (mod->name, name);
372                 mod->needload = true;
373                 mod->used = true;
374                 return mod;
375         }
376
377         Host_Error ("Mod_FindName: ran out of models\n");
378         return NULL;
379 }
380
381 /*
382 ==================
383 Mod_TouchModel
384
385 ==================
386 */
387 void Mod_TouchModel (const char *name)
388 {
389         model_t *mod;
390
391         mod = Mod_FindName (name);
392         mod->used = true;
393 }
394
395 /*
396 ==================
397 Mod_ForName
398
399 Loads in a model for the given name
400 ==================
401 */
402 model_t *Mod_ForName (const char *name, qboolean crash, qboolean checkdisk, qboolean isworldmodel)
403 {
404         return Mod_LoadModel (Mod_FindName (name), crash, checkdisk, isworldmodel);
405 }
406
407 qbyte *mod_base;
408
409
410 //=============================================================================
411
412 /*
413 ================
414 Mod_Print
415 ================
416 */
417 static void Mod_Print (void)
418 {
419         int             i;
420         model_t *mod;
421
422         Con_Printf ("Loaded models:\n");
423         for (i = 0, mod = mod_known;i < MAX_MOD_KNOWN;i++, mod++)
424                 if (mod->name[0])
425                         Con_Printf ("%4iK %s\n", mod->mempool ? (mod->mempool->totalsize + 1023) / 1024 : 0, mod->name);
426 }
427
428 int Mod_FindTriangleWithEdge(const int *elements, int numtriangles, int start, int end, int ignore)
429 {
430         int i, match, count;
431         count = 0;
432         match = -1;
433         for (i = 0;i < numtriangles;i++, elements += 3)
434         {
435                      if ((elements[0] == start && elements[1] == end)
436                       || (elements[1] == start && elements[2] == end)
437                       || (elements[2] == start && elements[0] == end))
438                 {
439                         if (i != ignore)
440                                 match = i;
441                         count++;
442                 }
443                 else if ((elements[1] == start && elements[0] == end)
444                       || (elements[2] == start && elements[1] == end)
445                       || (elements[0] == start && elements[2] == end))
446                         count++;
447         }
448         // detect edges shared by three triangles and make them seams
449         if (count > 2)
450                 match = -1;
451         return match;
452 }
453
454 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
455 {
456         int i, *n;
457         const int *e;
458         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
459         {
460                 n[0] = Mod_FindTriangleWithEdge(elements, numtriangles, e[1], e[0], i);
461                 n[1] = Mod_FindTriangleWithEdge(elements, numtriangles, e[2], e[1], i);
462                 n[2] = Mod_FindTriangleWithEdge(elements, numtriangles, e[0], e[2], i);
463         }
464 }
465
466 void Mod_ValidateElements(const int *elements, int numtriangles, int numverts, const char *filename, int fileline)
467 {
468         int i;
469         for (i = 0;i < numtriangles * 3;i++)
470                 if ((unsigned int)elements[i] >= (unsigned int)numverts)
471                         Con_Printf("Mod_ValidateElements: out of bounds element detected at %s:%d\n", filename, fileline);
472 }
473
474 /*
475 a note on the cost of executing this function:
476 per triangle: 188 (83 42 13 45 4 1)
477 assignments: 83 (20 3 3 3 1 4 4 1 3 4 3 4 30)
478 adds: 42 (2 2 2 2 3 2 2 27)
479 subtracts: 13 (3 3 3 1 3)
480 multiplies: 45 (6 3 6 6 3 3 6 6 6)
481 rsqrts: 4 (1 1 1 1)
482 compares: 1 (1)
483 per vertex: 39 (12 6 18 3)
484 assignments: 12 (4 4 4)
485 adds: 6 (2 2 2)
486 multiplies: 18 (6 6 6)
487 rsqrts: 3 (1 1 1)
488 */
489
490 void Mod_BuildTextureVectorsAndNormals(int numverts, int numtriangles, const float *vertex3f, const float *texcoord2f, const int *elements, float *svector3f, float *tvector3f, float *normal3f)
491 {
492         int i, tnum, voffset;
493         float vert[3][4], vec[3][4], sdir[3], tdir[3], normal[3], f, *v;
494         const int *e;
495         // clear the vectors
496         memset(svector3f, 0, numverts * sizeof(float[3]));
497         memset(tvector3f, 0, numverts * sizeof(float[3]));
498         memset(normal3f, 0, numverts * sizeof(float[3]));
499         // process each vertex of each triangle and accumulate the results
500         for (tnum = 0, e = elements;tnum < numtriangles;tnum++, e += 3)
501         {
502                 // calculate texture matrix for triangle
503                 // 20 assignments
504                 voffset = e[0];
505                 vert[0][0] = vertex3f[voffset*3+0];
506                 vert[0][1] = vertex3f[voffset*3+1];
507                 vert[0][2] = vertex3f[voffset*3+2];
508                 vert[0][3] = texcoord2f[voffset*2];
509                 voffset = e[1];
510                 vert[1][0] = vertex3f[voffset*3+0];
511                 vert[1][1] = vertex3f[voffset*3+1];
512                 vert[1][2] = vertex3f[voffset*3+2];
513                 vert[1][3] = texcoord2f[voffset*2];
514                 voffset = e[2];
515                 vert[2][0] = vertex3f[voffset*3+0];
516                 vert[2][1] = vertex3f[voffset*3+1];
517                 vert[2][2] = vertex3f[voffset*3+2];
518                 vert[2][3] = texcoord2f[voffset*2];
519                 // 3 assignments, 3 subtracts
520                 VectorSubtract(vert[1], vert[0], vec[0]);
521                 // 3 assignments, 3 subtracts
522                 VectorSubtract(vert[2], vert[0], vec[1]);
523                 // 3 assignments, 3 subtracts, 6 multiplies
524                 CrossProduct(vec[0], vec[1], normal);
525                 // 1 assignment, 2 adds, 3 multiplies, 1 compare
526                 if (DotProduct(normal, normal) >= 0.001)
527                 {
528                         // 4 assignments, 1 rsqrt, 2 adds, 6 multiplies
529                         VectorNormalize(normal);
530                         tdir[0] = ((vert[1][3] - vert[0][3]) * (vert[2][0] - vert[0][0]) - (vert[2][3] - vert[0][3]) * (vert[1][0] - vert[0][0]));
531                         tdir[1] = ((vert[1][3] - vert[0][3]) * (vert[2][1] - vert[0][1]) - (vert[2][3] - vert[0][3]) * (vert[1][1] - vert[0][1]));
532                         tdir[2] = ((vert[1][3] - vert[0][3]) * (vert[2][2] - vert[0][2]) - (vert[2][3] - vert[0][3]) * (vert[1][2] - vert[0][2]));
533                         // 4 assignments, 1 rsqrt, 2 adds, 6 multiplies
534                         VectorNormalize(tdir);
535                         // 1 assignments, 1 negates, 2 adds, 3 multiplies
536                         f = -DotProduct(tdir, normal);
537                         // 3 assignments, 3 adds, 3 multiplies
538                         VectorMA(tdir, f, normal, tdir);
539                         // 4 assignments, 1 rsqrt, 2 adds, 6 multiplies
540                         VectorNormalize(tdir);
541                         // 3 assignments, 3 subtracts, 6 multiplies
542                         CrossProduct(tdir, normal, sdir);
543                         // this is probably not necessary
544                         // 4 assignments, 1 rsqrt, 2 adds, 6 multiplies
545                         VectorNormalize(sdir);
546                         //
547                         VectorNegate(sdir, sdir);
548                         // accumulate matrix onto verts used by triangle
549                         // 30 assignments, 27 adds
550                         for (i = 0;i < 3;i++)
551                         {
552                                 voffset = e[i];
553                                 svector3f[voffset*3  ] += sdir[0];
554                                 svector3f[voffset*3+1] += sdir[1];
555                                 svector3f[voffset*3+2] += sdir[2];
556                                 tvector3f[voffset*3  ] += tdir[0];
557                                 tvector3f[voffset*3+1] += tdir[1];
558                                 tvector3f[voffset*3+2] += tdir[2];
559                                 normal3f[voffset*3  ] += normal[0];
560                                 normal3f[voffset*3+1] += normal[1];
561                                 normal3f[voffset*3+2] += normal[2];
562                         }
563                 }
564         }
565         // now we could divide the vectors by the number of averaged values on
566         // each vertex...  but instead normalize them
567         for (i = 0, v = svector3f;i < numverts;i++, v += 3)
568                 // 4 assignments, 1 rsqrt, 2 adds, 6 multiplies
569                 VectorNormalize(v);
570         for (i = 0, v = tvector3f;i < numverts;i++, v += 3)
571                 // 4 assignments, 1 rsqrt, 2 adds, 6 multiplies
572                 VectorNormalize(v);
573         for (i = 0, v = normal3f;i < numverts;i++, v += 3)
574                 // 4 assignments, 1 rsqrt, 2 adds, 6 multiplies
575                 VectorNormalize(v);
576 }
577
578 shadowmesh_t *Mod_ShadowMesh_Alloc(mempool_t *mempool, int maxverts)
579 {
580         shadowmesh_t *mesh;
581         mesh = Mem_Alloc(mempool, sizeof(shadowmesh_t) + maxverts * sizeof(float[3]) + maxverts * sizeof(int[3]) + maxverts * sizeof(int[3]) + SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *) + maxverts * sizeof(shadowmeshvertexhash_t));
582         mesh->maxverts = maxverts;
583         mesh->maxtriangles = maxverts;
584         mesh->numverts = 0;
585         mesh->numtriangles = 0;
586         mesh->vertex3f = (float *)(mesh + 1);
587         mesh->element3i = (int *)(mesh->vertex3f + mesh->maxverts * 3);
588         mesh->neighbor3i = (int *)(mesh->element3i + mesh->maxtriangles * 3);
589         mesh->vertexhashtable = (shadowmeshvertexhash_t **)(mesh->neighbor3i + mesh->maxtriangles * 3);
590         mesh->vertexhashentries = (shadowmeshvertexhash_t *)(mesh->vertexhashtable + SHADOWMESHVERTEXHASH);
591         return mesh;
592 }
593
594 shadowmesh_t *Mod_ShadowMesh_ReAlloc(mempool_t *mempool, shadowmesh_t *oldmesh)
595 {
596         shadowmesh_t *newmesh;
597         newmesh = Mem_Alloc(mempool, sizeof(shadowmesh_t) + oldmesh->numverts * sizeof(float[3]) + oldmesh->numtriangles * sizeof(int[3]) + oldmesh->numtriangles * sizeof(int[3]));
598         newmesh->maxverts = newmesh->numverts = oldmesh->numverts;
599         newmesh->maxtriangles = newmesh->numtriangles = oldmesh->numtriangles;
600         newmesh->vertex3f = (float *)(newmesh + 1);
601         newmesh->element3i = (int *)(newmesh->vertex3f + newmesh->maxverts * 3);
602         newmesh->neighbor3i = (int *)(newmesh->element3i + newmesh->maxtriangles * 3);
603         memcpy(newmesh->vertex3f, oldmesh->vertex3f, newmesh->numverts * sizeof(float[3]));
604         memcpy(newmesh->element3i, oldmesh->element3i, newmesh->numtriangles * sizeof(int[3]));
605         memcpy(newmesh->neighbor3i, oldmesh->neighbor3i, newmesh->numtriangles * sizeof(int[3]));
606         return newmesh;
607 }
608
609 int Mod_ShadowMesh_AddVertex(shadowmesh_t *mesh, float *v)
610 {
611         int hashindex;
612         float *m;
613         shadowmeshvertexhash_t *hash;
614         // this uses prime numbers intentionally
615         hashindex = (int) (v[0] * 3 + v[1] * 5 + v[2] * 7) % SHADOWMESHVERTEXHASH;
616         for (hash = mesh->vertexhashtable[hashindex];hash;hash = hash->next)
617         {
618                 m = mesh->vertex3f + (hash - mesh->vertexhashentries) * 3;
619                 if (m[0] == v[0] && m[1] == v[1] &&  m[2] == v[2])
620                         return hash - mesh->vertexhashentries;
621         }
622         hash = mesh->vertexhashentries + mesh->numverts;
623         hash->next = mesh->vertexhashtable[hashindex];
624         mesh->vertexhashtable[hashindex] = hash;
625         m = mesh->vertex3f + (hash - mesh->vertexhashentries) * 3;
626         VectorCopy(v, m);
627         mesh->numverts++;
628         return mesh->numverts - 1;
629 }
630
631 void Mod_ShadowMesh_AddTriangle(mempool_t *mempool, shadowmesh_t *mesh, float *vert0, float *vert1, float *vert2)
632 {
633         while (mesh->numverts + 3 > mesh->maxverts || mesh->numtriangles + 1 > mesh->maxtriangles)
634         {
635                 if (mesh->next == NULL)
636                         mesh->next = Mod_ShadowMesh_Alloc(mempool, max(mesh->maxtriangles, 1));
637                 mesh = mesh->next;
638         }
639         mesh->element3i[mesh->numtriangles * 3 + 0] = Mod_ShadowMesh_AddVertex(mesh, vert0);
640         mesh->element3i[mesh->numtriangles * 3 + 1] = Mod_ShadowMesh_AddVertex(mesh, vert1);
641         mesh->element3i[mesh->numtriangles * 3 + 2] = Mod_ShadowMesh_AddVertex(mesh, vert2);
642         mesh->numtriangles++;
643 }
644
645 void Mod_ShadowMesh_AddPolygon(mempool_t *mempool, shadowmesh_t *mesh, int numverts, float *verts)
646 {
647         int i;
648         float *v;
649         for (i = 0, v = verts + 3;i < numverts - 2;i++, v += 3)
650                 Mod_ShadowMesh_AddTriangle(mempool, mesh, verts, v, v + 3);
651         /*
652         int i, i1, i2, i3;
653         float *v;
654         while (mesh->numverts + numverts > mesh->maxverts || mesh->numtriangles + (numverts - 2) > mesh->maxtriangles)
655         {
656                 if (mesh->next == NULL)
657                         mesh->next = Mod_ShadowMesh_Alloc(mempool, max(mesh->maxtriangles, numverts));
658                 mesh = mesh->next;
659         }
660         i1 = Mod_ShadowMesh_AddVertex(mesh, verts);
661         i2 = 0;
662         i3 = Mod_ShadowMesh_AddVertex(mesh, verts + 3);
663         for (i = 0, v = verts + 6;i < numverts - 2;i++, v += 3)
664         {
665                 i2 = i3;
666                 i3 = Mod_ShadowMesh_AddVertex(mesh, v);
667                 mesh->elements[mesh->numtriangles * 3 + 0] = i1;
668                 mesh->elements[mesh->numtriangles * 3 + 1] = i2;
669                 mesh->elements[mesh->numtriangles * 3 + 2] = i3;
670                 mesh->numtriangles++;
671         }
672         */
673 }
674
675 void Mod_ShadowMesh_AddMesh(mempool_t *mempool, shadowmesh_t *mesh, int numverts, float *verts, int numtris, int *elements)
676 {
677         int i;
678         for (i = 0;i < numtris;i++, elements += 3)
679                 Mod_ShadowMesh_AddTriangle(mempool, mesh, verts + elements[0] * 3, verts + elements[1] * 3, verts + elements[2] * 3);
680 }
681
682 shadowmesh_t *Mod_ShadowMesh_Begin(mempool_t *mempool, int initialnumtriangles)
683 {
684         return Mod_ShadowMesh_Alloc(mempool, initialnumtriangles);
685 }
686
687 shadowmesh_t *Mod_ShadowMesh_Finish(mempool_t *mempool, shadowmesh_t *firstmesh)
688 {
689 #if 1
690         //int i;
691         shadowmesh_t *mesh, *newmesh, *nextmesh;
692         // reallocate meshs to conserve space
693         for (mesh = firstmesh, firstmesh = NULL;mesh;mesh = nextmesh)
694         {
695                 nextmesh = mesh->next;
696                 if (mesh->numverts >= 3 && mesh->numtriangles >= 1)
697                 {
698                         newmesh = Mod_ShadowMesh_ReAlloc(mempool, mesh);
699                         newmesh->next = firstmesh;
700                         firstmesh = newmesh;
701                         //Con_Printf("mesh\n");
702                         //for (i = 0;i < newmesh->numtriangles;i++)
703                         //      Con_Printf("tri %d %d %d\n", newmesh->elements[i * 3 + 0], newmesh->elements[i * 3 + 1], newmesh->elements[i * 3 + 2]);
704                         Mod_ValidateElements(newmesh->element3i, newmesh->numtriangles, newmesh->numverts, __FILE__, __LINE__);
705                         Mod_BuildTriangleNeighbors(newmesh->neighbor3i, newmesh->element3i, newmesh->numtriangles);
706                 }
707                 Mem_Free(mesh);
708         }
709 #else
710         shadowmesh_t *mesh;
711         for (mesh = firstmesh;mesh;mesh = mesh->next)
712         {
713                 Mod_ValidateElements(mesh->elements, mesh->numtriangles, mesh->numverts, __FILE__, __LINE__);
714                 Mod_BuildTriangleNeighbors(mesh->neighbors, mesh->elements, mesh->numtriangles);
715         }
716 #endif
717         return firstmesh;
718 }
719
720 void Mod_ShadowMesh_CalcBBox(shadowmesh_t *firstmesh, vec3_t mins, vec3_t maxs, vec3_t center, float *radius)
721 {
722         int i;
723         shadowmesh_t *mesh;
724         vec3_t nmins, nmaxs, ncenter, temp;
725         float nradius2, dist2, *v;
726         // calculate bbox
727         for (mesh = firstmesh;mesh;mesh = mesh->next)
728         {
729                 if (mesh == firstmesh)
730                 {
731                         VectorCopy(mesh->vertex3f, nmins);
732                         VectorCopy(mesh->vertex3f, nmaxs);
733                 }
734                 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
735                 {
736                         if (nmins[0] > v[0]) nmins[0] = v[0];if (nmaxs[0] < v[0]) nmaxs[0] = v[0];
737                         if (nmins[1] > v[1]) nmins[1] = v[1];if (nmaxs[1] < v[1]) nmaxs[1] = v[1];
738                         if (nmins[2] > v[2]) nmins[2] = v[2];if (nmaxs[2] < v[2]) nmaxs[2] = v[2];
739                 }
740         }
741         // calculate center and radius
742         ncenter[0] = (nmins[0] + nmaxs[0]) * 0.5f;
743         ncenter[1] = (nmins[1] + nmaxs[1]) * 0.5f;
744         ncenter[2] = (nmins[2] + nmaxs[2]) * 0.5f;
745         nradius2 = 0;
746         for (mesh = firstmesh;mesh;mesh = mesh->next)
747         {
748                 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
749                 {
750                         VectorSubtract(v, ncenter, temp);
751                         dist2 = DotProduct(temp, temp);
752                         if (nradius2 < dist2)
753                                 nradius2 = dist2;
754                 }
755         }
756         // return data
757         if (mins)
758                 VectorCopy(nmins, mins);
759         if (maxs)
760                 VectorCopy(nmaxs, maxs);
761         if (center)
762                 VectorCopy(ncenter, center);
763         if (radius)
764                 *radius = sqrt(nradius2);
765 }
766
767 void Mod_ShadowMesh_Free(shadowmesh_t *mesh)
768 {
769         shadowmesh_t *nextmesh;
770         for (;mesh;mesh = nextmesh)
771         {
772                 nextmesh = mesh->next;
773                 Mem_Free(mesh);
774         }
775 }
776
777 static rtexture_t *GL_TextureForSkinLayer(const qbyte *in, int width, int height, const char *name, const unsigned int *palette, int textureflags)
778 {
779         int i;
780         for (i = 0;i < width*height;i++)
781                 if (((qbyte *)&palette[in[i]])[3] > 0)
782                         return R_LoadTexture2D (loadmodel->texturepool, name, width, height, in, TEXTYPE_PALETTE, textureflags, palette);
783         return NULL;
784 }
785
786 static int detailtexturecycle = 0;
787 int Mod_LoadSkinFrame (skinframe_t *skinframe, char *basename, int textureflags, int loadpantsandshirt, int usedetailtexture, int loadglowtexture)
788 {
789         imageskin_t s;
790         memset(skinframe, 0, sizeof(*skinframe));
791         if (!image_loadskin(&s, basename))
792                 return false;
793         if (usedetailtexture)
794                 skinframe->detail = mod_shared_detailtextures[(detailtexturecycle++) % NUM_DETAILTEXTURES];
795         skinframe->base = R_LoadTexture2D (loadmodel->texturepool, basename, s.basepixels_width, s.basepixels_height, s.basepixels, TEXTYPE_RGBA, textureflags, NULL);
796         if (s.nmappixels != NULL)
797                 skinframe->nmap = R_LoadTexture2D (loadmodel->texturepool, va("%s_nmap", basename), s.basepixels_width, s.basepixels_height, s.nmappixels, TEXTYPE_RGBA, textureflags, NULL);
798         if (s.glosspixels != NULL)
799                 skinframe->gloss = R_LoadTexture2D (loadmodel->texturepool, va("%s_gloss", basename), s.glosspixels_width, s.glosspixels_height, s.glosspixels, TEXTYPE_RGBA, textureflags, NULL);
800         if (s.glowpixels != NULL && loadglowtexture)
801                 skinframe->glow = R_LoadTexture2D (loadmodel->texturepool, va("%s_glow", basename), s.glowpixels_width, s.glowpixels_height, s.glowpixels, TEXTYPE_RGBA, textureflags, NULL);
802         if (s.maskpixels != NULL)
803                 skinframe->fog = R_LoadTexture2D (loadmodel->texturepool, va("%s_mask", basename), s.maskpixels_width, s.maskpixels_height, s.maskpixels, TEXTYPE_RGBA, textureflags, NULL);
804         if (loadpantsandshirt)
805         {
806                 if (s.pantspixels != NULL)
807                         skinframe->pants = R_LoadTexture2D (loadmodel->texturepool, va("%s_pants", basename), s.pantspixels_width, s.pantspixels_height, s.pantspixels, TEXTYPE_RGBA, textureflags, NULL);
808                 if (s.shirtpixels != NULL)
809                         skinframe->shirt = R_LoadTexture2D (loadmodel->texturepool, va("%s_shirt", basename), s.shirtpixels_width, s.shirtpixels_height, s.shirtpixels, TEXTYPE_RGBA, textureflags, NULL);
810         }
811         image_freeskin(&s);
812         return true;
813 }
814
815 int Mod_LoadSkinFrame_Internal (skinframe_t *skinframe, char *basename, int textureflags, int loadpantsandshirt, int usedetailtexture, int loadglowtexture, qbyte *skindata, int width, int height)
816 {
817         qbyte *temp1, *temp2;
818         memset(skinframe, 0, sizeof(*skinframe));
819         if (!skindata)
820                 return false;
821         if (usedetailtexture)
822                 skinframe->detail = mod_shared_detailtextures[(detailtexturecycle++) % NUM_DETAILTEXTURES];
823         if (r_shadow_bumpscale_basetexture.value > 0)
824         {
825                 temp1 = Mem_Alloc(loadmodel->mempool, width * height * 8);
826                 temp2 = temp1 + width * height * 4;
827                 Image_Copy8bitRGBA(skindata, temp1, width * height, palette_nofullbrights);
828                 Image_HeightmapToNormalmap(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
829                 skinframe->nmap = R_LoadTexture2D(loadmodel->texturepool, va("%s_nmap", basename), width, height, temp2, TEXTYPE_RGBA, textureflags, NULL);
830                 Mem_Free(temp1);
831         }
832         if (loadglowtexture)
833         {
834                 skinframe->glow = GL_TextureForSkinLayer(skindata, width, height, va("%s_glow", basename), palette_onlyfullbrights, textureflags); // glow
835                 skinframe->base = skinframe->merged = GL_TextureForSkinLayer(skindata, width, height, va("%s_merged", basename), palette_nofullbrights, textureflags); // all but fullbrights
836                 if (loadpantsandshirt)
837                 {
838                         skinframe->pants = GL_TextureForSkinLayer(skindata, width, height, va("%s_pants", basename), palette_pantsaswhite, textureflags); // pants
839                         skinframe->shirt = GL_TextureForSkinLayer(skindata, width, height, va("%s_shirt", basename), palette_shirtaswhite, textureflags); // shirt
840                         if (skinframe->pants || skinframe->shirt)
841                                 skinframe->base = GL_TextureForSkinLayer(skindata, width, height, va("%s_nospecial", basename), palette_nocolormapnofullbrights, textureflags); // no special colors
842                 }
843         }
844         else
845         {
846                 skinframe->base = skinframe->merged = GL_TextureForSkinLayer(skindata, width, height, va("%s_merged", basename), palette_complete, textureflags); // all
847                 if (loadpantsandshirt)
848                 {
849                         skinframe->pants = GL_TextureForSkinLayer(skindata, width, height, va("%s_pants", basename), palette_pantsaswhite, textureflags); // pants
850                         skinframe->shirt = GL_TextureForSkinLayer(skindata, width, height, va("%s_shirt", basename), palette_shirtaswhite, textureflags); // shirt
851                         if (skinframe->pants || skinframe->shirt)
852                                 skinframe->base = GL_TextureForSkinLayer(skindata, width, height, va("%s_nospecial", basename), palette_nocolormap, textureflags); // no pants or shirt
853                 }
854         }
855         return true;
856 }