forked from DiligentGraphics/DiligentCore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeviceContextWebGPUImpl.cpp
More file actions
2408 lines (2006 loc) · 105 KB
/
DeviceContextWebGPUImpl.cpp
File metadata and controls
2408 lines (2006 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2023-2025 Diligent Graphics LLC
*
* 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 "DeviceContextWebGPUImpl.hpp"
#include "RenderDeviceWebGPUImpl.hpp"
#include "TextureWebGPUImpl.hpp"
#include "TextureViewWebGPUImpl.hpp"
#include "BufferWebGPUImpl.hpp"
#include "PipelineStateWebGPUImpl.hpp"
#include "PipelineResourceSignatureWebGPUImpl.hpp"
#include "PipelineResourceAttribsWebGPU.hpp"
#include "ShaderResourceCacheWebGPU.hpp"
#include "RenderPassWebGPUImpl.hpp"
#include "FramebufferWebGPUImpl.hpp"
#include "FenceWebGPUImpl.hpp"
#include "QueryManagerWebGPU.hpp"
#include "QueryWebGPUImpl.hpp"
#include "AttachmentCleanerWebGPU.hpp"
#include "WebGPUTypeConversions.hpp"
#include "SyncPointWebGPU.hpp"
namespace Diligent
{
DeviceContextWebGPUImpl::DeviceContextWebGPUImpl(IReferenceCounters* pRefCounters,
RenderDeviceWebGPUImpl* pDevice,
const DeviceContextDesc& Desc) :
// clang-format off
TDeviceContextBase
{
pRefCounters,
pDevice,
Desc
}
// clang-format on
{
m_wgpuQueue.Reset(wgpuDeviceGetQueue(pDevice->GetWebGPUDevice()));
FenceDesc InternalFenceDesc;
InternalFenceDesc.Name = "Device context internal fence";
pDevice->CreateFence(InternalFenceDesc, &m_pFence);
m_MappedBuffers.reserve(16);
}
void DeviceContextWebGPUImpl::Begin(Uint32 ImmediateContextId)
{
DEV_CHECK_ERR(ImmediateContextId == 0, "WebGPU supports only one immediate context");
TDeviceContextBase::Begin(DeviceContextIndex{ImmediateContextId}, COMMAND_QUEUE_TYPE_GRAPHICS);
}
void DeviceContextWebGPUImpl::SetPipelineState(IPipelineState* pPipelineState)
{
if (!TDeviceContextBase::SetPipelineState(pPipelineState, PipelineStateWebGPUImpl::IID_InternalImpl))
return;
m_EncoderState.Invalidate(WebGPUEncoderState::CMD_ENCODER_STATE_PIPELINE_STATE);
Uint32 DvpCompatibleSRBCount = 0;
PrepareCommittedResources(m_BindInfo, DvpCompatibleSRBCount);
// Commit all SRBs when PSO changes
m_BindInfo.StaleSRBMask |= m_BindInfo.ActiveSRBMask;
const Uint32 SignatureCount = m_pPipelineState->GetResourceSignatureCount();
Uint32 ActiveBindGroupIndex = 0;
for (Uint32 i = 0; i < SignatureCount; ++i)
{
PipelineResourceSignatureWebGPUImpl* pSign = m_pPipelineState->GetResourceSignature(i);
if (pSign == nullptr || pSign->GetNumBindGroups() == 0)
{
for (WebGPUResourceBindInfo::BindGroupInfo& BindGroup : m_BindInfo.BindGroups[i])
{
// Make the group inactive, but do not reset wgpuBindGroup - it might be used by a PSO that is set later
BindGroup.MakeInactive();
}
continue;
}
VERIFY_EXPR(i == pSign->GetDesc().BindingIndex);
VERIFY_EXPR(m_BindInfo.ActiveSRBMask & (1u << i));
VERIFY(m_pPipelineState->GetPipelineLayout().GetFirstBindGroupIndex(i) == ActiveBindGroupIndex, "Bind group index mismatch");
for (PipelineResourceSignatureWebGPUImpl::BIND_GROUP_ID BindGroupId : {PipelineResourceSignatureWebGPUImpl::BIND_GROUP_ID_STATIC_MUTABLE,
PipelineResourceSignatureWebGPUImpl::BIND_GROUP_ID_DYNAMIC})
{
WebGPUResourceBindInfo::BindGroupInfo& BindGroup = m_BindInfo.BindGroups[i][BindGroupId];
if (pSign->HasBindGroup(BindGroupId))
{
const Uint32 DynamicOffsetCount = pSign->GetDynamicOffsetCount(BindGroupId);
BindGroup.DynamicBufferOffsets.resize(DynamicOffsetCount);
for (Uint32& Offset : BindGroup.DynamicBufferOffsets)
Offset = ~0u;
BindGroup.BindIndex = ActiveBindGroupIndex++;
}
else
{
// Make the group inactive, but do not reset wgpuBindGroup - it might be used by a PSO that is set later
BindGroup.MakeInactive();
}
}
}
VERIFY(m_pPipelineState->GetPipelineLayout().GetBindGroupCount() == ActiveBindGroupIndex, "Bind group count mismatch");
}
void DeviceContextWebGPUImpl::TransitionShaderResources(IShaderResourceBinding* pShaderResourceBinding)
{
DEV_CHECK_ERR(pShaderResourceBinding != nullptr, "Shader resource binding must not be null");
}
#ifdef DILIGENT_DEVELOPMENT
void DeviceContextWebGPUImpl::DvpValidateCommittedShaderResources()
{
if (m_BindInfo.ResourcesValidated)
return;
DvpVerifySRBCompatibility(m_BindInfo);
const Uint32 SignCount = m_pPipelineState->GetResourceSignatureCount();
for (Uint32 i = 0; i < SignCount; ++i)
{
const PipelineResourceSignatureWebGPUImpl* pSign = m_pPipelineState->GetResourceSignature(i);
if (pSign == nullptr || pSign->GetNumBindGroups() == 0)
continue; // Skip null and empty signatures
VERIFY(i == pSign->GetDesc().BindingIndex, "Resource signature index mismatch");
for (PipelineResourceSignatureWebGPUImpl::BIND_GROUP_ID BindGroupId : {PipelineResourceSignatureWebGPUImpl::BIND_GROUP_ID_STATIC_MUTABLE,
PipelineResourceSignatureWebGPUImpl::BIND_GROUP_ID_DYNAMIC})
{
const WebGPUResourceBindInfo::BindGroupInfo& BindGroup = m_BindInfo.BindGroups[i][BindGroupId];
DEV_CHECK_ERR(BindGroup.IsActive() == pSign->HasBindGroup(BindGroupId),
"Active bind group flag mismatch for resource signature '", pSign->GetDesc().Name, "', binding index ", i, ", bind group id ", BindGroupId, ".");
DEV_CHECK_ERR(!BindGroup.IsActive() || BindGroup.wgpuBindGroup != nullptr,
"Bind group is not initialized for resource signature '", pSign->GetDesc().Name, "', binding index ", i, ", bind group id ", BindGroupId, ".");
}
}
m_pPipelineState->DvpVerifySRBResources(this, m_BindInfo.ResourceCaches);
m_BindInfo.ResourcesValidated = true;
}
#endif
void DeviceContextWebGPUImpl::CommitShaderResources(IShaderResourceBinding* pShaderResourceBinding,
RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)
{
TDeviceContextBase::CommitShaderResources(pShaderResourceBinding, StateTransitionMode, 0 /*Dummy*/);
ShaderResourceBindingWebGPUImpl* pResBindingWebGPU = ClassPtrCast<ShaderResourceBindingWebGPUImpl>(pShaderResourceBinding);
ShaderResourceCacheWebGPU& ResourceCache = pResBindingWebGPU->GetResourceCache();
if (ResourceCache.GetNumBindGroups() == 0)
{
// Ignore SRBs that contain no resources
return;
}
#ifdef DILIGENT_DEBUG
ResourceCache.DbgVerifyDynamicBuffersCounter();
#endif
const WGPUDevice wgpuDevice = m_pDevice->GetWebGPUDevice();
const Uint32 SRBIndex = pResBindingWebGPU->GetBindingIndex();
PipelineResourceSignatureWebGPUImpl* pSignature = pResBindingWebGPU->GetSignature();
m_BindInfo.Set(SRBIndex, pResBindingWebGPU);
Uint32 BGIndex = 0;
for (PipelineResourceSignatureWebGPUImpl::BIND_GROUP_ID BindGroupId : {PipelineResourceSignatureWebGPUImpl::BIND_GROUP_ID_STATIC_MUTABLE,
PipelineResourceSignatureWebGPUImpl::BIND_GROUP_ID_DYNAMIC})
{
WebGPUResourceBindInfo::BindGroupInfo& BindGroup = m_BindInfo.BindGroups[SRBIndex][BindGroupId];
if (pSignature->HasBindGroup(BindGroupId))
{
BindGroup.wgpuBindGroup = ResourceCache.UpdateBindGroup(wgpuDevice, BGIndex, pSignature->GetWGPUBindGroupLayout(BindGroupId));
++BGIndex;
}
else
{
BindGroup.wgpuBindGroup = nullptr;
}
}
VERIFY_EXPR(BGIndex == ResourceCache.GetNumBindGroups());
}
void SetBindGroup(WGPURenderPassEncoder Encoder, uint32_t GroupIndex, WGPUBindGroup Group, const std::vector<Uint32>& DynamicOffsets)
{
wgpuRenderPassEncoderSetBindGroup(Encoder, GroupIndex, Group, DynamicOffsets.size(), !DynamicOffsets.empty() ? DynamicOffsets.data() : nullptr);
}
void SetBindGroup(WGPUComputePassEncoder Encoder, uint32_t GroupIndex, WGPUBindGroup Group, const std::vector<Uint32>& DynamicOffsets)
{
wgpuComputePassEncoderSetBindGroup(Encoder, GroupIndex, Group, DynamicOffsets.size(), !DynamicOffsets.empty() ? DynamicOffsets.data() : nullptr);
}
template <typename CmdEncoderType>
void DeviceContextWebGPUImpl::CommitBindGroups(CmdEncoderType CmdEncoder, Uint32 CommitSRBMask, bool InlineConstantsIntact)
{
VERIFY(CommitSRBMask != 0, "This method should not be called when there is nothing to commit");
const Uint32 FirstSign = PlatformMisc::GetLSB(CommitSRBMask);
const Uint32 LastSign = PlatformMisc::GetMSB(CommitSRBMask);
VERIFY_EXPR(LastSign < m_pPipelineState->GetResourceSignatureCount());
for (Uint32 sign = FirstSign; sign <= LastSign; ++sign)
{
const Uint32 SRBBit = 1u << sign;
if ((CommitSRBMask & SRBBit) == 0)
continue;
const ShaderResourceCacheWebGPU* ResourceCache = m_BindInfo.ResourceCaches[sign];
VERIFY_EXPR(ResourceCache != nullptr);
// Update inline constant buffers if needed
const bool SRBStale = (m_BindInfo.StaleSRBMask & SRBBit) != 0;
if ((m_BindInfo.InlineConstantsSRBMask & SRBBit) != 0)
{
VERIFY(ResourceCache->HasInlineConstants(),
"Shader resource cache does not contain inline constants, but the corresponding bit in InlineConstantsSRBMask is set.");
// Update inline constant buffers if the SRB is stale or inline constants have changed
if (SRBStale || !InlineConstantsIntact)
{
if (PipelineResourceSignatureWebGPUImpl* pSign = m_pPipelineState->GetResourceSignature(sign))
{
pSign->UpdateInlineConstantBuffers(*ResourceCache, this);
}
}
}
Uint32 BindGroupCacheIndex = 0;
for (PipelineResourceSignatureWebGPUImpl::BIND_GROUP_ID BindGroupId : {PipelineResourceSignatureWebGPUImpl::BIND_GROUP_ID_STATIC_MUTABLE,
PipelineResourceSignatureWebGPUImpl::BIND_GROUP_ID_DYNAMIC})
{
WebGPUResourceBindInfo::BindGroupInfo& BindGroup = m_BindInfo.BindGroups[sign][BindGroupId];
if (!BindGroup.IsActive())
continue;
bool DynamicOffsetsChanged = false;
if (!BindGroup.DynamicBufferOffsets.empty())
{
DynamicOffsetsChanged = ResourceCache->GetDynamicBufferOffsets(this, BindGroup.DynamicBufferOffsets, BindGroupCacheIndex);
}
++BindGroupCacheIndex;
if (!SRBStale && !DynamicOffsetsChanged)
{
continue;
}
if (WGPUBindGroup wgpuBindGroup = BindGroup.wgpuBindGroup)
{
SetBindGroup(CmdEncoder, BindGroup.BindIndex, wgpuBindGroup, BindGroup.DynamicBufferOffsets);
}
else
{
DEV_ERROR("Active bind group at index ", BindGroup.BindIndex, " is not initialized");
}
}
}
// Note that there is one global dynamic buffer from which all dynamic resources are suballocated,
// and this buffer is not resizable, so the buffer handle can never change.
m_BindInfo.StaleSRBMask &= ~m_BindInfo.ActiveSRBMask;
}
void DeviceContextWebGPUImpl::InvalidateState()
{
TDeviceContextBase::InvalidateState();
m_PendingClears.Clear();
m_EncoderState.Clear();
m_BindInfo.Reset();
}
void DeviceContextWebGPUImpl::SetStencilRef(Uint32 StencilRef)
{
if (TDeviceContextBase::SetStencilRef(StencilRef, 0))
m_EncoderState.Invalidate(WebGPUEncoderState::CMD_ENCODER_STATE_STENCIL_REF);
}
void DeviceContextWebGPUImpl::SetBlendFactors(const float* pBlendFactors)
{
if (TDeviceContextBase::SetBlendFactors(pBlendFactors, 0))
m_EncoderState.Invalidate(WebGPUEncoderState::CMD_ENCODER_STATE_BLEND_FACTORS);
}
void DeviceContextWebGPUImpl::SetVertexBuffers(Uint32 StartSlot,
Uint32 NumBuffersSet,
IBuffer* const* ppBuffers,
const Uint64* pOffsets,
RESOURCE_STATE_TRANSITION_MODE StateTransitionMode,
SET_VERTEX_BUFFERS_FLAGS Flags)
{
TDeviceContextBase::SetVertexBuffers(StartSlot, NumBuffersSet, ppBuffers, pOffsets, StateTransitionMode, Flags);
m_EncoderState.Invalidate(WebGPUEncoderState::CMD_ENCODER_STATE_VERTEX_BUFFERS);
}
void DeviceContextWebGPUImpl::SetIndexBuffer(IBuffer* pIndexBuffer,
Uint64 ByteOffset,
RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)
{
TDeviceContextBase::SetIndexBuffer(pIndexBuffer, ByteOffset, StateTransitionMode);
m_EncoderState.Invalidate(WebGPUEncoderState::CMD_ENCODER_STATE_INDEX_BUFFER);
}
void DeviceContextWebGPUImpl::SetViewports(Uint32 NumViewports,
const Viewport* pViewports,
Uint32 RTWidth,
Uint32 RTHeight)
{
TDeviceContextBase::SetViewports(NumViewports, pViewports, RTWidth, RTHeight);
m_EncoderState.Invalidate(WebGPUEncoderState::CMD_ENCODER_STATE_VIEWPORTS);
}
void DeviceContextWebGPUImpl::SetScissorRects(Uint32 NumRects, const Rect* pRects, Uint32 RTWidth, Uint32 RTHeight)
{
TDeviceContextBase::SetScissorRects(NumRects, pRects, RTWidth, RTHeight);
m_EncoderState.Invalidate(WebGPUEncoderState::CMD_ENCODER_STATE_SCISSOR_RECTS);
}
void DeviceContextWebGPUImpl::SetRenderTargetsExt(const SetRenderTargetsAttribs& Attribs)
{
if (m_PendingClears.AnyPending())
{
bool RTChanged =
Attribs.NumRenderTargets != m_NumBoundRenderTargets ||
Attribs.pDepthStencil != m_pBoundDepthStencil ||
Attribs.pShadingRateMap != m_pBoundShadingRateMap;
for (Uint32 RTIndex = 0; RTIndex < m_NumBoundRenderTargets && !RTChanged; ++RTIndex)
RTChanged = m_pBoundRenderTargets[RTIndex] != Attribs.ppRenderTargets[RTIndex];
if (RTChanged)
{
VERIFY(!m_wgpuRenderPassEncoder, "There should be no active render command encoder when pending clears mask is not zero");
EndCommandEncoders(COMMAND_ENCODER_FLAG_ALL & ~COMMAND_ENCODER_FLAG_RENDER);
CommitRenderTargets();
}
}
if (TDeviceContextBase::SetRenderTargets(Attribs) || (Attribs.NumRenderTargets == 0 && Attribs.pDepthStencil == nullptr))
{
EndCommandEncoders();
SetViewports(1, nullptr, 0, 0);
}
}
void DeviceContextWebGPUImpl::BeginRenderPass(const BeginRenderPassAttribs& Attribs)
{
TDeviceContextBase::BeginRenderPass(Attribs);
m_AttachmentClearValues.resize(Attribs.ClearValueCount);
for (Uint32 RTIndex = 0; RTIndex < Attribs.ClearValueCount; ++RTIndex)
m_AttachmentClearValues[RTIndex] = Attribs.pClearValues[RTIndex];
CommitSubpassRenderTargets();
}
void DeviceContextWebGPUImpl::NextSubpass()
{
EndCommandEncoders();
TDeviceContextBase::NextSubpass();
CommitSubpassRenderTargets();
}
void DeviceContextWebGPUImpl::EndRenderPass()
{
VERIFY(m_wgpuRenderPassEncoder, "There is no active render command encoder. Did you begin the render pass?");
EndCommandEncoders();
TDeviceContextBase::EndRenderPass();
}
void DeviceContextWebGPUImpl::Draw(const DrawAttribs& Attribs)
{
TDeviceContextBase::Draw(Attribs, 0);
#ifdef DILIGENT_DEVELOPMENT
DvpValidateCommittedShaderResources();
#endif
if (Attribs.NumVertices == 0 || Attribs.NumInstances == 0)
return;
WGPURenderPassEncoder wgpuRenderCmdEncoder = PrepareForDraw(Attribs.Flags);
wgpuRenderPassEncoderDraw(wgpuRenderCmdEncoder, Attribs.NumVertices, Attribs.NumInstances, Attribs.StartVertexLocation, Attribs.FirstInstanceLocation);
}
void DeviceContextWebGPUImpl::MultiDraw(const MultiDrawAttribs& Attribs)
{
TDeviceContextBase::MultiDraw(Attribs, 0);
#ifdef DILIGENT_DEVELOPMENT
DvpValidateCommittedShaderResources();
#endif
if (Attribs.NumInstances == 0)
return;
WGPURenderPassEncoder wgpuRenderCmdEncoder = PrepareForDraw(Attribs.Flags);
for (Uint32 DrawIdx = 0; DrawIdx < Attribs.DrawCount; ++DrawIdx)
{
const MultiDrawItem& Item = Attribs.pDrawItems[DrawIdx];
if (Item.NumVertices > 0)
wgpuRenderPassEncoderDraw(wgpuRenderCmdEncoder, Item.NumVertices, Attribs.NumInstances, Item.StartVertexLocation, Attribs.FirstInstanceLocation);
}
}
void DeviceContextWebGPUImpl::DrawIndexed(const DrawIndexedAttribs& Attribs)
{
TDeviceContextBase::DrawIndexed(Attribs, 0);
#ifdef DILIGENT_DEVELOPMENT
DvpValidateCommittedShaderResources();
#endif
if (Attribs.NumIndices == 0 || Attribs.NumInstances == 0)
return;
WGPURenderPassEncoder wgpuRenderCmdEncoder = PrepareForIndexedDraw(Attribs.Flags, Attribs.IndexType);
wgpuRenderPassEncoderDrawIndexed(wgpuRenderCmdEncoder, Attribs.NumIndices, Attribs.NumInstances, Attribs.FirstIndexLocation, Attribs.BaseVertex, Attribs.FirstInstanceLocation);
}
void DeviceContextWebGPUImpl::MultiDrawIndexed(const MultiDrawIndexedAttribs& Attribs)
{
TDeviceContextBase::MultiDrawIndexed(Attribs, 0);
#ifdef DILIGENT_DEVELOPMENT
DvpValidateCommittedShaderResources();
#endif
if (Attribs.NumInstances == 0)
return;
WGPURenderPassEncoder wgpuRenderCmdEncoder = PrepareForIndexedDraw(Attribs.Flags, Attribs.IndexType);
for (Uint32 DrawIdx = 0; DrawIdx < Attribs.DrawCount; ++DrawIdx)
{
const MultiDrawIndexedItem& Item = Attribs.pDrawItems[DrawIdx];
if (Item.NumIndices > 0)
wgpuRenderPassEncoderDrawIndexed(wgpuRenderCmdEncoder, Item.NumIndices, Attribs.NumInstances, Item.FirstIndexLocation, Item.BaseVertex, Attribs.FirstInstanceLocation);
}
}
void DeviceContextWebGPUImpl::DrawIndirect(const DrawIndirectAttribs& Attribs)
{
TDeviceContextBase::DrawIndirect(Attribs, 0);
#ifdef DILIGENT_DEVELOPMENT
DvpValidateCommittedShaderResources();
if (Attribs.pAttribsBuffer->GetDesc().Usage == USAGE_DYNAMIC)
DvpVerifyDynamicAllocation(ClassPtrCast<BufferWebGPUImpl>(Attribs.pAttribsBuffer));
#endif
WGPURenderPassEncoder wgpuRenderCmdEncoder = PrepareForDraw(Attribs.Flags);
Uint64 IndirectBufferOffset = Attribs.DrawArgsOffset;
WGPUBuffer wgpuIndirectBuffer = PrepareForIndirectCommand(Attribs.pAttribsBuffer, IndirectBufferOffset);
for (Uint32 DrawIdx = 0; DrawIdx < Attribs.DrawCount; ++DrawIdx)
{
wgpuRenderPassEncoderDrawIndirect(wgpuRenderCmdEncoder, wgpuIndirectBuffer, IndirectBufferOffset);
IndirectBufferOffset += Attribs.DrawArgsStride;
}
}
void DeviceContextWebGPUImpl::DrawIndexedIndirect(const DrawIndexedIndirectAttribs& Attribs)
{
TDeviceContextBase::DrawIndexedIndirect(Attribs, 0);
#ifdef DILIGENT_DEVELOPMENT
DvpValidateCommittedShaderResources();
if (Attribs.pAttribsBuffer->GetDesc().Usage == USAGE_DYNAMIC)
DvpVerifyDynamicAllocation(ClassPtrCast<BufferWebGPUImpl>(Attribs.pAttribsBuffer));
#endif
WGPURenderPassEncoder wgpuRenderCmdEncoder = PrepareForIndexedDraw(Attribs.Flags, Attribs.IndexType);
Uint64 IndirectBufferOffset = Attribs.DrawArgsOffset;
WGPUBuffer wgpuIndirectBuffer = PrepareForIndirectCommand(Attribs.pAttribsBuffer, IndirectBufferOffset);
for (Uint32 DrawIdx = 0; DrawIdx < Attribs.DrawCount; ++DrawIdx)
{
wgpuRenderPassEncoderDrawIndexedIndirect(wgpuRenderCmdEncoder, wgpuIndirectBuffer, IndirectBufferOffset);
IndirectBufferOffset += Attribs.DrawArgsStride;
}
}
void DeviceContextWebGPUImpl::DrawMesh(const DrawMeshAttribs& Attribs)
{
UNSUPPORTED("DrawMesh is not supported in WebGPU");
}
void DeviceContextWebGPUImpl::DrawMeshIndirect(const DrawMeshIndirectAttribs& Attribs)
{
UNSUPPORTED("DrawMeshIndirect is not supported in WebGPU");
}
void DeviceContextWebGPUImpl::DispatchCompute(const DispatchComputeAttribs& Attribs)
{
TDeviceContextBase::DispatchCompute(Attribs, 0);
#ifdef DILIGENT_DEVELOPMENT
DvpValidateCommittedShaderResources();
#endif
if (Attribs.ThreadGroupCountX == 0 || Attribs.ThreadGroupCountY == 0 || Attribs.ThreadGroupCountZ == 0)
return;
WGPUComputePassEncoder wgpuComputeCmdEncoder = PrepareForDispatchCompute();
wgpuComputePassEncoderDispatchWorkgroups(wgpuComputeCmdEncoder, Attribs.ThreadGroupCountX, Attribs.ThreadGroupCountY, Attribs.ThreadGroupCountZ);
}
void DeviceContextWebGPUImpl::DispatchComputeIndirect(const DispatchComputeIndirectAttribs& Attribs)
{
TDeviceContextBase::DispatchComputeIndirect(Attribs, 0);
#ifdef DILIGENT_DEVELOPMENT
DvpValidateCommittedShaderResources();
if (Attribs.pAttribsBuffer->GetDesc().Usage == USAGE_DYNAMIC)
DvpVerifyDynamicAllocation(ClassPtrCast<BufferWebGPUImpl>(Attribs.pAttribsBuffer));
#endif
WGPUComputePassEncoder wgpuComputeCmdEncoder = PrepareForDispatchCompute();
Uint64 IndirectBufferOffset = Attribs.DispatchArgsByteOffset;
WGPUBuffer wgpuIndirectBuffer = PrepareForIndirectCommand(Attribs.pAttribsBuffer, IndirectBufferOffset);
wgpuComputePassEncoderDispatchWorkgroupsIndirect(wgpuComputeCmdEncoder, wgpuIndirectBuffer, IndirectBufferOffset);
}
void DeviceContextWebGPUImpl::ClearDepthStencil(ITextureView* pView,
CLEAR_DEPTH_STENCIL_FLAGS ClearFlags,
float Depth,
Uint8 Stencil,
RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)
{
TDeviceContextBase::ClearDepthStencil(pView);
if (pView != m_pBoundDepthStencil)
{
LOG_ERROR_MESSAGE("Depth stencil buffer must be bound to the context to be cleared in WebGPU backend");
return;
}
if (m_wgpuRenderPassEncoder)
ClearAttachment(-1, COLOR_MASK_NONE, ClearFlags, &Depth, Stencil);
else
{
if (ClearFlags & CLEAR_DEPTH_FLAG)
m_PendingClears.SetDepth(Depth);
if (ClearFlags & CLEAR_STENCIL_FLAG)
m_PendingClears.SetStencil(Stencil);
}
}
void DeviceContextWebGPUImpl::ClearRenderTarget(ITextureView* pView,
const void* RGBA,
RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)
{
TDeviceContextBase::ClearRenderTarget(pView);
static constexpr float Zero[4] = {0.f, 0.f, 0.f, 0.f};
if (RGBA == nullptr)
RGBA = Zero;
Int32 RTIndex = -1;
for (Uint32 Index = 0; Index < m_NumBoundRenderTargets; ++Index)
{
if (m_pBoundRenderTargets[Index] == pView)
{
RTIndex = static_cast<Int32>(Index);
break;
}
}
if (RTIndex == -1)
{
LOG_ERROR_MESSAGE("Render target must be bound to the context to be cleared in WebGPU backend");
return;
}
if (m_wgpuRenderPassEncoder)
ClearAttachment(RTIndex, COLOR_MASK_ALL, CLEAR_DEPTH_FLAG_NONE, static_cast<const float*>(RGBA), 0);
else
m_PendingClears.SetColor(RTIndex, static_cast<const float*>(RGBA));
}
void DeviceContextWebGPUImpl::UpdateBuffer(IBuffer* pBuffer,
Uint64 Offset,
Uint64 Size,
const void* pData,
RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)
{
TDeviceContextBase::UpdateBuffer(pBuffer, Offset, Size, pData, StateTransitionMode);
EndCommandEncoders();
BufferWebGPUImpl* const pBufferWebGPU = ClassPtrCast<BufferWebGPUImpl>(pBuffer);
const BufferDesc& BuffDesc = pBufferWebGPU->GetDesc();
if (BuffDesc.Usage == USAGE_DEFAULT)
{
const UploadMemoryManagerWebGPU::Allocation UploadAlloc = AllocateUploadMemory(StaticCast<size_t>(Size));
if (!UploadAlloc)
{
LOG_ERROR("Failed to allocate upload memory for buffer update");
return;
}
// The data will be flushed to GPU before the command buffer is submitted to the queue in Flush()
memcpy(UploadAlloc.pData, pData, StaticCast<size_t>(Size));
wgpuCommandEncoderCopyBufferToBuffer(GetCommandEncoder(), UploadAlloc.wgpuBuffer, UploadAlloc.Offset,
pBufferWebGPU->m_wgpuBuffer, Offset, Size);
}
else
{
LOG_ERROR_MESSAGE(GetUsageString(BuffDesc.Usage), " buffers can't be updated using UpdateBuffer method");
}
}
void DeviceContextWebGPUImpl::CopyBuffer(IBuffer* pSrcBuffer,
Uint64 SrcOffset,
RESOURCE_STATE_TRANSITION_MODE SrcBufferTransitionMode,
IBuffer* pDstBuffer,
Uint64 DstOffset,
Uint64 Size,
RESOURCE_STATE_TRANSITION_MODE DstBufferTransitionMode)
{
TDeviceContextBase::CopyBuffer(pSrcBuffer, SrcOffset, SrcBufferTransitionMode, pDstBuffer, DstOffset, Size, DstBufferTransitionMode);
EndCommandEncoders();
BufferWebGPUImpl* const pSrcBufferWebGPU = ClassPtrCast<BufferWebGPUImpl>(pSrcBuffer);
BufferWebGPUImpl* const pDstBufferWebGPU = ClassPtrCast<BufferWebGPUImpl>(pDstBuffer);
const BufferDesc& SrcDesc = pSrcBufferWebGPU->GetDesc();
const BufferDesc& DstDesc = pDstBufferWebGPU->GetDesc();
if (SrcDesc.Usage != USAGE_STAGING && DstDesc.Usage != USAGE_STAGING)
{
WGPUBuffer wgpuSrcBuffer = pSrcBufferWebGPU->m_wgpuBuffer;
WGPUBuffer wgpuDstBuffer = pDstBufferWebGPU->m_wgpuBuffer;
if (wgpuSrcBuffer == nullptr)
{
VERIFY_EXPR(SrcDesc.Usage == USAGE_DYNAMIC);
const DynamicMemoryManagerWebGPU::Allocation& DynAlloc = GetDynamicBufferAllocation(pSrcBufferWebGPU);
wgpuSrcBuffer = DynAlloc.wgpuBuffer;
SrcOffset += DynAlloc.Offset;
}
wgpuCommandEncoderCopyBufferToBuffer(GetCommandEncoder(), wgpuSrcBuffer, SrcOffset, wgpuDstBuffer, DstOffset, Size);
}
else if (SrcDesc.Usage == USAGE_STAGING && DstDesc.Usage != USAGE_STAGING)
{
WebGPUResourceBase::StagingBufferInfo* pSrcStagingBuffer = pSrcBufferWebGPU->GetStagingBuffer();
if (pSrcStagingBuffer == nullptr)
{
DEV_ERROR("Unable to get staging buffer info from the source buffer");
return;
}
WGPUBuffer wgpuDstBuffer = pDstBufferWebGPU->m_wgpuBuffer;
WGPUBuffer wgpuSrcBuffer = pSrcStagingBuffer->wgpuBuffer;
wgpuCommandEncoderCopyBufferToBuffer(GetCommandEncoder(), wgpuSrcBuffer, SrcOffset, wgpuDstBuffer, DstOffset, Size);
m_PendingStagingWrites.emplace(pSrcStagingBuffer, RefCntAutoPtr<IObject>{pSrcBufferWebGPU});
}
else if (SrcDesc.Usage != USAGE_STAGING && DstDesc.Usage == USAGE_STAGING)
{
WebGPUResourceBase::StagingBufferInfo* pDstStagingBuffer = pDstBufferWebGPU->GetStagingBuffer();
if (pDstStagingBuffer == nullptr)
{
DEV_ERROR("Unable to get staging buffer info from the destination buffer");
return;
}
WGPUBuffer wgpuSrcBuffer = pSrcBufferWebGPU->m_wgpuBuffer.Get();
WGPUBuffer wgpuDstBuffer = pDstStagingBuffer->wgpuBuffer;
if (wgpuSrcBuffer == nullptr)
{
VERIFY_EXPR(SrcDesc.Usage == USAGE_DYNAMIC);
const DynamicMemoryManagerWebGPU::Allocation& DynAlloc = GetDynamicBufferAllocation(pSrcBufferWebGPU);
wgpuSrcBuffer = DynAlloc.wgpuBuffer;
SrcOffset += DynAlloc.Offset;
}
wgpuCommandEncoderCopyBufferToBuffer(GetCommandEncoder(), wgpuSrcBuffer, SrcOffset, wgpuDstBuffer, DstOffset, Size);
m_PendingStagingReads.emplace(pDstStagingBuffer, RefCntAutoPtr<IObject>{pDstBufferWebGPU});
}
else
{
UNSUPPORTED("Copying data between staging buffers is not supported and is likely not want you really want to do");
}
}
void DeviceContextWebGPUImpl::MapBuffer(IBuffer* pBuffer,
MAP_TYPE MapType,
MAP_FLAGS MapFlags,
PVoid& pMappedData)
{
TDeviceContextBase::MapBuffer(pBuffer, MapType, MapFlags, pMappedData);
BufferWebGPUImpl* const pBufferWebGPU = ClassPtrCast<BufferWebGPUImpl>(pBuffer);
const BufferDesc& BuffDesc = pBufferWebGPU->GetDesc();
if (MapType == MAP_READ)
{
DEV_CHECK_ERR(BuffDesc.Usage == USAGE_STAGING, "Buffer must be created as USAGE_STAGING to be mapped for reading");
if ((MapFlags & MAP_FLAG_DO_NOT_WAIT) == 0)
{
LOG_WARNING_MESSAGE("WebGPU backend never waits for GPU when mapping staging buffers for reading. "
"Applications must use fences or other synchronization methods to explicitly synchronize "
"access and use MAP_FLAG_DO_NOT_WAIT flag.");
}
pMappedData = pBufferWebGPU->Map(MapType);
}
else if (MapType == MAP_WRITE)
{
if (BuffDesc.Usage == USAGE_STAGING)
{
pMappedData = pBufferWebGPU->Map(MapType);
}
else if (BuffDesc.Usage == USAGE_DYNAMIC)
{
const Uint32 DynamicBufferId = pBufferWebGPU->GetDynamicBufferId();
VERIFY(DynamicBufferId != ~0u, "Dynamic buffer '", BuffDesc.Name, "' does not have dynamic buffer ID");
if (m_MappedBuffers.size() <= DynamicBufferId)
m_MappedBuffers.resize(DynamicBufferId + 1);
DynamicMemoryManagerWebGPU::Allocation& DynAllocation = m_MappedBuffers[DynamicBufferId].Allocation;
#ifdef DILIGENT_DEVELOPMENT
m_MappedBuffers[DynamicBufferId].DvpBufferUID = pBufferWebGPU->GetUniqueID();
#endif
if ((MapFlags & MAP_FLAG_DISCARD) != 0 || !DynAllocation)
{
DynAllocation = AllocateDynamicMemory(StaticCast<size_t>(BuffDesc.Size), pBufferWebGPU->GetAlignment());
if (!DynAllocation)
{
LOG_ERROR("Failed to allocate dynamic memory for buffer mapping. Try increasing the size of the dynamic heap in engine EngineWebGPUCreateInfo");
return;
}
pMappedData = DynAllocation.pData;
}
else
{
if (pBufferWebGPU->m_wgpuBuffer != nullptr)
{
LOG_ERROR("Formatted or structured buffers require actual WebGPU backing resource and cannot be suballocated "
"from dynamic heap. In current implementation, the entire contents of the backing buffer is updated when the buffer is unmapped. "
"As a consequence, the buffer cannot be mapped with MAP_FLAG_NO_OVERWRITE flag because updating the whole "
"buffer will overwrite regions that may still be in use by the GPU.");
return;
}
pMappedData = DynAllocation.pData;
}
}
else
{
LOG_ERROR("Only USAGE_DYNAMIC or USAGE_STAGING WebGPU buffers can be mapped for writing");
}
}
else if (MapType == MAP_READ_WRITE)
{
LOG_ERROR("MAP_READ_WRITE is not supported in WebGPU backend");
}
else
{
UNEXPECTED("Unknown map type");
}
}
void DeviceContextWebGPUImpl::UnmapBuffer(IBuffer* pBuffer, MAP_TYPE MapType)
{
TDeviceContextBase::UnmapBuffer(pBuffer, MapType);
BufferWebGPUImpl* const pBufferWebGPU = ClassPtrCast<BufferWebGPUImpl>(pBuffer);
const BufferDesc& BuffDesc = pBufferWebGPU->GetDesc();
if (MapType == MAP_READ)
{
pBufferWebGPU->Unmap();
}
else if (MapType == MAP_WRITE)
{
if (BuffDesc.Usage == USAGE_STAGING)
{
pBufferWebGPU->Unmap();
}
else if (BuffDesc.Usage == USAGE_DYNAMIC)
{
if (WGPUBuffer wgpuBuffer = pBufferWebGPU->m_wgpuBuffer)
{
DEV_CHECK_ERR(!m_pActiveRenderPass,
"Unmapping dynamic buffer with backing WebGPU resource requires "
"copying the data from shared memory to private storage. This can only be "
"done by blit encoder outside of render pass.");
const DynamicMemoryManagerWebGPU::Allocation& DynAllocation = GetDynamicBufferAllocation(pBufferWebGPU);
EndCommandEncoders();
wgpuCommandEncoderCopyBufferToBuffer(GetCommandEncoder(), DynAllocation.wgpuBuffer, DynAllocation.Offset, wgpuBuffer, 0, BuffDesc.Size);
}
}
else
{
LOG_ERROR("Only USAGE_DYNAMIC, USAGE_STAGING WebGPU buffers can be mapped for writing");
}
}
}
#ifdef DILIGENT_DEVELOPMENT
void DeviceContextWebGPUImpl::DvpVerifyDynamicAllocation(const BufferWebGPUImpl* pBuffer) const
{
VERIFY_EXPR(pBuffer != nullptr);
if (pBuffer->m_wgpuBuffer != nullptr)
return;
const BufferDesc& BuffDesc = pBuffer->GetDesc();
VERIFY_EXPR(BuffDesc.Usage == USAGE_DYNAMIC);
const Uint32 DynamicBufferId = pBuffer->GetDynamicBufferId();
VERIFY(DynamicBufferId != ~0u, "Dynamic buffer '", pBuffer->GetDesc().Name, "' does not have dynamic buffer ID");
if (DynamicBufferId >= m_MappedBuffers.size())
{
DEV_ERROR("Dynamic buffer '", BuffDesc.Name, "' has not been mapped. Note: memory for dynamic buffers is allocated when a buffer is mapped.");
return;
}
const MappedBuffer& MappedBuff = m_MappedBuffers[DynamicBufferId];
DEV_CHECK_ERR(MappedBuff.Allocation, "Dynamic buffer '", BuffDesc.Name, "' has not been mapped before its first use. Context Id: ", GetContextId(),
". Note: memory for dynamic buffers is allocated when a buffer is mapped.");
DEV_CHECK_ERR(MappedBuff.Allocation.dvpFrameNumber == GetFrameNumber(), "Dynamic allocation of dynamic buffer '", BuffDesc.Name, "' in frame ", GetFrameNumber(),
" is out-of-date. Note: contents of all dynamic resources is discarded at the end of every frame. A buffer must be mapped before its first use in any frame.");
DEV_CHECK_ERR(MappedBuff.DvpBufferUID == pBuffer->GetUniqueID(), "Dynamic buffer ID mismatch. Buffer '", BuffDesc.Name, "' has ID ", pBuffer->GetUniqueID(), " but the ID of the mapped buffer is ",
MappedBuff.DvpBufferUID, ". This indicates that dynamic space has been reassigned to a different buffer, which has not been mapped.");
}
#endif
const DynamicMemoryManagerWebGPU::Allocation& DeviceContextWebGPUImpl::GetDynamicBufferAllocation(const BufferWebGPUImpl* pBuffer) const
{
VERIFY_EXPR(pBuffer->GetDesc().Usage == USAGE_DYNAMIC);
const Uint32 DynamicBufferId = pBuffer->GetDynamicBufferId();
VERIFY(DynamicBufferId != ~0u, "Dynamic buffer '", pBuffer->GetDesc().Name, "' does not have dynamic buffer ID");
DEV_CHECK_ERR(DynamicBufferId < m_MappedBuffers.size(), "Buffer '", pBuffer->GetDesc().Name, "' has not been mapped in this context");
static DynamicMemoryManagerWebGPU::Allocation NullAllocation;
return DynamicBufferId < m_MappedBuffers.size() ? m_MappedBuffers[DynamicBufferId].Allocation : NullAllocation;
}
Uint64 DeviceContextWebGPUImpl::GetDynamicBufferOffset(const BufferWebGPUImpl* pBuffer, bool VerifyAllocation) const
{
VERIFY_EXPR(pBuffer != nullptr);
if (pBuffer->m_wgpuBuffer != nullptr)
return 0;
#ifdef DILIGENT_DEVELOPMENT
if (VerifyAllocation)
{
DvpVerifyDynamicAllocation(pBuffer);
}
#endif
const Uint32 DynamicBufferId = pBuffer->GetDynamicBufferId();
VERIFY(DynamicBufferId != ~0u, "Dynamic buffer '", pBuffer->GetDesc().Name, "' does not have dynamic buffer ID");
return DynamicBufferId < m_MappedBuffers.size() ?
m_MappedBuffers[DynamicBufferId].Allocation.Offset :
0;
}
void DeviceContextWebGPUImpl::UpdateTexture(ITexture* pTexture,
Uint32 MipLevel,
Uint32 Slice,
const Box& DstBox,
const TextureSubResData& SubresData,
RESOURCE_STATE_TRANSITION_MODE SrcBufferStateTransitionMode,
RESOURCE_STATE_TRANSITION_MODE DstTextureStateTransitionMode)
{
TDeviceContextBase::UpdateTexture(pTexture, MipLevel, Slice, DstBox, SubresData, SrcBufferStateTransitionMode, DstTextureStateTransitionMode);
EndCommandEncoders();
if (SubresData.pSrcBuffer != nullptr)
{
TextureWebGPUImpl* const pDstTextureWebGPU = ClassPtrCast<TextureWebGPUImpl>(pTexture);
BufferWebGPUImpl* const pSrcBufferWebGPU = ClassPtrCast<BufferWebGPUImpl>(SubresData.pSrcBuffer);
const BufferDesc& SrcBuffDesc = pSrcBufferWebGPU->GetDesc();
WGPUImageCopyTexture wgpuImageCopyDst{};
wgpuImageCopyDst.texture = pDstTextureWebGPU->GetWebGPUTexture();
wgpuImageCopyDst.aspect = WGPUTextureAspect_All;
wgpuImageCopyDst.origin.x = DstBox.MinX;
wgpuImageCopyDst.origin.y = DstBox.MinY;
wgpuImageCopyDst.origin.z = Slice != 0 ? Slice : DstBox.MinZ;
wgpuImageCopyDst.mipLevel = MipLevel;
const TextureFormatAttribs& FmtAttribs = GetTextureFormatAttribs(pDstTextureWebGPU->GetDesc().Format);
WGPUExtent3D wgpuCopySize{};
wgpuCopySize.width = DstBox.Width();
wgpuCopySize.height = DstBox.Height();
wgpuCopySize.depthOrArrayLayers = DstBox.Depth();
if (FmtAttribs.ComponentType == COMPONENT_TYPE_COMPRESSED)
{
wgpuCopySize.width = AlignUp(wgpuCopySize.width, FmtAttribs.BlockWidth);
wgpuCopySize.height = AlignUp(wgpuCopySize.height, FmtAttribs.BlockHeight);
}
WebGPUResourceBase::StagingBufferInfo* pSrcStagingBuffer = nullptr;
if (SrcBuffDesc.Usage == USAGE_STAGING)
{
pSrcStagingBuffer = pSrcBufferWebGPU->GetStagingBuffer();
if (pSrcStagingBuffer == nullptr)
{
DEV_ERROR("Unable to get staging buffer info from the source buffer");
return;
}
}
WGPUImageCopyBuffer wgpuImageCopySrc{};
wgpuImageCopySrc.buffer = pSrcStagingBuffer != nullptr ? pSrcStagingBuffer->wgpuBuffer : pSrcBufferWebGPU->GetWebGPUBuffer();
wgpuImageCopySrc.layout.offset = SubresData.SrcOffset;
wgpuImageCopySrc.layout.bytesPerRow = static_cast<Uint32>(SubresData.Stride);
wgpuImageCopySrc.layout.rowsPerImage = wgpuCopySize.height;
wgpuCommandEncoderCopyBufferToTexture(GetCommandEncoder(), &wgpuImageCopySrc, &wgpuImageCopyDst, &wgpuCopySize);
if (pSrcStagingBuffer != nullptr)
{
m_PendingStagingWrites.emplace(pSrcStagingBuffer, RefCntAutoPtr<IObject>{pSrcBufferWebGPU});
}
}
else
{
TextureWebGPUImpl* const pTextureWebGPU = ClassPtrCast<TextureWebGPUImpl>(pTexture);
const TextureDesc& TexDesc = pTextureWebGPU->GetDesc();
const BufferToTextureCopyInfo CopyInfo = GetBufferToTextureCopyInfo(TexDesc.Format, DstBox, TextureWebGPUImpl::ImageCopyBufferRowAlignment);
const UploadMemoryManagerWebGPU::Allocation UploadAlloc = AllocateUploadMemory(StaticCast<size_t>(CopyInfo.MemorySize));
if (!UploadAlloc)
{
LOG_ERROR("Failed to allocate upload memory for texture update");
return;
}
for (Uint32 LayerIdx = 0; LayerIdx < CopyInfo.Region.Depth(); ++LayerIdx)
{
for (Uint32 RawIdx = 0; RawIdx < CopyInfo.RowCount; ++RawIdx)
{
const Uint64 SrcOffset = RawIdx * SubresData.Stride + LayerIdx * SubresData.DepthStride;
const Uint64 DstOffset = RawIdx * CopyInfo.RowStride + LayerIdx * CopyInfo.DepthStride;
memcpy(UploadAlloc.pData + DstOffset, static_cast<const uint8_t*>(SubresData.pData) + SrcOffset, StaticCast<size_t>(CopyInfo.RowSize));
}
}
WGPUImageCopyBuffer wgpuImageCopySrc{};
wgpuImageCopySrc.buffer = UploadAlloc.wgpuBuffer;
wgpuImageCopySrc.layout.offset = UploadAlloc.Offset;
wgpuImageCopySrc.layout.bytesPerRow = static_cast<Uint32>(CopyInfo.RowStride);
wgpuImageCopySrc.layout.rowsPerImage = static_cast<Uint32>(CopyInfo.DepthStride / CopyInfo.RowStride);
WGPUImageCopyTexture wgpuImageCopyDst{};
wgpuImageCopyDst.texture = pTextureWebGPU->GetWebGPUTexture();
wgpuImageCopyDst.aspect = WGPUTextureAspect_All;
wgpuImageCopyDst.origin.x = DstBox.MinX;
wgpuImageCopyDst.origin.y = DstBox.MinY;
wgpuImageCopyDst.origin.z = Slice != 0 ? Slice : DstBox.MinZ;
wgpuImageCopyDst.mipLevel = MipLevel;
const TextureFormatAttribs& FmtAttribs = GetTextureFormatAttribs(TexDesc.Format);