-
Notifications
You must be signed in to change notification settings - Fork 99
/
UnitDrawer.cpp
2359 lines (1799 loc) · 69.5 KB
/
UnitDrawer.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
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */
#include "UnitDrawer.h"
#include "UnitDrawerState.hpp"
#include "Game/Camera.h"
#include "Game/CameraHandler.h"
#include "Game/Game.h"
#include "Game/GameHelper.h"
#include "Game/GameSetup.h"
#include "Game/GlobalUnsynced.h"
#include "Game/Players/Player.h"
#include "Game/UI/MiniMap.h"
#include "Map/BaseGroundDrawer.h"
#include "Map/Ground.h"
#include "Map/MapInfo.h"
#include "Map/ReadMap.h"
#include "Rendering/Env/ISky.h"
#include "Rendering/Env/IWater.h"
#include "Rendering/Env/CubeMapHandler.h"
#include "Rendering/FarTextureHandler.h"
#include "Rendering/GL/glExtra.h"
#include "Rendering/GL/VertexArray.h"
#include "Rendering/Env/IGroundDecalDrawer.h"
#include "Rendering/Colors.h"
#include "Rendering/IconHandler.h"
#include "Rendering/LuaObjectDrawer.h"
#include "Rendering/ShadowHandler.h"
#include "Rendering/Shaders/Shader.h"
#include "Rendering/Textures/Bitmap.h"
#include "Rendering/Textures/3DOTextureHandler.h"
#include "Rendering/Textures/S3OTextureHandler.h"
#include "Sim/Features/Feature.h"
#include "Sim/Misc/LosHandler.h"
#include "Sim/Misc/TeamHandler.h"
#include "Sim/Projectiles/ExplosionGenerator.h"
#include "Sim/Units/BuildInfo.h"
#include "Sim/Units/UnitDef.h"
#include "Sim/Units/UnitDefHandler.h"
#include "Sim/Units/Unit.h"
#include "Sim/Units/UnitHandler.h"
#include "System/Config/ConfigHandler.h"
#include "System/FileSystem/FileHandler.h"
#include "System/ContainerUtil.h"
#include "System/EventHandler.h"
#include "System/MemPoolTypes.h"
#include "System/SpringMath.h"
#define UNIT_SHADOW_ALPHA_MASKING
CONFIG(int, UnitLodDist).defaultValue(1000).headlessValue(0);
CONFIG(int, UnitIconDist).defaultValue(200).headlessValue(0);
CONFIG(float, UnitIconScaleUI).defaultValue(1.0f).minimumValue(0.5f).maximumValue(2.0f);
CONFIG(float, UnitIconFadeStart).defaultValue(3000.0f).minimumValue(1.0f).maximumValue(10000.0f);
CONFIG(float, UnitIconFadeVanish).defaultValue(1000.0f).minimumValue(1.0f).maximumValue(10000.0f);
CONFIG(float, UnitTransparency).defaultValue(0.7f);
CONFIG(bool, UnitIconsAsUI).defaultValue(false).description("Draw unit icons like it is an UI element and not like unit's LOD.");
CONFIG(bool, UnitIconsHideWithUI).defaultValue(false).description("Hide unit icons when UI is hidden.");
CONFIG(int, MaxDynamicModelLights)
.defaultValue(1)
.minimumValue(0);
CONFIG(bool, AdvUnitShading).defaultValue(true).headlessValue(false).safemodeValue(false).description("Determines whether specular highlights and other lighting effects are rendered for units.");
CUnitDrawer* unitDrawer = nullptr;
float CUnitDrawer::iconSizeBase = 32;
float CUnitDrawer::iconScale = 1;
float CUnitDrawer::iconFadeStart = 3000;
float CUnitDrawer::iconFadeVanish = 1000;
float CUnitDrawer::iconZoomDist;
// can not be a CUnitDrawer; destruction in global
// scope might happen after ~EventHandler which is
// referenced by ~EventClient
static uint8_t unitDrawerMem[sizeof(CUnitDrawer)];
static FixedDynMemPool<sizeof(GhostSolidObject), MAX_UNITS / 1000, MAX_UNITS / 32> ghostMemPool;
static void LoadUnitExplosionGenerators() {
using F = decltype(&UnitDef::AddModelExpGenID);
using T = decltype(UnitDef::modelCEGTags);
const auto LoadGenerators = [](UnitDef* ud, const F addExplGenID, const T& explGenTags, const char* explGenPrefix) {
for (const auto& explGenTag: explGenTags) {
if (explGenTag[0] == 0)
break;
// build a contiguous range of valid ID's
(ud->*addExplGenID)(explGenHandler.LoadGeneratorID(explGenTag, explGenPrefix));
}
};
for (unsigned int i = 0, n = unitDefHandler->NumUnitDefs(); i < n; i++) {
UnitDef* ud = const_cast<UnitDef*>(unitDefHandler->GetUnitDefByID(i + 1));
// piece- and crash-generators can only be custom so the prefix is not required to be given game-side
LoadGenerators(ud, &UnitDef::AddModelExpGenID, ud->modelCEGTags, "");
LoadGenerators(ud, &UnitDef::AddPieceExpGenID, ud->pieceCEGTags, CEG_PREFIX_STRING);
LoadGenerators(ud, &UnitDef::AddCrashExpGenID, ud->crashCEGTags, CEG_PREFIX_STRING);
}
}
static const void BindOpaqueTex(const CS3OTextureHandler::S3OTexMat* textureMat) {
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textureMat->tex2);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureMat->tex1);
}
static const void BindOpaqueTexAtlas(const CS3OTextureHandler::S3OTexMat*) {
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textureHandler3DO.GetAtlasTex2ID());
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureHandler3DO.GetAtlasTex1ID());
}
static const void BindOpaqueTexDummy(const CS3OTextureHandler::S3OTexMat*) {}
static const void BindShadowTex(const CS3OTextureHandler::S3OTexMat* textureMat) {
glActiveTexture(GL_TEXTURE0);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, textureMat->tex2);
}
static const void KillShadowTex(const CS3OTextureHandler::S3OTexMat*) {
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE0);
}
static const void BindShadowTexAtlas(const CS3OTextureHandler::S3OTexMat*) {
glActiveTexture(GL_TEXTURE0);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, textureHandler3DO.GetAtlasTex2ID());
}
static const void KillShadowTexAtlas(const CS3OTextureHandler::S3OTexMat*) {
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE0);
}
static const void PushRenderState3DO() {
BindOpaqueTexAtlas(nullptr);
glPushAttrib(GL_POLYGON_BIT);
glDisable(GL_CULL_FACE);
}
static const void PushRenderStateS3O() {
if (globalRendering->supportRestartPrimitive) {
glPrimitiveRestartIndexNV(-1U);
}
}
static const void PushRenderStateASS() { /* no-op */ }
static const void PopRenderState3DO() { glPopAttrib(); }
static const void PopRenderStateS3O() { /* no-op */ }
static const void PopRenderStateASS() { /* no-op */ }
static const void SetTeamColorDummy(const IUnitDrawerState* state, int team, const float2 alpha) {}
static const void SetTeamColorValid(const IUnitDrawerState* state, int team, const float2 alpha) { state->SetTeamColor(team, alpha); }
// typedef std::function<void(int)> BindTexFunc;
// typedef std::function<void(const CS3OTextureHandler::S3OTexMat*)> BindTexFunc;
// typedef std::function<void()> KillTexFunc;
typedef const void (*BindTexFunc)(const CS3OTextureHandler::S3OTexMat*);
typedef const void (*BindTexFunc)(const CS3OTextureHandler::S3OTexMat*);
typedef const void (*KillTexFunc)(const CS3OTextureHandler::S3OTexMat*);
typedef const void (*PushRenderStateFunc)();
typedef const void (*PopRenderStateFunc)();
typedef const void (*SetTeamColorFunc)(const IUnitDrawerState*, int team, const float2 alpha);
static const BindTexFunc opaqueTexBindFuncs[MODELTYPE_OTHER] = {
BindOpaqueTexDummy, // 3DO (no-op, done by PushRenderState3DO)
BindOpaqueTex, // S3O
BindOpaqueTex, // ASS
};
static const BindTexFunc shadowTexBindFuncs[MODELTYPE_OTHER] = {
BindShadowTexAtlas, // 3DO
BindShadowTex, // S3O
BindShadowTex, // ASS
};
static const BindTexFunc* bindModelTexFuncs[] = {
&opaqueTexBindFuncs[0], // opaque+alpha
&shadowTexBindFuncs[0], // shadow
};
static const KillTexFunc shadowTexKillFuncs[MODELTYPE_OTHER] = {
KillShadowTexAtlas, // 3DO
KillShadowTex, // S3O
KillShadowTex, // ASS
};
static const PushRenderStateFunc renderStatePushFuncs[MODELTYPE_OTHER] = {
PushRenderState3DO,
PushRenderStateS3O,
PushRenderStateASS,
};
static const PopRenderStateFunc renderStatePopFuncs[MODELTYPE_OTHER] = {
PopRenderState3DO,
PopRenderStateS3O,
PopRenderStateASS,
};
static const SetTeamColorFunc setTeamColorFuncs[] = {
SetTeamColorDummy,
SetTeamColorValid,
};
// low-level (batch and solo)
// note: also called during SP
void CUnitDrawer::BindModelTypeTexture(int mdlType, int texType) {
const auto texFun = bindModelTexFuncs[shadowHandler.InShadowPass()][mdlType];
const auto texMat = textureHandlerS3O.GetTexture(texType);
texFun(texMat);
}
void CUnitDrawer::PushModelRenderState(int mdlType) { renderStatePushFuncs[mdlType](); }
void CUnitDrawer::PopModelRenderState (int mdlType) { renderStatePopFuncs [mdlType](); }
// mid-level (solo only)
void CUnitDrawer::PushModelRenderState(const S3DModel* m) {
PushModelRenderState(m->type);
BindModelTypeTexture(m->type, m->textureType);
}
void CUnitDrawer::PopModelRenderState(const S3DModel* m) {
PopModelRenderState(m->type);
}
// high-level (solo only)
void CUnitDrawer::PushModelRenderState(const CSolidObject* o) { PushModelRenderState(o->model); }
void CUnitDrawer::PopModelRenderState(const CSolidObject* o) { PopModelRenderState(o->model); }
void CUnitDrawer::InitStatic() {
if (unitDrawer == nullptr)
unitDrawer = new (unitDrawerMem) CUnitDrawer();
unitDrawer->Init();
}
void CUnitDrawer::KillStatic(bool reload) {
unitDrawer->Kill();
if (reload)
return;
spring::SafeDestruct(unitDrawer);
memset(unitDrawerMem, 0, sizeof(unitDrawerMem));
}
void CUnitDrawer::Init() {
eventHandler.AddClient(this);
LuaObjectDrawer::ReadLODScales(LUAOBJ_UNIT);
SetUnitDrawDist((float)configHandler->GetInt("UnitLodDist"));
SetUnitIconDist((float)configHandler->GetInt("UnitIconDist"));
iconScale = configHandler->GetFloat("UnitIconScaleUI");
iconFadeStart = configHandler->GetFloat("UnitIconFadeStart");
iconFadeVanish = configHandler->GetFloat("UnitIconFadeVanish");
useScreenIcons = configHandler->GetBool("UnitIconsAsUI");
iconHideWithUI = configHandler->GetBool("UnitIconsHideWithUI");
alphaValues.x = std::max(0.11f, std::min(1.0f, 1.0f - configHandler->GetFloat("UnitTransparency")));
alphaValues.y = std::min(1.0f, alphaValues.x + 0.1f);
alphaValues.z = std::min(1.0f, alphaValues.x + 0.2f);
alphaValues.w = std::min(1.0f, alphaValues.x + 0.4f);
LoadUnitExplosionGenerators();
for (int modelType = MODELTYPE_3DO; modelType < MODELTYPE_OTHER; modelType++) {
opaqueModelRenderers[modelType].Init();
alphaModelRenderers[modelType].Init();
}
unitDefImages.clear();
unitDefImages.resize(unitDefHandler->NumUnitDefs() + 1);
deadGhostBuildings.resize(teamHandler.ActiveAllyTeams());
liveGhostBuildings.resize(teamHandler.ActiveAllyTeams());
// LH must be initialized before drawer-state is initialized
lightHandler.Init(2U, configHandler->GetInt("MaxDynamicModelLights"));
unitDrawerStates.fill(nullptr);
unitDrawerStates[DRAWER_STATE_SSP] = IUnitDrawerState::GetInstance(globalRendering->haveARB, globalRendering->haveGLSL);
unitDrawerStates[DRAWER_STATE_FFP] = IUnitDrawerState::GetInstance( false, false);
drawModelFuncs[0] = &CUnitDrawer::DrawUnitModelBeingBuiltOpaque;
drawModelFuncs[1] = &CUnitDrawer::DrawUnitModelBeingBuiltShadow;
drawModelFuncs[2] = &CUnitDrawer::DrawUnitModel;
// shared with FeatureDrawer!
geomBuffer = LuaObjectDrawer::GetGeometryBuffer();
drawForward = true;
drawDeferred = (geomBuffer->Valid());
wireFrameMode = false;
// NOTE:
// advShading can NOT change at runtime if initially false***
// (see AdvModelShadingActionExecutor), so we will always use
// FFP renderer-state (in ::Draw) in that special case and it
// does not matter whether SSP renderer-state is initialized
// *** except for DrawAlphaUnits
advShading = (unitDrawerStates[DRAWER_STATE_SSP]->Init(this) && cubeMapHandler.Init());
// note: state must be pre-selected before the first drawn frame
// Sun*Changed can be called first, e.g. if DynamicSun is enabled
unitDrawerStates[DRAWER_STATE_SEL] = const_cast<IUnitDrawerState*>(GetWantedDrawerState(false));
iconSizeBase = std::max(16.0f, std::max(globalRendering->viewSizeX, globalRendering->viewSizeY) * iconSizeMult * iconScale);
}
void CUnitDrawer::Kill()
{
eventHandler.RemoveClient(this);
autoLinkedEvents.clear();
unitDrawerStates[DRAWER_STATE_SSP]->Kill(); IUnitDrawerState::FreeInstance(unitDrawerStates[DRAWER_STATE_SSP]);
unitDrawerStates[DRAWER_STATE_FFP]->Kill(); IUnitDrawerState::FreeInstance(unitDrawerStates[DRAWER_STATE_FFP]);
cubeMapHandler.Free();
for (CUnit* u: unsortedUnits) {
groundDecals->ForceRemoveSolidObject(u);
}
for (UnitDefImage& img: unitDefImages) {
img.Free();
}
for (int allyTeam = 0; allyTeam < deadGhostBuildings.size(); ++allyTeam) {
for (int modelType = MODELTYPE_3DO; modelType < MODELTYPE_OTHER; modelType++) {
auto& lgb = liveGhostBuildings[allyTeam][modelType];
auto& dgb = deadGhostBuildings[allyTeam][modelType];
for (auto it = dgb.begin(); it != dgb.end(); ++it) {
GhostSolidObject* gso = *it;
if (gso->DecRef())
continue;
// <ghost> might be the gbOwner of a decal; groundDecals is deleted after us
groundDecals->GhostDestroyed(gso);
ghostMemPool.free(gso);
}
dgb.clear();
lgb.clear();
}
}
// reuse inner vectors when reloading
// deadGhostBuildings.clear();
// liveGhostBuildings.clear();
for (int modelType = MODELTYPE_3DO; modelType < MODELTYPE_OTHER; modelType++) {
opaqueModelRenderers[modelType].Kill();
alphaModelRenderers[modelType].Kill();
}
unsortedUnits.clear();
unitsByIcon.clear();
geomBuffer = nullptr;
}
void CUnitDrawer::Update()
{
for (int modelType = MODELTYPE_3DO; modelType < MODELTYPE_OTHER; modelType++) {
UpdateTempDrawUnits(tempOpaqueUnits[modelType]);
UpdateTempDrawUnits(tempAlphaUnits[modelType]);
}
iconUnits.clear();
const float3 camPos = (camHandler->GetCurrentController()).GetPos();
const float3 camDir = (camHandler->GetCurrentController()).GetDir();
float dist = CGround::LineGroundCol(camPos, camDir * 150000.0f, false);
if (dist < 0)
dist = std::max(0.0f, CGround::LinePlaneCol(camPos, camDir, 150000.0f, readMap->GetCurrAvgHeight()));
iconZoomDist = dist;
for (CUnit* unit: unsortedUnits) {
if (useScreenIcons)
UpdateUnitIconStateScreen(unit);
else
UpdateUnitIconState(unit);
UpdateUnitDrawPos(unit);
}
if ((useDistToGroundForIcons = (camHandler->GetCurrentController()).GetUseDistToGroundForIcons())) {
const float3& camPos = camera->GetPos();
// use the height at the current camera position
//const float groundHeight = CGround::GetHeightAboveWater(camPos.x, camPos.z, false);
// use the middle between the highest and lowest position on the map as average
const float groundHeight = readMap->GetCurrAvgHeight();
const float overGround = camPos.y - groundHeight;
sqCamDistToGroundForIcons = overGround * overGround;
}
}
void CUnitDrawer::Draw(bool drawReflection, bool drawRefraction)
{
sky->SetupFog();
assert((CCameraHandler::GetActiveCamera())->GetCamType() != CCamera::CAMTYPE_SHADOW);
// first do the deferred pass; conditional because
// most of the water renderers use their own FBO's
if (drawDeferred && !drawReflection && !drawRefraction)
LuaObjectDrawer::DrawDeferredPass(LUAOBJ_UNIT);
// now do the regular forward pass
if (drawForward)
DrawOpaquePass(false, drawReflection, drawRefraction);
farTextureHandler->Draw();
glDisable(GL_FOG);
glDisable(GL_ALPHA_TEST);
glDisable(GL_TEXTURE_2D);
}
void CUnitDrawer::DrawOpaquePass(bool deferredPass, bool drawReflection, bool drawRefraction)
{
SetupOpaqueDrawing(deferredPass);
for (int modelType = MODELTYPE_3DO; modelType < MODELTYPE_OTHER; modelType++) {
PushModelRenderState(modelType);
DrawOpaqueUnits(modelType, drawReflection, drawRefraction);
DrawOpaqueAIUnits(modelType);
PopModelRenderState(modelType);
}
ResetOpaqueDrawing(deferredPass);
// draw all custom'ed units that were bypassed in the loop above
LuaObjectDrawer::SetDrawPassGlobalLODFactor(LUAOBJ_UNIT);
LuaObjectDrawer::DrawOpaqueMaterialObjects(LUAOBJ_UNIT, deferredPass);
}
void CUnitDrawer::DrawOpaqueUnits(int modelType, bool drawReflection, bool drawRefraction)
{
const auto& mdlRenderer = opaqueModelRenderers[modelType];
// const auto& unitBinKeys = mdlRenderer.GetObjectBinKeys();
for (unsigned int i = 0, n = mdlRenderer.GetNumObjectBins(); i < n; i++) {
BindModelTypeTexture(modelType, mdlRenderer.GetObjectBinKey(i));
for (CUnit* unit: mdlRenderer.GetObjectBin(i)) {
DrawOpaqueUnit(unit, drawReflection, drawRefraction);
}
}
}
inline void CUnitDrawer::DrawOpaqueUnit(CUnit* unit, bool drawReflection, bool drawRefraction)
{
if (!CanDrawOpaqueUnit(unit, drawReflection, drawRefraction))
return;
if ((unit->pos).SqDistance(camera->GetPos()) > (unit->sqRadius * unitDrawDistSqr)) {
farTextureHandler->Queue(unit);
return;
}
if (LuaObjectDrawer::AddOpaqueMaterialObject(unit, LUAOBJ_UNIT))
return;
// draw the unit with the default (non-Lua) material
SetTeamColour(unit->team);
DrawUnitTrans(unit, 0, 0, false, false);
}
void CUnitDrawer::DrawOpaqueAIUnits(int modelType)
{
const std::vector<TempDrawUnit>& tmpOpaqueUnits = tempOpaqueUnits[modelType];
// NOTE: not type-sorted
for (const TempDrawUnit& unit: tmpOpaqueUnits) {
if (!camera->InView(unit.pos, 100.0f))
continue;
DrawOpaqueAIUnit(unit);
}
}
void CUnitDrawer::DrawOpaqueAIUnit(const TempDrawUnit& unit)
{
glPushMatrix();
glTranslatef3(unit.pos);
glRotatef(unit.rotation * math::RAD_TO_DEG, 0.0f, 1.0f, 0.0f);
const UnitDef* def = unit.unitDef;
const S3DModel* mdl = def->model;
assert(mdl != nullptr);
BindModelTypeTexture(mdl->type, mdl->textureType);
SetTeamColour(unit.team);
mdl->DrawStatic();
glPopMatrix();
}
void CUnitDrawer::DrawUnitIcons()
{
// draw unit icons and radar blips
glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_CURRENT_BIT);
glEnable(GL_TEXTURE_2D);
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0.05f);
// A2C effectiveness is limited below four samples
if (globalRendering->msaaLevel >= 4)
glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
for (CUnit* u: iconUnits) {
const unsigned short closBits = (u->losStatus[gu->myAllyTeam] & (LOS_INLOS ));
const unsigned short plosBits = (u->losStatus[gu->myAllyTeam] & (LOS_PREVLOS | LOS_CONTRADAR));
DrawIcon(u, !gu->spectatingFullView && closBits == 0 && plosBits != (LOS_PREVLOS | LOS_CONTRADAR));
}
glPopAttrib();
}
void CUnitDrawer::DrawUnitIconsScreen()
{
if (game->hideInterface && iconHideWithUI)
return;
// draw unit icons and radar blips
glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_CURRENT_BIT);
glEnable(GL_TEXTURE_2D);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0.05f);
CVertexArray* va = GetVertexArray();
iconSizeBase = std::max(12.0f, std::max(globalRendering->viewSizeX, globalRendering->viewSizeY) * iconSizeMult * iconScale);
for (auto iconIt = unitsByIcon.cbegin(); iconIt != unitsByIcon.cend(); ++iconIt)
{
const icon::CIconData* icon = iconIt->first;
const std::vector<const CUnit*>& units = iconIt->second;
if (icon == nullptr)
continue;
if (units.empty())
continue;
va->Initialize();
va->EnlargeArrays(units.size() * 4, 0, VA_SIZE_2DTC);
icon->BindTexture();
for (const CUnit* unit: units)
{
if (unit->noDraw)
continue;
if (unit->IsInVoid())
continue;
if (unit->health <= 0 || unit->beingBuilt)
continue;
const unsigned short closBits = (unit->losStatus[gu->myAllyTeam] & (LOS_INLOS ));
const unsigned short plosBits = (unit->losStatus[gu->myAllyTeam] & (LOS_PREVLOS | LOS_CONTRADAR));
assert(unit->myIcon == icon);
DrawIconScreenArray(unit, icon, !gu->spectatingFullView && closBits == 0 && plosBits != (LOS_PREVLOS | LOS_CONTRADAR), iconZoomDist, va);
}
va->DrawArray2dTC(GL_QUADS);
}
glPopAttrib();
}
/******************************************************************************/
/******************************************************************************/
bool CUnitDrawer::CanDrawOpaqueUnit(
const CUnit* unit,
bool drawReflection,
bool drawRefraction
) const {
if (unit == (drawReflection? nullptr: (gu->GetMyPlayer())->fpsController.GetControllee()))
return false;
if (unit->noDraw)
return false;
if (unit->IsInVoid())
return false;
// unit will be drawn as icon instead
if (unit->isIcon)
return false;
if (!(unit->losStatus[gu->myAllyTeam] & LOS_INLOS) && !gu->spectatingFullView)
return false;
// either PLAYER or UWREFL
const CCamera* cam = CCameraHandler::GetActiveCamera();
if (drawRefraction && !unit->IsInWater())
return false;
if (drawReflection && !ObjectVisibleReflection(unit->drawMidPos, cam->GetPos(), unit->GetDrawRadius()))
return false;
return (cam->InView(unit->drawMidPos, unit->GetDrawRadius()));
}
bool CUnitDrawer::CanDrawOpaqueUnitShadow(const CUnit* unit) const
{
if (unit->noDraw)
return false;
if (unit->IsInVoid())
return false;
// no shadow if unit is already an icon from player's POV
if (unit->isIcon)
return false;
if (unit->isCloaked)
return false;
const CCamera* cam = CCameraHandler::GetActiveCamera();
const bool unitInLOS = ((unit->losStatus[gu->myAllyTeam] & LOS_INLOS) || gu->spectatingFullView);
const bool unitInView = cam->InView(unit->drawMidPos, unit->GetDrawRadius());
return (unitInLOS && unitInView);
}
void CUnitDrawer::DrawOpaqueUnitShadow(CUnit* unit) {
if (!CanDrawOpaqueUnitShadow(unit))
return;
if (LuaObjectDrawer::AddShadowMaterialObject(unit, LUAOBJ_UNIT))
return;
DrawUnitTrans(unit, 0, 0, false, false);
}
void CUnitDrawer::DrawOpaqueUnitsShadow(int modelType) {
const auto& mdlRenderer = opaqueModelRenderers[modelType];
// const auto& unitBinKeys = mdlRenderer.GetObjectBinKeys();
for (unsigned int i = 0, n = mdlRenderer.GetNumObjectBins(); i < n; i++) {
// only need to bind the atlas once for 3DO's, but KISS
assert((modelType != MODELTYPE_3DO) || (mdlRenderer.GetObjectBinKey(i) == 0));
shadowTexBindFuncs[modelType](textureHandlerS3O.GetTexture(mdlRenderer.GetObjectBinKey(i)));
for (CUnit* unit: mdlRenderer.GetObjectBin(i)) {
DrawOpaqueUnitShadow(unit);
}
shadowTexKillFuncs[modelType](nullptr);
}
}
void CUnitDrawer::DrawShadowPass()
{
glColor3f(1.0f, 1.0f, 1.0f);
glPolygonOffset(1.0f, 1.0f);
glEnable(GL_POLYGON_OFFSET_FILL);
#ifdef UNIT_SHADOW_ALPHA_MASKING
glAlphaFunc(GL_GREATER, 0.5f);
glEnable(GL_ALPHA_TEST);
#endif
Shader::IProgramObject* po = shadowHandler.GetShadowGenProg(CShadowHandler::SHADOWGEN_PROGRAM_MODEL);
po->Enable();
{
assert((CCameraHandler::GetActiveCamera())->GetCamType() == CCamera::CAMTYPE_SHADOW);
// 3DO's have clockwise-wound faces and
// (usually) holes, so disable backface
// culling for them
glDisable(GL_CULL_FACE);
DrawOpaqueUnitsShadow(MODELTYPE_3DO);
glEnable(GL_CULL_FACE);
for (int modelType = MODELTYPE_S3O; modelType < MODELTYPE_OTHER; modelType++) {
// note: just use DrawOpaqueUnits()? would
// save texture switches needed anyway for
// UNIT_SHADOW_ALPHA_MASKING
DrawOpaqueUnitsShadow(modelType);
}
}
po->Disable();
#ifdef UNIT_SHADOW_ALPHA_MASKING
glDisable(GL_ALPHA_TEST);
#endif
glDisable(GL_POLYGON_OFFSET_FILL);
LuaObjectDrawer::SetDrawPassGlobalLODFactor(LUAOBJ_UNIT);
LuaObjectDrawer::DrawShadowMaterialObjects(LUAOBJ_UNIT, false);
}
void CUnitDrawer::DrawIconScreenArray(const CUnit* unit, const icon::CIconData* icon, bool useDefaultIcon, const float dist, CVertexArray* va)
{
// iconUnits should not never contain void-space units, see UpdateUnitIconState
assert(!unit->IsInVoid());
// drawMidPos is auto-calculated now; can wobble on its own as pieces move
float3 pos = (!gu->spectatingFullView) ?
unit->GetObjDrawErrorPos(gu->myAllyTeam) :
unit->GetObjDrawMidPos();
pos = camera->CalcWindowCoordinates(pos);
if (pos.z < 0)
return;
// use white for selected units
const uint8_t* srcColor = unit->isSelected? color4::white: teamHandler.Team(unit->team)->color;
uint8_t color[4] = { srcColor[0], srcColor[1], srcColor[2], 255 };
float unitRadiusMult = icon->GetSize();
if (icon->GetRadiusAdjust() && !useDefaultIcon)
unitRadiusMult *= (unit->radius / icon->GetRadiusScale());
unitRadiusMult = (unitRadiusMult - 1) * 0.75 + 1;
// fade icons away in high zoom in levels
if (!unit->isIcon)
if (dist / unitRadiusMult < iconFadeVanish)
return;
else if (iconFadeVanish < iconFadeStart && dist / unitRadiusMult < iconFadeStart)
// alpha range [64, 255], since icons is unrecognisable with alpha < 64
color[3] = 64 + 191.0f * (dist / unitRadiusMult - iconFadeVanish) / (iconFadeStart - iconFadeVanish);
// calculate the vertices
const float offset = iconSizeBase / 2.0f * unitRadiusMult;
const float x0 = (pos.x - offset) / globalRendering->viewSizeX;
const float y0 = (pos.y + offset) / globalRendering->viewSizeY;
const float x1 = (pos.x + offset) / globalRendering->viewSizeX;
const float y1 = (pos.y - offset) / globalRendering->viewSizeY;
if (x1 < 0 || x0 > 1 || y0 < 0 || y1 > 1)
return; // don't try to draw outside the screen
// Draw the icon.
icon->DrawArray(va, x0, y0, x1, y1, color);
}
void CUnitDrawer::DrawIcon(CUnit* unit, bool useDefaultIcon)
{
// iconUnits should not never contain void-space units, see UpdateUnitIconState
assert(!unit->IsInVoid());
// If the icon is to be drawn as a radar blip, we want to get the default icon.
const icon::CIconData* iconData = nullptr;
if (useDefaultIcon) {
iconData = icon::iconHandler.GetDefaultIconData();
} else {
iconData = unit->unitDef->iconType.GetIconData();
}
// drawMidPos is auto-calculated now; can wobble on its own as pieces move
float3 pos = (!gu->spectatingFullView) ?
unit->GetObjDrawErrorPos(gu->myAllyTeam) :
unit->GetObjDrawMidPos();
// make sure icon is above ground (needed before we calculate scale below)
const float h = CGround::GetHeightReal(pos.x, pos.z, false);
pos.y = std::max(pos.y, h);
// Calculate the icon size. It scales with:
// * The square root of the camera distance.
// * The mod defined 'iconSize' (which acts a multiplier).
// * The unit radius, depending on whether the mod defined 'radiusadjust' is true or false.
const float dist = std::min(8000.0f, fastmath::sqrt_builtin(camera->GetPos().SqDistance(pos)));
const float iconScale = 0.4f * fastmath::sqrt_builtin(dist); // makes far icons bigger
float scale = iconData->GetSize() * iconScale;
if (iconData->GetRadiusAdjust() && !useDefaultIcon)
scale *= (unit->radius / iconData->GetRadiusScale());
// make sure icon is not partly under ground
pos.y = std::max(pos.y, h + (unit->iconRadius = scale));
// use white for selected units
const uint8_t* colors[] = {teamHandler.Team(unit->team)->color, color4::white};
const uint8_t* color = colors[unit->isSelected];
glColor3ubv(color);
// calculate the vertices
const float3 dy = camera->GetUp() * scale;
const float3 dx = camera->GetRight() * scale;
const float3 vn = pos - dx;
const float3 vp = pos + dx;
const float3 vnn = vn - dy;
const float3 vpn = vp - dy;
const float3 vnp = vn + dy;
const float3 vpp = vp + dy;
// Draw the icon.
iconData->Draw(vnn, vpn, vnp, vpp);
}
void CUnitDrawer::SetupAlphaDrawing(bool deferredPass)
{
glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_POLYGON_BIT);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE * wireFrameMode + GL_FILL * (1 - wireFrameMode));
unitDrawerStates[DRAWER_STATE_SEL] = const_cast<IUnitDrawerState*>(GetWantedDrawerState(true));
unitDrawerStates[DRAWER_STATE_SEL]->Enable(this, /*deferredPass*/ false, true);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0.1f);
glDepthMask(GL_FALSE);
}
void CUnitDrawer::ResetAlphaDrawing(bool deferredPass)
{
unitDrawerStates[DRAWER_STATE_SEL]->Disable(this, /*deferredPass*/ false);
glPopAttrib();
}
void CUnitDrawer::DrawAlphaPass()
{
{
SetupAlphaDrawing(false);
if (UseAdvShading())
glDisable(GL_ALPHA_TEST);
for (int modelType = MODELTYPE_3DO; modelType < MODELTYPE_OTHER; modelType++) {
PushModelRenderState(modelType);
DrawAlphaUnits(modelType);
DrawAlphaAIUnits(modelType);
PopModelRenderState(modelType);
}
if (UseAdvShading())
glEnable(GL_ALPHA_TEST);
ResetAlphaDrawing(false);
}
LuaObjectDrawer::SetDrawPassGlobalLODFactor(LUAOBJ_UNIT);
LuaObjectDrawer::DrawAlphaMaterialObjects(LUAOBJ_UNIT, false);
}
void CUnitDrawer::DrawAlphaUnits(int modelType)
{
{
const auto& mdlRenderer = alphaModelRenderers[modelType];
// const auto& unitBinKeys = mdlRenderer.GetObjectBinKeys();
for (unsigned int i = 0, n = mdlRenderer.GetNumObjectBins(); i < n; i++) {
BindModelTypeTexture(modelType, mdlRenderer.GetObjectBinKey(i));
for (CUnit* unit: mdlRenderer.GetObjectBin(i)) {
DrawAlphaUnit(unit, modelType, false);
}
}
}
// living and dead ghosted buildings
if (!gu->spectatingFullView)
DrawGhostedBuildings(modelType);
}
inline void CUnitDrawer::DrawAlphaUnit(CUnit* unit, int modelType, bool drawGhostBuildingsPass) {
if (!camera->InView(unit->drawMidPos, unit->GetDrawRadius()))
return;
if (LuaObjectDrawer::AddAlphaMaterialObject(unit, LUAOBJ_UNIT))
return;
const unsigned short losStatus = unit->losStatus[gu->myAllyTeam];
if (drawGhostBuildingsPass) {
// check for decoy models
const UnitDef* decoyDef = unit->unitDef->decoyDef;
const S3DModel* model = nullptr;
if (decoyDef == nullptr) {
model = unit->model;
} else {
model = decoyDef->LoadModel();
}
// FIXME: needs a second pass
if (model->type != modelType)
return;
// ghosted enemy units
if (losStatus & LOS_CONTRADAR) {
glColor4f(0.9f, 0.9f, 0.9f, alphaValues.z);
} else {
glColor4f(0.6f, 0.6f, 0.6f, alphaValues.y);
}
glPushMatrix();
glTranslatef3(unit->drawPos);
glRotatef(unit->buildFacing * 90.0f, 0, 1, 0);
// the units in liveGhostedBuildings[modelType] are not
// sorted by textureType, but we cannot merge them with
// alphaModelRenderers[modelType] either since they are
// not actually cloaked
BindModelTypeTexture(modelType, model->textureType);
SetTeamColour(unit->team, float2((losStatus & LOS_CONTRADAR)? alphaValues.z: alphaValues.y, 1.0f));
model->DrawStatic();
glPopMatrix();
glColor4f(1.0f, 1.0f, 1.0f, alphaValues.x);
return;
}
if (unit->isIcon)
return;
if ((losStatus & LOS_INLOS) || gu->spectatingFullView) {
SetTeamColour(unit->team, float2(alphaValues.x, 1.0f));
DrawUnitTrans(unit, 0, 0, false, false);
}
}
void CUnitDrawer::DrawAlphaAIUnits(int modelType)
{
std::vector<TempDrawUnit>& tmpAlphaUnits = tempAlphaUnits[modelType];
// NOTE: not type-sorted
for (const TempDrawUnit& unit: tmpAlphaUnits) {
if (!camera->InView(unit.pos, 100.0f))
continue;
DrawAlphaAIUnit(unit);
DrawAlphaAIUnitBorder(unit);
}
}