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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
|
/*
* Copyright 2019-2021 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include "pch.h"
#include "DeviceContextGLImpl.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include <array>
#include "SwapChainGL.h"
#include "RenderDeviceGLImpl.hpp"
#include "BufferGLImpl.hpp"
#include "ShaderGLImpl.hpp"
#include "Texture1D_GL.hpp"
#include "Texture1DArray_GL.hpp"
#include "Texture2D_GL.hpp"
#include "Texture2DArray_GL.hpp"
#include "Texture3D_GL.hpp"
#include "SamplerGLImpl.hpp"
#include "BufferViewGLImpl.hpp"
#include "PipelineStateGLImpl.hpp"
#include "FenceGLImpl.hpp"
#include "ShaderResourceBindingGLImpl.hpp"
#include "GLTypeConversions.hpp"
#include "VAOCache.hpp"
#include "GraphicsAccessories.hpp"
namespace Diligent
{
DeviceContextGLImpl::DeviceContextGLImpl(IReferenceCounters* pRefCounters, class RenderDeviceGLImpl* pDeviceGL, bool bIsDeferred) :
// clang-format off
TDeviceContextBase
{
pRefCounters,
pDeviceGL,
bIsDeferred
},
m_ContextState{pDeviceGL},
m_DefaultFBO {false }
// clang-format on
{
m_BoundWritableTextures.reserve(16);
m_BoundWritableBuffers.reserve(16);
}
IMPLEMENT_QUERY_INTERFACE(DeviceContextGLImpl, IID_DeviceContextGL, TDeviceContextBase)
void DeviceContextGLImpl::SetPipelineState(IPipelineState* pPipelineState)
{
VERIFY_EXPR(pPipelineState != nullptr);
auto* pPipelineStateGLImpl = ValidatedCast<PipelineStateGLImpl>(pPipelineState);
if (PipelineStateGLImpl::IsSameObject(m_pPipelineState, pPipelineStateGLImpl))
return;
TDeviceContextBase::SetPipelineState(pPipelineStateGLImpl, 0 /*Dummy*/);
const auto& Desc = pPipelineStateGLImpl->GetDesc();
if (Desc.PipelineType == PIPELINE_TYPE_COMPUTE)
{
}
else if (Desc.PipelineType == PIPELINE_TYPE_GRAPHICS)
{
const auto& GraphicsPipeline = pPipelineStateGLImpl->GetGraphicsPipelineDesc();
// Set rasterizer state
{
const auto& RasterizerDesc = GraphicsPipeline.RasterizerDesc;
m_ContextState.SetFillMode(RasterizerDesc.FillMode);
m_ContextState.SetCullMode(RasterizerDesc.CullMode);
m_ContextState.SetFrontFace(RasterizerDesc.FrontCounterClockwise);
m_ContextState.SetDepthBias(static_cast<Float32>(RasterizerDesc.DepthBias), RasterizerDesc.SlopeScaledDepthBias);
if (RasterizerDesc.DepthBiasClamp != 0)
LOG_WARNING_MESSAGE("Depth bias clamp is not supported on OpenGL");
// Enabling depth clamping in GL is the same as disabling clipping in Direct3D.
// https://docs.microsoft.com/en-us/windows/win32/api/d3d11/ns-d3d11-d3d11_rasterizer_desc
// https://www.khronos.org/opengl/wiki/GLAPI/glEnable
m_ContextState.SetDepthClamp(!RasterizerDesc.DepthClipEnable);
m_ContextState.EnableScissorTest(RasterizerDesc.ScissorEnable);
if (RasterizerDesc.AntialiasedLineEnable)
LOG_WARNING_MESSAGE("Line antialiasing is not supported on OpenGL");
}
// Set blend state
{
const auto& BSDsc = GraphicsPipeline.BlendDesc;
m_ContextState.SetBlendState(BSDsc, GraphicsPipeline.SampleMask);
}
// Set depth-stencil state
{
const auto& DepthStencilDesc = GraphicsPipeline.DepthStencilDesc;
m_ContextState.EnableDepthTest(DepthStencilDesc.DepthEnable);
m_ContextState.EnableDepthWrites(DepthStencilDesc.DepthWriteEnable);
m_ContextState.SetDepthFunc(DepthStencilDesc.DepthFunc);
m_ContextState.EnableStencilTest(DepthStencilDesc.StencilEnable);
m_ContextState.SetStencilWriteMask(DepthStencilDesc.StencilWriteMask);
{
const auto& FrontFace = DepthStencilDesc.FrontFace;
m_ContextState.SetStencilFunc(GL_FRONT, FrontFace.StencilFunc, m_StencilRef, DepthStencilDesc.StencilReadMask);
m_ContextState.SetStencilOp(GL_FRONT, FrontFace.StencilFailOp, FrontFace.StencilDepthFailOp, FrontFace.StencilPassOp);
}
{
const auto& BackFace = DepthStencilDesc.BackFace;
m_ContextState.SetStencilFunc(GL_BACK, BackFace.StencilFunc, m_StencilRef, DepthStencilDesc.StencilReadMask);
m_ContextState.SetStencilOp(GL_BACK, BackFace.StencilFailOp, BackFace.StencilDepthFailOp, BackFace.StencilPassOp);
}
}
m_ContextState.InvalidateVAO();
}
else
{
LOG_ERROR_MESSAGE(GetPipelineTypeString(Desc.PipelineType), " pipeline '", Desc.Name, "' is not supported in OpenGL");
return;
}
// Note that the program may change if a shader is created after the call
// (ShaderResourcesGL needs to bind a program to load uniforms), but before
// the draw command.
m_pPipelineState->CommitProgram(m_ContextState);
const auto SignCount = m_pPipelineState->GetResourceSignatureCount();
m_BindInfo.ActiveSRBMask = 0;
for (Uint32 s = 0; s < SignCount; ++s)
{
const auto* pLayoutSign = m_pPipelineState->GetResourceSignature(s);
if (pLayoutSign == nullptr || pLayoutSign->GetTotalResourceCount() == 0)
continue;
m_BindInfo.ActiveSRBMask |= (1u << s);
}
#ifdef DILIGENT_DEVELOPMENT
// Unbind incompatible SRB and SRB with a higher binding index.
// This is the same behavior that used in Vulkan backend.
for (auto sign = DvpGetCompatibleSignatureCount(m_BindInfo.SRBs.data()); sign < SignCount; ++sign)
{
m_BindInfo.SRBs[sign] = nullptr;
m_BindInfo.ClearStaleSRBBit(sign);
}
m_BindInfo.CommittedResourcesValidated = false;
#endif
}
void DeviceContextGLImpl::TransitionShaderResources(IPipelineState* pPipelineState, IShaderResourceBinding* pShaderResourceBinding)
{
if (m_pActiveRenderPass)
{
LOG_ERROR_MESSAGE("State transitions are not allowed inside a render pass.");
return;
}
}
void DeviceContextGLImpl::CommitShaderResources(IShaderResourceBinding* pShaderResourceBinding, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)
{
if (!DeviceContextBase::CommitShaderResources(pShaderResourceBinding, StateTransitionMode, 0))
return;
auto* pShaderResBindingGL = ValidatedCast<ShaderResourceBindingGLImpl>(pShaderResourceBinding);
const auto SRBIndex = pShaderResBindingGL->GetBindingIndex();
m_BindInfo.SRBs[SRBIndex] = pShaderResBindingGL;
m_BindInfo.SetStaleSRBBit(SRBIndex);
#ifdef DILIGENT_DEVELOPMENT
m_BindInfo.CommittedResourcesValidated = false;
#endif
}
void DeviceContextGLImpl::SetStencilRef(Uint32 StencilRef)
{
if (TDeviceContextBase::SetStencilRef(StencilRef, 0))
{
m_ContextState.SetStencilRef(GL_FRONT, StencilRef);
m_ContextState.SetStencilRef(GL_BACK, StencilRef);
}
}
void DeviceContextGLImpl::SetBlendFactors(const float* pBlendFactors)
{
if (TDeviceContextBase::SetBlendFactors(pBlendFactors, 0))
{
m_ContextState.SetBlendFactors(m_BlendFactors);
}
}
void DeviceContextGLImpl::SetVertexBuffers(Uint32 StartSlot,
Uint32 NumBuffersSet,
IBuffer** ppBuffers,
Uint32* pOffsets,
RESOURCE_STATE_TRANSITION_MODE StateTransitionMode,
SET_VERTEX_BUFFERS_FLAGS Flags)
{
TDeviceContextBase::SetVertexBuffers(StartSlot, NumBuffersSet, ppBuffers, pOffsets, StateTransitionMode, Flags);
m_ContextState.InvalidateVAO();
}
void DeviceContextGLImpl::InvalidateState()
{
TDeviceContextBase::InvalidateState();
m_ContextState.Invalidate();
m_BoundWritableTextures.clear();
m_BoundWritableBuffers.clear();
m_IsDefaultFBOBound = false;
}
void DeviceContextGLImpl::SetIndexBuffer(IBuffer* pIndexBuffer, Uint32 ByteOffset, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)
{
TDeviceContextBase::SetIndexBuffer(pIndexBuffer, ByteOffset, StateTransitionMode);
m_ContextState.InvalidateVAO();
}
void DeviceContextGLImpl::SetViewports(Uint32 NumViewports, const Viewport* pViewports, Uint32 RTWidth, Uint32 RTHeight)
{
TDeviceContextBase::SetViewports(NumViewports, pViewports, RTWidth, RTHeight);
VERIFY(NumViewports == m_NumViewports, "Unexpected number of viewports");
if (NumViewports == 1)
{
const auto& vp = m_Viewports[0];
// Note that OpenGL and DirectX use different origin of
// the viewport in window coordinates:
//
// DirectX (0,0)
// \ ____________
// | |
// | |
// | |
// | |
// |____________|
// /
// OpenGL (0,0)
//
float BottomLeftY = static_cast<float>(RTHeight) - (vp.TopLeftY + vp.Height);
float BottomLeftX = vp.TopLeftX;
Int32 x = static_cast<int>(BottomLeftX);
Int32 y = static_cast<int>(BottomLeftY);
Int32 w = static_cast<int>(vp.Width);
Int32 h = static_cast<int>(vp.Height);
if (static_cast<float>(x) == BottomLeftX &&
static_cast<float>(y) == BottomLeftY &&
static_cast<float>(w) == vp.Width &&
static_cast<float>(h) == vp.Height)
{
// GL_INVALID_VALUE is generated if either width or height is negative
// https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glViewport.xml
glViewport(x, y, w, h);
}
else
{
// GL_INVALID_VALUE is generated if either width or height is negative
// https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glViewportIndexed.xhtml
glViewportIndexedf(0, BottomLeftX, BottomLeftY, vp.Width, vp.Height);
}
DEV_CHECK_GL_ERROR("Failed to set viewport");
glDepthRangef(vp.MinDepth, vp.MaxDepth);
DEV_CHECK_GL_ERROR("Failed to set depth range");
}
else
{
for (Uint32 i = 0; i < NumViewports; ++i)
{
const auto& vp = m_Viewports[i];
float BottomLeftY = static_cast<float>(RTHeight) - (vp.TopLeftY + vp.Height);
float BottomLeftX = vp.TopLeftX;
glViewportIndexedf(i, BottomLeftX, BottomLeftY, vp.Width, vp.Height);
DEV_CHECK_GL_ERROR("Failed to set viewport #", i);
glDepthRangef(vp.MinDepth, vp.MaxDepth);
DEV_CHECK_GL_ERROR("Failed to set depth range for viewport #", i);
}
}
}
void DeviceContextGLImpl::SetScissorRects(Uint32 NumRects, const Rect* pRects, Uint32 RTWidth, Uint32 RTHeight)
{
TDeviceContextBase::SetScissorRects(NumRects, pRects, RTWidth, RTHeight);
VERIFY(NumRects == m_NumScissorRects, "Unexpected number of scissor rects");
if (NumRects == 1)
{
const auto& Rect = m_ScissorRects[0];
// Note that OpenGL and DirectX use different origin
// of the viewport in window coordinates:
//
// DirectX (0,0)
// \ ____________
// | |
// | |
// | |
// | |
// |____________|
// /
// OpenGL (0,0)
//
auto glBottom = RTHeight - Rect.bottom;
auto width = Rect.right - Rect.left;
auto height = Rect.bottom - Rect.top;
glScissor(Rect.left, glBottom, width, height);
DEV_CHECK_GL_ERROR("Failed to set scissor rect");
}
else
{
for (Uint32 sr = 0; sr < NumRects; ++sr)
{
const auto& Rect = m_ScissorRects[sr];
auto glBottom = RTHeight - Rect.bottom;
auto width = Rect.right - Rect.left;
auto height = Rect.bottom - Rect.top;
glScissorIndexed(sr, Rect.left, glBottom, width, height);
DEV_CHECK_GL_ERROR("Failed to set scissor rect #", sr);
}
}
}
void DeviceContextGLImpl::SetSwapChain(ISwapChainGL* pSwapChain)
{
m_pSwapChain = pSwapChain;
}
void DeviceContextGLImpl::CommitRenderTargets()
{
VERIFY(m_pActiveRenderPass == nullptr, "This method must not be called inside render pass");
if (!m_IsDefaultFBOBound && m_NumBoundRenderTargets == 0 && !m_pBoundDepthStencil)
return;
if (m_IsDefaultFBOBound)
{
GLuint DefaultFBOHandle = m_pSwapChain->GetDefaultFBO();
if (m_DefaultFBO != DefaultFBOHandle)
{
m_DefaultFBO = GLObjectWrappers::GLFrameBufferObj{true, GLObjectWrappers::GLFBOCreateReleaseHelper(DefaultFBOHandle)};
}
m_ContextState.BindFBO(m_DefaultFBO);
}
else
{
VERIFY(m_NumBoundRenderTargets != 0 || m_pBoundDepthStencil, "At least one render target or a depth stencil is expected");
Uint32 NumRenderTargets = m_NumBoundRenderTargets;
VERIFY(NumRenderTargets < MAX_RENDER_TARGETS, "Too many render targets (", NumRenderTargets, ") are being set");
NumRenderTargets = std::min(NumRenderTargets, MAX_RENDER_TARGETS);
const auto& CtxCaps = m_ContextState.GetContextCaps();
VERIFY(NumRenderTargets < static_cast<Uint32>(CtxCaps.m_iMaxDrawBuffers), "This device only supports ", CtxCaps.m_iMaxDrawBuffers, " draw buffers, but ", NumRenderTargets, " are being set");
NumRenderTargets = std::min(NumRenderTargets, static_cast<Uint32>(CtxCaps.m_iMaxDrawBuffers));
TextureViewGLImpl* pBoundRTVs[MAX_RENDER_TARGETS] = {};
for (Uint32 rt = 0; rt < NumRenderTargets; ++rt)
{
pBoundRTVs[rt] = m_pBoundRenderTargets[rt];
DEV_CHECK_ERR(!pBoundRTVs[rt] || pBoundRTVs[rt]->GetTexture<TextureBaseGL>()->GetGLHandle(),
"Color buffer of the default framebuffer can only be bound with the default framebuffer's depth buffer "
"and cannot be combined with any other render target or depth buffer in OpenGL backend.");
}
DEV_CHECK_ERR(!m_pBoundDepthStencil || m_pBoundDepthStencil->GetTexture<TextureBaseGL>()->GetGLHandle(),
"Depth buffer of the default framebuffer can only be bound with the default framebuffer's color buffer "
"and cannot be combined with any other render target in OpenGL backend.");
auto CurrentNativeGLContext = m_ContextState.GetCurrentGLContext();
auto& FBOCache = m_pDevice->GetFBOCache(CurrentNativeGLContext);
const auto& FBO = FBOCache.GetFBO(NumRenderTargets, pBoundRTVs, m_pBoundDepthStencil, m_ContextState);
// Even though the write mask only applies to writes to a framebuffer, the mask state is NOT
// Framebuffer state. So it is NOT part of a Framebuffer Object or the Default Framebuffer.
// Binding a new framebuffer will NOT affect the mask.
m_ContextState.BindFBO(FBO);
}
// Set the viewport to match the render target size
SetViewports(1, nullptr, 0, 0);
}
void DeviceContextGLImpl::SetRenderTargets(Uint32 NumRenderTargets,
ITextureView* ppRenderTargets[],
ITextureView* pDepthStencil,
RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)
{
#ifdef DILIGENT_DEVELOPMENT
if (m_pActiveRenderPass != nullptr)
{
LOG_ERROR_MESSAGE("Calling SetRenderTargets inside active render pass is invalid. End the render pass first");
return;
}
#endif
if (TDeviceContextBase::SetRenderTargets(NumRenderTargets, ppRenderTargets, pDepthStencil))
{
if (m_NumBoundRenderTargets == 1 && m_pBoundRenderTargets[0] && m_pBoundRenderTargets[0]->GetTexture<TextureBaseGL>()->GetGLHandle() == 0)
{
DEV_CHECK_ERR(!m_pBoundDepthStencil || m_pBoundDepthStencil->GetTexture<TextureBaseGL>()->GetGLHandle() == 0,
"Attempting to bind texture '", m_pBoundDepthStencil->GetTexture()->GetDesc().Name,
"' as depth buffer with the default framebuffer's color buffer: color buffer of the default framebuffer "
"can only be bound with the default framebuffer's depth buffer and cannot be combined with any other depth buffer in OpenGL backend.");
m_IsDefaultFBOBound = true;
}
else if (m_NumBoundRenderTargets == 0 && m_pBoundDepthStencil && m_pBoundDepthStencil->GetTexture<TextureBaseGL>()->GetGLHandle() == 0)
{
m_IsDefaultFBOBound = true;
}
else
{
m_IsDefaultFBOBound = false;
}
CommitRenderTargets();
}
}
void DeviceContextGLImpl::ResetRenderTargets()
{
TDeviceContextBase::ResetRenderTargets();
m_IsDefaultFBOBound = false;
m_ContextState.InvalidateFBO();
}
void DeviceContextGLImpl::BeginSubpass()
{
VERIFY_EXPR(m_pActiveRenderPass);
VERIFY_EXPR(m_pBoundFramebuffer);
const auto& RPDesc = m_pActiveRenderPass->GetDesc();
VERIFY_EXPR(m_SubpassIndex < RPDesc.SubpassCount);
const auto& SubpassDesc = RPDesc.pSubpasses[m_SubpassIndex];
const auto& FBDesc = m_pBoundFramebuffer->GetDesc();
const auto& RenderTargetFBO = m_pBoundFramebuffer->GetSubpassFramebuffer(m_SubpassIndex).RenderTarget;
if (RenderTargetFBO != 0)
{
m_ContextState.BindFBO(RenderTargetFBO);
}
else
{
GLuint DefaultFBOHandle = m_pSwapChain->GetDefaultFBO();
if (m_DefaultFBO != DefaultFBOHandle)
{
m_DefaultFBO = GLObjectWrappers::GLFrameBufferObj{true, GLObjectWrappers::GLFBOCreateReleaseHelper(DefaultFBOHandle)};
}
m_ContextState.BindFBO(m_DefaultFBO);
}
for (Uint32 rt = 0; rt < SubpassDesc.RenderTargetAttachmentCount; ++rt)
{
const auto& RTAttachmentRef = SubpassDesc.pRenderTargetAttachments[rt];
if (RTAttachmentRef.AttachmentIndex != ATTACHMENT_UNUSED)
{
auto* const pRTV = ValidatedCast<TextureViewGLImpl>(FBDesc.ppAttachments[RTAttachmentRef.AttachmentIndex]);
if (pRTV == nullptr)
continue;
auto* const pColorTexGL = pRTV->GetTexture<TextureBaseGL>();
pColorTexGL->TextureMemoryBarrier(
MEMORY_BARRIER_FRAMEBUFFER, // Reads and writes via framebuffer object attachments after the
// barrier will reflect data written by shaders prior to the barrier.
// Additionally, framebuffer writes issued after the barrier will wait
// on the completion of all shader writes issued prior to the barrier.
m_ContextState);
const auto& AttachmentDesc = RPDesc.pAttachments[RTAttachmentRef.AttachmentIndex];
auto FirstLastUse = m_pActiveRenderPass->GetAttachmentFirstLastUse(RTAttachmentRef.AttachmentIndex);
if (FirstLastUse.first == m_SubpassIndex && AttachmentDesc.LoadOp == ATTACHMENT_LOAD_OP_CLEAR)
{
ClearRenderTarget(pRTV, m_AttachmentClearValues[RTAttachmentRef.AttachmentIndex].Color, RESOURCE_STATE_TRANSITION_MODE_NONE);
}
}
}
if (SubpassDesc.pDepthStencilAttachment != nullptr)
{
const auto DepthAttachmentIndex = SubpassDesc.pDepthStencilAttachment->AttachmentIndex;
if (DepthAttachmentIndex != ATTACHMENT_UNUSED)
{
auto* const pDSV = ValidatedCast<TextureViewGLImpl>(FBDesc.ppAttachments[DepthAttachmentIndex]);
if (pDSV != nullptr)
{
auto* pDepthTexGL = pDSV->GetTexture<TextureBaseGL>();
pDepthTexGL->TextureMemoryBarrier(MEMORY_BARRIER_FRAMEBUFFER, m_ContextState);
const auto& AttachmentDesc = RPDesc.pAttachments[DepthAttachmentIndex];
auto FirstLastUse = m_pActiveRenderPass->GetAttachmentFirstLastUse(DepthAttachmentIndex);
if (FirstLastUse.first == m_SubpassIndex && AttachmentDesc.LoadOp == ATTACHMENT_LOAD_OP_CLEAR)
{
const auto& ClearVal = m_AttachmentClearValues[DepthAttachmentIndex].DepthStencil;
ClearDepthStencil(pDSV, CLEAR_DEPTH_FLAG | CLEAR_STENCIL_FLAG, ClearVal.Depth, ClearVal.Stencil, RESOURCE_STATE_TRANSITION_MODE_NONE);
}
}
}
}
}
void DeviceContextGLImpl::EndSubpass()
{
VERIFY_EXPR(m_pActiveRenderPass);
VERIFY_EXPR(m_pBoundFramebuffer);
const auto& RPDesc = m_pActiveRenderPass->GetDesc();
VERIFY_EXPR(m_SubpassIndex < RPDesc.SubpassCount);
const auto& SubpassDesc = RPDesc.pSubpasses[m_SubpassIndex];
const auto& SubpassFBOs = m_pBoundFramebuffer->GetSubpassFramebuffer(m_SubpassIndex);
#ifdef DILIGENT_DEBUG
{
GLint glCurrReadFB = 0;
glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &glCurrReadFB);
CHECK_GL_ERROR("Failed to get current read framebuffer");
GLuint glExpectedReadFB = SubpassFBOs.RenderTarget != 0 ? static_cast<GLuint>(SubpassFBOs.RenderTarget) : m_pSwapChain->GetDefaultFBO();
VERIFY(static_cast<GLuint>(glCurrReadFB) == glExpectedReadFB, "Unexpected read framebuffer");
}
#endif
if (SubpassDesc.pResolveAttachments != nullptr)
{
GLuint ResolveDstFBO = SubpassFBOs.Resolve;
if (ResolveDstFBO == 0)
{
ResolveDstFBO = m_pSwapChain.RawPtr<ISwapChainGL>()->GetDefaultFBO();
}
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, ResolveDstFBO);
DEV_CHECK_GL_ERROR("Failed to bind resolve destination FBO as draw framebuffer");
const auto& FBODesc = m_pBoundFramebuffer->GetDesc();
glBlitFramebuffer(0, 0, static_cast<GLint>(FBODesc.Width), static_cast<GLint>(FBODesc.Height),
0, 0, static_cast<GLint>(FBODesc.Width), static_cast<GLint>(FBODesc.Height),
GL_COLOR_BUFFER_BIT,
GL_NEAREST // Filter is ignored
);
DEV_CHECK_GL_ERROR("glBlitFramebuffer() failed when resolving multi-sampled attachments");
}
if (glInvalidateFramebuffer != nullptr)
{
// It is crucially important to invalidate the framebuffer while it is bound
// https://community.arm.com/developer/tools-software/graphics/b/blog/posts/mali-performance-2-how-to-correctly-handle-framebuffers
GLsizei InvalidateAttachmentsCount = 0;
std::array<GLenum, MAX_RENDER_TARGETS + 1> InvalidateAttachments;
for (Uint32 rt = 0; rt < SubpassDesc.RenderTargetAttachmentCount; ++rt)
{
const auto RTAttachmentIdx = SubpassDesc.pRenderTargetAttachments[rt].AttachmentIndex;
if (RTAttachmentIdx != ATTACHMENT_UNUSED)
{
auto AttachmentLastUse = m_pActiveRenderPass->GetAttachmentFirstLastUse(RTAttachmentIdx).second;
if (AttachmentLastUse == m_SubpassIndex && RPDesc.pAttachments[RTAttachmentIdx].StoreOp == ATTACHMENT_STORE_OP_DISCARD)
{
if (SubpassFBOs.RenderTarget == 0)
{
VERIFY(rt == 0, "Default framebuffer can only have single color attachment");
InvalidateAttachments[InvalidateAttachmentsCount++] = GL_COLOR;
}
else
{
InvalidateAttachments[InvalidateAttachmentsCount++] = GL_COLOR_ATTACHMENT0 + rt;
}
}
}
}
if (SubpassDesc.pDepthStencilAttachment != nullptr)
{
const auto DSAttachmentIdx = SubpassDesc.pDepthStencilAttachment->AttachmentIndex;
if (DSAttachmentIdx != ATTACHMENT_UNUSED)
{
auto AttachmentLastUse = m_pActiveRenderPass->GetAttachmentFirstLastUse(DSAttachmentIdx).second;
if (AttachmentLastUse == m_SubpassIndex && RPDesc.pAttachments[DSAttachmentIdx].StoreOp == ATTACHMENT_STORE_OP_DISCARD)
{
const auto& FmtAttribs = GetTextureFormatAttribs(RPDesc.pAttachments[DSAttachmentIdx].Format);
VERIFY_EXPR(FmtAttribs.ComponentType == COMPONENT_TYPE_DEPTH || FmtAttribs.ComponentType == COMPONENT_TYPE_DEPTH_STENCIL);
if (SubpassFBOs.RenderTarget == 0)
{
InvalidateAttachments[InvalidateAttachmentsCount++] = GL_DEPTH;
if (FmtAttribs.ComponentType == COMPONENT_TYPE_DEPTH_STENCIL)
InvalidateAttachments[InvalidateAttachmentsCount++] = GL_STENCIL;
}
else
{
InvalidateAttachments[InvalidateAttachmentsCount++] = FmtAttribs.ComponentType == COMPONENT_TYPE_DEPTH ? GL_DEPTH_ATTACHMENT : GL_DEPTH_STENCIL_ATTACHMENT;
}
}
}
}
if (InvalidateAttachmentsCount > 0)
{
glInvalidateFramebuffer(GL_READ_FRAMEBUFFER, InvalidateAttachmentsCount, InvalidateAttachments.data());
DEV_CHECK_GL_ERROR("glInvalidateFramebuffer() failed");
}
}
// TODO: invalidate input attachments using glInvalidateTexImage
m_ContextState.InvalidateFBO();
}
void DeviceContextGLImpl::BeginRenderPass(const BeginRenderPassAttribs& Attribs)
{
TDeviceContextBase::BeginRenderPass(Attribs);
m_AttachmentClearValues.resize(Attribs.ClearValueCount);
for (Uint32 i = 0; i < Attribs.ClearValueCount; ++i)
m_AttachmentClearValues[i] = Attribs.pClearValues[i];
VERIFY_EXPR(m_pBoundFramebuffer);
SetViewports(1, nullptr, 0, 0);
BeginSubpass();
}
void DeviceContextGLImpl::NextSubpass()
{
EndSubpass();
TDeviceContextBase::NextSubpass();
BeginSubpass();
m_AttachmentClearValues.clear();
}
void DeviceContextGLImpl::EndRenderPass()
{
EndSubpass();
TDeviceContextBase::EndRenderPass();
m_ContextState.InvalidateFBO();
}
#ifdef DILIGENT_DEVELOPMENT
void DeviceContextGLImpl::DvpValidateCommittedShaderResources()
{
if (m_BindInfo.CommittedResourcesValidated)
return;
m_pPipelineState->DvpVerifySRBResources(m_BindInfo.SRBs.data(), m_BindInfo.BaseBindings.data(), static_cast<Uint32>(m_BindInfo.SRBs.size()));
m_BindInfo.CommittedResourcesValidated = true;
}
#endif
void DeviceContextGLImpl::BindProgramResources()
{
//if (m_CommitedResourcesTentativeBarriers != 0)
// LOG_INFO_MESSAGE("Not all tentative resource barriers have been executed since the last call to CommitShaderResources(). Did you forget to call Draw()/DispatchCompute() ?");
if ((m_BindInfo.StaleSRBMask & m_BindInfo.ActiveSRBMask) == 0)
return;
VERIFY_EXPR(m_BoundWritableTextures.empty());
VERIFY_EXPR(m_BoundWritableBuffers.empty());
m_CommitedResourcesTentativeBarriers = MEMORY_BARRIER_NONE;
TBindings Bindings = {};
auto ActiveSRBMask = Uint32{m_BindInfo.ActiveSRBMask};
while (ActiveSRBMask != 0)
{
Uint32 sign = PlatformMisc::GetLSB(ActiveSRBMask);
VERIFY_EXPR(sign < m_pPipelineState->GetResourceSignatureCount());
Uint32 SignBit = (1u << sign);
ActiveSRBMask &= ~SignBit;
const auto* pSRB = m_BindInfo.SRBs[sign];
DEV_CHECK_ERR(pSRB != nullptr, "No SRB is bound for index ", sign);
if (m_BindInfo.StaleSRBMask & SignBit)
{
auto& ResoureCache = pSRB->GetResourceCache();
ResoureCache.BindResources(GetContextState(), Bindings, m_BoundWritableTextures, m_BoundWritableBuffers);
#ifdef DILIGENT_DEVELOPMENT
m_BindInfo.BaseBindings[sign] = Bindings;
#endif
}
pSRB->GetSignature()->ShiftBindings(Bindings);
}
m_BindInfo.StaleSRBMask &= ~m_BindInfo.ActiveSRBMask;
#if GL_ARB_shader_image_load_store
// Go through the list of textures bound as AUVs and set the required memory barriers
for (auto* pWritableTex : m_BoundWritableTextures)
{
constexpr MEMORY_BARRIER TextureMemBarriers = MEMORY_BARRIER_ALL_TEXTURE_BARRIERS;
m_CommitedResourcesTentativeBarriers |= TextureMemBarriers;
// Set new required barriers for the time when texture is used next time
pWritableTex->SetPendingMemoryBarriers(TextureMemBarriers);
}
m_BoundWritableTextures.clear();
for (auto* pWritableBuff : m_BoundWritableBuffers)
{
constexpr MEMORY_BARRIER BufferMemoryBarriers = MEMORY_BARRIER_ALL_BUFFER_BARRIERS;
m_CommitedResourcesTentativeBarriers |= BufferMemoryBarriers;
// Set new required barriers for the time when buffer is used next time
pWritableBuff->SetPendingMemoryBarriers(BufferMemoryBarriers);
}
m_BoundWritableBuffers.clear();
#endif
}
void DeviceContextGLImpl::PrepareForDraw(DRAW_FLAGS Flags, bool IsIndexed, GLenum& GlTopology)
{
#ifdef DILIGENT_DEVELOPMENT
if ((Flags & DRAW_FLAG_VERIFY_RENDER_TARGETS) != 0)
DvpVerifyRenderTargets();
#endif
// The program might have changed since the last SetPipelineState call if a shader was
// created after the call (ShaderResourcesGL needs to bind a program to load uniforms).
m_pPipelineState->CommitProgram(m_ContextState);
BindProgramResources();
auto CurrNativeGLContext = m_pDevice->m_GLContext.GetCurrentNativeGLContext();
const auto& PipelineDesc = m_pPipelineState->GetGraphicsPipelineDesc();
if (!m_ContextState.IsValidVAOBound())
{
auto& VAOCache = m_pDevice->GetVAOCache(CurrNativeGLContext);
IBuffer* pIndexBuffer = IsIndexed ? m_pIndexBuffer.RawPtr() : nullptr;
if (PipelineDesc.InputLayout.NumElements > 0 || pIndexBuffer != nullptr)
{
const auto& VAO = VAOCache.GetVAO(m_pPipelineState, pIndexBuffer, m_VertexStreams, m_NumVertexStreams, m_ContextState);
m_ContextState.BindVAO(VAO);
}
else
{
// Draw command will fail if no VAO is bound. If no vertex description is set
// (which is the case if, for instance, the command only inputs VertexID),
// use empty VAO
const auto& VAO = VAOCache.GetEmptyVAO();
m_ContextState.BindVAO(VAO);
}
}
auto Topology = PipelineDesc.PrimitiveTopology;
if (Topology >= PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST)
{
#if GL_ARB_tessellation_shader
GlTopology = GL_PATCHES;
auto NumVertices = static_cast<Int32>(Topology - PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST + 1);
m_ContextState.SetNumPatchVertices(NumVertices);
#else
UNSUPPORTED("Tessellation is not supported");
#endif
}
else
{
GlTopology = PrimitiveTopologyToGLTopology(Topology);
}
#ifdef DILIGENT_DEVELOPMENT
DvpValidateCommittedShaderResources();
#endif
}
void DeviceContextGLImpl::PrepareForIndexedDraw(VALUE_TYPE IndexType, Uint32 FirstIndexLocation, GLenum& GLIndexType, Uint32& FirstIndexByteOffset)
{
GLIndexType = TypeToGLType(IndexType);
VERIFY(GLIndexType == GL_UNSIGNED_BYTE || GLIndexType == GL_UNSIGNED_SHORT || GLIndexType == GL_UNSIGNED_INT,
"Unsupported index type");
VERIFY(m_pIndexBuffer, "Index Buffer is not bound to the pipeline");
FirstIndexByteOffset = static_cast<Uint32>(GetValueSize(IndexType)) * FirstIndexLocation + m_IndexDataStartOffset;
}
void DeviceContextGLImpl::PostDraw()
{
// IMPORTANT: new pending memory barriers in the context must be set
// after all previous barriers have been executed.
// m_CommitedResourcesTentativeBarriers contains memory barriers that will be required
// AFTER the actual draw/dispatch command is executed.
m_ContextState.SetPendingMemoryBarriers(m_CommitedResourcesTentativeBarriers);
m_CommitedResourcesTentativeBarriers = MEMORY_BARRIER_NONE;
}
void DeviceContextGLImpl::Draw(const DrawAttribs& Attribs)
{
if (!DvpVerifyDrawArguments(Attribs))
return;
GLenum GlTopology;
PrepareForDraw(Attribs.Flags, false, GlTopology);
if (Attribs.NumInstances > 1 || Attribs.FirstInstanceLocation != 0)
{
if (Attribs.FirstInstanceLocation != 0)
glDrawArraysInstancedBaseInstance(GlTopology, Attribs.StartVertexLocation, Attribs.NumVertices, Attribs.NumInstances, Attribs.FirstInstanceLocation);
else
glDrawArraysInstanced(GlTopology, Attribs.StartVertexLocation, Attribs.NumVertices, Attribs.NumInstances);
}
else
{
glDrawArrays(GlTopology, Attribs.StartVertexLocation, Attribs.NumVertices);
}
DEV_CHECK_GL_ERROR("OpenGL draw command failed");
PostDraw();
}
void DeviceContextGLImpl::DrawIndexed(const DrawIndexedAttribs& Attribs)
{
if (!DvpVerifyDrawIndexedArguments(Attribs))
return;
GLenum GlTopology;
PrepareForDraw(Attribs.Flags, true, GlTopology);
GLenum GLIndexType;
Uint32 FirstIndexByteOffset;
PrepareForIndexedDraw(Attribs.IndexType, Attribs.FirstIndexLocation, GLIndexType, FirstIndexByteOffset);
// NOTE: Base Vertex and Base Instance versions are not supported even in OpenGL ES 3.1
// This functionality can be emulated by adjusting stream offsets. This, however may cause
// errors in case instance data is read from the same stream as vertex data. Thus handling
// such cases is left to the application
if (Attribs.NumInstances > 1 || Attribs.FirstInstanceLocation != 0)
{
if (Attribs.BaseVertex > 0)
{
if (Attribs.FirstInstanceLocation != 0)
glDrawElementsInstancedBaseVertexBaseInstance(GlTopology, Attribs.NumIndices, GLIndexType, reinterpret_cast<GLvoid*>(static_cast<size_t>(FirstIndexByteOffset)), Attribs.NumInstances, Attribs.BaseVertex, Attribs.FirstInstanceLocation);
else
glDrawElementsInstancedBaseVertex(GlTopology, Attribs.NumIndices, GLIndexType, reinterpret_cast<GLvoid*>(static_cast<size_t>(FirstIndexByteOffset)), Attribs.NumInstances, Attribs.BaseVertex);
}
else
{
if (Attribs.FirstInstanceLocation != 0)
glDrawElementsInstancedBaseInstance(GlTopology, Attribs.NumIndices, GLIndexType, reinterpret_cast<GLvoid*>(static_cast<size_t>(FirstIndexByteOffset)), Attribs.NumInstances, Attribs.FirstInstanceLocation);
else
glDrawElementsInstanced(GlTopology, Attribs.NumIndices, GLIndexType, reinterpret_cast<GLvoid*>(static_cast<size_t>(FirstIndexByteOffset)), Attribs.NumInstances);
}
}
else
{
if (Attribs.BaseVertex > 0)
glDrawElementsBaseVertex(GlTopology, Attribs.NumIndices, GLIndexType, reinterpret_cast<GLvoid*>(static_cast<size_t>(FirstIndexByteOffset)), Attribs.BaseVertex);
else
glDrawElements(GlTopology, Attribs.NumIndices, GLIndexType, reinterpret_cast<GLvoid*>(static_cast<size_t>(FirstIndexByteOffset)));
}
DEV_CHECK_GL_ERROR("OpenGL draw command failed");
PostDraw();
}
void DeviceContextGLImpl::PrepareForIndirectDraw(IBuffer* pAttribsBuffer)
{
#if GL_ARB_draw_indirect
auto* pIndirectDrawAttribsGL = ValidatedCast<BufferGLImpl>(pAttribsBuffer);
// The indirect rendering functions take their data from the buffer currently bound to the
// GL_DRAW_INDIRECT_BUFFER binding. Thus, any of indirect draw functions will fail if no buffer is
// bound to that binding.
pIndirectDrawAttribsGL->BufferMemoryBarrier(
MEMORY_BARRIER_INDIRECT_BUFFER, // Command data sourced from buffer objects by
// Draw*Indirect and DispatchComputeIndirect commands after the barrier
// will reflect data written by shaders prior to the barrier.The buffer
// objects affected by this bit are derived from the DRAW_INDIRECT_BUFFER
// and DISPATCH_INDIRECT_BUFFER bindings.
m_ContextState);
constexpr bool ResetVAO = false; // GL_DRAW_INDIRECT_BUFFER does not affect VAO
m_ContextState.BindBuffer(GL_DRAW_INDIRECT_BUFFER, pIndirectDrawAttribsGL->m_GlBuffer, ResetVAO);
#endif
}
void DeviceContextGLImpl::DrawIndirect(const DrawIndirectAttribs& Attribs, IBuffer* pAttribsBuffer)
{
if (!DvpVerifyDrawIndirectArguments(Attribs, pAttribsBuffer))
return;
#if GL_ARB_draw_indirect
GLenum GlTopology;
PrepareForDraw(Attribs.Flags, true, GlTopology);
// http://www.opengl.org/wiki/Vertex_Rendering
PrepareForIndirectDraw(pAttribsBuffer);
//typedef struct {
// GLuint count;
// GLuint instanceCount;
// GLuint first;
// GLuint baseInstance;
//} DrawArraysIndirectCommand;
glDrawArraysIndirect(GlTopology, reinterpret_cast<const void*>(static_cast<size_t>(Attribs.IndirectDrawArgsOffset)));
// Note that on GLES 3.1, baseInstance is present but reserved and must be zero
DEV_CHECK_GL_ERROR("glDrawArraysIndirect() failed");
constexpr bool ResetVAO = false; // GL_DRAW_INDIRECT_BUFFER does not affect VAO
m_ContextState.BindBuffer(GL_DRAW_INDIRECT_BUFFER, GLObjectWrappers::GLBufferObj::Null(), ResetVAO);
PostDraw();
#else
LOG_ERROR_MESSAGE("Indirect rendering is not supported");
#endif
}
void DeviceContextGLImpl::DrawIndexedIndirect(const DrawIndexedIndirectAttribs& Attribs, IBuffer* pAttribsBuffer)
{
if (!DvpVerifyDrawIndexedIndirectArguments(Attribs, pAttribsBuffer))
return;
#if GL_ARB_draw_indirect
GLenum GlTopology;
PrepareForDraw(Attribs.Flags, true, GlTopology);
GLenum GLIndexType;
Uint32 FirstIndexByteOffset;
PrepareForIndexedDraw(Attribs.IndexType, 0, GLIndexType, FirstIndexByteOffset);
// http://www.opengl.org/wiki/Vertex_Rendering
PrepareForIndirectDraw(pAttribsBuffer);
//typedef struct {
// GLuint count;
// GLuint instanceCount;
// GLuint firstIndex;
// GLuint baseVertex;
// GLuint baseInstance;
//} DrawElementsIndirectCommand;
glDrawElementsIndirect(GlTopology, GLIndexType, reinterpret_cast<const void*>(static_cast<size_t>(Attribs.IndirectDrawArgsOffset)));
// Note that on GLES 3.1, baseInstance is present but reserved and must be zero
DEV_CHECK_GL_ERROR("glDrawElementsIndirect() failed");
constexpr bool ResetVAO = false; // GL_DISPATCH_INDIRECT_BUFFER does not affect VAO
m_ContextState.BindBuffer(GL_DRAW_INDIRECT_BUFFER, GLObjectWrappers::GLBufferObj::Null(), ResetVAO);
PostDraw();
#else
LOG_ERROR_MESSAGE("Indirect rendering is not supported");
#endif
}
void DeviceContextGLImpl::DrawMesh(const DrawMeshAttribs& Attribs)
{
UNSUPPORTED("DrawMesh is not supported in OpenGL");
}
void DeviceContextGLImpl::DrawMeshIndirect(const DrawMeshIndirectAttribs& Attribs, IBuffer* pAttribsBuffer)
{
UNSUPPORTED("DrawMeshIndirect is not supported in OpenGL");
}
void DeviceContextGLImpl::DrawMeshIndirectCount(const DrawMeshIndirectCountAttribs& Attribs, IBuffer* pAttribsBuffer, IBuffer* pCountBuffer)
{
UNSUPPORTED("DrawMeshIndirectCount is not supported in OpenGL");
}
void DeviceContextGLImpl::DispatchCompute(const DispatchComputeAttribs& Attribs)
{
if (!DvpVerifyDispatchArguments(Attribs))
return;
#ifdef DILIGENT_DEVELOPMENT
DvpValidateCommittedShaderResources();
#endif
#if GL_ARB_compute_shader
// The program might have changed since the last SetPipelineState call if a shader was
// created after the call (ShaderResourcesGL needs to bind a program to load uniforms).
m_pPipelineState->CommitProgram(m_ContextState);
BindProgramResources();
glDispatchCompute(Attribs.ThreadGroupCountX, Attribs.ThreadGroupCountY, Attribs.ThreadGroupCountZ);
DEV_CHECK_GL_ERROR("glDispatchCompute() failed");
PostDraw();
#else
UNSUPPORTED("Compute shaders are not supported");
#endif
}
void DeviceContextGLImpl::DispatchComputeIndirect(const DispatchComputeIndirectAttribs& Attribs, IBuffer* pAttribsBuffer)
{
if (!DvpVerifyDispatchIndirectArguments(Attribs, pAttribsBuffer))
return;
#ifdef DILIGENT_DEVELOPMENT
DvpValidateCommittedShaderResources();
#endif
#if GL_ARB_compute_shader
// The program might have changed since the last SetPipelineState call if a shader was
// created after the call (ShaderResourcesGL needs to bind a program to load uniforms).
m_pPipelineState->CommitProgram(m_ContextState);
BindProgramResources();
auto* pBufferGL = ValidatedCast<BufferGLImpl>(pAttribsBuffer);
pBufferGL->BufferMemoryBarrier(
MEMORY_BARRIER_INDIRECT_BUFFER, // Command data sourced from buffer objects by
// Draw*Indirect and DispatchComputeIndirect commands after the barrier
// will reflect data written by shaders prior to the barrier.The buffer
// objects affected by this bit are derived from the DRAW_INDIRECT_BUFFER
// and DISPATCH_INDIRECT_BUFFER bindings.
m_ContextState);
constexpr bool ResetVAO = false; // GL_DISPATCH_INDIRECT_BUFFER does not affect VAO
m_ContextState.BindBuffer(GL_DISPATCH_INDIRECT_BUFFER, pBufferGL->m_GlBuffer, ResetVAO);
DEV_CHECK_GL_ERROR("Failed to bind a buffer for dispatch indirect command");
glDispatchComputeIndirect(Attribs.DispatchArgsByteOffset);
DEV_CHECK_GL_ERROR("glDispatchComputeIndirect() failed");
m_ContextState.BindBuffer(GL_DISPATCH_INDIRECT_BUFFER, GLObjectWrappers::GLBufferObj::Null(), ResetVAO);
PostDraw();
#else
UNSUPPORTED("Compute shaders are not supported");
#endif
}
void DeviceContextGLImpl::ClearDepthStencil(ITextureView* pView,
CLEAR_DEPTH_STENCIL_FLAGS ClearFlags,
float fDepth,
Uint8 Stencil,
RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)
{
if (!TDeviceContextBase::ClearDepthStencil(pView))
return;
VERIFY_EXPR(pView != nullptr);
if (pView != m_pBoundDepthStencil)
{
LOG_ERROR_MESSAGE("Depth stencil buffer must be bound to the context to be cleared in OpenGL backend");
return;
}
Uint32 glClearFlags = 0;
if (ClearFlags & CLEAR_DEPTH_FLAG) glClearFlags |= GL_DEPTH_BUFFER_BIT;
if (ClearFlags & CLEAR_STENCIL_FLAG) glClearFlags |= GL_STENCIL_BUFFER_BIT;
glClearDepthf(fDepth);
glClearStencil(Stencil);
// If depth writes are disabled, glClear() will not clear depth buffer!
bool DepthWritesEnabled = m_ContextState.GetDepthWritesEnabled();
m_ContextState.EnableDepthWrites(True);
// Unlike OpenGL, in D3D10+, the full extent of the resource view is always cleared.
// Viewport and scissor settings are not applied.
bool ScissorTestEnabled = m_ContextState.GetScissorTestEnabled();
m_ContextState.EnableScissorTest(False);
// The pixel ownership test, the scissor test, dithering, and the buffer writemasks affect
// the operation of glClear. The scissor box bounds the cleared region. Alpha function,
// blend function, logical operation, stenciling, texture mapping, and depth-buffering
// are ignored by glClear.
glClear(glClearFlags);
DEV_CHECK_GL_ERROR("glClear() failed");
m_ContextState.EnableDepthWrites(DepthWritesEnabled);
m_ContextState.EnableScissorTest(ScissorTestEnabled);
}
void DeviceContextGLImpl::ClearRenderTarget(ITextureView* pView, const float* RGBA, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)
{
if (!TDeviceContextBase::ClearRenderTarget(pView))
return;
VERIFY_EXPR(pView != nullptr);
Int32 RTIndex = -1;
for (Uint32 rt = 0; rt < m_NumBoundRenderTargets; ++rt)
{
if (m_pBoundRenderTargets[rt] == pView)
{
RTIndex = rt;
break;
}
}
if (RTIndex == -1)
{
LOG_ERROR_MESSAGE("Render target must be bound to the context to be cleared in OpenGL backend");
return;
}
static const float Zero[4] = {0, 0, 0, 0};
if (RGBA == nullptr)
RGBA = Zero;
// The pixel ownership test, the scissor test, dithering, and the buffer writemasks affect
// the operation of glClear. The scissor box bounds the cleared region. Alpha function,
// blend function, logical operation, stenciling, texture mapping, and depth-buffering
// are ignored by glClear.
// Unlike OpenGL, in D3D10+, the full extent of the resource view is always cleared.
// Viewport and scissor settings are not applied.
// Disable scissor test
bool ScissorTestEnabled = m_ContextState.GetScissorTestEnabled();
m_ContextState.EnableScissorTest(False);
// Set write mask
Uint32 WriteMask = 0;
Bool bIndependentBlend = False;
m_ContextState.GetColorWriteMask(RTIndex, WriteMask, bIndependentBlend);
m_ContextState.SetColorWriteMask(RTIndex, COLOR_MASK_ALL, bIndependentBlend);
glClearBufferfv(GL_COLOR, RTIndex, RGBA);
DEV_CHECK_GL_ERROR("glClearBufferfv() failed");
m_ContextState.SetColorWriteMask(RTIndex, WriteMask, bIndependentBlend);
m_ContextState.EnableScissorTest(ScissorTestEnabled);
}
void DeviceContextGLImpl::Flush()
{
if (m_pActiveRenderPass != nullptr)
{
LOG_ERROR_MESSAGE("Flushing device context inside an active render pass.");
}
glFlush();
m_BindInfo = {};
}
void DeviceContextGLImpl::FinishFrame()
{
TDeviceContextBase::EndFrame();
}
void DeviceContextGLImpl::FinishCommandList(class ICommandList** ppCommandList)
{
LOG_ERROR("Deferred contexts are not supported in OpenGL mode");
}
void DeviceContextGLImpl::ExecuteCommandLists(Uint32 NumCommandLists,
ICommandList* const* ppCommandLists)
{
LOG_ERROR("Deferred contexts are not supported in OpenGL mode");
}
void DeviceContextGLImpl::SignalFence(IFence* pFence, Uint64 Value)
{
VERIFY(!m_bIsDeferred, "Fence can only be signaled from immediate context");
GLObjectWrappers::GLSyncObj GLFence{glFenceSync(
GL_SYNC_GPU_COMMANDS_COMPLETE, // Condition must always be GL_SYNC_GPU_COMMANDS_COMPLETE
0 // Flags, must be 0
)};
DEV_CHECK_GL_ERROR("Failed to create gl fence");
auto* pFenceGLImpl = ValidatedCast<FenceGLImpl>(pFence);
pFenceGLImpl->AddPendingFence(std::move(GLFence), Value);
}
void DeviceContextGLImpl::WaitForFence(IFence* pFence, Uint64 Value, bool FlushContext)
{
VERIFY(!m_bIsDeferred, "Fence can only be waited from immediate context");
auto* pFenceGLImpl = ValidatedCast<FenceGLImpl>(pFence);
pFenceGLImpl->Wait(Value, FlushContext);
}
void DeviceContextGLImpl::WaitForIdle()
{
VERIFY(!m_bIsDeferred, "Only immediate contexts can be idled");
Flush();
glFinish();
}
void DeviceContextGLImpl::BeginQuery(IQuery* pQuery)
{
if (!TDeviceContextBase::BeginQuery(pQuery, 0))
return;
auto* pQueryGLImpl = ValidatedCast<QueryGLImpl>(pQuery);
auto QueryType = pQueryGLImpl->GetDesc().Type;
auto glQuery = pQueryGLImpl->GetGlQueryHandle();
switch (QueryType)
{
case QUERY_TYPE_OCCLUSION:
#if GL_SAMPLES_PASSED
glBeginQuery(GL_SAMPLES_PASSED, glQuery);
DEV_CHECK_GL_ERROR("Failed to begin GL_SAMPLES_PASSED query");
#else
LOG_ERROR_MESSAGE_ONCE("GL_SAMPLES_PASSED query is not supported by this device");
#endif
break;
case QUERY_TYPE_BINARY_OCCLUSION:
glBeginQuery(GL_ANY_SAMPLES_PASSED, glQuery);
DEV_CHECK_GL_ERROR("Failed to begin GL_ANY_SAMPLES_PASSED query");
break;
case QUERY_TYPE_PIPELINE_STATISTICS:
#if GL_PRIMITIVES_GENERATED
glBeginQuery(GL_PRIMITIVES_GENERATED, glQuery);
DEV_CHECK_GL_ERROR("Failed to begin GL_PRIMITIVES_GENERATED query");
#else
LOG_ERROR_MESSAGE_ONCE("GL_PRIMITIVES_GENERATED query is not supported by this device");
#endif
break;
case QUERY_TYPE_DURATION:
#if GL_TIME_ELAPSED
glBeginQuery(GL_TIME_ELAPSED, glQuery);
DEV_CHECK_GL_ERROR("Failed to begin GL_TIME_ELAPSED query");
#else
LOG_ERROR_MESSAGE_ONCE("Duration queries are not supported by this device");
#endif
break;
default:
UNEXPECTED("Unexpected query type");
}
}
void DeviceContextGLImpl::EndQuery(IQuery* pQuery)
{
if (!TDeviceContextBase::EndQuery(pQuery, 0))
return;
auto* pQueryGLImpl = ValidatedCast<QueryGLImpl>(pQuery);
auto QueryType = pQueryGLImpl->GetDesc().Type;
switch (QueryType)
{
case QUERY_TYPE_OCCLUSION:
#if GL_SAMPLES_PASSED
glEndQuery(GL_SAMPLES_PASSED);
DEV_CHECK_GL_ERROR("Failed to end GL_SAMPLES_PASSED query");
#endif
break;
case QUERY_TYPE_BINARY_OCCLUSION:
glEndQuery(GL_ANY_SAMPLES_PASSED);
DEV_CHECK_GL_ERROR("Failed to end GL_ANY_SAMPLES_PASSED query");
break;
case QUERY_TYPE_PIPELINE_STATISTICS:
#if GL_PRIMITIVES_GENERATED
glEndQuery(GL_PRIMITIVES_GENERATED);
DEV_CHECK_GL_ERROR("Failed to end GL_PRIMITIVES_GENERATED query");
#endif
break;
case QUERY_TYPE_TIMESTAMP:
#if GL_TIMESTAMP
if (glQueryCounter != nullptr)
{
glQueryCounter(pQueryGLImpl->GetGlQueryHandle(), GL_TIMESTAMP);
DEV_CHECK_GL_ERROR("glQueryCounter failed");
}
else
#endif
{
LOG_ERROR_MESSAGE_ONCE("Timer queries are not supported by this device");
}
break;
case QUERY_TYPE_DURATION:
#if GL_TIME_ELAPSED
glEndQuery(GL_TIME_ELAPSED);
DEV_CHECK_GL_ERROR("Failed to end GL_TIME_ELAPSED query");
#else
LOG_ERROR_MESSAGE_ONCE("Duration queries are not supported by this device");
#endif
break;
default:
UNEXPECTED("Unexpected query type");
}
}
bool DeviceContextGLImpl::UpdateCurrentGLContext()
{
auto NativeGLContext = m_pDevice->m_GLContext.GetCurrentNativeGLContext();
if (NativeGLContext == NULL)
return false;
m_ContextState.SetCurrentGLContext(NativeGLContext);
return true;
}
void DeviceContextGLImpl::UpdateBuffer(IBuffer* pBuffer,
Uint32 Offset,
Uint32 Size,
const void* pData,
RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)
{
TDeviceContextBase::UpdateBuffer(pBuffer, Offset, Size, pData, StateTransitionMode);
auto* pBufferGL = ValidatedCast<BufferGLImpl>(pBuffer);
pBufferGL->UpdateData(m_ContextState, Offset, Size, pData);
}
void DeviceContextGLImpl::CopyBuffer(IBuffer* pSrcBuffer,
Uint32 SrcOffset,
RESOURCE_STATE_TRANSITION_MODE SrcBufferTransitionMode,
IBuffer* pDstBuffer,
Uint32 DstOffset,
Uint32 Size,
RESOURCE_STATE_TRANSITION_MODE DstBufferTransitionMode)
{
TDeviceContextBase::CopyBuffer(pSrcBuffer, SrcOffset, SrcBufferTransitionMode, pDstBuffer, DstOffset, Size, DstBufferTransitionMode);
auto* pSrcBufferGL = ValidatedCast<BufferGLImpl>(pSrcBuffer);
auto* pDstBufferGL = ValidatedCast<BufferGLImpl>(pDstBuffer);
pDstBufferGL->CopyData(m_ContextState, *pSrcBufferGL, SrcOffset, DstOffset, Size);
}
void DeviceContextGLImpl::MapBuffer(IBuffer* pBuffer, MAP_TYPE MapType, MAP_FLAGS MapFlags, PVoid& pMappedData)
{
TDeviceContextBase::MapBuffer(pBuffer, MapType, MapFlags, pMappedData);
auto* pBufferGL = ValidatedCast<BufferGLImpl>(pBuffer);
pBufferGL->Map(m_ContextState, MapType, MapFlags, pMappedData);
}
void DeviceContextGLImpl::UnmapBuffer(IBuffer* pBuffer, MAP_TYPE MapType)
{
TDeviceContextBase::UnmapBuffer(pBuffer, MapType);
auto* pBufferGL = ValidatedCast<BufferGLImpl>(pBuffer);
pBufferGL->Unmap(m_ContextState);
}
void DeviceContextGLImpl::UpdateTexture(ITexture* pTexture,
Uint32 MipLevel,
Uint32 Slice,
const Box& DstBox,
const TextureSubResData& SubresData,
RESOURCE_STATE_TRANSITION_MODE SrcBufferStateTransitionMode,
RESOURCE_STATE_TRANSITION_MODE TextureStateTransitionMode)
{
TDeviceContextBase::UpdateTexture(pTexture, MipLevel, Slice, DstBox, SubresData, SrcBufferStateTransitionMode, TextureStateTransitionMode);
auto* pTexGL = ValidatedCast<TextureBaseGL>(pTexture);
pTexGL->UpdateData(m_ContextState, MipLevel, Slice, DstBox, SubresData);
}
void DeviceContextGLImpl::CopyTexture(const CopyTextureAttribs& CopyAttribs)
{
TDeviceContextBase::CopyTexture(CopyAttribs);
auto* pSrcTexGL = ValidatedCast<TextureBaseGL>(CopyAttribs.pSrcTexture);
auto* pDstTexGL = ValidatedCast<TextureBaseGL>(CopyAttribs.pDstTexture);
const auto& SrcTexDesc = pSrcTexGL->GetDesc();
const auto& DstTexDesc = pDstTexGL->GetDesc();
auto SrcMipLevelAttribs = GetMipLevelProperties(SrcTexDesc, CopyAttribs.SrcMipLevel);
Box FullSrcBox;
FullSrcBox.MaxX = SrcMipLevelAttribs.LogicalWidth;
FullSrcBox.MaxY = SrcMipLevelAttribs.LogicalHeight;
FullSrcBox.MaxZ = SrcMipLevelAttribs.Depth;
auto* pSrcBox = CopyAttribs.pSrcBox != nullptr ? CopyAttribs.pSrcBox : &FullSrcBox;
if (SrcTexDesc.Usage == USAGE_STAGING && DstTexDesc.Usage != USAGE_STAGING)
{
TextureSubResData SubresData;
SubresData.pData = nullptr;
SubresData.pSrcBuffer = pSrcTexGL->GetPBO();
SubresData.SrcOffset =
GetStagingTextureLocationOffset(SrcTexDesc, CopyAttribs.SrcSlice, CopyAttribs.SrcMipLevel,
TextureBaseGL::PBOOffsetAlignment,
pSrcBox->MinX, pSrcBox->MinY, pSrcBox->MinZ);
SubresData.Stride = SrcMipLevelAttribs.RowSize;
SubresData.DepthStride = SrcMipLevelAttribs.DepthSliceSize;
Box DstBox;
DstBox.MinX = CopyAttribs.DstX;
DstBox.MinY = CopyAttribs.DstY;
DstBox.MinZ = CopyAttribs.DstZ;
DstBox.MaxX = DstBox.MinX + pSrcBox->MaxX - pSrcBox->MinX;
DstBox.MaxY = DstBox.MinY + pSrcBox->MaxY - pSrcBox->MinY;
DstBox.MaxZ = DstBox.MinZ + pSrcBox->MaxZ - pSrcBox->MinZ;
pDstTexGL->UpdateData(m_ContextState, CopyAttribs.DstMipLevel, CopyAttribs.DstSlice, DstBox, SubresData);
}
else if (SrcTexDesc.Usage != USAGE_STAGING && DstTexDesc.Usage == USAGE_STAGING)
{
if (pSrcTexGL->GetGLTextureHandle() == 0)
{
auto* pSwapChainGL = m_pSwapChain.RawPtr<ISwapChainGL>();
GLuint DefaultFBOHandle = pSwapChainGL->GetDefaultFBO();
glBindFramebuffer(GL_READ_FRAMEBUFFER, DefaultFBOHandle);
DEV_CHECK_GL_ERROR("Failed to bind default FBO as read framebuffer");
}
else
{
TextureViewDesc SrcTexViewDesc;
SrcTexViewDesc.ViewType = TEXTURE_VIEW_RENDER_TARGET;
SrcTexViewDesc.MostDetailedMip = CopyAttribs.SrcMipLevel;
SrcTexViewDesc.FirstArraySlice = CopyAttribs.SrcSlice;
SrcTexViewDesc.NumArraySlices = 1;
SrcTexViewDesc.NumMipLevels = 1;
TextureViewGLImpl SrcTexView //
{
nullptr, // pRefCounters
m_pDevice,
SrcTexViewDesc,
pSrcTexGL,
false, // bCreateGLViewTex
false // bIsDefaultView
};
auto CurrentNativeGLContext = m_ContextState.GetCurrentGLContext();
auto& fboCache = m_pDevice->GetFBOCache(CurrentNativeGLContext);
TextureViewGLImpl* pSrcViews[] = {&SrcTexView};
const auto& SrcFBO = fboCache.GetFBO(1, pSrcViews, nullptr, m_ContextState);
glBindFramebuffer(GL_READ_FRAMEBUFFER, SrcFBO);
DEV_CHECK_GL_ERROR("Failed to bind FBO as read framebuffer");
}
auto* pDstBuffer = ValidatedCast<BufferGLImpl>(pDstTexGL->GetPBO());
VERIFY(pDstBuffer != nullptr, "Internal staging buffer must not be null");
// GetStagingTextureLocationOffset assumes pixels are tightly packed in every subresource - no padding
// except between subresources.
const auto DstOffset =
GetStagingTextureLocationOffset(DstTexDesc, CopyAttribs.DstSlice, CopyAttribs.DstMipLevel,
TextureBaseGL::PBOOffsetAlignment,
CopyAttribs.DstX, CopyAttribs.DstY, CopyAttribs.DstZ);
m_ContextState.BindBuffer(GL_PIXEL_PACK_BUFFER, pDstBuffer->GetGLHandle(), true);
const auto& TransferAttribs = GetNativePixelTransferAttribs(SrcTexDesc.Format);
glReadPixels(pSrcBox->MinX, pSrcBox->MinY, pSrcBox->MaxX - pSrcBox->MinX, pSrcBox->MaxY - pSrcBox->MinY,
TransferAttribs.PixelFormat, TransferAttribs.DataType, reinterpret_cast<void*>(static_cast<size_t>(DstOffset)));
DEV_CHECK_GL_ERROR("Failed to read pixel from framebuffer to pixel pack buffer");
m_ContextState.BindBuffer(GL_PIXEL_PACK_BUFFER, GLObjectWrappers::GLBufferObj::Null(), true);
// Restore original FBO
m_ContextState.InvalidateFBO();
CommitRenderTargets();
}
else
{
VERIFY(SrcTexDesc.Usage != USAGE_STAGING && DstTexDesc.Usage != USAGE_STAGING, "Copying between staging textures is not supported");
pDstTexGL->CopyData(this, pSrcTexGL, CopyAttribs.SrcMipLevel, CopyAttribs.SrcSlice, CopyAttribs.pSrcBox,
CopyAttribs.DstMipLevel, CopyAttribs.DstSlice, CopyAttribs.DstX, CopyAttribs.DstY, CopyAttribs.DstZ);
}
}
void DeviceContextGLImpl::MapTextureSubresource(ITexture* pTexture,
Uint32 MipLevel,
Uint32 ArraySlice,
MAP_TYPE MapType,
MAP_FLAGS MapFlags,
const Box* pMapRegion,
MappedTextureSubresource& MappedData)
{
TDeviceContextBase::MapTextureSubresource(pTexture, MipLevel, ArraySlice, MapType, MapFlags, pMapRegion, MappedData);
auto* pTexGL = ValidatedCast<TextureBaseGL>(pTexture);
const auto& TexDesc = pTexGL->GetDesc();
if (TexDesc.Usage == USAGE_STAGING)
{
auto PBOOffset = GetStagingTextureSubresourceOffset(TexDesc, ArraySlice, MipLevel, TextureBaseGL::PBOOffsetAlignment);
auto MipLevelAttribs = GetMipLevelProperties(TexDesc, MipLevel);
auto pPBO = ValidatedCast<BufferGLImpl>(pTexGL->GetPBO());
pPBO->MapRange(m_ContextState, MapType, MapFlags, PBOOffset, MipLevelAttribs.MipSize, MappedData.pData);
MappedData.Stride = MipLevelAttribs.RowSize;
MappedData.DepthStride = MipLevelAttribs.MipSize;
}
else
{
LOG_ERROR_MESSAGE("Only staging textures can be mapped in OpenGL");
MappedData = MappedTextureSubresource{};
}
}
void DeviceContextGLImpl::UnmapTextureSubresource(ITexture* pTexture, Uint32 MipLevel, Uint32 ArraySlice)
{
TDeviceContextBase::UnmapTextureSubresource(pTexture, MipLevel, ArraySlice);
auto* pTexGL = ValidatedCast<TextureBaseGL>(pTexture);
const auto& TexDesc = pTexGL->GetDesc();
if (TexDesc.Usage == USAGE_STAGING)
{
auto pPBO = ValidatedCast<BufferGLImpl>(pTexGL->GetPBO());
pPBO->Unmap(m_ContextState);
}
else
{
LOG_ERROR_MESSAGE("Only staging textures can be mapped in OpenGL");
}
}
void DeviceContextGLImpl::GenerateMips(ITextureView* pTexView)
{
TDeviceContextBase::GenerateMips(pTexView);
auto* pTexViewGL = ValidatedCast<TextureViewGLImpl>(pTexView);
auto BindTarget = pTexViewGL->GetBindTarget();
m_ContextState.BindTexture(-1, BindTarget, pTexViewGL->GetHandle());
glGenerateMipmap(BindTarget);
DEV_CHECK_GL_ERROR("Failed to generate mip maps");
m_ContextState.BindTexture(-1, BindTarget, GLObjectWrappers::GLTextureObj::Null());
}
void DeviceContextGLImpl::TransitionResourceStates(Uint32 BarrierCount, StateTransitionDesc* pResourceBarriers)
{
VERIFY(m_pActiveRenderPass == nullptr, "State transitions are not allowed inside a render pass");
}
void DeviceContextGLImpl::ResolveTextureSubresource(ITexture* pSrcTexture,
ITexture* pDstTexture,
const ResolveTextureSubresourceAttribs& ResolveAttribs)
{
TDeviceContextBase::ResolveTextureSubresource(pSrcTexture, pDstTexture, ResolveAttribs);
auto* pSrcTexGl = ValidatedCast<TextureBaseGL>(pSrcTexture);
auto* pDstTexGl = ValidatedCast<TextureBaseGL>(pDstTexture);
const auto& SrcTexDesc = pSrcTexGl->GetDesc();
//const auto& DstTexDesc = pDstTexGl->GetDesc();
auto CurrentNativeGLContext = m_ContextState.GetCurrentGLContext();
auto& FBOCache = m_pDevice->GetFBOCache(CurrentNativeGLContext);
{
TextureViewDesc SrcTexViewDesc;
SrcTexViewDesc.ViewType = TEXTURE_VIEW_RENDER_TARGET;
SrcTexViewDesc.MostDetailedMip = ResolveAttribs.SrcMipLevel;
SrcTexViewDesc.FirstArraySlice = ResolveAttribs.SrcSlice;
TextureViewGLImpl SrcTexView //
{
nullptr, // pRefCounters
m_pDevice,
SrcTexViewDesc,
pSrcTexGl,
false, // bCreateGLViewTex
false // bIsDefaultView
};
TextureViewGLImpl* pSrcViews[] = {&SrcTexView};
const auto& SrcFBO = FBOCache.GetFBO(1, pSrcViews, nullptr, m_ContextState);
glBindFramebuffer(GL_READ_FRAMEBUFFER, SrcFBO);
DEV_CHECK_GL_ERROR("Failed to bind FBO as read framebuffer");
}
if (pDstTexGl->GetGLHandle())
{
TextureViewDesc DstTexViewDesc;
DstTexViewDesc.ViewType = TEXTURE_VIEW_RENDER_TARGET;
DstTexViewDesc.MostDetailedMip = ResolveAttribs.DstMipLevel;
DstTexViewDesc.FirstArraySlice = ResolveAttribs.DstSlice;
TextureViewGLImpl DstTexView //
{
nullptr, // pRefCounters
m_pDevice,
DstTexViewDesc,
pDstTexGl,
false, // bCreateGLViewTex
false // bIsDefaultView
};
TextureViewGLImpl* pDstViews[] = {&DstTexView};
const auto& DstFBO = FBOCache.GetFBO(1, pDstViews, nullptr, m_ContextState);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, DstFBO);
DEV_CHECK_GL_ERROR("Failed to bind FBO as draw framebuffer");
}
else
{
auto* pSwapChainGL = m_pSwapChain.RawPtr<ISwapChainGL>();
GLuint DefaultFBOHandle = pSwapChainGL->GetDefaultFBO();
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, DefaultFBOHandle);
DEV_CHECK_GL_ERROR("Failed to bind default FBO as draw framebuffer");
}
const auto& MipAttribs = GetMipLevelProperties(SrcTexDesc, ResolveAttribs.SrcMipLevel);
glBlitFramebuffer(0, 0, static_cast<GLint>(MipAttribs.LogicalWidth), static_cast<GLint>(MipAttribs.LogicalHeight),
0, 0, static_cast<GLint>(MipAttribs.LogicalWidth), static_cast<GLint>(MipAttribs.LogicalHeight),
GL_COLOR_BUFFER_BIT,
GL_NEAREST // Filter is ignored
);
DEV_CHECK_GL_ERROR("glBlitFramebuffer() failed when resolving multi-sampled texture");
// Restore original FBO
m_ContextState.InvalidateFBO();
CommitRenderTargets();
}
void DeviceContextGLImpl::BuildBLAS(const BuildBLASAttribs& Attribs)
{
UNSUPPORTED("BuildBLAS is not supported in OpenGL");
}
void DeviceContextGLImpl::BuildTLAS(const BuildTLASAttribs& Attribs)
{
UNSUPPORTED("BuildTLAS is not supported in OpenGL");
}
void DeviceContextGLImpl::CopyBLAS(const CopyBLASAttribs& Attribs)
{
UNSUPPORTED("CopyBLAS is not supported in OpenGL");
}
void DeviceContextGLImpl::CopyTLAS(const CopyTLASAttribs& Attribs)
{
UNSUPPORTED("CopyTLAS is not supported in OpenGL");
}
void DeviceContextGLImpl::WriteBLASCompactedSize(const WriteBLASCompactedSizeAttribs& Attribs)
{
UNSUPPORTED("WriteBLASCompactedSize is not supported in OpenGL");
}
void DeviceContextGLImpl::WriteTLASCompactedSize(const WriteTLASCompactedSizeAttribs& Attribs)
{
UNSUPPORTED("WriteTLASCompactedSize is not supported in OpenGL");
}
void DeviceContextGLImpl::TraceRays(const TraceRaysAttribs& Attribs)
{
UNSUPPORTED("TraceRays is not supported in OpenGL");
}
void DeviceContextGLImpl::TraceRaysIndirect(const TraceRaysIndirectAttribs& Attribs, IBuffer* pAttribsBuffer)
{
UNSUPPORTED("TraceRaysIndirect is not supported in OpenGL");
}
} // namespace Diligent
|