forked from stride3d/stride
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCommandList.Vulkan.cs
More file actions
1852 lines (1591 loc) · 100 KB
/
Copy pathCommandList.Vulkan.cs
File metadata and controls
1852 lines (1591 loc) · 100 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 (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
#if STRIDE_GRAPHICS_API_VULKAN
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Stride.Core;
using Stride.Core.Collections;
using Stride.Core.Mathematics;
using Vortice.Vulkan;
using static Vortice.Vulkan.Vulkan;
namespace Stride.Graphics
{
public partial class CommandList
{
/// <summary>
/// Unique ID for this command list, incremented on each Reset.
/// Used to detect when a resource is first used on a different command list,
/// requiring barriers to be re-issued even if the layout already matches.
/// </summary>
internal int CommandListId;
internal CommandBufferPool CommandBufferPool;
private PipelineState activePipeline;
private bool pipelineDirty = true;
// Per-CB layout state. Stride's per-Texture NativeLayout is a single shared field mutated
// by every CB's ResourceBarrierTransition calls in arbitrary order, which disagrees with
// Vulkan's per-execution-order layout tracking when CBs record concurrently. This map
// remembers what layout THIS CB believes each texture holds for the draws it records.
// Cleared on Reset. The first touch of a texture in a CB still falls back to NativeLayout —
// that's a known limitation to be addressed by adding a "last-submitted layout" tracker.
private readonly Dictionary<Texture, BarrierLayout> currentCbLayouts = new();
// Dynamic rendering state: whether a render pass instance (vkCmdBeginRendering) is active,
// whether the bound attachments changed since it began, and which depth layout it declared.
private bool activeRendering;
private bool renderingDirty = true;
private bool activeDepthReadOnly;
private VkDescriptorPool descriptorPool;
private VkDescriptorSet descriptorSet;
private uint[] allocatedTypeCounts;
private uint allocatedSetCount;
private uint? activeStencilReference = 0;
private CompiledCommandList currentCommandList;
public static CommandList New(GraphicsDevice device)
{
return new CommandList(device);
}
private CommandList(GraphicsDevice device) : base(device)
{
Recreate();
}
private void Recreate()
{
CommandBufferPool = new CommandBufferPool(GraphicsDevice, false);
descriptorPool = GraphicsDevice.DescriptorPools.GetObject(GraphicsDevice.CommandListFence.GetCompletedValue());
allocatedTypeCounts = new uint[DescriptorSetLayout.DescriptorTypeCount];
allocatedSetCount = 0;
Reset();
}
/// <summary>
/// Resets a Command List back to its initial state as if a new Command List was just created.
/// </summary>
public unsafe partial void Reset()
{
if (currentCommandList.Builder != null)
return;
// New command list ID so resources know they need to re-issue barriers
CommandListId = System.Threading.Interlocked.Increment(ref GraphicsDevice.NextCommandListId);
DebugScopeResetForNewRecording();
CleanupRenderPass();
boundDescriptorSets.Clear();
currentCbLayouts.Clear();
renderingDirty = true;
currentCommandList.Builder = this;
currentCommandList.NativeCommandBuffer = CommandBufferPool.GetObject(GraphicsDevice.CommandListFence.GetCompletedValue());
currentCommandList.DescriptorPools = GraphicsDevice.DescriptorPoolLists.Acquire();
currentCommandList.StagingResources = GraphicsDevice.StagingResourceLists.Acquire();
var beginInfo = new VkCommandBufferBeginInfo
{
sType = VkStructureType.CommandBufferBeginInfo,
flags = VkCommandBufferUsageFlags.OneTimeSubmit
};
GraphicsDevice.NativeDeviceApi.vkBeginCommandBuffer(currentCommandList.NativeCommandBuffer, &beginInfo);
pipelineDirty = true;
viewportDirty = true;
scissorsDirty = true;
activeStencilReference = null;
}
/// <summary>
/// Indicates that recording to the Command List has finished.
/// </summary>
/// <returns>
/// A <see cref="CompiledCommandList"/> representing the frozen list of recorded commands
/// that can be executed at a later time.
/// </returns>
public partial CompiledCommandList Close()
{
// End active render pass
CleanupRenderPass();
// Close
GraphicsDevice.CheckResult(GraphicsDevice.NativeDeviceApi.vkEndCommandBuffer(currentCommandList.NativeCommandBuffer));
// Staging resources not updated anymore
foreach (var stagingResource in currentCommandList.StagingResources)
{
stagingResource.UpdatingCommandList = null;
}
activePipeline = null;
var result = currentCommandList;
currentCommandList = default;
return result;
}
/// <summary>
/// Closes and executes the Command List.
/// </summary>
public partial void Flush()
{
GraphicsDevice.ExecuteCommandList(Close());
}
private unsafe void FlushInternal(bool wait)
{
var commandListFenceValue = GraphicsDevice.ExecuteCommandListInternal(Close());
if (wait)
GraphicsDevice.CommandListFence.WaitForFenceCPUInternal(commandListFenceValue);
Reset();
}
/// <summary>
/// Vulkan-specific implementation that clears and restores the state of the Graphics Device.
/// </summary>
private partial void ClearStateImpl()
{
}
/// <summary>
/// Unbinds all depth-stencil buffer and render targets from the output-merger stage.
/// </summary>
private void ResetTargetsImpl()
{
}
/// <summary>
/// Binds a depth-stencil buffer and a set of render targets to the output-merger stage. See <see cref="Textures+and+render+targets"/> to learn how to use it.
/// </summary>
/// <param name="depthStencilBuffer">The depth stencil buffer.</param>
/// <param name="renderTargets">The render targets.</param>
/// <exception cref="ArgumentNullException">renderTargetViews</exception>
private partial void SetRenderTargetsImpl(Texture depthStencilBuffer, ReadOnlySpan<Texture> renderTargets)
{
// The base class updated the bound targets; the next draw restarts the render pass
// instance with them if they changed
renderingDirty = true;
}
/// <summary>
/// Sets the stream targets.
/// </summary>
/// <param name="buffers">The buffers.</param>
public void SetStreamTargets(params Buffer[] buffers)
{
}
private unsafe void BindPipeline()
{
if (!pipelineDirty)
return;
GraphicsDevice.NativeDeviceApi.vkCmdBindPipeline(currentCommandList.NativeCommandBuffer, activePipeline.IsCompute ? VkPipelineBindPoint.Compute : VkPipelineBindPoint.Graphics, activePipeline.NativePipeline);
}
/// <summary>
/// Gets or sets the 1st viewport. See <see cref="Render+states"/> to learn how to use it.
/// </summary>
/// <value>The viewport.</value>
private unsafe void SetViewportImpl()
{
if (!viewportDirty && !scissorsDirty)
return;
//// TODO D3D12 Hardcoded for one viewport
var viewportCopy = Viewport;
if (activePipeline?.Description.RasterizerState.ScissorTestEnable ?? false)
{
if (scissorsDirty)
{
// Use manual scissor
var scissor = scissors[0];
var nativeScissor = new VkRect2D(scissor.Left, scissor.Top, (uint)scissor.Width, (uint)scissor.Height);
GraphicsDevice.NativeDeviceApi.vkCmdSetScissor(currentCommandList.NativeCommandBuffer, firstScissor: 0, scissorCount: 1, &nativeScissor);
}
}
else
{
// Use viewport
// Always update, because either scissor or viewport was dirty and we use viewport size
var scissor = new VkRect2D((int) viewportCopy.X, (int) viewportCopy.Y, (uint) viewportCopy.Width, (uint) viewportCopy.Height);
GraphicsDevice.NativeDeviceApi.vkCmdSetScissor(currentCommandList.NativeCommandBuffer, firstScissor: 0, scissorCount: 1, &scissor);
}
scissorsDirty = false;
// Since Vulkan 1.1, we can use negative viewport instead of doing gl_Position.y = -gl_Position.y in the shader
// Note: we mutate viewportCopy _after_ vkCmdSetScissor has been called
viewportCopy.Y = viewportCopy.Y + viewportCopy.Height;
viewportCopy.Height = -viewportCopy.Height;
if (viewportDirty)
{
GraphicsDevice.NativeDeviceApi.vkCmdSetViewport(currentCommandList.NativeCommandBuffer, firstViewport: 0, viewportCount: 1, (VkViewport*)&viewportCopy);
viewportDirty = false;
}
}
/// <summary>
/// Unsets the render targets.
/// </summary>
public void UnsetRenderTargets()
{
}
/// <summary>
/// Vulkan implementation that sets a scissor rectangle to the rasterizer stage.
/// </summary>
/// <param name="scissorRectangle">The scissor rectangle to set.</param>
private unsafe partial void SetScissorRectangleImpl(ref readonly Rectangle scissorRectangle)
{
// Do nothing. Vulkan already sets the scissor rectangle as part of PrepareDraw()
}
/// <summary>
/// Vulkan implementation that sets one or more scissor rectangles to the rasterizer stage.
/// </summary>
/// <param name="scissorCount">The number of scissor rectangles to bind.</param>
/// <param name="scissorRectangles">The set of scissor rectangles to bind.</param>
private unsafe partial void SetScissorRectanglesImpl(ReadOnlySpan<Rectangle> scissorRectangles)
{
// Do nothing. Vulkan already sets the scissor rectangles as part of PrepareDraw()
}
/// <summary>
/// Prepares a draw call. This method is called before each Draw() method to setup the correct Primitive, InputLayout and VertexBuffers.
/// </summary>
/// <exception cref="InvalidOperationException">Cannot GraphicsDevice.Draw*() without an effect being previously applied with Effect.Apply() method</exception>
private unsafe void PrepareDraw()
{
RecordDebugCounter(DebugCounterKind.Draw);
// Transition resources to correct layouts before starting the render pass
TransitionBoundResources();
// Lazily set the render pass and frame buffer
EnsureRenderPass();
BindPipeline();
BindDescriptorSets();
SetViewportImpl();
GraphicsDevice.NativeDeviceApi.vkCmdSetStencilReference(currentCommandList.NativeCommandBuffer, VkStencilFaceFlags.FrontAndBack, activeStencilReference ?? 0);
}
/// <summary>
/// Automatically transitions bound textures to the layouts expected by the pipeline:
/// render targets to ColorAttachmentOptimal, depth to DepthStencilAttachmentOptimal,
/// sampled images to ShaderReadOnlyOptimal, storage images to General.
/// Must be called BEFORE EnsureRenderPass since barriers cannot be issued inside a render pass.
/// </summary>
private void TransitionBoundResources()
{
if (activePipeline == null)
return;
// Transition render target attachments.
for (int i = 0; i < RenderTargetCount; i++)
{
var rt = renderTargets[i];
if (rt != null)
{
var parent = rt.ParentTexture ?? rt;
if (!currentCbLayouts.TryGetValue(parent, out var current) || current != BarrierLayout.RenderTarget)
ResourceBarrierTransition(rt, BarrierLayout.RenderTarget);
}
}
// If the pipeline disables depth+stencil writes the depth attachment can ride in
// DepthStencilReadOnlyOptimal — matching the attachment layout EnsureRenderPass declares
// and leaving the image sampleable (soft-edge particles).
var dss = activePipeline.Description.DepthStencilState;
bool depthReadOnly = !dss.DepthBufferWriteEnable
&& (!dss.StencilEnable || dss.StencilWriteMask == 0);
var depthAttachmentLayout = depthReadOnly
? VkImageLayout.DepthStencilReadOnlyOptimal
: VkImageLayout.DepthStencilAttachmentOptimal;
var depthAttachmentBarrier = depthReadOnly
? BarrierLayout.DepthStencilRead
: BarrierLayout.DepthStencilWrite;
Texture depthParent = null;
if (depthStencilBuffer != null)
{
depthParent = depthStencilBuffer.ParentTexture ?? depthStencilBuffer;
if (!currentCbLayouts.TryGetValue(depthParent, out var currentDepth) || currentDepth != depthAttachmentBarrier)
ResourceBarrierTransition(depthStencilBuffer, depthAttachmentBarrier);
}
// Transition sampled/storage textures bound in descriptors
var bindingCount = activePipeline.DescriptorBindingMapping.Count;
for (int index = 0; index < bindingCount; index++)
{
var mapping = activePipeline.DescriptorBindingMapping[index];
if (mapping.DescriptorType != VkDescriptorType.SampledImage &&
mapping.DescriptorType != VkDescriptorType.StorageImage)
continue;
var sourceSet = boundDescriptorSets[mapping.SourceSet];
var heapObject = sourceSet.HeapObjects[sourceSet.DescriptorStartOffset + mapping.SourceBinding];
if (heapObject.Value is Texture texture)
{
var parent = texture.ParentTexture ?? texture;
// Don't transition swapchain images that are queued for presentation
if (parent.NativeLayout == VkImageLayout.PresentSrcKHR)
continue;
// Skip if this sampled image is the currently bound read-only depth buffer:
// DepthStencilReadOnlyOptimal is already valid for shader reads and moving it
// to ShaderReadOnlyOptimal would break the render pass's attachment layout.
if (depthReadOnly && depthParent != null && parent == depthParent
&& mapping.DescriptorType == VkDescriptorType.SampledImage)
continue;
// Always call ResourceBarrierTransition — even if the layout matches, the barrier
// must be re-issued when the resource was last transitioned by a different command list.
var layout = mapping.DescriptorType == VkDescriptorType.SampledImage
? BarrierLayout.ShaderResource
: BarrierLayout.UnorderedAccess;
ResourceBarrierTransition(parent, layout);
}
}
}
private unsafe void BindDescriptorSets()
{
// Keep track of descriptor pool usage
bool isPoolExhausted = ++allocatedSetCount > GraphicsDevice.MaxDescriptorSetCount;
for (int i = 0; i < DescriptorSetLayout.DescriptorTypeCount; i++)
{
allocatedTypeCounts[i] += activePipeline.DescriptorTypeCounts[i];
if (allocatedTypeCounts[i] > GraphicsDevice.MaxDescriptorTypeCounts[i])
{
isPoolExhausted = true;
break;
}
}
if (isPoolExhausted)
{
// Retrieve a new pool
currentCommandList.DescriptorPools.Add(descriptorPool);
descriptorPool = GraphicsDevice.DescriptorPools.GetObject(GraphicsDevice.CommandListFence.GetCompletedValue());
allocatedSetCount = 1;
for (int i = 0; i < DescriptorSetLayout.DescriptorTypeCount; i++)
{
allocatedTypeCounts[i] = activePipeline.DescriptorTypeCounts[i];
}
}
// Allocate descriptor set
var nativeDescriptorSetLayout = activePipeline.NativeDescriptorSetLayout;
var allocateInfo = new VkDescriptorSetAllocateInfo
{
sType = VkStructureType.DescriptorSetAllocateInfo,
descriptorPool = descriptorPool,
descriptorSetCount = 1,
pSetLayouts = &nativeDescriptorSetLayout
};
VkDescriptorSet localDescriptorSet;
GraphicsDevice.NativeDeviceApi.vkAllocateDescriptorSets(GraphicsDevice.NativeDevice, &allocateInfo, &localDescriptorSet);
descriptorSet = localDescriptorSet;
#if !STRIDE_GRAPHICS_NO_DESCRIPTOR_COPIES
copies.Clear(true);
foreach (var mapping in activePipeline.DescriptorBindingMapping)
{
copies.Add(new VkCopyDescriptorSet
{
sType = VkStructureType.CopyDescriptorSet,
srcSet = boundDescriptorSets[mapping.SourceSet],
srcBinding = (uint) mapping.SourceBinding,
srcArrayElement = 0,
dstSet = localDescriptorSet,
dstBinding = (uint) mapping.DestinationBinding,
dstArrayElement = 0,
descriptorCount = 1
});
}
fixed (VkCopyDescriptorSet* fCopiesItems = copies.Items)
GraphicsDevice.NativeDeviceApi.vkUpdateDescriptorSets(GraphicsDevice.NativeDevice, 0, null, (uint) copies.Count, fCopiesItems);
#else
var bindingCount = activePipeline.DescriptorBindingMapping.Count;
var writes = stackalloc VkWriteDescriptorSet[bindingCount];
var descriptorDatas = stackalloc DescriptorData[bindingCount];
for (int index = 0; index < bindingCount; index++)
{
var mapping = activePipeline.DescriptorBindingMapping[index];
var sourceSet = boundDescriptorSets[mapping.SourceSet];
var heapObject = sourceSet.HeapObjects[sourceSet.DescriptorStartOffset + mapping.SourceBinding];
var write = writes + index;
var descriptorData = descriptorDatas + index;
*write = new VkWriteDescriptorSet
{
sType = VkStructureType.WriteDescriptorSet,
descriptorType = mapping.DescriptorType,
dstSet = localDescriptorSet,
dstBinding = (uint)mapping.DestinationBinding,
dstArrayElement = 0,
descriptorCount = 1
};
switch (mapping.DescriptorType)
{
case VkDescriptorType.SampledImage:
{
var texture = heapObject.Value as Texture;
// The descriptor's layout field must match the image's actual layout as
// this CB understands it. Use the per-CB map rather than texture.NativeLayout
// (which can be mutated by other CBs recording concurrently).
var parent = texture?.ParentTexture ?? texture;
var perCb = parent != null && currentCbLayouts.TryGetValue(parent, out var l) ? (BarrierLayout?)l : null;
var imageLayout = perCb == BarrierLayout.DepthStencilRead
? VkImageLayout.DepthStencilReadOnlyOptimal
: VkImageLayout.ShaderReadOnlyOptimal;
descriptorData->ImageInfo = new VkDescriptorImageInfo { imageView = texture?.NativeImageView ?? GraphicsDevice.EmptyTexture.NativeImageView, imageLayout = imageLayout };
write->pImageInfo = &descriptorData->ImageInfo;
break;
}
case VkDescriptorType.StorageImage:
{
var texture = heapObject.Value as Texture;
descriptorData->ImageInfo = new VkDescriptorImageInfo { imageView = texture?.NativeImageView ?? GraphicsDevice.EmptyTexture.NativeImageView, imageLayout = VkImageLayout.General };
write->pImageInfo = &descriptorData->ImageInfo;
break;
}
case VkDescriptorType.Sampler:
var samplerState = heapObject.Value as SamplerState;
descriptorData->ImageInfo = new VkDescriptorImageInfo { sampler = samplerState?.NativeSampler ?? GraphicsDevice.SamplerStates.LinearClamp.NativeSampler };
write->pImageInfo = &descriptorData->ImageInfo;
break;
case VkDescriptorType.UniformBuffer:
var buffer = heapObject.Value as Buffer;
descriptorData->BufferInfo = new VkDescriptorBufferInfo { buffer = buffer?.NativeBuffer ?? VkBuffer.Null, offset = (ulong)heapObject.Offset, range = (ulong)heapObject.Size };
write->pBufferInfo = &descriptorData->BufferInfo;
break;
case VkDescriptorType.UniformTexelBuffer:
case VkDescriptorType.StorageTexelBuffer:
buffer = heapObject.Value as Buffer;
descriptorData->BufferView = buffer?.NativeBufferView ?? (mapping.ResourceElementIsInteger ? GraphicsDevice.EmptyTexelBufferInt.NativeBufferView : GraphicsDevice.EmptyTexelBufferFloat.NativeBufferView);
write->pTexelBufferView = &descriptorData->BufferView;
break;
case VkDescriptorType.StorageBuffer:
buffer = heapObject.Value as Buffer;
// heapObject.Offset is repurposed to carry InitialCounterOffset for UAVs
// (defaults to -1) and is not the descriptor binding offset; structured /
// raw buffer descriptors always bind from offset 0 over the whole buffer.
descriptorData->BufferInfo = new VkDescriptorBufferInfo { buffer = buffer?.NativeBuffer ?? VkBuffer.Null, offset = 0, range = (ulong)(buffer?.SizeInBytes ?? 0)};
write->pBufferInfo = &descriptorData->BufferInfo;
break;
default:
throw new InvalidOperationException();
}
}
GraphicsDevice.NativeDeviceApi.vkUpdateDescriptorSets(GraphicsDevice.NativeDevice, (uint)bindingCount, writes, descriptorCopyCount: 0, descriptorCopies: null);
#endif
GraphicsDevice.NativeDeviceApi.vkCmdBindDescriptorSets(currentCommandList.NativeCommandBuffer, activePipeline.IsCompute ? VkPipelineBindPoint.Compute : VkPipelineBindPoint.Graphics, activePipeline.NativeLayout, firstSet: 0, descriptorSetCount: 1, &localDescriptorSet, dynamicOffsetCount: 0, dynamicOffsets: null);
}
private readonly FastList<VkCopyDescriptorSet> copies = new();
public void SetStencilReference(int stencilReference)
{
if (activeStencilReference != stencilReference)
{
activeStencilReference = (uint) stencilReference;
GraphicsDevice.NativeDeviceApi.vkCmdSetStencilReference(currentCommandList.NativeCommandBuffer, VkStencilFaceFlags.FrontAndBack, activeStencilReference.Value);
}
}
public void SetPipelineState(PipelineState pipelineState)
{
if (pipelineState == activePipeline)
return;
viewportDirty = true;
// If scissor state changed, force a refresh
scissorsDirty |= (pipelineState?.Description.RasterizerState.ScissorTestEnable ?? false) != (activePipeline?.Description.RasterizerState.ScissorTestEnable ?? false);
activePipeline = pipelineState;
pipelineDirty = true;
}
public unsafe void SetVertexBuffer(int index, Buffer buffer, int offset, int stride)
{
// TODO VULKAN API: Stride is part of Pipeline
// TODO VULKAN: Handle multiple buffers. Collect and apply before draw?
//if (index != 0)
// throw new NotImplementedException();
var bufferCopy = buffer.NativeBuffer;
var offsetCopy = (ulong) offset;
GraphicsDevice.NativeDeviceApi.vkCmdBindVertexBuffers(currentCommandList.NativeCommandBuffer, (uint) index, bindingCount: 1, &bufferCopy, &offsetCopy);
}
public void SetIndexBuffer(Buffer buffer, int offset, bool is32bits)
{
GraphicsDevice.NativeDeviceApi.vkCmdBindIndexBuffer(currentCommandList.NativeCommandBuffer, buffer.NativeBuffer, (ulong) offset, is32bits ? VkIndexType.Uint32 : VkIndexType.Uint16);
}
/// <summary>
/// Transitions a resource to a new layout using the cross-platform barrier abstraction.
/// </summary>
// TODO: subresource parameter is currently ignored — Vulkan always transitions all
// subresources. This is incorrect when different subresources need different layouts
// (e.g. reading mip 0 as ShaderResource while writing mip 1 as RenderTarget).
// Per-subresource tracking would require storing per-subresource VkImageLayout
// to emit precise barriers. Not currently hit by the engine's rendering pipeline.
public unsafe void ResourceBarrierTransition(GraphicsResource resource, BarrierLayout newLayout, uint subresource = uint.MaxValue)
{
RecordDebugCounter(DebugCounterKind.Barrier);
if (resource is Texture texture)
{
if (texture.ParentTexture != null)
texture = texture.ParentTexture;
// Resolve "from" layout for THIS CB. If we've already transitioned the texture in
// this CB, use that; otherwise assume the last-submitted global state (NativeLayout).
// This keeps the barrier's oldLayout accurate even when other CBs have mutated the
// global tracker concurrently.
VkImageLayout oldLayout;
VkAccessFlags oldAccessMask;
VkPipelineStageFlags sourceStages;
if (currentCbLayouts.TryGetValue(texture, out var fromLayout))
{
if (fromLayout == newLayout)
return; // already at target in this CB
oldLayout = BarrierMapping.ToVkImageLayout(fromLayout);
oldAccessMask = BarrierMapping.ToVkAccessFlags(fromLayout);
sourceStages = BarrierMapping.ToVkPipelineStageFlags(fromLayout);
}
else
{
oldLayout = texture.NativeLayout;
oldAccessMask = texture.NativeAccessMask;
sourceStages = texture.NativePipelineStageMask;
}
var newVkLayout = BarrierMapping.ToVkImageLayout(newLayout);
var newAccessMask = BarrierMapping.ToVkAccessFlags(newLayout);
var newStages = BarrierMapping.ToVkPipelineStageFlags(newLayout);
// Update per-CB map, global state, and subresource tracker together
currentCbLayouts[texture] = newLayout;
texture.NativeLayout = newVkLayout;
texture.NativeAccessMask = newAccessMask;
texture.NativePipelineStageMask = newStages;
texture.LayoutTracker.Set(uint.MaxValue, newLayout);
if (oldLayout == VkImageLayout.Undefined || oldLayout == VkImageLayout.PresentSrcKHR)
sourceStages = VkPipelineStageFlags.TopOfPipe;
// End render pass, so barrier affects all commands in the buffer
CleanupRenderPass();
var memoryBarrier = new VkImageMemoryBarrier(texture.NativeImage, new VkImageSubresourceRange(texture.NativeImageAspect, 0, uint.MaxValue, 0, uint.MaxValue), oldAccessMask, newAccessMask, oldLayout, newVkLayout);
GraphicsDevice.NativeDeviceApi.vkCmdPipelineBarrier(currentCommandList.NativeCommandBuffer, sourceStages, newStages, VkDependencyFlags.None, 0, null, 0, null, 1, &memoryBarrier);
}
else
{
throw new NotImplementedException();
}
}
[Obsolete("Use BarrierLayout overload instead.")]
public void ResourceBarrierTransition(GraphicsResource resource, GraphicsResourceState newState)
{
var layout = (int)newState switch
{
0x04 => BarrierLayout.RenderTarget,
0x08 => BarrierLayout.UnorderedAccess,
0x10 => BarrierLayout.DepthStencilWrite,
0x20 => BarrierLayout.DepthStencilRead,
0x80 => BarrierLayout.ShaderResource,
0xC0 => BarrierLayout.ShaderResource,
0x400 => BarrierLayout.CopyDest,
0x800 => BarrierLayout.CopySource,
0x1000 => BarrierLayout.ResolveDest,
0x2000 => BarrierLayout.ResolveSource,
_ => BarrierLayout.Common,
};
ResourceBarrierTransition(resource, layout);
}
/// <summary>
/// Ensures the pipeline stage mask is compatible with the access flags in a buffer barrier.
/// HOST_READ/HOST_WRITE access requires VK_PIPELINE_STAGE_HOST_BIT, which is not included
/// in VK_PIPELINE_STAGE_ALL_COMMANDS_BIT.
/// </summary>
internal static VkPipelineStageFlags FixStagesForAccess(VkPipelineStageFlags stages, VkAccessFlags access)
{
if ((access & (VkAccessFlags.HostRead | VkAccessFlags.HostWrite)) != 0)
stages |= VkPipelineStageFlags.Host;
return stages;
}
#if !STRIDE_GRAPHICS_NO_DESCRIPTOR_COPIES
private readonly FastList<VkDescriptorSet> boundDescriptorSets = new FastList<VkDescriptorSet>();
#else
private readonly FastList<DescriptorSet> boundDescriptorSets = new();
#endif
public void SetDescriptorSets(int index, DescriptorSet[] descriptorSets)
{
if (index != 0)
throw new NotImplementedException();
boundDescriptorSets.Clear(fastClear: true);
for (int i = 0; i < descriptorSets.Length; i++)
{
#if !STRIDE_GRAPHICS_NO_DESCRIPTOR_COPIES
boundDescriptorSets.Add(descriptorSets[i].NativeDescriptorSet);
#else
boundDescriptorSets.Add(descriptorSets[i]);
#endif
}
}
/// <inheritdoc />
public void Dispatch(int threadCountX, int threadCountY, int threadCountZ)
{
RecordDebugCounter(DebugCounterKind.Dispatch);
CleanupRenderPass();
TransitionBoundResources();
BindPipeline();
BindDescriptorSets();
GraphicsDevice.NativeDeviceApi.vkCmdDispatch(currentCommandList.NativeCommandBuffer, (uint)threadCountX, (uint)threadCountY, (uint)threadCountZ);
}
/// <summary>
/// Dispatches the specified indirect buffer.
/// </summary>
/// <param name="indirectBuffer">The indirect buffer.</param>
/// <param name="offsetInBytes">The offset information bytes.</param>
public void Dispatch(Buffer indirectBuffer, int offsetInBytes)
{
RecordDebugCounter(DebugCounterKind.Dispatch);
CleanupRenderPass();
TransitionBoundResources();
BindPipeline();
BindDescriptorSets();
GraphicsDevice.NativeDeviceApi.vkCmdDispatchIndirect(currentCommandList.NativeCommandBuffer, indirectBuffer.NativeBuffer, (ulong)offsetInBytes);
}
/// <summary>
/// Draw non-indexed, non-instanced primitives.
/// </summary>
/// <param name="vertexCount">Number of vertices to draw.</param>
/// <param name="startVertexLocation">Index of the first vertex, which is usually an offset in a vertex buffer; it could also be used as the first vertex id generated for a shader parameter marked with the <strong>SV_TargetId</strong> system-value semantic.</param>
public void Draw(int vertexCount, int startVertexLocation = 0)
{
PrepareDraw();
GraphicsDevice.NativeDeviceApi.vkCmdDraw(currentCommandList.NativeCommandBuffer, (uint) vertexCount, instanceCount: 1, (uint) startVertexLocation, firstInstance: 0);
GraphicsDevice.FrameTriangleCount += (uint) vertexCount;
GraphicsDevice.FrameDrawCalls++;
}
/// <summary>
/// Draw geometry of an unknown size.
/// </summary>
public void DrawAuto()
{
PrepareDraw();
throw new NotImplementedException();
//NativeDeviceContext.DrawAuto();
GraphicsDevice.FrameDrawCalls++;
}
/// <summary>
/// Draw indexed, non-instanced primitives.
/// </summary>
/// <param name="indexCount">Number of indices to draw.</param>
/// <param name="startIndexLocation">The location of the first index read by the GPU from the index buffer.</param>
/// <param name="baseVertexLocation">A value added to each index before reading a vertex from the vertex buffer.</param>
public void DrawIndexed(int indexCount, int startIndexLocation = 0, int baseVertexLocation = 0)
{
PrepareDraw();
GraphicsDevice.NativeDeviceApi.vkCmdDrawIndexed(currentCommandList.NativeCommandBuffer, (uint) indexCount, instanceCount: 1, (uint) startIndexLocation, baseVertexLocation, firstInstance: 0);
GraphicsDevice.FrameDrawCalls++;
GraphicsDevice.FrameTriangleCount += (uint) indexCount;
}
/// <summary>
/// Draw indexed, instanced primitives.
/// </summary>
/// <param name="indexCountPerInstance">Number of indices read from the index buffer for each instance.</param>
/// <param name="instanceCount">Number of instances to draw.</param>
/// <param name="startIndexLocation">The location of the first index read by the GPU from the index buffer.</param>
/// <param name="baseVertexLocation">A value added to each index before reading a vertex from the vertex buffer.</param>
/// <param name="startInstanceLocation">A value added to each index before reading per-instance data from a vertex buffer.</param>
public void DrawIndexedInstanced(int indexCountPerInstance, int instanceCount, int startIndexLocation = 0, int baseVertexLocation = 0, int startInstanceLocation = 0)
{
PrepareDraw();
GraphicsDevice.NativeDeviceApi.vkCmdDrawIndexed(currentCommandList.NativeCommandBuffer, (uint) indexCountPerInstance, (uint) instanceCount, (uint) startIndexLocation, baseVertexLocation, (uint) startInstanceLocation);
//NativeCommandList.DrawIndexedInstanced(indexCountPerInstance, instanceCount, startIndexLocation, baseVertexLocation, startInstanceLocation);
GraphicsDevice.FrameDrawCalls++;
GraphicsDevice.FrameTriangleCount += (uint) (indexCountPerInstance * instanceCount);
}
/// <summary>
/// Draw indexed, instanced, GPU-generated primitives.
/// </summary>
/// <param name="argumentsBuffer">A buffer containing the GPU generated primitives.</param>
/// <param name="alignedByteOffsetForArgs">Offset in <em>pBufferForArgs</em> to the start of the GPU generated primitives.</param>
public void DrawIndexedInstanced(Buffer argumentsBuffer, int alignedByteOffsetForArgs = 0)
{
if (argumentsBuffer == null) throw new ArgumentNullException("argumentsBuffer");
PrepareDraw();
throw new NotImplementedException();
//NativeCommandBuffer.DrawIndirect(argumentsBuffer.NativeBuffer, (ulong) alignedByteOffsetForArgs, );
//NativeDeviceContext.DrawIndexedInstancedIndirect(argumentsBuffer.NativeBuffer, alignedByteOffsetForArgs);
GraphicsDevice.FrameDrawCalls++;
}
/// <summary>
/// Draw non-indexed, instanced primitives.
/// </summary>
/// <param name="vertexCountPerInstance">Number of vertices to draw.</param>
/// <param name="instanceCount">Number of instances to draw.</param>
/// <param name="startVertexLocation">Index of the first vertex.</param>
/// <param name="startInstanceLocation">A value added to each index before reading per-instance data from a vertex buffer.</param>
public void DrawInstanced(int vertexCountPerInstance, int instanceCount, int startVertexLocation = 0, int startInstanceLocation = 0)
{
PrepareDraw();
GraphicsDevice.NativeDeviceApi.vkCmdDraw(currentCommandList.NativeCommandBuffer, (uint) vertexCountPerInstance, (uint) instanceCount, (uint) startVertexLocation, (uint) startVertexLocation);
//NativeCommandList.DrawInstanced(vertexCountPerInstance, instanceCount, startVertexLocation, startInstanceLocation);
GraphicsDevice.FrameDrawCalls++;
GraphicsDevice.FrameTriangleCount += (uint) (vertexCountPerInstance * instanceCount);
}
/// <summary>
/// Draw instanced, GPU-generated primitives.
/// </summary>
/// <param name="argumentsBuffer">An arguments buffer</param>
/// <param name="alignedByteOffsetForArgs">Offset in <em>pBufferForArgs</em> to the start of the GPU generated primitives.</param>
public void DrawInstanced(Buffer argumentsBuffer, int alignedByteOffsetForArgs = 0)
{
if (argumentsBuffer == null) throw new ArgumentNullException("argumentsBuffer");
PrepareDraw();
throw new NotImplementedException();
//NativeDeviceContext.DrawIndexedInstancedIndirect(argumentsBuffer.NativeBuffer, alignedByteOffsetForArgs);
GraphicsDevice.FrameDrawCalls++;
}
/// <summary>
/// Begins profiling.
/// </summary>
/// <param name="profileColor">Color of the profile.</param>
/// <param name="name">The name.</param>
public unsafe void BeginProfile(Color4 profileColor, string name)
{
GraphicsDevice.PushDebugScope(name);
if (GraphicsDevice.IsProfilingSupported)
{
var bytes = System.Text.Encoding.ASCII.GetBytes(name);
fixed (byte* bytesPointer = &bytes[0])
{
var labelInfo = new VkDebugUtilsLabelEXT
{
sType = VkStructureType.DebugUtilsLabelEXT,
pLabelName = bytesPointer
};
GraphicsDevice.NativeInstanceApi.vkCmdBeginDebugUtilsLabelEXT(currentCommandList.NativeCommandBuffer, &labelInfo);
}
}
}
/// <summary>
/// Ends profiling.
/// </summary>
public void EndProfile()
{
GraphicsDevice.PopDebugScope();
if (GraphicsDevice.IsProfilingSupported)
{
GraphicsDevice.NativeInstanceApi.vkCmdEndDebugUtilsLabelEXT(currentCommandList.NativeCommandBuffer);
}
}
/// <summary>
/// Submit a timestamp query.
/// </summary>
/// <param name="queryPool">The QueryPool owning the query.</param>
/// <param name="query">The timestamp query.</param>
public void WriteTimestamp(QueryPool queryPool, int index)
{
GraphicsDevice.NativeDeviceApi.vkCmdWriteTimestamp(currentCommandList.NativeCommandBuffer, VkPipelineStageFlags.AllCommands, queryPool.NativeQueryPool, (uint) index);
}
public void ResetQueryPool(QueryPool queryPool)
{
GraphicsDevice.NativeDeviceApi.vkCmdResetQueryPool(currentCommandList.NativeCommandBuffer, queryPool.NativeQueryPool, firstQuery: 0, (uint) queryPool.QueryCount);
}
/// <summary>
/// Clears the specified depth stencil buffer. See <see cref="Textures+and+render+targets"/> to learn how to use it.
/// </summary>
/// <param name="depthStencilBuffer">The depth stencil buffer.</param>
/// <param name="options">The options.</param>
/// <param name="depth">The depth.</param>
/// <param name="stencil">The stencil.</param>
/// <exception cref="InvalidOperationException"></exception>
public unsafe void Clear(Texture depthStencilBuffer, DepthStencilClearOptions options, float depth = 1, byte stencil = 0)
{
RecordDebugCounter(DebugCounterKind.Clear);
// Barriers need to be global to command buffer
CleanupRenderPass();
var barrierRange = depthStencilBuffer.NativeResourceRange;
// Adjust aspectMask to clear only the specified part (depth or stencil)
var clearRange = depthStencilBuffer.NativeResourceRange;
clearRange.aspectMask = VkImageAspectFlags.None;
if ((options & DepthStencilClearOptions.DepthBuffer) != 0)
clearRange.aspectMask |= VkImageAspectFlags.Depth & depthStencilBuffer.NativeImageAspect;
if ((options & DepthStencilClearOptions.Stencil) != 0)
clearRange.aspectMask |= VkImageAspectFlags.Stencil & depthStencilBuffer.NativeImageAspect;
var memoryBarrier = new VkImageMemoryBarrier(depthStencilBuffer.NativeImage, barrierRange, depthStencilBuffer.NativeAccessMask, VkAccessFlags.TransferWrite, depthStencilBuffer.NativeLayout, VkImageLayout.TransferDstOptimal);
GraphicsDevice.NativeDeviceApi.vkCmdPipelineBarrier(currentCommandList.NativeCommandBuffer, depthStencilBuffer.NativePipelineStageMask, VkPipelineStageFlags.Transfer, VkDependencyFlags.None, memoryBarrierCount: 0, memoryBarriers: null, bufferMemoryBarrierCount: 0, bufferMemoryBarriers: null, imageMemoryBarrierCount: 1, &memoryBarrier);
var clearValue = new VkClearDepthStencilValue(depth, stencil);
GraphicsDevice.NativeDeviceApi.vkCmdClearDepthStencilImage(currentCommandList.NativeCommandBuffer, depthStencilBuffer.NativeImage, VkImageLayout.TransferDstOptimal, &clearValue, rangeCount: 1, &clearRange);
memoryBarrier = new VkImageMemoryBarrier(depthStencilBuffer.NativeImage, barrierRange, VkAccessFlags.TransferWrite, depthStencilBuffer.NativeAccessMask, VkImageLayout.TransferDstOptimal, depthStencilBuffer.NativeLayout);
GraphicsDevice.NativeDeviceApi.vkCmdPipelineBarrier(currentCommandList.NativeCommandBuffer, VkPipelineStageFlags.Transfer, depthStencilBuffer.NativePipelineStageMask, VkDependencyFlags.None, memoryBarrierCount: 0, memoryBarriers: null, bufferMemoryBarrierCount: 0, bufferMemoryBarriers: null, imageMemoryBarrierCount: 1, &memoryBarrier);
depthStencilBuffer.IsInitialized = true;
}
/// <summary>
/// Clears the specified render target. See <see cref="Textures+and+render+targets"/> to learn how to use it.
/// </summary>
/// <param name="renderTarget">The render target.</param>
/// <param name="color">The color.</param>
/// <exception cref="ArgumentNullException">renderTarget</exception>
public unsafe void Clear(Texture renderTarget, Color4 color)
{
RecordDebugCounter(DebugCounterKind.Clear);
// TODO VULKAN: Detect if inside render pass. If so, NativeCommandBuffer.ClearAttachments()
// Barriers need to be global to command buffer
CleanupRenderPass();
var clearRange = renderTarget.NativeResourceRange;
var memoryBarrier = new VkImageMemoryBarrier(renderTarget.NativeImage, clearRange, renderTarget.NativeAccessMask, VkAccessFlags.TransferWrite, renderTarget.NativeLayout, VkImageLayout.TransferDstOptimal);
GraphicsDevice.NativeDeviceApi.vkCmdPipelineBarrier(currentCommandList.NativeCommandBuffer, renderTarget.NativePipelineStageMask, VkPipelineStageFlags.Transfer, VkDependencyFlags.None, memoryBarrierCount: 0, memoryBarriers: null, bufferMemoryBarrierCount: 0, bufferMemoryBarriers: null, imageMemoryBarrierCount: 1, &memoryBarrier);
GraphicsDevice.NativeDeviceApi.vkCmdClearColorImage(currentCommandList.NativeCommandBuffer, renderTarget.NativeImage, VkImageLayout.TransferDstOptimal, (VkClearColorValue*) &color, rangeCount: 1, &clearRange);
memoryBarrier = new VkImageMemoryBarrier(renderTarget.NativeImage, clearRange, VkAccessFlags.TransferWrite, renderTarget.NativeAccessMask, VkImageLayout.TransferDstOptimal, renderTarget.NativeLayout);
GraphicsDevice.NativeDeviceApi.vkCmdPipelineBarrier(currentCommandList.NativeCommandBuffer, VkPipelineStageFlags.Transfer, renderTarget.NativePipelineStageMask, VkDependencyFlags.None, memoryBarrierCount: 0, memoryBarriers: null, bufferMemoryBarrierCount: 0, bufferMemoryBarriers: null, imageMemoryBarrierCount: 1, &memoryBarrier);
renderTarget.IsInitialized = true;
}
/// <summary>
/// Clears a read-write Buffer. This buffer must have been created with read-write/unordered access.
/// </summary>
/// <param name="buffer">The buffer.</param>
/// <param name="value">The value.</param>
/// <exception cref="ArgumentNullException">buffer</exception>
/// <exception cref="ArgumentException">Expecting buffer supporting UAV;buffer</exception>
public void ClearReadWrite(Buffer buffer, Vector4 value)
{
throw new NotImplementedException();
}
/// <summary>
/// Clears a read-write Buffer. This buffer must have been created with read-write/unordered access.
/// </summary>
/// <param name="buffer">The buffer.</param>
/// <param name="value">The value.</param>
/// <exception cref="ArgumentNullException">buffer</exception>
/// <exception cref="ArgumentException">Expecting buffer supporting UAV;buffer</exception>
public void ClearReadWrite(Buffer buffer, Int4 value)
{
throw new NotImplementedException();
}
/// <summary>
/// Clears a read-write Buffer. This buffer must have been created with read-write/unordered access.
/// </summary>
/// <param name="buffer">The buffer.</param>
/// <param name="value">The value.</param>
/// <exception cref="ArgumentNullException">buffer</exception>
/// <exception cref="ArgumentException">Expecting buffer supporting UAV;buffer</exception>
public void ClearReadWrite(Buffer buffer, UInt4 value)
{
throw new NotImplementedException();
}
/// <summary>
/// Clears a read-write Texture. This texture must have been created with read-write/unordered access.
/// </summary>
/// <param name="texture">The texture.</param>
/// <param name="value">The value.</param>
/// <exception cref="ArgumentNullException">texture</exception>
/// <exception cref="ArgumentException">Expecting buffer supporting UAV;texture</exception>
public unsafe void ClearReadWrite(Texture texture, Vector4 value)
{
var clearValue = new VkClearColorValue(value.X, value.Y, value.Z, value.W);
ClearReadWriteImpl(texture, clearValue);
}
public unsafe void ClearReadWrite(Texture texture, Int4 value)
{
// D3D11 ClearUnorderedAccessViewUint writes raw integer values.
// Vulkan vkCmdClearColorImage expects float values for UNORM/SNORM formats, not raw integers.
// Convert to float to match D3D11 behavior.
if (texture.ViewFormat.IsUNorm)
{
float scale = 1.0f / texture.ViewFormat.UNormMaxValue;
ClearReadWrite(texture, new Vector4(value.X * scale, value.Y * scale, value.Z * scale, value.W * scale));
return;
}
var clearValue = new VkClearColorValue(*(uint*)&value.X, *(uint*)&value.Y, *(uint*)&value.Z, *(uint*)&value.W);
ClearReadWriteImpl(texture, clearValue);
}
public unsafe void ClearReadWrite(Texture texture, UInt4 value)
{
if (texture.ViewFormat.IsUNorm)
{
float scale = 1.0f / texture.ViewFormat.UNormMaxValue;