]> icculus.org git repositories - divverent/netradiant.git/blob - tools/quake3/q3map2/model.c
skinfiles: use the VFS
[divverent/netradiant.git] / tools / quake3 / q3map2 / model.c
1 /* -------------------------------------------------------------------------------
2
3 Copyright (C) 1999-2007 id Software, Inc. and contributors.
4 For a list of contributors, see the accompanying CONTRIBUTORS file.
5
6 This file is part of GtkRadiant.
7
8 GtkRadiant is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12
13 GtkRadiant is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GtkRadiant; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21
22 ----------------------------------------------------------------------------------
23
24 This code has been altered significantly from its original form, to support
25 several games based on the Quake III Arena engine, in the form of "Q3Map2."
26
27 ------------------------------------------------------------------------------- */
28
29
30
31 /* marker */
32 #define MODEL_C
33
34
35
36 /* dependencies */
37 #include "q3map2.h"
38
39
40
41 /* 
42 PicoPrintFunc()
43 callback for picomodel.lib
44 */
45
46 void PicoPrintFunc( int level, const char *str )
47 {
48         if( str == NULL )
49                 return;
50         switch( level )
51         {
52                 case PICO_NORMAL:
53                         Sys_Printf( "%s\n", str );
54                         break;
55                 
56                 case PICO_VERBOSE:
57                         Sys_FPrintf( SYS_VRB, "%s\n", str );
58                         break;
59                 
60                 case PICO_WARNING:
61                         Sys_Printf( "WARNING: %s\n", str );
62                         break;
63                 
64                 case PICO_ERROR:
65                         Sys_Printf( "ERROR: %s\n", str );
66                         break;
67                 
68                 case PICO_FATAL:
69                         Error( "ERROR: %s\n", str );
70                         break;
71         }
72 }
73
74
75
76 /* 
77 PicoLoadFileFunc()
78 callback for picomodel.lib
79 */
80
81 void PicoLoadFileFunc( char *name, byte **buffer, int *bufSize )
82 {
83         *bufSize = vfsLoadFile( (const char*) name, (void**) buffer, 0 );
84 }
85
86
87
88 /*
89 FindModel() - ydnar
90 finds an existing picoModel and returns a pointer to the picoModel_t struct or NULL if not found
91 */
92
93 picoModel_t *FindModel( const char *name, int frame )
94 {
95         int                     i;
96         
97         
98         /* init */
99         if( numPicoModels <= 0 )
100                 memset( picoModels, 0, sizeof( picoModels ) );
101         
102         /* dummy check */
103         if( name == NULL || name[ 0 ] == '\0' )
104                 return NULL;
105         
106         /* search list */
107         for( i = 0; i < MAX_MODELS; i++ )
108         {
109                 if( picoModels[ i ] != NULL &&
110                         !strcmp( PicoGetModelName( picoModels[ i ] ), name ) &&
111                         PicoGetModelFrameNum( picoModels[ i ] ) == frame )
112                         return picoModels[ i ];
113         }
114         
115         /* no matching picoModel found */
116         return NULL;
117 }
118
119
120
121 /*
122 LoadModel() - ydnar
123 loads a picoModel and returns a pointer to the picoModel_t struct or NULL if not found
124 */
125
126 picoModel_t *LoadModel( const char *name, int frame )
127 {
128         int                             i;
129         picoModel_t             *model, **pm;
130         
131         
132         /* init */
133         if( numPicoModels <= 0 )
134                 memset( picoModels, 0, sizeof( picoModels ) );
135         
136         /* dummy check */
137         if( name == NULL || name[ 0 ] == '\0' )
138                 return NULL;
139         
140         /* try to find existing picoModel */
141         model = FindModel( name, frame );
142         if( model != NULL )
143                 return model;
144         
145         /* none found, so find first non-null picoModel */
146         pm = NULL;
147         for( i = 0; i < MAX_MODELS; i++ )
148         {
149                 if( picoModels[ i ] == NULL )
150                 {
151                         pm = &picoModels[ i ];
152                         break;
153                 }
154         }
155         
156         /* too many picoModels? */
157         if( pm == NULL )
158                 Error( "MAX_MODELS (%d) exceeded, there are too many model files referenced by the map.", MAX_MODELS );
159         
160         /* attempt to parse model */
161         *pm = PicoLoadModel( (char*) name, frame );
162         
163         /* if loading failed, make a bogus model to silence the rest of the warnings */
164         if( *pm == NULL )
165         {
166                 /* allocate a new model */
167                 *pm = PicoNewModel();
168                 if( *pm == NULL )
169                         return NULL;
170                 
171                 /* set data */
172                 PicoSetModelName( *pm, (char*) name );
173                 PicoSetModelFrameNum( *pm, frame );
174         }
175         
176         /* debug code */
177         #if 0
178         {
179                 int                             numSurfaces, numVertexes;
180                 picoSurface_t   *ps;
181                 
182                 
183                 Sys_Printf( "Model %s\n", name );
184                 numSurfaces = PicoGetModelNumSurfaces( *pm );
185                 for( i = 0; i < numSurfaces; i++ )
186                 {
187                         ps = PicoGetModelSurface( *pm, i );
188                         numVertexes = PicoGetSurfaceNumVertexes( ps );
189                         Sys_Printf( "Surface %d has %d vertexes\n", i, numVertexes );
190                 }
191         }
192         #endif
193         
194         /* set count */
195         if( *pm != NULL )
196                 numPicoModels++;
197         
198         /* return the picoModel */
199         return *pm;
200 }
201
202
203
204 /*
205 InsertModel() - ydnar
206 adds a picomodel into the bsp
207 */
208
209 void InsertModel( const char *name, int skin, int frame, m4x4_t transform, remap_t *remap, shaderInfo_t *celShader, int eNum, int castShadows, int recvShadows, int spawnFlags, float lightmapScale, int lightmapSampleSize, float shadeAngle )
210 {
211         int                                     i, j, k, s, numSurfaces;
212         m4x4_t                          identity, nTransform;
213         picoModel_t                     *model;
214         picoShader_t            *shader;
215         picoSurface_t           *surface;
216         shaderInfo_t            *si;
217         mapDrawSurface_t        *ds;
218         bspDrawVert_t           *dv;
219         char                            *picoShaderName;
220         char                            shaderName[ MAX_QPATH ];
221         picoVec_t                       *xyz, *normal, *st;
222         byte                            *color;
223         picoIndex_t                     *indexes;
224         remap_t                         *rm, *glob;
225         skinfile_t                      *sf, *sf2;
226         double                          normalEpsilon_save;
227         double                          distanceEpsilon_save;
228         char                            skinfilename[ MAX_QPATH ];
229         char                            *skinfilecontent;
230         int                                     skinfilesize;
231         char                            *skinfileptr, *skinfilenextptr;
232         FILE                            *skinfilehandle;
233         
234         
235         /* get model */
236         model = LoadModel( name, frame );
237         if( model == NULL )
238                 return;
239
240         /* load skin file */
241         snprintf(skinfilename, sizeof(skinfilename), "%s_%d.skin", name, skin);
242         skinfilename[sizeof(skinfilename)-1] = 0;
243         skinfilehandle = fopen(skinfilename, "r");
244         skinfilesize = vfsLoadFile(skinfilename, (void**) &skinfilecontent, 0);
245         if(skinfilesize < 0)
246         {
247                 /* fallback to skin 0 if invalid */
248                 snprintf(skinfilename, sizeof(skinfilename), "%s_0.skin", name);
249                 skinfilename[sizeof(skinfilename)-1] = 0;
250                 skinfilesize = vfsLoadFile(skinfilename, (void**) &skinfilecontent, 0);
251                 if(skinfilesize < 0)
252                         Sys_Printf( "Skin %d of %s does not exist, using 0 instead\n", skin, name );
253         }
254         sf = NULL;
255         if(skinfilesize)
256         {
257                 Sys_Printf( "Using skin %d of %s\n", skin, name );
258                 int pos;
259                 for(skinfileptr = skinfilecontent; *skinfileptr; skinfileptr = skinfilenextptr)
260                 {
261                         // for fscanf
262                         char format[64];
263
264                         skinfilenextptr = strchr(skinfileptr, '\r');
265                         if(skinfilenextptr)
266                         {
267                                 *skinfilenextptr++ = 0;
268                         }
269                         else
270                         {
271                                 skinfilenextptr = strchr(skinfileptr, '\n');
272                                 if(skinfilenextptr)
273                                         *skinfilenextptr++ = 0;
274                                 else
275                                         skinfilenextptr = skinfileptr + strlen(skinfileptr);
276                         }
277
278                         /* create new item */
279                         sf2 = sf;
280                         sf = safe_malloc( sizeof( *sf ) );
281                         sf->next = sf2;
282
283                         sprintf(format, "replace %%%ds %%%ds%%n", (int)sizeof(sf->name)-1, (int)sizeof(sf->to)-1);
284                         pos = 0;
285                         if(sscanf(skinfileptr, format, &sf->name, &sf->to, &pos) > 0 && pos > 0)
286                                 continue;
287                         sprintf(format, "%%%ds,%%%ds%%n", (int)sizeof(sf->name)-1, (int)sizeof(sf->to)-1);
288                         pos = 0;
289                         if(sscanf(skinfileptr, format, &sf->name, &sf->to, &pos) > 0 && pos > 0)
290                                 continue;
291
292                         /* invalid input line -> discard sf struct */
293                         free(sf);
294                         sf = sf2;
295                 }
296                 free(skinfilecontent);
297         }
298         
299         /* handle null matrix */
300         if( transform == NULL )
301         {
302                 m4x4_identity( identity );
303                 transform = identity;
304         }
305         
306         /* hack: Stable-1_2 and trunk have differing row/column major matrix order
307            this transpose is necessary with Stable-1_2
308            uncomment the following line with old m4x4_t (non 1.3/spog_branch) code */
309         //%     m4x4_transpose( transform );
310         
311         /* create transform matrix for normals */
312         memcpy( nTransform, transform, sizeof( m4x4_t ) );
313         if( m4x4_invert( nTransform ) )
314                 Sys_FPrintf( SYS_VRB, "WARNING: Can't invert model transform matrix, using transpose instead\n" );
315         m4x4_transpose( nTransform );
316         
317         /* fix bogus lightmap scale */
318         if( lightmapScale <= 0.0f )
319                 lightmapScale = 1.0f;
320
321         /* fix bogus shade angle */
322         if( shadeAngle <= 0.0f )
323                 shadeAngle = 0.0f;
324         
325         /* each surface on the model will become a new map drawsurface */
326         numSurfaces = PicoGetModelNumSurfaces( model );
327         //%     Sys_FPrintf( SYS_VRB, "Model %s has %d surfaces\n", name, numSurfaces );
328         for( s = 0; s < numSurfaces; s++ )
329         {
330                 /* get surface */
331                 surface = PicoGetModelSurface( model, s );
332                 if( surface == NULL )
333                         continue;
334                 
335                 /* only handle triangle surfaces initially (fixme: support patches) */
336                 if( PicoGetSurfaceType( surface ) != PICO_TRIANGLES )
337                         continue;
338                 
339                 /* allocate a surface (ydnar: gs mods) */
340                 ds = AllocDrawSurface( SURFACE_TRIANGLES );
341                 ds->entityNum = eNum;
342                 ds->castShadows = castShadows;
343                 ds->recvShadows = recvShadows;
344                 
345                 /* get shader name */
346         shader = PicoGetSurfaceShader( surface );
347                 if( shader == NULL )
348                         picoShaderName = "";
349                 else
350                         picoShaderName = PicoGetShaderName( shader );
351
352                 /* handle .skin file */
353                 if(sf)
354                 {
355                         picoShaderName = NULL;
356                         for(sf2 = sf; sf2 != NULL; sf2 = sf2->next)
357                         {
358                                 if( !Q_stricmp( surface->name, sf2->name ) )
359                                 {
360                                         Sys_FPrintf( SYS_VRB, "Skin file: mapping %s to %s\n", surface->name, sf2->to );
361                                         picoShaderName = sf2->to;
362                                         break;
363                                 }
364                         }
365                         if(!picoShaderName)
366                         {
367                                 Sys_FPrintf( SYS_VRB, "Skin file: not mapping %s\n", surface->name );
368                                 continue;
369                         }
370                 }
371
372                 /* handle shader remapping */
373                 glob = NULL;
374                 for( rm = remap; rm != NULL; rm = rm->next )
375                 {
376                         if( rm->from[ 0 ] == '*' && rm->from[ 1 ] == '\0' )
377                                 glob = rm;
378                         else if( !Q_stricmp( picoShaderName, rm->from ) )
379                         {
380                                 Sys_FPrintf( SYS_VRB, "Remapping %s to %s\n", picoShaderName, rm->to );
381                                 picoShaderName = rm->to;
382                                 glob = NULL;
383                                 break;
384                         }
385                 }
386                 
387                 if( glob != NULL )
388                 {
389                         Sys_FPrintf( SYS_VRB, "Globbing %s to %s\n", picoShaderName, glob->to );
390                         picoShaderName = glob->to;
391                 }
392                 
393                 /* shader renaming for sof2 */
394                 if( renameModelShaders )
395                 {
396                         strcpy( shaderName, picoShaderName );
397                         StripExtension( shaderName );
398                         if( spawnFlags & 1 )
399                                 strcat( shaderName, "_RMG_BSP" );
400                         else
401                                 strcat( shaderName, "_BSP" );
402                         si = ShaderInfoForShader( shaderName );
403                 }
404                 else
405                         si = ShaderInfoForShader( picoShaderName );
406                 
407                 /* set shader */
408                 ds->shaderInfo = si;
409
410                 /* force to meta? */
411                 if( (si != NULL && si->forceMeta) || (spawnFlags & 4) ) /* 3rd bit */
412                         ds->type = SURFACE_FORCED_META;
413
414                 /* fix the surface's normals (jal: conditioned by shader info) */
415                 if( !(spawnFlags & 64) && ( shadeAngle == 0.0f || ds->type != SURFACE_FORCED_META ) )
416                         PicoFixSurfaceNormals( surface );
417
418                 /* set sample size */
419                 if( lightmapSampleSize > 0.0f )
420                         ds->sampleSize = lightmapSampleSize;
421                 
422                 /* set lightmap scale */
423                 if( lightmapScale > 0.0f )
424                         ds->lightmapScale = lightmapScale;
425
426                 /* set shading angle */
427                 if( shadeAngle > 0.0f )
428                         ds->shadeAngleDegrees = shadeAngle;
429                 
430                 /* set particulars */
431                 ds->numVerts = PicoGetSurfaceNumVertexes( surface );
432                 ds->verts = safe_malloc( ds->numVerts * sizeof( ds->verts[ 0 ] ) );
433                 memset( ds->verts, 0, ds->numVerts * sizeof( ds->verts[ 0 ] ) );
434                 
435                 ds->numIndexes = PicoGetSurfaceNumIndexes( surface );
436                 ds->indexes = safe_malloc( ds->numIndexes * sizeof( ds->indexes[ 0 ] ) );
437                 memset( ds->indexes, 0, ds->numIndexes * sizeof( ds->indexes[ 0 ] ) );
438                 
439                 /* copy vertexes */
440                 for( i = 0; i < ds->numVerts; i++ )
441                 {
442                         /* get vertex */
443                         dv = &ds->verts[ i ];
444                         
445                         /* xyz and normal */
446                         xyz = PicoGetSurfaceXYZ( surface, i );
447                         VectorCopy( xyz, dv->xyz );
448                         m4x4_transform_point( transform, dv->xyz );
449                         
450                         normal = PicoGetSurfaceNormal( surface, i );
451                         VectorCopy( normal, dv->normal );
452                         m4x4_transform_normal( nTransform, dv->normal );
453                         VectorNormalize( dv->normal, dv->normal );
454
455                         /* ydnar: tek-fu celshading support for flat shaded shit */
456                         if( flat )
457                         {
458                                 dv->st[ 0 ] = si->stFlat[ 0 ];
459                                 dv->st[ 1 ] = si->stFlat[ 1 ];
460                         }
461                         
462                         /* ydnar: gs mods: added support for explicit shader texcoord generation */
463                         else if( si->tcGen )
464                         {
465                                 /* project the texture */
466                                 dv->st[ 0 ] = DotProduct( si->vecs[ 0 ], dv->xyz );
467                                 dv->st[ 1 ] = DotProduct( si->vecs[ 1 ], dv->xyz );
468                         }
469                         
470                         /* normal texture coordinates */
471                         else
472                         {
473                                 st = PicoGetSurfaceST( surface, 0, i );
474                                 dv->st[ 0 ] = st[ 0 ];
475                                 dv->st[ 1 ] = st[ 1 ];
476                         }
477                         
478                         /* set lightmap/color bits */
479                         color = PicoGetSurfaceColor( surface, 0, i );
480                         for( j = 0; j < MAX_LIGHTMAPS; j++ )
481                         {
482                                 dv->lightmap[ j ][ 0 ] = 0.0f;
483                                 dv->lightmap[ j ][ 1 ] = 0.0f;
484                                 if(spawnFlags & 32) // spawnflag 32: model color -> alpha hack
485                                 {
486                                         dv->color[ j ][ 0 ] = 255.0f;
487                                         dv->color[ j ][ 1 ] = 255.0f;
488                                         dv->color[ j ][ 2 ] = 255.0f;
489                                         dv->color[ j ][ 3 ] = RGBTOGRAY( color );
490                                 }
491                                 else
492                                 {
493                                         dv->color[ j ][ 0 ] = color[ 0 ];
494                                         dv->color[ j ][ 1 ] = color[ 1 ];
495                                         dv->color[ j ][ 2 ] = color[ 2 ];
496                                         dv->color[ j ][ 3 ] = color[ 3 ];
497                                 }
498                         }
499                 }
500                 
501                 /* copy indexes */
502                 indexes = PicoGetSurfaceIndexes( surface, 0 );
503                 for( i = 0; i < ds->numIndexes; i++ )
504                         ds->indexes[ i ] = indexes[ i ];
505                 
506                 /* set cel shader */
507                 ds->celShader = celShader;
508                 
509                 /* ydnar: giant hack land: generate clipping brushes for model triangles */
510                 if( si->clipModel || (spawnFlags & 2) ) /* 2nd bit */
511                 {
512                         vec3_t          points[ 4 ], backs[ 3 ];
513                         vec4_t          plane, reverse, pa, pb, pc;
514                         
515                         
516                         /* temp hack */
517                         if( !si->clipModel && !(si->compileFlags & C_SOLID) )
518                                 continue;
519                         
520                         /* walk triangle list */
521                         for( i = 0; i < ds->numIndexes; i += 3 )
522                         {
523                                 /* overflow hack */
524                                 AUTOEXPAND_BY_REALLOC(mapplanes, (nummapplanes+64) << 1, allocatedmapplanes, 1024);
525                                 
526                                 /* make points and back points */
527                                 for( j = 0; j < 3; j++ )
528                                 {
529                                         /* get vertex */
530                                         dv = &ds->verts[ ds->indexes[ i + j ] ];
531                                         
532                                         /* copy xyz */
533                                         VectorCopy( dv->xyz, points[ j ] );
534                                         VectorCopy( dv->xyz, backs[ j ] );
535                                         
536                                         /* find nearest axial to normal and push back points opposite */
537                                         /* note: this doesn't work as well as simply using the plane of the triangle, below */
538                                         for( k = 0; k < 3; k++ )
539                                         {
540                                                 if( fabs( dv->normal[ k ] ) >= fabs( dv->normal[ (k + 1) % 3 ] ) &&
541                                                         fabs( dv->normal[ k ] ) >= fabs( dv->normal[ (k + 2) % 3 ] ) )
542                                                 {
543                                                         backs[ j ][ k ] += dv->normal[ k ] < 0.0f ? 64.0f : -64.0f;
544                                                         break;
545                                                 }
546                                         }
547                                 }
548
549                                 VectorCopy( points[0], points[3] ); // for cyclic usage
550                                 
551                                 /* make plane for triangle */
552                                 // div0: add some extra spawnflags:
553                                 //   0: snap normals to axial planes for extrusion
554                                 //   8: extrude with the original normals
555                                 //  16: extrude only with up/down normals (ideal for terrain)
556                                 //  24: extrude by distance zero (may need engine changes)
557                                 if( PlaneFromPoints( plane, points[ 0 ], points[ 1 ], points[ 2 ] ) )
558                                 {
559                                         vec3_t bestNormal;
560                                         float backPlaneDistance = 2;
561
562                                         if(spawnFlags & 8) // use a DOWN normal
563                                         {
564                                                 if(spawnFlags & 16)
565                                                 {
566                                                         // 24: normal as is, and zero width (broken)
567                                                         VectorCopy(plane, bestNormal);
568                                                 }
569                                                 else
570                                                 {
571                                                         // 8: normal as is
572                                                         VectorCopy(plane, bestNormal);
573                                                 }
574                                         }
575                                         else
576                                         {
577                                                 if(spawnFlags & 16)
578                                                 {
579                                                         // 16: UP/DOWN normal
580                                                         VectorSet(bestNormal, 0, 0, (plane[2] >= 0 ? 1 : -1));
581                                                 }
582                                                 else
583                                                 {
584                                                         // 0: axial normal
585                                                         if(fabs(plane[0]) > fabs(plane[1])) // x>y
586                                                                 if(fabs(plane[1]) > fabs(plane[2])) // x>y, y>z
587                                                                         VectorSet(bestNormal, (plane[0] >= 0 ? 1 : -1), 0, 0);
588                                                                 else // x>y, z>=y
589                                                                         if(fabs(plane[0]) > fabs(plane[2])) // x>z, z>=y
590                                                                                 VectorSet(bestNormal, (plane[0] >= 0 ? 1 : -1), 0, 0);
591                                                                         else // z>=x, x>y
592                                                                                 VectorSet(bestNormal, 0, 0, (plane[2] >= 0 ? 1 : -1));
593                                                         else // y>=x
594                                                                 if(fabs(plane[1]) > fabs(plane[2])) // y>z, y>=x
595                                                                         VectorSet(bestNormal, 0, (plane[1] >= 0 ? 1 : -1), 0);
596                                                                 else // z>=y, y>=x
597                                                                         VectorSet(bestNormal, 0, 0, (plane[2] >= 0 ? 1 : -1));
598                                                 }
599                                         }
600
601                                         /* build a brush */
602                                         buildBrush = AllocBrush( 48 );
603                                         buildBrush->entityNum = mapEntityNum;
604                                         buildBrush->original = buildBrush;
605                                         buildBrush->contentShader = si;
606                                         buildBrush->compileFlags = si->compileFlags;
607                                         buildBrush->contentFlags = si->contentFlags;
608                                         normalEpsilon_save = normalEpsilon;
609                                         distanceEpsilon_save = distanceEpsilon;
610                                         if(si->compileFlags & C_STRUCTURAL) // allow forced structural brushes here
611                                         {
612                                                 buildBrush->detail = qfalse;
613
614                                                 // only allow EXACT matches when snapping for these (this is mostly for caulk brushes inside a model)
615                                                 if(normalEpsilon > 0)
616                                                         normalEpsilon = 0;
617                                                 if(distanceEpsilon > 0)
618                                                         distanceEpsilon = 0;
619                                         }
620                                         else
621                                                 buildBrush->detail = qtrue;
622
623                                         /* regenerate back points */
624                                         for( j = 0; j < 3; j++ )
625                                         {
626                                                 /* get vertex */
627                                                 dv = &ds->verts[ ds->indexes[ i + j ] ];
628
629                                                 // shift by some units
630                                                 VectorMA(dv->xyz, -64.0f, bestNormal, backs[j]); // 64 prevents roundoff errors a bit
631                                         }
632
633                                         /* make back plane */
634                                         VectorScale( plane, -1.0f, reverse );
635                                         reverse[ 3 ] = -plane[ 3 ];
636                                         if((spawnFlags & 24) != 24)
637                                                 reverse[3] += DotProduct(bestNormal, plane) * backPlaneDistance;
638                                         // that's at least sqrt(1/3) backPlaneDistance, unless in DOWN mode; in DOWN mode, we are screwed anyway if we encounter a plane that's perpendicular to the xy plane)
639
640                                         if( PlaneFromPoints( pa, points[ 2 ], points[ 1 ], backs[ 1 ] ) &&
641                                                         PlaneFromPoints( pb, points[ 1 ], points[ 0 ], backs[ 0 ] ) &&
642                                                         PlaneFromPoints( pc, points[ 0 ], points[ 2 ], backs[ 2 ] ) )
643                                         {
644                                                 /* set up brush sides */
645                                                 buildBrush->numsides = 5;
646                                                 buildBrush->sides[ 0 ].shaderInfo = si;
647                                                 for( j = 1; j < buildBrush->numsides; j++ )
648                                                         buildBrush->sides[ j ].shaderInfo = NULL; // don't emit these faces as draw surfaces, should make smaller BSPs; hope this works
649
650                                                 buildBrush->sides[ 0 ].planenum = FindFloatPlane( plane, plane[ 3 ], 3, points );
651                                                 buildBrush->sides[ 1 ].planenum = FindFloatPlane( pa, pa[ 3 ], 2, &points[ 1 ] ); // pa contains points[1] and points[2]
652                                                 buildBrush->sides[ 2 ].planenum = FindFloatPlane( pb, pb[ 3 ], 2, &points[ 0 ] ); // pb contains points[0] and points[1]
653                                                 buildBrush->sides[ 3 ].planenum = FindFloatPlane( pc, pc[ 3 ], 2, &points[ 2 ] ); // pc contains points[2] and points[0] (copied to points[3]
654                                                 buildBrush->sides[ 4 ].planenum = FindFloatPlane( reverse, reverse[ 3 ], 3, backs );
655                                         }
656                                         else
657                                         {
658                                                 free(buildBrush);
659                                                 continue;
660                                         }
661
662                                         normalEpsilon = normalEpsilon_save;
663                                         distanceEpsilon = distanceEpsilon_save;
664
665                                         /* add to entity */
666                                         if( CreateBrushWindings( buildBrush ) )
667                                         {
668                                                 AddBrushBevels();
669                                                 //%     EmitBrushes( buildBrush, NULL, NULL );
670                                                 buildBrush->next = entities[ mapEntityNum ].brushes;
671                                                 entities[ mapEntityNum ].brushes = buildBrush;
672                                                 entities[ mapEntityNum ].numBrushes++;
673                                         }
674                                         else
675                                                 free( buildBrush );
676                                 }
677                         }
678                 }
679         }
680 }
681
682
683
684 /*
685 AddTriangleModels()
686 adds misc_model surfaces to the bsp
687 */
688
689 void AddTriangleModels( entity_t *e )
690 {
691         int                             num, frame, skin, castShadows, recvShadows, spawnFlags;
692         entity_t                *e2;
693         const char              *targetName;
694         const char              *target, *model, *value;
695         char                    shader[ MAX_QPATH ];
696         shaderInfo_t    *celShader;
697         float                   temp, baseLightmapScale, lightmapScale;
698         float                   shadeAngle;
699         int                             lightmapSampleSize;
700         vec3_t                  origin, scale, angles;
701         m4x4_t                  transform;
702         epair_t                 *ep;
703         remap_t                 *remap, *remap2;
704         char                    *split;
705         
706         
707         /* note it */
708         Sys_FPrintf( SYS_VRB, "--- AddTriangleModels ---\n" );
709         
710         /* get current brush entity targetname */
711         if( e == entities )
712                 targetName = "";
713         else
714         {
715                 targetName = ValueForKey( e, "targetname" );
716         
717                 /* misc_model entities target non-worldspawn brush model entities */
718                 if( targetName[ 0 ] == '\0' )
719                         return;
720         }
721         
722         /* get lightmap scale */
723         /* vortex: added _ls key (short name of lightmapscale) */
724         baseLightmapScale = 0.0f;
725         if( strcmp( "", ValueForKey( e, "lightmapscale" ) ) ||
726                 strcmp( "", ValueForKey( e, "_lightmapscale" ) ) || 
727                 strcmp( "", ValueForKey( e, "_ls" ) ) )
728         {
729                 baseLightmapScale = FloatForKey( e, "lightmapscale" );
730                 if( baseLightmapScale <= 0.0f )
731                         baseLightmapScale = FloatForKey( e, "_lightmapscale" );
732                 if( baseLightmapScale <= 0.0f )
733                         baseLightmapScale = FloatForKey( e, "_ls" );
734                 if( baseLightmapScale < 0.0f )
735                         baseLightmapScale = 0.0f;
736                 if( baseLightmapScale > 0.0f )
737                         Sys_Printf( "World Entity has lightmap scale of %.4f\n", baseLightmapScale );
738         }
739         
740         
741         /* walk the entity list */
742         for( num = 1; num < numEntities; num++ )
743         {
744                 /* get e2 */
745                 e2 = &entities[ num ];
746                 
747                 /* convert misc_models into raw geometry */
748                 if( Q_stricmp( "misc_model", ValueForKey( e2, "classname" ) ) )
749                         continue;
750
751                 /* ydnar: added support for md3 models on non-worldspawn models */
752                 target = ValueForKey( e2, "target" );
753                 if( strcmp( target, targetName ) )
754                         continue;
755                 
756                 /* get model name */
757                 model = ValueForKey( e2, "model" );
758                 if( model[ 0 ] == '\0' )
759                 {
760                         Sys_Printf( "WARNING: misc_model at %i %i %i without a model key\n",
761                                 (int) origin[ 0 ], (int) origin[ 1 ], (int) origin[ 2 ] );
762                         continue;
763                 }
764                 
765                 /* get model frame */
766                 frame = IntForKey( e2, "_frame" );
767                 
768                 /* worldspawn (and func_groups) default to cast/recv shadows in worldspawn group */
769                 if( e == entities )
770                 {
771                         castShadows = WORLDSPAWN_CAST_SHADOWS;
772                         recvShadows = WORLDSPAWN_RECV_SHADOWS;
773                 }
774                 
775                 /* other entities don't cast any shadows, but recv worldspawn shadows */
776                 else
777                 {
778                         castShadows = ENTITY_CAST_SHADOWS;
779                         recvShadows = ENTITY_RECV_SHADOWS;
780                 }
781                 
782                 /* get explicit shadow flags */
783                 GetEntityShadowFlags( e2, e, &castShadows, &recvShadows );
784                 
785                 /* get spawnflags */
786                 spawnFlags = IntForKey( e2, "spawnflags" );
787                 
788                 /* get origin */
789                 GetVectorForKey( e2, "origin", origin );
790                 VectorSubtract( origin, e->origin, origin );    /* offset by parent */
791                 
792                 /* get scale */
793                 scale[ 0 ] = scale[ 1 ] = scale[ 2 ] = 1.0f;
794                 temp = FloatForKey( e2, "modelscale" );
795                 if( temp != 0.0f )
796                         scale[ 0 ] = scale[ 1 ] = scale[ 2 ] = temp;
797                 value = ValueForKey( e2, "modelscale_vec" );
798                 if( value[ 0 ] != '\0' )
799                         sscanf( value, "%f %f %f", &scale[ 0 ], &scale[ 1 ], &scale[ 2 ] );
800                 
801                 /* get "angle" (yaw) or "angles" (pitch yaw roll) */
802                 angles[ 0 ] = angles[ 1 ] = angles[ 2 ] = 0.0f;
803                 angles[ 2 ] = FloatForKey( e2, "angle" );
804                 value = ValueForKey( e2, "angles" );
805                 if( value[ 0 ] != '\0' )
806                         sscanf( value, "%f %f %f", &angles[ 1 ], &angles[ 2 ], &angles[ 0 ] );
807                 
808                 /* set transform matrix (thanks spog) */
809                 m4x4_identity( transform );
810                 m4x4_pivoted_transform_by_vec3( transform, origin, angles, eXYZ, scale, vec3_origin );
811                 
812                 /* get shader remappings */
813                 remap = NULL;
814                 for( ep = e2->epairs; ep != NULL; ep = ep->next )
815                 {
816                         /* look for keys prefixed with "_remap" */
817                         if( ep->key != NULL && ep->value != NULL &&
818                                 ep->key[ 0 ] != '\0' && ep->value[ 0 ] != '\0' &&
819                                 !Q_strncasecmp( ep->key, "_remap", 6 ) )
820                         {
821                                 /* create new remapping */
822                                 remap2 = remap;
823                                 remap = safe_malloc( sizeof( *remap ) );
824                                 remap->next = remap2;
825                                 strcpy( remap->from, ep->value );
826                                 
827                                 /* split the string */
828                                 split = strchr( remap->from, ';' );
829                                 if( split == NULL )
830                                 {
831                                         Sys_Printf( "WARNING: Shader _remap key found in misc_model without a ; character\n" );
832                                         free( remap );
833                                         remap = remap2;
834                                         continue;
835                                 }
836                                 
837                                 /* store the split */
838                                 *split = '\0';
839                                 strcpy( remap->to, (split + 1) );
840                                 
841                                 /* note it */
842                                 //%     Sys_FPrintf( SYS_VRB, "Remapping %s to %s\n", remap->from, remap->to );
843                         }
844                 }
845                 
846                 /* ydnar: cel shader support */
847                 value = ValueForKey( e2, "_celshader" );
848                 if( value[ 0 ] == '\0' )
849                         value = ValueForKey( &entities[ 0 ], "_celshader" );
850                 if( value[ 0 ] != '\0' )
851                 {
852                         sprintf( shader, "textures/%s", value );
853                         celShader = ShaderInfoForShader( shader );
854                 }
855                 else
856                         celShader = *globalCelShader ? ShaderInfoForShader(globalCelShader) : NULL;
857
858                 /* jal : entity based _samplesize */
859                 lightmapSampleSize = 0;
860                 if ( strcmp( "", ValueForKey( e2, "_lightmapsamplesize" ) ) )
861                         lightmapSampleSize = IntForKey( e2, "_lightmapsamplesize" );
862                 else if ( strcmp( "", ValueForKey( e2, "_samplesize" ) ) )
863                         lightmapSampleSize = IntForKey( e2, "_samplesize" );
864
865                 if( lightmapSampleSize < 0 )
866                         lightmapSampleSize = 0;
867
868                 if( lightmapSampleSize > 0.0f )
869                         Sys_Printf( "misc_model has lightmap sample size of %.d\n", lightmapSampleSize );
870
871                 /* get lightmap scale */
872                 /* vortex: added _ls key (short name of lightmapscale) */
873                 lightmapScale = 0.0f;
874                 if( strcmp( "", ValueForKey( e2, "lightmapscale" ) ) ||
875                         strcmp( "", ValueForKey( e2, "_lightmapscale" ) ) || 
876                         strcmp( "", ValueForKey( e2, "_ls" ) ) )
877                 {
878                         lightmapScale = FloatForKey( e2, "lightmapscale" );
879                         if( lightmapScale <= 0.0f )
880                                 lightmapScale = FloatForKey( e2, "_lightmapscale" );
881                         if( lightmapScale <= 0.0f )
882                                 lightmapScale = FloatForKey( e2, "_ls" );
883                         if( lightmapScale < 0.0f )
884                                 lightmapScale = 0.0f;
885                         if( lightmapScale > 0.0f )
886                                 Sys_Printf( "misc_model has lightmap scale of %.4f\n", lightmapScale );
887                 }
888
889                 /* jal : entity based _shadeangle */
890                 shadeAngle = 0.0f;
891                 if ( strcmp( "", ValueForKey( e2, "_shadeangle" ) ) )
892                         shadeAngle = FloatForKey( e2, "_shadeangle" );
893                 /* vortex' aliases */
894                 else if ( strcmp( "", ValueForKey( e2, "_smoothnormals" ) ) )
895                         shadeAngle = FloatForKey( e2, "_smoothnormals" );
896                 else if ( strcmp( "", ValueForKey( e2, "_sn" ) ) )
897                         shadeAngle = FloatForKey( e2, "_sn" );
898                 else if ( strcmp( "", ValueForKey( e2, "_smooth" ) ) )
899                         shadeAngle = FloatForKey( e2, "_smooth" );
900
901                 if( shadeAngle < 0.0f )
902                         shadeAngle = 0.0f;
903
904                 if( shadeAngle > 0.0f )
905                         Sys_Printf( "misc_model has shading angle of %.4f\n", shadeAngle );
906
907                 skin = IntForKey(e2, "skin");
908
909                 /* insert the model */
910                 InsertModel( model, skin, frame, transform, remap, celShader, mapEntityNum, castShadows, recvShadows, spawnFlags, lightmapScale, lightmapSampleSize, shadeAngle );
911                 
912                 /* free shader remappings */
913                 while( remap != NULL )
914                 {
915                         remap2 = remap->next;
916                         free( remap );
917                         remap = remap2;
918                 }
919         }
920 }