fix two bugs cppcheck found
[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( const char *name, byte **buffer, int *bufSize )
82 {
83         *bufSize = vfsLoadFile( 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( 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, 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         
233         
234         /* get model */
235         model = LoadModel( name, frame );
236         if( model == NULL )
237                 return;
238
239         /* load skin file */
240         snprintf(skinfilename, sizeof(skinfilename), "%s_%d.skin", name, skin);
241         skinfilename[sizeof(skinfilename)-1] = 0;
242         skinfilesize = vfsLoadFile(skinfilename, (void**) &skinfilecontent, 0);
243         if(skinfilesize < 0 && skin != 0)
244         {
245                 /* fallback to skin 0 if invalid */
246                 snprintf(skinfilename, sizeof(skinfilename), "%s_0.skin", name);
247                 skinfilename[sizeof(skinfilename)-1] = 0;
248                 skinfilesize = vfsLoadFile(skinfilename, (void**) &skinfilecontent, 0);
249                 if(skinfilesize >= 0)
250                         Sys_Printf( "Skin %d of %s does not exist, using 0 instead\n", skin, name );
251         }
252         sf = NULL;
253         if(skinfilesize >= 0)
254         {
255                 Sys_Printf( "Using skin %d of %s\n", skin, name );
256                 int pos;
257                 for(skinfileptr = skinfilecontent; *skinfileptr; skinfileptr = skinfilenextptr)
258                 {
259                         // for fscanf
260                         char format[64];
261
262                         skinfilenextptr = strchr(skinfileptr, '\r');
263                         if(skinfilenextptr)
264                         {
265                                 *skinfilenextptr++ = 0;
266                         }
267                         else
268                         {
269                                 skinfilenextptr = strchr(skinfileptr, '\n');
270                                 if(skinfilenextptr)
271                                         *skinfilenextptr++ = 0;
272                                 else
273                                         skinfilenextptr = skinfileptr + strlen(skinfileptr);
274                         }
275
276                         /* create new item */
277                         sf2 = sf;
278                         sf = safe_malloc( sizeof( *sf ) );
279                         sf->next = sf2;
280
281                         sprintf(format, "replace %%%ds %%%ds", (int)sizeof(sf->name)-1, (int)sizeof(sf->to)-1);
282                         if(sscanf(skinfileptr, format, sf->name, sf->to) == 2)
283                                 continue;
284                         sprintf(format, " %%%d[^,       ] ,%%%ds", (int)sizeof(sf->name)-1, (int)sizeof(sf->to)-1);
285                         if((pos = sscanf(skinfileptr, format, sf->name, sf->to)) == 2)
286                                 continue;
287
288                         /* invalid input line -> discard sf struct */
289                         Sys_Printf( "Discarding skin directive in %s: %s\n", skinfilename, skinfileptr );
290                         free(sf);
291                         sf = sf2;
292                 }
293                 free(skinfilecontent);
294         }
295         
296         /* handle null matrix */
297         if( transform == NULL )
298         {
299                 m4x4_identity( identity );
300                 transform = identity;
301         }
302         
303         /* hack: Stable-1_2 and trunk have differing row/column major matrix order
304            this transpose is necessary with Stable-1_2
305            uncomment the following line with old m4x4_t (non 1.3/spog_branch) code */
306         //%     m4x4_transpose( transform );
307         
308         /* create transform matrix for normals */
309         memcpy( nTransform, transform, sizeof( m4x4_t ) );
310         if( m4x4_invert( nTransform ) )
311                 Sys_FPrintf( SYS_VRB, "WARNING: Can't invert model transform matrix, using transpose instead\n" );
312         m4x4_transpose( nTransform );
313         
314         /* fix bogus lightmap scale */
315         if( lightmapScale <= 0.0f )
316                 lightmapScale = 1.0f;
317
318         /* fix bogus shade angle */
319         if( shadeAngle <= 0.0f )
320                 shadeAngle = 0.0f;
321         
322         /* each surface on the model will become a new map drawsurface */
323         numSurfaces = PicoGetModelNumSurfaces( model );
324         //%     Sys_FPrintf( SYS_VRB, "Model %s has %d surfaces\n", name, numSurfaces );
325         for( s = 0; s < numSurfaces; s++ )
326         {
327                 /* get surface */
328                 surface = PicoGetModelSurface( model, s );
329                 if( surface == NULL )
330                         continue;
331                 
332                 /* only handle triangle surfaces initially (fixme: support patches) */
333                 if( PicoGetSurfaceType( surface ) != PICO_TRIANGLES )
334                         continue;
335                 
336                 /* allocate a surface (ydnar: gs mods) */
337                 ds = AllocDrawSurface( SURFACE_TRIANGLES );
338                 ds->entityNum = eNum;
339                 ds->castShadows = castShadows;
340                 ds->recvShadows = recvShadows;
341                 
342                 /* get shader name */
343         shader = PicoGetSurfaceShader( surface );
344                 if( shader == NULL )
345                         picoShaderName = "";
346                 else
347                         picoShaderName = PicoGetShaderName( shader );
348
349                 /* handle .skin file */
350                 if(sf)
351                 {
352                         picoShaderName = NULL;
353                         for(sf2 = sf; sf2 != NULL; sf2 = sf2->next)
354                         {
355                                 if( !Q_stricmp( surface->name, sf2->name ) )
356                                 {
357                                         Sys_FPrintf( SYS_VRB, "Skin file: mapping %s to %s\n", surface->name, sf2->to );
358                                         picoShaderName = sf2->to;
359                                         break;
360                                 }
361                         }
362                         if(!picoShaderName)
363                         {
364                                 Sys_FPrintf( SYS_VRB, "Skin file: not mapping %s\n", surface->name );
365                                 continue;
366                         }
367                 }
368
369                 /* handle shader remapping */
370                 glob = NULL;
371                 for( rm = remap; rm != NULL; rm = rm->next )
372                 {
373                         if( rm->from[ 0 ] == '*' && rm->from[ 1 ] == '\0' )
374                                 glob = rm;
375                         else if( !Q_stricmp( picoShaderName, rm->from ) )
376                         {
377                                 Sys_FPrintf( SYS_VRB, "Remapping %s to %s\n", picoShaderName, rm->to );
378                                 picoShaderName = rm->to;
379                                 glob = NULL;
380                                 break;
381                         }
382                 }
383                 
384                 if( glob != NULL )
385                 {
386                         Sys_FPrintf( SYS_VRB, "Globbing %s to %s\n", picoShaderName, glob->to );
387                         picoShaderName = glob->to;
388                 }
389                 
390                 /* shader renaming for sof2 */
391                 if( renameModelShaders )
392                 {
393                         strcpy( shaderName, picoShaderName );
394                         StripExtension( shaderName );
395                         if( spawnFlags & 1 )
396                                 strcat( shaderName, "_RMG_BSP" );
397                         else
398                                 strcat( shaderName, "_BSP" );
399                         si = ShaderInfoForShader( shaderName );
400                 }
401                 else
402                         si = ShaderInfoForShader( picoShaderName );
403                 
404                 /* set shader */
405                 ds->shaderInfo = si;
406
407                 /* force to meta? */
408                 if( (si != NULL && si->forceMeta) || (spawnFlags & 4) ) /* 3rd bit */
409                         ds->type = SURFACE_FORCED_META;
410
411                 /* fix the surface's normals (jal: conditioned by shader info) */
412                 if( !(spawnFlags & 64) && ( shadeAngle == 0.0f || ds->type != SURFACE_FORCED_META ) )
413                         PicoFixSurfaceNormals( surface );
414
415                 /* set sample size */
416                 if( lightmapSampleSize > 0.0f )
417                         ds->sampleSize = lightmapSampleSize;
418                 
419                 /* set lightmap scale */
420                 if( lightmapScale > 0.0f )
421                         ds->lightmapScale = lightmapScale;
422
423                 /* set shading angle */
424                 if( shadeAngle > 0.0f )
425                         ds->shadeAngleDegrees = shadeAngle;
426                 
427                 /* set particulars */
428                 ds->numVerts = PicoGetSurfaceNumVertexes( surface );
429                 ds->verts = safe_malloc( ds->numVerts * sizeof( ds->verts[ 0 ] ) );
430                 memset( ds->verts, 0, ds->numVerts * sizeof( ds->verts[ 0 ] ) );
431                 
432                 ds->numIndexes = PicoGetSurfaceNumIndexes( surface );
433                 ds->indexes = safe_malloc( ds->numIndexes * sizeof( ds->indexes[ 0 ] ) );
434                 memset( ds->indexes, 0, ds->numIndexes * sizeof( ds->indexes[ 0 ] ) );
435                 
436                 /* copy vertexes */
437                 for( i = 0; i < ds->numVerts; i++ )
438                 {
439                         /* get vertex */
440                         dv = &ds->verts[ i ];
441                         
442                         /* xyz and normal */
443                         xyz = PicoGetSurfaceXYZ( surface, i );
444                         VectorCopy( xyz, dv->xyz );
445                         m4x4_transform_point( transform, dv->xyz );
446                         
447                         normal = PicoGetSurfaceNormal( surface, i );
448                         VectorCopy( normal, dv->normal );
449                         m4x4_transform_normal( nTransform, dv->normal );
450                         VectorNormalize( dv->normal, dv->normal );
451
452                         /* ydnar: tek-fu celshading support for flat shaded shit */
453                         if( flat )
454                         {
455                                 dv->st[ 0 ] = si->stFlat[ 0 ];
456                                 dv->st[ 1 ] = si->stFlat[ 1 ];
457                         }
458                         
459                         /* ydnar: gs mods: added support for explicit shader texcoord generation */
460                         else if( si->tcGen )
461                         {
462                                 /* project the texture */
463                                 dv->st[ 0 ] = DotProduct( si->vecs[ 0 ], dv->xyz );
464                                 dv->st[ 1 ] = DotProduct( si->vecs[ 1 ], dv->xyz );
465                         }
466                         
467                         /* normal texture coordinates */
468                         else
469                         {
470                                 st = PicoGetSurfaceST( surface, 0, i );
471                                 dv->st[ 0 ] = st[ 0 ];
472                                 dv->st[ 1 ] = st[ 1 ];
473                         }
474                         
475                         /* set lightmap/color bits */
476                         color = PicoGetSurfaceColor( surface, 0, i );
477                         for( j = 0; j < MAX_LIGHTMAPS; j++ )
478                         {
479                                 dv->lightmap[ j ][ 0 ] = 0.0f;
480                                 dv->lightmap[ j ][ 1 ] = 0.0f;
481                                 if(spawnFlags & 32) // spawnflag 32: model color -> alpha hack
482                                 {
483                                         dv->color[ j ][ 0 ] = 255.0f;
484                                         dv->color[ j ][ 1 ] = 255.0f;
485                                         dv->color[ j ][ 2 ] = 255.0f;
486                                         dv->color[ j ][ 3 ] = RGBTOGRAY( color );
487                                 }
488                                 else
489                                 {
490                                         dv->color[ j ][ 0 ] = color[ 0 ];
491                                         dv->color[ j ][ 1 ] = color[ 1 ];
492                                         dv->color[ j ][ 2 ] = color[ 2 ];
493                                         dv->color[ j ][ 3 ] = color[ 3 ];
494                                 }
495                         }
496                 }
497                 
498                 /* copy indexes */
499                 indexes = PicoGetSurfaceIndexes( surface, 0 );
500                 for( i = 0; i < ds->numIndexes; i++ )
501                         ds->indexes[ i ] = indexes[ i ];
502                 
503                 /* set cel shader */
504                 ds->celShader = celShader;
505                 
506                 /* ydnar: giant hack land: generate clipping brushes for model triangles */
507                 if( si->clipModel || (spawnFlags & 2) ) /* 2nd bit */
508                 {
509                         vec3_t          points[ 4 ], backs[ 3 ];
510                         vec4_t          plane, reverse, pa, pb, pc;
511                         
512                         
513                         /* temp hack */
514                         if( !si->clipModel && !(si->compileFlags & C_SOLID) )
515                                 continue;
516                         
517                         /* walk triangle list */
518                         for( i = 0; i < ds->numIndexes; i += 3 )
519                         {
520                                 /* overflow hack */
521                                 AUTOEXPAND_BY_REALLOC(mapplanes, (nummapplanes+64) << 1, allocatedmapplanes, 1024);
522                                 
523                                 /* make points and back points */
524                                 for( j = 0; j < 3; j++ )
525                                 {
526                                         /* get vertex */
527                                         dv = &ds->verts[ ds->indexes[ i + j ] ];
528                                         
529                                         /* copy xyz */
530                                         VectorCopy( dv->xyz, points[ j ] );
531                                         VectorCopy( dv->xyz, backs[ j ] );
532                                         
533                                         /* find nearest axial to normal and push back points opposite */
534                                         /* note: this doesn't work as well as simply using the plane of the triangle, below */
535                                         for( k = 0; k < 3; k++ )
536                                         {
537                                                 if( fabs( dv->normal[ k ] ) >= fabs( dv->normal[ (k + 1) % 3 ] ) &&
538                                                         fabs( dv->normal[ k ] ) >= fabs( dv->normal[ (k + 2) % 3 ] ) )
539                                                 {
540                                                         backs[ j ][ k ] += dv->normal[ k ] < 0.0f ? 64.0f : -64.0f;
541                                                         break;
542                                                 }
543                                         }
544                                 }
545
546                                 VectorCopy( points[0], points[3] ); // for cyclic usage
547                                 
548                                 /* make plane for triangle */
549                                 // div0: add some extra spawnflags:
550                                 //   0: snap normals to axial planes for extrusion
551                                 //   8: extrude with the original normals
552                                 //  16: extrude only with up/down normals (ideal for terrain)
553                                 //  24: extrude by distance zero (may need engine changes)
554                                 if( PlaneFromPoints( plane, points[ 0 ], points[ 1 ], points[ 2 ] ) )
555                                 {
556                                         vec3_t bestNormal;
557                                         float backPlaneDistance = 2;
558
559                                         if(spawnFlags & 8) // use a DOWN normal
560                                         {
561                                                 if(spawnFlags & 16)
562                                                 {
563                                                         // 24: normal as is, and zero width (broken)
564                                                         VectorCopy(plane, bestNormal);
565                                                 }
566                                                 else
567                                                 {
568                                                         // 8: normal as is
569                                                         VectorCopy(plane, bestNormal);
570                                                 }
571                                         }
572                                         else
573                                         {
574                                                 if(spawnFlags & 16)
575                                                 {
576                                                         // 16: UP/DOWN normal
577                                                         VectorSet(bestNormal, 0, 0, (plane[2] >= 0 ? 1 : -1));
578                                                 }
579                                                 else
580                                                 {
581                                                         // 0: axial normal
582                                                         if(fabs(plane[0]) > fabs(plane[1])) // x>y
583                                                                 if(fabs(plane[1]) > fabs(plane[2])) // x>y, y>z
584                                                                         VectorSet(bestNormal, (plane[0] >= 0 ? 1 : -1), 0, 0);
585                                                                 else // x>y, z>=y
586                                                                         if(fabs(plane[0]) > fabs(plane[2])) // x>z, z>=y
587                                                                                 VectorSet(bestNormal, (plane[0] >= 0 ? 1 : -1), 0, 0);
588                                                                         else // z>=x, x>y
589                                                                                 VectorSet(bestNormal, 0, 0, (plane[2] >= 0 ? 1 : -1));
590                                                         else // y>=x
591                                                                 if(fabs(plane[1]) > fabs(plane[2])) // y>z, y>=x
592                                                                         VectorSet(bestNormal, 0, (plane[1] >= 0 ? 1 : -1), 0);
593                                                                 else // z>=y, y>=x
594                                                                         VectorSet(bestNormal, 0, 0, (plane[2] >= 0 ? 1 : -1));
595                                                 }
596                                         }
597
598                                         /* build a brush */
599                                         buildBrush = AllocBrush( 48 );
600                                         buildBrush->entityNum = mapEntityNum;
601                                         buildBrush->original = buildBrush;
602                                         buildBrush->contentShader = si;
603                                         buildBrush->compileFlags = si->compileFlags;
604                                         buildBrush->contentFlags = si->contentFlags;
605                                         normalEpsilon_save = normalEpsilon;
606                                         distanceEpsilon_save = distanceEpsilon;
607                                         if(si->compileFlags & C_STRUCTURAL) // allow forced structural brushes here
608                                         {
609                                                 buildBrush->detail = qfalse;
610
611                                                 // only allow EXACT matches when snapping for these (this is mostly for caulk brushes inside a model)
612                                                 if(normalEpsilon > 0)
613                                                         normalEpsilon = 0;
614                                                 if(distanceEpsilon > 0)
615                                                         distanceEpsilon = 0;
616                                         }
617                                         else
618                                                 buildBrush->detail = qtrue;
619
620                                         /* regenerate back points */
621                                         for( j = 0; j < 3; j++ )
622                                         {
623                                                 /* get vertex */
624                                                 dv = &ds->verts[ ds->indexes[ i + j ] ];
625
626                                                 // shift by some units
627                                                 VectorMA(dv->xyz, -64.0f, bestNormal, backs[j]); // 64 prevents roundoff errors a bit
628                                         }
629
630                                         /* make back plane */
631                                         VectorScale( plane, -1.0f, reverse );
632                                         reverse[ 3 ] = -plane[ 3 ];
633                                         if((spawnFlags & 24) != 24)
634                                                 reverse[3] += DotProduct(bestNormal, plane) * backPlaneDistance;
635                                         // 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)
636
637                                         if( PlaneFromPoints( pa, points[ 2 ], points[ 1 ], backs[ 1 ] ) &&
638                                                         PlaneFromPoints( pb, points[ 1 ], points[ 0 ], backs[ 0 ] ) &&
639                                                         PlaneFromPoints( pc, points[ 0 ], points[ 2 ], backs[ 2 ] ) )
640                                         {
641                                                 /* set up brush sides */
642                                                 buildBrush->numsides = 5;
643                                                 buildBrush->sides[ 0 ].shaderInfo = si;
644                                                 for( j = 1; j < buildBrush->numsides; j++ )
645                                                         buildBrush->sides[ j ].shaderInfo = NULL; // don't emit these faces as draw surfaces, should make smaller BSPs; hope this works
646
647                                                 buildBrush->sides[ 0 ].planenum = FindFloatPlane( plane, plane[ 3 ], 3, points );
648                                                 buildBrush->sides[ 1 ].planenum = FindFloatPlane( pa, pa[ 3 ], 2, &points[ 1 ] ); // pa contains points[1] and points[2]
649                                                 buildBrush->sides[ 2 ].planenum = FindFloatPlane( pb, pb[ 3 ], 2, &points[ 0 ] ); // pb contains points[0] and points[1]
650                                                 buildBrush->sides[ 3 ].planenum = FindFloatPlane( pc, pc[ 3 ], 2, &points[ 2 ] ); // pc contains points[2] and points[0] (copied to points[3]
651                                                 buildBrush->sides[ 4 ].planenum = FindFloatPlane( reverse, reverse[ 3 ], 3, backs );
652                                         }
653                                         else
654                                         {
655                                                 free(buildBrush);
656                                                 continue;
657                                         }
658
659                                         normalEpsilon = normalEpsilon_save;
660                                         distanceEpsilon = distanceEpsilon_save;
661
662                                         /* add to entity */
663                                         if( CreateBrushWindings( buildBrush ) )
664                                         {
665                                                 AddBrushBevels();
666                                                 //%     EmitBrushes( buildBrush, NULL, NULL );
667                                                 buildBrush->next = entities[ mapEntityNum ].brushes;
668                                                 entities[ mapEntityNum ].brushes = buildBrush;
669                                                 entities[ mapEntityNum ].numBrushes++;
670                                         }
671                                         else
672                                                 free( buildBrush );
673                                 }
674                         }
675                 }
676         }
677 }
678
679
680
681 /*
682 AddTriangleModels()
683 adds misc_model surfaces to the bsp
684 */
685
686 void AddTriangleModels( entity_t *e )
687 {
688         int                             num, frame, skin, castShadows, recvShadows, spawnFlags;
689         entity_t                *e2;
690         const char              *targetName;
691         const char              *target, *model, *value;
692         char                    shader[ MAX_QPATH ];
693         shaderInfo_t    *celShader;
694         float                   temp, baseLightmapScale, lightmapScale;
695         float                   shadeAngle;
696         int                             lightmapSampleSize;
697         vec3_t                  origin, scale, angles;
698         m4x4_t                  transform;
699         epair_t                 *ep;
700         remap_t                 *remap, *remap2;
701         char                    *split;
702         
703         
704         /* note it */
705         Sys_FPrintf( SYS_VRB, "--- AddTriangleModels ---\n" );
706         
707         /* get current brush entity targetname */
708         if( e == entities )
709                 targetName = "";
710         else
711         {
712                 targetName = ValueForKey( e, "targetname" );
713         
714                 /* misc_model entities target non-worldspawn brush model entities */
715                 if( targetName[ 0 ] == '\0' )
716                         return;
717         }
718         
719         /* get lightmap scale */
720         /* vortex: added _ls key (short name of lightmapscale) */
721         baseLightmapScale = 0.0f;
722         if( strcmp( "", ValueForKey( e, "lightmapscale" ) ) ||
723                 strcmp( "", ValueForKey( e, "_lightmapscale" ) ) || 
724                 strcmp( "", ValueForKey( e, "_ls" ) ) )
725         {
726                 baseLightmapScale = FloatForKey( e, "lightmapscale" );
727                 if( baseLightmapScale <= 0.0f )
728                         baseLightmapScale = FloatForKey( e, "_lightmapscale" );
729                 if( baseLightmapScale <= 0.0f )
730                         baseLightmapScale = FloatForKey( e, "_ls" );
731                 if( baseLightmapScale < 0.0f )
732                         baseLightmapScale = 0.0f;
733                 if( baseLightmapScale > 0.0f )
734                         Sys_Printf( "World Entity has lightmap scale of %.4f\n", baseLightmapScale );
735         }
736         
737         
738         /* walk the entity list */
739         for( num = 1; num < numEntities; num++ )
740         {
741                 /* get e2 */
742                 e2 = &entities[ num ];
743                 
744                 /* convert misc_models into raw geometry */
745                 if( Q_stricmp( "misc_model", ValueForKey( e2, "classname" ) ) )
746                         continue;
747
748                 /* ydnar: added support for md3 models on non-worldspawn models */
749                 target = ValueForKey( e2, "target" );
750                 if( strcmp( target, targetName ) )
751                         continue;
752                 
753                 /* get model name */
754                 model = ValueForKey( e2, "model" );
755                 if( model[ 0 ] == '\0' )
756                 {
757                         Sys_Printf( "WARNING: misc_model at %i %i %i without a model key\n",
758                                 (int) origin[ 0 ], (int) origin[ 1 ], (int) origin[ 2 ] );
759                         continue;
760                 }
761                 
762                 /* get model frame */
763                 frame = IntForKey( e2, "_frame" );
764                 
765                 /* worldspawn (and func_groups) default to cast/recv shadows in worldspawn group */
766                 if( e == entities )
767                 {
768                         castShadows = WORLDSPAWN_CAST_SHADOWS;
769                         recvShadows = WORLDSPAWN_RECV_SHADOWS;
770                 }
771                 
772                 /* other entities don't cast any shadows, but recv worldspawn shadows */
773                 else
774                 {
775                         castShadows = ENTITY_CAST_SHADOWS;
776                         recvShadows = ENTITY_RECV_SHADOWS;
777                 }
778                 
779                 /* get explicit shadow flags */
780                 GetEntityShadowFlags( e2, e, &castShadows, &recvShadows );
781                 
782                 /* get spawnflags */
783                 spawnFlags = IntForKey( e2, "spawnflags" );
784                 
785                 /* get origin */
786                 GetVectorForKey( e2, "origin", origin );
787                 VectorSubtract( origin, e->origin, origin );    /* offset by parent */
788                 
789                 /* get scale */
790                 scale[ 0 ] = scale[ 1 ] = scale[ 2 ] = 1.0f;
791                 temp = FloatForKey( e2, "modelscale" );
792                 if( temp != 0.0f )
793                         scale[ 0 ] = scale[ 1 ] = scale[ 2 ] = temp;
794                 value = ValueForKey( e2, "modelscale_vec" );
795                 if( value[ 0 ] != '\0' )
796                         sscanf( value, "%f %f %f", &scale[ 0 ], &scale[ 1 ], &scale[ 2 ] );
797                 
798                 /* get "angle" (yaw) or "angles" (pitch yaw roll) */
799                 angles[ 0 ] = angles[ 1 ] = angles[ 2 ] = 0.0f;
800                 angles[ 2 ] = FloatForKey( e2, "angle" );
801                 value = ValueForKey( e2, "angles" );
802                 if( value[ 0 ] != '\0' )
803                         sscanf( value, "%f %f %f", &angles[ 1 ], &angles[ 2 ], &angles[ 0 ] );
804                 
805                 /* set transform matrix (thanks spog) */
806                 m4x4_identity( transform );
807                 m4x4_pivoted_transform_by_vec3( transform, origin, angles, eXYZ, scale, vec3_origin );
808                 
809                 /* get shader remappings */
810                 remap = NULL;
811                 for( ep = e2->epairs; ep != NULL; ep = ep->next )
812                 {
813                         /* look for keys prefixed with "_remap" */
814                         if( ep->key != NULL && ep->value != NULL &&
815                                 ep->key[ 0 ] != '\0' && ep->value[ 0 ] != '\0' &&
816                                 !Q_strncasecmp( ep->key, "_remap", 6 ) )
817                         {
818                                 /* create new remapping */
819                                 remap2 = remap;
820                                 remap = safe_malloc( sizeof( *remap ) );
821                                 remap->next = remap2;
822                                 strcpy( remap->from, ep->value );
823                                 
824                                 /* split the string */
825                                 split = strchr( remap->from, ';' );
826                                 if( split == NULL )
827                                 {
828                                         Sys_Printf( "WARNING: Shader _remap key found in misc_model without a ; character\n" );
829                                         free( remap );
830                                         remap = remap2;
831                                         continue;
832                                 }
833                                 
834                                 /* store the split */
835                                 *split = '\0';
836                                 strcpy( remap->to, (split + 1) );
837                                 
838                                 /* note it */
839                                 //%     Sys_FPrintf( SYS_VRB, "Remapping %s to %s\n", remap->from, remap->to );
840                         }
841                 }
842                 
843                 /* ydnar: cel shader support */
844                 value = ValueForKey( e2, "_celshader" );
845                 if( value[ 0 ] == '\0' )
846                         value = ValueForKey( &entities[ 0 ], "_celshader" );
847                 if( value[ 0 ] != '\0' )
848                 {
849                         sprintf( shader, "textures/%s", value );
850                         celShader = ShaderInfoForShader( shader );
851                 }
852                 else
853                         celShader = *globalCelShader ? ShaderInfoForShader(globalCelShader) : NULL;
854
855                 /* jal : entity based _samplesize */
856                 lightmapSampleSize = 0;
857                 if ( strcmp( "", ValueForKey( e2, "_lightmapsamplesize" ) ) )
858                         lightmapSampleSize = IntForKey( e2, "_lightmapsamplesize" );
859                 else if ( strcmp( "", ValueForKey( e2, "_samplesize" ) ) )
860                         lightmapSampleSize = IntForKey( e2, "_samplesize" );
861
862                 if( lightmapSampleSize < 0 )
863                         lightmapSampleSize = 0;
864
865                 if( lightmapSampleSize > 0.0f )
866                         Sys_Printf( "misc_model has lightmap sample size of %.d\n", lightmapSampleSize );
867
868                 /* get lightmap scale */
869                 /* vortex: added _ls key (short name of lightmapscale) */
870                 lightmapScale = 0.0f;
871                 if( strcmp( "", ValueForKey( e2, "lightmapscale" ) ) ||
872                         strcmp( "", ValueForKey( e2, "_lightmapscale" ) ) || 
873                         strcmp( "", ValueForKey( e2, "_ls" ) ) )
874                 {
875                         lightmapScale = FloatForKey( e2, "lightmapscale" );
876                         if( lightmapScale <= 0.0f )
877                                 lightmapScale = FloatForKey( e2, "_lightmapscale" );
878                         if( lightmapScale <= 0.0f )
879                                 lightmapScale = FloatForKey( e2, "_ls" );
880                         if( lightmapScale < 0.0f )
881                                 lightmapScale = 0.0f;
882                         if( lightmapScale > 0.0f )
883                                 Sys_Printf( "misc_model has lightmap scale of %.4f\n", lightmapScale );
884                 }
885
886                 /* jal : entity based _shadeangle */
887                 shadeAngle = 0.0f;
888                 if ( strcmp( "", ValueForKey( e2, "_shadeangle" ) ) )
889                         shadeAngle = FloatForKey( e2, "_shadeangle" );
890                 /* vortex' aliases */
891                 else if ( strcmp( "", ValueForKey( e2, "_smoothnormals" ) ) )
892                         shadeAngle = FloatForKey( e2, "_smoothnormals" );
893                 else if ( strcmp( "", ValueForKey( e2, "_sn" ) ) )
894                         shadeAngle = FloatForKey( e2, "_sn" );
895                 else if ( strcmp( "", ValueForKey( e2, "_smooth" ) ) )
896                         shadeAngle = FloatForKey( e2, "_smooth" );
897
898                 if( shadeAngle < 0.0f )
899                         shadeAngle = 0.0f;
900
901                 if( shadeAngle > 0.0f )
902                         Sys_Printf( "misc_model has shading angle of %.4f\n", shadeAngle );
903
904                 skin = IntForKey(e2, "skin");
905
906                 /* insert the model */
907                 InsertModel( model, skin, frame, transform, remap, celShader, mapEntityNum, castShadows, recvShadows, spawnFlags, lightmapScale, lightmapSampleSize, shadeAngle );
908                 
909                 /* free shader remappings */
910                 while( remap != NULL )
911                 {
912                         remap2 = remap->next;
913                         free( remap );
914                         remap = remap2;
915                 }
916         }
917 }