forked from nillerusr/source-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
morph.cpp
2280 lines (1891 loc) · 73.2 KB
/
morph.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:
//
//===========================================================================//
#include "imorphinternal.h"
#include "tier0/dbg.h"
#include "materialsystem/imaterialsystem.h"
#include "materialsystem/MaterialSystemUtil.h"
#include "materialsystem/itexture.h"
#include "materialsystem/imesh.h"
#include "UtlSortVector.h"
#include "materialsystem_global.h"
#include "IHardwareConfigInternal.h"
#include "pixelwriter.h"
#include "itextureinternal.h"
#include "tier1/KeyValues.h"
#include "texturemanager.h"
#include "imaterialsysteminternal.h"
#include "imatrendercontextinternal.h"
#include "studio.h"
#include "tier0/vprof.h"
#include "renderparm.h"
#include "tier2/renderutils.h"
#include "bitmap/imageformat.h"
#include "materialsystem/IShader.h"
#include "imaterialinternal.h"
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Activate to get stats
//-----------------------------------------------------------------------------
//#define REPORT_MORPH_STATS 1
//-----------------------------------------------------------------------------
// Used to collapse quads with small gaps
//-----------------------------------------------------------------------------
#define MIN_SEGMENT_GAP_SIZE 12
//-----------------------------------------------------------------------------
// Used to compile the morph data into a vertex texture
//-----------------------------------------------------------------------------
class CVertexMorphDict
{
public:
CVertexMorphDict();
// Adds a morph to the dictionary
void AddMorph( const MorphVertexInfo_t &info );
// Sets up, cleans up the morph information
void Setup( );
void CleanUp();
// Gets at morph info
int MorphCount() const;
int GetMorphTargetId( int nMorphTargetIndex ) const;
int GetMorphVertexCount( int nMorphTargetIndex ) const;
const MorphVertexInfo_t &GetMorphVertexInfo( int nMorphTargetIndex, int nIndex ) const;
// Sorts deltas by destination vertex
void SortDeltas();
private:
// Sort method for each morph target's vertices
class CMorphVertexListLess
{
public:
bool Less( const MorphVertexInfo_t& src1, const MorphVertexInfo_t& src2, void *pCtx )
{
return src1.m_nVertexId < src2.m_nVertexId;
}
};
// A list of all vertices affecting a particular morph target
struct MorphVertexList_t
{
MorphVertexList_t() = default;
MorphVertexList_t( const MorphVertexList_t& src ) : m_nMorphTargetId( src.m_nMorphTargetId ) {}
int m_nMorphTargetId;
CUtlSortVector< MorphVertexInfo_t, CMorphVertexListLess > m_MorphInfo;
};
// Sort function for the morph lists
class VertexMorphDictLess
{
public:
bool Less( const MorphVertexList_t& src1, const MorphVertexList_t& src2, void *pCtx );
};
// For each morph, store all target vertex indices
// List of all morphs affecting all vertices, used for constructing the morph only
CUtlSortVector< MorphVertexList_t, VertexMorphDictLess > m_MorphLists;
};
//-----------------------------------------------------------------------------
// Used to sort the morphs affecting a particular vertex
//-----------------------------------------------------------------------------
bool CVertexMorphDict::VertexMorphDictLess::Less( const CVertexMorphDict::MorphVertexList_t& src1, const CVertexMorphDict::MorphVertexList_t& src2, void *pCtx )
{
return src1.m_nMorphTargetId < src2.m_nMorphTargetId;
}
//-----------------------------------------------------------------------------
// Dictionary of morphs affecting a particular vertex
//-----------------------------------------------------------------------------
CVertexMorphDict::CVertexMorphDict() : m_MorphLists()
{
}
//-----------------------------------------------------------------------------
// Adds a morph to the dictionary
//-----------------------------------------------------------------------------
void CVertexMorphDict::AddMorph( const MorphVertexInfo_t &info )
{
Assert( info.m_nVertexId != 65535 );
MorphVertexList_t find;
find.m_nMorphTargetId = info.m_nMorphTargetId;
int nIndex = m_MorphLists.Find( find );
if ( nIndex == m_MorphLists.InvalidIndex() )
{
m_MorphLists.Insert( find );
nIndex = m_MorphLists.Find( find );
}
m_MorphLists[nIndex].m_MorphInfo.InsertNoSort( info );
}
//-----------------------------------------------------------------------------
// Sets up, cleans up the morph information
//-----------------------------------------------------------------------------
void CVertexMorphDict::Setup( )
{
m_MorphLists.Purge();
}
void CVertexMorphDict::CleanUp( )
{
}
//-----------------------------------------------------------------------------
// Gets at the dictionary elemenst
//-----------------------------------------------------------------------------
int CVertexMorphDict::MorphCount() const
{
return m_MorphLists.Count();
}
int CVertexMorphDict::GetMorphTargetId( int i ) const
{
if ( i >= m_MorphLists.Count() )
return -1;
return m_MorphLists[i].m_nMorphTargetId;
}
int CVertexMorphDict::GetMorphVertexCount( int nMorphTarget ) const
{
return m_MorphLists[nMorphTarget].m_MorphInfo.Count();
}
const MorphVertexInfo_t &CVertexMorphDict::GetMorphVertexInfo( int nMorphTarget, int j ) const
{
return m_MorphLists[nMorphTarget].m_MorphInfo[j];
}
//-----------------------------------------------------------------------------
// Sorts deltas by destination vertex
//-----------------------------------------------------------------------------
void CVertexMorphDict::SortDeltas()
{
int nMorphTargetCount = m_MorphLists.Count();
for ( int i = 0; i < nMorphTargetCount; ++i )
{
m_MorphLists[i].m_MorphInfo.RedoSort();
}
}
//-----------------------------------------------------------------------------
//
// Morph data class
//
//-----------------------------------------------------------------------------
class CMorph : public IMorphInternal, public ITextureRegenerator
{
public:
// Constructor, destructor
CMorph();
~CMorph();
// Inherited from IMorph
virtual void Lock( float flFloatToFixedScale );
virtual void AddMorph( const MorphVertexInfo_t &info );
virtual void Unlock( );
// Inherited from IMorphInternal
virtual void Init( MorphFormat_t format, const char *pDebugName );
virtual void Bind( IMorphMgrRenderContext *pRenderContext );
virtual MorphFormat_t GetMorphFormat() const;
// Other public methods
bool RenderMorphWeights( IMatRenderContext *pRenderContext, int nRenderId, int nWeightCount, const MorphWeight_t* pWeights );
void AccumulateMorph( int nRenderId );
private:
// A list of all morphs affecting a particular vertex
// Assume that consecutive morphs are stored under each other in V coordinates
// both in the src texture and destination texture (which is the morph accumulation texture).
struct MorphSegment_t
{
unsigned int m_nFirstSrc;
unsigned short m_nFirstDest;
unsigned short m_nCount;
};
struct MorphQuad_t
{
unsigned int m_nFirstSrc;
unsigned short m_nFirstDest;
unsigned short m_nCount;
unsigned short m_nQuadIndex;
};
enum MorphTextureId_t
{
MORPH_TEXTURE_POS_NORMAL_DELTA = 0,
MORPH_TEXTURE_SPEED_SIDE_MAP,
MORPH_TEXTURE_COUNT
};
typedef void (CMorph::*MorphPixelWriter_t)( CPixelWriter &pixelWriter, int x, int y, const MorphVertexInfo_t &info );
typedef CUtlVector< MorphSegment_t > MorphSegmentList_t;
typedef CUtlVector< MorphQuad_t > MorphQuadList_t;
private:
// Inherited from ITextureRegenerator
virtual void RegenerateTextureBits( ITexture *pTexture, IVTFTexture *pVTFTexture, Rect_t *pRect );
virtual void Release() {}
// Packs all morph data in the dictionary into a vertex texture layout
void PackMorphData( );
// Builds the list of segments to render, returns total # of src texels to read from
void BuildSegmentList( CUtlVector< MorphSegmentList_t > &morphSegments );
// Builds the list of quads to render
void BuildQuadList( const CUtlVector< MorphSegmentList_t > &morphSegments );
// Computes the vertex texture width
void ComputeTextureDimensions( const CUtlVector< MorphSegmentList_t > &morphSegments );
// Writes a morph delta into the texture
void WriteDeltaPositionNormalToTexture( CPixelWriter &pixelWriter, int x, int y, const MorphVertexInfo_t &info );
void WriteSideSpeedToTexture( CPixelWriter &pixelWriter, int x, int y, const MorphVertexInfo_t &info );
// Computes the morph target 4tuple count
int Get4TupleCount( MorphFormat_t format ) const;
// Cleans up vertex textures
void CleanUp( );
// Is the morph locked?
bool IsLocked() const;
// Creates a material for use to do the morph accumulation
void CreateAccumulatorMaterial( int nMaterialIndex );
// Renders to the morph accumulator texture
void RenderMorphQuads( IMatRenderContext *pRenderContext, int nRenderId, int nTotalQuadCount, int nWeightCount, int *pWeightLookup, const MorphWeight_t* pWeights );
// Displays static morph data statistics
void DisplayMorphStats();
// Dynamic stat data
void ClearMorphStats();
void AccumulateMorphStats( int nActiveMorphCount, int nQuadsRendered, int nTexelsRendered );
void ReportMorphStats( );
void HandleMorphStats( int nActiveMorphCount, int nQuadsRendered, int nTexelsRendered );
// Computes morph texture size in bytes
int ComputeMorphTextureSizeInBytes( ) const;
// Counts the total number of vertices to place in the static mesh
int CountStaticMeshVertices() const;
// Determines mesh vertex format
VertexFormat_t ComputeVertexFormat( IMaterial * pMaterial ) const;
// Builds the list of quads to render
void CreateStaticMesh();
// Builds a list of non-zero morph targets
int BuildNonZeroMorphList( int *pWeightIndices, int nWeightCount, const MorphWeight_t* pWeights );
// Determines the total number of deltas
int DetermineTotalDeltaCount( const CUtlVector< MorphSegmentList_t > &morphSegments ) const;
// Binds the morph weight texture
void BindMorphWeight( int nRenderId );
private:
// Used when constructing the morph targets
CVertexMorphDict m_MorphDict;
bool m_bLocked;
// The morph format
MorphFormat_t m_Format;
// The compiled vertex textures
ITextureInternal *m_pMorphTexture[MORPH_TEXTURE_COUNT];
// The compiled vertex streams
IMesh* m_pMorphBuffer;
// Describes all morph line segments required to draw a particular morph
CUtlVector< MorphQuadList_t > m_MorphQuads;
CUtlVector< int > m_MorphTargetIdToQuadIndex;
// Caches off the morph weights when in the middle of performing morph accumulation
int m_nMaxMorphTargetCount;
MorphWeight_t *m_pRenderMorphWeight;
CMaterialReference m_MorphAccumulationMaterial;
// Float->fixed scale
float m_flFloatToFixedScale;
// Morph input texture size
int m_nTextureWidth;
int m_nTextureHeight;
#ifdef _DEBUG
CUtlString m_pDebugName;
#endif
// Used to unique-ify morph texture names
static int s_nUniqueId;
};
//-----------------------------------------------------------------------------
// Render context for morphing. Only is used to determine
// where in the morph accumulator to put the texture.
//-----------------------------------------------------------------------------
class CMorphMgrRenderContext : public IMorphMgrRenderContext
{
public:
enum UnnamedEnumsAreNotLegal
{
MAX_MODEL_MORPHS = 4,
};
CMorphMgrRenderContext();
int GetRenderId( CMorph* pMorph );
public:
int m_nMorphCount;
CMorph *m_pMorphsToAccumulate[MAX_MODEL_MORPHS];
#ifdef DBGFLAG_ASSERT
bool m_bInMorphAccumulation;
#endif
};
//-----------------------------------------------------------------------------
// Morph manager class
//-----------------------------------------------------------------------------
class CMorphMgr : public IMorphMgr
{
public:
CMorphMgr();
// Methods of IMorphMgr
virtual bool ShouldAllocateScratchTextures();
virtual void AllocateScratchTextures();
virtual void FreeScratchTextures();
virtual void AllocateMaterials();
virtual void FreeMaterials();
virtual ITextureInternal *MorphAccumulator();
virtual ITextureInternal *MorphWeights();
virtual IMorphInternal *CreateMorph();
virtual void DestroyMorph( IMorphInternal *pMorphData );
virtual int MaxHWMorphBatchCount() const;
virtual void BeginMorphAccumulation( IMorphMgrRenderContext *pIRenderContext );
virtual void EndMorphAccumulation( IMorphMgrRenderContext *pIRenderContext );
virtual void AccumulateMorph( IMorphMgrRenderContext *pIRenderContext, IMorph* pMorph, int nMorphCount, const MorphWeight_t* pWeights );
virtual void AdvanceFrame();
virtual bool GetMorphAccumulatorTexCoord( IMorphMgrRenderContext *pRenderContext, Vector2D *pTexCoord, IMorph *pMorph, int nVertex );
virtual IMorphMgrRenderContext *AllocateRenderContext();
virtual void FreeRenderContext( IMorphMgrRenderContext *pRenderContext );
// Other public methods
public:
// Computes texel offsets for the upper corner of the morph accumulator for a particular block
void ComputeAccumulatorSubrect( int *pXOffset, int *pYOffset, int *pWidth, int *pHeight, int nMorphAccumBlockId );
void GetAccumulatorSubrectDimensions( int *pWidth, int *pHeight );
int GetAccumulator4TupleCount() const;
// Computes texel offsets for the upper corner of the morph weight texture for a particular block
void ComputeWeightSubrect( int *pXOffset, int *pYOffset, int *pWidth, int *pHeight, int nMorphAccumBlockId );
// Used to compute stats of memory used
void RegisterMorphSizeInBytes( int nSizeInBytes );
int GetTotalMemoryUsage() const;
// Are we using the constant register method?
bool IsUsingConstantRegisters() const { return m_bUsingConstantRegisters; }
private:
// Displays 32bit float texture data
void Display32FTextureData( float *pBuf, int nTexelID, int *pSubRect, ITexture *pTexture, int n4TupleCount );
// A debugging utility to display the morph accumulator
void DebugMorphAccumulator( IMatRenderContext *pRenderContext );
// A debugging utility to display the morph weights
void DebugMorphWeights( IMatRenderContext *pRenderContext );
// Draws the morph accumulator + morph weights
void DrawMorphTempTexture( IMatRenderContext *pRenderContext, IMaterial *pMaterial, ITexture *pTexture );
private:
enum
{
MAX_MORPH_ACCUMULATOR_VERTICES = 32768,
MORPH_ACCUMULATOR_4TUPLES = 2, // 1 for pos + wrinkle, 1 for normal
};
int m_nAccumulatorWidth;
int m_nAccumulatorHeight;
int m_nSubrectVerticalCount;
int m_nWeightWidth;
int m_nWeightHeight;
int m_nFrameCount;
int m_nTotalMorphSizeInBytes;
IMaterial *m_pPrevMaterial;
void *m_pPrevProxy;
int m_nPrevBoneCount;
MaterialHeightClipMode_t m_nPrevClipMode;
bool m_bPrevClippingEnabled;
bool m_bUsingConstantRegisters;
bool m_bFlashlightMode;
ITextureInternal *m_pMorphAccumTexture;
ITextureInternal *m_pMorphWeightTexture;
IMaterial *m_pVisualizeMorphAccum;
IMaterial *m_pVisualizeMorphWeight;
IMaterial *m_pRenderMorphWeight;
};
//-----------------------------------------------------------------------------
// Singleton
//-----------------------------------------------------------------------------
static CMorphMgr s_MorphMgr;
IMorphMgr *g_pMorphMgr = &s_MorphMgr;
//-----------------------------------------------------------------------------
// Globals
//-----------------------------------------------------------------------------
int CMorph::s_nUniqueId = 0;
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
CMorph::CMorph()
{
memset( m_pMorphTexture, 0, sizeof(m_pMorphTexture) );
m_pMorphBuffer = NULL;
m_nTextureWidth = 0;
m_nTextureHeight = 0;
m_bLocked = false;
m_Format = 0;
m_flFloatToFixedScale = 1.0f;
m_pRenderMorphWeight = 0;
m_nMaxMorphTargetCount = 0;
}
CMorph::~CMorph()
{
CleanUp();
}
//-----------------------------------------------------------------------------
// Initialization
//-----------------------------------------------------------------------------
void CMorph::Init( MorphFormat_t format, const char *pDebugName )
{
m_Format = format;
#ifdef _DEBUG
m_pDebugName = pDebugName;
#endif
}
//-----------------------------------------------------------------------------
// Returns the morph format
//-----------------------------------------------------------------------------
MorphFormat_t CMorph::GetMorphFormat() const
{
return m_Format;
}
//-----------------------------------------------------------------------------
// Binds morph accumulator, morph weights
//-----------------------------------------------------------------------------
void CMorph::Bind( IMorphMgrRenderContext *pIRenderContext )
{
CMorphMgrRenderContext *pMorphRenderContext = static_cast< CMorphMgrRenderContext* >( pIRenderContext );
int nRenderId = pMorphRenderContext->GetRenderId( this );
if ( nRenderId < 0 )
return;
int nXOffset, nYOffset, nWidth, nHeight;
s_MorphMgr.ComputeAccumulatorSubrect( &nXOffset, &nYOffset, &nWidth, &nHeight, nRenderId );
g_pShaderAPI->SetIntRenderingParameter( INT_RENDERPARM_MORPH_ACCUMULATOR_4TUPLE_COUNT, s_MorphMgr.GetAccumulator4TupleCount() );
g_pShaderAPI->SetIntRenderingParameter( INT_RENDERPARM_MORPH_ACCUMULATOR_X_OFFSET, nXOffset );
g_pShaderAPI->SetIntRenderingParameter( INT_RENDERPARM_MORPH_ACCUMULATOR_Y_OFFSET, nYOffset );
g_pShaderAPI->SetIntRenderingParameter( INT_RENDERPARM_MORPH_ACCUMULATOR_SUBRECT_WIDTH, nWidth );
g_pShaderAPI->SetIntRenderingParameter( INT_RENDERPARM_MORPH_ACCUMULATOR_SUBRECT_HEIGHT, nHeight );
}
void CMorph::BindMorphWeight( int nRenderId )
{
int nXOffset, nYOffset, nWidth, nHeight;
s_MorphMgr.ComputeWeightSubrect( &nXOffset, &nYOffset, &nWidth, &nHeight, nRenderId );
g_pShaderAPI->SetIntRenderingParameter( INT_RENDERPARM_MORPH_WEIGHT_X_OFFSET, nXOffset );
g_pShaderAPI->SetIntRenderingParameter( INT_RENDERPARM_MORPH_WEIGHT_Y_OFFSET, nYOffset );
g_pShaderAPI->SetIntRenderingParameter( INT_RENDERPARM_MORPH_WEIGHT_SUBRECT_WIDTH, nWidth );
g_pShaderAPI->SetIntRenderingParameter( INT_RENDERPARM_MORPH_WEIGHT_SUBRECT_HEIGHT, nHeight );
}
//-----------------------------------------------------------------------------
// Computes morph texture size in bytes
//-----------------------------------------------------------------------------
int CMorph::ComputeMorphTextureSizeInBytes( ) const
{
int nSize = 0;
if ( m_pMorphTexture[MORPH_TEXTURE_POS_NORMAL_DELTA] )
{
int nTotal4Tuples = Get4TupleCount( m_Format );
nSize += m_nTextureWidth * m_nTextureHeight * nTotal4Tuples * ImageLoader::SizeInBytes( IMAGE_FORMAT_RGBA16161616 );
}
if ( m_pMorphTexture[MORPH_TEXTURE_SPEED_SIDE_MAP] )
{
nSize += m_nTextureWidth * m_nTextureHeight * ImageLoader::SizeInBytes( IMAGE_FORMAT_RGBA8888 );
}
// NOTE: Vertex size here is kind of a hack, but whatever.
int nVertexCount = CountStaticMeshVertices();
nSize += nVertexCount * 5 * sizeof(float);
return nSize;
}
//-----------------------------------------------------------------------------
// Cleans up vertex textures
//-----------------------------------------------------------------------------
void CMorph::CleanUp( )
{
CMatRenderContextPtr pRenderContext( g_pMaterialSystem );
int nMorphTextureSize = ComputeMorphTextureSizeInBytes();
s_MorphMgr.RegisterMorphSizeInBytes( -nMorphTextureSize );
IMaterial *pMat = m_MorphAccumulationMaterial;
m_MorphAccumulationMaterial.Shutdown();
if ( pMat )
{
pMat->DeleteIfUnreferenced();
}
if ( m_pMorphBuffer )
{
pRenderContext->DestroyStaticMesh( m_pMorphBuffer );
m_pMorphBuffer = NULL;
}
for ( int i = 0; i < MORPH_TEXTURE_COUNT; ++i )
{
if ( m_pMorphTexture[i] )
{
m_pMorphTexture[i]->SetTextureRegenerator( NULL );
m_pMorphTexture[i]->DecrementReferenceCount( );
m_pMorphTexture[i]->DeleteIfUnreferenced();
m_pMorphTexture[i] = NULL;
}
}
if ( m_pRenderMorphWeight )
{
delete[] m_pRenderMorphWeight;
m_pRenderMorphWeight = NULL;
}
m_nMaxMorphTargetCount = 0;
}
//-----------------------------------------------------------------------------
// Is the morph locked?
//-----------------------------------------------------------------------------
bool CMorph::IsLocked() const
{
return m_bLocked;
}
//-----------------------------------------------------------------------------
// Locks the morph data
//-----------------------------------------------------------------------------
void CMorph::Lock( float flFloatToFixedScale )
{
Assert( !IsLocked() );
m_bLocked = true;
CleanUp();
m_flFloatToFixedScale = flFloatToFixedScale;
m_MorphQuads.Purge();
m_MorphTargetIdToQuadIndex.RemoveAll();
m_MorphDict.Setup( );
}
//-----------------------------------------------------------------------------
// Adds morph data to the morph dictionary
//-----------------------------------------------------------------------------
void CMorph::AddMorph( const MorphVertexInfo_t &info )
{
Assert( IsLocked() );
m_MorphDict.AddMorph( info );
}
//-----------------------------------------------------------------------------
// Unlocks the morph data, builds the vertex textures
//-----------------------------------------------------------------------------
void CMorph::Unlock( )
{
Assert( IsLocked() );
// Sort the deltas by destination vertex
m_MorphDict.SortDeltas();
// Now lay out morph data as if it were in a vertex texture
PackMorphData( );
// Free up temporary memory used in building
m_MorphDict.CleanUp();
m_bLocked = false;
// Gather stats
int nMorphTextureSize = ComputeMorphTextureSizeInBytes();
s_MorphMgr.RegisterMorphSizeInBytes( nMorphTextureSize );
}
//-----------------------------------------------------------------------------
// Creates a material for use to do the morph accumulation
//-----------------------------------------------------------------------------
void CMorph::CreateAccumulatorMaterial( int nMaterialIndex )
{
// NOTE: Delta scale is a little tricky. The numbers are store in fixed-point 16 bit.
// The pixel shader will interpret 65536 as 1.0, and 0 as 0.0. In the pixel shader,
// we will read the delta, multiply it by 2, and subtract 1 to get a -1 to 1 range.
// The float to fixed scale is applied prior to writing it in (delta * scale + 32768).
// Therefore the max representable positive value =
// 65536 = max positive delta * scale + 32768
// max positive delta = 32768 / scale
// This is what we will multiply our -1 to 1 values by in the pixel shader.
char pTemp[256];
KeyValues *pVMTKeyValues = new KeyValues( "MorphAccumulate" );
pVMTKeyValues->SetInt( "$nocull", 1 );
pVMTKeyValues->SetFloat( "$deltascale", ( m_flFloatToFixedScale != 0.0f ) ? 32768.0f / m_flFloatToFixedScale : 1.0f );
if ( m_pMorphTexture[MORPH_TEXTURE_POS_NORMAL_DELTA] )
{
pVMTKeyValues->SetString( "$delta", m_pMorphTexture[MORPH_TEXTURE_POS_NORMAL_DELTA]->GetName() );
}
if ( m_pMorphTexture[MORPH_TEXTURE_SPEED_SIDE_MAP] )
{
pVMTKeyValues->SetString( "$sidespeed", m_pMorphTexture[MORPH_TEXTURE_SPEED_SIDE_MAP]->GetName() );
}
Q_snprintf( pTemp, sizeof(pTemp), "[%d %d %d]", m_nTextureWidth, m_nTextureHeight, Get4TupleCount(m_Format) );
pVMTKeyValues->SetString( "$dimensions", pTemp );
Q_snprintf( pTemp, sizeof(pTemp), "___AccumulateMorph%d.vmt", nMaterialIndex );
m_MorphAccumulationMaterial.Init( pTemp, pVMTKeyValues );
}
//-----------------------------------------------------------------------------
// Computes the morph target field count
//-----------------------------------------------------------------------------
int CMorph::Get4TupleCount( MorphFormat_t format ) const
{
int nSize = 0;
if ( format & ( MORPH_POSITION | MORPH_WRINKLE ) )
{
++nSize;
}
if ( format & MORPH_NORMAL )
{
++nSize;
}
return nSize;
}
//-----------------------------------------------------------------------------
// Determines the total number of deltas
//-----------------------------------------------------------------------------
int CMorph::DetermineTotalDeltaCount( const CUtlVector< MorphSegmentList_t > &morphSegments ) const
{
int nDeltaCount = 0;
int nMorphCount = morphSegments.Count();
for ( int i = 0; i < nMorphCount; ++i )
{
const MorphSegmentList_t& list = morphSegments[i];
int nSegmentCount = list.Count();
for ( int j = 0; j < nSegmentCount; ++j )
{
nDeltaCount += list[j].m_nCount;
}
}
return nDeltaCount;
}
//-----------------------------------------------------------------------------
// Computes the texture width
//-----------------------------------------------------------------------------
void CMorph::ComputeTextureDimensions( const CUtlVector< MorphSegmentList_t > &morphSegments )
{
int nTotalDeltas = DetermineTotalDeltaCount( morphSegments );
m_nTextureHeight = ceil( sqrt( (float)nTotalDeltas ) );
// Round the dimension up to a multiple of 4
m_nTextureHeight = ( m_nTextureHeight + 3 ) & ( ~0x3 );
m_nTextureWidth = ( m_nTextureHeight != 0 ) ? ( nTotalDeltas + ( m_nTextureHeight - 1 ) ) / m_nTextureHeight : 0;
m_nTextureWidth = ( m_nTextureWidth + 3 ) & ( ~0x3 );
int nTotal4Tuples = Get4TupleCount( m_Format );
// Make sure it obeys bounds
int nMaxTextureWidth = HardwareConfig()->MaxTextureWidth();
int nMaxTextureHeight = HardwareConfig()->MaxTextureHeight();
while( m_nTextureWidth * nTotal4Tuples > nMaxTextureWidth )
{
m_nTextureWidth >>= 1;
m_nTextureHeight <<= 1;
if ( m_nTextureHeight > nMaxTextureHeight )
{
Warning( "Morph texture is too big!!! Make brian add support for morphs having multiple textures.\n" );
Assert( 0 );
m_nTextureHeight = nMaxTextureHeight;
break;
}
}
}
//-----------------------------------------------------------------------------
// Displays morph data statistics
//-----------------------------------------------------------------------------
void CMorph::DisplayMorphStats()
{
ITexture *pDest = g_pMorphMgr->MorphAccumulator( );
int nDestTextureHeight = pDest->GetActualHeight();
#ifdef _DEBUG
Msg( "Morph %s:\n", m_pDebugName.Get() );
#else
Msg( "Morph :\n" );
#endif
int nMorphCount = m_MorphQuads.Count();
Msg( "\tMorph Target Count : %d\n", nMorphCount );
int nTotalQuadCount = 0;
int nTotalVertexCount = 0;
CUtlVector<int> quadHisto;
CUtlVector<int> vertexHisto;
CUtlVector<int> gapSizeHisto;
for ( int i = 0; i < nMorphCount; ++i )
{
MorphQuadList_t &list = m_MorphQuads[i];
int nQuadCount = list.Count();
int nVertexCount = 0;
for ( int j = 0; j < nQuadCount; ++j )
{
nVertexCount += list[j].m_nCount;
if ( j != 0 )
{
// Filter out src gaps + wraparound gaps
if ( ( list[j].m_nFirstDest / nDestTextureHeight == list[j-1].m_nFirstDest / nDestTextureHeight ) &&
( list[j].m_nFirstSrc / m_nTextureHeight == list[j-1].m_nFirstSrc / m_nTextureHeight ) )
{
int nGapSize = list[j].m_nFirstDest - ( list[j-1].m_nFirstDest + list[j-1].m_nCount );
while ( nGapSize >= gapSizeHisto.Count() )
{
gapSizeHisto.AddToTail( 0 );
}
gapSizeHisto[nGapSize] += 1;
}
}
}
while ( nQuadCount >= quadHisto.Count() )
{
quadHisto.AddToTail( 0 );
}
while ( nVertexCount >= vertexHisto.Count() )
{
vertexHisto.AddToTail( 0 );
}
quadHisto[nQuadCount]+=1;
vertexHisto[nVertexCount]+=1;
nTotalQuadCount += nQuadCount;
nTotalVertexCount += nVertexCount;
}
Msg( "\tAverage # of vertices per target: %d\n", nTotalVertexCount / nMorphCount );
Msg( "\tAverage # of quad draws per target: %d\n", nTotalQuadCount / nMorphCount );
Msg( "\tQuad Count Histogram :\n\t\t" );
for ( int i = 0; i < quadHisto.Count(); ++i )
{
if ( quadHisto[i] == 0 )
continue;
Msg( "[%d : %d] ", i, quadHisto[i] );
}
Msg( "\n\tVertex Count Histogram :\n\t\t" );
for ( int i = 0; i < vertexHisto.Count(); ++i )
{
if ( vertexHisto[i] == 0 )
continue;
Msg( "[%d : %d] ", i, vertexHisto[i] );
}
Msg( "\n\tGap size Count Histogram :\n\t\t" );
for ( int i = 0; i < gapSizeHisto.Count(); ++i )
{
if ( gapSizeHisto[i] == 0 )
continue;
Msg( "[%d : %d] ", i, gapSizeHisto[i] );
}
Msg( "\n" );
}
//-----------------------------------------------------------------------------
// Packs all morph data in the dictionary into a vertex texture layout
//-----------------------------------------------------------------------------
void CMorph::PackMorphData( )
{
CUtlVector< MorphSegmentList_t > morphSegments;
BuildSegmentList( morphSegments );
ComputeTextureDimensions( morphSegments );
BuildQuadList( morphSegments );
if ( m_nTextureWidth == 0 || m_nTextureHeight == 0 )
return;
char pTemp[512];
if ( m_Format & ( MORPH_POSITION | MORPH_WRINKLE | MORPH_NORMAL ) )
{
Q_snprintf( pTemp, sizeof(pTemp), "__morphtarget[%d]: pos/norm", s_nUniqueId );
int nTotal4Tuples = Get4TupleCount( m_Format );
ITexture *pTexture = g_pMaterialSystem->CreateProceduralTexture( pTemp, TEXTURE_GROUP_MORPH_TARGETS,
m_nTextureWidth * nTotal4Tuples, m_nTextureHeight, IMAGE_FORMAT_RGBA16161616,
TEXTUREFLAGS_NOMIP | TEXTUREFLAGS_NOLOD | TEXTUREFLAGS_NODEBUGOVERRIDE |
TEXTUREFLAGS_SINGLECOPY | TEXTUREFLAGS_CLAMPS | TEXTUREFLAGS_CLAMPT | TEXTUREFLAGS_POINTSAMPLE );
m_pMorphTexture[MORPH_TEXTURE_POS_NORMAL_DELTA] = static_cast<ITextureInternal*>( pTexture );
}
if ( m_Format & ( MORPH_SIDE | MORPH_SPEED ) )
{
Q_snprintf( pTemp, sizeof(pTemp), "__morphtarget[%d]: side/speed", s_nUniqueId );
ITexture *pTexture = g_pMaterialSystem->CreateProceduralTexture( pTemp, TEXTURE_GROUP_MORPH_TARGETS,
m_nTextureWidth, m_nTextureHeight, IMAGE_FORMAT_RGBA8888,
TEXTUREFLAGS_NOMIP | TEXTUREFLAGS_NOLOD | TEXTUREFLAGS_NODEBUGOVERRIDE |
TEXTUREFLAGS_SINGLECOPY | TEXTUREFLAGS_CLAMPS | TEXTUREFLAGS_CLAMPT | TEXTUREFLAGS_POINTSAMPLE );
m_pMorphTexture[MORPH_TEXTURE_SPEED_SIDE_MAP] = static_cast<ITextureInternal*>( pTexture );
}
for ( int i = 0; i < MORPH_TEXTURE_COUNT; ++i )
{
if ( m_pMorphTexture[i] )
{
m_pMorphTexture[i]->SetTextureRegenerator( this );
m_pMorphTexture[i]->Download();
}
}
CreateAccumulatorMaterial( s_nUniqueId );
++s_nUniqueId;
CreateStaticMesh();
#ifdef REPORT_MORPH_STATS
DisplayMorphStats( );
#endif
}
//-----------------------------------------------------------------------------
// Writes a morph delta into the texture
//-----------------------------------------------------------------------------
void CMorph::WriteDeltaPositionNormalToTexture( CPixelWriter &pixelWriter, int x, int y, const MorphVertexInfo_t &info )
{
// NOTE: 0 = -max range, 32767 = 0, 65534, 65535 = maxrange.
// This way we can encode +/- maxrange and 0 exactly
Assert ( m_Format & ( MORPH_POSITION | MORPH_WRINKLE | MORPH_NORMAL ) );
int n4TupleCount = Get4TupleCount( m_Format );
pixelWriter.Seek( x*n4TupleCount, y );
// NOTE: int cast is where it is to force round-to-zero prior to offset
if ( m_Format & ( MORPH_POSITION | MORPH_WRINKLE ) )
{
int r = 32767, g = 32767, b = 32767, a = 32767;
if ( m_Format & MORPH_POSITION )
{
r = (int)( info.m_PositionDelta.x * m_flFloatToFixedScale ) + 32767;
g = (int)( info.m_PositionDelta.y * m_flFloatToFixedScale ) + 32767;
b = (int)( info.m_PositionDelta.z * m_flFloatToFixedScale ) + 32767;
r = clamp( r, 0, 65534 );
g = clamp( g, 0, 65534 );
b = clamp( b, 0, 65534 );
}
if ( m_Format & MORPH_WRINKLE )
{
a = (int)( info.m_flWrinkleDelta * m_flFloatToFixedScale ) + 32767;
a = clamp( a, 0, 65534 );
}
pixelWriter.WritePixel( r, g, b, a );
}
if ( m_Format & MORPH_NORMAL )
{
int r = 32767, g = 32767, b = 32767, a = 32767;
r = (int)( info.m_NormalDelta.x * m_flFloatToFixedScale ) + 32767;
g = (int)( info.m_NormalDelta.y * m_flFloatToFixedScale ) + 32767;
b = (int)( info.m_NormalDelta.z * m_flFloatToFixedScale ) + 32767;
r = clamp( r, 0, 65534 );
g = clamp( g, 0, 65534 );
b = clamp( b, 0, 65534 );
pixelWriter.WritePixel( r, g, b, a );
}
}
void CMorph::WriteSideSpeedToTexture( CPixelWriter &pixelWriter, int x, int y, const MorphVertexInfo_t &info )
{
Assert ( m_Format & ( MORPH_SPEED | MORPH_SIDE ) );
// Speed + size go from 0 to 1.
int r = 0, g = 0, b = 0, a = 0;
if ( m_Format & MORPH_SIDE )
{
r = info.m_flSide * 255;
}
if ( m_Format & MORPH_SPEED )
{
g = info.m_flSpeed * 255;
}
r = clamp( r, 0, 255 );
g = clamp( g, 0, 255 );
pixelWriter.Seek( x, y );