forked from hitmen047/Source-PlusPlus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvradstaticprops.cpp
2721 lines (2287 loc) · 88.5 KB
/
vradstaticprops.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Revision: $
// $NoKeywords: $
//
// This file contains code to allow us to associate client data with bsp leaves.
//
//=============================================================================//
#include "vrad.h"
#include "mathlib/vector.h"
#include "UtlBuffer.h"
#include "utlvector.h"
#include "GameBSPFile.h"
#include "BSPTreeData.h"
#include "VPhysics_Interface.h"
#include "Studio.h"
#include "Optimize.h"
#include "Bsplib.h"
#include "CModel.h"
#include "PhysDll.h"
#include "phyfile.h"
#include "collisionutils.h"
#include "tier1/KeyValues.h"
#include "pacifier.h"
#include "materialsystem/imaterial.h"
#include "materialsystem/hardwareverts.h"
#include "materialsystem/hardwaretexels.h"
#include "byteswap.h"
#include "mpivrad.h"
#include "vtf/vtf.h"
#include "tier1/utldict.h"
#include "tier1/utlsymbol.h"
#include "bitmap/tgawriter.h"
#include "messbuf.h"
#include "vmpi.h"
#include "vmpi_distribute_work.h"
#define ALIGN_TO_POW2(x,y) (((x)+(y-1))&~(y-1))
// identifies a vertex embedded in solid
// lighting will be copied from nearest valid neighbor
struct badVertex_t
{
int m_ColorVertex;
Vector m_Position;
Vector m_Normal;
};
// a final colored vertex
struct colorVertex_t
{
Vector m_Color;
Vector m_Position;
bool m_bValid;
};
// a texel suitable for a model
struct colorTexel_t
{
Vector m_Color;
Vector m_WorldPosition;
Vector m_WorldNormal;
float m_fDistanceToTri; // If we are outside of the triangle, how far away is it?
bool m_bValid;
bool m_bPossiblyInteresting;
};
class CComputeStaticPropLightingResults
{
public:
~CComputeStaticPropLightingResults()
{
m_ColorVertsArrays.PurgeAndDeleteElements();
m_ColorTexelsArrays.PurgeAndDeleteElements();
}
CUtlVector< CUtlVector<colorVertex_t>* > m_ColorVertsArrays;
CUtlVector< CUtlVector<colorTexel_t>* > m_ColorTexelsArrays;
};
//-----------------------------------------------------------------------------
struct Rasterizer
{
struct Location
{
Vector barycentric;
Vector2D uv;
bool insideTriangle;
};
Rasterizer(Vector2D t0, Vector2D t1, Vector2D t2, size_t resX, size_t resY)
: mT0(t0)
, mT1(t1)
, mT2(t2)
, mResX(resX)
, mResY(resY)
, mUvStepX(1.0f / resX)
, mUvStepY(1.0f / resY)
{
Build();
}
CUtlVector< Location >::iterator begin() { return mRasterizedLocations.begin(); }
CUtlVector< Location >::iterator end() { return mRasterizedLocations.end(); }
void Build();
inline size_t GetRow(float y) const { return size_t(y * mResY); }
inline size_t GetCol(float x) const { return size_t(x * mResX); }
inline size_t GetLinearPos( const CUtlVector< Location >::iterator& it ) const
{
// Given an iterator, return what the linear position in the buffer would be for the data.
return (size_t)(GetRow(it->uv.y) * mResX)
+ (size_t)(GetCol(it->uv.x));
}
private:
const Vector2D mT0, mT1, mT2;
const size_t mResX, mResY;
const float mUvStepX, mUvStepY;
// Right now, we just fill this out and directly iterate over it.
// It could be large. This is a memory/speed tradeoff. We could instead generate them
// on demand.
CUtlVector< Location > mRasterizedLocations;
};
//-----------------------------------------------------------------------------
inline Vector ComputeBarycentric( Vector2D _edgeC, Vector2D _edgeA, Vector2D _edgeB, float _dAA, float _dAB, float _dBB, float _invDenom )
{
float dCA = _edgeC.Dot(_edgeA);
float dCB = _edgeC.Dot(_edgeB);
Vector retVal;
retVal.y = (_dBB * dCA - _dAB * dCB) * _invDenom;
retVal.z = (_dAA * dCB - _dAB * dCA) * _invDenom;
retVal.x = 1.0f - retVal.y - retVal.z;
return retVal;
}
//-----------------------------------------------------------------------------
void Rasterizer::Build()
{
// For now, use the barycentric method. It's easy, I'm lazy.
// We can optimize later if it's a performance issue.
const float baseX = mUvStepX / 2.0f;
const float baseY = mUvStepY / 2.0f;
float fMinX = min(min(mT0.x, mT1.x), mT2.x);
float fMinY = min(min(mT0.y, mT1.y), mT2.y);
float fMaxX = max(max(mT0.x, mT1.x), mT2.x);
float fMaxY = max(max(mT0.y, mT1.y), mT2.y);
// Degenerate. Consider warning about these, but otherwise no problem.
if (fMinX == fMaxX || fMinY == fMaxY)
return;
// Clamp to 0..1
fMinX = max(0, fMinX);
fMinY = max(0, fMinY);
fMaxX = min(1.0f, fMaxX);
fMaxY = min(1.0f, fMaxY);
// We puff the interesting area up by 1 so we can hit an inflated region for the necessary bilerp data.
// If we wanted to support better texturing (almost definitely unnecessary), we'd change this to a larger size.
const int kFilterSampleRadius = 1;
int iMinX = GetCol(fMinX) - kFilterSampleRadius;
int iMinY = GetRow(fMinY) - kFilterSampleRadius;
int iMaxX = GetCol(fMaxX) + 1 + kFilterSampleRadius;
int iMaxY = GetRow(fMaxY) + 1 + kFilterSampleRadius;
// Clamp to valid texture (integer) locations
iMinX = max(0, iMinX);
iMinY = max(0, iMinY);
iMaxX = min(iMaxX, mResX - 1);
iMaxY = min(iMaxY, mResY - 1);
// Set the size to be as expected.
// TODO: Pass this in from outside to minimize allocations
int count = (iMaxY - iMinY + 1)
* (iMaxX - iMinX + 1);
mRasterizedLocations.EnsureCount(count);
memset( mRasterizedLocations.Base(), 0, mRasterizedLocations.Count() * sizeof( Location ) );
// Computing Barycentrics adapted from here http://gamedev.stackexchange.com/questions/23743/whats-the-most-efficient-way-to-find-barycentric-coordinates
Vector2D edgeA = mT1 - mT0;
Vector2D edgeB = mT2 - mT0;
float dAA = edgeA.Dot(edgeA);
float dAB = edgeA.Dot(edgeB);
float dBB = edgeB.Dot(edgeB);
float invDenom = 1.0f / (dAA * dBB - dAB * dAB);
int linearPos = 0;
for (int j = iMinY; j <= iMaxY; ++j) {
for (int i = iMinX; i <= iMaxX; ++i) {
Vector2D testPt( i * mUvStepX + baseX, j * mUvStepY + baseY );
Vector barycentric = ComputeBarycentric( testPt - mT0, edgeA, edgeB, dAA, dAB, dBB, invDenom );
// Test whether the point is inside the triangle.
// MCJOHNTODO: Edge rules and whatnot--right now we re-rasterize points on the edge.
Location& newLoc = mRasterizedLocations[linearPos++];
newLoc.barycentric = barycentric;
newLoc.uv = testPt;
newLoc.insideTriangle = (barycentric.x >= 0.0f && barycentric.x <= 1.0f && barycentric.y >= 0.0f && barycentric.y <= 1.0f && barycentric.z >= 0.0f && barycentric.z <= 1.0f);
}
}
}
//-----------------------------------------------------------------------------
// Globals
//-----------------------------------------------------------------------------
CUtlSymbolTable g_ForcedTextureShadowsModels;
// DON'T USE THIS FROM WITHIN A THREAD. THERE IS A THREAD CONTEXT CREATED
// INSIDE PropTested_t. USE THAT INSTEAD.
IPhysicsCollision *s_pPhysCollision = NULL;
static void ConvertTexelDataToTexture(unsigned int _resX, unsigned int _resY, ImageFormat _destFmt, const CUtlVector<colorTexel_t>& _srcTexels, CUtlMemory<byte>* _outTexture);
// Such a monstrosity. :(
static void GenerateLightmapSamplesForMesh( const matrix3x4_t& _matPos, const matrix3x4_t& _matNormal, int _iThread, int _skipProp, int _nFlags, int _lightmapResX, int _lightmapResY,
studiohdr_t* _pStudioHdr, mstudiomodel_t* _pStudioModel, OptimizedModel::ModelHeader_t* _pVtxModel, int _meshID,
CComputeStaticPropLightingResults *_pResults );
// Debug function, converts lightmaps to linear space then dumps them out.
// TODO: Write out the file in a .dds instead of a .tga, in whatever format we're supposed to use.
static void DumpLightmapLinear( const char* _dstFilename, const CUtlVector<colorTexel_t>& _srcTexels, int _width, int _height );
//-----------------------------------------------------------------------------
// Vrad's static prop manager
//-----------------------------------------------------------------------------
class CVradStaticPropMgr : public IVradStaticPropMgr
{
public:
// constructor, destructor
CVradStaticPropMgr();
virtual ~CVradStaticPropMgr();
// methods of IStaticPropMgr
void Init();
void Shutdown();
// iterate all the instanced static props and compute their vertex lighting
void ComputeLighting( int iThread );
private:
// VMPI stuff.
static void VMPI_ProcessStaticProp_Static( int iThread, uint64 iStaticProp, MessageBuffer *pBuf );
static void VMPI_ReceiveStaticPropResults_Static( uint64 iStaticProp, MessageBuffer *pBuf, int iWorker );
void VMPI_ProcessStaticProp( int iThread, int iStaticProp, MessageBuffer *pBuf );
void VMPI_ReceiveStaticPropResults( int iStaticProp, MessageBuffer *pBuf, int iWorker );
// local thread version
static void ThreadComputeStaticPropLighting( int iThread, void *pUserData );
void ComputeLightingForProp( int iThread, int iStaticProp );
// Methods associated with unserializing static props
void UnserializeModelDict( CUtlBuffer& buf );
void UnserializeModels( CUtlBuffer& buf );
void UnserializeStaticProps();
// Creates a collision model
void CreateCollisionModel( char const* pModelName );
private:
// Unique static prop models
struct StaticPropDict_t
{
vcollide_t m_loadedModel;
CPhysCollide* m_pModel;
Vector m_Mins; // Bounding box is in local coordinates
Vector m_Maxs;
studiohdr_t* m_pStudioHdr;
CUtlBuffer m_VtxBuf;
CUtlVector<int> m_textureShadowIndex; // each texture has an index if this model casts texture shadows
CUtlVector<int> m_triangleMaterialIndex;// each triangle has an index if this model casts texture shadows
};
struct MeshData_t
{
CUtlVector<Vector> m_VertexColors;
CUtlMemory<byte> m_TexelsEncoded;
int m_nLod;
};
// A static prop instance
struct CStaticProp
{
Vector m_Origin;
QAngle m_Angles;
Vector m_mins;
Vector m_maxs;
Vector m_LightingOrigin;
int m_ModelIdx;
BSPTreeDataHandle_t m_Handle;
CUtlVector<MeshData_t> m_MeshData;
int m_Flags;
bool m_bLightingOriginValid;
// Note that all lightmaps for a given prop share the same resolution (and format)--and there can be multiple lightmaps
// per prop (if there are multiple pieces--the watercooler is an example).
// This is effectively because there's not a good way in hammer for a prop to say "this should be the resolution
// of each of my sub-pieces."
ImageFormat m_LightmapImageFormat;
unsigned int m_LightmapImageWidth;
unsigned int m_LightmapImageHeight;
};
// Enumeration context
struct EnumContext_t
{
PropTested_t* m_pPropTested;
Ray_t const* m_pRay;
};
// The list of all static props
CUtlVector <StaticPropDict_t> m_StaticPropDict;
CUtlVector <CStaticProp> m_StaticProps;
bool m_bIgnoreStaticPropTrace;
void ComputeLighting( CStaticProp &prop, int iThread, int prop_index, CComputeStaticPropLightingResults *pResults );
void ApplyLightingToStaticProp( int iStaticProp, CStaticProp &prop, const CComputeStaticPropLightingResults *pResults );
void SerializeLighting();
void AddPolysForRayTrace();
void BuildTriList( CStaticProp &prop );
};
//-----------------------------------------------------------------------------
// Expose IVradStaticPropMgr to vrad
//-----------------------------------------------------------------------------
static CVradStaticPropMgr g_StaticPropMgr;
IVradStaticPropMgr* StaticPropMgr()
{
return &g_StaticPropMgr;
}
//-----------------------------------------------------------------------------
// constructor, destructor
//-----------------------------------------------------------------------------
CVradStaticPropMgr::CVradStaticPropMgr()
{
// set to ignore static prop traces
m_bIgnoreStaticPropTrace = false;
}
CVradStaticPropMgr::~CVradStaticPropMgr()
{
}
//-----------------------------------------------------------------------------
// Makes sure the studio model is a static prop
//-----------------------------------------------------------------------------
bool IsStaticProp( studiohdr_t* pHdr )
{
if (!(pHdr->flags & STUDIOHDR_FLAGS_STATIC_PROP))
return false;
return true;
}
//-----------------------------------------------------------------------------
// Load a file into a Utlbuf
//-----------------------------------------------------------------------------
static bool LoadFile( char const* pFileName, CUtlBuffer& buf )
{
if ( !g_pFullFileSystem )
return false;
return g_pFullFileSystem->ReadFile( pFileName, NULL, buf );
}
//-----------------------------------------------------------------------------
// Constructs the file name from the model name
//-----------------------------------------------------------------------------
static char const* ConstructFileName( char const* pModelName )
{
static char buf[1024];
sprintf( buf, "%s%s", gamedir, pModelName );
return buf;
}
//-----------------------------------------------------------------------------
// Computes a convex hull from a studio mesh
//-----------------------------------------------------------------------------
static CPhysConvex* ComputeConvexHull( mstudiomesh_t* pMesh, studiohdr_t *pStudioHdr )
{
const mstudio_meshvertexdata_t *vertData = pMesh->GetVertexData( (void *)pStudioHdr );
Assert( vertData ); // This can only return NULL on X360 for now
// Generate a list of all verts in the mesh
Vector** ppVerts = (Vector**)_alloca(pMesh->numvertices * sizeof(Vector*) );
for (int i = 0; i < pMesh->numvertices; ++i)
{
ppVerts[i] = vertData->Position(i);
}
// Generate a convex hull from the verts
return s_pPhysCollision->ConvexFromVerts( ppVerts, pMesh->numvertices );
}
//-----------------------------------------------------------------------------
// Computes a convex hull from the studio model
//-----------------------------------------------------------------------------
CPhysCollide* ComputeConvexHull( studiohdr_t* pStudioHdr )
{
CUtlVector<CPhysConvex*> convexHulls;
for (int body = 0; body < pStudioHdr->numbodyparts; ++body )
{
mstudiobodyparts_t *pBodyPart = pStudioHdr->pBodypart( body );
for( int model = 0; model < pBodyPart->nummodels; ++model )
{
mstudiomodel_t *pStudioModel = pBodyPart->pModel( model );
for( int mesh = 0; mesh < pStudioModel->nummeshes; ++mesh )
{
// Make a convex hull for each mesh
// NOTE: This won't work unless the model has been compiled
// with $staticprop
mstudiomesh_t *pStudioMesh = pStudioModel->pMesh( mesh );
convexHulls.AddToTail( ComputeConvexHull( pStudioMesh, pStudioHdr ) );
}
}
}
// Convert an array of convex elements to a compiled collision model
// (this deletes the convex elements)
return s_pPhysCollision->ConvertConvexToCollide( convexHulls.Base(), convexHulls.Size() );
}
//-----------------------------------------------------------------------------
// Load studio model vertex data from a file...
//-----------------------------------------------------------------------------
bool LoadStudioModel( char const* pModelName, CUtlBuffer& buf )
{
// No luck, gotta build it
// Construct the file name...
if (!LoadFile( pModelName, buf ))
{
Warning("Error! Unable to load model \"%s\"\n", pModelName );
return false;
}
// Check that it's valid
if (strncmp ((const char *) buf.PeekGet(), "IDST", 4) &&
strncmp ((const char *) buf.PeekGet(), "IDAG", 4))
{
Warning("Error! Invalid model file \"%s\"\n", pModelName );
return false;
}
studiohdr_t* pHdr = (studiohdr_t*)buf.PeekGet();
Studio_ConvertStudioHdrToNewVersion( pHdr );
if (pHdr->version != STUDIO_VERSION)
{
if ( g_bIgnoreModelVersions )
{
Warning( "Warning! Unexpected model version \"%s\"\n", pModelName );
}
else
{
Warning( "Error! Invalid model version \"%s\"\n", pModelName );
return false;
}
}
if (!IsStaticProp(pHdr))
{
if ( !g_bAllowDynamicPropsAsStatic )
{
Warning( "Error! To use model \"%s\"\n"
" as a static prop, it must be compiled with $staticprop!\n", pModelName );
return false;
}
else
{
Warning( "Warning! Using dynamic model \"%s\"\n"
" as a static prop\n", pModelName );
}
}
// ensure reset
pHdr->pVertexBase = NULL;
pHdr->pIndexBase = NULL;
return true;
}
bool LoadStudioCollisionModel( char const* pModelName, CUtlBuffer& buf )
{
char tmp[1024];
Q_strncpy( tmp, pModelName, sizeof( tmp ) );
Q_SetExtension( tmp, ".phy", sizeof( tmp ) );
// No luck, gotta build it
if (!LoadFile( tmp, buf ))
{
// this is not an error, the model simply has no PHY file
return false;
}
phyheader_t *header = (phyheader_t *)buf.PeekGet();
if ( header->size != sizeof(*header) || header->solidCount <= 0 )
return false;
return true;
}
bool LoadVTXFile( char const* pModelName, const studiohdr_t *pStudioHdr, CUtlBuffer& buf )
{
char filename[MAX_PATH];
// construct filename
Q_StripExtension( pModelName, filename, sizeof( filename ) );
strcat( filename, ".dx90.vtx" );
if ( !g_bAllowDX90VTX || !LoadFile( filename, buf ) )
{
filename[V_strlen(filename) - 6] = '8';
}
if ( !LoadFile( filename, buf ) )
{
Warning( "Error! Unable to load file \"%s\"\n", filename );
return false;
}
OptimizedModel::FileHeader_t* pVtxHdr = (OptimizedModel::FileHeader_t *)buf.Base();
// Check that it's valid
if ( pVtxHdr->version != OPTIMIZED_MODEL_FILE_VERSION )
{
if ( g_bIgnoreModelVersions )
{
Warning( "Warning! Unepected VTX file version: %d, expected %d \"%s\"\n", pVtxHdr->version, OPTIMIZED_MODEL_FILE_VERSION, filename );
}
else
{
Warning( "Error! Invalid VTX file version: %d, expected %d \"%s\"\n", pVtxHdr->version, OPTIMIZED_MODEL_FILE_VERSION, filename );
return false;
}
}
if ( pVtxHdr->checkSum != pStudioHdr->checksum )
{
Warning( "Error! Invalid VTX file checksum: %d, expected %d \"%s\"\n", pVtxHdr->checkSum, pStudioHdr->checksum, filename );
return false;
}
return true;
}
//-----------------------------------------------------------------------------
// Gets a vertex position from a strip index
//-----------------------------------------------------------------------------
inline static Vector* PositionFromIndex( const mstudio_meshvertexdata_t *vertData, mstudiomesh_t* pMesh, OptimizedModel::StripGroupHeader_t* pStripGroup, int i )
{
OptimizedModel::Vertex_t* pVert = pStripGroup->pVertex( i );
return vertData->Position( pVert->origMeshVertID );
}
//-----------------------------------------------------------------------------
// Purpose: Writes a glview text file containing the collision surface in question
// Input : *pCollide -
// *pFilename -
//-----------------------------------------------------------------------------
void DumpCollideToGlView( vcollide_t *pCollide, const char *pFilename )
{
if ( !pCollide )
return;
Msg("Writing %s...\n", pFilename );
FILE *fp = fopen( pFilename, "w" );
for (int i = 0; i < pCollide->solidCount; ++i)
{
Vector *outVerts;
int vertCount = s_pPhysCollision->CreateDebugMesh( pCollide->solids[i], &outVerts );
int triCount = vertCount / 3;
int vert = 0;
unsigned char r = (i & 1) * 64 + 64;
unsigned char g = (i & 2) * 64 + 64;
unsigned char b = (i & 4) * 64 + 64;
float fr = r / 255.0f;
float fg = g / 255.0f;
float fb = b / 255.0f;
for ( int i = 0; i < triCount; i++ )
{
fprintf( fp, "3\n" );
fprintf( fp, "%6.3f %6.3f %6.3f %.2f %.3f %.3f\n",
outVerts[vert].x, outVerts[vert].y, outVerts[vert].z, fr, fg, fb );
vert++;
fprintf( fp, "%6.3f %6.3f %6.3f %.2f %.3f %.3f\n",
outVerts[vert].x, outVerts[vert].y, outVerts[vert].z, fr, fg, fb );
vert++;
fprintf( fp, "%6.3f %6.3f %6.3f %.2f %.3f %.3f\n",
outVerts[vert].x, outVerts[vert].y, outVerts[vert].z, fr, fg, fb );
vert++;
}
s_pPhysCollision->DestroyDebugMesh( vertCount, outVerts );
}
fclose( fp );
}
static bool PointInTriangle( const Vector2D &p, const Vector2D &v0, const Vector2D &v1, const Vector2D &v2 )
{
float coords[3];
GetBarycentricCoords2D( v0, v1, v2, p, coords );
for ( int i = 0; i < 3; i++ )
{
if ( coords[i] < 0.0f || coords[i] > 1.0f )
return false;
}
float sum = coords[0] + coords[1] + coords[2];
if ( sum > 1.0f )
return false;
return true;
}
bool LoadFileIntoBuffer( CUtlBuffer &buf, const char *pFilename )
{
FileHandle_t fileHandle = g_pFileSystem->Open( pFilename, "rb" );
if ( !fileHandle )
return false;
// Get the file size
int texSize = g_pFileSystem->Size( fileHandle );
buf.EnsureCapacity( texSize );
int nBytesRead = g_pFileSystem->Read( buf.Base(), texSize, fileHandle );
g_pFileSystem->Close( fileHandle );
buf.SeekPut( CUtlBuffer::SEEK_HEAD, nBytesRead );
buf.SeekGet( CUtlBuffer::SEEK_HEAD, 0 );
return true;
}
// keeps a list of all textures that cast shadows via alpha channel
class CShadowTextureList
{
public:
// This loads a vtf and converts it to RGB8888 format
unsigned char *LoadVTFRGB8888( const char *pName, int *pWidth, int *pHeight, bool *pClampU, bool *pClampV )
{
char szPath[MAX_PATH];
Q_strncpy( szPath, "materials/", sizeof( szPath ) );
Q_strncat( szPath, pName, sizeof( szPath ), COPY_ALL_CHARACTERS );
Q_strncat( szPath, ".vtf", sizeof( szPath ), COPY_ALL_CHARACTERS );
Q_FixSlashes( szPath, CORRECT_PATH_SEPARATOR );
CUtlBuffer buf;
if ( !LoadFileIntoBuffer( buf, szPath ) )
return NULL;
IVTFTexture *pTex = CreateVTFTexture();
if (!pTex->Unserialize( buf ))
return NULL;
Msg("Loaded alpha texture %s\n", szPath );
unsigned char *pSrcImage = pTex->ImageData( 0, 0, 0, 0, 0, 0 );
int iWidth = pTex->Width();
int iHeight = pTex->Height();
ImageFormat dstFormat = IMAGE_FORMAT_RGBA8888;
ImageFormat srcFormat = pTex->Format();
*pClampU = (pTex->Flags() & TEXTUREFLAGS_CLAMPS) ? true : false;
*pClampV = (pTex->Flags() & TEXTUREFLAGS_CLAMPT) ? true : false;
unsigned char *pDstImage = new unsigned char[ImageLoader::GetMemRequired( iWidth, iHeight, 1, dstFormat, false )];
if( !ImageLoader::ConvertImageFormat( pSrcImage, srcFormat,
pDstImage, dstFormat, iWidth, iHeight, 0, 0 ) )
{
delete[] pDstImage;
return NULL;
}
*pWidth = iWidth;
*pHeight = iHeight;
return pDstImage;
}
// Checks the database for the material and loads if necessary
// returns true if found and pIndex will be the index, -1 if no alpha shadows
bool FindOrLoadIfValid( const char *pMaterialName, int *pIndex )
{
*pIndex = -1;
int index = m_Textures.Find(pMaterialName);
bool bFound = false;
if ( index != m_Textures.InvalidIndex() )
{
bFound = true;
*pIndex = index;
}
else
{
KeyValues *pVMT = new KeyValues("vmt");
CUtlBuffer buf(0,0,CUtlBuffer::TEXT_BUFFER);
LoadFileIntoBuffer( buf, pMaterialName );
if ( pVMT->LoadFromBuffer( pMaterialName, buf ) )
{
bFound = true;
if ( pVMT->FindKey("$translucent") || pVMT->FindKey("$alphatest") )
{
KeyValues *pBaseTexture = pVMT->FindKey("$basetexture");
if ( pBaseTexture )
{
const char *pBaseTextureName = pBaseTexture->GetString();
if ( pBaseTextureName )
{
int w, h;
bool bClampU = false;
bool bClampV = false;
unsigned char *pImageBits = LoadVTFRGB8888( pBaseTextureName, &w, &h, &bClampU, &bClampV );
if ( pImageBits )
{
int index = m_Textures.Insert( pMaterialName );
m_Textures[index].InitFromRGB8888( w, h, pImageBits );
*pIndex = index;
if ( pVMT->FindKey("$nocull") )
{
// UNDONE: Support this? Do we need to emit two triangles?
m_Textures[index].allowBackface = true;
}
m_Textures[index].clampU = bClampU;
m_Textures[index].clampV = bClampV;
delete[] pImageBits;
}
}
}
}
}
pVMT->deleteThis();
}
return bFound;
}
// iterate the textures for the model and load each one into the database
// this is used on models marked to cast texture shadows
void LoadAllTexturesForModel( studiohdr_t *pHdr, int *pTextureList )
{
for ( int i = 0; i < pHdr->numtextures; i++ )
{
int textureIndex = -1;
// try to add each texture to the transparent shadow manager
char szPath[MAX_PATH];
// iterate quietly through all specified directories until a valid material is found
for ( int j = 0; j < pHdr->numcdtextures; j++ )
{
Q_strncpy( szPath, "materials/", sizeof( szPath ) );
Q_strncat( szPath, pHdr->pCdtexture( j ), sizeof( szPath ) );
const char *textureName = pHdr->pTexture( i )->pszName();
Q_strncat( szPath, textureName, sizeof( szPath ), COPY_ALL_CHARACTERS );
Q_strncat( szPath, ".vmt", sizeof( szPath ), COPY_ALL_CHARACTERS );
Q_FixSlashes( szPath, CORRECT_PATH_SEPARATOR );
if ( FindOrLoadIfValid( szPath, &textureIndex ) )
break;
}
pTextureList[i] = textureIndex;
}
}
int AddMaterialEntry( int shadowTextureIndex, const Vector2D &t0, const Vector2D &t1, const Vector2D &t2 )
{
int index = m_MaterialEntries.AddToTail();
m_MaterialEntries[index].textureIndex = shadowTextureIndex;
m_MaterialEntries[index].uv[0] = t0;
m_MaterialEntries[index].uv[1] = t1;
m_MaterialEntries[index].uv[2] = t2;
return index;
}
// HACKHACK: Compute the average coverage for this triangle by sampling the AABB of its texture space
float ComputeCoverageForTriangle( int shadowTextureIndex, const Vector2D &t0, const Vector2D &t1, const Vector2D &t2 )
{
float umin = min(t0.x, t1.x);
umin = min(umin, t2.x);
float umax = max(t0.x, t1.x);
umax = max(umax, t2.x);
float vmin = min(t0.y, t1.y);
vmin = min(vmin, t2.y);
float vmax = max(t0.y, t1.y);
vmax = max(vmax, t2.y);
// UNDONE: Do something about tiling
umin = clamp(umin, 0, 1);
umax = clamp(umax, 0, 1);
vmin = clamp(vmin, 0, 1);
vmax = clamp(vmax, 0, 1);
Assert(umin>=0.0f && umax <= 1.0f);
Assert(vmin>=0.0f && vmax <= 1.0f);
const alphatexture_t &tex = m_Textures.Element(shadowTextureIndex);
int u0 = umin * (tex.width-1);
int u1 = umax * (tex.width-1);
int v0 = vmin * (tex.height-1);
int v1 = vmax * (tex.height-1);
int total = 0;
int count = 0;
for ( int v = v0; v <= v1; v++ )
{
int row = (v * tex.width);
for ( int u = u0; u <= u1; u++ )
{
total += tex.pAlphaTexels[row + u];
count++;
}
}
if ( count )
{
float coverage = float(total) / (count * 255.0f);
return coverage;
}
return 1.0f;
}
int SampleMaterial( int materialIndex, const Vector &coords, bool bBackface )
{
const materialentry_t &mat = m_MaterialEntries[materialIndex];
const alphatexture_t &tex = m_Textures.Element(m_MaterialEntries[materialIndex].textureIndex);
if ( bBackface && !tex.allowBackface )
return 0;
Vector2D uv = coords.x * mat.uv[0] + coords.y * mat.uv[1] + coords.z * mat.uv[2];
int u = RoundFloatToInt( uv[0] * tex.width );
int v = RoundFloatToInt( uv[1] * tex.height );
// asume power of 2, clamp or wrap
// UNDONE: Support clamp? This code should work
#if 0
u = tex.clampU ? clamp(u,0,(tex.width-1)) : (u & (tex.width-1));
v = tex.clampV ? clamp(v,0,(tex.height-1)) : (v & (tex.height-1));
#else
// for now always wrap
u &= (tex.width-1);
v &= (tex.height-1);
#endif
return tex.pAlphaTexels[v * tex.width + u];
}
struct alphatexture_t
{
short width;
short height;
bool allowBackface;
bool clampU;
bool clampV;
unsigned char *pAlphaTexels;
void InitFromRGB8888( int w, int h, unsigned char *pTexels )
{
width = w;
height = h;
pAlphaTexels = new unsigned char[w*h];
for ( int i = 0; i < h; i++ )
{
for ( int j = 0; j < w; j++ )
{
int index = (i*w) + j;
pAlphaTexels[index] = pTexels[index*4 + 3];
}
}
}
};
struct materialentry_t
{
int textureIndex;
Vector2D uv[3];
};
// this is the list of textures we've loaded
// only load each one once
CUtlDict< alphatexture_t, unsigned short > m_Textures;
CUtlVector<materialentry_t> m_MaterialEntries;
};
// global to keep the shadow-casting texture list and their alpha bits
CShadowTextureList g_ShadowTextureList;
float ComputeCoverageFromTexture( float b0, float b1, float b2, int32 hitID )
{
const float alphaScale = 1.0f / 255.0f;
// UNDONE: Pass ray down to determine backfacing?
//Vector normal( tri.m_flNx, tri.m_flNy, tri.m_flNz );
//bool bBackface = DotProduct(delta, tri.N) > 0 ? true : false;
Vector coords(b0,b1,b2);
return alphaScale * g_ShadowTextureList.SampleMaterial( g_RtEnv.GetTriangleMaterial(hitID), coords, false );
}
// this is here to strip models/ or .mdl or whatnot
void CleanModelName( const char *pModelName, char *pOutput, int outLen )
{
// strip off leading models/ if it exists
const char *pModelDir = "models/";
int modelLen = Q_strlen(pModelDir);
if ( !Q_strnicmp(pModelName, pModelDir, modelLen ) )
{
pModelName += modelLen;
}
Q_strncpy( pOutput, pModelName, outLen );
// truncate any .mdl extension
char *dot = strchr(pOutput,'.');
if ( dot )
{
*dot = 0;
}
}
void ForceTextureShadowsOnModel( const char *pModelName )
{
char buf[1024];
CleanModelName( pModelName, buf, sizeof(buf) );
if ( !g_ForcedTextureShadowsModels.Find(buf).IsValid())
{
g_ForcedTextureShadowsModels.AddString(buf);
}
}
bool IsModelTextureShadowsForced( const char *pModelName )
{
char buf[1024];
CleanModelName( pModelName, buf, sizeof(buf) );
return g_ForcedTextureShadowsModels.Find(buf).IsValid();
}
//-----------------------------------------------------------------------------
// Creates a collision model (based on the render geometry!)
//-----------------------------------------------------------------------------
void CVradStaticPropMgr::CreateCollisionModel( char const* pModelName )
{
CUtlBuffer buf;
CUtlBuffer bufvtx;
CUtlBuffer bufphy;
int i = m_StaticPropDict.AddToTail();
m_StaticPropDict[i].m_pModel = NULL;
m_StaticPropDict[i].m_pStudioHdr = NULL;
if ( !LoadStudioModel( pModelName, buf ) )
{
VectorCopy( vec3_origin, m_StaticPropDict[i].m_Mins );
VectorCopy( vec3_origin, m_StaticPropDict[i].m_Maxs );
return;
}
studiohdr_t* pHdr = (studiohdr_t*)buf.Base();
VectorCopy( pHdr->hull_min, m_StaticPropDict[i].m_Mins );
VectorCopy( pHdr->hull_max, m_StaticPropDict[i].m_Maxs );
if ( LoadStudioCollisionModel( pModelName, bufphy ) )
{
phyheader_t header;
bufphy.Get( &header, sizeof(header) );
vcollide_t *pCollide = &m_StaticPropDict[i].m_loadedModel;
s_pPhysCollision->VCollideLoad( pCollide, header.solidCount, (const char *)bufphy.PeekGet(), bufphy.TellPut() - bufphy.TellGet() );
m_StaticPropDict[i].m_pModel = m_StaticPropDict[i].m_loadedModel.solids[0];
/*
static int propNum = 0;
char tmp[128];