yum-mirror/slang

Making it easier to work with shaders

git clone https://git.yummers.dev/yum-mirror/slang

ArielG-NV[CBP] Pointer frontend changes + groupshared pointer support (#7848)7758625d3

master
57.7 KiB1991 linesraw
1import slang;
2
3public namespace gfx
4{
5public typedef slang.Result Result;
6
7public typedef intptr_t Int;
8public typedef uintptr_t UInt;
9public typedef uint64_t DeviceAddress;
10public typedef int GfxIndex;
11public typedef int GfxCount;
12public typedef intptr_t Size;
13public typedef intptr_t Offset;
14
15public static const uint64_t kTimeoutInfinite = 0xFFFFFFFFFFFFFFFF;
16
17public enum class StructType
18{
19    D3D12ExtendedDesc,
20};
21
22public enum class StageType
23{
24    Unknown,
25    Vertex,
26    Hull,
27    Domain,
28    Geometry,
29    Fragment,
30    Compute,
31    RayGeneration,
32    Intersection,
33    AnyHit,
34    ClosestHit,
35    Miss,
36    Callable,
37    Amplification,
38    Mesh,
39    CountOf,
40};
41
42public enum class DeviceType
43{
44    Unknown,
45    Default,
46    DirectX11,
47    DirectX12,
48    OpenGl,
49    Vulkan,
50    Metal,
51    CPU,
52    CUDA,
53    CountOf,
54};
55
56public enum class ProjectionStyle
57{
58    Unknown,
59    OpenGl,
60    DirectX,
61    Vulkan,
62    Metal,
63    CountOf,
64};
65
66public enum class BindingStyle
67{
68    Unknown,
69    DirectX,
70    OpenGl,
71    Vulkan,
72    Metal,
73    CPU,
74    CUDA,
75    CountOf,
76};
77
78public enum class AccessFlag
79{
80    None,
81    Read,
82    Write,
83};
84
85public static const GfxCount kMaxRenderTargetCount = 8;
86
87// Defines how linking should be performed for a shader program.
88public enum class LinkingStyle
89{
90    // Compose all entry-points in a single program, then compile all entry-points together with the same
91    // set of root shader arguments.
92    SingleProgram,
93
94    // Link and compile each entry-point individually, potentially with different specializations.
95    SeparateEntryPointCompilation
96};
97
98public enum class ShaderModuleSourceType
99{
100    SlangSource,           // a slang source string in memory.
101    SlangModuleBinary,     // a slang module binary code in memory.
102    SlangSourceFile,       // a slang source from file.
103    SlangModuleBinaryFile, // a slang module binary code from file.
104};
105
106public struct ShaderProgramDesc2
107{
108    public ShaderModuleSourceType sourceType = ShaderModuleSourceType::SlangSource;
109    public void *sourceData = nullptr;
110    public Size sourceDataSize = 0;
111
112    // Number of entry points to include in the shader program. 0 means include all entry points
113    // defined in the module.
114    public GfxCount entryPointCount = 0;
115    // Names of entry points to include in the shader program. The size of the array must be
116    // `entryPointCount`.
117    public NativeString* entryPointNames = nullptr;
118};
119
120[COM("9d32d0ad-915c-4ffd-91e2-508554a04a76")]
121public interface IShaderProgram
122{
123    public slang::TypeReflection* findTypeByName(NativeString name);
124};
125
126public enum class Format
127{
128    // D3D formats omitted: 19-22, 44-47, 65-66, 68-70, 73, 76, 79, 82, 88-89, 92-94, 97, 100-114
129    // These formats are omitted due to lack of a corresponding Vulkan format. D24_UNORM_S8_UINT (DXGI_FORMAT 45)
130    // has a matching Vulkan format but is also omitted as it is only supported by Nvidia.
131    Unknown,
132
133    R32G32B32A32_TYPELESS,
134    R32G32B32_TYPELESS,
135    R32G32_TYPELESS,
136    R32_TYPELESS,
137
138    R16G16B16A16_TYPELESS,
139    R16G16_TYPELESS,
140    R16_TYPELESS,
141
142    R8G8B8A8_TYPELESS,
143    R8G8_TYPELESS,
144    R8_TYPELESS,
145    B8G8R8A8_TYPELESS,
146
147    R32G32B32A32_FLOAT,
148    R32G32B32_FLOAT,
149    R32G32_FLOAT,
150    R32_FLOAT,
151
152    R16G16B16A16_FLOAT,
153    R16G16_FLOAT,
154    R16_FLOAT,
155
156    R64_UINT,
157
158    R32G32B32A32_UINT,
159    R32G32B32_UINT,
160    R32G32_UINT,
161    R32_UINT,
162
163    R16G16B16A16_UINT,
164    R16G16_UINT,
165    R16_UINT,
166
167    R8G8B8A8_UINT,
168    R8G8_UINT,
169    R8_UINT,
170
171    R64_SINT,
172
173    R32G32B32A32_SINT,
174    R32G32B32_SINT,
175    R32G32_SINT,
176    R32_SINT,
177
178    R16G16B16A16_SINT,
179    R16G16_SINT,
180    R16_SINT,
181
182    R8G8B8A8_SINT,
183    R8G8_SINT,
184    R8_SINT,
185
186    R16G16B16A16_UNORM,
187    R16G16_UNORM,
188    R16_UNORM,
189
190    R8G8B8A8_UNORM,
191    R8G8B8A8_UNORM_SRGB,
192    R8G8_UNORM,
193    R8_UNORM,
194    B8G8R8A8_UNORM,
195    B8G8R8A8_UNORM_SRGB,
196    B8G8R8X8_UNORM,
197    B8G8R8X8_UNORM_SRGB,
198
199    R16G16B16A16_SNORM,
200    R16G16_SNORM,
201    R16_SNORM,
202
203    R8G8B8A8_SNORM,
204    R8G8_SNORM,
205    R8_SNORM,
206
207    D32_FLOAT,
208    D16_UNORM,
209
210    B4G4R4A4_UNORM,
211    B5G6R5_UNORM,
212    B5G5R5A1_UNORM,
213
214    R9G9B9E5_SHAREDEXP,
215    R10G10B10A2_TYPELESS,
216    R10G10B10A2_UNORM,
217    R10G10B10A2_UINT,
218    R11G11B10_FLOAT,
219
220    BC1_UNORM,
221    BC1_UNORM_SRGB,
222    BC2_UNORM,
223    BC2_UNORM_SRGB,
224    BC3_UNORM,
225    BC3_UNORM_SRGB,
226    BC4_UNORM,
227    BC4_SNORM,
228    BC5_UNORM,
229    BC5_SNORM,
230    BC6H_UF16,
231    BC6H_SF16,
232    BC7_UNORM,
233    BC7_UNORM_SRGB,
234
235    _Count,
236};
237
238public struct FormatInfo
239{
240    public GfxCount channelCount; ///< The amount of channels in the format. Only set if the channelType is set
241    public uint8_t channelType;   ///< One of SlangScalarType None if type isn't made up of elements of type. TODO: Change to uint32_t?
242
243    public Size blockSizeInBytes;   ///< The size of a block in bytes.
244    public GfxCount pixelsPerBlock; ///< The number of pixels contained in a block.
245    public GfxCount blockWidth;     ///< The width of a block in pixels.
246    public GfxCount blockHeight;    ///< The height of a block in pixels.
247};
248
249public enum class InputSlotClass
250{
251    PerVertex, PerInstance
252};
253
254public struct InputElementDesc
255{
256    public NativeString semanticName; ///< The name of the corresponding parameter in shader code.
257    public GfxIndex semanticIndex;   ///< The index of the corresponding parameter in shader code. Only needed if multiple parameters share a semantic name.
258    public Format format;            ///< The format of the data being fetched for this element.
259    public Offset offset;            ///< The offset in bytes of this element from the start of the corresponding chunk of vertex stream data.
260    public GfxIndex bufferSlotIndex; ///< The index of the vertex stream to fetch this element's data from.
261};
262
263public struct VertexStreamDesc
264{
265    public Size stride;                   ///< The stride in bytes for this vertex stream.
266    public InputSlotClass slotClass;      ///< Whether the stream contains per-vertex or per-instance data.
267    public GfxCount instanceDataStepRate; ///< How many instances to draw per chunk of data.
268};
269
270public enum class PrimitiveType
271{
272    Point, Line, Triangle, Patch
273};
274
275public enum class PrimitiveTopology
276{
277    TriangleList, TriangleStrip, PointList, LineList, LineStrip
278};
279
280public enum class ResourceState
281{
282    Undefined,
283    General,
284    PreInitialized,
285    VertexBuffer,
286    IndexBuffer,
287    ConstantBuffer,
288    StreamOutput,
289    ShaderResource,
290    UnorderedAccess,
291    RenderTarget,
292    DepthRead,
293    DepthWrite,
294    Present,
295    IndirectArgument,
296    CopySource,
297    CopyDestination,
298    ResolveSource,
299    ResolveDestination,
300    AccelerationStructure,
301    AccelerationStructureBuildInput,
302    _Count
303};
304
305public struct ResourceStateSet
306{
307    public uint64_t m_bitFields;
308
309    [mutating]
310    public void add(ResourceState state) { m_bitFields |= (1LL << (uint32_t)state); }
311
312    public bool contains(ResourceState state) { return (m_bitFields & (1LL << (uint32_t)state)) != 0; }
313    public __init() { m_bitFields = 0; }
314    public __init(ResourceState state) { add(state); }
315};
316
317public ResourceStateSet operator &(ResourceStateSet val, ResourceStateSet that)
318{
319    ResourceStateSet result;
320    result.m_bitFields = val.m_bitFields & that.m_bitFields;
321    return result;
322}
323
324/// Describes how memory for the resource should be allocated for CPU access.
325public enum class MemoryType
326{
327    DeviceLocal,
328    Upload,
329    ReadBack,
330};
331
332public enum class InteropHandleAPI
333{
334    Unknown,
335    D3D12,                    // A D3D12 object pointer.
336    Vulkan,                   // A general Vulkan object handle.
337    CUDA,                     // A general CUDA object handle.
338    Win32,                    // A general Win32 HANDLE.
339    FileDescriptor,           // A file descriptor.
340    DeviceAddress,            // A device address.
341    D3D12CpuDescriptorHandle, // A D3D12_CPU_DESCRIPTOR_HANDLE value.
342    Metal,                    // A general Metal object handle.
343};
344
345public struct InteropHandle
346{
347    public InteropHandleAPI api = InteropHandleAPI::Unknown;
348    public uint64_t handleValue = 0LLU;
349};
350
351// Declare opaque type
352public struct InputLayoutDesc
353{
354    public InputElementDesc *inputElements;
355    public GfxCount inputElementCount;
356    public VertexStreamDesc *vertexStreams;
357    public GfxCount vertexStreamCount;
358};
359
360[COM("45223711-a84b-455c-befa-4937421e8e2e")]
361public interface IInputLayout
362{   
363};
364
365/// The type of resource.
366/// NOTE! The order needs to be such that all texture types are at or after Texture1D (otherwise isTexture won't work correctly)
367public enum class ResourceType
368{
369    Unknown,     ///< Unknown
370    Buffer,      ///< A buffer (like a constant/index/vertex buffer)
371    Texture1D,   ///< A 1d texture
372    Texture2D,   ///< A 2d texture
373    Texture3D,   ///< A 3d texture
374    TextureCube, ///< A cubemap consists of 6 Texture2D like faces
375    _Count,
376};
377
378/// Base class for Descs
379public struct ResourceDescBase
380{
381    public ResourceType type = ResourceType::Unknown;
382    public ResourceState defaultState = ResourceState::Undefined;
383    public ResourceStateSet allowedStates = {};
384    public MemoryType memoryType = MemoryType::DeviceLocal;
385    public InteropHandle existingHandle = {};
386    public bool isShared = false;
387};
388
389[COM("a0e39f34-8398-4522-95c2-ebc0f984ef3f")]
390public interface IResource
391{
392    public ResourceType getType();
393    public Result getNativeResourceHandle(out InteropHandle outHandle);
394    public Result getSharedHandle(out InteropHandle outHandle);
395    public Result setDebugName(NativeString name);
396    public NativeString getDebugName();
397};
398
399public struct MemoryRange
400{
401    // TODO: Change to Offset/Size?
402    public uint64_t offset;
403    public uint64_t size;
404};
405
406public struct BufferResourceDesc : ResourceDescBase
407{
408    public Size sizeInBytes = 0; ///< Total size in bytes
409    public Size elementSize = 0; ///< Get the element stride. If > 0, this is a structured buffer
410    public Format format = Format::Unknown;
411};
412
413[COM("1b274efe-5e37-492b-826e-7ee7e8f5a49b")]
414public interface IBufferResource : IResource
415{
416    public BufferResourceDesc *getDesc();
417    public DeviceAddress getDeviceAddress();
418    public Result map(MemoryRange *rangeToRead, void **outPointer);
419    public Result unmap(MemoryRange* writtenRange);
420};
421
422public struct DepthStencilClearValue
423{
424    public float depth = 1.0f;
425    public uint32_t stencil = 0;
426};
427
428public struct ColorClearValue
429{
430    public float4 values;
431
432    [mutating]
433    public void setValue(uint4 uintVal)
434    {
435        values = reinterpret<float4, uint4>(uintVal);
436    }
437
438    [mutating]
439    public void setValue(float4 floatVal)
440    {
441        values = floatVal;
442    }
443};
444
445public struct ClearValue
446{
447    public ColorClearValue color;
448    public DepthStencilClearValue depthStencil;
449};
450
451public struct BufferRange
452{
453    public Offset offset;   ///< Offset in bytes.
454    public Size size;       ///< Size in bytes.
455};
456
457public enum class TextureAspect : uint32_t
458{
459    Default = 0,
460    Color = 0x00000001,
461    Depth = 0x00000002,
462    Stencil = 0x00000004,
463    MetaData = 0x00000008,
464    Plane0 = 0x00000010,
465    Plane1 = 0x00000020,
466    Plane2 = 0x00000040,
467
468    DepthStencil = 0x6,
469};
470
471public struct SubresourceRange
472{
473    public TextureAspect aspectMask;
474    public GfxIndex mipLevel;
475    public GfxCount mipLevelCount;
476    public GfxIndex baseArrayLayer; // For Texture3D, this is WSlice.
477    public GfxCount layerCount;     // For cube maps, this is a multiple of 6.
478};
479
480public static const Size kRemainingTextureSize = 0xFFFFFFFF;
481public struct TextureResourceSampleDesc
482{
483    public GfxCount numSamples; ///< Number of samples per pixel
484    public int quality;         ///< The quality measure for the samples
485};
486
487public struct TextureResourceDesc : ResourceDescBase
488{
489    public int3 size;
490
491    public GfxCount arraySize = 0; ///< Array size
492
493    public GfxCount numMipLevels = 0;         ///< Number of mip levels - if 0 will create all mip levels
494    public Format format;             ///< The resources format
495    public TextureResourceSampleDesc sampleDesc; ///< How the resource is sampled
496    public ClearValue* optimalClearValue;
497};
498
499/// Data for a single subresource of a texture.
500///
501/// Each subresource is a tensor with `1 <= rank <= 3`,
502/// where the rank is deterined by the base shape of the
503/// texture (Buffer, 1D, 2D, 3D, or Cube). For the common
504/// case of a 2D texture, `rank == 2` and each subresource
505/// is a 2D image.
506///
507/// Subresource tensors must be stored in a row-major layout,
508/// so that the X axis strides over texels, the Y axis strides
509/// over 1D rows of texels, and the Z axis strides over 2D
510/// "layers" of texels.
511///
512/// For a texture with multiple mip levels or array elements,
513/// each mip level and array element is stores as a distinct
514/// subresource. When indexing into an array of subresources,
515/// the index of a subresoruce for mip level `m` and array
516/// index `a` is `m + a*mipLevelCount`.
517///
518public struct SubresourceData
519{
520    /// Pointer to texel data for the subresource tensor.
521    public void *data;
522
523    /// Stride in bytes between rows of the subresource tensor.
524    ///
525    /// This is the number of bytes to add to a pointer to a texel
526    /// at (X,Y,Z) to get to a texel at (X,Y+1,Z).
527    ///
528    /// Devices may not support all possible values for `strideY`.
529    /// In particular, they may only support strictly positive strides.
530    ///
531    public gfx::Size strideY;
532
533    /// Stride in bytes between layers of the subresource tensor.
534    ///
535    /// This is the number of bytes to add to a pointer to a texel
536    /// at (X,Y,Z) to get to a texel at (X,Y,Z+1).
537    ///
538    /// Devices may not support all possible values for `strideZ`.
539    /// In particular, they may only support strictly positive strides.
540    ///
541    public gfx::Size strideZ;
542};
543
544[COM("cf88a31c-6187-46c5-a4b7-eb-58-c7-33-40-17")]
545public interface ITextureResource : IResource
546{
547    public TextureResourceDesc* getDesc();
548};
549
550public enum class ComparisonFunc : uint8_t
551{
552    Never = 0x0,
553    Less = 0x1,
554    Equal = 0x2,
555    LessEqual = 0x3,
556    Greater = 0x4,
557    NotEqual = 0x5,
558    GreaterEqual = 0x6,
559    Always = 0x7,
560};
561
562public enum class TextureFilteringMode
563{
564    Point,
565    Linear,
566};
567
568public enum class TextureAddressingMode
569{
570    Wrap,
571    ClampToEdge,
572    ClampToBorder,
573    MirrorRepeat,
574    MirrorOnce,
575};
576
577public enum class TextureReductionOp
578{
579    Average,
580    Comparison,
581    Minimum,
582    Maximum,
583};
584
585public struct SamplerStateDesc
586{
587    public TextureFilteringMode minFilter;
588    public TextureFilteringMode magFilter;
589    public TextureFilteringMode mipFilter;
590    public TextureReductionOp reductionOp;
591    public TextureAddressingMode addressU;
592    public TextureAddressingMode addressV;
593    public TextureAddressingMode addressW;
594    public float mipLODBias;
595    public uint32_t maxAnisotropy;
596    public ComparisonFunc comparisonFunc;
597    public float4 borderColor;
598    public float minLOD;
599    public float maxLOD;
600    public __init()
601    {
602        minFilter = TextureFilteringMode::Linear;
603        magFilter = TextureFilteringMode::Linear;
604        mipFilter = TextureFilteringMode::Linear;
605        reductionOp = TextureReductionOp::Average;
606        addressU = TextureAddressingMode::Wrap;
607        addressV = TextureAddressingMode::Wrap;
608        addressW = TextureAddressingMode::Wrap;
609        mipLODBias = 0.0f;
610        maxAnisotropy = 1;
611        comparisonFunc = ComparisonFunc::Never;
612        borderColor = float4(1.0f, 1.0f, 1.0f, 1.0f);
613        minLOD = -float.maxValue;
614        maxLOD = float.maxValue;
615    }
616};
617
618[COM("8b8055df-9377-401d-91ff-3f-a3-bf-66-64-f4")]
619public interface ISamplerState
620{
621    /// Returns a native API handle representing this sampler state object.
622    /// When using D3D12, this will be a D3D12_CPU_DESCRIPTOR_HANDLE.
623    /// When using Vulkan, this will be a VkSampler.
624    public Result getNativeHandle(InteropHandle *outNativeHandle);
625};
626
627public enum class ResourceViewType
628{
629    Unknown,
630
631    RenderTarget,
632    DepthStencil,
633    ShaderResource,
634    UnorderedAccess,
635    AccelerationStructure,
636
637    CountOf_,
638};
639
640public struct RenderTargetDesc
641{
642    // The resource shape of this render target view.
643    public ResourceType shape;
644};
645
646public struct ResourceViewDesc
647{
648    public ResourceViewType type;
649    public Format format;
650
651    // Required fields for `RenderTarget` and `DepthStencil` views.
652    public RenderTargetDesc renderTarget;
653    // Specifies the range of a texture resource for a ShaderRsource/UnorderedAccess/RenderTarget/DepthStencil view.
654    public SubresourceRange subresourceRange;
655    // Specifies the range of a buffer resource for a ShaderResource/UnorderedAccess view.
656    public BufferRange bufferRange;
657};
658
659[COM("7b6c4926-0884-408c-ad8a-50-3a-8e-23-98-a4")]
660public interface IResourceView
661{
662    public ResourceViewDesc* getViewDesc();
663
664    /// Returns a native API handle representing this resource view object.
665    /// When using D3D12, this will be a D3D12_CPU_DESCRIPTOR_HANDLE or a buffer device address depending
666    /// on the type of the resource view.
667    /// When using Vulkan, this will be a VkImageView, VkBufferView, VkAccelerationStructure or a VkBuffer
668    /// depending on the type of the resource view.
669    public Result getNativeHandle(InteropHandle *outNativeHandle);
670};
671
672public enum class AccelerationStructureKind
673{
674    TopLevel,
675    BottomLevel
676};
677
678// The public enum values are intentionally consistent with
679// D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS.
680public enum AccelerationStructureBuildFlags
681{
682    None,
683    AllowUpdate = 1,
684    AllowCompaction = 2,
685    PreferFastTrace = 4,
686    PreferFastBuild = 8,
687    MinimizeMemory = 16,
688    PerformUpdate = 32
689};
690
691public enum class GeometryType
692{
693    Triangles, ProcedurePrimitives
694};
695
696public struct GeometryFlags
697{
698    // The public enum values are intentionally consistent with
699    // D3D12_RAYTRACING_GEOMETRY_FLAGS.
700    public enum Enum
701    {
702        None,
703        Opaque = 1,
704        NoDuplicateAnyHitInvocation = 2
705    };
706};
707
708public struct TriangleDesc
709{
710    public DeviceAddress transform3x4;
711    public Format indexFormat;
712    public Format vertexFormat;
713    public GfxCount indexCount;
714    public GfxCount vertexCount;
715    public DeviceAddress indexData;
716    public DeviceAddress vertexData;
717    public Size vertexStride;
718};
719
720public struct ProceduralAABB
721{
722    public float minX;
723    public float minY;
724    public float minZ;
725    public float maxX;
726    public float maxY;
727    public float maxZ;
728};
729
730public struct ProceduralAABBDesc
731{
732    /// Number of AABBs.
733    public GfxCount count;
734
735    /// Pointer to an array of `ProceduralAABB` values in device memory.
736    public DeviceAddress data;
737
738    /// Stride in bytes of the AABB values array.
739    public Size stride;
740};
741
742public struct GeometryDesc
743{
744    public GeometryType type;
745    public GeometryFlags::Enum flags;
746    public TriangleDesc triangles;
747    public property ProceduralAABBDesc proceduralAABBs
748    {
749        get { return reinterpret<ProceduralAABBDesc, TriangleDesc>(triangles); }
750        set { triangles = reinterpret<TriangleDesc, ProceduralAABBDesc>(newValue); }
751    }
752};
753
754// The public enum values are kept consistent with D3D12_RAYTRACING_INSTANCE_FLAGS
755// and VkGeometryInstanceFlagBitsKHR.
756public enum GeometryInstanceFlags
757{
758    None = 0,
759    TriangleFacingCullDisable = 0x00000001,
760    TriangleFrontCounterClockwise = 0x00000002,
761    ForceOpaque = 0x00000004,
762    NoOpaque = 0x00000008
763};
764
765// TODO: Should any of these be changed?
766// The layout of this public struct is intentionally consistent with D3D12_RAYTRACING_INSTANCE_DESC
767// and VkAccelerationStructureInstanceKHR.
768public struct InstanceDesc
769{
770    public float transform[3][4];
771    public uint32_t instanceID24_mask8;
772    public property uint32_t instanceID { get { return instanceID24_mask8 & 0xFFFFFF; } set { instanceID24_mask8 = (instanceID24_mask8 & 0xFF000000) | (newValue & 0xFFFFFF); } }
773    public property uint32_t instanceMask { get { return instanceID24_mask8 >> 24; } set { instanceID24_mask8 = (newValue << 24) | (instanceID24_mask8 & 0x00FFFFFF); } }
774
775    public uint32_t instanceContributionToHitGroupIndex24_flags8;
776    public property uint32_t instanceContributionToHitGroupIndex
777    {
778        get { return instanceContributionToHitGroupIndex24_flags8 & 0xFFFFFF; }
779        set { instanceContributionToHitGroupIndex24_flags8 = (instanceContributionToHitGroupIndex24_flags8 & 0xFF000000) | (newValue & 0xFFFFFF); }
780    }
781    public property GeometryInstanceFlags flags
782    {
783        get { return (GeometryInstanceFlags)(instanceContributionToHitGroupIndex24_flags8 >> 24); }
784        set { instanceContributionToHitGroupIndex24_flags8 = ((uint32_t)newValue << 24) | (instanceContributionToHitGroupIndex24_flags8 & 0x00FFFFFF); }
785    }
786    public DeviceAddress accelerationStructure;
787};
788
789public struct AccelerationStructurePrebuildInfo
790{
791    public Size resultDataMaxSize;
792    public Size scratchDataSize;
793    public Size updateScratchDataSize;
794};
795
796public struct AccelerationStructureBuildInputs
797{
798    public AccelerationStructureKind kind;
799
800    public AccelerationStructureBuildFlags flags;
801
802    public GfxCount descCount;
803
804    /// Array of `InstanceDesc` values in device memory.
805    /// Used when `kind` is `TopLevel`.
806    public DeviceAddress instanceDescs;
807
808    /// Array of `GeometryDesc` values.
809    /// Used when `kind` is `BottomLevel`.
810    public GeometryDesc *geometryDescs;
811};
812
813public struct AccelerationStructureCreateDesc
814{
815    public AccelerationStructureKind kind;
816    public NativeRef<IBufferResource> buffer;
817    public Offset offset;
818    public Size size;
819};
820
821public struct AccelerationStructureBuildDesc
822{
823    public AccelerationStructureBuildInputs inputs;
824    public NativeRef<IAccelerationStructure> source;
825    public NativeRef<IAccelerationStructure> dest;
826    public DeviceAddress scratchData;
827};
828
829[COM("a5cdda3c-1d4e-4df7-8ef2-b7-3f-ce-04-de-3b")]
830public interface IAccelerationStructure : IResourceView
831{
832    public DeviceAddress getDeviceAddress();
833};
834
835public struct FenceDesc
836{
837    public uint64_t initialValue;
838    public bool isShared;
839};
840
841[COM("7fe1c283-d3f4-48ed-aaf3-01-51-96-4e-7c-b5")]
842public interface IFence
843{
844    /// Returns the currently signaled value on the device.
845    public Result getCurrentValue(uint64_t *outValue);
846
847    /// Signals the fence from the host with the specified value.
848    public Result setCurrentValue(uint64_t value);
849
850    public Result getSharedHandle(InteropHandle *outHandle);
851    public Result getNativeHandle(InteropHandle *outNativeHandle);
852};
853
854public struct ShaderOffset
855{
856    public Int uniformOffset = 0; // TODO: Change to Offset?
857    public GfxIndex bindingRangeIndex = 0;
858    public GfxIndex bindingArrayIndex = 0;
859}
860
861public enum class ShaderObjectContainerType
862{
863    None, Array, StructuredBuffer
864};
865
866[COM("c1fa997e-5ca2-45ae-9bcb-c4-35-9e-85-05-85")]
867public interface IShaderObject
868{
869    public slang::TypeLayoutReflection* getElementTypeLayout();
870    public ShaderObjectContainerType getContainerType();
871    public GfxCount getEntryPointCount();
872    public Result getEntryPoint(GfxIndex index, out Optional<IShaderObject> entryPoint);
873    public Result setData(ShaderOffset *offset, void *data, Size size);
874    public Result getObject(ShaderOffset *offset, out Optional<IShaderObject> object);
875    public Result setObject(ShaderOffset* offset, IShaderObject object);
876    public Result setResource(ShaderOffset* offset, IResourceView resourceView);
877    public Result setSampler(ShaderOffset* offset, ISamplerState sampler);
878    public Result setCombinedTextureSampler(ShaderOffset* offset, IResourceView textureView, ISamplerState sampler);
879
880    /// Manually overrides the specialization argument for the sub-object binding at `offset`.
881    /// Specialization arguments are passed to the shader compiler to specialize the type
882    /// of interface-typed shader parameters.
883    public Result setSpecializationArgs(
884        ShaderOffset* offset,
885        slang::SpecializationArg *args,
886        GfxCount count);
887
888    public Result getCurrentVersion(
889        ITransientResourceHeap transientHeap,
890        out IShaderObject outObject);
891
892    public void* getRawData();
893
894    public Size getSize();
895
896    /// Use the provided constant buffer instead of the internally created one.
897    public Result setConstantBufferOverride(IBufferResource constantBuffer);
898};
899
900public enum class StencilOp : uint8_t
901{
902    Keep,
903    Zero,
904    Replace,
905    IncrementSaturate,
906    DecrementSaturate,
907    Invert,
908    IncrementWrap,
909    DecrementWrap,
910};
911
912public enum class FillMode : uint8_t
913{
914    Solid,
915    Wireframe,
916};
917
918public enum class CullMode : uint8_t
919{
920    None,
921    Front,
922    Back,
923};
924
925public enum class FrontFaceMode : uint8_t
926{
927    CounterClockwise,
928    Clockwise,
929};
930
931public struct DepthStencilOpDesc
932{
933    public StencilOp stencilFailOp = StencilOp::Keep;
934    public StencilOp stencilDepthFailOp = StencilOp::Keep;
935    public StencilOp stencilPassOp = StencilOp::Keep;
936    public ComparisonFunc stencilFunc = ComparisonFunc::Always;
937    public __init()
938    {
939        stencilFailOp = StencilOp::Keep;
940        stencilDepthFailOp = StencilOp::Keep;
941        stencilPassOp = StencilOp::Keep;
942        stencilFunc = ComparisonFunc::Always;
943    }
944};
945
946public struct DepthStencilDesc
947{
948    public bool depthTestEnable = false;
949    public bool depthWriteEnable = true;
950    public ComparisonFunc depthFunc = ComparisonFunc::Less;
951
952    public bool stencilEnable = false;
953    public uint32_t stencilReadMask = 0xFFFFFFFF;
954    public uint32_t stencilWriteMask = 0xFFFFFFFF;
955    public DepthStencilOpDesc frontFace;
956    public DepthStencilOpDesc backFace;
957
958    public uint32_t stencilRef = 0;
959
960    public __init()
961    {
962        depthTestEnable = false;
963        depthWriteEnable = true;
964        depthFunc = ComparisonFunc::Less;
965        stencilEnable = false;
966        stencilReadMask = 0xFFFFFFFF;
967        stencilWriteMask = 0xFFFFFFFF;
968        stencilRef = 0;
969    }
970};
971
972public struct RasterizerDesc
973{
974    public FillMode fillMode = FillMode::Solid;
975    public CullMode cullMode = CullMode::None;
976    public FrontFaceMode frontFace = FrontFaceMode::CounterClockwise;
977    public int32_t depthBias = 0;
978    public float depthBiasClamp = 0.0f;
979    public float slopeScaledDepthBias = 0.0f;
980    public bool depthClipEnable = true;
981    public bool scissorEnable = false;
982    public bool multisampleEnable = false;
983    public bool antialiasedLineEnable = false;
984    public bool enableConservativeRasterization = false;
985    public uint32_t forcedSampleCount = 0;
986
987    public __init()
988    {
989        fillMode = FillMode::Solid;
990        cullMode = CullMode::None;
991        frontFace = FrontFaceMode::CounterClockwise;
992        depthBias = 0;
993        depthBiasClamp = 0.0f;
994        slopeScaledDepthBias = 0.0f;
995        depthClipEnable = true;
996        scissorEnable = false;
997        multisampleEnable = false;
998        antialiasedLineEnable = false;
999        enableConservativeRasterization = false;
1000        forcedSampleCount = 0;
1001    }
1002};
1003
1004public enum class LogicOp
1005{
1006    NoOp,
1007};
1008
1009public enum class BlendOp
1010{
1011    Add,
1012    Subtract,
1013    ReverseSubtract,
1014    Min,
1015    Max,
1016};
1017
1018public enum class BlendFactor
1019{
1020    Zero,
1021    One,
1022    SrcColor,
1023    InvSrcColor,
1024    SrcAlpha,
1025    InvSrcAlpha,
1026    DestAlpha,
1027    InvDestAlpha,
1028    DestColor,
1029    InvDestColor,
1030    SrcAlphaSaturate,
1031    BlendColor,
1032    InvBlendColor,
1033    SecondarySrcColor,
1034    InvSecondarySrcColor,
1035    SecondarySrcAlpha,
1036    InvSecondarySrcAlpha,
1037};
1038
1039public enum RenderTargetWriteMask
1040{
1041    EnableNone = 0,
1042    EnableRed = 0x01,
1043    EnableGreen = 0x02,
1044    EnableBlue = 0x04,
1045    EnableAlpha = 0x08,
1046    EnableAll = 0x0F,
1047};
1048
1049public struct AspectBlendDesc
1050{
1051    public BlendFactor srcFactor = BlendFactor::One;
1052    public BlendFactor dstFactor = BlendFactor::Zero;
1053    public BlendOp op = BlendOp::Add;
1054
1055    __init()
1056    {
1057        srcFactor = BlendFactor::One;
1058        dstFactor = BlendFactor::Zero;
1059        op = BlendOp::Add;
1060    }
1061};
1062
1063public struct TargetBlendDesc
1064{
1065    public AspectBlendDesc color;
1066    public AspectBlendDesc alpha;
1067    public bool enableBlend;
1068    public LogicOp logicOp;
1069    public RenderTargetWriteMask writeMask;
1070    public __init()
1071    {
1072        enableBlend = false;
1073        logicOp = LogicOp::NoOp;
1074        writeMask = RenderTargetWriteMask::EnableAll;
1075    }
1076};
1077
1078public struct BlendDesc
1079{
1080    public TargetBlendDesc targets[kMaxRenderTargetCount] = {};
1081    public GfxCount targetCount = 0;
1082
1083    public bool alphaToCoverageEnable = false;
1084};
1085
1086public struct FramebufferTargetLayout
1087{
1088    public Format format;
1089    public GfxCount sampleCount;
1090};
1091
1092public struct FramebufferLayoutDesc
1093{
1094    public GfxCount renderTargetCount;
1095    public FramebufferTargetLayout *renderTargets;
1096    public FramebufferTargetLayout *depthStencil;
1097};
1098
1099[COM("0a838785-c13a-4832-ad88-64-06-b5-4b-5e-ba")]
1100public interface IFramebufferLayout
1101{
1102};
1103
1104public struct GraphicsPipelineStateDesc
1105{
1106    public NativeRef<IShaderProgram> program;
1107
1108    public NativeRef<IInputLayout> inputLayout;
1109    public NativeRef<IFramebufferLayout> framebufferLayout;
1110    public PrimitiveType primitiveType;
1111    public DepthStencilDesc depthStencil;
1112    public RasterizerDesc rasterizer;
1113    public BlendDesc blend;
1114
1115    public __init()
1116    {
1117        program = {IShaderProgram()};
1118        inputLayout = {IInputLayout()};
1119        framebufferLayout = {IFramebufferLayout()};
1120        primitiveType = PrimitiveType::Triangle;
1121        depthStencil = {};
1122        rasterizer = {};
1123        blend = {};
1124    }
1125};
1126
1127public struct ComputePipelineStateDesc
1128{
1129    public NativeRef<IShaderProgram> program;
1130    public void *d3d12RootSignatureOverride;
1131};
1132
1133public enum RayTracingPipelineFlags
1134{
1135    None = 0,
1136    SkipTriangles = 1,
1137    SkipProcedurals = 2,
1138};
1139
1140public struct HitGroupDesc
1141{
1142    public NativeString hitGroupName;
1143    public NativeString closestHitEntryPoint;
1144    public NativeString anyHitEntryPoint;
1145    public NativeString intersectionEntryPoint;
1146};
1147
1148public struct RayTracingPipelineStateDesc
1149{
1150    public NativeRef<IShaderProgram> program;
1151    public GfxCount hitGroupCount = 0;
1152    public HitGroupDesc *hitGroups;
1153    public int maxRecursion = 0;
1154    public Size maxRayPayloadSize = 0;
1155    public Size maxAttributeSizeInBytes = 8;
1156    public RayTracingPipelineFlags flags = RayTracingPipelineFlags::None;
1157};
1158
1159// Specifies the bytes to overwrite into a record in the shader table.
1160public struct ShaderRecordOverwrite
1161{
1162    public Offset offset;   // Offset within the shader record.
1163    public Size size;       // Number of bytes to overwrite.
1164    public uint8_t data[8]; // Content to overwrite.
1165};
1166
1167public struct ShaderTableDesc
1168{
1169    public GfxCount rayGenShaderCount;
1170    public NativeString* rayGenShaderEntryPointNames;
1171    public ShaderRecordOverwrite *rayGenShaderRecordOverwrites;
1172
1173    public GfxCount missShaderCount;
1174    public NativeString *missShaderEntryPointNames;
1175    public ShaderRecordOverwrite *missShaderRecordOverwrites;
1176
1177    public GfxCount hitGroupCount;
1178    public NativeString *hitGroupNames;
1179    public ShaderRecordOverwrite *hitGroupRecordOverwrites;
1180
1181    NativeRef<IShaderProgram> program;
1182};
1183
1184[COM("a721522c-df31-4c2f-a5e7-3b-e0-12-4b-31-78")]
1185public interface IShaderTable
1186{
1187
1188};
1189
1190[COM("0ca7e57d-8a90-44f3-bdb1-fe-9b-35-3f-5a-72")]
1191public interface IPipelineState
1192{
1193    Result getNativeHandle(InteropHandle *outHandle);
1194};
1195
1196public struct ScissorRect
1197{
1198    public int32_t minX;
1199    public int32_t minY;
1200    public int32_t maxX;
1201    public int32_t maxY;
1202};
1203
1204public struct Viewport
1205{
1206    public float originX = 0.0f;
1207    public float originY = 0.0f;
1208    public float extentX = 0.0f;
1209    public float extentY = 0.0f;
1210    public float minZ = 0.0f;
1211    public float maxZ = 1.0f;
1212};
1213
1214public struct FramebufferDesc
1215{
1216    public GfxCount renderTargetCount;
1217    public NativeRef<IResourceView> *renderTargetViews;
1218    public NativeRef<IResourceView> depthStencilView;
1219    public NativeRef<IFramebufferLayout> layout;
1220};
1221
1222[COM("0f0c0d9a-4ef3-4e18-9ba9-34-60-ea-69-87-95")]
1223public interface IFramebuffer
1224{
1225};
1226
1227public enum class WindowHandleType
1228{
1229    Unknown,
1230    Win32Handle,
1231    XLibHandle,
1232};
1233
1234public struct WindowHandle
1235{
1236    public WindowHandleType type;
1237    public void* handleValues[2];
1238    public static WindowHandle fromHwnd(void *hwnd)
1239    {
1240        WindowHandle handle = {WindowHandleType::Unknown, {nullptr, nullptr}};
1241        handle.type = WindowHandleType::Win32Handle;
1242        handle.handleValues[0] = hwnd;
1243        return handle;
1244    }
1245    public static WindowHandle fromXWindow(void *xdisplay, uint32_t xwindow)
1246    {
1247        WindowHandle handle = {WindowHandleType::Unknown, {nullptr, nullptr}};
1248        handle.type = WindowHandleType::XLibHandle;
1249        handle.handleValues[0] = xdisplay;
1250        handle.handleValues[1] = (void*)xwindow;
1251        return handle;
1252    }
1253};
1254
1255public enum FaceMask
1256{
1257    Front = 1, Back = 2
1258};
1259
1260public enum class TargetLoadOp
1261{
1262    Load, Clear, DontCare
1263};
1264public enum class TargetStoreOp
1265{
1266    Store, DontCare
1267};
1268public struct TargetAccessDesc
1269{
1270    public TargetLoadOp loadOp;
1271    public TargetLoadOp stencilLoadOp;
1272    public TargetStoreOp storeOp;
1273    public TargetStoreOp stencilStoreOp;
1274    public ResourceState initialState;
1275    public ResourceState finalState;
1276};
1277public struct RenderPassLayoutDesc
1278{
1279    public NativeRef<IFramebufferLayout> framebufferLayout;
1280    public GfxCount renderTargetCount;
1281    public TargetAccessDesc *renderTargetAccess;
1282    public TargetAccessDesc *depthStencilAccess;
1283};
1284
1285[COM("daab0b1a-f45d-4ae9-bf2c-e0-bb-76-7d-fa-d1")]
1286public interface IRenderPassLayout
1287{
1288};
1289
1290public enum class QueryType
1291{
1292    Timestamp,
1293    AccelerationStructureCompactedSize,
1294    AccelerationStructureSerializedSize,
1295    AccelerationStructureCurrentSize,
1296};
1297
1298public struct QueryPoolDesc
1299{
1300    public QueryType type;
1301    public GfxCount count;
1302};
1303
1304[COM("c2cc3784-12da-480a-a874-8b-31-96-1c-a4-36")]
1305public interface IQueryPool
1306{
1307    public Result getResult(GfxIndex queryIndex, GfxCount count, uint64_t *data);
1308    public Result reset();
1309};
1310
1311[COM("77ea6383-be3d-40aa-8b45-fd-f0-d7-5b-fa-34")]
1312public interface ICommandEncoder
1313{
1314    public void endEncoding();
1315    public void writeTimestamp(IQueryPool queryPool, GfxIndex queryIndex);
1316};
1317
1318public struct IndirectDispatchArguments
1319{
1320    public GfxCount ThreadGroupCountX;
1321    public GfxCount ThreadGroupCountY;
1322    public GfxCount ThreadGroupCountZ;
1323};
1324
1325public struct IndirectDrawArguments
1326{
1327    public GfxCount VertexCountPerInstance;
1328    public GfxCount InstanceCount;
1329    public GfxIndex StartVertexLocation;
1330    public GfxIndex StartInstanceLocation;
1331};
1332
1333public struct IndirectDrawIndexedArguments
1334{
1335    public GfxCount IndexCountPerInstance;
1336    public GfxCount InstanceCount;
1337    public GfxIndex StartIndexLocation;
1338    public GfxIndex BaseVertexLocation;
1339    public GfxIndex StartInstanceLocation;
1340};
1341
1342public struct SamplePosition
1343{
1344    public int8_t x;
1345    public int8_t y;
1346};
1347
1348public enum ClearResourceViewFlags
1349{
1350    None = 0,
1351    ClearDepth = 1,
1352    ClearStencil = 2,
1353    FloatClearValues = 4
1354};
1355
1356[COM("F99A00E9-ED50-4088-8A0E-3B26755031EA")]
1357public interface IResourceCommandEncoder : ICommandEncoder
1358{
1359    public void copyBuffer(
1360                 IBufferResource dst,
1361                 Offset dstOffset,
1362                 IBufferResource src,
1363                 Offset srcOffset,
1364                 Size size);
1365    /// Copies texture from src to dst. If dstSubresource and srcSubresource has mipLevelCount = 0
1366    /// and layerCount = 0, the entire resource is being copied and dstOffset, srcOffset and extent
1367    /// arguments are ignored.
1368    public void copyTexture(
1369        ITextureResource dst,
1370        ResourceState dstState,
1371        SubresourceRange dstSubresource,
1372        int3 dstOffset,
1373        NativeRef<ITextureResource> src,
1374        ResourceState srcState,
1375        SubresourceRange srcSubresource,
1376        int3 srcOffset,
1377        int3 extent);
1378
1379    /// Copies texture to a buffer. Each row is aligned to kTexturePitchAlignment.
1380    public void copyTextureToBuffer(
1381        IBufferResource dst,
1382        Offset dstOffset,
1383        Size dstSize,
1384        Size dstRowStride,
1385        ITextureResource src,
1386        ResourceState srcState,
1387        SubresourceRange srcSubresource,
1388        int3 srcOffset,
1389        int3 extent);
1390    public void uploadTextureData(
1391        ITextureResource dst,
1392        SubresourceRange subResourceRange,
1393        int3 offset,
1394        int3 extent,
1395        SubresourceData *subResourceData,
1396        GfxCount subResourceDataCount);
1397    public void uploadBufferData(IBufferResource dst, Offset offset, Size size, void *data);
1398    public void textureBarrier(
1399        GfxCount count, NativeRef<ITextureResource> *textures, ResourceState src, ResourceState dst);
1400    public void textureSubresourceBarrier(
1401        ITextureResource texture,
1402        SubresourceRange subresourceRange,
1403        ResourceState src,
1404        ResourceState dst);
1405    public void bufferBarrier(
1406        GfxCount count, NativeRef<IBufferResource> *buffers, ResourceState src, ResourceState dst);
1407    public void clearResourceView(
1408        IResourceView view, ClearValue *clearValue, ClearResourceViewFlags flags);
1409    public void resolveResource(
1410        ITextureResource source,
1411        ResourceState sourceState,
1412        SubresourceRange sourceRange,
1413        ITextureResource dest,
1414        ResourceState destState,
1415        SubresourceRange destRange);
1416    public void resolveQuery(
1417        IQueryPool queryPool,
1418        GfxIndex index,
1419        GfxCount count,
1420        IBufferResource buffer,
1421        Offset offset);
1422    public void beginDebugEvent(NativeString name, float rgbColor[3]);
1423    public void endDebugEvent();
1424};
1425
1426[COM("7A8D56D0-53E6-4AD6-85F7-D14DC110FDCE")]
1427public interface IRenderCommandEncoder : IResourceCommandEncoder
1428{
1429    // Sets the current pipeline state. This method returns a transient shader object for
1430    // writing shader parameters. This shader object will not retain any resources or
1431    // sub-shader-objects bound to it. The user must be responsible for ensuring that any
1432    // resources or shader objects that is set into `outRootShaderObject` stays alive during
1433    // the execution of the command buffer.
1434    public Result bindPipeline(IPipelineState state, out IShaderObject outRootShaderObject);
1435
1436    // Sets the current pipeline state along with a pre-created mutable root shader object.
1437    public Result bindPipelineWithRootObject(IPipelineState state, NativeRef<IShaderObject> rootObject);
1438
1439    public void setViewports(GfxCount count, Viewport *viewports);
1440    public void setScissorRects(GfxCount count, ScissorRect *scissors);
1441
1442    public void setPrimitiveTopology(PrimitiveTopology topology);
1443    public void setVertexBuffers(
1444        GfxIndex startSlot,
1445        GfxCount slotCount,
1446        NativeRef<IBufferResource>* buffers,
1447        Offset *offsets);
1448
1449    public void setIndexBuffer(IBufferResource buffer, Format indexFormat, Offset offset);
1450    public void draw(GfxCount vertexCount, GfxIndex startVertex);
1451    public void drawIndexed(GfxCount indexCount, GfxIndex startIndex = 0, GfxIndex baseVertex = 0);
1452    public void drawIndirect(
1453        GfxCount maxDrawCount,
1454        IBufferResource argBuffer,
1455        Offset argOffset,
1456        NativeRef<IBufferResource> countBuffer,
1457        Offset countOffset = 0);
1458    public void drawIndexedIndirect(
1459        GfxCount maxDrawCount,
1460        IBufferResource argBuffer,
1461        Offset argOffset,
1462        NativeRef<IBufferResource> countBuffer,
1463        Offset countOffset = 0);
1464    public void setStencilReference(uint32_t referenceValue);
1465    public Result setSamplePositions(
1466        GfxCount samplesPerPixel, GfxCount pixelCount, SamplePosition *samplePositions);
1467    public void drawInstanced(
1468        GfxCount vertexCount,
1469        GfxCount instanceCount,
1470        GfxIndex startVertex,
1471        GfxIndex startInstanceLocation);
1472    public void drawIndexedInstanced(
1473        GfxCount indexCount,
1474        GfxCount instanceCount,
1475        GfxIndex startIndexLocation,
1476        GfxIndex baseVertexLocation,
1477        GfxIndex startInstanceLocation);
1478};
1479
1480[COM("88AA9322-82F7-4FE6-A68A-29C7FE798737")]
1481public interface IComputeCommandEncoder : IResourceCommandEncoder
1482{
1483    // Sets the current pipeline state. This method returns a transient shader object for
1484    // writing shader parameters. This shader object will not retain any resources or
1485    // sub-shader-objects bound to it. The user must be responsible for ensuring that any
1486    // resources or shader objects that is set into `outRooShaderObject` stays alive during
1487    // the execution of the command buffer.
1488    public Result bindPipeline(IPipelineState state, out Optional<IShaderObject> outRootShaderObject);
1489
1490    // Sets the current pipeline state along with a pre-created mutable root shader object.
1491    public Result bindPipelineWithRootObject(IPipelineState state, IShaderObject rootObject);
1492
1493    public void dispatchCompute(int x, int y, int z);
1494    public void dispatchComputeIndirect(IBufferResource cmdBuffer, Offset offset);
1495};
1496
1497public enum class AccelerationStructureCopyMode
1498{
1499    Clone, Compact
1500};
1501
1502public struct AccelerationStructureQueryDesc
1503{
1504    public QueryType queryType;
1505
1506    public NativeRef<IQueryPool> queryPool;
1507
1508    public GfxIndex firstQueryIndex;
1509};
1510
1511[COM("9a672b87-5035-45e3-967c-1f-85-cd-b3-63-4f")]
1512public interface IRayTracingCommandEncoder : IResourceCommandEncoder
1513{
1514    public void buildAccelerationStructure(
1515        AccelerationStructureBuildDesc *desc,
1516        GfxCount propertyQueryCount,
1517        AccelerationStructureQueryDesc *queryDescs);
1518    public void copyAccelerationStructure(
1519        NativeRef<IAccelerationStructure> dest,
1520        NativeRef<IAccelerationStructure> src,
1521        AccelerationStructureCopyMode mode);
1522    public void queryAccelerationStructureProperties(
1523        GfxCount accelerationStructureCount,
1524        NativeRef<IAccelerationStructure> *accelerationStructures,
1525        GfxCount queryCount,
1526        AccelerationStructureQueryDesc *queryDescs);
1527    public void serializeAccelerationStructure(DeviceAddress dest, IAccelerationStructure source);
1528    public void deserializeAccelerationStructure(IAccelerationStructure dest, DeviceAddress source);
1529
1530    public Result bindPipeline(IPipelineState state, out IShaderObject rootObject);
1531    // Sets the current pipeline state along with a pre-created mutable root shader object.
1532    public Result bindPipelineWithRootObject(IPipelineState state, IShaderObject rootObject);
1533
1534    /// Issues a dispatch command to start ray tracing workload with a ray tracing pipeline.
1535    /// `rayGenShaderIndex` specifies the index into the shader table that identifies the ray generation shader.
1536    public void dispatchRays(
1537        GfxIndex rayGenShaderIndex,
1538        NativeRef<IShaderTable> shaderTable,
1539        GfxCount width,
1540        GfxCount height,
1541        GfxCount depth);
1542};
1543
1544[COM("5d56063f-91d4-4723-a7a7-7a-15-af-93-eb-48")]
1545public interface ICommandBuffer
1546{
1547    // Only one encoder may be open at a time. User must call `ICommandEncoder::endEncoding`
1548    // before calling other `encode*Commands` methods.
1549    // Once `endEncoding` is called, the `ICommandEncoder` object becomes obsolete and is
1550    // invalid for further use. To continue recording, the user must request a new encoder
1551    // object by calling one of the `encode*Commands` methods again.
1552    public void encodeRenderCommands(
1553        IRenderPassLayout renderPass,
1554        IFramebuffer framebuffer,
1555        out IRenderCommandEncoder outEncoder);
1556
1557    public void encodeComputeCommands(out Optional<IComputeCommandEncoder> encoder);
1558
1559    public void encodeResourceCommands(out Optional<IResourceCommandEncoder> outEncoder);
1560
1561    public void encodeRayTracingCommands(out Optional<IRayTracingCommandEncoder> outEncoder);
1562
1563    public void close();
1564
1565    public Result getNativeHandle(out InteropHandle outHandle);
1566};
1567
1568public enum class QueueType
1569{
1570    Graphics
1571};
1572public struct CommandQueueDesc
1573{
1574    public QueueType type;
1575};
1576
1577[COM("14e2bed0-0ad0-4dc8-b341-06-3f-e7-2d-bf-0e")]
1578public interface ICommandQueue
1579{
1580    public const CommandQueueDesc* getDesc();
1581
1582    public void executeCommandBuffers(
1583        GfxCount count,
1584        NativeRef<ICommandBuffer> *commandBuffers,
1585        Optional<IFence> fenceToSignal,
1586        uint64_t newFenceValue);
1587
1588    public Result getNativeHandle(out InteropHandle outHandle);
1589
1590    public void waitOnHost();
1591
1592    /// Queues a device side wait for the given fences.
1593    public Result waitForFenceValuesOnDevice(GfxCount fenceCount, NativeRef<IFence> *fences, uint64_t *waitValues);
1594};
1595
1596public enum TransientResourceHeapFlags
1597{
1598    None = 0,
1599    AllowResizing = 0x1,
1600};
1601
1602public struct TransientResourceHeapDesc
1603{
1604    public TransientResourceHeapFlags flags;
1605    public Size constantBufferSize;
1606    public GfxCount samplerDescriptorCount;
1607    public GfxCount uavDescriptorCount;
1608    public GfxCount srvDescriptorCount;
1609    public GfxCount constantBufferDescriptorCount;
1610    public GfxCount accelerationStructureDescriptorCount;
1611};
1612
1613[COM("cd48bd29-ee72-41b8-bcff-0a-2b-3a-aa-6d-0b")]
1614public interface ITransientResourceHeap
1615{
1616    // Waits until GPU commands issued before last call to `finish()` has been completed, and resets
1617    // all transient resources holds by the heap.
1618    // This method must be called before using the transient heap to issue new GPU commands.
1619    // In most situations this method should be called at the beginning of each frame.
1620    public Result synchronizeAndReset();
1621
1622    // Must be called when the application has done using this heap to issue commands. In most situations
1623    // this method should be called at the end of each frame.
1624    public Result finish();
1625
1626    // Command buffers are one-time use. Once it is submitted to the queue via
1627    // `executeCommandBuffers` a command buffer is no longer valid to be used any more. Command
1628    // buffers must be closed before submission. The current D3D12 implementation has a limitation
1629    // that only one command buffer maybe recorded at a time. User must finish recording a command
1630    // buffer before creating another command buffer.
1631    public Result createCommandBuffer(out Optional<ICommandBuffer> outCommandBuffer);
1632};
1633
1634public struct SwapchainDesc
1635{
1636    public Format format;
1637    public GfxCount width, height;
1638    public GfxCount imageCount;
1639    public NativeRef<ICommandQueue> queue;
1640    public bool enableVSync;
1641};
1642
1643[COM("be91ba6c-0784-4308-a1-00-19-c3-66-83-44-b2")]
1644public interface ISwapchain
1645{
1646    public const SwapchainDesc* getDesc();
1647
1648    /// Returns the back buffer image at `index`.
1649    public Result getImage(GfxIndex index, out ITextureResource outResource);
1650
1651    /// Present the next image in the swapchain.
1652    public Result present();
1653
1654    /// Returns the index of next back buffer image that will be presented in the next
1655    /// `present` call. If the swapchain is invalid/out-of-date, this method returns -1.
1656    public int acquireNextImage();
1657
1658    /// Resizes the back buffers of this swapchain. All render target views and framebuffers
1659    /// referencing the back buffer images must be freed before calling this method.
1660    public Result resize(GfxCount width, GfxCount height);
1661
1662    // Check if the window is occluded.
1663    public bool isOccluded();
1664
1665    // Toggle full screen mode.
1666    public Result setFullScreenMode(bool mode);
1667};
1668
1669public struct DeviceInfo
1670{
1671    public DeviceType deviceType;
1672
1673    public BindingStyle bindingStyle;
1674
1675    public ProjectionStyle projectionStyle;
1676
1677    /// An projection matrix that ensures x, y mapping to pixels
1678    /// is the same on all targets
1679    public float identityProjectionMatrix[16];
1680
1681    /// The name of the graphics API being used by this device.
1682    public NativeString apiName;
1683
1684    /// The name of the graphics adapter.
1685    public NativeString adapterName;
1686
1687    /// The clock frequency used in timestamp queries.
1688    public uint64_t timestampFrequency;
1689};
1690
1691public enum class DebugMessageType
1692{
1693    Info, Warning, Error
1694};
1695public enum class DebugMessageSource
1696{
1697    Layer, Driver, Slang
1698};
1699
1700[COM("B219D7E8-255A-2572-D46C-A0E5D99CEB90")]
1701public interface IDebugCallback
1702{
1703    public void handleMessage(DebugMessageType type, DebugMessageSource source, NativeString message);
1704};
1705
1706public struct SlangDesc
1707{
1708    public NativeRef<slang::IGlobalSession> slangGlobalSession = {slang::IGlobalSession()}; // (optional) A slang global session object. If null will create automatically.
1709
1710    public slang::SlangMatrixLayoutMode defaultMatrixLayoutMode = slang::SlangMatrixLayoutMode::SLANG_MATRIX_LAYOUT_ROW_MAJOR;
1711
1712    public NativeString *searchPaths = nullptr;
1713    public GfxCount searchPathCount = 0;
1714
1715    public slang::PreprocessorMacroDesc *preprocessorMacros = nullptr;
1716    public GfxCount preprocessorMacroCount = 0;
1717
1718    public NativeString targetProfile = ""; // (optional) Target shader profile. If null this will be set to platform dependent default.
1719    public slang::SlangFloatingPointMode floatingPointMode = slang::SlangFloatingPointMode::SLANG_FLOATING_POINT_MODE_DEFAULT;
1720    public slang::SlangOptimizationLevel optimizationLevel = slang::SlangOptimizationLevel::SLANG_OPTIMIZATION_LEVEL_DEFAULT;
1721    public slang::SlangTargetFlags targetFlags = slang::SlangTargetFlags.None;
1722    public slang::SlangLineDirectiveMode lineDirectiveMode = slang::SlangLineDirectiveMode::SLANG_LINE_DIRECTIVE_MODE_DEFAULT;
1723};
1724
1725public struct ShaderCacheDesc
1726{
1727    // The root directory for the shader cache. If not set, shader cache is disabled.
1728    public NativeString shaderCachePath = "";
1729    // The maximum number of entries stored in the cache.
1730    public GfxCount maxEntryCount = 0;
1731};
1732
1733public struct DeviceInteropHandles
1734{
1735    public InteropHandle handles[3] = {};
1736};
1737
1738public struct DeviceDesc
1739{
1740    // The underlying API/Platform of the device.
1741    public DeviceType deviceType = DeviceType::Default;
1742    // The device's handles (if they exist) and their associated API. For D3D12, this contains a single InteropHandle
1743    // for the ID3D12Device. For Vulkan, the first InteropHandle is the VkInstance, the second is the VkPhysicalDevice,
1744    // and the third is the VkDevice. For CUDA, this only contains a single value for the CUDADevice.
1745    public DeviceInteropHandles existingDeviceHandles = {};
1746    // Name to identify the adapter to use
1747    public NativeString adapter = "";
1748    // Number of required features.
1749    public GfxCount requiredFeatureCount = 0;
1750    // Array of required feature names, whose size is `requiredFeatureCount`.
1751    public NativeString *requiredFeatures = nullptr;
1752    // A command dispatcher object that intercepts and handles actual low-level API call.
1753    void *apiCommandDispatcher = nullptr;
1754    // The slot (typically UAV) used to identify NVAPI intrinsics. If >=0 NVAPI is required.
1755    public GfxIndex nvapiExtnSlot = -1;
1756    // Configurations for the shader cache.
1757    public ShaderCacheDesc shaderCache = {};
1758    // Configurations for Slang compiler.
1759    public SlangDesc slang = {};
1760
1761    public GfxCount extendedDescCount = 0;
1762    public void **extendedDescs = nullptr;
1763};
1764
1765[COM("715bdf26-5135-11eb-AE93-02-42-AC-13-00-02")]
1766public interface IDevice
1767{
1768    public Result getNativeDeviceHandles(out DeviceInteropHandles outHandles);
1769
1770    public bool hasFeature(NativeString feature);
1771
1772    /// Returns a list of features supported by the renderer.
1773    public Result getFeatures(NativeString *outFeatures, Size bufferSize, GfxCount *outFeatureCount);
1774
1775    public Result getFormatSupportedResourceStates(Format format, ResourceStateSet *outStates);
1776
1777    public Result getSlangSession(NativeRef<slang::ISession>* outSlangSession);
1778
1779    public Result createTransientResourceHeap(
1780        TransientResourceHeapDesc *desc,
1781        out Optional<ITransientResourceHeap> outHeap);
1782
1783    /// Create a texture resource.
1784    ///
1785    /// If `initData` is non-null, then it must point to an array of
1786    /// `ITextureResource::SubresourceData` with one element for each
1787    /// subresource of the texture being created.
1788    ///
1789    /// The number of subresources in a texture is:
1790    ///
1791    ///     effectiveElementCount * mipLevelCount
1792    ///
1793    /// where the effective element count is computed as:
1794    ///
1795    ///     effectiveElementCount = (isArray ? arrayElementCount : 1) * (isCube ? 6 : 1);
1796    ///
1797    public Result createTextureResource(
1798        TextureResourceDesc* desc,
1799        SubresourceData *initData,
1800        out ITextureResource outResource);
1801
1802    public Result createTextureFromNativeHandle(
1803        InteropHandle handle,
1804        TextureResourceDesc* srcDesc,
1805        out ITextureResource outResource);
1806
1807    public Result createTextureFromSharedHandle(
1808        InteropHandle handle,
1809        TextureResourceDesc *srcDesc,
1810        Size size,
1811        out ITextureResource outResource);
1812
1813    /// Create a buffer resource
1814    public Result createBufferResource(
1815        BufferResourceDesc* desc,
1816        void *initData,
1817        out Optional<IBufferResource> outResource);
1818
1819    public Result createBufferFromNativeHandle(
1820        InteropHandle handle,
1821        BufferResourceDesc* srcDesc,
1822        out IBufferResource outResource);
1823
1824    public Result createBufferFromSharedHandle(
1825        InteropHandle handle,
1826        BufferResourceDesc* srcDesc,
1827        out IBufferResource outResource);
1828
1829    public Result createSamplerState(SamplerStateDesc* desc, out ISamplerState outSampler);
1830
1831    public Result createTextureView(
1832        ITextureResource texture, ResourceViewDesc* desc, out IResourceView outView);
1833
1834    public Result createBufferView(
1835        IBufferResource buffer,
1836        Optional<IBufferResource> counterBuffer,
1837        ResourceViewDesc* desc,
1838        out Optional<IResourceView> outView);
1839
1840    public Result createFramebufferLayout(FramebufferLayoutDesc* desc, out IFramebufferLayout outFrameBuffer);
1841
1842    public Result createFramebuffer(FramebufferDesc* desc, out IFramebuffer outFrameBuffer);
1843
1844    public Result createRenderPassLayout(
1845        RenderPassLayoutDesc* desc,
1846        out IRenderPassLayout outRenderPassLayout);
1847
1848    public Result createSwapchain(
1849        SwapchainDesc* desc, WindowHandle window, out ISwapchain outSwapchain);
1850
1851    public Result createInputLayout(
1852        InputLayoutDesc* desc, out IInputLayout outLayout);
1853
1854    public Result createCommandQueue(CommandQueueDesc* desc, out Optional<ICommandQueue> outQueue);
1855
1856    public Result createShaderObject(
1857        slang::TypeReflection *type,
1858        ShaderObjectContainerType container,
1859        out IShaderObject outObject);
1860
1861    public Result createMutableShaderObject(
1862        slang::TypeReflection *type,
1863        ShaderObjectContainerType container,
1864        out IShaderObject outObject);
1865
1866    public Result createShaderObjectFromTypeLayout(
1867        slang::TypeLayoutReflection *typeLayout, out IShaderObject outObject);
1868
1869    public Result createMutableShaderObjectFromTypeLayout(
1870        slang::TypeLayoutReflection *typeLayout, out IShaderObject outObject);
1871
1872    public Result createMutableRootShaderObject(
1873        IShaderProgram program,
1874        out IShaderObject outObject);
1875
1876    public Result createShaderTable(ShaderTableDesc* desc, out IShaderTable outTable);
1877
1878    public Result createProgram(
1879        void *desc,
1880        out IShaderProgram outProgram,
1881        out slang::ISlangBlob outDiagnosticBlob);
1882
1883    public Result createProgram2(
1884        ShaderProgramDesc2 *desc,
1885        out Optional<IShaderProgram> outProgram,
1886        out Optional<slang::ISlangBlob> outDiagnosticBlob);
1887
1888    public Result createGraphicsPipelineState(
1889        GraphicsPipelineStateDesc *desc,
1890        out Optional<IPipelineState> outState);
1891
1892    public Result createComputePipelineState(
1893        ComputePipelineStateDesc* desc,
1894        out Optional<IPipelineState> outState);
1895
1896    public Result createRayTracingPipelineState(
1897        RayTracingPipelineStateDesc *desc, out Optional<IPipelineState> outState);
1898
1899    /// Read back texture resource and stores the result in `outBlob`.
1900    public Result readTextureResource(
1901        ITextureResource resource,
1902        ResourceState state,
1903        out slang::ISlangBlob outBlob,
1904        out Size outRowPitch,
1905        out Size outPixelSize);
1906
1907    public Result readBufferResource(
1908        IBufferResource buffer,
1909        Offset offset,
1910        Size size,
1911        out Optional<slang::ISlangBlob> outBlob);
1912
1913    /// Get the type of this renderer
1914    public DeviceInfo* getDeviceInfo();
1915
1916    public Result createQueryPool(
1917        QueryPoolDesc* desc, out IQueryPool outPool);
1918
1919    public Result getAccelerationStructurePrebuildInfo(
1920        AccelerationStructureBuildInputs* buildInputs,
1921        out AccelerationStructurePrebuildInfo outPrebuildInfo);
1922
1923    public Result createAccelerationStructure(
1924        AccelerationStructureCreateDesc* desc,
1925        out IAccelerationStructure outView);
1926
1927    public Result createFence(FenceDesc* desc, out IFence outFence);
1928
1929    /// Wait on the host for the fences to signals.
1930    /// `timeout` is in nanoseconds, can be set to `kTimeoutInfinite`.
1931    public Result waitForFences(
1932        GfxCount fenceCount,
1933        NativeRef<IFence>* fences,
1934        uint64_t *values,
1935        bool waitForAll,
1936        uint64_t timeout);
1937
1938    public Result getTextureAllocationInfo(
1939        TextureResourceDesc* desc, out Size outSize, out Size outAlignment);
1940
1941    public Result getTextureRowAlignment(out Size outAlignment);
1942};
1943
1944public struct ShaderCacheStats
1945{
1946    public GfxCount hitCount;
1947    public GfxCount missCount;
1948    public GfxCount entryCount;
1949};
1950
1951[COM("715bdf26-5135-11eb-AE93-02-42-AC-13-00-02")]
1952public interface IShaderCache
1953{
1954    public Result clearShaderCache();
1955    public Result getShaderCacheStats(out ShaderCacheStats outStats);
1956    public Result resetShaderCacheStats();
1957};
1958
1959#define SLANG_GFX_IMPORT [DllImport("gfx")]
1960/// Checks if format is compressed
1961SLANG_GFX_IMPORT public bool gfxIsCompressedFormat(Format format);
1962
1963/// Checks if format is typeless
1964SLANG_GFX_IMPORT public bool gfxIsTypelessFormat(Format format);
1965
1966/// Gets information about the format
1967SLANG_GFX_IMPORT public Result gfxGetFormatInfo(Format format, FormatInfo *outInfo);
1968
1969/// Given a type returns a function that can conpublic struct it, or nullptr if there isn't one
1970SLANG_GFX_IMPORT public Result gfxCreateDevice(const Ptr<DeviceDesc> desc, out Optional<IDevice> outDevice);
1971
1972/// Reports current set of live objects in gfx.
1973/// Currently this only calls D3D's ReportLiveObjects.
1974SLANG_GFX_IMPORT public Result gfxReportLiveObjects();
1975
1976/// Sets a callback for receiving debug messages.
1977/// The layer does not hold a strong reference to the callback object.
1978/// The user is responsible for holding the callback object alive.
1979SLANG_GFX_IMPORT public Result gfxSetDebugCallback(IDebugCallback callback);
1980
1981/// Enables debug layer. The debug layer will check all `gfx` calls and verify that uses are valid.
1982SLANG_GFX_IMPORT public void gfxEnableDebugLayer();
1983
1984SLANG_GFX_IMPORT public NativeString gfxGetDeviceTypeName(DeviceType type);
1985
1986public bool succeeded(Result code)
1987{
1988    return code >= 0;
1989}
1990
1991}