-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
l_studio.cpp
5060 lines (4333 loc) · 165 KB
/
l_studio.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. ============//
//
// models are the only shared resource between a client and server running
// on the same machine.
//===========================================================================//
#include "render_pch.h"
#include "client.h"
#include "gl_model_private.h"
#include "studio.h"
#include "phyfile.h"
#include "cdll_int.h"
#include "istudiorender.h"
#include "client_class.h"
#include "float.h"
#include "materialsystem/imaterialsystemhardwareconfig.h"
#include "materialsystem/ivballoctracker.h"
#include "modelloader.h"
#include "lightcache.h"
#include "studio_internal.h"
#include "cdll_engine_int.h"
#include "vphysics_interface.h"
#include "utllinkedlist.h"
#include "studio.h"
#include "icliententitylist.h"
#include "engine/ivmodelrender.h"
#include "optimize.h"
#include "icliententity.h"
#include "sys_dll.h"
#include "debugoverlay.h"
#include "enginetrace.h"
#include "l_studio.h"
#include "filesystem_engine.h"
#include "ModelInfo.h"
#include "cl_main.h"
#include "tier0/vprof.h"
#include "r_decal.h"
#include "vstdlib/random.h"
#include "datacache/idatacache.h"
#include "materialsystem/materialsystem_config.h"
#include "materialsystem/itexture.h"
#include "IHammer.h"
#if defined( _WIN32 ) && !defined( _X360 )
#include <xmmintrin.h>
#endif
#include "staticpropmgr.h"
#include "materialsystem/hardwaretexels.h"
#include "materialsystem/hardwareverts.h"
#include "tier1/callqueue.h"
#include "filesystem/IQueuedLoader.h"
#include "tier2/tier2.h"
#include "tier1/UtlSortVector.h"
#include "tier1/lzmaDecoder.h"
#include "ipooledvballocator.h"
#include "shaderapi/ishaderapi.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
// #define VISUALIZE_TIME_AVERAGE 1
extern ConVar r_flashlight_version2;
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
void R_StudioInitLightingCache( void );
float Engine_WorldLightDistanceFalloff( const dworldlight_t *wl, const Vector& delta, bool bNoRadiusCheck = false );
void SetRootLOD_f( IConVar *var, const char *pOldString, float flOldValue );
void r_lod_f( IConVar *var, const char *pOldValue, float flOldValue );
void FlushLOD_f();
class CColorMeshData;
static void CreateLightmapsFromData(CColorMeshData* _colorMeshData);
//-----------------------------------------------------------------------------
// Global variables
//-----------------------------------------------------------------------------
ConVar r_drawmodelstatsoverlay( "r_drawmodelstatsoverlay", "0", FCVAR_CHEAT );
ConVar r_drawmodelstatsoverlaydistance( "r_drawmodelstatsoverlaydistance", "500", FCVAR_CHEAT );
ConVar r_drawmodellightorigin( "r_DrawModelLightOrigin", "0", FCVAR_CHEAT );
extern ConVar r_worldlights;
ConVar r_lod( "r_lod", "-1", 0, "", r_lod_f );
static ConVar r_entity( "r_entity", "-1", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY );
static ConVar r_lightaverage( "r_lightaverage", "1", 0, "Activates/deactivate light averaging" );
static ConVar r_lightinterp( "r_lightinterp", "5", FCVAR_CHEAT, "Controls the speed of light interpolation, 0 turns off interpolation" );
static ConVar r_eyeglintlodpixels( "r_eyeglintlodpixels", "20.0", FCVAR_CHEAT, "The number of pixels wide an eyeball has to be before rendering an eyeglint. Is a floating point value." );
ConVar r_rootlod( "r_rootlod", "0", FCVAR_MATERIAL_SYSTEM_THREAD | FCVAR_ARCHIVE, "Root LOD", true, 0, true, MAX_NUM_LODS-1, SetRootLOD_f );
static ConVar r_decalstaticprops( "r_decalstaticprops", "1", 0, "Decal static props test" );
static ConCommand r_flushlod( "r_flushlod", FlushLOD_f, "Flush and reload LODs." );
ConVar r_debugrandomstaticlighting( "r_debugrandomstaticlighting", "0", FCVAR_CHEAT, "Set to 1 to randomize static lighting for debugging. Must restart for change to take affect." );
ConVar r_proplightingfromdisk( "r_proplightingfromdisk", "1", FCVAR_CHEAT, "0=Off, 1=On, 2=Show Errors" );
static ConVar r_itemblinkmax( "r_itemblinkmax", ".3", FCVAR_CHEAT );
static ConVar r_itemblinkrate( "r_itemblinkrate", "4.5", FCVAR_CHEAT );
static ConVar r_proplightingpooling( "r_proplightingpooling", "-1.0", FCVAR_CHEAT, "0 - off, 1 - static prop color meshes are allocated from a single shared vertex buffer (on hardware that supports stream offset)" );
//-----------------------------------------------------------------------------
// StudioRender config
//-----------------------------------------------------------------------------
static ConVar r_showenvcubemap( "r_showenvcubemap", "0", FCVAR_CHEAT );
static ConVar r_eyemove ( "r_eyemove", "1", FCVAR_ARCHIVE ); // look around
static ConVar r_eyeshift_x ( "r_eyeshift_x", "0", FCVAR_ARCHIVE ); // eye X position
static ConVar r_eyeshift_y ( "r_eyeshift_y", "0", FCVAR_ARCHIVE ); // eye Y position
static ConVar r_eyeshift_z ( "r_eyeshift_z", "0", FCVAR_ARCHIVE ); // eye Z position
static ConVar r_eyesize ( "r_eyesize", "0", FCVAR_ARCHIVE ); // adjustment to iris textures
static ConVar mat_softwareskin( "mat_softwareskin", "0", FCVAR_CHEAT );
static ConVar r_nohw ( "r_nohw", "0", FCVAR_CHEAT );
static ConVar r_nosw ( "r_nosw", "0", FCVAR_CHEAT );
static ConVar r_teeth ( "r_teeth", "1" );
static ConVar r_drawentities ( "r_drawentities", "1", FCVAR_CHEAT );
static ConVar r_flex ( "r_flex", "1" );
static ConVar r_eyes ( "r_eyes", "1" );
static ConVar r_skin ( "r_skin", "0", FCVAR_CHEAT );
static ConVar r_modelwireframedecal ( "r_modelwireframedecal", "0", FCVAR_CHEAT );
static ConVar r_maxmodeldecal ( "r_maxmodeldecal", "50" );
static StudioRenderConfig_t s_StudioRenderConfig;
void UpdateStudioRenderConfig( void )
{
// This can happen during initialization
if ( !g_pMaterialSystemConfig || !g_pStudioRender )
return;
memset( &s_StudioRenderConfig, 0, sizeof(s_StudioRenderConfig) );
s_StudioRenderConfig.bEyeMove = !!r_eyemove.GetInt();
s_StudioRenderConfig.fEyeShiftX = r_eyeshift_x.GetFloat();
s_StudioRenderConfig.fEyeShiftY = r_eyeshift_y.GetFloat();
s_StudioRenderConfig.fEyeShiftZ = r_eyeshift_z.GetFloat();
s_StudioRenderConfig.fEyeSize = r_eyesize.GetFloat();
if ( IsPC() && ( mat_softwareskin.GetInt() || ShouldDrawInWireFrameMode() ) )
{
s_StudioRenderConfig.bSoftwareSkin = true;
}
else
{
s_StudioRenderConfig.bSoftwareSkin = false;
}
s_StudioRenderConfig.bNoHardware = !!r_nohw.GetInt();
s_StudioRenderConfig.bNoSoftware = !!r_nosw.GetInt();
s_StudioRenderConfig.bTeeth = !!r_teeth.GetInt();
s_StudioRenderConfig.drawEntities = r_drawentities.GetInt();
s_StudioRenderConfig.bFlex = !!r_flex.GetInt();
s_StudioRenderConfig.bEyes = !!r_eyes.GetInt();
s_StudioRenderConfig.bWireframe = ShouldDrawInWireFrameMode();
s_StudioRenderConfig.bDrawNormals = mat_normals.GetBool();
s_StudioRenderConfig.skin = r_skin.GetInt();
s_StudioRenderConfig.maxDecalsPerModel = r_maxmodeldecal.GetInt();
s_StudioRenderConfig.bWireframeDecals = r_modelwireframedecal.GetInt() != 0;
s_StudioRenderConfig.fullbright = g_pMaterialSystemConfig->nFullbright;
s_StudioRenderConfig.bSoftwareLighting = g_pMaterialSystemConfig->bSoftwareLighting;
s_StudioRenderConfig.bShowEnvCubemapOnly = r_showenvcubemap.GetInt() ? true : false;
s_StudioRenderConfig.fEyeGlintPixelWidthLODThreshold = r_eyeglintlodpixels.GetFloat();
g_pStudioRender->UpdateConfig( s_StudioRenderConfig );
}
void R_InitStudio( void )
{
#ifndef SWDS
R_StudioInitLightingCache();
#endif
}
//-----------------------------------------------------------------------------
// Converts world lights to materialsystem lights
//-----------------------------------------------------------------------------
#define MIN_LIGHT_VALUE 0.03f
bool WorldLightToMaterialLight( dworldlight_t* pWorldLight, LightDesc_t& light )
{
// BAD
light.m_Attenuation0 = 0.0f;
light.m_Attenuation1 = 0.0f;
light.m_Attenuation2 = 0.0f;
switch(pWorldLight->type)
{
case emit_spotlight:
light.m_Type = MATERIAL_LIGHT_SPOT;
light.m_Attenuation0 = pWorldLight->constant_attn;
light.m_Attenuation1 = pWorldLight->linear_attn;
light.m_Attenuation2 = pWorldLight->quadratic_attn;
light.m_Theta = 2.0 * acos( pWorldLight->stopdot );
light.m_Phi = 2.0 * acos( pWorldLight->stopdot2 );
light.m_ThetaDot = pWorldLight->stopdot;
light.m_PhiDot = pWorldLight->stopdot2;
light.m_Falloff = pWorldLight->exponent ? pWorldLight->exponent : 1.0f;
break;
case emit_surface:
// A 180 degree spotlight
light.m_Type = MATERIAL_LIGHT_SPOT;
light.m_Attenuation2 = 1.0;
light.m_Theta = M_PI;
light.m_Phi = M_PI;
light.m_ThetaDot = 0.0f;
light.m_PhiDot = 0.0f;
light.m_Falloff = 1.0f;
break;
case emit_point:
light.m_Type = MATERIAL_LIGHT_POINT;
light.m_Attenuation0 = pWorldLight->constant_attn;
light.m_Attenuation1 = pWorldLight->linear_attn;
light.m_Attenuation2 = pWorldLight->quadratic_attn;
break;
case emit_skylight:
light.m_Type = MATERIAL_LIGHT_DIRECTIONAL;
break;
// NOTE: Can't do quake lights in hardware (x-r factor)
case emit_quakelight: // not supported
case emit_skyambient: // doesn't factor into local lighting
// skip these
return false;
}
// No attenuation case..
if ((light.m_Attenuation0 == 0.0f) && (light.m_Attenuation1 == 0.0f) &&
(light.m_Attenuation2 == 0.0f))
{
light.m_Attenuation0 = 1.0f;
}
// renormalize light intensity...
memcpy( &light.m_Position, &pWorldLight->origin, 3 * sizeof(float) );
memcpy( &light.m_Direction, &pWorldLight->normal, 3 * sizeof(float) );
light.m_Color[0] = pWorldLight->intensity[0];
light.m_Color[1] = pWorldLight->intensity[1];
light.m_Color[2] = pWorldLight->intensity[2];
// Make it stop when the lighting gets to min%...
float intensity = sqrtf( DotProduct( light.m_Color, light.m_Color ) );
// Compute the light range based on attenuation factors
if (pWorldLight->radius != 0)
{
light.m_Range = pWorldLight->radius;
}
else
{
// FALLBACK: older lights use this
if (light.m_Attenuation2 == 0.0f)
{
if (light.m_Attenuation1 == 0.0f)
{
light.m_Range = sqrtf(FLT_MAX);
}
else
{
light.m_Range = (intensity / MIN_LIGHT_VALUE - light.m_Attenuation0) / light.m_Attenuation1;
}
}
else
{
float a = light.m_Attenuation2;
float b = light.m_Attenuation1;
float c = light.m_Attenuation0 - intensity / MIN_LIGHT_VALUE;
float discrim = b * b - 4 * a * c;
if (discrim < 0.0f)
light.m_Range = sqrtf(FLT_MAX);
else
{
light.m_Range = (-b + sqrtf(discrim)) / (2.0f * a);
if (light.m_Range < 0)
light.m_Range = 0;
}
}
}
light.m_Flags = LIGHTTYPE_OPTIMIZATIONFLAGS_DERIVED_VALUES_CALCED;
if( light.m_Attenuation0 != 0.0f )
{
light.m_Flags |= LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION0;
}
if( light.m_Attenuation1 != 0.0f )
{
light.m_Flags |= LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION1;
}
if( light.m_Attenuation2 != 0.0f )
{
light.m_Flags |= LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION2;
}
return true;
}
//-----------------------------------------------------------------------------
// Sets the hardware lighting state
//-----------------------------------------------------------------------------
static void R_SetNonAmbientLightingState( int numLights, dworldlight_t *locallight[MAXLOCALLIGHTS],
int *pNumLightDescs, LightDesc_t *pLightDescs, bool bUpdateStudioRenderLights )
{
Assert( numLights >= 0 && numLights <= MAXLOCALLIGHTS );
// convert dworldlight_t's to LightDesc_t's and send 'em down to g_pStudioRender->
*pNumLightDescs = 0;
LightDesc_t *pLightDesc;
for ( int i = 0; i < numLights; i++)
{
pLightDesc = &pLightDescs[*pNumLightDescs];
if (!WorldLightToMaterialLight( locallight[i], *pLightDesc ))
continue;
// Apply lightstyle
float bias = LightStyleValue( locallight[i]->style );
// Deal with overbrighting + bias
pLightDesc->m_Color[0] *= bias;
pLightDesc->m_Color[1] *= bias;
pLightDesc->m_Color[2] *= bias;
*pNumLightDescs += 1;
Assert( *pNumLightDescs <= MAXLOCALLIGHTS );
}
if ( bUpdateStudioRenderLights )
{
g_pStudioRender->SetLocalLights( *pNumLightDescs, pLightDescs );
}
}
//-----------------------------------------------------------------------------
// Computes the center of the studio model for illumination purposes
//-----------------------------------------------------------------------------
void R_ComputeLightingOrigin( IClientRenderable *pRenderable, studiohdr_t* pStudioHdr, const matrix3x4_t &matrix, Vector& center )
{
int nAttachmentIndex = pStudioHdr->IllumPositionAttachmentIndex();
if ( nAttachmentIndex <= 0 )
{
VectorTransform( pStudioHdr->illumposition, matrix, center );
}
else
{
matrix3x4_t attachment;
pRenderable->GetAttachment( nAttachmentIndex, attachment );
VectorTransform( pStudioHdr->illumposition, attachment, center );
}
}
#if 0
// garymct - leave this in here for now. . we might need this for bumped models
void R_StudioCalculateVirtualLightAndLightCube( Vector& mid, Vector& virtualLightPosition,
Vector& virtualLightColor, Vector* lightBoxColor )
{
int i, j;
Vector delta;
float dist2, ratio;
byte *pvis;
float t;
static ConVar bumpLightBlendRatioMin( "bump_light_blend_ratio_min", "0.00002" );
static ConVar bumpLightBlendRatioMax( "bump_light_blend_ratio_max", "0.00004" );
if ( g_pMaterialSystemConfig->nFullbright == 1 )
return;
VectorClear( virtualLightPosition );
VectorClear( virtualLightColor );
for( i = 0; i < 6; i++ )
{
VectorClear( lightBoxColor[i] );
}
byte pvs[MAX_MAP_LEAFS/8];
pvis = CM_Vis( pvs, sizeof(pvs), CM_LeafCluster( CM_PointLeafnum( mid ), DVIS_PVS );
float sumBumpBlendParam = 0;
for (i = 0; i < host_state.worldbrush->numworldlights; i++)
{
dworldlight_t *wl = &host_state.worldbrush->worldlights[i];
if (wl->cluster < 0)
continue;
// only do it if the entity can see into the lights leaf
if (!BIT_SET( pvis, (wl->cluster)))
continue;
// hack: for this test, only deal with point light sources.
if( wl->type != emit_point )
continue;
// check distance
VectorSubtract( wl->origin, mid, delta );
dist2 = DotProduct( delta, delta );
ratio = R_WorldLightDistanceFalloff( wl, delta );
VectorNormalize( delta );
ratio = ratio * R_WorldLightAngle( wl, wl->normal, delta, delta );
float bumpBlendParam; // 0.0 = all cube, 1.0 = all bump
// lerp
bumpBlendParam =
( ratio - bumpLightBlendRatioMin.GetFloat() ) /
( bumpLightBlendRatioMax.GetFloat() - bumpLightBlendRatioMin.GetFloat() );
if( bumpBlendParam > 0.0 )
{
// Get the bit that goes into the bump light
sumBumpBlendParam += bumpBlendParam;
VectorMA( virtualLightPosition, bumpBlendParam, wl->origin, virtualLightPosition );
VectorMA( virtualLightColor, bumpBlendParam, wl->intensity, virtualLightColor );
}
if( bumpBlendParam < 1.0f )
{
// Get the bit that goes into the cube
float cubeBlendParam;
cubeBlendParam = 1.0f - bumpBlendParam;
if( cubeBlendParam < 0.0f )
{
cubeBlendParam = 0.0f;
}
for (j = 0; j < numBoxDir; j++)
{
t = DotProduct( r_boxdir[j], delta );
if (t > 0)
{
VectorMA( lightBoxColor[j], ratio * t * cubeBlendParam, wl->intensity, lightBoxColor[j] );
}
}
}
}
// Get the final virtual light position and color.
VectorMultiply( virtualLightPosition, 1.0f / sumBumpBlendParam, virtualLightPosition );
VectorMultiply( virtualLightColor, 1.0f / sumBumpBlendParam, virtualLightColor );
}
#endif
// TODO: move cone calcs to position
// TODO: cone clipping calc's wont work for boxlight since the player asks for a single point. Not sure what the volume is.
float Engine_WorldLightDistanceFalloff( const dworldlight_t *wl, const Vector& delta, bool bNoRadiusCheck )
{
float falloff;
switch (wl->type)
{
case emit_surface:
#if 1
// Cull out stuff that's too far
if (wl->radius != 0)
{
if ( DotProduct( delta, delta ) > (wl->radius * wl->radius))
return 0.0f;
}
return InvRSquared(delta);
#else
// 1/r*r
falloff = DotProduct( delta, delta );
if (falloff < 1)
return 1.f;
else
return 1.f / falloff;
#endif
break;
case emit_skylight:
return 1.f;
break;
case emit_quakelight:
// X - r;
falloff = wl->linear_attn - FastSqrt( DotProduct( delta, delta ) );
if (falloff < 0)
return 0.f;
return falloff;
break;
case emit_skyambient:
return 1.f;
break;
case emit_point:
case emit_spotlight: // directional & positional
{
float dist2, dist;
dist2 = DotProduct( delta, delta );
dist = FastSqrt( dist2 );
// Cull out stuff that's too far
if (!bNoRadiusCheck && (wl->radius != 0) && (dist > wl->radius))
return 0.f;
return 1.f / (wl->constant_attn + wl->linear_attn * dist + wl->quadratic_attn * dist2);
}
break;
default:
// Bug: need to return an error
break;
}
return 1.f;
}
/*
light_normal (lights normal translated to same space as other normals)
surface_normal
light_direction_normal | (light_pos - vertex_pos) |
*/
float Engine_WorldLightAngle( const dworldlight_t *wl, const Vector& lnormal, const Vector& snormal, const Vector& delta )
{
float dot, dot2, ratio = 0;
switch (wl->type)
{
case emit_surface:
dot = DotProduct( snormal, delta );
if (dot < 0)
return 0;
dot2 = -DotProduct (delta, lnormal);
if (dot2 <= ON_EPSILON/10)
return 0; // behind light surface
return dot * dot2;
case emit_point:
dot = DotProduct( snormal, delta );
if (dot < 0)
return 0;
return dot;
case emit_spotlight:
// return 1.0; // !!!
dot = DotProduct( snormal, delta );
if (dot < 0)
return 0;
dot2 = -DotProduct (delta, lnormal);
if (dot2 <= wl->stopdot2)
return 0; // outside light cone
ratio = dot;
if (dot2 >= wl->stopdot)
return ratio; // inside inner cone
if ((wl->exponent == 1) || (wl->exponent == 0))
{
ratio *= (dot2 - wl->stopdot2) / (wl->stopdot - wl->stopdot2);
}
else
{
ratio *= pow((dot2 - wl->stopdot2) / (wl->stopdot - wl->stopdot2), wl->exponent );
}
return ratio;
case emit_skylight:
dot2 = -DotProduct( snormal, lnormal );
if (dot2 < 0)
return 0;
return dot2;
case emit_quakelight:
// linear falloff
dot = DotProduct( snormal, delta );
if (dot < 0)
return 0;
return dot;
case emit_skyambient:
// not supported
return 1;
default:
// Bug: need to return an error
break;
}
return 0;
}
//-----------------------------------------------------------------------------
// Allocator for color mesh vertex buffers (for use with static props only).
// It uses a trivial allocation scheme, which assumes that allocations and
// deallocations are not interleaved (you do all allocs, then all deallocs).
//-----------------------------------------------------------------------------
class CPooledVBAllocator_ColorMesh : public IPooledVBAllocator
{
public:
CPooledVBAllocator_ColorMesh();
virtual ~CPooledVBAllocator_ColorMesh();
// Allocate the shared mesh (vertex buffer)
virtual bool Init( VertexFormat_t format, int numVerts );
// Free the shared mesh (after Deallocate is called for all sub-allocs)
virtual void Clear();
// Get the shared mesh (vertex buffer) from which sub-allocations are made
virtual IMesh *GetSharedMesh() { return m_pMesh; }
// Get a pointer to the start of the vertex buffer data
virtual void *GetVertexBufferBase() { return m_pVertexBufferBase; }
virtual int GetNumVertsAllocated() { return m_totalVerts; }
// Allocate a sub-range of 'numVerts' from free space in the shared vertex buffer
// (returns the byte offset from the start of the VB to the new allocation)
virtual int Allocate( int numVerts );
// Deallocate an existing allocation
virtual void Deallocate( int offset, int numVerts );
private:
// Assert/warn that the allocator is in a clear/empty state (returns FALSE if not)
bool CheckIsClear( void );
IMesh *m_pMesh; // The shared mesh (vertex buffer) from which sub-allocations are made
void *m_pVertexBufferBase; // A pointer to the start of the vertex buffer data
int m_totalVerts; // The number of verts in the shared vertex buffer
int m_vertexSize; // The stride of the shared vertex buffer
int m_numAllocations; // The number of extant allocations
int m_numVertsAllocated; // The number of vertices in extant allocations
int m_nextFreeOffset; // The offset to be returned by the next call to Allocate()
// (incremented as a simple stack)
bool m_bStartedDeallocation; // This is set when Deallocate() is called for the first time,
// at which point Allocate() cannot be called again until all
// extant allocations have been deallocated.
};
struct colormeshparams_t
{
int m_nMeshes;
int m_nTotalVertexes;
// Given memory alignment (VBs must be 4-KB aligned on X360, for example), it can be more efficient
// to allocate many color meshes out of a single shared vertex buffer (using vertex 'stream offset')
IPooledVBAllocator *m_pPooledVBAllocator;
int m_nVertexes[256];
FileNameHandle_t m_fnHandle;
};
class CColorMeshData
{
public:
void DestroyResource()
{
g_pFileSystem->AsyncFinish( m_hAsyncControlVertex, true );
g_pFileSystem->AsyncRelease( m_hAsyncControlVertex );
g_pFileSystem->AsyncFinish( m_hAsyncControlTexel, true );
g_pFileSystem->AsyncRelease( m_hAsyncControlTexel );
// release the array of meshes
CMatRenderContextPtr pRenderContext( materials );
for ( int i=0; i<m_nMeshes; i++ )
{
if ( m_pMeshInfos[i].m_pPooledVBAllocator )
{
// Let the pooling allocator dealloc this sub-range of the shared vertex buffer
m_pMeshInfos[i].m_pPooledVBAllocator->Deallocate( m_pMeshInfos[i].m_nVertOffsetInBytes, m_pMeshInfos[i].m_nNumVerts );
}
else
{
// Free this standalone mesh
pRenderContext->DestroyStaticMesh( m_pMeshInfos[i].m_pMesh );
}
if (m_pMeshInfos[i].m_pLightmap)
{
m_pMeshInfos[i].m_pLightmap->Release();
m_pMeshInfos[i].m_pLightmap = NULL;
}
if (m_pMeshInfos[i].m_pLightmapData)
{
delete [] m_pMeshInfos[i].m_pLightmapData->m_pTexelData;
delete m_pMeshInfos[i].m_pLightmapData;
}
}
delete [] m_pMeshInfos;
delete [] m_ppTargets;
delete this;
}
CColorMeshData *GetData()
{
return this;
}
unsigned int Size()
{
// TODO: This is wrong because we don't currently account for the size of the textures we create.
// However, that data isn't available until way after this query is made, so just live with
// this for now I guess?
return m_nTotalSize;
}
static CColorMeshData *CreateResource( const colormeshparams_t ¶ms )
{
CColorMeshData *data = new CColorMeshData;
data->m_bHasInvalidVB = false;
data->m_bColorMeshValid = false;
data->m_bColorTextureValid = false;
data->m_bColorTextureCreated = false;
data->m_bNeedsRetry = false;
data->m_hAsyncControlVertex = NULL;
data->m_hAsyncControlTexel = NULL;
data->m_fnHandle = params.m_fnHandle;
data->m_nTotalSize = params.m_nMeshes * sizeof( IMesh* ) + params.m_nTotalVertexes * 4;
data->m_nMeshes = params.m_nMeshes;
data->m_pMeshInfos = new ColorMeshInfo_t[params.m_nMeshes];
Q_memset( data->m_pMeshInfos, 0, params.m_nMeshes*sizeof( ColorMeshInfo_t ) );
data->m_ppTargets = new unsigned char *[params.m_nMeshes];
CMeshBuilder meshBuilder;
CMatRenderContextPtr pRenderContext( materials );
for ( int i=0; i<params.m_nMeshes; i++ )
{
VertexFormat_t vertexFormat = VERTEX_SPECULAR;
data->m_pMeshInfos[i].m_pMesh = NULL;
data->m_pMeshInfos[i].m_pPooledVBAllocator = params.m_pPooledVBAllocator;
data->m_pMeshInfos[i].m_nVertOffsetInBytes = 0;
data->m_pMeshInfos[i].m_nNumVerts = params.m_nVertexes[i];
data->m_pMeshInfos[i].m_pLightmapData = NULL;
data->m_pMeshInfos[i].m_pLightmap = NULL;
if ( params.m_pPooledVBAllocator != NULL )
{
// Allocate a portion of a single, shared VB for each color mesh
data->m_pMeshInfos[i].m_nVertOffsetInBytes = params.m_pPooledVBAllocator->Allocate( params.m_nVertexes[i] );
if ( data->m_pMeshInfos[i].m_nVertOffsetInBytes == -1 )
{
// Failed (fall back to regular allocations)
data->m_pMeshInfos[i].m_pPooledVBAllocator = NULL;
data->m_pMeshInfos[i].m_nVertOffsetInBytes = 0;
}
else
{
// Set up the mesh+data pointers
data->m_pMeshInfos[i].m_pMesh = params.m_pPooledVBAllocator->GetSharedMesh();
data->m_ppTargets[i] = ( (unsigned char *)params.m_pPooledVBAllocator->GetVertexBufferBase() ) + data->m_pMeshInfos[i].m_nVertOffsetInBytes;
}
}
if ( data->m_pMeshInfos[i].m_pMesh == NULL )
{
if ( g_VBAllocTracker )
g_VBAllocTracker->TrackMeshAllocations( "CColorMeshData::CreateResource" );
// Allocate a standalone VB per color mesh
data->m_pMeshInfos[i].m_pMesh = pRenderContext->CreateStaticMesh( vertexFormat, TEXTURE_GROUP_STATIC_VERTEX_BUFFER_COLOR );
if ( g_VBAllocTracker )
g_VBAllocTracker->TrackMeshAllocations( NULL );
}
Assert( data->m_pMeshInfos[i].m_pMesh );
if ( !data->m_pMeshInfos[i].m_pMesh )
{
data->DestroyResource();
data = NULL;
break;
}
}
return data;
}
static unsigned int EstimatedSize( const colormeshparams_t ¶ms )
{
// each vertex is a 4 byte color
return params.m_nMeshes * sizeof( IMesh* ) + params.m_nTotalVertexes * 4;
}
int m_nMeshes;
ColorMeshInfo_t *m_pMeshInfos;
unsigned char **m_ppTargets;
unsigned int m_nTotalSize;
FSAsyncControl_t m_hAsyncControlVertex;
FSAsyncControl_t m_hAsyncControlTexel;
unsigned int m_bHasInvalidVB : 1;
unsigned int m_bColorMeshValid : 1;
unsigned int m_bColorTextureValid : 1; // Whether the texture data is valid, but not necessarily created
unsigned int m_bColorTextureCreated : 1; // Whether the texture data has actually been created.
unsigned int m_bNeedsRetry : 1;
FileNameHandle_t m_fnHandle;
};
//-----------------------------------------------------------------------------
//
// Implementation of IVModelRender
//
//-----------------------------------------------------------------------------
// UNDONE: Move this to hud export code, subsume previous functions
class CModelRender : public IVModelRender,
public CManagedDataCacheClient< CColorMeshData, colormeshparams_t >
{
public:
// members of the IVModelRender interface
virtual void ForcedMaterialOverride( IMaterial *newMaterial, OverrideType_t nOverrideType = OVERRIDE_NORMAL );
virtual int DrawModel(
int flags, IClientRenderable *cliententity,
ModelInstanceHandle_t instance, int entity_index, const model_t *model,
const Vector& origin, QAngle const& angles,
int skin, int body, int hitboxset,
const matrix3x4_t* pModelToWorld,
const matrix3x4_t *pLightingOffset );
virtual void SetViewTarget( const CStudioHdr *pStudioHdr, int nBodyIndex, const Vector& target );
// Creates, destroys instance data to be associated with the model
virtual ModelInstanceHandle_t CreateInstance( IClientRenderable *pRenderable, LightCacheHandle_t* pHandle );
virtual void SetStaticLighting( ModelInstanceHandle_t handle, LightCacheHandle_t* pCache );
virtual LightCacheHandle_t GetStaticLighting( ModelInstanceHandle_t handle );
virtual void DestroyInstance( ModelInstanceHandle_t handle );
virtual bool ChangeInstance( ModelInstanceHandle_t handle, IClientRenderable *pRenderable );
// Creates a decal on a model instance by doing a planar projection
// along the ray. The material is the decal material, the radius is the
// radius of the decal to create.
virtual void AddDecal( ModelInstanceHandle_t handle, Ray_t const& ray,
const Vector& decalUp, int decalIndex, int body, bool noPokethru = false, int maxLODToDecal = ADDDECAL_TO_ALL_LODS );
virtual void AddColoredDecal( ModelInstanceHandle_t handle, Ray_t const& ray,
const Vector& decalUp, int decalIndex, int body, Color cColor, bool noPokethru = false, int maxLODToDecal = ADDDECAL_TO_ALL_LODS );
virtual void GetMaterialOverride( IMaterial** ppOutForcedMaterial, OverrideType_t* pOutOverrideType );
// Removes all the decals on a model instance
virtual void RemoveAllDecals( ModelInstanceHandle_t handle );
// Remove all decals from all models
virtual void RemoveAllDecalsFromAllModels();
// Shadow rendering (render-to-texture)
virtual matrix3x4_t* DrawModelShadowSetup( IClientRenderable *pRenderable, int body, int skin, DrawModelInfo_t *pInfo, matrix3x4_t *pBoneToWorld );
virtual void DrawModelShadow( IClientRenderable *pRenderable, const DrawModelInfo_t &info, matrix3x4_t *pBoneToWorld );
// Used to allow the shadow mgr to manage a list of shadows per model
unsigned short& FirstShadowOnModelInstance( ModelInstanceHandle_t handle ) { return m_ModelInstances[handle].m_FirstShadow; }
// This gets called when overbright, etc gets changed to recompute static prop lighting.
virtual bool RecomputeStaticLighting( ModelInstanceHandle_t handle );
// Handlers for alt-tab
virtual void ReleaseAllStaticPropColorData( void );
virtual void RestoreAllStaticPropColorData( void );
// Extended version of drawmodel
virtual bool DrawModelSetup( ModelRenderInfo_t &pInfo, DrawModelState_t *pState, matrix3x4_t *pBoneToWorld, matrix3x4_t** ppBoneToWorldOut );
virtual int DrawModelEx( ModelRenderInfo_t &pInfo );
virtual int DrawModelExStaticProp( ModelRenderInfo_t &pInfo );
virtual int DrawStaticPropArrayFast( StaticPropRenderInfo_t *pProps, int count, bool bShadowDepth );
// Sets up lighting context for a point in space
virtual void SetupLighting( const Vector &vecCenter );
virtual void SuppressEngineLighting( bool bSuppress );
inline vertexFileHeader_t *CacheVertexData() { return g_pMDLCache->GetVertexData( (MDLHandle_t)(int)m_pStudioHdr->virtualModel&0xffff ); }
bool Init();
void Shutdown();
bool GetItemName( DataCacheClientID_t clientId, const void *pItem, char *pDest, unsigned nMaxLen );
struct staticPropAsyncContext_t
{
DataCacheHandle_t m_ColorMeshHandle;
CColorMeshData *m_pColorMeshData;
int m_nMeshes;
unsigned int m_nRootLOD;
char m_szFilenameVertex[MAX_PATH];
char m_szFilenameTexel[MAX_PATH];
};
void StaticPropColorMeshCallback( void *pContext, const void *pData, int numReadBytes, FSAsyncStatus_t asyncStatus );
void StaticPropColorTexelCallback(void *pContext, const void *pData, int numReadBytes, FSAsyncStatus_t asyncStatus);
// 360 holds onto static prop color meshes during same map transitions
void PurgeCachedStaticPropColorData();
bool IsStaticPropColorDataCached( const char *pName );
DataCacheHandle_t GetCachedStaticPropColorData( const char *pName );
virtual void SetupColorMeshes( int nTotalVerts );
private:
enum
{
CURRENT_LIGHTING_UNINITIALIZED = -999999
};
enum ModelInstanceFlags_t
{
MODEL_INSTANCE_HAS_STATIC_LIGHTING = 0x1,
MODEL_INSTANCE_HAS_DISKCOMPILED_COLOR = 0x2,
MODEL_INSTANCE_DISKCOMPILED_COLOR_BAD = 0x4,
MODEL_INSTANCE_HAS_COLOR_DATA = 0x8
};
struct ModelInstance_t
{
IClientRenderable* m_pRenderable;
// Need to store off the model. When it changes, we lose all instance data..
model_t* m_pModel;
StudioDecalHandle_t m_DecalHandle;
// Stores off the current lighting state
LightingState_t m_CurrentLightingState;
LightingState_t m_AmbientLightingState;
Vector m_flLightIntensity[MAXLOCALLIGHTS];
float m_flLightingTime;
// First shadow projected onto the model
unsigned short m_FirstShadow;
unsigned short m_nFlags;
// Static lighting
LightCacheHandle_t m_LightCacheHandle;
// Color mesh managed by cache
DataCacheHandle_t m_ColorMeshHandle;
};
// Sets up the render state for a model
matrix3x4_t* SetupModelState( IClientRenderable *pRenderable );
int ComputeLOD( const ModelRenderInfo_t &info, studiohwdata_t *pStudioHWData );
void DrawModelExecute( const DrawModelState_t &state, const ModelRenderInfo_t &pInfo, matrix3x4_t *pCustomBoneToWorld = NULL );
void InitColormeshParams( ModelInstance_t &instance, studiohwdata_t *pStudioHWData, colormeshparams_t *pColorMeshParams );
CColorMeshData *FindOrCreateStaticPropColorData( ModelInstanceHandle_t handle );
void DestroyStaticPropColorData( ModelInstanceHandle_t handle );
bool UpdateStaticPropColorData( IHandleEntity *pEnt, ModelInstanceHandle_t handle );
void ProtectColorDataIfQueued( DataCacheHandle_t );
void ValidateStaticPropColorData( ModelInstanceHandle_t handle );
bool LoadStaticPropColorData( IHandleEntity *pProp, DataCacheHandle_t colorMeshHandle, studiohwdata_t *pStudioHWData );
// Returns true if the model instance is valid
bool IsModelInstanceValid( ModelInstanceHandle_t handle );
void DebugDrawLightingOrigin( const DrawModelState_t& state, const ModelRenderInfo_t &pInfo );
LightingState_t *TimeAverageLightingState( ModelInstanceHandle_t handle,
LightingState_t *pLightingState, int nEntIndex, const Vector *pLightingOrigin );
// Cause the current lighting state to match the given one
void SnapCurrentLightingState( ModelInstance_t &inst, LightingState_t *pLightingState );
// Sets up lighting state for rendering
void StudioSetupLighting( const DrawModelState_t &state, const Vector& absEntCenter,
LightCacheHandle_t* pLightcache, bool bVertexLit, bool bNeedsEnvCubemap, bool &bStaticLighting,
DrawModelInfo_t &drawInfo, const ModelRenderInfo_t &pInfo, int drawFlags );
// Time average the ambient term
void TimeAverageAmbientLight( LightingState_t &actualLightingState, ModelInstance_t &inst,
float flAttenFactor, LightingState_t *pLightingState, const Vector *pLightingOrigin );
// Old-style computation of vertex lighting
void ComputeModelVertexLightingOld( mstudiomodel_t *pModel,
matrix3x4_t& matrix, const LightingState_t &lightingState, color24 *pLighting,
bool bUseConstDirLighting, float flConstDirLightAmount );
// New-style computation of vertex lighting
void ComputeModelVertexLighting( IHandleEntity *pProp,
mstudiomodel_t *pModel, OptimizedModel::ModelLODHeader_t *pVtxLOD,
matrix3x4_t& matrix, Vector4D *pTempMem, color24 *pLighting );
// Internal Decal
void AddDecalInternal( ModelInstanceHandle_t handle, Ray_t const& ray, const Vector& decalUp, int decalIndex, int body, bool bUseColor, Color cColor, bool noPokeThru, int maxLODToDecal);
// Model instance data
CUtlLinkedList< ModelInstance_t, ModelInstanceHandle_t > m_ModelInstances;
// current active model
studiohdr_t *m_pStudioHdr;
bool m_bSuppressEngineLighting;
CUtlDict< DataCacheHandle_t, int > m_CachedStaticPropColorData;