From a28bda0d7817df3106908a56c17bfcb00e526cdb Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Wed, 28 Aug 2024 21:25:41 -0700 Subject: [PATCH 01/24] feat: apple support Signed-off-by: Michael Pollind --- CMakeLists.txt | 18 ++++++++- Include/.DS_Store | Bin 0 -> 6148 bytes Include/Extensions/NRIWrapperMTL.h | 24 ++++++++++++ Include/NRIDescs.h | 16 +++++++- Source/Creation/Creation.cpp | 25 ++++++++++++- Source/Metal/BufferMetal.h | 14 +++++++ Source/Metal/BufferMetal.mm | 2 + Source/Metal/DeviceMetal.h | 36 ++++++++++++++++++ Source/Metal/DeviceMetal.hpp | 17 +++++++++ Source/Metal/DeviceMetal.mm | 57 +++++++++++++++++++++++++++++ Source/Shared/SharedExternal.h | 2 + Source/VK/DeviceVK.h | 3 +- 12 files changed, 209 insertions(+), 5 deletions(-) create mode 100644 Include/.DS_Store create mode 100644 Include/Extensions/NRIWrapperMTL.h create mode 100644 Source/Metal/BufferMetal.h create mode 100644 Source/Metal/BufferMetal.mm create mode 100644 Source/Metal/DeviceMetal.h create mode 100644 Source/Metal/DeviceMetal.hpp create mode 100644 Source/Metal/DeviceMetal.mm diff --git a/CMakeLists.txt b/CMakeLists.txt index 2f7197b..b1e6b67 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,6 +5,8 @@ option (NRI_STATIC_LIBRARY "Build static library" OFF) # Options: backends option (NRI_ENABLE_NONE_SUPPORT "Enable NONE backend" ON) +option (NRI_ENABLE_VK_SUPPORT "Enable VULKAN backend" ON) +option (NRI_ENABLE_METAL_SUPPORT "Enable METAL backend" ON) option (NRI_ENABLE_D3D11_SUPPORT "Enable D3D11 backend" ON) option (NRI_ENABLE_D3D12_SUPPORT "Enable D3D12 backend" ON) option (NRI_ENABLE_VK_SUPPORT "Enable VULKAN backend" ON) @@ -226,8 +228,19 @@ if (WIN32 AND NRI_ENABLE_D3D12_SUPPORT) endif () endif () +# METAL +if (NRI_ENABLE_METAL_SUPPORT AND APPLE) + message ("NRI adding backend: METAL") + set (COMPILE_DEFINITIONS ${COMPILE_DEFINITIONS} NRI_USE_MTL=1) + file (GLOB MTL_SOURCE "Source/Metal/*.cpp" "Source/Metal/*.mm" "Source/Metal/*.h" "Source/Metal/*.hpp" ) + source_group ("" FILES ${MTL_SOURCE}) + add_library (NRI_MTL STATIC ${MTL_SOURCE}) + target_include_directories (NRI_MTL PRIVATE "Include" "Source/Shared" "External") + target_compile_definitions (NRI_MTL PRIVATE ${COMPILE_DEFINITIONS}) +endif() + # VK -if (NRI_ENABLE_VK_SUPPORT) +if (NRI_ENABLE_VK_SUPPORT AND NOT APPLE) message ("NRI adding backend: VK") set (COMPILE_DEFINITIONS ${COMPILE_DEFINITIONS} NRI_USE_VK=1) @@ -335,6 +348,9 @@ endif () if (NRI_ENABLE_VK_SUPPORT) target_link_libraries (${PROJECT_NAME} PRIVATE NRI_VK) endif () +if (NRI_ENABLE_METAL_SUPPORT) + target_link_libraries (${PROJECT_NAME} PRIVATE NRI_MTL) +endif () set_property (TARGET ${PROJECT_NAME} PROPERTY FOLDER ${PROJECT_FOLDER}) diff --git a/Include/.DS_Store b/Include/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..dbf90847cd1bd865f676ed42ad220f31e71536bd GIT binary patch literal 6148 zcmeHKO>Yx15FNKE*`z|sfv*eFN?fB7Dis=W*{12C2RL*Q8~}ygB%&*}>nOV+MNy=^ z0zZZ$|Aha-3EtRKi6qT|3qp}c8o#l}&yHVYdrd^DGZ{Q0Y7mhJXROpwTw|PPU$HG| zsRET5Bcq%W(!}V@Dc}_N-xc7!Tc;Dcq=JTK-^%_yO?5v`b&Nb84oC34U&auv;l$H? zB%JT@C{6OB)%u~fwkta~s$SLG_1=c(dKwl{G08j8_%+vFXr0DaaTLEyhSOf-*0Iit zD9MInLr4Zgbb0eC$p(7b(UWYD8*XS5Ud^lZ8h2;2gZ6&YKX@{4`m^?atLZ;JY|rO4 z@AiX-PtSTE(u+)gHb0&ejw@p~1+U->f@|gY7>=`4XYY|`?hZYtGdiU`I$sj%8?t{2 zbw_$0<5;|)5k(L>p%|XR3;M)kAkMkIIF`Df*1;sSjV7UwvJ}d4`$$G{&!3 z<@{XYpz3V%6_8Ef?QZ^3-3pxoPJzEvfX@dX&KL-m7R}Lt!aMb!BmU*ZS~xa5nB&S~L_Cavht1ui|@fW61d& W00Y6&B3fYXL%_)33a7w7Rp2+N0+gKq literal 0 HcmV?d00001 diff --git a/Include/Extensions/NRIWrapperMTL.h b/Include/Extensions/NRIWrapperMTL.h new file mode 100644 index 0000000..6d62a9b --- /dev/null +++ b/Include/Extensions/NRIWrapperMTL.h @@ -0,0 +1,24 @@ +// © 2021 NVIDIA Corporation + +#pragma once + +#include "NRIDeviceCreation.h" + +NRI_NAMESPACE_BEGIN + +NRI_STRUCT(DeviceCreationMTLDesc) +{ + bool enableNRIValidation; + id MtlDevice; +} + +NRI_STRUCT(CommandBufferMTLDesc) +{ + +} + + +NRI_API NRI_NAME(Result) NRI_CALL nriCreateDeviceFromMtlDevice(const NRI_NAME_REF(DeviceCreationMTLDesc) deviceDesc, NRI_NAME_REF(Device*) device); + +NRI_NAMESPACE_END + diff --git a/Include/NRIDescs.h b/Include/NRIDescs.h index 14a49be..9e66b90 100644 --- a/Include/NRIDescs.h +++ b/Include/NRIDescs.h @@ -1,4 +1,4 @@ -// © 2021 NVIDIA Corporation +// © 2021 NVIDIA Corporation #pragma once @@ -1283,11 +1283,23 @@ NriStruct(PipelineStatisticsDesc) { #pragma region [ Device desc ] //============================================================================================================================================================================================ +NriEnum(GraphicsAPI, uint8_t, + D3D11, + D3D12, + VK, + MTL, + + MAX_NUM +); + NriEnum(Vendor, uint8_t, UNKNOWN, NVIDIA, AMD, - INTEL + INTEL, + APPLE, + + MAX_NUM ); NriStruct(AdapterDesc) { diff --git a/Source/Creation/Creation.cpp b/Source/Creation/Creation.cpp index f294a7c..550733b 100644 --- a/Source/Creation/Creation.cpp +++ b/Source/Creation/Creation.cpp @@ -18,7 +18,12 @@ Result CreateDeviceD3D12(const DeviceCreationDesc& deviceCreationDesc, DeviceBas Result CreateDeviceD3D12(const DeviceCreationD3D12Desc& deviceCreationDesc, DeviceBase*& device); #endif -#if NRI_USE_VK +#if NRI_USE_MTL +Result CreateDeviceMTL(const DeviceCreationDesc& deviceCreationDesc, DeviceBase*& device); +Result CreateDeviceMTL(const DeviceCreationMTLDesc& deviceCreationDesc, DeviceBase*& device); +#endif + +#if NRI_USE_VULKAN Result CreateDeviceVK(const DeviceCreationDesc& deviceCreationDesc, DeviceBase*& device); Result CreateDeviceVK(const DeviceCreationVKDesc& deviceDesc, DeviceBase*& device); #endif @@ -209,6 +214,24 @@ NRI_API Result NRI_CALL nriCreateDeviceFromD3D12Device(const DeviceCreationD3D12 return FinalizeDeviceCreation(deviceCreationDesc, *deviceImpl, device); } +NRI_API Result NRI_CALL nriCreateDeviceFromMtlDevice(const DeviceCreationMTLDesc& deviceCreationMtlDesc, Device*& device) { + DeviceCreationDesc deviceCreationDesc = {}; + deviceCreationDesc.graphicsAPI = GraphicsAPI::MTL; + deviceCreationDesc.enableNRIValidation = deviceCreationMtlDesc.enableNRIValidation; + + Result result = Result::UNSUPPORTED; + DeviceBase* deviceImpl = nullptr; + +#if NRI_USE_MTL + result = CreateDeviceD3D12(tempDeviceCreationD3D12Desc, deviceImpl); +#endif + + if (result != Result::SUCCESS) + return result; + + return FinalizeDeviceCreation(deviceCreationDesc, *deviceImpl, device); +} + NRI_API Result NRI_CALL nriCreateDeviceFromVkDevice(const DeviceCreationVKDesc& deviceCreationVKDesc, Device*& device) { DeviceCreationDesc deviceCreationDesc = {}; deviceCreationDesc.callbackInterface = deviceCreationVKDesc.callbackInterface; diff --git a/Source/Metal/BufferMetal.h b/Source/Metal/BufferMetal.h new file mode 100644 index 0000000..6c906e2 --- /dev/null +++ b/Source/Metal/BufferMetal.h @@ -0,0 +1,14 @@ + + +#import + +struct BufferMetal { + +private: + id pBuffer; + //id pIndirectCommandBuffer; + uint64_t mOffset; +}; + + + diff --git a/Source/Metal/BufferMetal.mm b/Source/Metal/BufferMetal.mm new file mode 100644 index 0000000..f01f9ab --- /dev/null +++ b/Source/Metal/BufferMetal.mm @@ -0,0 +1,2 @@ +#include "BufferMetal.h" + diff --git a/Source/Metal/DeviceMetal.h b/Source/Metal/DeviceMetal.h new file mode 100644 index 0000000..b51a1df --- /dev/null +++ b/Source/Metal/DeviceMetal.h @@ -0,0 +1,36 @@ +#pragma once + +namespace nri { + +struct DeviceMetal final : public DeviceBase { + BufferMetal(const CallbackInterface& callbacks, const StdAllocator& stdAllocator); + ~BufferMetal(); + + Result FillFunctionTable(CoreInterface& table) const; + Result FillFunctionTable(HelperInterface& table) const; + Result FillFunctionTable(LowLatencyInterface& table) const; + Result FillFunctionTable(MeshShaderInterface& table) const; + Result FillFunctionTable(RayTracingInterface& table) const; + Result FillFunctionTable(StreamerInterface& table) const; + Result FillFunctionTable(SwapChainInterface& table) const; + Result FillFunctionTable(ResourceAllocatorInterface& table) const; + Result FillFunctionTable(WrapperD3D11Interface& table) const; + Result FillFunctionTable(WrapperD3D12Interface& table) const; + Result FillFunctionTable(WrapperVKInterface& table) const; + + //================================================================================================================ + // DeviceBase + //================================================================================================================ + + inline const DeviceDesc& GetDesc() const { + return m_Desc; + } + + Result Create(const DeviceCreationDesc& deviceCreationDesc, const DeviceCreationMTLDesc& deviceCreationVKDesc, bool isWrapper); +private: + DeviceDesc m_Desc = {}; + id m_Device; + DeviceDesc m_Desc = {}; + bool m_OwnsNativeObjects = true; +}; +}; // namespace nri diff --git a/Source/Metal/DeviceMetal.hpp b/Source/Metal/DeviceMetal.hpp new file mode 100644 index 0000000..8a90349 --- /dev/null +++ b/Source/Metal/DeviceMetal.hpp @@ -0,0 +1,17 @@ +Declare_PartiallyFillFunctionTable_Functions(MTL); + +#pragma region[ Core ] + +static const DeviceDesc& NRI_CALL GetDeviceDesc(const Device& device) { + return ((const DeviceMetal&)device).GetDesc(); +} + +#pragma endregion + + +Define_Core_Device_PartiallyFillFunctionTable(MTL); +Define_Helper_Device_PartiallyFillFunctionTable(MTL); +Define_RayTracing_Device_PartiallyFillFunctionTable(MTL); +Define_Streamer_Device_PartiallyFillFunctionTable(MTL); +Define_SwapChain_Device_PartiallyFillFunctionTable(MTL); +Define_ResourceAllocator_Device_PartiallyFillFunctionTable(MTL); diff --git a/Source/Metal/DeviceMetal.mm b/Source/Metal/DeviceMetal.mm new file mode 100644 index 0000000..4e7c837 --- /dev/null +++ b/Source/Metal/DeviceMetal.mm @@ -0,0 +1,57 @@ +#include "DeviceMetal.h" + +using namespace nri; + +BufferMetal::BufferMetal(const CallbackInterface& callbacks, const StdAllocator& stdAllocator) + : DeviceBase(callbacks, stdAllocator) { + m_Desc.graphicsAPI = GraphicsAPI::VK; + m_Desc.nriVersionMajor = NRI_VERSION_MAJOR; + m_Desc.nriVersionMinor = NRI_VERSION_MINOR; + +} +BufferMetal::~BufferMetal() { + +} + +Result CreateDeviceMTL(const DeviceCreationDesc& deviceCreationDesc, DeviceBase*& device) { + +} + +Result CreateDeviceMTL(const DeviceCreationMTLDesc& deviceCreationDesc, DeviceBase*& device) { + +} + +Result DeviceMetal::Create(const DeviceCreationDesc& deviceCreationDesc, const DeviceCreationMTLDesc& deviceCreationMTLDesc, bool isWrapper) { + m_OwnsNativeObjects = !isWrapper; + + if(isWrapper) { + m_Device = deviceCreationMTLDesc.MtlDevice; + } + + strncpy(m_Desc.adapterDesc.name, [m_Device.name UTF8String], sizeof(m_Desc.adapterDesc.name)); + // No vendor id, device id for Apple GPUs + if (strstr(m_Desc.adapterDesc.name, "Apple")) + { + m_Desc.adapterDesc.vendor = nri::Vendor::APPLE; + } else { + const uint64_t regID = [m_Device registryID]; + if (regID) + { + io_registry_entry_t entry = IOServiceGetMatchingService(kIOMasterPortDefault, IORegistryEntryIDMatching(regID)); + if (entry) + { + // That returned the IOGraphicsAccelerator nub. Its parent, then, is the actual PCI device. + io_registry_entry_t parent; + if (IORegistryEntryGetParentEntry(entry, kIOServicePlane, &parent) == kIOReturnSuccess) + { + m_Desc.adapterDesc.vendor = GetVendorFromID(GetEntryProperty(parent, CFSTR("vendor-id"))); + m_Desc.adapterDesc.deviceId = GetEntryProperty(parent, CFSTR("device-id")); + IOObjectRelease(parent); + } + IOObjectRelease(entry); + } + } + } + + +} diff --git a/Source/Shared/SharedExternal.h b/Source/Shared/SharedExternal.h index 6d0bc4d..b619aeb 100644 --- a/Source/Shared/SharedExternal.h +++ b/Source/Shared/SharedExternal.h @@ -174,6 +174,8 @@ inline nri::Vendor GetVendorFromID(uint32_t vendorID) { return nri::Vendor::AMD; case 0x8086: return nri::Vendor::INTEL; + case 0x106b: + return nri::Vendor::APPLE; } return nri::Vendor::UNKNOWN; diff --git a/Source/VK/DeviceVK.h b/Source/VK/DeviceVK.h index 37ca2a2..75ccc75 100644 --- a/Source/VK/DeviceVK.h +++ b/Source/VK/DeviceVK.h @@ -2,6 +2,7 @@ #pragma once + namespace nri { struct CommandQueueVK; @@ -25,7 +26,7 @@ struct DeviceVK final : public DeviceBase { return m_Device; } - inline operator VkPhysicalDevice() const { + inline operator VkPhysicalDevice() const {DeviceB return m_PhysicalDevice; } From 5d5d8f33f47115720f874a7851534d77fefcd45c Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Thu, 29 Aug 2024 00:01:17 -0700 Subject: [PATCH 02/24] feat: add templte classes Signed-off-by: Michael Pollind --- Include/Extensions/NRIWrapperMTL.h | 17 ++ Source/Metal/BufferMTL.h | 48 ++++ Source/Metal/{BufferMetal.mm => BufferMTL.mm} | 0 Source/Metal/BufferMetal.h | 14 -- Source/Metal/{DeviceMetal.h => DeviceMTL.h} | 25 +- Source/Metal/DeviceMTL.hpp | 222 ++++++++++++++++++ Source/Metal/DeviceMTL.mm | 142 +++++++++++ Source/Metal/DeviceMetal.hpp | 17 -- Source/Metal/DeviceMetal.mm | 57 ----- Source/Metal/MemoryMTL.h | 57 +++++ Source/Metal/MemoryMTL.mm | 36 +++ Source/Metal/TextureMTL.h | 21 ++ Source/Metal/TextureMTL.mm | 0 13 files changed, 556 insertions(+), 100 deletions(-) create mode 100644 Source/Metal/BufferMTL.h rename Source/Metal/{BufferMetal.mm => BufferMTL.mm} (100%) delete mode 100644 Source/Metal/BufferMetal.h rename Source/Metal/{DeviceMetal.h => DeviceMTL.h} (84%) create mode 100644 Source/Metal/DeviceMTL.hpp create mode 100644 Source/Metal/DeviceMTL.mm delete mode 100644 Source/Metal/DeviceMetal.hpp delete mode 100644 Source/Metal/DeviceMetal.mm create mode 100644 Source/Metal/MemoryMTL.h create mode 100644 Source/Metal/MemoryMTL.mm create mode 100644 Source/Metal/TextureMTL.h create mode 100644 Source/Metal/TextureMTL.mm diff --git a/Include/Extensions/NRIWrapperMTL.h b/Include/Extensions/NRIWrapperMTL.h index 6d62a9b..b3dac1d 100644 --- a/Include/Extensions/NRIWrapperMTL.h +++ b/Include/Extensions/NRIWrapperMTL.h @@ -6,6 +6,9 @@ NRI_NAMESPACE_BEGIN + + + NRI_STRUCT(DeviceCreationMTLDesc) { bool enableNRIValidation; @@ -17,6 +20,20 @@ NRI_STRUCT(CommandBufferMTLDesc) } +NRI_STRUCT(BufferMTLDesc) +{ + id buffer; + void* mappedMemory; + MTLResourceOptions options; +} + + +NRI_STRUCT(MemoryMTLDesc) +{ + id buffer; + void* mappedMemory; + MTLResourceOptions options; +} NRI_API NRI_NAME(Result) NRI_CALL nriCreateDeviceFromMtlDevice(const NRI_NAME_REF(DeviceCreationMTLDesc) deviceDesc, NRI_NAME_REF(Device*) device); diff --git a/Source/Metal/BufferMTL.h b/Source/Metal/BufferMTL.h new file mode 100644 index 0000000..a71e757 --- /dev/null +++ b/Source/Metal/BufferMTL.h @@ -0,0 +1,48 @@ + + +#import + +struct DeviceMTL; +struct MemoryMTL; + +struct BufferMTL { + + inline BufferMTL(DeviceMTL& device) + : m_Device(device) { + } + + inline id GetHandle() const { + return pBuffer; + } + + inline VkDeviceAddress GetDeviceAddress() const { + return m_DeviceAddress; + } + + inline DeviceMTL& GetDevice() const { + return m_Device; + } + + inline const BufferDesc& GetDesc() const { + return m_Desc; + } + + ~BufferMTL(); + + Result Create(const BufferDesc& bufferDesc); + Result Create(const BufferVKDesc& bufferDesc); + Result Create(const AllocateBufferDesc& bufferDesc); + +private: + DeviceVK& m_Device; + id pBuffer; + uint8_t* m_MappedMemory = nullptr; + uint64_t m_MappedMemoryOffset = 0; + uint64_t m_MappedMemoryRangeSize = 0; + uint64_t m_MappedMemoryRangeOffset = 0; + BufferDesc m_Desc = {}; + bool m_OwnsNativeObjects = true; +}; + + + diff --git a/Source/Metal/BufferMetal.mm b/Source/Metal/BufferMTL.mm similarity index 100% rename from Source/Metal/BufferMetal.mm rename to Source/Metal/BufferMTL.mm diff --git a/Source/Metal/BufferMetal.h b/Source/Metal/BufferMetal.h deleted file mode 100644 index 6c906e2..0000000 --- a/Source/Metal/BufferMetal.h +++ /dev/null @@ -1,14 +0,0 @@ - - -#import - -struct BufferMetal { - -private: - id pBuffer; - //id pIndirectCommandBuffer; - uint64_t mOffset; -}; - - - diff --git a/Source/Metal/DeviceMetal.h b/Source/Metal/DeviceMTL.h similarity index 84% rename from Source/Metal/DeviceMetal.h rename to Source/Metal/DeviceMTL.h index b51a1df..2056726 100644 --- a/Source/Metal/DeviceMetal.h +++ b/Source/Metal/DeviceMTL.h @@ -2,21 +2,10 @@ namespace nri { -struct DeviceMetal final : public DeviceBase { +struct DeviceMTl final : public DeviceBase { BufferMetal(const CallbackInterface& callbacks, const StdAllocator& stdAllocator); ~BufferMetal(); - Result FillFunctionTable(CoreInterface& table) const; - Result FillFunctionTable(HelperInterface& table) const; - Result FillFunctionTable(LowLatencyInterface& table) const; - Result FillFunctionTable(MeshShaderInterface& table) const; - Result FillFunctionTable(RayTracingInterface& table) const; - Result FillFunctionTable(StreamerInterface& table) const; - Result FillFunctionTable(SwapChainInterface& table) const; - Result FillFunctionTable(ResourceAllocatorInterface& table) const; - Result FillFunctionTable(WrapperD3D11Interface& table) const; - Result FillFunctionTable(WrapperD3D12Interface& table) const; - Result FillFunctionTable(WrapperVKInterface& table) const; //================================================================================================================ // DeviceBase @@ -25,12 +14,24 @@ struct DeviceMetal final : public DeviceBase { inline const DeviceDesc& GetDesc() const { return m_Desc; } + + FormatSupportBits GetFormatSupport(const Device& device, Format format); + + Result FillFunctionTable(CoreInterface& table) const; + Result FillFunctionTable(HelperInterface& table) const; + Result FillFunctionTable(LowLatencyInterface& table) const; + Result FillFunctionTable(MeshShaderInterface& table) const; + Result FillFunctionTable(RayTracingInterface& table) const; + Result FillFunctionTable(StreamerInterface& table) const; + Result FillFunctionTable(SwapChainInterface& table) const; + Result FillFunctionTable(ResourceAllocatorInterface& table) const; Result Create(const DeviceCreationDesc& deviceCreationDesc, const DeviceCreationMTLDesc& deviceCreationVKDesc, bool isWrapper); private: DeviceDesc m_Desc = {}; id m_Device; DeviceDesc m_Desc = {}; + MTLGPUFamily m_Family; bool m_OwnsNativeObjects = true; }; }; // namespace nri diff --git a/Source/Metal/DeviceMTL.hpp b/Source/Metal/DeviceMTL.hpp new file mode 100644 index 0000000..267e1f8 --- /dev/null +++ b/Source/Metal/DeviceMTL.hpp @@ -0,0 +1,222 @@ +Declare_PartiallyFillFunctionTable_Functions(MTL); + +#pragma region[ Core ] + +static const DeviceDesc& NRI_CALL GetDeviceDesc(const Device& device) { + return ((const DeviceMTL&)device).GetDesc(); +} + +static const BufferDesc& NRI_CALL GetBufferDesc(const Buffer& buffer) { + return ((const BufferMTL&)buffer).GetDesc(); +} + +static const TextureDesc& NRI_CALL GetTextureDesc(const Texture& texture) { + return ((const TextureMTL&)texture).GetDesc(); +} + +static FormatSupportBits NRI_CALL GetFormatSupport(const Device& device, Format format) { + return ((const DeviceDesc&)device).GetFormatSupport(format); +} + +static void NRI_CALL GetBufferMemoryDesc(const Device& device, const BufferDesc& bufferDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { + D3D12_RESOURCE_DESC desc = {}; + GetResourceDesc(&desc, bufferDesc); + + ((const DeviceD3D12&)device).GetMemoryDesc(memoryLocation, desc, memoryDesc); +} + +static void NRI_CALL GetTextureMemoryDesc(const Device& device, const TextureDesc& textureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { + D3D12_RESOURCE_DESC desc = {}; + GetResourceDesc(&desc, textureDesc); + + ((const DeviceD3D12&)device).GetMemoryDesc(memoryLocation, desc, memoryDesc); +} + +static Result NRI_CALL GetCommandQueue(Device& device, CommandQueueType commandQueueType, CommandQueue*& commandQueue) { + return ((DeviceD3D12&)device).GetCommandQueue(commandQueueType, commandQueue); +} + +static Result NRI_CALL CreateCommandAllocator(const CommandQueue& commandQueue, CommandAllocator*& commandAllocator) { + DeviceD3D12& device = ((CommandQueueD3D12&)commandQueue).GetDevice(); + return device.CreateImplementation(commandAllocator, commandQueue); +} + +static Result NRI_CALL CreateDescriptorPool(Device& device, const DescriptorPoolDesc& descriptorPoolDesc, DescriptorPool*& descriptorPool) { + return ((DeviceD3D12&)device).CreateImplementation(descriptorPool, descriptorPoolDesc); +} + +static Result NRI_CALL CreateBuffer(Device& device, const BufferDesc& bufferDesc, Buffer*& buffer) { + return ((DeviceD3D12&)device).CreateImplementation(buffer, bufferDesc); +} + +static Result NRI_CALL CreateTexture(Device& device, const TextureDesc& textureDesc, Texture*& texture) { + return ((DeviceD3D12&)device).CreateImplementation(texture, textureDesc); +} + +static Result NRI_CALL CreateBufferView(const BufferViewDesc& bufferViewDesc, Descriptor*& bufferView) { + DeviceD3D12& device = ((const BufferD3D12*)bufferViewDesc.buffer)->GetDevice(); + return device.CreateImplementation(bufferView, bufferViewDesc); +} + +static Result NRI_CALL CreateTexture1DView(const Texture1DViewDesc& textureViewDesc, Descriptor*& textureView) { + DeviceD3D12& device = ((const TextureD3D12*)textureViewDesc.texture)->GetDevice(); + return device.CreateImplementation(textureView, textureViewDesc); +} + +static Result NRI_CALL CreateTexture2DView(const Texture2DViewDesc& textureViewDesc, Descriptor*& textureView) { + DeviceD3D12& device = ((const TextureD3D12*)textureViewDesc.texture)->GetDevice(); + return device.CreateImplementation(textureView, textureViewDesc); +} + +static Result NRI_CALL CreateTexture3DView(const Texture3DViewDesc& textureViewDesc, Descriptor*& textureView) { + DeviceD3D12& device = ((const TextureD3D12*)textureViewDesc.texture)->GetDevice(); + return device.CreateImplementation(textureView, textureViewDesc); +} + +static Result NRI_CALL CreateSampler(Device& device, const SamplerDesc& samplerDesc, Descriptor*& sampler) { + return ((DeviceD3D12&)device).CreateImplementation(sampler, samplerDesc); +} + +static Result NRI_CALL CreatePipelineLayout(Device& device, const PipelineLayoutDesc& pipelineLayoutDesc, PipelineLayout*& pipelineLayout) { + return ((DeviceD3D12&)device).CreateImplementation(pipelineLayout, pipelineLayoutDesc); +} + +static Result NRI_CALL CreateGraphicsPipeline(Device& device, const GraphicsPipelineDesc& graphicsPipelineDesc, Pipeline*& pipeline) { + return ((DeviceD3D12&)device).CreateImplementation(pipeline, graphicsPipelineDesc); +} + +static Result NRI_CALL CreateComputePipeline(Device& device, const ComputePipelineDesc& computePipelineDesc, Pipeline*& pipeline) { + return ((DeviceD3D12&)device).CreateImplementation(pipeline, computePipelineDesc); +} + +static Result NRI_CALL CreateFence(Device& device, uint64_t initialValue, Fence*& fence) { + return ((DeviceD3D12&)device).CreateImplementation(fence, initialValue); +} + +static Result NRI_CALL CreateQueryPool(Device& device, const QueryPoolDesc& queryPoolDesc, QueryPool*& queryPool) { + return ((DeviceD3D12&)device).CreateImplementation(queryPool, queryPoolDesc); +} + +static void NRI_CALL DestroyCommandBuffer(CommandBuffer& commandBuffer) { + Destroy((CommandBufferD3D12*)&commandBuffer); +} + +static void NRI_CALL DestroyCommandAllocator(CommandAllocator& commandAllocator) { + Destroy((CommandAllocatorD3D12*)&commandAllocator); +} + +static void NRI_CALL DestroyDescriptorPool(DescriptorPool& descriptorPool) { + Destroy((DescriptorPoolD3D12*)&descriptorPool); +} + +static void NRI_CALL DestroyBuffer(Buffer& buffer) { + Destroy((BufferD3D12*)&buffer); +} + +static void NRI_CALL DestroyTexture(Texture& texture) { + Destroy((TextureD3D12*)&texture); +} + +static void NRI_CALL DestroyDescriptor(Descriptor& descriptor) { + Destroy((DescriptorD3D12*)&descriptor); +} + +static void NRI_CALL DestroyPipelineLayout(PipelineLayout& pipelineLayout) { + Destroy((PipelineLayoutD3D12*)&pipelineLayout); +} + +static void NRI_CALL DestroyPipeline(Pipeline& pipeline) { + Destroy((PipelineD3D12*)&pipeline); +} + +static void NRI_CALL DestroyQueryPool(QueryPool& queryPool) { + Destroy((QueryPoolD3D12*)&queryPool); +} + +static void NRI_CALL DestroyFence(Fence& fence) { + Destroy((FenceD3D12*)&fence); +} + +static Result NRI_CALL AllocateMemory(Device& device, const AllocateMemoryDesc& allocateMemoryDesc, Memory*& memory) { + return ((DeviceD3D12&)device).CreateImplementation(memory, allocateMemoryDesc); +} + +static Result NRI_CALL BindBufferMemory(Device& device, const BufferMemoryBindingDesc* memoryBindingDescs, uint32_t memoryBindingDescNum) { + return ((DeviceD3D12&)device).BindBufferMemory(memoryBindingDescs, memoryBindingDescNum); +} + +static Result NRI_CALL BindTextureMemory(Device& device, const TextureMemoryBindingDesc* memoryBindingDescs, uint32_t memoryBindingDescNum) { + return ((DeviceD3D12&)device).BindTextureMemory(memoryBindingDescs, memoryBindingDescNum); +} + +static void NRI_CALL FreeMemory(Memory& memory) { + Destroy((MemoryD3D12*)&memory); +} + +static void NRI_CALL SetDeviceDebugName(Device& device, const char* name) { + ((DeviceD3D12&)device).SetDebugName(name); +} + +static void NRI_CALL SetPipelineDebugName(Pipeline& pipeline, const char* name) { + ((PipelineD3D12&)pipeline).SetDebugName(name); +} + +static void NRI_CALL SetPipelineLayoutDebugName(PipelineLayout& pipelineLayout, const char* name) { + ((PipelineLayoutD3D12&)pipelineLayout).SetDebugName(name); +} + +static void NRI_CALL SetMemoryDebugName(Memory& memory, const char* name) { + ((MemoryMetal&)memory).SetDebugName(name); +} + +static void* NRI_CALL GetDeviceNativeObject(const Device& device) { + if (!(&device)) + return nullptr; + + return ((DeviceMetal&)device).GetNativeObject(); +} + +Result DeviceMetal::FillFunctionTable(CoreInterface& table) const { + table = {}; + Core_Device_PartiallyFillFunctionTableMTL(table); + Core_Buffer_PartiallyFillFunctionTableMTL(table); + Core_CommandAllocator_PartiallyFillFunctionTableMTL(table); + Core_CommandBuffer_PartiallyFillFunctionTableMTL(table); + Core_CommandQueue_PartiallyFillFunctionTableMTL(table); + Core_Descriptor_PartiallyFillFunctionTableMTL(table); + Core_DescriptorPool_PartiallyFillFunctionTableMTL(table); + Core_DescriptorSet_PartiallyFillFunctionTableMTL(table); + Core_Fence_PartiallyFillFunctionTableMTL(table); + Core_QueryPool_PartiallyFillFunctionTableMTL(table); + Core_Texture_PartiallyFillFunctionTableMTL(table); + return ValidateFunctionTable(table); +} + +#pragma endregion + + +Result DeviceMetal::FillFunctionTable(HelperInterface& table) const { + +} + +Result DeviceMetal::FillFunctionTable(LowLatencyInterface& table) const { +} + +Result DeviceMetal::FillFunctionTable(MeshShaderInterface& table) const { +} + +Result DeviceMetal::FillFunctionTable(RayTracingInterface& table) const { +} +Result DeviceMetal::FillFunctionTable(StreamerInterface& table) const { +} +Result DeviceMetal::FillFunctionTable(SwapChainInterface& table) const { +} +Result DeviceMetal::FillFunctionTable(ResourceAllocatorInterface& table) const { +} + +Define_Core_Device_PartiallyFillFunctionTable(MTL); +Define_Helper_Device_PartiallyFillFunctionTable(MTL); +Define_RayTracing_Device_PartiallyFillFunctionTable(MTL); +Define_Streamer_Device_PartiallyFillFunctionTable(MTL); +Define_SwapChain_Device_PartiallyFillFunctionTable(MTL); +Define_ResourceAllocator_Device_PartiallyFillFunctionTable(MTL); diff --git a/Source/Metal/DeviceMTL.mm b/Source/Metal/DeviceMTL.mm new file mode 100644 index 0000000..aae2f50 --- /dev/null +++ b/Source/Metal/DeviceMTL.mm @@ -0,0 +1,142 @@ +#include "DeviceMetal.h" + +using namespace nri; + +BufferMetal::BufferMetal(const CallbackInterface& callbacks, const StdAllocator& stdAllocator) + : DeviceBase(callbacks, stdAllocator) { + m_Desc.graphicsAPI = GraphicsAPI::VK; + m_Desc.nriVersionMajor = NRI_VERSION_MAJOR; + m_Desc.nriVersionMinor = NRI_VERSION_MINOR; + +} + +BufferMetal::~BufferMetal() { + +} + +Result CreateDeviceMTL(const DeviceCreationDesc& deviceCreationDesc, DeviceBase*& device) { + +} + + +Result CreateDeviceMTL(const DeviceCreationMTLDesc& deviceCreationDesc, DeviceBase*& device) { + +} + +//ResultOrError GetMTLGPUFamily(id device) { +// // https://developer.apple.com/documentation/metal/mtldevice/detecting_gpu_features_and_metal_software_versions?language=objc +// +// if (@available(macOS 10.15, iOS 10.13, *)) { +// if ([device supportsFamily:MTLGPUFamilyApple7]) { +// return MTLGPUFamily::Apple7; +// } +// if ([device supportsFamily:MTLGPUFamilyApple6]) { +// return MTLGPUFamily::Apple6; +// } +// if ([device supportsFamily:MTLGPUFamilyApple5]) { +// return MTLGPUFamily::Apple5; +// } +// if ([device supportsFamily:MTLGPUFamilyApple4]) { +// return MTLGPUFamily::Apple4; +// } +// if ([device supportsFamily:MTLGPUFamilyApple3]) { +// return MTLGPUFamily::Apple3; +// } +// if ([device supportsFamily:MTLGPUFamilyApple2]) { +// return MTLGPUFamily::Apple2; +// } +// if ([device supportsFamily:MTLGPUFamilyApple1]) { +// return MTLGPUFamily::Apple1; +// } +// +// // This family is no longer supported in the macOS 10.15 SDK but still exists so +// // default to it. +// return MTLGPUFamily::Mac1; +// } +// +// return DAWN_INTERNAL_ERROR("Unsupported Metal device"); +//} +// +//} // anonymous namespace + +FormatSupportBits DeviceMTL::GetFormatSupport(const Device& device, Format format) { + int currentFamily = HIGHEST_GPU_FAMILY; + for (; currentFamily >= (int)MTLGPUFamilyApple1; currentFamily--) { + if ([m_device supportsFamily:(MTLGPUFamily)currentFamily]) { + highestAppleFamily = (MTLGPUFamily)currentFamily; + break; + } + } +} + +static inline bool FindMTLGpuFamily(id device, MTLGPUFamily* family) { + //https://developer.apple.com/documentation/metal/mtldevice/detecting_gpu_features_and_metal_software_versions?language=objc + if (@available(macOS 10.15, iOS 10.13, *)) { + if ([device supportsFamily:MTLGPUFamilyApple7]) { + return MTLGPUFamily::Apple7; + } + if ([device supportsFamily:MTLGPUFamilyApple6]) { + return MTLGPUFamily::Apple6; + } + if ([device supportsFamily:MTLGPUFamilyApple5]) { + return MTLGPUFamily::Apple5; + } + if ([device supportsFamily:MTLGPUFamilyApple4]) { + return MTLGPUFamily::Apple4; + } + if ([device supportsFamily:MTLGPUFamilyApple3]) { + return MTLGPUFamily::Apple3; + } + if ([device supportsFamily:MTLGPUFamilyApple2]) { + return MTLGPUFamily::Apple2; + } + if ([device supportsFamily:MTLGPUFamilyApple1]) { + return MTLGPUFamily::Apple1; + } + + // This family is no longer supported in the macOS 10.15 SDK but still exists so + // default to it. + //return MTLGPUFamily::Mac1; + (*family) = MTLGPUFamily::Mac1; + return true; + } + + return false; +} + + +Result DeviceMTL::Create(const DeviceCreationDesc& deviceCreationDesc, const DeviceCreationMTLDesc& deviceCreationMTLDesc, bool isWrapper) { + m_OwnsNativeObjects = !isWrapper; + + if(isWrapper) { + m_Device = deviceCreationMTLDesc.MtlDevice; + } + + strncpy(m_Desc.adapterDesc.name, [m_Device.name UTF8String], sizeof(m_Desc.adapterDesc.name)); + // No vendor id, device id for Apple GPUs + if (strstr(m_Desc.adapterDesc.name, "Apple")) { + m_Desc.adapterDesc.vendor = nri::Vendor::APPLE; + } + + const uint64_t regID = [m_Device registryID]; + if (regID) + { + IORef entry =AcquireIORef(IOServiceGetMatchingService(kIOMasterPortDefault, IORegistryEntryIDMatching(regID))); + if (entry) + { + // That returned the IOGraphicsAccelerator nub. Its parent, then, is the actual PCI device. + IORef deviceEntry; + if (IORegistryEntryGetParentEntry(entry, kIOServicePlane, &deviceEntry) == kIOReturnSuccess) + { + m_Desc.adapterDesc.vendor = GetVendorFromID(GetEntryProperty(deviceEntry, CFSTR("vendor-id"))); + m_Desc.adapterDesc.deviceId = GetEntryProperty(deviceEntry, CFSTR("device-id")); + } + } + } + + m_Desc.adapterDesc.luid = 0; + m_Desc.adapterDesc.videoMemorySize = 0; + m_Desc.adapterDesc.systemMemorySize = 0; + return Result::SUCCESS; + +} diff --git a/Source/Metal/DeviceMetal.hpp b/Source/Metal/DeviceMetal.hpp deleted file mode 100644 index 8a90349..0000000 --- a/Source/Metal/DeviceMetal.hpp +++ /dev/null @@ -1,17 +0,0 @@ -Declare_PartiallyFillFunctionTable_Functions(MTL); - -#pragma region[ Core ] - -static const DeviceDesc& NRI_CALL GetDeviceDesc(const Device& device) { - return ((const DeviceMetal&)device).GetDesc(); -} - -#pragma endregion - - -Define_Core_Device_PartiallyFillFunctionTable(MTL); -Define_Helper_Device_PartiallyFillFunctionTable(MTL); -Define_RayTracing_Device_PartiallyFillFunctionTable(MTL); -Define_Streamer_Device_PartiallyFillFunctionTable(MTL); -Define_SwapChain_Device_PartiallyFillFunctionTable(MTL); -Define_ResourceAllocator_Device_PartiallyFillFunctionTable(MTL); diff --git a/Source/Metal/DeviceMetal.mm b/Source/Metal/DeviceMetal.mm deleted file mode 100644 index 4e7c837..0000000 --- a/Source/Metal/DeviceMetal.mm +++ /dev/null @@ -1,57 +0,0 @@ -#include "DeviceMetal.h" - -using namespace nri; - -BufferMetal::BufferMetal(const CallbackInterface& callbacks, const StdAllocator& stdAllocator) - : DeviceBase(callbacks, stdAllocator) { - m_Desc.graphicsAPI = GraphicsAPI::VK; - m_Desc.nriVersionMajor = NRI_VERSION_MAJOR; - m_Desc.nriVersionMinor = NRI_VERSION_MINOR; - -} -BufferMetal::~BufferMetal() { - -} - -Result CreateDeviceMTL(const DeviceCreationDesc& deviceCreationDesc, DeviceBase*& device) { - -} - -Result CreateDeviceMTL(const DeviceCreationMTLDesc& deviceCreationDesc, DeviceBase*& device) { - -} - -Result DeviceMetal::Create(const DeviceCreationDesc& deviceCreationDesc, const DeviceCreationMTLDesc& deviceCreationMTLDesc, bool isWrapper) { - m_OwnsNativeObjects = !isWrapper; - - if(isWrapper) { - m_Device = deviceCreationMTLDesc.MtlDevice; - } - - strncpy(m_Desc.adapterDesc.name, [m_Device.name UTF8String], sizeof(m_Desc.adapterDesc.name)); - // No vendor id, device id for Apple GPUs - if (strstr(m_Desc.adapterDesc.name, "Apple")) - { - m_Desc.adapterDesc.vendor = nri::Vendor::APPLE; - } else { - const uint64_t regID = [m_Device registryID]; - if (regID) - { - io_registry_entry_t entry = IOServiceGetMatchingService(kIOMasterPortDefault, IORegistryEntryIDMatching(regID)); - if (entry) - { - // That returned the IOGraphicsAccelerator nub. Its parent, then, is the actual PCI device. - io_registry_entry_t parent; - if (IORegistryEntryGetParentEntry(entry, kIOServicePlane, &parent) == kIOReturnSuccess) - { - m_Desc.adapterDesc.vendor = GetVendorFromID(GetEntryProperty(parent, CFSTR("vendor-id"))); - m_Desc.adapterDesc.deviceId = GetEntryProperty(parent, CFSTR("device-id")); - IOObjectRelease(parent); - } - IOObjectRelease(entry); - } - } - } - - -} diff --git a/Source/Metal/MemoryMTL.h b/Source/Metal/MemoryMTL.h new file mode 100644 index 0000000..2374d2a --- /dev/null +++ b/Source/Metal/MemoryMTL.h @@ -0,0 +1,57 @@ +// © 2021 NVIDIA Corporation + +#pragma once + +#include + +namespace nri { + +struct DeviceMTL; + +struct MemoryMTL { + + inline MemoryMTL (DeviceMTL& device) + : m_Device(device) { + } + + inline VkDeviceMemory GetHandle() const { + return m_Handle; + } + + inline DeviceVK& GetDevice() const { + return m_Device; + } + + inline MemoryType GetType() const { + return m_Type; + } + + inline uint8_t* GetMappedMemory() const { + return m_MappedMemory; + } + + ~MemoryMTL(); + + Result Create(const MemoryMTLDesc& memoryDesc); + Result Create(const AllocateMemoryDesc& allocateMemoryDesc); + //Result CreateDedicated(const BufferVK& buffer); + //Result CreateDedicated(const TextureVK& texture); + + //================================================================================================================ + // NRI + //================================================================================================================ + + void SetDebugName(const char* name); + +private: + DeviceMTL& m_Device; + id m_Buffer; + uint8_t* m_MappedMemory = nullptr; + MemoryType m_Type = std::numeric_limits::max(); + float m_Priority = 0.0f; + bool m_OwnsNativeObjects = true; +}; + + +} + diff --git a/Source/Metal/MemoryMTL.mm b/Source/Metal/MemoryMTL.mm new file mode 100644 index 0000000..528facd --- /dev/null +++ b/Source/Metal/MemoryMTL.mm @@ -0,0 +1,36 @@ +// © 2021 NVIDIA Corporation + +#include "MemoryMTL.h" + +using namespace nri; + +MemoryMTL::~MemoryMTL() { + //if (m_OwnsNativeObjects) { + // const auto& vk = m_Device.GetDispatchTable(); + // vk.FreeMemory(m_Device, m_Handle, m_Device.GetAllocationCallbacks()); + //} +} + +Result MemoryMTL::Create(const MemoryMTLDesc& memoryDesc) { + if (!memoryDesc.vkDeviceMemory) + return Result::INVALID_ARGUMENT; + + MemoryTypeInfo memoryTypeInfo = {}; + + //bool found = m_Device.GetMemoryTypeByIndex(memoryDesc.memoryTypeIndex, memoryTypeInfo); + //RETURN_ON_FAILURE(&m_Device, found, Result::INVALID_ARGUMENT, "Can't find memory by index"); + + m_OwnsNativeObjects = false; + m_Buffer = memoryDesc.buffer; + m_MappedMemory = (uint8_t*)memoryDesc.mappedMemory; + m_Type = memoryDesc.options; + + const auto& mtl = m_Device.GetDispatchTable(); + //if (!m_MappedMemory && IsHostVisibleMemory(memoryTypeInfo.location)) { + // VkResult result = mtl.MapMemory(m_Device, m_Handle, 0, memoryDesc.size, 0, (void**)&m_MappedMemory); + // RETURN_ON_FAILURE(&m_Device, result == VK_SUCCESS, GetReturnCode(result), "vkMapMemory returned %d", (int32_t)result); + //} + + return Result::SUCCESS; +} + diff --git a/Source/Metal/TextureMTL.h b/Source/Metal/TextureMTL.h new file mode 100644 index 0000000..71d7718 --- /dev/null +++ b/Source/Metal/TextureMTL.h @@ -0,0 +1,21 @@ +// © 2021 NVIDIA Corporation + +#pragma once + + +namespace nri { + +struct DeviceMTL; + +struct TextureMTL { + + inline TextureMTL(DeviceMTL& device) + : m_Device(device) { + } +private: + DeviceMTL& m_Device; + +}; + +} + diff --git a/Source/Metal/TextureMTL.mm b/Source/Metal/TextureMTL.mm new file mode 100644 index 0000000..e69de29 From 457200c166e8c449219cfccb866769350a695ba2 Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Fri, 30 Aug 2024 08:01:24 -0700 Subject: [PATCH 03/24] feat: add command queue mtl Signed-off-by: Michael Pollind --- Include/.DS_Store | Bin 6148 -> 0 bytes Include/Extensions/NRIWrapperMTL.h | 16 ++++ Source/Metal/CommandQueueMTL.h | 50 +++++++++++ Source/Metal/CommandQueueMTL.mm | 21 +++++ Source/Metal/DeviceMTL.h | 4 + Source/Metal/DeviceMTL.mm | 131 ++++++++++++++--------------- Source/Metal/TextureMTL.h | 1 - Source/VK/CommandQueueVK.h | 1 - 8 files changed, 155 insertions(+), 69 deletions(-) delete mode 100644 Include/.DS_Store create mode 100644 Source/Metal/CommandQueueMTL.h create mode 100644 Source/Metal/CommandQueueMTL.mm diff --git a/Include/.DS_Store b/Include/.DS_Store deleted file mode 100644 index dbf90847cd1bd865f676ed42ad220f31e71536bd..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKO>Yx15FNKE*`z|sfv*eFN?fB7Dis=W*{12C2RL*Q8~}ygB%&*}>nOV+MNy=^ z0zZZ$|Aha-3EtRKi6qT|3qp}c8o#l}&yHVYdrd^DGZ{Q0Y7mhJXROpwTw|PPU$HG| zsRET5Bcq%W(!}V@Dc}_N-xc7!Tc;Dcq=JTK-^%_yO?5v`b&Nb84oC34U&auv;l$H? zB%JT@C{6OB)%u~fwkta~s$SLG_1=c(dKwl{G08j8_%+vFXr0DaaTLEyhSOf-*0Iit zD9MInLr4Zgbb0eC$p(7b(UWYD8*XS5Ud^lZ8h2;2gZ6&YKX@{4`m^?atLZ;JY|rO4 z@AiX-PtSTE(u+)gHb0&ejw@p~1+U->f@|gY7>=`4XYY|`?hZYtGdiU`I$sj%8?t{2 zbw_$0<5;|)5k(L>p%|XR3;M)kAkMkIIF`Df*1;sSjV7UwvJ}d4`$$G{&!3 z<@{XYpz3V%6_8Ef?QZ^3-3pxoPJzEvfX@dX&KL-m7R}Lt!aMb!BmU*ZS~xa5nB&S~L_Cavht1ui|@fW61d& W00Y6&B3fYXL%_)33a7w7Rp2+N0+gKq diff --git a/Include/Extensions/NRIWrapperMTL.h b/Include/Extensions/NRIWrapperMTL.h index b3dac1d..b57e6c0 100644 --- a/Include/Extensions/NRIWrapperMTL.h +++ b/Include/Extensions/NRIWrapperMTL.h @@ -7,6 +7,22 @@ NRI_NAMESPACE_BEGIN +NRI_ENUM +( + MTLGPUFamily, uint8_t, + + Apple1, + Apple2, + Apple3, + Apple4, + Apple5, + Apple6, + Apple7, + Mac1, + Mac2, + + MAX_APPLE_FAMILY_NUM +); NRI_STRUCT(DeviceCreationMTLDesc) diff --git a/Source/Metal/CommandQueueMTL.h b/Source/Metal/CommandQueueMTL.h new file mode 100644 index 0000000..85f4669 --- /dev/null +++ b/Source/Metal/CommandQueueMTL.h @@ -0,0 +1,50 @@ +// © 2021 NVIDIA Corporation + +#pragma once + + +namespace nri { + +struct DeviceMTL; + +struct CommandQueueMTL { + + inline CommandQueueMTL(DeviceMTL& device) + : m_Device(device) { + } + + ~CommandQueueMTL(); + + inline operator id() const { + return m_Handle; + } + + inline DeviceMTL& GetDevice() const { + return m_Device; + } + + inline uint32_t GetFamilyIndex() const { + return m_FamilyIndex; + } + + inline CommandQueueType GetType() const { + return m_Type; + } + + inline Lock& GetLock() { + return m_Lock; + } + + void SetDebugName(const char* name); + Result Create(CommandQueueType type, uint32_t familyIndex, id handle); +private: + DeviceMTL& m_Device; + uint32_t m_FamilyIndex = INVALID_FAMILY_INDEX; + CommandQueueType m_Type = CommandQueueType(-1); + id m_Handle; + Lock m_Lock; +}; + +} + + diff --git a/Source/Metal/CommandQueueMTL.mm b/Source/Metal/CommandQueueMTL.mm new file mode 100644 index 0000000..2386982 --- /dev/null +++ b/Source/Metal/CommandQueueMTL.mm @@ -0,0 +1,21 @@ +// © 2021 NVIDIA Corporation + +#include "CommandQueueMTL.h" + +using namespace nri; + + +CommandQueueMTL::~CommandQueueMTL() { + m_CommandQueue = nil; +} + +Result CommandQueueMTL::Create(CommandQueueType type, uint32_t familyIndex, id handle) { + m_Type = type; + m_FamilyIndex = familyIndex; + m_Handle = handle; + return Result::SUCCESS; +} + +void CommandQueueMTL::SetDebugName(const char* name) { + +} diff --git a/Source/Metal/DeviceMTL.h b/Source/Metal/DeviceMTL.h index 2056726..5b244d4 100644 --- a/Source/Metal/DeviceMTL.h +++ b/Source/Metal/DeviceMTL.h @@ -7,6 +7,9 @@ struct DeviceMTl final : public DeviceBase { ~BufferMetal(); + + Result GetCommandQueue(CommandQueueType commandQueueType, CommandQueue*& commandQueue); + //================================================================================================================ // DeviceBase //================================================================================================================ @@ -30,6 +33,7 @@ struct DeviceMTl final : public DeviceBase { private: DeviceDesc m_Desc = {}; id m_Device; + std::array m_CommandQueues = {}; DeviceDesc m_Desc = {}; MTLGPUFamily m_Family; bool m_OwnsNativeObjects = true; diff --git a/Source/Metal/DeviceMTL.mm b/Source/Metal/DeviceMTL.mm index aae2f50..97b7992 100644 --- a/Source/Metal/DeviceMTL.mm +++ b/Source/Metal/DeviceMTL.mm @@ -2,6 +2,10 @@ using namespace nri; + +static inline bool FindMTLGpuFamily(id device, MTLGPUFamily *family); + + BufferMetal::BufferMetal(const CallbackInterface& callbacks, const StdAllocator& stdAllocator) : DeviceBase(callbacks, stdAllocator) { m_Desc.graphicsAPI = GraphicsAPI::VK; @@ -23,42 +27,6 @@ Result CreateDeviceMTL(const DeviceCreationMTLDesc& deviceCreationDesc, DeviceBa } -//ResultOrError GetMTLGPUFamily(id device) { -// // https://developer.apple.com/documentation/metal/mtldevice/detecting_gpu_features_and_metal_software_versions?language=objc -// -// if (@available(macOS 10.15, iOS 10.13, *)) { -// if ([device supportsFamily:MTLGPUFamilyApple7]) { -// return MTLGPUFamily::Apple7; -// } -// if ([device supportsFamily:MTLGPUFamilyApple6]) { -// return MTLGPUFamily::Apple6; -// } -// if ([device supportsFamily:MTLGPUFamilyApple5]) { -// return MTLGPUFamily::Apple5; -// } -// if ([device supportsFamily:MTLGPUFamilyApple4]) { -// return MTLGPUFamily::Apple4; -// } -// if ([device supportsFamily:MTLGPUFamilyApple3]) { -// return MTLGPUFamily::Apple3; -// } -// if ([device supportsFamily:MTLGPUFamilyApple2]) { -// return MTLGPUFamily::Apple2; -// } -// if ([device supportsFamily:MTLGPUFamilyApple1]) { -// return MTLGPUFamily::Apple1; -// } -// -// // This family is no longer supported in the macOS 10.15 SDK but still exists so -// // default to it. -// return MTLGPUFamily::Mac1; -// } -// -// return DAWN_INTERNAL_ERROR("Unsupported Metal device"); -//} -// -//} // anonymous namespace - FormatSupportBits DeviceMTL::GetFormatSupport(const Device& device, Format format) { int currentFamily = HIGHEST_GPU_FAMILY; for (; currentFamily >= (int)MTLGPUFamilyApple1; currentFamily--) { @@ -69,42 +37,14 @@ Result CreateDeviceMTL(const DeviceCreationMTLDesc& deviceCreationDesc, DeviceBa } } -static inline bool FindMTLGpuFamily(id device, MTLGPUFamily* family) { - //https://developer.apple.com/documentation/metal/mtldevice/detecting_gpu_features_and_metal_software_versions?language=objc - if (@available(macOS 10.15, iOS 10.13, *)) { - if ([device supportsFamily:MTLGPUFamilyApple7]) { - return MTLGPUFamily::Apple7; - } - if ([device supportsFamily:MTLGPUFamilyApple6]) { - return MTLGPUFamily::Apple6; - } - if ([device supportsFamily:MTLGPUFamilyApple5]) { - return MTLGPUFamily::Apple5; - } - if ([device supportsFamily:MTLGPUFamilyApple4]) { - return MTLGPUFamily::Apple4; - } - if ([device supportsFamily:MTLGPUFamilyApple3]) { - return MTLGPUFamily::Apple3; - } - if ([device supportsFamily:MTLGPUFamilyApple2]) { - return MTLGPUFamily::Apple2; - } - if ([device supportsFamily:MTLGPUFamilyApple1]) { - return MTLGPUFamily::Apple1; - } - // This family is no longer supported in the macOS 10.15 SDK but still exists so - // default to it. - //return MTLGPUFamily::Mac1; - (*family) = MTLGPUFamily::Mac1; - return true; - } +Result DeviceMTL::GetCommandQueue(CommandQueueType commandQueueType, CommandQueue*& commandQueue) { - return false; } + + Result DeviceMTL::Create(const DeviceCreationDesc& deviceCreationDesc, const DeviceCreationMTLDesc& deviceCreationMTLDesc, bool isWrapper) { m_OwnsNativeObjects = !isWrapper; @@ -134,9 +74,66 @@ static inline bool FindMTLGpuFamily(id device, MTLGPUFamily* family) } } + MTLGPUFamily family; + if(!FindMTLGpuFamily(m_Device, family)) { + return Result::UNSUPPORTED; + } + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf + //TODO: fill desc + switch(family) { + case MTLGPUFamily::Apple1: + break; + default: + break; + } + m_Desc.adapterDesc.luid = 0; m_Desc.adapterDesc.videoMemorySize = 0; m_Desc.adapterDesc.systemMemorySize = 0; return Result::SUCCESS; } + + +static inline bool FindMTLGpuFamily(id device, + MTLGPUFamily *family) { + // https://developer.apple.com/documentation/metal/mtldevice/detecting_gpu_features_and_metal_software_versions?language=objc + if (@available(macOS 10.15, iOS 10.13, *)) { + if ([device supportsFamily:MTLGPUFamilyApple7]) { + (*family) = MTLGPUFamily::Apple7; + return true; + } + if ([device supportsFamily:MTLGPUFamilyApple6]) { + (*family) = MTLGPUFamily::Apple6; + return true; + } + if ([device supportsFamily:MTLGPUFamilyApple5]) { + (*family) = MTLGPUFamily::Apple5; + return true; + } + if ([device supportsFamily:MTLGPUFamilyApple4]) { + (*family) = MTLGPUFamily::Apple4; + return true; + } + if ([device supportsFamily:MTLGPUFamilyApple3]) { + (*family) = MTLGPUFamily::Apple3; + return true; + } + if ([device supportsFamily:MTLGPUFamilyApple2]) { + (*family) = MTLGPUFamily::Apple2; + return true; + } + if ([device supportsFamily:MTLGPUFamilyApple1]) { + (*family) = MTLGPUFamily::Apple1; + return true; + } + + // This family is no longer supported in the macOS 10.15 SDK but still + // exists so default to it. + // return MTLGPUFamily::Mac1; + (*family) = MTLGPUFamily::Mac1; + return true; + } + return false; +} + diff --git a/Source/Metal/TextureMTL.h b/Source/Metal/TextureMTL.h index 71d7718..0195ba8 100644 --- a/Source/Metal/TextureMTL.h +++ b/Source/Metal/TextureMTL.h @@ -2,7 +2,6 @@ #pragma once - namespace nri { struct DeviceMTL; diff --git a/Source/VK/CommandQueueVK.h b/Source/VK/CommandQueueVK.h index 71a1821..bfb0c6d 100644 --- a/Source/VK/CommandQueueVK.h +++ b/Source/VK/CommandQueueVK.h @@ -39,7 +39,6 @@ struct CommandQueueVK { void SetDebugName(const char* name); void Submit(const QueueSubmitDesc& queueSubmitDesc, const SwapChain* swapChain); - Result UploadData(const TextureUploadDesc* textureUploadDescs, uint32_t textureUploadDescNum, const BufferUploadDesc* bufferUploadDescs, uint32_t bufferUploadDescNum); Result WaitForIdle(); private: From bd20ca5f29da7a3fc01d035d9d855fd71578694f Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Fri, 30 Aug 2024 08:05:34 -0700 Subject: [PATCH 04/24] add ds_store Signed-off-by: Michael Pollind --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index ef35f6b..42f0944 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +# apple +.DS_Store + # cmake CMakeFiles/ .cmake/ From 5838a59a0296e2b54636f2a828f68fdba814305d Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Fri, 30 Aug 2024 08:08:01 -0700 Subject: [PATCH 05/24] feat: update commanQueuMTL Signed-off-by: Michael Pollind --- Source/Metal/CommandQueueMTL.h | 2 -- Source/Metal/CommandQueueMTL.mm | 14 ++++++++++++-- Source/VK/CommandQueueVK.h | 1 + Source/VK/DeviceVK.h | 3 +-- 4 files changed, 14 insertions(+), 6 deletions(-) diff --git a/Source/Metal/CommandQueueMTL.h b/Source/Metal/CommandQueueMTL.h index 85f4669..0c5b35b 100644 --- a/Source/Metal/CommandQueueMTL.h +++ b/Source/Metal/CommandQueueMTL.h @@ -1,8 +1,6 @@ // © 2021 NVIDIA Corporation - #pragma once - namespace nri { struct DeviceMTL; diff --git a/Source/Metal/CommandQueueMTL.mm b/Source/Metal/CommandQueueMTL.mm index 2386982..6956aa2 100644 --- a/Source/Metal/CommandQueueMTL.mm +++ b/Source/Metal/CommandQueueMTL.mm @@ -15,7 +15,17 @@ m_Handle = handle; return Result::SUCCESS; } - -void CommandQueueMTL::SetDebugName(const char* name) { +inline void CommandQueueMTL::SetDebugName(const char* name) { + [m_Handle setLabel:[NSString stringWithUTF8String:name]]; } + +Result CommandQueueVK::WaitForIdle() { + + id waitCmdBuf = [m_Handle commandBufferWithUnretainedReferences]; + + [waitCmdBuf commit]; + [waitCmdBuf waitUntilCompleted]; + + waitCmdBuf = nil; +} \ No newline at end of file diff --git a/Source/VK/CommandQueueVK.h b/Source/VK/CommandQueueVK.h index bfb0c6d..71a1821 100644 --- a/Source/VK/CommandQueueVK.h +++ b/Source/VK/CommandQueueVK.h @@ -39,6 +39,7 @@ struct CommandQueueVK { void SetDebugName(const char* name); void Submit(const QueueSubmitDesc& queueSubmitDesc, const SwapChain* swapChain); + Result UploadData(const TextureUploadDesc* textureUploadDescs, uint32_t textureUploadDescNum, const BufferUploadDesc* bufferUploadDescs, uint32_t bufferUploadDescNum); Result WaitForIdle(); private: diff --git a/Source/VK/DeviceVK.h b/Source/VK/DeviceVK.h index 75ccc75..37ca2a2 100644 --- a/Source/VK/DeviceVK.h +++ b/Source/VK/DeviceVK.h @@ -2,7 +2,6 @@ #pragma once - namespace nri { struct CommandQueueVK; @@ -26,7 +25,7 @@ struct DeviceVK final : public DeviceBase { return m_Device; } - inline operator VkPhysicalDevice() const {DeviceB + inline operator VkPhysicalDevice() const { return m_PhysicalDevice; } From e1a21566057ff69a16a6d8be53e2da313b717056 Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Sat, 31 Aug 2024 09:24:04 -0700 Subject: [PATCH 06/24] feat: add conversion and start texture Signed-off-by: Michael Pollind --- CMakeLists.txt | 7 +++ Include/Extensions/NRIWrapperMTL.h | 8 ++- Source/Creation/Creation.cpp | 11 ++++ Source/Metal/ConversionMTL.h | 33 ++++++++++++ Source/Metal/ConversionMTL.mm | 82 ++++++++++++++++++++++++++++++ Source/Metal/DeviceMTL.h | 15 +++--- Source/Metal/DeviceMTL.mm | 12 ++++- Source/Metal/FencMTL.mm | 11 ++++ Source/Metal/FenceMTL.h | 28 ++++++++++ Source/Metal/MemoryMTL.h | 6 +-- Source/Metal/TextureMTL.h | 20 +++++++- Source/Metal/TextureMTL.mm | 24 +++++++++ Source/Shared/SharedExternal.h | 1 + 13 files changed, 243 insertions(+), 15 deletions(-) create mode 100644 Source/Metal/ConversionMTL.h create mode 100644 Source/Metal/ConversionMTL.mm create mode 100644 Source/Metal/FencMTL.mm create mode 100644 Source/Metal/FenceMTL.h diff --git a/CMakeLists.txt b/CMakeLists.txt index b1e6b67..d5a6f53 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -235,6 +235,13 @@ if (NRI_ENABLE_METAL_SUPPORT AND APPLE) file (GLOB MTL_SOURCE "Source/Metal/*.cpp" "Source/Metal/*.mm" "Source/Metal/*.h" "Source/Metal/*.hpp" ) source_group ("" FILES ${MTL_SOURCE}) add_library (NRI_MTL STATIC ${MTL_SOURCE}) + target_link_libraries(NRI_MTL + "-framework Metal" + "-framework MetalKit" + "-framework AppKit" + "-framework Foundation" + "-framework QuartzCore" + ) target_include_directories (NRI_MTL PRIVATE "Include" "Source/Shared" "External") target_compile_definitions (NRI_MTL PRIVATE ${COMPILE_DEFINITIONS}) endif() diff --git a/Include/Extensions/NRIWrapperMTL.h b/Include/Extensions/NRIWrapperMTL.h index b57e6c0..5ecf69e 100644 --- a/Include/Extensions/NRIWrapperMTL.h +++ b/Include/Extensions/NRIWrapperMTL.h @@ -42,7 +42,13 @@ NRI_STRUCT(BufferMTLDesc) void* mappedMemory; MTLResourceOptions options; } - + +NRI_STRUCT(TextureMTLDesc) +{ + id mtlTexture; + MTLTextureDescriptor* descriptor; +} + NRI_STRUCT(MemoryMTLDesc) { diff --git a/Source/Creation/Creation.cpp b/Source/Creation/Creation.cpp index 550733b..1864790 100644 --- a/Source/Creation/Creation.cpp +++ b/Source/Creation/Creation.cpp @@ -273,6 +273,17 @@ NRI_API Format NRI_CALL nriConvertDXGIFormatToNRI(uint32_t dxgiFormat) { return DXGIFormatToNRIFormat(dxgiFormat); } +NRI_API uint32_t NRI_CALL nriConvertNRIFormatToMTL(Format format) { + MaybeUnused(format); + +#if NRI_USE_VULKAN + return NRIFormatToMTLFormat(format); +#else + return 0; +#endif +} + + NRI_API uint32_t NRI_CALL nriConvertNRIFormatToVK(Format format) { MaybeUnused(format); diff --git a/Source/Metal/ConversionMTL.h b/Source/Metal/ConversionMTL.h new file mode 100644 index 0000000..4150710 --- /dev/null +++ b/Source/Metal/ConversionMTL.h @@ -0,0 +1,33 @@ +#pragma once + +#import + +#include "NRIMacro.h" +#include "NRIDescs.h" +#include "Extensions/NRIWrapperVK.h" + +namespace nri { + + constexpr std::array IMAGE_TYPES = { + MTLTextureType1D, // TEXTURE_1D + MTLTextureType2D, // TEXTURE_2D + MTLTextureType3D, // TEXTURE_3D + }; + + constexpr MTLTextureType GetImageTypeMTL(TextureType type) { + return IMAGE_TYPES[(size_t)type]; + } + + + inline MTLTextureType GetFormatMTL(Format format, bool demoteSrgb = false) { + if (demoteSrgb) { + const FormatProps& formatProps = GetFormatProps(format); + if (formatProps.isSrgb) + format = (Format)((uint32_t)format - 1); + } + + return (MTLTextureType)NRIFormatToMTLFormat(format); + } + +}; + diff --git a/Source/Metal/ConversionMTL.mm b/Source/Metal/ConversionMTL.mm new file mode 100644 index 0000000..92d6ea5 --- /dev/null +++ b/Source/Metal/ConversionMTL.mm @@ -0,0 +1,82 @@ +#include "ConversionMTL.h" + +// Each depth/stencil format is only compatible with itself in VK +constexpr std::array MLT_FORMAT = { + MTLPixelFormatInvalid, // UNKNOWN + MTLPixelFormatR8Unorm, // R8_UNORM + MTLPixelFormatR8Snorm, // R8_SNORM + MTLPixelFormatR8Uint, // R8_UINT + MTLPixelFormatR8Sint, // R8_SINT + MTLPixelFormatRG8Unorm, // RG8_UNORM + MTLPixelFormatRG8Snorm, // RG8_SNORM + MTLPixelFormatRG8Uint, // RG8_UINT + MTLPixelFormatRG8Sint, // RG8_SINT + MTLPixelFormatBGRA8Unorm, // BGRA8_UNORM + MTLPixelFormatBGRA8Unorm_sRGB, // BGRA8_SRGB + MTLPixelFormatRGBA8Unorm, // RGBA8_UNORM + MTLPixelFormatRGBA8Unorm_sRGB, // RGBA8_SRGB + MTLPixelFormatRGBA8Snorm, // RGBA8_SNORM + MTLPixelFormatRGBA8Uint, // RGBA8_UINT + MTLPixelFormatRGBA8Sint, // RGBA8_SINT + MTLPixelFormatR16Unorm, // R16_UNORM + MTLPixelFormatR16Snorm, // R16_SNORM + MTLPixelFormatR16Uint, // R16_UINT + MTLPixelFormatR16Sint, // R16_SINT + MTLPixelFormatR16Float, // R16_SFLOAT + MTLPixelFormatRG16Unorm, // RG16_UNORM + MTLPixelFormatRG16Snorm, // RG16_SNORM + MTLPixelFormatRG16Uint, // RG16_UINT + MTLPixelFormatRG16Sint, // RG16_SINT + MTLPixelFormatRG16Float, // RG16_SFLOAT + MTLPixelFormatRGBA16Unorm, // RGBA16_UNORM + MTLPixelFormatRGBA16Snorm, // RGBA16_SNORM + MTLPixelFormatRGBA16Uint, // RGBA16_UINT + MTLPixelFormatRGBA16Sint, // RGBA16_SINT + MTLPixelFormatRGBA16Float, // RGBA16_SFLOAT + MTLPixelFormatR32Uint, // R32_UINT + MTLPixelFormatR32Sint, // R32_SINT + MTLPixelFormatR32Float, // R32_SFLOAT + MTLPixelFormatRG32Uint, // RG32_UINT + MTLPixelFormatRG32Sint, // RG32_SINT + MTLPixelFormatRG32Float, // RG32_SFLOAT + MTLPixelFormatRGB32Uint, // RGB32_UINT + MTLPixelFormatRGB32Sint, // RGB32_SINT + MTLPixelFormatRGB32Float, // RGB32_SFLOAT + MTLPixelFormatRGBA32Uint, // RGB32_UINT + MTLPixelFormatRGBA32Sint, // RGB32_SINT + MTLPixelFormatRGBA32Float, // RGB32_SFLOAT + MTLPixelFormatB5G6R5Unorm, // B5_G6_R5_UNORM + MTLPixelFormatA1BGR5Unorm, // B5_G5_R5_A1_UNORM + MTLPixelFormatABGR4Unorm, // B4_G4_R4_A4_UNORM + MTLPixelFormatRGB10A2Unorm, // R10_G10_B10_A2_UNORM + MTLPixelFormatRGB10A2Uint, // R10_G10_B10_A2_UINT + MTLPixelFormatRG11B10Float, // R11_G11_B10_UFLOAT + MTLPixelFormatRGB9E5Float, // R9_G9_B9_E5_UFLOAT + MTLPixelFormatBC1_RGBA, // BC1_RGBA_UNORM + MTLPixelFormatBC1_RGBA_sRGB, // BC1_RGBA_SRGB + MTLPixelFormatBC2_RGBA, // BC2_RGBA_UNORM + MTLPixelFormatBC2_RGBA_sRGB, // BC2_RGBA_SRGB + MTLPixelFormatBC3_RGBA, // BC3_RGBA_UNORM + MTLPixelFormatBC3_RGBA_sRGB, // BC3_RGBA_SRGB + MTLPixelFormatBC4_RUnorm, // BC4_R_UNORM + MTLPixelFormatBC4_RSnorm, // BC4_R_SNORM + MTLPixelFormatBC5_RGUnorm, // BC5_RG_UNORM + MTLPixelFormatBC5_RGSnorm, // BC5_RG_SNORM + MTLPixelFormatBC6H_RGBUfloat, // BC6H_RGB_UFLOAT + MTLPixelFormatBC6H_RGBFloat, // BC6H_RGB_SFLOAT + MTLPixelFormatBC7_RGBAUnorm, // BC7_RGBA_UNORM + MTLPixelFormatBC7_RGBAUnorm_sRGB, // BC7_RGBA_SRGB + MTLPixelFormatDepth16Unorm, // D16_UNORM + MTLPixelFormatDepth24Unorm_Stencil8, // D24_UNORM_S8_UINT + MTLPixelFormatDepth32Float, // D32_SFLOAT + MTLPixelFormatDepth32Float_Stencil8, // D32_SFLOAT_S8_UINT_X24 + MTLPixelFormatDepth24Unorm_Stencil8, // R24_UNORM_X8 + MTLPixelFormatDepth24Unorm_Stencil8, // X24_G8_UINT + MTLPixelFormatDepth32Float_Stencil8, // R32_SFLOAT_X8_X24 + MTLPixelFormatDepth32Float_Stencil8, // X32_G8_UINT_X24 +}; + +uint32_t NRIFormatToMTLFormat(Format format) { + return (uint32_t)VK_FORMAT[(uint32_t)format]; +} + diff --git a/Source/Metal/DeviceMTL.h b/Source/Metal/DeviceMTL.h index 5b244d4..a3997dc 100644 --- a/Source/Metal/DeviceMTL.h +++ b/Source/Metal/DeviceMTL.h @@ -3,23 +3,24 @@ namespace nri { struct DeviceMTl final : public DeviceBase { - BufferMetal(const CallbackInterface& callbacks, const StdAllocator& stdAllocator); - ~BufferMetal(); - + DeviceMTl(const CallbackInterface& callbacks, const StdAllocator& stdAllocator); + ~DeviceMTl(); Result GetCommandQueue(CommandQueueType commandQueueType, CommandQueue*& commandQueue); - //================================================================================================================ - // DeviceBase - //================================================================================================================ + inline operator id&() const { + return m_Device; + } inline const DeviceDesc& GetDesc() const { return m_Desc; } FormatSupportBits GetFormatSupport(const Device& device, Format format); - + + void FillCreateInfo(const TextureDesc& bufferDesc, MTLTextureDescriptor* info) const; + Result FillFunctionTable(CoreInterface& table) const; Result FillFunctionTable(HelperInterface& table) const; Result FillFunctionTable(LowLatencyInterface& table) const; diff --git a/Source/Metal/DeviceMTL.mm b/Source/Metal/DeviceMTL.mm index 97b7992..65bade1 100644 --- a/Source/Metal/DeviceMTL.mm +++ b/Source/Metal/DeviceMTL.mm @@ -42,8 +42,16 @@ Result CreateDeviceMTL(const DeviceCreationMTLDesc& deviceCreationDesc, DeviceBa } - - +void DeviceMTL::FillCreateInfo(const TextureDesc& textureDesc, MTLTextureDescriptor* info) const { + info.textureType = ::GetImageTypeMTL(textureDesc.type); + into.pixelFormat = ::GetFormatMTL(textureDesc.format, true); + into.width = pDesc->mWidth; + into.height = pDesc->mHeight; + into.depth = pDesc->mDepth; + into.mipmapLevelCount = mipLevels; + into.sampleCount = pDesc->mSampleCount; + into.arrayLength = pDesc->mArraySize; +} Result DeviceMTL::Create(const DeviceCreationDesc& deviceCreationDesc, const DeviceCreationMTLDesc& deviceCreationMTLDesc, bool isWrapper) { m_OwnsNativeObjects = !isWrapper; diff --git a/Source/Metal/FencMTL.mm b/Source/Metal/FencMTL.mm new file mode 100644 index 0000000..f009671 --- /dev/null +++ b/Source/Metal/FencMTL.mm @@ -0,0 +1,11 @@ +#include "FenceMTL.h" + +using namespace nri; + +FenceMTL::~FenceMTL() { + +} + +Result FenceMTL::Create(uint64_t initialValue) { + m_Handle = dispatch_semaphore_create(initialValue); +} diff --git a/Source/Metal/FenceMTL.h b/Source/Metal/FenceMTL.h new file mode 100644 index 0000000..3aa3c29 --- /dev/null +++ b/Source/Metal/FenceMTL.h @@ -0,0 +1,28 @@ +// © 2021 NVIDIA Corporation +#pragma once + +namespace nri { + +struct DeviceMTL; + +struct FenceMTL { + inline FenceMTL(DeviceMTL& device) + : m_Device(device) { + } + ~FenceMTL(); + + inline DeviceMTL& GetDevice() const { + return m_Device; + } + + Result Create(uint64_t initialValue); + + //void SetDebugName(const char* name); + //uint64_t GetFenceValue() const; + //void Wait(uint64_t value); +private: + dispatch_semaphore_t m_Handle; + DeviceMTL& m_Device; +}; + +} // namespace nri diff --git a/Source/Metal/MemoryMTL.h b/Source/Metal/MemoryMTL.h index 2374d2a..72caa7a 100644 --- a/Source/Metal/MemoryMTL.h +++ b/Source/Metal/MemoryMTL.h @@ -14,11 +14,11 @@ struct MemoryMTL { : m_Device(device) { } - inline VkDeviceMemory GetHandle() const { - return m_Handle; + inline id GetHandle() const { + return m_Buffer; } - inline DeviceVK& GetDevice() const { + inline DeviceMTL& GetDevice() const { return m_Device; } diff --git a/Source/Metal/TextureMTL.h b/Source/Metal/TextureMTL.h index 0195ba8..b856e50 100644 --- a/Source/Metal/TextureMTL.h +++ b/Source/Metal/TextureMTL.h @@ -11,10 +11,26 @@ struct TextureMTL { inline TextureMTL(DeviceMTL& device) : m_Device(device) { } + + ~TextureMTL(); + + inline id& GetHandle() const { + return m_Handle; + } + + inline DeviceMTL& GetDevice() const { + return m_Device; + } + + + Result Create(const TextureDesc& textureDesc); + Result Create(const TextureMTLDesc& textureDesc); +// Result Create(const AllocateTextureDesc& textureDesc); + private: DeviceMTL& m_Device; - + id m_Handle; + TextureDesc m_Desc = {}; }; - } diff --git a/Source/Metal/TextureMTL.mm b/Source/Metal/TextureMTL.mm index e69de29..876cc2d 100644 --- a/Source/Metal/TextureMTL.mm +++ b/Source/Metal/TextureMTL.mm @@ -0,0 +1,24 @@ +#include "TextureMTL.h" + +TextureMTL::~TextureMTL() { + m_Handle = nil; +} + + +Result Create(const TextureMTLDesc& textureDesc) { + m_Handle = texturedesc.texture; + return Result::SUCCESS; +} + +Result Create(const TextureMTLDesc& textureDesc) { + return Result::SUCCESS; +} + +Result Create(const TextureDesc& textureDesc) { + MTLTextureDescriptor* info = [[MTLTextureDescriptor alloc] init]; + m_Device.FillCreateInfo(textureDesc, info); + + m_Handle = [m_Device newTextureWithDescriptor:textureDesc]; + return Result::SUCCESS; +} + diff --git a/Source/Shared/SharedExternal.h b/Source/Shared/SharedExternal.h index b619aeb..1709991 100644 --- a/Source/Shared/SharedExternal.h +++ b/Source/Shared/SharedExternal.h @@ -164,6 +164,7 @@ nri::Format VKFormatToNRIFormat(uint32_t vkFormat); uint32_t NRIFormatToDXGIFormat(nri::Format format); uint32_t NRIFormatToVKFormat(nri::Format format); +uint32_t NRIFormatToMTLFormat(nri::Format format); // Misc inline nri::Vendor GetVendorFromID(uint32_t vendorID) { From 3ef604ea932d8d7c9177589d5e3950c2785f12e6 Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Sun, 1 Sep 2024 00:01:47 -0700 Subject: [PATCH 07/24] feat: add more to api Signed-off-by: Michael Pollind --- Source/Metal/BufferMTL.h | 2 - Source/Metal/BufferMTL.mm | 11 +++ Source/Metal/ConversionMTL.h | 159 +++++++++++++++++++++++++++--- Source/Metal/DeviceMTL.h | 6 +- Source/Metal/DeviceMTL.hpp | 77 +++++++++------ Source/Metal/DeviceMTL.mm | 2 +- Source/Metal/PipelineLayoutMTL.h | 54 ++++++++++ Source/Metal/PipelineLayoutMTL.mm | 0 Source/Metal/PipelineMTL.h | 20 ++++ Source/Metal/PipelineMTL.mm | 55 +++++++++++ Source/Metal/TextureMTL.h | 9 +- 11 files changed, 337 insertions(+), 58 deletions(-) create mode 100644 Source/Metal/PipelineLayoutMTL.h create mode 100644 Source/Metal/PipelineLayoutMTL.mm create mode 100644 Source/Metal/PipelineMTL.h create mode 100644 Source/Metal/PipelineMTL.mm diff --git a/Source/Metal/BufferMTL.h b/Source/Metal/BufferMTL.h index a71e757..c7924f5 100644 --- a/Source/Metal/BufferMTL.h +++ b/Source/Metal/BufferMTL.h @@ -1,5 +1,3 @@ - - #import struct DeviceMTL; diff --git a/Source/Metal/BufferMTL.mm b/Source/Metal/BufferMTL.mm index f01f9ab..a336722 100644 --- a/Source/Metal/BufferMTL.mm +++ b/Source/Metal/BufferMTL.mm @@ -1,2 +1,13 @@ #include "BufferMetal.h" +Result BufferMTL::Create(const BufferDesc& bufferDesc) { + return RESULT::SUCCESS; +} + +Result BufferMTL::Create(const BufferVKDesc& bufferDesc) { + return RESULT::SUCCESS; +} + +Result BufferMTL::Create(const AllocateBufferDesc& bufferDesc) { + return RESULT::SUCCESS; +} diff --git a/Source/Metal/ConversionMTL.h b/Source/Metal/ConversionMTL.h index 4150710..b381dc3 100644 --- a/Source/Metal/ConversionMTL.h +++ b/Source/Metal/ConversionMTL.h @@ -8,26 +8,153 @@ namespace nri { - constexpr std::array IMAGE_TYPES = { - MTLTextureType1D, // TEXTURE_1D - MTLTextureType2D, // TEXTURE_2D - MTLTextureType3D, // TEXTURE_3D - }; - - constexpr MTLTextureType GetImageTypeMTL(TextureType type) { - return IMAGE_TYPES[(size_t)type]; - } +constexpr std::array IMAGE_TYPES = { + MTLTextureType1D, // TEXTURE_1D + MTLTextureType2D, // TEXTURE_2D + MTLTextureType3D, // TEXTURE_3D +}; + +constexpr MTLTextureType GetImageTypeMTL(TextureType type) { + return IMAGE_TYPES[(size_t)type]; +} + +constexpr std::array BLEND_OP = { + MTLBlendOperationAdd, // ADD + MTLBlendOperationSubtract, // SUBTRACT + MTLBlendOperationReverseSubtract, // REVERSE_SUBTRACT + MTLBlendOperationMin, // MIN + MTLBlendOperationMax // MAX +}; +constexpr MTLBlendOperation GetBlendOp(BlendFunc blendFunc) { + return BLEND_OP[(size_t)blendFunc]; +} + +constexpr std::array BLEND_FACTOR = { + MTLBlendFactorZero, // ZERO + MTLBlendFactorOne, // ONE + MTLBlendFactorSourceColor, // SRC_COLOR + MTLBlendFactorOneMinusSourceColor, // ONE_MINUS_SRC_COLOR + MTLBlendFactorDestinationColor, // DST_COLOR + MTLBlendFactorOneMinusDestinationColor, // ONE_MINUS_DST_COLOR + MTLBlendFactorSourceAlpha, // SRC_ALPHA + MTLBlendFactorOneMinusSourceAlpha, // ONE_MINUS_SRC_ALPHA + MTLBlendFactorDestinationAlpha, // DST_ALPHA + MTLBlendFactorOneMinusDestinationAlpha, // ONE_MINUS_DST_ALPHA + MTLBlendFactorBlendColor, // CONSTANT_COLOR + MTLBlendFactorOneMinusBlendColor, // ONE_MINUS_CONSTANT_COLOR + MTLBlendFactorBlendAlpha, // CONSTANT_ALPHA + MTLBlendFactorOneMinusBlendAlpha, // ONE_MINUS_CONSTANT_ALPHA + MTLBlendFactorSourceAlphaSaturated, // SRC_ALPHA_SATURATE + MTLBlendFactorSource1Color, // SRC1_COLOR + MTLBlendFactorOneMinusSource1Color, // ONE_MINUS_SRC1_COLOR + MTLBlendFactorSource1Alpha, // SRC1_ALPHA + MTLBlendFactorOneMinusSource1Alpha, // ONE_MINUS_SRC1_ALPHA +}; + + + +constexpr MTLColorWriteMask GetColorComponent(ColorWriteBits colorWriteMask) { + return MTLColorWriteMask(colorWriteMask) & MTLColorWriteMaskAll; +} + + +constexpr MTLBlendFactor GetBlendFactor(BlendFactor blendFactor) { + return BLEND_FACTOR[(size_t)blendFactor]; +} + +constexpr std::array COMPARE_OP = { + MTLCompareFunctionNever, // NONE + MTLCompareFunctionAlways, // ALWAYS + MTLCompareFunctionNever, // NEVER + MTLCompareFunctionEqual, // EQUAL + MTLCompareFunctionNotEqual, // NOT_EQUAL + MTLCompareFunctionLess, // LESS + MTLCompareFunctionLessEqual, // LESS_EQUAL + MTLCompareFunctionGreater, // GREATER + MTLCompareFunctionGreaterEqual, // GREATER_EQUAL +}; + +constexpr MTLCompareFunction GetCompareOp(CompareFunc compareFunc) { + return COMPARE_OP[(size_t)compareFunc]; +} + +constexpr std::array STENCIL_OP = { + MTLStencilOperationKeep, // KEEP + MTLStencilOperationZero, // ZERO + MTLStencilOperationReplace, // REPLACE + MTLStencilOperationIncrementClamp, // INCREMENT_AND_CLAMP + MTLStencilOperationDecrementClamp, // DECREMENT_AND_CLAMP + MTLStencilOperationInvert, // INVERT + MTLStencilOperationIncrementWrap, // INCREMENT_AND_WRAP + MTLStencilOperationDecrementWrap // DECREMENT_AND_WRAP +}; + +constexpr MTLStencilOperation GetStencilOp(StencilFunc stencilFunc) { + return STENCIL_OP[(size_t)stencilFunc]; +} + + +constexpr std::array CULL_MODES = { + MTLCullModeNone, // NONE + MTLCullModeFront, // FRONT + MTLCullModeBack // BACK +}; + +constexpr MTLCullMode GetCullMode(CullMode cullMode) { + return CULL_MODES[(size_t)cullMode]; +} + +constexpr std::array POLYGON_MODES = { + MTLTriangleFillModeFill, // SOLID + MTLTriangleFillModeLines // WIREFRAME +}; + +constexpr MTLTriangleFillMode GetPolygonMode(FillMode fillMode) { + return POLYGON_MODES[(size_t)fillMode]; +} + +constexpr std::array SAMPLER_ADDRESS_MODE = { + MTLSamplerAddressModeRepeat, // REPEAT + MTLSamplerAddressModeMirrorRepeat, // MIRRORED_REPEAT + MTLSamplerAddressModeClampToEdge, // CLAMP_TO_EDGE + MTLSamplerAddressModeClampToBorder // CLAMP_TO_BORDER +}; + +constexpr MTLSamplerAddressMode GetSamplerAddressMode(AddressMode addressMode) { + return SAMPLER_ADDRESS_MODE[(size_t)addressMode]; +} + + + +constexpr std::array TOPOLOGIES = { + MTLPrimitiveTopologyClassPoint, // POINT_LIST + MTLPrimitiveTopologyClassLine, // LINE_LIST + MTLPrimitiveTopologyClassLine, // LINE_STRIP + MTLPrimitiveTopologyClassTriangle, // TRIANGLE_LIST + MTLPrimitiveTopologyClassTriangle, // TRIANGLE_STRIP + MTLPrimitiveTopologyClassLine, // LINE_LIST_WITH_ADJACENCY + MTLPrimitiveTopologyClassLine, // LINE_STRIP_WITH_ADJACENCY + MTLPrimitiveTopologyClassTriangle, // TRIANGLE_LIST_WITH_ADJACENCY + MTLPrimitiveTopologyClassTriangle, // TRIANGLE_STRIP_WITH_ADJACENCY + MTLPrimitiveTopologyClassTriangle // PATCH_LIST TODO: not sure +}; + + +constexpr MTLPrimitiveTopologyClass GetTopologyMTL(Topology topology) { + return TOPOLOGIES[(size_t)topology]; +} - inline MTLTextureType GetFormatMTL(Format format, bool demoteSrgb = false) { - if (demoteSrgb) { - const FormatProps& formatProps = GetFormatProps(format); - if (formatProps.isSrgb) - format = (Format)((uint32_t)format - 1); - } - return (MTLTextureType)NRIFormatToMTLFormat(format); +inline MTLTextureType GetFormatMTL(Format format, bool demoteSrgb = false) { + if (demoteSrgb) { + const FormatProps& formatProps = GetFormatProps(format); + if (formatProps.isSrgb) + format = (Format)((uint32_t)format - 1); } + + return (MTLTextureType)NRIFormatToMTLFormat(format); +} }; diff --git a/Source/Metal/DeviceMTL.h b/Source/Metal/DeviceMTL.h index a3997dc..11aa325 100644 --- a/Source/Metal/DeviceMTL.h +++ b/Source/Metal/DeviceMTL.h @@ -2,9 +2,9 @@ namespace nri { -struct DeviceMTl final : public DeviceBase { - DeviceMTl(const CallbackInterface& callbacks, const StdAllocator& stdAllocator); - ~DeviceMTl(); +struct DeviceMTL final : public DeviceBase { + DeviceMTL(const CallbackInterface& callbacks, const StdAllocator& stdAllocator); + ~DeviceMTL(); Result GetCommandQueue(CommandQueueType commandQueueType, CommandQueue*& commandQueue); diff --git a/Source/Metal/DeviceMTL.hpp b/Source/Metal/DeviceMTL.hpp index 267e1f8..8e2b3b4 100644 --- a/Source/Metal/DeviceMTL.hpp +++ b/Source/Metal/DeviceMTL.hpp @@ -1,3 +1,5 @@ +// © 2021 NVIDIA Corporation + Declare_PartiallyFillFunctionTable_Functions(MTL); #pragma region[ Core ] @@ -19,90 +21,101 @@ static FormatSupportBits NRI_CALL GetFormatSupport(const Device& device, Format } static void NRI_CALL GetBufferMemoryDesc(const Device& device, const BufferDesc& bufferDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { - D3D12_RESOURCE_DESC desc = {}; - GetResourceDesc(&desc, bufferDesc); + //D3D12_RESOURCE_DESC desc = {}; + //GetResourceDesc(&desc, bufferDesc); - ((const DeviceD3D12&)device).GetMemoryDesc(memoryLocation, desc, memoryDesc); + //((const DeviceD3D12&)device).GetMemoryDesc(memoryLocation, desc, memoryDesc); } static void NRI_CALL GetTextureMemoryDesc(const Device& device, const TextureDesc& textureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { - D3D12_RESOURCE_DESC desc = {}; - GetResourceDesc(&desc, textureDesc); + //D3D12_RESOURCE_DESC desc = {}; + //GetResourceDesc(&desc, textureDesc); - ((const DeviceD3D12&)device).GetMemoryDesc(memoryLocation, desc, memoryDesc); + //((const DeviceD3D12&)device).GetMemoryDesc(memoryLocation, desc, memoryDesc); } static Result NRI_CALL GetCommandQueue(Device& device, CommandQueueType commandQueueType, CommandQueue*& commandQueue) { - return ((DeviceD3D12&)device).GetCommandQueue(commandQueueType, commandQueue); + return ((DeviceMTL&)device).GetCommandQueue(commandQueueType, commandQueue); } static Result NRI_CALL CreateCommandAllocator(const CommandQueue& commandQueue, CommandAllocator*& commandAllocator) { - DeviceD3D12& device = ((CommandQueueD3D12&)commandQueue).GetDevice(); - return device.CreateImplementation(commandAllocator, commandQueue); + //DeviceMTL& device = ((CommandQueueD3D12&)commandQueue).GetDevice(); + //return device.CreateImplementation(commandAllocator, commandQueue); + return Result::SUCCESS; } static Result NRI_CALL CreateDescriptorPool(Device& device, const DescriptorPoolDesc& descriptorPoolDesc, DescriptorPool*& descriptorPool) { - return ((DeviceD3D12&)device).CreateImplementation(descriptorPool, descriptorPoolDesc); + //return ((DeviceMTL&)device).CreateImplementation(descriptorPool, descriptorPoolDesc); + return Result::SUCCESS; } static Result NRI_CALL CreateBuffer(Device& device, const BufferDesc& bufferDesc, Buffer*& buffer) { - return ((DeviceD3D12&)device).CreateImplementation(buffer, bufferDesc); + //return ((DeviceMTL&)device).CreateImplementation(buffer, bufferDesc); + return Result::SUCCESS; } static Result NRI_CALL CreateTexture(Device& device, const TextureDesc& textureDesc, Texture*& texture) { - return ((DeviceD3D12&)device).CreateImplementation(texture, textureDesc); + //return ((DeviceMTL&)device).CreateImplementation(texture, textureDesc); + return Result::SUCCESS; } static Result NRI_CALL CreateBufferView(const BufferViewDesc& bufferViewDesc, Descriptor*& bufferView) { - DeviceD3D12& device = ((const BufferD3D12*)bufferViewDesc.buffer)->GetDevice(); - return device.CreateImplementation(bufferView, bufferViewDesc); + //DeviceMTL& device = ((const BufferD3D12*)bufferViewDesc.buffer)->GetDevice(); + //return device.CreateImplementation(bufferView, bufferViewDesc); + return Result::SUCCESS; } static Result NRI_CALL CreateTexture1DView(const Texture1DViewDesc& textureViewDesc, Descriptor*& textureView) { - DeviceD3D12& device = ((const TextureD3D12*)textureViewDesc.texture)->GetDevice(); - return device.CreateImplementation(textureView, textureViewDesc); + //DeviceMTL& device = ((const TextureD3D12*)textureViewDesc.texture)->GetDevice(); + //return device.CreateImplementation(textureView, textureViewDesc); + return Result::SUCCESS; } static Result NRI_CALL CreateTexture2DView(const Texture2DViewDesc& textureViewDesc, Descriptor*& textureView) { - DeviceD3D12& device = ((const TextureD3D12*)textureViewDesc.texture)->GetDevice(); - return device.CreateImplementation(textureView, textureViewDesc); + //DeviceMTL& device = ((const TextureD3D12*)textureViewDesc.texture)->GetDevice(); + //return device.CreateImplementation(textureView, textureViewDesc); + return Result::SUCCESS; } static Result NRI_CALL CreateTexture3DView(const Texture3DViewDesc& textureViewDesc, Descriptor*& textureView) { - DeviceD3D12& device = ((const TextureD3D12*)textureViewDesc.texture)->GetDevice(); - return device.CreateImplementation(textureView, textureViewDesc); + //DeviceMTL& device = ((const TextureD3D12*)textureViewDesc.texture)->GetDevice(); + //return device.CreateImplementation(textureView, textureViewDesc); + return Result::SUCCESS; } static Result NRI_CALL CreateSampler(Device& device, const SamplerDesc& samplerDesc, Descriptor*& sampler) { - return ((DeviceD3D12&)device).CreateImplementation(sampler, samplerDesc); + //return ((DeviceMTL&)device).CreateImplementation(sampler, samplerDesc); + return Result::SUCCESS; } static Result NRI_CALL CreatePipelineLayout(Device& device, const PipelineLayoutDesc& pipelineLayoutDesc, PipelineLayout*& pipelineLayout) { - return ((DeviceD3D12&)device).CreateImplementation(pipelineLayout, pipelineLayoutDesc); + //return ((DeviceMTL&)device).CreateImplementation(pipelineLayout, pipelineLayoutDesc); + return Result::SUCCESS; } static Result NRI_CALL CreateGraphicsPipeline(Device& device, const GraphicsPipelineDesc& graphicsPipelineDesc, Pipeline*& pipeline) { - return ((DeviceD3D12&)device).CreateImplementation(pipeline, graphicsPipelineDesc); + //return ((DeviceMTL&)device).CreateImplementation(pipeline, graphicsPipelineDesc); + return Result::SUCCESS; } static Result NRI_CALL CreateComputePipeline(Device& device, const ComputePipelineDesc& computePipelineDesc, Pipeline*& pipeline) { - return ((DeviceD3D12&)device).CreateImplementation(pipeline, computePipelineDesc); + return ((DeviceMTL&)device).CreateImplementation(pipeline, computePipelineDesc); } static Result NRI_CALL CreateFence(Device& device, uint64_t initialValue, Fence*& fence) { - return ((DeviceD3D12&)device).CreateImplementation(fence, initialValue); + return ((DeviceMTL&)device).CreateImplementation(fence, initialValue); } static Result NRI_CALL CreateQueryPool(Device& device, const QueryPoolDesc& queryPoolDesc, QueryPool*& queryPool) { - return ((DeviceD3D12&)device).CreateImplementation(queryPool, queryPoolDesc); + return ((DeviceMTL&)device).CreateImplementation(queryPool, queryPoolDesc); } static void NRI_CALL DestroyCommandBuffer(CommandBuffer& commandBuffer) { - Destroy((CommandBufferD3D12*)&commandBuffer); + //Destroy((CommandBufferD3D12*)&commandBuffer); } static void NRI_CALL DestroyCommandAllocator(CommandAllocator& commandAllocator) { - Destroy((CommandAllocatorD3D12*)&commandAllocator); + //Destroy((CommandAllocatorD3D12*)&commandAllocator); } static void NRI_CALL DestroyDescriptorPool(DescriptorPool& descriptorPool) { @@ -138,15 +151,15 @@ static void NRI_CALL DestroyFence(Fence& fence) { } static Result NRI_CALL AllocateMemory(Device& device, const AllocateMemoryDesc& allocateMemoryDesc, Memory*& memory) { - return ((DeviceD3D12&)device).CreateImplementation(memory, allocateMemoryDesc); + return ((DeviceMTL&)device).CreateImplementation(memory, allocateMemoryDesc); } static Result NRI_CALL BindBufferMemory(Device& device, const BufferMemoryBindingDesc* memoryBindingDescs, uint32_t memoryBindingDescNum) { - return ((DeviceD3D12&)device).BindBufferMemory(memoryBindingDescs, memoryBindingDescNum); + return ((DeviceMTL&)device).BindBufferMemory(memoryBindingDescs, memoryBindingDescNum); } static Result NRI_CALL BindTextureMemory(Device& device, const TextureMemoryBindingDesc* memoryBindingDescs, uint32_t memoryBindingDescNum) { - return ((DeviceD3D12&)device).BindTextureMemory(memoryBindingDescs, memoryBindingDescNum); + return ((DeviceMTL&)device).BindTextureMemory(memoryBindingDescs, memoryBindingDescNum); } static void NRI_CALL FreeMemory(Memory& memory) { @@ -154,7 +167,7 @@ static void NRI_CALL FreeMemory(Memory& memory) { } static void NRI_CALL SetDeviceDebugName(Device& device, const char* name) { - ((DeviceD3D12&)device).SetDebugName(name); + ((DeviceMTL&)device).SetDebugName(name); } static void NRI_CALL SetPipelineDebugName(Pipeline& pipeline, const char* name) { diff --git a/Source/Metal/DeviceMTL.mm b/Source/Metal/DeviceMTL.mm index 65bade1..dc20091 100644 --- a/Source/Metal/DeviceMTL.mm +++ b/Source/Metal/DeviceMTL.mm @@ -39,7 +39,7 @@ Result CreateDeviceMTL(const DeviceCreationMTLDesc& deviceCreationDesc, DeviceBa Result DeviceMTL::GetCommandQueue(CommandQueueType commandQueueType, CommandQueue*& commandQueue) { - + return Result::SUCCESS; } void DeviceMTL::FillCreateInfo(const TextureDesc& textureDesc, MTLTextureDescriptor* info) const { diff --git a/Source/Metal/PipelineLayoutMTL.h b/Source/Metal/PipelineLayoutMTL.h new file mode 100644 index 0000000..464c31c --- /dev/null +++ b/Source/Metal/PipelineLayoutMTL.h @@ -0,0 +1,54 @@ +#pragma once + +namespace nri { + +struct DeviceMTL; + +struct PipelineLayoutMTL { + inline PipelineLayoutMTL (DeviceMTL& device) + : m_Device(device) { + } + +// inline operator VkPipelineLayout() const { +// return m_Handle; +// } +// +// inline DeviceVK& GetDevice() const { +// return m_Device; +// } +// +// inline const RuntimeBindingInfo& GetRuntimeBindingInfo() const { +// return m_RuntimeBindingInfo; +// } +// +// inline VkDescriptorSetLayout GetDescriptorSetLayout(uint32_t index) const { +// return m_DescriptorSetLayouts[index]; +// } +// +// inline VkPipelineBindPoint GetPipelineBindPoint() const { +// return m_PipelineBindPoint; +// } +// +// inline uint32_t GetDescriptorSetSpace(uint32_t setIndexInPipelineLayout) const { +// return m_DescriptorSetSpaces[setIndexInPipelineLayout]; +// } +// + ~PipelineLayoutMTL(); +// +// Result Create(const PipelineLayoutDesc& pipelineLayoutDesc); +// +// //================================================================================================================ +// // NRI +// //================================================================================================================ +// +// void SetDebugName(const char* name); + + +private: + DeviceMTL& m_Device; + id m_PipelineDesc; + //Vector m_DescriptorSetLayouts; + +}; + +} diff --git a/Source/Metal/PipelineLayoutMTL.mm b/Source/Metal/PipelineLayoutMTL.mm new file mode 100644 index 0000000..e69de29 diff --git a/Source/Metal/PipelineMTL.h b/Source/Metal/PipelineMTL.h new file mode 100644 index 0000000..61b4344 --- /dev/null +++ b/Source/Metal/PipelineMTL.h @@ -0,0 +1,20 @@ +#pragma once + +namespace nri { + +struct DeviceMTL; +struct PipelineLayoutMTL; + +struct PipelineMTL { + inline PipelineMTL(DeviceMTL& device) + : m_Device(device) { + } + ~PipelineMTL(); + + Result Create(const GraphicsPipelineDesc& graphicsPipelineDesc); +private: + DeviceMTL& m_Device; +}; + +} + diff --git a/Source/Metal/PipelineMTL.mm b/Source/Metal/PipelineMTL.mm new file mode 100644 index 0000000..53493ac --- /dev/null +++ b/Source/Metal/PipelineMTL.mm @@ -0,0 +1,55 @@ +#include "PipelineMTL.h" +#import + +PipelineMTL::~PipelineMTL() { + +} + +Result PipelineMTL::Create(const GraphicsPipelineDesc& graphicsPipelineDesc) { + MTLRenderPipelineDescriptor *renderPipelineDesc = [[MTLRenderPipelineDescriptor alloc] init]; + for (uint32_t i = 0; i < graphicsPipelineDesc.shaderNum; i++) { + } + + const VertexInputDesc *vi = graphicsPipelineDesc.vertexInput; + if (vi) { + VkVertexInputBindingDescription* streams const_cast(vertexInputState.pVertexBindingDescriptions); + for (uint32_t i = 0; i < vi->streamNum; i++) { + const VertexStreamDesc &stream = vi->streams[i]; + renderPipelineDesc.vertexDescriptor.layouts[attribute_desc.streamIndex].stride = stream.stride; + renderPipelineDesc.vertexDescriptor.layouts[attribute_desc.streamIndex].stepRate = 1; + } + } + + const InputAssemblyDesc& ia = graphicsPipelineDesc.inputAssembly; + renderPipelineDesc.inputPrimitiveTopology = GetTopologyMTL(ia.topology); + + if (graphicsPipelineDesc.multisample) { + // TODO: multisampling + } + + + // Blending + const OutputMergerDesc& om = graphicsPipelineDesc.outputMerger; + + // assign render target pixel format for all attachments + for (uint32_t i = 0; i < om.colorNum; i++) { + + MTLRenderPipelineColorAttachmentDescriptor& colorAtachment = &renderPipelineDesc.colorAttachments[i]; + const ColorAttachmentDesc& attachmentDesc = om.color[i]; + + colorAtachment.pixelFormat = GetFormatMTL(attachmentDesc.format, false); + + colorAtachment.blendingEnabled = attachmentDesc.blendEnabled; + colorAtachment.rgbBlendOperation = GetBlendOp(attachmentDesc.colorBlend.func); + colorAtachment.alphaBlendOperation = GetBlendOp(attachmentDesc.alphaBlend.func); + + colorAtachment.sourceRGBBlendFactor = GetBlendFactor(attachmentDesc.colorBlend.srcFactor); + colorAtachment.destinationRGBBlendFactor = GetBlendFactor(attachmentDesc.colorBlend.dstFactor); + colorAtachment.sourceAlphaBlendFactor = GetBlendFactor(attachmentDesc.alphaBlend.srcFactor); + colorAtachment.destinationAlphaBlendFactor = GetBlendFactor(attachmentDesc.alphaBlend.dstFactor); + + colorAtachment.writeMask = GetColorComponent(pDesc->mColorWriteMasks[blendDescIndex]); + + } + +} diff --git a/Source/Metal/TextureMTL.h b/Source/Metal/TextureMTL.h index b856e50..d10e989 100644 --- a/Source/Metal/TextureMTL.h +++ b/Source/Metal/TextureMTL.h @@ -11,7 +11,6 @@ struct TextureMTL { inline TextureMTL(DeviceMTL& device) : m_Device(device) { } - ~TextureMTL(); inline id& GetHandle() const { @@ -22,15 +21,17 @@ struct TextureMTL { return m_Device; } + inline const TextureDesc& GetDesc() const { + return m_Desc; + } Result Create(const TextureDesc& textureDesc); Result Create(const TextureMTLDesc& textureDesc); -// Result Create(const AllocateTextureDesc& textureDesc); private: DeviceMTL& m_Device; - id m_Handle; TextureDesc m_Desc = {}; + id m_Handle; }; -} +} // namespace nri \ No newline at end of file From 7c07c32e7b16106948ef66f323ee0379ed2ba73a Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Sun, 1 Sep 2024 17:31:14 -0700 Subject: [PATCH 08/24] feat: fix build Signed-off-by: Michael Pollind --- CMakeLists.txt | 2 +- Include/Extensions/NRIWrapperMTL.h | 60 +++++----- Include/NRIDescs.h | 11 +- Source/Creation/Creation.cpp | 4 +- Source/Metal/BufferMTL.h | 28 ++--- Source/Metal/BufferMTL.mm | 13 ++- Source/Metal/CommandQueueMTL.h | 8 +- Source/Metal/CommandQueueMTL.mm | 9 +- Source/Metal/ConversionMTL.h | 43 +++----- Source/Metal/ConversionMTL.mm | 14 ++- Source/Metal/DeviceMTL.h | 14 ++- Source/Metal/DeviceMTL.hpp | 47 ++++---- Source/Metal/DeviceMTL.mm | 172 ++++++++++++++--------------- Source/Metal/FencMTL.mm | 2 + Source/Metal/FenceMTL.h | 3 + Source/Metal/MemoryMTL.h | 2 + Source/Metal/MemoryMTL.mm | 13 ++- Source/Metal/PipelineLayoutMTL.h | 5 +- Source/Metal/PipelineLayoutMTL.mm | 11 ++ Source/Metal/PipelineMTL.h | 2 + Source/Metal/PipelineMTL.mm | 37 ++++--- Source/Metal/SharedMTL.h | 8 ++ Source/Metal/TextureMTL.h | 15 +-- Source/Metal/TextureMTL.mm | 31 ++++-- Source/Shared/SharedExternal.h | 5 +- 25 files changed, 310 insertions(+), 249 deletions(-) create mode 100644 Source/Metal/SharedMTL.h diff --git a/CMakeLists.txt b/CMakeLists.txt index d5a6f53..17c650f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -247,7 +247,7 @@ if (NRI_ENABLE_METAL_SUPPORT AND APPLE) endif() # VK -if (NRI_ENABLE_VK_SUPPORT AND NOT APPLE) +if (NRI_ENABLE_VK_SUPPORT) message ("NRI adding backend: VK") set (COMPILE_DEFINITIONS ${COMPILE_DEFINITIONS} NRI_USE_VK=1) diff --git a/Include/Extensions/NRIWrapperMTL.h b/Include/Extensions/NRIWrapperMTL.h index 5ecf69e..96a8fc0 100644 --- a/Include/Extensions/NRIWrapperMTL.h +++ b/Include/Extensions/NRIWrapperMTL.h @@ -7,55 +7,57 @@ NRI_NAMESPACE_BEGIN -NRI_ENUM -( - MTLGPUFamily, uint8_t, - - Apple1, - Apple2, - Apple3, - Apple4, - Apple5, - Apple6, - Apple7, - Mac1, - Mac2, - - MAX_APPLE_FAMILY_NUM -); +typedef void* MTLBufferHandle; +typedef void* MTLTextureHandle; +typedef void* MTLDeviceHandle; + +//NRI_ENUM +//( +// MTLGPUFamily, uint8_t, + // Apple1, +// Apple2, +// Apple3, +// Apple4, +// Apple5, +// Apple6, +// Apple7, +// Mac1, +// Mac2, + +// MAX_APPLE_FAMILY_NUM +//); NRI_STRUCT(DeviceCreationMTLDesc) { bool enableNRIValidation; - id MtlDevice; -} + MTLDeviceHandle MtlDevice; +}; NRI_STRUCT(CommandBufferMTLDesc) { -} +}; NRI_STRUCT(BufferMTLDesc) { - id buffer; + MTLBufferHandle buffer; void* mappedMemory; - MTLResourceOptions options; -} + //MTLResourceOptions options; +}; NRI_STRUCT(TextureMTLDesc) { - id mtlTexture; - MTLTextureDescriptor* descriptor; -} - + //MTLTextureHandle mtlTexture; + //MTLTextureDescriptor* descriptor; +}; NRI_STRUCT(MemoryMTLDesc) { - id buffer; + MTLBufferHandle buffer; void* mappedMemory; - MTLResourceOptions options; -} + //MTLResourceOptions options; +}; NRI_API NRI_NAME(Result) NRI_CALL nriCreateDeviceFromMtlDevice(const NRI_NAME_REF(DeviceCreationMTLDesc) deviceDesc, NRI_NAME_REF(Device*) device); diff --git a/Include/NRIDescs.h b/Include/NRIDescs.h index 9e66b90..a859f3b 100644 --- a/Include/NRIDescs.h +++ b/Include/NRIDescs.h @@ -1292,7 +1292,14 @@ NriEnum(GraphicsAPI, uint8_t, MAX_NUM ); -NriEnum(Vendor, uint8_t, +// defined in apple framework +#undef INTEL +#undef AMD + +NRI_ENUM +( + + Vendor, uint8_t, UNKNOWN, NVIDIA, AMD, @@ -1300,7 +1307,7 @@ NriEnum(Vendor, uint8_t, APPLE, MAX_NUM -); +); NriStruct(AdapterDesc) { char name[256]; diff --git a/Source/Creation/Creation.cpp b/Source/Creation/Creation.cpp index 1864790..ad81f93 100644 --- a/Source/Creation/Creation.cpp +++ b/Source/Creation/Creation.cpp @@ -223,7 +223,7 @@ NRI_API Result NRI_CALL nriCreateDeviceFromMtlDevice(const DeviceCreationMTLDesc DeviceBase* deviceImpl = nullptr; #if NRI_USE_MTL - result = CreateDeviceD3D12(tempDeviceCreationD3D12Desc, deviceImpl); + //result = CreateDeviceD3D12(tempDeviceCreationD3D12Desc, deviceImpl); #endif if (result != Result::SUCCESS) @@ -402,6 +402,8 @@ NRI_API void NRI_CALL nriReportLiveObjects() { pDebug->ReportLiveObjects(DXGI_DEBUG_ALL, (DXGI_DEBUG_RLO_FLAGS)((uint32_t)DXGI_DEBUG_RLO_DETAIL | (uint32_t)DXGI_DEBUG_RLO_IGNORE_INTERNAL)); } +#elif __APPLE__ + #else # include # define GET_VK_FUNCTION(instance, name) \ diff --git a/Source/Metal/BufferMTL.h b/Source/Metal/BufferMTL.h index c7924f5..63be8c8 100644 --- a/Source/Metal/BufferMTL.h +++ b/Source/Metal/BufferMTL.h @@ -1,38 +1,40 @@ +// © 2021 NVIDIA Corporation +#pragma once + #import +namespace nri { + struct DeviceMTL; struct MemoryMTL; struct BufferMTL { - + inline BufferMTL(DeviceMTL& device) - : m_Device(device) { + : m_Device(device) { } - + inline id GetHandle() const { return pBuffer; } - - inline VkDeviceAddress GetDeviceAddress() const { - return m_DeviceAddress; - } - + + inline DeviceMTL& GetDevice() const { return m_Device; } - + inline const BufferDesc& GetDesc() const { return m_Desc; } - + ~BufferMTL(); Result Create(const BufferDesc& bufferDesc); Result Create(const BufferVKDesc& bufferDesc); Result Create(const AllocateBufferDesc& bufferDesc); - + private: - DeviceVK& m_Device; + DeviceMTL& m_Device; id pBuffer; uint8_t* m_MappedMemory = nullptr; uint64_t m_MappedMemoryOffset = 0; @@ -43,4 +45,4 @@ struct BufferMTL { }; - +}; diff --git a/Source/Metal/BufferMTL.mm b/Source/Metal/BufferMTL.mm index a336722..38e4759 100644 --- a/Source/Metal/BufferMTL.mm +++ b/Source/Metal/BufferMTL.mm @@ -1,13 +1,18 @@ -#include "BufferMetal.h" +#include "SharedMTL.h" + +#include "BufferMTL.h" + +using namespace nri; + Result BufferMTL::Create(const BufferDesc& bufferDesc) { - return RESULT::SUCCESS; + return Result::SUCCESS; } Result BufferMTL::Create(const BufferVKDesc& bufferDesc) { - return RESULT::SUCCESS; + return Result::SUCCESS; } Result BufferMTL::Create(const AllocateBufferDesc& bufferDesc) { - return RESULT::SUCCESS; + return Result::SUCCESS; } diff --git a/Source/Metal/CommandQueueMTL.h b/Source/Metal/CommandQueueMTL.h index 0c5b35b..e983c5e 100644 --- a/Source/Metal/CommandQueueMTL.h +++ b/Source/Metal/CommandQueueMTL.h @@ -1,6 +1,8 @@ // © 2021 NVIDIA Corporation #pragma once +#import + namespace nri { struct DeviceMTL; @@ -32,12 +34,14 @@ struct CommandQueueMTL { inline Lock& GetLock() { return m_Lock; } - + + Result WaitForIdle(); + void SetDebugName(const char* name); Result Create(CommandQueueType type, uint32_t familyIndex, id handle); private: DeviceMTL& m_Device; - uint32_t m_FamilyIndex = INVALID_FAMILY_INDEX; + uint32_t m_FamilyIndex = 0; CommandQueueType m_Type = CommandQueueType(-1); id m_Handle; Lock m_Lock; diff --git a/Source/Metal/CommandQueueMTL.mm b/Source/Metal/CommandQueueMTL.mm index 6956aa2..dde2fbc 100644 --- a/Source/Metal/CommandQueueMTL.mm +++ b/Source/Metal/CommandQueueMTL.mm @@ -1,12 +1,13 @@ // © 2021 NVIDIA Corporation +#include "SharedMTL.h" + #include "CommandQueueMTL.h" using namespace nri; - CommandQueueMTL::~CommandQueueMTL() { - m_CommandQueue = nil; + m_Handle = nil; } Result CommandQueueMTL::Create(CommandQueueType type, uint32_t familyIndex, id handle) { @@ -20,7 +21,7 @@ [m_Handle setLabel:[NSString stringWithUTF8String:name]]; } -Result CommandQueueVK::WaitForIdle() { +Result CommandQueueMTL::WaitForIdle() { id waitCmdBuf = [m_Handle commandBufferWithUnretainedReferences]; @@ -28,4 +29,4 @@ [waitCmdBuf waitUntilCompleted]; waitCmdBuf = nil; -} \ No newline at end of file +} diff --git a/Source/Metal/ConversionMTL.h b/Source/Metal/ConversionMTL.h index b381dc3..d1aa5b5 100644 --- a/Source/Metal/ConversionMTL.h +++ b/Source/Metal/ConversionMTL.h @@ -1,23 +1,9 @@ #pragma once -#import - -#include "NRIMacro.h" -#include "NRIDescs.h" -#include "Extensions/NRIWrapperVK.h" +#include namespace nri { -constexpr std::array IMAGE_TYPES = { - MTLTextureType1D, // TEXTURE_1D - MTLTextureType2D, // TEXTURE_2D - MTLTextureType3D, // TEXTURE_3D -}; - -constexpr MTLTextureType GetImageTypeMTL(TextureType type) { - return IMAGE_TYPES[(size_t)type]; -} - constexpr std::array BLEND_OP = { MTLBlendOperationAdd, // ADD MTLBlendOperationSubtract, // SUBTRACT @@ -29,6 +15,16 @@ constexpr MTLBlendOperation GetBlendOp(BlendFunc blendFunc) { return BLEND_OP[(size_t)blendFunc]; } +constexpr std::array IMAGE_TYPES = { + MTLTextureType1D, // TEXTURE_1D + MTLTextureType2D, // TEXTURE_2D + MTLTextureType3D, // TEXTURE_3D +}; + +constexpr MTLTextureType GetImageTypeMTL(TextureType type) { + return IMAGE_TYPES[(size_t)type]; +} + constexpr std::array BLEND_FACTOR = { MTLBlendFactorZero, // ZERO MTLBlendFactorOne, // ONE @@ -51,17 +47,14 @@ constexpr std::array BLEND_FACTOR MTLBlendFactorOneMinusSource1Alpha, // ONE_MINUS_SRC1_ALPHA }; - +constexpr MTLBlendFactor GetBlendFactor(BlendFactor blendFactor) { + return BLEND_FACTOR[(size_t)blendFactor]; +} constexpr MTLColorWriteMask GetColorComponent(ColorWriteBits colorWriteMask) { return MTLColorWriteMask(colorWriteMask) & MTLColorWriteMaskAll; } - -constexpr MTLBlendFactor GetBlendFactor(BlendFactor blendFactor) { - return BLEND_FACTOR[(size_t)blendFactor]; -} - constexpr std::array COMPARE_OP = { MTLCompareFunctionNever, // NONE MTLCompareFunctionAlways, // ALWAYS @@ -117,7 +110,7 @@ constexpr std::array SAMPLE MTLSamplerAddressModeRepeat, // REPEAT MTLSamplerAddressModeMirrorRepeat, // MIRRORED_REPEAT MTLSamplerAddressModeClampToEdge, // CLAMP_TO_EDGE - MTLSamplerAddressModeClampToBorder // CLAMP_TO_BORDER + MTLSamplerAddressModeClampToZero // CLAMP_TO_BORDER }; constexpr MTLSamplerAddressMode GetSamplerAddressMode(AddressMode addressMode) { @@ -144,16 +137,14 @@ constexpr MTLPrimitiveTopologyClass GetTopologyMTL(Topology topology) { return TOPOLOGIES[(size_t)topology]; } - - -inline MTLTextureType GetFormatMTL(Format format, bool demoteSrgb = false) { +inline MTLPixelFormat GetFormatMTL(Format format, bool demoteSrgb = false) { if (demoteSrgb) { const FormatProps& formatProps = GetFormatProps(format); if (formatProps.isSrgb) format = (Format)((uint32_t)format - 1); } - return (MTLTextureType)NRIFormatToMTLFormat(format); + return (MTLPixelFormat)NRIFormatToMTLFormat(format); } }; diff --git a/Source/Metal/ConversionMTL.mm b/Source/Metal/ConversionMTL.mm index 92d6ea5..8e13b6d 100644 --- a/Source/Metal/ConversionMTL.mm +++ b/Source/Metal/ConversionMTL.mm @@ -1,7 +1,11 @@ +#include "SharedMTL.h" + #include "ConversionMTL.h" +using namespace nri; + // Each depth/stencil format is only compatible with itself in VK -constexpr std::array MLT_FORMAT = { +constexpr std::array MTL_FORMAT = { MTLPixelFormatInvalid, // UNKNOWN MTLPixelFormatR8Unorm, // R8_UNORM MTLPixelFormatR8Snorm, // R8_SNORM @@ -39,9 +43,9 @@ MTLPixelFormatRG32Uint, // RG32_UINT MTLPixelFormatRG32Sint, // RG32_SINT MTLPixelFormatRG32Float, // RG32_SFLOAT - MTLPixelFormatRGB32Uint, // RGB32_UINT - MTLPixelFormatRGB32Sint, // RGB32_SINT - MTLPixelFormatRGB32Float, // RGB32_SFLOAT + MTLPixelFormatInvalid, // RGB32_UINT //TODO: lookup correct values + MTLPixelFormatInvalid, // RGB32_SINT //TODO: lookup correct values + MTLPixelFormatInvalid, // RGB32_SFLOAT //TODO: lookup correct values MTLPixelFormatRGBA32Uint, // RGB32_UINT MTLPixelFormatRGBA32Sint, // RGB32_SINT MTLPixelFormatRGBA32Float, // RGB32_SFLOAT @@ -77,6 +81,6 @@ }; uint32_t NRIFormatToMTLFormat(Format format) { - return (uint32_t)VK_FORMAT[(uint32_t)format]; + return (uint32_t)MTL_FORMAT[(uint32_t)format]; } diff --git a/Source/Metal/DeviceMTL.h b/Source/Metal/DeviceMTL.h index 11aa325..3edeb1d 100644 --- a/Source/Metal/DeviceMTL.h +++ b/Source/Metal/DeviceMTL.h @@ -1,7 +1,11 @@ #pragma once +#import + namespace nri { +struct CommandQueueMTL; + struct DeviceMTL final : public DeviceBase { DeviceMTL(const CallbackInterface& callbacks, const StdAllocator& stdAllocator); ~DeviceMTL(); @@ -9,7 +13,7 @@ struct DeviceMTL final : public DeviceBase { Result GetCommandQueue(CommandQueueType commandQueueType, CommandQueue*& commandQueue); - inline operator id&() const { + inline operator id() const { return m_Device; } @@ -17,14 +21,15 @@ struct DeviceMTL final : public DeviceBase { return m_Desc; } - FormatSupportBits GetFormatSupport(const Device& device, Format format); + //FormatSupportBits GetFormatSupport(const Device& device, Format format); - void FillCreateInfo(const TextureDesc& bufferDesc, MTLTextureDescriptor* info) const; + //void FillCreateInfo(const TextureDesc& bufferDesc, MTLTextureDescriptor* info) const; + // void FillCreateInfo(const TextureDesc& bufferDesc, MTLTextureDescriptor* info) const; Result FillFunctionTable(CoreInterface& table) const; Result FillFunctionTable(HelperInterface& table) const; Result FillFunctionTable(LowLatencyInterface& table) const; - Result FillFunctionTable(MeshShaderInterface& table) const; + Result FillFnctionTable(MeshShaderInterface& table) const; Result FillFunctionTable(RayTracingInterface& table) const; Result FillFunctionTable(StreamerInterface& table) const; Result FillFunctionTable(SwapChainInterface& table) const; @@ -32,7 +37,6 @@ struct DeviceMTL final : public DeviceBase { Result Create(const DeviceCreationDesc& deviceCreationDesc, const DeviceCreationMTLDesc& deviceCreationVKDesc, bool isWrapper); private: - DeviceDesc m_Desc = {}; id m_Device; std::array m_CommandQueues = {}; DeviceDesc m_Desc = {}; diff --git a/Source/Metal/DeviceMTL.hpp b/Source/Metal/DeviceMTL.hpp index 8e2b3b4..43c4359 100644 --- a/Source/Metal/DeviceMTL.hpp +++ b/Source/Metal/DeviceMTL.hpp @@ -99,15 +99,18 @@ static Result NRI_CALL CreateGraphicsPipeline(Device& device, const GraphicsPipe } static Result NRI_CALL CreateComputePipeline(Device& device, const ComputePipelineDesc& computePipelineDesc, Pipeline*& pipeline) { - return ((DeviceMTL&)device).CreateImplementation(pipeline, computePipelineDesc); + //return ((DeviceMTL&)device).CreateImplementation(pipeline, computePipelineDesc); + return Result::SUCCESS; } static Result NRI_CALL CreateFence(Device& device, uint64_t initialValue, Fence*& fence) { - return ((DeviceMTL&)device).CreateImplementation(fence, initialValue); + //return ((DeviceMTL&)device).CreateImplementation(fence, initialValue); + return Result::SUCCESS; } static Result NRI_CALL CreateQueryPool(Device& device, const QueryPoolDesc& queryPoolDesc, QueryPool*& queryPool) { - return ((DeviceMTL&)device).CreateImplementation(queryPool, queryPoolDesc); + //return ((DeviceMTL&)device).CreateImplementation(queryPool, queryPoolDesc); + return Result::SUCCESS; } static void NRI_CALL DestroyCommandBuffer(CommandBuffer& commandBuffer) { @@ -119,74 +122,78 @@ static void NRI_CALL DestroyCommandAllocator(CommandAllocator& commandAllocator) } static void NRI_CALL DestroyDescriptorPool(DescriptorPool& descriptorPool) { - Destroy((DescriptorPoolD3D12*)&descriptorPool); + //Destroy((DescriptorPoolD3D12*)&descriptorPool); } static void NRI_CALL DestroyBuffer(Buffer& buffer) { - Destroy((BufferD3D12*)&buffer); + //Destroy((BufferD3D12*)&buffer); } static void NRI_CALL DestroyTexture(Texture& texture) { - Destroy((TextureD3D12*)&texture); + //Destroy((TextureD3D12*)&texture); } static void NRI_CALL DestroyDescriptor(Descriptor& descriptor) { - Destroy((DescriptorD3D12*)&descriptor); + //Destroy((DescriptorD3D12*)&descriptor); } static void NRI_CALL DestroyPipelineLayout(PipelineLayout& pipelineLayout) { - Destroy((PipelineLayoutD3D12*)&pipelineLayout); + //Destroy((PipelineLayoutD3D12*)&pipelineLayout); } static void NRI_CALL DestroyPipeline(Pipeline& pipeline) { - Destroy((PipelineD3D12*)&pipeline); + //Destroy((PipelineD3D12*)&pipeline); } static void NRI_CALL DestroyQueryPool(QueryPool& queryPool) { - Destroy((QueryPoolD3D12*)&queryPool); + //Destroy((QueryPoolD3D12*)&queryPool); } static void NRI_CALL DestroyFence(Fence& fence) { - Destroy((FenceD3D12*)&fence); + //Destroy((FenceD3D12*)&fence); } static Result NRI_CALL AllocateMemory(Device& device, const AllocateMemoryDesc& allocateMemoryDesc, Memory*& memory) { - return ((DeviceMTL&)device).CreateImplementation(memory, allocateMemoryDesc); + return Result::SUCCESS; + //return ((DeviceMTL&)device).CreateImplementation(memory, allocateMemoryDesc); } static Result NRI_CALL BindBufferMemory(Device& device, const BufferMemoryBindingDesc* memoryBindingDescs, uint32_t memoryBindingDescNum) { - return ((DeviceMTL&)device).BindBufferMemory(memoryBindingDescs, memoryBindingDescNum); + //return ((DeviceMTL&)device).BindBufferMemory(memoryBindingDescs, memoryBindingDescNum); + return Result::SUCCESS; } static Result NRI_CALL BindTextureMemory(Device& device, const TextureMemoryBindingDesc* memoryBindingDescs, uint32_t memoryBindingDescNum) { - return ((DeviceMTL&)device).BindTextureMemory(memoryBindingDescs, memoryBindingDescNum); + //return ((DeviceMTL&)device).BindTextureMemory(memoryBindingDescs, memoryBindingDescNum); + return Result::SUCCESS; } static void NRI_CALL FreeMemory(Memory& memory) { - Destroy((MemoryD3D12*)&memory); +// Destroy((MemoryD3D12*)&memory); } static void NRI_CALL SetDeviceDebugName(Device& device, const char* name) { - ((DeviceMTL&)device).SetDebugName(name); +// ((DeviceMTL&)device).SetDebugName(name); } static void NRI_CALL SetPipelineDebugName(Pipeline& pipeline, const char* name) { - ((PipelineD3D12&)pipeline).SetDebugName(name); +// ((PipelineD3D12&)pipeline).SetDebugName(name); } static void NRI_CALL SetPipelineLayoutDebugName(PipelineLayout& pipelineLayout, const char* name) { - ((PipelineLayoutD3D12&)pipelineLayout).SetDebugName(name); +// ((PipelineLayoutD3D12&)pipelineLayout).SetDebugName(name); } static void NRI_CALL SetMemoryDebugName(Memory& memory, const char* name) { - ((MemoryMetal&)memory).SetDebugName(name); +// ((MemoryMetal&)memory).SetDebugName(name); } static void* NRI_CALL GetDeviceNativeObject(const Device& device) { if (!(&device)) return nullptr; + return (MTLDevice*)((DeviceMTL&)device); - return ((DeviceMetal&)device).GetNativeObject(); + //return ((DeviceMetal&)device).GetNativeObject(); } Result DeviceMetal::FillFunctionTable(CoreInterface& table) const { diff --git a/Source/Metal/DeviceMTL.mm b/Source/Metal/DeviceMTL.mm index dc20091..b6543c4 100644 --- a/Source/Metal/DeviceMTL.mm +++ b/Source/Metal/DeviceMTL.mm @@ -1,12 +1,55 @@ -#include "DeviceMetal.h" +#include "SharedMTL.h" + +#include "DeviceMTL.h" using namespace nri; +static bool FindMTLGpuFamily(id device, + MTLGPUFamily *family) { + // https://developer.apple.com/documentation/metal/mtldevice/detecting_gpu_features_and_metal_software_versions?language=objc + if (@available(macOS 10.15, iOS 10.13, *)) { + if ([device supportsFamily:MTLGPUFamilyApple7]) { + (*family) = MTLGPUFamily::MTLGPUFamilyApple7; + return true; + } + if ([device supportsFamily:MTLGPUFamilyApple6]) { + (*family) = MTLGPUFamily::MTLGPUFamilyApple6; + return true; + } + if ([device supportsFamily:MTLGPUFamilyApple5]) { + (*family) = MTLGPUFamily::MTLGPUFamilyApple5; + return true; + } + if ([device supportsFamily:MTLGPUFamilyApple4]) { + (*family) = MTLGPUFamily::MTLGPUFamilyApple4; + return true; + } + if ([device supportsFamily:MTLGPUFamilyApple3]) { + (*family) = MTLGPUFamily::MTLGPUFamilyApple3; + return true; + } + if ([device supportsFamily:MTLGPUFamilyApple2]) { + (*family) = MTLGPUFamily::MTLGPUFamilyApple2; + return true; + } + if ([device supportsFamily:MTLGPUFamilyApple1]) { + (*family) = MTLGPUFamily::MTLGPUFamilyApple1; + return true; + } + + // This family is no longer supported in the macOS 10.15 SDK but still + // exists so default to it. + // return MTLGPUFamily::Mac1; + (*family) = MTLGPUFamily::MTLGPUFamilyMac1; + return true; + } + return false; +} + -static inline bool FindMTLGpuFamily(id device, MTLGPUFamily *family); -BufferMetal::BufferMetal(const CallbackInterface& callbacks, const StdAllocator& stdAllocator) +DeviceMTL::DeviceMTL(const CallbackInterface& callbacks, const StdAllocator& stdAllocator) : DeviceBase(callbacks, stdAllocator) { m_Desc.graphicsAPI = GraphicsAPI::VK; m_Desc.nriVersionMajor = NRI_VERSION_MAJOR; @@ -14,50 +57,42 @@ } -BufferMetal::~BufferMetal() { - -} +DeviceMTL::~DeviceMTL() { -Result CreateDeviceMTL(const DeviceCreationDesc& deviceCreationDesc, DeviceBase*& device) { - } -Result CreateDeviceMTL(const DeviceCreationMTLDesc& deviceCreationDesc, DeviceBase*& device) { - -} - -FormatSupportBits DeviceMTL::GetFormatSupport(const Device& device, Format format) { - int currentFamily = HIGHEST_GPU_FAMILY; - for (; currentFamily >= (int)MTLGPUFamilyApple1; currentFamily--) { - if ([m_device supportsFamily:(MTLGPUFamily)currentFamily]) { - highestAppleFamily = (MTLGPUFamily)currentFamily; - break; - } - } -} +//FormatSupportBits DeviceMTL::GetFormatSupport(const Device& device, Format format) { +// int currentFamily = HIGHEST_GPU_FAMILY; +// for (; currentFamily >= (int)MTLGPUFamilyApple1; currentFamily--) { +// if ([m_Device supportsFamily:(MTLGPUFamily)currentFamily]) { +// highestAppleFamily = (MTLGPUFamily)currentFamily; +// break; +// } +// } +//} Result DeviceMTL::GetCommandQueue(CommandQueueType commandQueueType, CommandQueue*& commandQueue) { return Result::SUCCESS; } -void DeviceMTL::FillCreateInfo(const TextureDesc& textureDesc, MTLTextureDescriptor* info) const { - info.textureType = ::GetImageTypeMTL(textureDesc.type); - into.pixelFormat = ::GetFormatMTL(textureDesc.format, true); - into.width = pDesc->mWidth; - into.height = pDesc->mHeight; - into.depth = pDesc->mDepth; - into.mipmapLevelCount = mipLevels; - into.sampleCount = pDesc->mSampleCount; - into.arrayLength = pDesc->mArraySize; -} +//void DeviceMTL::FillCreateInfo(const TextureDesc& textureDesc, MTLTextureDescriptor* info) const { +// info.textureType = ::GetImageTypeMTL(textureDesc.type); +// //info.pixelFormat = ::GetFormatMTL(textureDesc.format, true); +// //info.width = pDesc->mWidth; +// //info.height = pDesc->mHeight; +// //info.depth = pDesc->mDepth; +// //info.mipmapLevelCount = mipLevels; +// //info.sampleCount = pDesc->mSampleCount; +// //info.arrayLength = pDesc->mArraySize; +//} Result DeviceMTL::Create(const DeviceCreationDesc& deviceCreationDesc, const DeviceCreationMTLDesc& deviceCreationMTLDesc, bool isWrapper) { m_OwnsNativeObjects = !isWrapper; if(isWrapper) { - m_Device = deviceCreationMTLDesc.MtlDevice; + // m_Device = deviceCreationMTLDesc.MtlDevice; } strncpy(m_Desc.adapterDesc.name, [m_Device.name UTF8String], sizeof(m_Desc.adapterDesc.name)); @@ -69,28 +104,28 @@ Result CreateDeviceMTL(const DeviceCreationMTLDesc& deviceCreationDesc, DeviceBa const uint64_t regID = [m_Device registryID]; if (regID) { - IORef entry =AcquireIORef(IOServiceGetMatchingService(kIOMasterPortDefault, IORegistryEntryIDMatching(regID))); - if (entry) - { + // IORef entry =AcquireIORef(IOServiceGetMatchingService(kIOMasterPortDefault, IORegistryEntryIDMatching(regID))); + // if (entry) + // { // That returned the IOGraphicsAccelerator nub. Its parent, then, is the actual PCI device. - IORef deviceEntry; - if (IORegistryEntryGetParentEntry(entry, kIOServicePlane, &deviceEntry) == kIOReturnSuccess) - { - m_Desc.adapterDesc.vendor = GetVendorFromID(GetEntryProperty(deviceEntry, CFSTR("vendor-id"))); - m_Desc.adapterDesc.deviceId = GetEntryProperty(deviceEntry, CFSTR("device-id")); - } - } + // IORef deviceEntry; + // if (IORegistryEntryGetParentEntry(entry, kIOServicePlane, &deviceEntry) == kIOReturnSuccess) + // { + // m_Desc.adapterDesc.vendor = GetVendorFromID(GetEntryProperty(deviceEntry, CFSTR("vendor-id"))); + // m_Desc.adapterDesc.deviceId = GetEntryProperty(deviceEntry, CFSTR("device-id")); + // } + // } } MTLGPUFamily family; - if(!FindMTLGpuFamily(m_Device, family)) { - return Result::UNSUPPORTED; - } + // if(!FindMTLGpuFamily(m_Device, family)) { + // return Result::UNSUPPORTED; + //} // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf //TODO: fill desc switch(family) { - case MTLGPUFamily::Apple1: - break; + // case MTLGPUFamily::Apple1: + // break; default: break; } @@ -102,46 +137,3 @@ Result CreateDeviceMTL(const DeviceCreationMTLDesc& deviceCreationDesc, DeviceBa } - -static inline bool FindMTLGpuFamily(id device, - MTLGPUFamily *family) { - // https://developer.apple.com/documentation/metal/mtldevice/detecting_gpu_features_and_metal_software_versions?language=objc - if (@available(macOS 10.15, iOS 10.13, *)) { - if ([device supportsFamily:MTLGPUFamilyApple7]) { - (*family) = MTLGPUFamily::Apple7; - return true; - } - if ([device supportsFamily:MTLGPUFamilyApple6]) { - (*family) = MTLGPUFamily::Apple6; - return true; - } - if ([device supportsFamily:MTLGPUFamilyApple5]) { - (*family) = MTLGPUFamily::Apple5; - return true; - } - if ([device supportsFamily:MTLGPUFamilyApple4]) { - (*family) = MTLGPUFamily::Apple4; - return true; - } - if ([device supportsFamily:MTLGPUFamilyApple3]) { - (*family) = MTLGPUFamily::Apple3; - return true; - } - if ([device supportsFamily:MTLGPUFamilyApple2]) { - (*family) = MTLGPUFamily::Apple2; - return true; - } - if ([device supportsFamily:MTLGPUFamilyApple1]) { - (*family) = MTLGPUFamily::Apple1; - return true; - } - - // This family is no longer supported in the macOS 10.15 SDK but still - // exists so default to it. - // return MTLGPUFamily::Mac1; - (*family) = MTLGPUFamily::Mac1; - return true; - } - return false; -} - diff --git a/Source/Metal/FencMTL.mm b/Source/Metal/FencMTL.mm index f009671..d0ee5d5 100644 --- a/Source/Metal/FencMTL.mm +++ b/Source/Metal/FencMTL.mm @@ -1,3 +1,5 @@ +#include "SharedMTL.h" + #include "FenceMTL.h" using namespace nri; diff --git a/Source/Metal/FenceMTL.h b/Source/Metal/FenceMTL.h index 3aa3c29..0531e63 100644 --- a/Source/Metal/FenceMTL.h +++ b/Source/Metal/FenceMTL.h @@ -1,6 +1,9 @@ // © 2021 NVIDIA Corporation + #pragma once +#import + namespace nri { struct DeviceMTL; diff --git a/Source/Metal/MemoryMTL.h b/Source/Metal/MemoryMTL.h index 72caa7a..9ab89d5 100644 --- a/Source/Metal/MemoryMTL.h +++ b/Source/Metal/MemoryMTL.h @@ -4,6 +4,8 @@ #include +#import + namespace nri { struct DeviceMTL; diff --git a/Source/Metal/MemoryMTL.mm b/Source/Metal/MemoryMTL.mm index 528facd..b94511c 100644 --- a/Source/Metal/MemoryMTL.mm +++ b/Source/Metal/MemoryMTL.mm @@ -1,4 +1,5 @@ // © 2021 NVIDIA Corporation +#include "SharedMTL.h" #include "MemoryMTL.h" @@ -12,20 +13,20 @@ } Result MemoryMTL::Create(const MemoryMTLDesc& memoryDesc) { - if (!memoryDesc.vkDeviceMemory) - return Result::INVALID_ARGUMENT; + // if (!memoryDesc.vkDeviceMemory) + // return Result::INVALID_ARGUMENT; - MemoryTypeInfo memoryTypeInfo = {}; + // MemoryTypeInfo memoryTypeInfo = {}; //bool found = m_Device.GetMemoryTypeByIndex(memoryDesc.memoryTypeIndex, memoryTypeInfo); //RETURN_ON_FAILURE(&m_Device, found, Result::INVALID_ARGUMENT, "Can't find memory by index"); m_OwnsNativeObjects = false; - m_Buffer = memoryDesc.buffer; + // m_Buffer = memoryDesc.buffer; m_MappedMemory = (uint8_t*)memoryDesc.mappedMemory; - m_Type = memoryDesc.options; + // m_Type = memoryDesc.options; - const auto& mtl = m_Device.GetDispatchTable(); + // const auto& mtl = m_Device.GetDispatchTable(); //if (!m_MappedMemory && IsHostVisibleMemory(memoryTypeInfo.location)) { // VkResult result = mtl.MapMemory(m_Device, m_Handle, 0, memoryDesc.size, 0, (void**)&m_MappedMemory); // RETURN_ON_FAILURE(&m_Device, result == VK_SUCCESS, GetReturnCode(result), "vkMapMemory returned %d", (int32_t)result); diff --git a/Source/Metal/PipelineLayoutMTL.h b/Source/Metal/PipelineLayoutMTL.h index 464c31c..e3c2a2b 100644 --- a/Source/Metal/PipelineLayoutMTL.h +++ b/Source/Metal/PipelineLayoutMTL.h @@ -1,5 +1,7 @@ #pragma once +#import + namespace nri { struct DeviceMTL; @@ -30,7 +32,7 @@ struct PipelineLayoutMTL { // } // // inline uint32_t GetDescriptorSetSpace(uint32_t setIndexInPipelineLayout) const { -// return m_DescriptorSetSpaces[setIndexInPipelineLayout]; + // } // ~PipelineLayoutMTL(); @@ -46,7 +48,6 @@ struct PipelineLayoutMTL { private: DeviceMTL& m_Device; - id m_PipelineDesc; //Vector m_DescriptorSetLayouts; }; diff --git a/Source/Metal/PipelineLayoutMTL.mm b/Source/Metal/PipelineLayoutMTL.mm index e69de29..7760b5f 100644 --- a/Source/Metal/PipelineLayoutMTL.mm +++ b/Source/Metal/PipelineLayoutMTL.mm @@ -0,0 +1,11 @@ +#include "SharedMTL.h" + +#include "PipelineLayoutMTL.h" + +using namespace nri; + +PipelineLayoutMTL::~PipelineLayoutMTL() { + +} + + diff --git a/Source/Metal/PipelineMTL.h b/Source/Metal/PipelineMTL.h index 61b4344..ccb7e15 100644 --- a/Source/Metal/PipelineMTL.h +++ b/Source/Metal/PipelineMTL.h @@ -1,5 +1,7 @@ #pragma once +#import + namespace nri { struct DeviceMTL; diff --git a/Source/Metal/PipelineMTL.mm b/Source/Metal/PipelineMTL.mm index 53493ac..3603b52 100644 --- a/Source/Metal/PipelineMTL.mm +++ b/Source/Metal/PipelineMTL.mm @@ -1,5 +1,8 @@ +#include "SharedMTL.h" + #include "PipelineMTL.h" -#import + +using namespace nri; PipelineMTL::~PipelineMTL() { @@ -12,12 +15,12 @@ const VertexInputDesc *vi = graphicsPipelineDesc.vertexInput; if (vi) { - VkVertexInputBindingDescription* streams const_cast(vertexInputState.pVertexBindingDescriptions); - for (uint32_t i = 0; i < vi->streamNum; i++) { - const VertexStreamDesc &stream = vi->streams[i]; - renderPipelineDesc.vertexDescriptor.layouts[attribute_desc.streamIndex].stride = stream.stride; - renderPipelineDesc.vertexDescriptor.layouts[attribute_desc.streamIndex].stepRate = 1; - } + // VkVertexInputBindingDescription* streams const_cast(vertexInputState.pVertexBindingDescriptions); + //for (uint32_t i = 0; i < vi->streamNum; i++) { + // const VertexStreamDesc &stream = vi->streams[i]; + // renderPipelineDesc.vertexDescriptor.layouts[attribute_desc.streamIndex].stride = stream.stride; + // renderPipelineDesc.vertexDescriptor.layouts[attribute_desc.streamIndex].stepRate = 1; + // } } const InputAssemblyDesc& ia = graphicsPipelineDesc.inputAssembly; @@ -34,21 +37,21 @@ // assign render target pixel format for all attachments for (uint32_t i = 0; i < om.colorNum; i++) { - MTLRenderPipelineColorAttachmentDescriptor& colorAtachment = &renderPipelineDesc.colorAttachments[i]; + // MTLRenderPipelineColorAttachmentDescriptor& colorAtachment = &renderPipelineDesc.colorAttachments[i]; const ColorAttachmentDesc& attachmentDesc = om.color[i]; - colorAtachment.pixelFormat = GetFormatMTL(attachmentDesc.format, false); + //colorAtachment.pixelFormat = GetFormatMTL(attachmentDesc.format, false); - colorAtachment.blendingEnabled = attachmentDesc.blendEnabled; - colorAtachment.rgbBlendOperation = GetBlendOp(attachmentDesc.colorBlend.func); - colorAtachment.alphaBlendOperation = GetBlendOp(attachmentDesc.alphaBlend.func); + //colorAtachment.blendingEnabled = attachmentDesc.blendEnabled; + //colorAtachment.rgbBlendOperation = GetBlendOp(attachmentDesc.colorBlend.func); + //colorAtachment.alphaBlendOperation = GetBlendOp(attachmentDesc.alphaBlend.func); - colorAtachment.sourceRGBBlendFactor = GetBlendFactor(attachmentDesc.colorBlend.srcFactor); - colorAtachment.destinationRGBBlendFactor = GetBlendFactor(attachmentDesc.colorBlend.dstFactor); - colorAtachment.sourceAlphaBlendFactor = GetBlendFactor(attachmentDesc.alphaBlend.srcFactor); - colorAtachment.destinationAlphaBlendFactor = GetBlendFactor(attachmentDesc.alphaBlend.dstFactor); + //colorAtachment.sourceRGBBlendFactor = GetBlendFactor(attachmentDesc.colorBlend.srcFactor); + //colorAtachment.destinationRGBBlendFactor = GetBlendFactor(attachmentDesc.colorBlend.dstFactor); + //colorAtachment.sourceAlphaBlendFactor = GetBlendFactor(attachmentDesc.alphaBlend.srcFactor); + //colorAtachment.destinationAlphaBlendFactor = GetBlendFactor(attachmentDesc.alphaBlend.dstFactor); - colorAtachment.writeMask = GetColorComponent(pDesc->mColorWriteMasks[blendDescIndex]); + //colorAtachment.writeMask = GetColorComponent(pDesc->mColorWriteMasks[blendDescIndex]); } diff --git a/Source/Metal/SharedMTL.h b/Source/Metal/SharedMTL.h new file mode 100644 index 0000000..58262f0 --- /dev/null +++ b/Source/Metal/SharedMTL.h @@ -0,0 +1,8 @@ +#import + +#include "SharedExternal.h" + +#include "ConversionMTL.h" +#include "DeviceMTL.h" + + diff --git a/Source/Metal/TextureMTL.h b/Source/Metal/TextureMTL.h index d10e989..296b804 100644 --- a/Source/Metal/TextureMTL.h +++ b/Source/Metal/TextureMTL.h @@ -1,10 +1,11 @@ // © 2021 NVIDIA Corporation - #pragma once +#import + namespace nri { -struct DeviceMTL; +struct DeviceMTL; struct TextureMTL { @@ -13,9 +14,9 @@ struct TextureMTL { } ~TextureMTL(); - inline id& GetHandle() const { - return m_Handle; - } + //inline id GetHandle() const { + // return m_Handle; + //} inline DeviceMTL& GetDevice() const { return m_Device; @@ -26,7 +27,7 @@ struct TextureMTL { } Result Create(const TextureDesc& textureDesc); - Result Create(const TextureMTLDesc& textureDesc); + //Result Create(const TextureMTLDesc& textureDesc); private: DeviceMTL& m_Device; @@ -34,4 +35,4 @@ struct TextureMTL { id m_Handle; }; -} // namespace nri \ No newline at end of file +} // namespace nri diff --git a/Source/Metal/TextureMTL.mm b/Source/Metal/TextureMTL.mm index 876cc2d..edbb8d9 100644 --- a/Source/Metal/TextureMTL.mm +++ b/Source/Metal/TextureMTL.mm @@ -1,24 +1,31 @@ +#include "SharedMTL.h" + #include "TextureMTL.h" +using namespace nri; + TextureMTL::~TextureMTL() { m_Handle = nil; } -Result Create(const TextureMTLDesc& textureDesc) { - m_Handle = texturedesc.texture; - return Result::SUCCESS; -} - -Result Create(const TextureMTLDesc& textureDesc) { - return Result::SUCCESS; -} +//Result TextureMTL::Create(const TextureMTLDesc& textureDesc) { +// m_Handle = texturedesc.texture; +// return Result::SUCCESS; +//} -Result Create(const TextureDesc& textureDesc) { +Result TextureMTL::Create(const TextureDesc& textureDesc) { MTLTextureDescriptor* info = [[MTLTextureDescriptor alloc] init]; - m_Device.FillCreateInfo(textureDesc, info); - - m_Handle = [m_Device newTextureWithDescriptor:textureDesc]; + info.textureType = ::GetImageTypeMTL(textureDesc.type); + info.pixelFormat = ::GetFormatMTL(textureDesc.format, true); + info.width = textureDesc.width; + info.height = textureDesc.height; + info.depth = textureDesc.depth; + info.mipmapLevelCount = textureDesc.mipNum; + // info.sampleCount = textureDesc->mSampleCount; + // info.arrayLength = textureDesc->mArraySize; + + //m_Handle = [m_Device newTextureWithDescriptor:textureDesc]; return Result::SUCCESS; } diff --git a/Source/Shared/SharedExternal.h b/Source/Shared/SharedExternal.h index 1709991..48eecd8 100644 --- a/Source/Shared/SharedExternal.h +++ b/Source/Shared/SharedExternal.h @@ -1,4 +1,4 @@ -// © 2021 NVIDIA Corporation +// © 2021 NVIDIA Corporation #pragma once @@ -29,6 +29,7 @@ typedef uint32_t DXGI_FORMAT; #include "Extensions/NRIWrapperD3D11.h" #include "Extensions/NRIWrapperD3D12.h" #include "Extensions/NRIWrapperVK.h" +#include "Extensions/NRIWrapperMTL.h" #include "NRICompatibility.hlsli" @@ -175,8 +176,6 @@ inline nri::Vendor GetVendorFromID(uint32_t vendorID) { return nri::Vendor::AMD; case 0x8086: return nri::Vendor::INTEL; - case 0x106b: - return nri::Vendor::APPLE; } return nri::Vendor::UNKNOWN; From 7e4536112a5f1fba9a1e16c05437daf40234795f Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Sun, 1 Sep 2024 21:30:31 -0700 Subject: [PATCH 09/24] feat: add graphics queu Signed-off-by: Michael Pollind --- Source/Metal/CommandQueueMTL.h | 7 +-- Source/Metal/CommandQueueMTL.mm | 13 ++++-- Source/Metal/DeviceMTL.h | 19 +++++++-- Source/Metal/DeviceMTL.hpp | 19 ++++++++- Source/Metal/DeviceMTL.mm | 75 +++++++++++++++++++++++---------- Source/Metal/TextureMTL.h | 2 +- Source/Metal/TextureMTL.mm | 9 ++-- 7 files changed, 103 insertions(+), 41 deletions(-) diff --git a/Source/Metal/CommandQueueMTL.h b/Source/Metal/CommandQueueMTL.h index e983c5e..7d48be9 100644 --- a/Source/Metal/CommandQueueMTL.h +++ b/Source/Metal/CommandQueueMTL.h @@ -22,10 +22,6 @@ struct CommandQueueMTL { inline DeviceMTL& GetDevice() const { return m_Device; } - - inline uint32_t GetFamilyIndex() const { - return m_FamilyIndex; - } inline CommandQueueType GetType() const { return m_Type; @@ -38,10 +34,9 @@ struct CommandQueueMTL { Result WaitForIdle(); void SetDebugName(const char* name); - Result Create(CommandQueueType type, uint32_t familyIndex, id handle); + Result Create(CommandQueueType type); private: DeviceMTL& m_Device; - uint32_t m_FamilyIndex = 0; CommandQueueType m_Type = CommandQueueType(-1); id m_Handle; Lock m_Lock; diff --git a/Source/Metal/CommandQueueMTL.mm b/Source/Metal/CommandQueueMTL.mm index dde2fbc..1eb6305 100644 --- a/Source/Metal/CommandQueueMTL.mm +++ b/Source/Metal/CommandQueueMTL.mm @@ -10,10 +10,17 @@ m_Handle = nil; } -Result CommandQueueMTL::Create(CommandQueueType type, uint32_t familyIndex, id handle) { +Result CommandQueueMTL::Create(CommandQueueType type) { m_Type = type; - m_FamilyIndex = familyIndex; - m_Handle = handle; + const char* queueNames[] = { + "GRAPHICS_QUEUE", // GRAPHICS + "TRANSFER_QUEUE", // TRANSFER + "COMPUTE_QUEUE" // COMPUTE + }; + + m_Handle = [m_Device newCommandQueueWithMaxCommandBufferCount:512]; + SetDebugName(queueNames[(uint32_t)type]); + return Result::SUCCESS; } diff --git a/Source/Metal/DeviceMTL.h b/Source/Metal/DeviceMTL.h index 3edeb1d..de01369 100644 --- a/Source/Metal/DeviceMTL.h +++ b/Source/Metal/DeviceMTL.h @@ -21,11 +21,23 @@ struct DeviceMTL final : public DeviceBase { return m_Desc; } - //FormatSupportBits GetFormatSupport(const Device& device, Format format); + void Destruct() override; - //void FillCreateInfo(const TextureDesc& bufferDesc, MTLTextureDescriptor* info) const; - // void FillCreateInfo(const TextureDesc& bufferDesc, MTLTextureDescriptor* info) const; + template + inline Result CreateImplementation(Interface*& entity, const Args&... args) { + Implementation* impl = Allocate(GetStdAllocator(), *this); + Result result = impl->Create(args...); + if (result != Result::SUCCESS) { + Destroy(GetStdAllocator(), impl); + entity = nullptr; + } else + entity = (Interface*)impl; + + return result; + } + + Result FillFunctionTable(CoreInterface& table) const; Result FillFunctionTable(HelperInterface& table) const; Result FillFunctionTable(LowLatencyInterface& table) const; @@ -37,6 +49,7 @@ struct DeviceMTL final : public DeviceBase { Result Create(const DeviceCreationDesc& deviceCreationDesc, const DeviceCreationMTLDesc& deviceCreationVKDesc, bool isWrapper); private: + Lock m_Lock; id m_Device; std::array m_CommandQueues = {}; DeviceDesc m_Desc = {}; diff --git a/Source/Metal/DeviceMTL.hpp b/Source/Metal/DeviceMTL.hpp index 43c4359..c05ec9a 100644 --- a/Source/Metal/DeviceMTL.hpp +++ b/Source/Metal/DeviceMTL.hpp @@ -214,24 +214,39 @@ Result DeviceMetal::FillFunctionTable(CoreInterface& table) const { #pragma endregion - Result DeviceMetal::FillFunctionTable(HelperInterface& table) const { - + table = {}; + return ResVult::UNSUPPORTED; } Result DeviceMetal::FillFunctionTable(LowLatencyInterface& table) const { + table = {}; + return ResVult::UNSUPPORTED; } Result DeviceMetal::FillFunctionTable(MeshShaderInterface& table) const { + table = {}; + return ResVult::UNSUPPORTED; } Result DeviceMetal::FillFunctionTable(RayTracingInterface& table) const { + table = {}; + return ResVult::UNSUPPORTED; } + Result DeviceMetal::FillFunctionTable(StreamerInterface& table) const { + table = {}; + return ResVult::UNSUPPORTED; } + Result DeviceMetal::FillFunctionTable(SwapChainInterface& table) const { + table = {}; + return ResVult::UNSUPPORTED; } + Result DeviceMetal::FillFunctionTable(ResourceAllocatorInterface& table) const { + table = {}; + return ResVult::UNSUPPORTED; } Define_Core_Device_PartiallyFillFunctionTable(MTL); diff --git a/Source/Metal/DeviceMTL.mm b/Source/Metal/DeviceMTL.mm index b6543c4..2bdcdba 100644 --- a/Source/Metal/DeviceMTL.mm +++ b/Source/Metal/DeviceMTL.mm @@ -1,5 +1,7 @@ #include "SharedMTL.h" +#include "CommandQueueMTL.h" + #include "DeviceMTL.h" using namespace nri; @@ -48,15 +50,18 @@ static bool FindMTLGpuFamily(id device, - -DeviceMTL::DeviceMTL(const CallbackInterface& callbacks, const StdAllocator& stdAllocator) - : DeviceBase(callbacks, stdAllocator) { +DeviceMTL::DeviceMTL(const CallbackInterface& callbacks, const StdAllocator& stdAllocator) : DeviceBase(callbacks, stdAllocator) { m_Desc.graphicsAPI = GraphicsAPI::VK; m_Desc.nriVersionMajor = NRI_VERSION_MAJOR; m_Desc.nriVersionMinor = NRI_VERSION_MINOR; } + +void DeviceMTL::Destruct() { + Destroy(GetStdAllocator(), this); +} + DeviceMTL::~DeviceMTL() { } @@ -74,7 +79,31 @@ static bool FindMTLGpuFamily(id device, Result DeviceMTL::GetCommandQueue(CommandQueueType commandQueueType, CommandQueue*& commandQueue) { - return Result::SUCCESS; + ExclusiveScope lock(m_Lock); + + // Check if already created (or wrapped) + uint32_t index = (uint32_t)commandQueueType; + if (m_CommandQueues[index]) { + commandQueue = (CommandQueue*)m_CommandQueues[index]; + return Result::SUCCESS; + } + + // Check if supported + //uint32_t queueFamilyIndex = m_QueueFamilyIndices[index]; + //if (queueFamilyIndex == INVALID_FAMILY_INDEX) { + // commandQueue = nullptr; + // return Result::UNSUPPORTED; + //} + + // Create + //VkQueue handle = VK_NULL_HANDLE; + //m_VK.GetDeviceQueue(m_Device, queueFamilyIndex, 0, &handle); + + Result result = CreateImplementation(commandQueue, commandQueueType); + if (result == Result::SUCCESS) + m_CommandQueues[index] = (CommandQueueMTL*)commandQueue; + + return result; } //void DeviceMTL::FillCreateInfo(const TextureDesc& textureDesc, MTLTextureDescriptor* info) const { @@ -90,36 +119,36 @@ static bool FindMTLGpuFamily(id device, Result DeviceMTL::Create(const DeviceCreationDesc& deviceCreationDesc, const DeviceCreationMTLDesc& deviceCreationMTLDesc, bool isWrapper) { m_OwnsNativeObjects = !isWrapper; - + if(isWrapper) { - // m_Device = deviceCreationMTLDesc.MtlDevice; + // m_Device = deviceCreationMTLDesc.MtlDevice; } - + strncpy(m_Desc.adapterDesc.name, [m_Device.name UTF8String], sizeof(m_Desc.adapterDesc.name)); // No vendor id, device id for Apple GPUs if (strstr(m_Desc.adapterDesc.name, "Apple")) { m_Desc.adapterDesc.vendor = nri::Vendor::APPLE; - } - + } + const uint64_t regID = [m_Device registryID]; if (regID) { - // IORef entry =AcquireIORef(IOServiceGetMatchingService(kIOMasterPortDefault, IORegistryEntryIDMatching(regID))); - // if (entry) - // { - // That returned the IOGraphicsAccelerator nub. Its parent, then, is the actual PCI device. - // IORef deviceEntry; - // if (IORegistryEntryGetParentEntry(entry, kIOServicePlane, &deviceEntry) == kIOReturnSuccess) - // { - // m_Desc.adapterDesc.vendor = GetVendorFromID(GetEntryProperty(deviceEntry, CFSTR("vendor-id"))); - // m_Desc.adapterDesc.deviceId = GetEntryProperty(deviceEntry, CFSTR("device-id")); - // } - // } + // IORef entry =AcquireIORef(IOServiceGetMatchingService(kIOMasterPortDefault, IORegistryEntryIDMatching(regID))); + // if (entry) + // { + // That returned the IOGraphicsAccelerator nub. Its parent, then, is the actual PCI device. + // IORef deviceEntry; + // if (IORegistryEntryGetParentEntry(entry, kIOServicePlane, &deviceEntry) == kIOReturnSuccess) + // { + // m_Desc.adapterDesc.vendor = GetVendorFromID(GetEntryProperty(deviceEntry, CFSTR("vendor-id"))); + // m_Desc.adapterDesc.deviceId = GetEntryProperty(deviceEntry, CFSTR("device-id")); + // } + // } } - + MTLGPUFamily family; - // if(!FindMTLGpuFamily(m_Device, family)) { - // return Result::UNSUPPORTED; + // if(!FindMTLGpuFamily(m_Device, family)) { + // return Result::UNSUPPORTED; //} // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf //TODO: fill desc diff --git a/Source/Metal/TextureMTL.h b/Source/Metal/TextureMTL.h index 296b804..f4f5841 100644 --- a/Source/Metal/TextureMTL.h +++ b/Source/Metal/TextureMTL.h @@ -26,7 +26,7 @@ struct TextureMTL { return m_Desc; } - Result Create(const TextureDesc& textureDesc); + Result CreateFromTextureDesc(const TextureDesc& textureDesc); //Result Create(const TextureMTLDesc& textureDesc); private: diff --git a/Source/Metal/TextureMTL.mm b/Source/Metal/TextureMTL.mm index edbb8d9..3d4cf67 100644 --- a/Source/Metal/TextureMTL.mm +++ b/Source/Metal/TextureMTL.mm @@ -14,7 +14,7 @@ // return Result::SUCCESS; //} -Result TextureMTL::Create(const TextureDesc& textureDesc) { +Result TextureMTL::CreateFromTextureDesc(const TextureDesc& textureDesc) { MTLTextureDescriptor* info = [[MTLTextureDescriptor alloc] init]; info.textureType = ::GetImageTypeMTL(textureDesc.type); info.pixelFormat = ::GetFormatMTL(textureDesc.format, true); @@ -22,8 +22,11 @@ info.height = textureDesc.height; info.depth = textureDesc.depth; info.mipmapLevelCount = textureDesc.mipNum; - // info.sampleCount = textureDesc->mSampleCount; - // info.arrayLength = textureDesc->mArraySize; + info.sampleCount = textureDesc.sampleNum; + info.arrayLength = textureDesc.layerNum; + + m_Handle = [m_Device newTextureWithDescriptor:info]; + m_Desc = textureDesc; //m_Handle = [m_Device newTextureWithDescriptor:textureDesc]; return Result::SUCCESS; From 45462cf109da809a52c124e061db22beae219784 Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Tue, 3 Sep 2024 21:36:02 -0700 Subject: [PATCH 10/24] feat: add interface Signed-off-by: Michael Pollind --- Source/Metal/ConversionMTL.h | 16 ++++++++ Source/Metal/DescriptorMTL.h | 0 Source/Metal/DeviceMTL.hpp | 64 ++++++++++++++++--------------- Source/Metal/DeviceMTL.mm | 17 ++++++++ Source/Metal/PipelineLayoutMTL.h | 43 +++++---------------- Source/Metal/PipelineLayoutMTL.mm | 26 +++++++++++++ Source/Metal/PipelineMTL.mm | 28 +++++++------- Source/Metal/QueryMTL.h | 0 Source/Metal/QueryMTL.mm | 0 Source/Metal/SwapChainMTL.h | 23 +++++++++++ Source/Metal/SwapChainMTL.mm | 0 Source/Metal/TextureMTL.h | 4 +- Source/Metal/TextureMTL.mm | 3 +- 13 files changed, 146 insertions(+), 78 deletions(-) create mode 100644 Source/Metal/DescriptorMTL.h create mode 100644 Source/Metal/QueryMTL.h create mode 100644 Source/Metal/QueryMTL.mm create mode 100644 Source/Metal/SwapChainMTL.h create mode 100644 Source/Metal/SwapChainMTL.mm diff --git a/Source/Metal/ConversionMTL.h b/Source/Metal/ConversionMTL.h index d1aa5b5..a0c53d3 100644 --- a/Source/Metal/ConversionMTL.h +++ b/Source/Metal/ConversionMTL.h @@ -55,6 +55,22 @@ constexpr MTLColorWriteMask GetColorComponent(ColorWriteBits colorWriteMask) { return MTLColorWriteMask(colorWriteMask) & MTLColorWriteMaskAll; } +constexpr std::array DESCRIPTOR_TYPES = { + MTLDataTypeSampler, // SAMPLER + MTLDataTypeNone, // CONSTANT_BUFFER + MTLDataTypeTexture, // TEXTURE + MTLDataTypeNone, // STORAGE_TEXTURE + MTLDataTypeStruct, // BUFFER + MTLDataTypeStruct, // STORAGE_BUFFER + MTLDataTypeArray, // STRUCTURED_BUFFER + MTLDataTypeStruct, // STORAGE_STRUCTURED_BUFFER + MTLDataTypePrimitiveAccelerationStructure // ACCELERATION_STRUCTURE +}; + +constexpr MTLDataType GetDescriptorType(DescriptorType type) { + return DESCRIPTOR_TYPES[(size_t)type]; +} + constexpr std::array COMPARE_OP = { MTLCompareFunctionNever, // NONE MTLCompareFunctionAlways, // ALWAYS diff --git a/Source/Metal/DescriptorMTL.h b/Source/Metal/DescriptorMTL.h new file mode 100644 index 0000000..e69de29 diff --git a/Source/Metal/DeviceMTL.hpp b/Source/Metal/DeviceMTL.hpp index c05ec9a..011c3bc 100644 --- a/Source/Metal/DeviceMTL.hpp +++ b/Source/Metal/DeviceMTL.hpp @@ -17,7 +17,8 @@ static const TextureDesc& NRI_CALL GetTextureDesc(const Texture& texture) { } static FormatSupportBits NRI_CALL GetFormatSupport(const Device& device, Format format) { - return ((const DeviceDesc&)device).GetFormatSupport(format); + return (FormatSupportBits)0; + //return ((const DeviceDesc&)device).GetFormatSupport(format); } static void NRI_CALL GetBufferMemoryDesc(const Device& device, const BufferDesc& bufferDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { @@ -45,18 +46,16 @@ static Result NRI_CALL CreateCommandAllocator(const CommandQueue& commandQueue, } static Result NRI_CALL CreateDescriptorPool(Device& device, const DescriptorPoolDesc& descriptorPoolDesc, DescriptorPool*& descriptorPool) { - //return ((DeviceMTL&)device).CreateImplementation(descriptorPool, descriptorPoolDesc); + //return ((DeviceMTL&)device).CreateImplementation(descriptorPool, descriptorPoolDesc); return Result::SUCCESS; } static Result NRI_CALL CreateBuffer(Device& device, const BufferDesc& bufferDesc, Buffer*& buffer) { - //return ((DeviceMTL&)device).CreateImplementation(buffer, bufferDesc); - return Result::SUCCESS; + return ((DeviceMTL&)device).CreateImplementation(buffer, bufferDesc); } static Result NRI_CALL CreateTexture(Device& device, const TextureDesc& textureDesc, Texture*& texture) { - //return ((DeviceMTL&)device).CreateImplementation(texture, textureDesc); - return Result::SUCCESS; + return ((DeviceMTL&)device).CreateImplementation(texture, textureDesc); } static Result NRI_CALL CreateBufferView(const BufferViewDesc& bufferViewDesc, Descriptor*& bufferView) { @@ -65,7 +64,12 @@ static Result NRI_CALL CreateBufferView(const BufferViewDesc& bufferViewDesc, De return Result::SUCCESS; } + static Result NRI_CALL CreateTexture1DView(const Texture1DViewDesc& textureViewDesc, Descriptor*& textureView) { + //DeviceMTL& device = ((const TextureMTL*)textureViewDesc.texture)->GetDevice(); + //return device.CreateImplementation(textureView, textureViewDesc); + + //DeviceMTL& device = ((const TextureD3D12*)textureViewDesc.texture)->GetDevice(); //return device.CreateImplementation(textureView, textureViewDesc); return Result::SUCCESS; @@ -150,7 +154,7 @@ static void NRI_CALL DestroyQueryPool(QueryPool& queryPool) { } static void NRI_CALL DestroyFence(Fence& fence) { - //Destroy((FenceD3D12*)&fence); + Destroy((FenceMTL*)&fence); } static Result NRI_CALL AllocateMemory(Device& device, const AllocateMemoryDesc& allocateMemoryDesc, Memory*& memory) { @@ -191,12 +195,12 @@ static void NRI_CALL SetMemoryDebugName(Memory& memory, const char* name) { static void* NRI_CALL GetDeviceNativeObject(const Device& device) { if (!(&device)) return nullptr; - return (MTLDevice*)((DeviceMTL&)device); + return (DeviceMTL*)&((DeviceMTL&)device); //return ((DeviceMetal&)device).GetNativeObject(); } -Result DeviceMetal::FillFunctionTable(CoreInterface& table) const { +Result DeviceMTL::FillFunctionTable(CoreInterface& table) const { table = {}; Core_Device_PartiallyFillFunctionTableMTL(table); Core_Buffer_PartiallyFillFunctionTableMTL(table); @@ -214,44 +218,44 @@ Result DeviceMetal::FillFunctionTable(CoreInterface& table) const { #pragma endregion -Result DeviceMetal::FillFunctionTable(HelperInterface& table) const { +Result DeviceMTL::FillFunctionTable(HelperInterface& table) const { table = {}; - return ResVult::UNSUPPORTED; + return Result::UNSUPPORTED; } -Result DeviceMetal::FillFunctionTable(LowLatencyInterface& table) const { +Result DeviceMTL::FillFunctionTable(LowLatencyInterface& table) const { table = {}; - return ResVult::UNSUPPORTED; + return Result::UNSUPPORTED; } -Result DeviceMetal::FillFunctionTable(MeshShaderInterface& table) const { - table = {}; - return ResVult::UNSUPPORTED; -} +//Result DeviceMTL::FillFunctionTable(MeshShaderInterface& table) const { +// table = {}; +// return Result::UNSUPPORTED; +//} -Result DeviceMetal::FillFunctionTable(RayTracingInterface& table) const { +Result DeviceMTL::FillFunctionTable(RayTracingInterface& table) const { table = {}; - return ResVult::UNSUPPORTED; + return Result::UNSUPPORTED; } -Result DeviceMetal::FillFunctionTable(StreamerInterface& table) const { +Result DeviceMTL::FillFunctionTable(StreamerInterface& table) const { table = {}; - return ResVult::UNSUPPORTED; + return Result::UNSUPPORTED; } -Result DeviceMetal::FillFunctionTable(SwapChainInterface& table) const { +Result DeviceMTL::FillFunctionTable(SwapChainInterface& table) const { table = {}; - return ResVult::UNSUPPORTED; + return Result::UNSUPPORTED; } -Result DeviceMetal::FillFunctionTable(ResourceAllocatorInterface& table) const { +Result DeviceMTL::FillFunctionTable(ResourceAllocatorInterface& table) const { table = {}; - return ResVult::UNSUPPORTED; + return Result::UNSUPPORTED; } Define_Core_Device_PartiallyFillFunctionTable(MTL); -Define_Helper_Device_PartiallyFillFunctionTable(MTL); -Define_RayTracing_Device_PartiallyFillFunctionTable(MTL); -Define_Streamer_Device_PartiallyFillFunctionTable(MTL); -Define_SwapChain_Device_PartiallyFillFunctionTable(MTL); -Define_ResourceAllocator_Device_PartiallyFillFunctionTable(MTL); +//Define_Helper_Device_PartiallyFillFunctionTable(MTL); +//Define_RayTracing_Device_PartiallyFillFunctionTable(MTL); +//Define_Streamer_Device_PartiallyFillFunctionTable(MTL); +//Define_SwapChain_Device_PartiallyFillFunctionTable(MTL); +//Define_ResourceAllocator_Device_PartiallyFillFunctionTable(MTL); diff --git a/Source/Metal/DeviceMTL.mm b/Source/Metal/DeviceMTL.mm index 2bdcdba..b2960f5 100644 --- a/Source/Metal/DeviceMTL.mm +++ b/Source/Metal/DeviceMTL.mm @@ -4,6 +4,20 @@ #include "DeviceMTL.h" +//#include "AccelerationStructureVK.h" +#include "BufferMTL.h" +//#include "CommandAllocatorVK.h" +//#include "CommandBufferMTL.h" +#include "CommandQueueMTL.h" +//#include "DescriptorPoolMTL.h" +#include "DescriptorSetMTL.h" +#include "TextureMTL.h" +#include "FenceMTL.h" +#include "MemoryMTL.h" +#include "PipelineLayoutMTL.h" +#include "PipelineMTL.h" + + using namespace nri; static bool FindMTLGpuFamily(id device, @@ -130,6 +144,7 @@ static bool FindMTLGpuFamily(id device, m_Desc.adapterDesc.vendor = nri::Vendor::APPLE; } + const uint64_t regID = [m_Device registryID]; if (regID) { @@ -166,3 +181,5 @@ static bool FindMTLGpuFamily(id device, } +#include "DeviceMTL.hpp" + diff --git a/Source/Metal/PipelineLayoutMTL.h b/Source/Metal/PipelineLayoutMTL.h index e3c2a2b..3a575b8 100644 --- a/Source/Metal/PipelineLayoutMTL.h +++ b/Source/Metal/PipelineLayoutMTL.h @@ -11,45 +11,22 @@ struct PipelineLayoutMTL { : m_Device(device) { } -// inline operator VkPipelineLayout() const { -// return m_Handle; -// } -// -// inline DeviceVK& GetDevice() const { -// return m_Device; -// } -// -// inline const RuntimeBindingInfo& GetRuntimeBindingInfo() const { -// return m_RuntimeBindingInfo; -// } -// -// inline VkDescriptorSetLayout GetDescriptorSetLayout(uint32_t index) const { -// return m_DescriptorSetLayouts[index]; -// } -// -// inline VkPipelineBindPoint GetPipelineBindPoint() const { -// return m_PipelineBindPoint; -// } -// -// inline uint32_t GetDescriptorSetSpace(uint32_t setIndexInPipelineLayout) const { - -// } -// ~PipelineLayoutMTL(); // -// Result Create(const PipelineLayoutDesc& pipelineLayoutDesc); -// -// //================================================================================================================ -// // NRI -// //================================================================================================================ -// -// void SetDebugName(const char* name); + inline Result Create(const PipelineLayoutDesc& pipelineLayoutDesc) { + return CreateDesc(pipelineLayoutDesc); + } + + struct PipelineDescriptorSet { + NSMutableArray* m_ArgumentDescriptors; + }; private: + Result CreateDesc(const PipelineLayoutDesc& pipelineLayoutDesc); DeviceMTL& m_Device; - //Vector m_DescriptorSetLayouts; - + + std::vector m_DescriptorSets; }; } diff --git a/Source/Metal/PipelineLayoutMTL.mm b/Source/Metal/PipelineLayoutMTL.mm index 7760b5f..7a50767 100644 --- a/Source/Metal/PipelineLayoutMTL.mm +++ b/Source/Metal/PipelineLayoutMTL.mm @@ -8,4 +8,30 @@ } +Result PipelineLayoutMTL::CreateDesc(const PipelineLayoutDesc& pipelineLayoutDesc) { + m_DescriptorSets.resize(pipelineLayoutDesc.descriptorSetNum); + for (uint32_t i = 0; i < pipelineLayoutDesc.descriptorSetNum; i++) { + const DescriptorSetDesc& descriptorSetDesc = pipelineLayoutDesc.descriptorSets[i]; + + NSMutableArray* argumentDescriptors = [[NSMutableArray alloc] init]; + MTLArgumentDescriptor* argDescriptor = [MTLArgumentDescriptor argumentDescriptor]; + + for(size_t r = 0; r < descriptorSetDesc.rangeNum; r++) { + + } + + + //argDescriptor.access = memberDescriptor.mAccessType; + //argDescriptor.arrayLength = memberDescriptor.mArrayLength; + //argDescriptor.constantBlockAlignment = memberDescriptor.mAlignment; + //argDescriptor.dataType = memberDescriptor.mDataType; + //argDescriptor.index = memberDescriptor.mArgumentIndex; + //argDescriptor.textureType = memberDescriptor.mTextureType; + + [argumentDescriptors addObject:argDescriptor]; + m_DescriptorSets[i].m_ArgumentDescriptors = argumentDescriptors; + + } + return Result::SUCCESS; +} diff --git a/Source/Metal/PipelineMTL.mm b/Source/Metal/PipelineMTL.mm index 3603b52..39b574c 100644 --- a/Source/Metal/PipelineMTL.mm +++ b/Source/Metal/PipelineMTL.mm @@ -12,9 +12,14 @@ MTLRenderPipelineDescriptor *renderPipelineDesc = [[MTLRenderPipelineDescriptor alloc] init]; for (uint32_t i = 0; i < graphicsPipelineDesc.shaderNum; i++) { } + // Depth-stencil + const DepthAttachmentDesc& da = graphicsPipelineDesc.outputMerger.depth; + const StencilAttachmentDesc& sa = graphicsPipelineDesc.outputMerger.stencil; + const PipelineLayout *pl = graphicsPipelineDesc.pipelineLayout; const VertexInputDesc *vi = graphicsPipelineDesc.vertexInput; if (vi) { + // VkVertexInputBindingDescription* streams const_cast(vertexInputState.pVertexBindingDescriptions); //for (uint32_t i = 0; i < vi->streamNum; i++) { // const VertexStreamDesc &stream = vi->streams[i]; @@ -30,28 +35,25 @@ // TODO: multisampling } - // Blending - const OutputMergerDesc& om = graphicsPipelineDesc.outputMerger; // assign render target pixel format for all attachments + const OutputMergerDesc& om = graphicsPipelineDesc.outputMerger; for (uint32_t i = 0; i < om.colorNum; i++) { - // MTLRenderPipelineColorAttachmentDescriptor& colorAtachment = &renderPipelineDesc.colorAttachments[i]; const ColorAttachmentDesc& attachmentDesc = om.color[i]; - - //colorAtachment.pixelFormat = GetFormatMTL(attachmentDesc.format, false); + renderPipelineDesc.colorAttachments[i].pixelFormat = GetFormatMTL(attachmentDesc.format, false); - //colorAtachment.blendingEnabled = attachmentDesc.blendEnabled; - //colorAtachment.rgbBlendOperation = GetBlendOp(attachmentDesc.colorBlend.func); - //colorAtachment.alphaBlendOperation = GetBlendOp(attachmentDesc.alphaBlend.func); + renderPipelineDesc.colorAttachments[i].blendingEnabled = attachmentDesc.blendEnabled; + renderPipelineDesc.colorAttachments[i].rgbBlendOperation = GetBlendOp(attachmentDesc.colorBlend.func); + renderPipelineDesc.colorAttachments[i].alphaBlendOperation = GetBlendOp(attachmentDesc.alphaBlend.func); - //colorAtachment.sourceRGBBlendFactor = GetBlendFactor(attachmentDesc.colorBlend.srcFactor); - //colorAtachment.destinationRGBBlendFactor = GetBlendFactor(attachmentDesc.colorBlend.dstFactor); - //colorAtachment.sourceAlphaBlendFactor = GetBlendFactor(attachmentDesc.alphaBlend.srcFactor); - //colorAtachment.destinationAlphaBlendFactor = GetBlendFactor(attachmentDesc.alphaBlend.dstFactor); + renderPipelineDesc.colorAttachments[i].sourceRGBBlendFactor = GetBlendFactor(attachmentDesc.colorBlend.srcFactor); + renderPipelineDesc.colorAttachments[i].destinationRGBBlendFactor = GetBlendFactor(attachmentDesc.colorBlend.dstFactor); + renderPipelineDesc.colorAttachments[i].sourceAlphaBlendFactor = GetBlendFactor(attachmentDesc.alphaBlend.srcFactor); + renderPipelineDesc.colorAttachments[i].destinationAlphaBlendFactor = GetBlendFactor(attachmentDesc.alphaBlend.dstFactor); - //colorAtachment.writeMask = GetColorComponent(pDesc->mColorWriteMasks[blendDescIndex]); + renderPipelineDesc.colorAttachments[i].writeMask = GetColorComponent(attachmentDesc.colorWriteMask); } diff --git a/Source/Metal/QueryMTL.h b/Source/Metal/QueryMTL.h new file mode 100644 index 0000000..e69de29 diff --git a/Source/Metal/QueryMTL.mm b/Source/Metal/QueryMTL.mm new file mode 100644 index 0000000..e69de29 diff --git a/Source/Metal/SwapChainMTL.h b/Source/Metal/SwapChainMTL.h new file mode 100644 index 0000000..b2de4e6 --- /dev/null +++ b/Source/Metal/SwapChainMTL.h @@ -0,0 +1,23 @@ +// © 2021 NVIDIA Corporation + +#pragma once + +namespace nri { + +// Let's keep things simple and hide it under the hood +constexpr uint32_t MAX_NUMBER_OF_FRAMES_IN_FLIGHT = 8; + +struct SwapChainMTL: public DisplayDescHelper { + SwapChainVK(DeviceMTL& device); + ~SwapChainVK(); + + Result Create(const SwapChainDesc& swapChainDesc); + +private: + DeviceMTL& m_Device; + uint64_t m_PresentId = 0; + uint32_t m_TextureIndex = 0; + uint8_t m_FrameIndex = 0; // in flight, not global +}; + +}; diff --git a/Source/Metal/SwapChainMTL.mm b/Source/Metal/SwapChainMTL.mm new file mode 100644 index 0000000..e69de29 diff --git a/Source/Metal/TextureMTL.h b/Source/Metal/TextureMTL.h index f4f5841..a6a4f1e 100644 --- a/Source/Metal/TextureMTL.h +++ b/Source/Metal/TextureMTL.h @@ -26,10 +26,12 @@ struct TextureMTL { return m_Desc; } - Result CreateFromTextureDesc(const TextureDesc& textureDesc); + Result Create(const TextureDesc& textureDesc); //Result Create(const TextureMTLDesc& textureDesc); private: + // Result CreateFromTextureDesc(const TextureDesc& textureDesc); + DeviceMTL& m_Device; TextureDesc m_Desc = {}; id m_Handle; diff --git a/Source/Metal/TextureMTL.mm b/Source/Metal/TextureMTL.mm index 3d4cf67..b66fcb0 100644 --- a/Source/Metal/TextureMTL.mm +++ b/Source/Metal/TextureMTL.mm @@ -14,7 +14,8 @@ // return Result::SUCCESS; //} -Result TextureMTL::CreateFromTextureDesc(const TextureDesc& textureDesc) { + +Result TextureMTL::Create(const TextureDesc& textureDesc) { MTLTextureDescriptor* info = [[MTLTextureDescriptor alloc] init]; info.textureType = ::GetImageTypeMTL(textureDesc.type); info.pixelFormat = ::GetFormatMTL(textureDesc.format, true); From 07ed0feb74201654c99c20ff0094bf3f36c9cbf1 Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Wed, 4 Sep 2024 21:46:56 -0700 Subject: [PATCH 11/24] feat: add descriptor Signed-off-by: Michael Pollind --- Source/Metal/DescriptorMTL.h | 26 ++++++++++++++++++++++++++ Source/Metal/DescriptorMTL.mm | 0 Source/Metal/DeviceMTL.mm | 1 - 3 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 Source/Metal/DescriptorMTL.mm diff --git a/Source/Metal/DescriptorMTL.h b/Source/Metal/DescriptorMTL.h index e69de29..0cce5fe 100644 --- a/Source/Metal/DescriptorMTL.h +++ b/Source/Metal/DescriptorMTL.h @@ -0,0 +1,26 @@ +// © 2021 NVIDIA Corporation + +#pragma once + +namespace nri { + +struct DeviceMTL; + + +struct DescriptorMTL { + + inline DescriptorMTL (DeviceMTL& device) + : m_Device(device) { + } + + inline Result Create(const Texture1DViewDesc& textureViewDesc) {} + inline Result Create(const Texture2DViewDesc& textureViewDesc){} + inline Result Create(const Texture3DViewDesc& textureViewDesc){} + inline Result Create(const SamplerDesc& samplerDesc){} + +private: + DeviceMTL& m_Device; + +}; + +} // namespace nri diff --git a/Source/Metal/DescriptorMTL.mm b/Source/Metal/DescriptorMTL.mm new file mode 100644 index 0000000..e69de29 diff --git a/Source/Metal/DeviceMTL.mm b/Source/Metal/DeviceMTL.mm index b2960f5..81174bb 100644 --- a/Source/Metal/DeviceMTL.mm +++ b/Source/Metal/DeviceMTL.mm @@ -10,7 +10,6 @@ //#include "CommandBufferMTL.h" #include "CommandQueueMTL.h" //#include "DescriptorPoolMTL.h" -#include "DescriptorSetMTL.h" #include "TextureMTL.h" #include "FenceMTL.h" #include "MemoryMTL.h" From 417d6b2a1d2eaf423e0f2b57be441a40aaf79ca8 Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Wed, 4 Sep 2024 21:59:30 -0700 Subject: [PATCH 12/24] fix compiling errors Signed-off-by: Michael Pollind --- Include/Extensions/NRIWrapperMTL.h | 34 +++++++----------------------- Include/NRIDescs.h | 13 +++--------- 2 files changed, 11 insertions(+), 36 deletions(-) diff --git a/Include/Extensions/NRIWrapperMTL.h b/Include/Extensions/NRIWrapperMTL.h index 96a8fc0..3425a15 100644 --- a/Include/Extensions/NRIWrapperMTL.h +++ b/Include/Extensions/NRIWrapperMTL.h @@ -4,62 +4,44 @@ #include "NRIDeviceCreation.h" -NRI_NAMESPACE_BEGIN - +NriNamespaceBegin typedef void* MTLBufferHandle; typedef void* MTLTextureHandle; typedef void* MTLDeviceHandle; -//NRI_ENUM -//( -// MTLGPUFamily, uint8_t, - - // Apple1, -// Apple2, -// Apple3, -// Apple4, -// Apple5, -// Apple6, -// Apple7, -// Mac1, -// Mac2, - -// MAX_APPLE_FAMILY_NUM -//); - -NRI_STRUCT(DeviceCreationMTLDesc) +NriStruct(DeviceCreationMTLDesc) { bool enableNRIValidation; MTLDeviceHandle MtlDevice; }; -NRI_STRUCT(CommandBufferMTLDesc) +NriStruct(CommandBufferMTLDesc) { }; -NRI_STRUCT(BufferMTLDesc) +NriStruct(BufferMTLDesc) { MTLBufferHandle buffer; void* mappedMemory; //MTLResourceOptions options; }; -NRI_STRUCT(TextureMTLDesc) +NriStruct(TextureMTLDesc) { //MTLTextureHandle mtlTexture; //MTLTextureDescriptor* descriptor; }; -NRI_STRUCT(MemoryMTLDesc) +NriStruct(MemoryMTLDesc) { MTLBufferHandle buffer; void* mappedMemory; //MTLResourceOptions options; }; -NRI_API NRI_NAME(Result) NRI_CALL nriCreateDeviceFromMtlDevice(const NRI_NAME_REF(DeviceCreationMTLDesc) deviceDesc, NRI_NAME_REF(Device*) device); +NRI_API Nri(Result) NRI_CALL nriCreateDeviceFromMtlDevice(const NriRef(DeviceCreationMTLDesc) deviceDesc, NriRef(Device*) device); -NRI_NAMESPACE_END +NriNamespaceEnd diff --git a/Include/NRIDescs.h b/Include/NRIDescs.h index a859f3b..9131f66 100644 --- a/Include/NRIDescs.h +++ b/Include/NRIDescs.h @@ -1287,26 +1287,19 @@ NriEnum(GraphicsAPI, uint8_t, D3D11, D3D12, VK, - MTL, - - MAX_NUM + MTL ); // defined in apple framework #undef INTEL #undef AMD -NRI_ENUM -( - - Vendor, uint8_t, +NriEnum(Vendor, uint8_t, UNKNOWN, NVIDIA, AMD, INTEL, - APPLE, - - MAX_NUM + APPLE ); NriStruct(AdapterDesc) { From 0a7e5b1bb7b5c9c02aa2b3ffa88ca63d7344561f Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Thu, 5 Sep 2024 22:18:10 -0700 Subject: [PATCH 13/24] feat: start on command buffer logic Signed-off-by: Michael Pollind --- Source/Metal/CommandBufferMTL.h | 100 +++++++++++++++++ Source/Metal/CommandBufferMTL.hpp | 179 ++++++++++++++++++++++++++++++ Source/Metal/CommandBufferMTL.mm | 119 ++++++++++++++++++++ Source/Metal/ConversionMTL.h | 22 ++-- Source/Metal/DeviceMTL.h | 5 +- Source/Metal/DeviceMTL.hpp | 6 +- Source/Metal/DeviceMTL.mm | 12 ++ Source/Metal/PipelineLayoutMTL.h | 8 +- Source/Metal/PipelineLayoutMTL.mm | 2 +- Source/Metal/PipelineMTL.h | 21 ++++ Source/Metal/PipelineMTL.mm | 34 +++++- 11 files changed, 484 insertions(+), 24 deletions(-) create mode 100644 Source/Metal/CommandBufferMTL.h create mode 100644 Source/Metal/CommandBufferMTL.hpp create mode 100644 Source/Metal/CommandBufferMTL.mm diff --git a/Source/Metal/CommandBufferMTL.h b/Source/Metal/CommandBufferMTL.h new file mode 100644 index 0000000..c6fd170 --- /dev/null +++ b/Source/Metal/CommandBufferMTL.h @@ -0,0 +1,100 @@ +// © 2021 NVIDIA Corporation + +#pragma once + +#import + +namespace nri { + +struct DeviceMTL; +struct PipelineMTL; +struct BufferMTL; +struct PipelineLayoutMTL; +struct TextureMTL; +struct DescriptorMTL; + +struct CommandBufferMTL { + inline CommandBufferMTL(DeviceMTL& device) + : m_Device(device) { + } + + // inline operator VkCommandBuffer() const { + // return m_Handle; + // } + + inline DeviceMTL& GetDevice() const { + return m_Device; + } + + void SetDebugName(const char* name); + Result Begin(const DescriptorPool* descriptorPool); + Result End(); + void SetPipeline(const Pipeline& pipeline); + void SetPipelineLayout(const PipelineLayout& pipelineLayout); + void SetDescriptorSet(uint32_t setIndexInPipelineLayout, const DescriptorSet& descriptorSet, const uint32_t* dynamicConstantBufferOffsets); + void SetConstants(uint32_t pushConstantIndex, const void* data, uint32_t size); + void SetDescriptorPool(const DescriptorPool& descriptorPool); + void Barrier(const BarrierGroupDesc& barrierGroupDesc); + void BeginRendering(const AttachmentsDesc& attachmentsDesc); + void EndRendering(); + void SetViewports(const Viewport* viewports, uint32_t viewportNum); + void SetScissors(const Rect* rects, uint32_t rectNum); + void SetDepthBounds(float boundsMin, float boundsMax); + void SetStencilReference(uint8_t frontRef, uint8_t backRef); + void SetSamplePositions(const SamplePosition* positions, Sample_t positionNum, Sample_t sampleNum); + void SetBlendConstants(const Color32f& color); + void SetShadingRate(const ShadingRateDesc& shadingRateDesc); + void ClearAttachments(const ClearDesc* clearDescs, uint32_t clearDescNum, const Rect* rects, uint32_t rectNum); + void SetIndexBuffer(const Buffer& buffer, uint64_t offset, IndexType indexType); + void SetVertexBuffers(uint32_t baseSlot, uint32_t bufferNum, const Buffer* const* buffers, const uint64_t* offsets); + void Draw(const DrawDesc& drawDesc); + void DrawIndexed(const DrawIndexedDesc& drawIndexedDesc); + void DrawIndirect(const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset); + void DrawIndexedIndirect(const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset); + void Dispatch(const DispatchDesc& dispatchDesc); + void DispatchIndirect(const Buffer& buffer, uint64_t offset); + void BeginQuery(const QueryPool& queryPool, uint32_t offset); + void EndQuery(const QueryPool& queryPool, uint32_t offset); + void BeginAnnotation(const char* name); + void EndAnnotation(); + void ClearStorageBuffer(const ClearStorageBufferDesc& clearDesc); + void ClearStorageTexture(const ClearStorageTextureDesc& clearDesc); + void CopyBuffer(Buffer& dstBuffer, uint64_t dstOffset, const Buffer& srcBuffer, uint64_t srcOffset, uint64_t size); + void CopyTexture(Texture& dstTexture, const TextureRegionDesc* dstRegionDesc, const Texture& srcTexture, const TextureRegionDesc* srcRegionDesc); + void UploadBufferToTexture(Texture& dstTexture, const TextureRegionDesc& dstRegionDesc, const Buffer& srcBuffer, const TextureDataLayoutDesc& srcDataLayoutDesc); + void ReadbackTextureToBuffer(Buffer& dstBuffer, TextureDataLayoutDesc& dstDataLayoutDesc, const Texture& srcTexture, const TextureRegionDesc& srcRegionDesc); + void CopyQueries(const QueryPool& queryPool, uint32_t offset, uint32_t num, Buffer& dstBuffer, uint64_t dstOffset); + void ResetQueries(const QueryPool& queryPool, uint32_t offset, uint32_t num); + void BuildTopLevelAccelerationStructure(uint32_t instanceNum, const Buffer& buffer, uint64_t bufferOffset, AccelerationStructureBuildBits flags, AccelerationStructure& dst, Buffer& scratch, uint64_t scratchOffset); + void BuildBottomLevelAccelerationStructure(uint32_t geometryObjectNum, const GeometryObject* geometryObjects, AccelerationStructureBuildBits flags, AccelerationStructure& dst, Buffer& scratch, uint64_t scratchOffset); + void UpdateTopLevelAccelerationStructure(uint32_t instanceNum, const Buffer& buffer, uint64_t bufferOffset, AccelerationStructureBuildBits flags, AccelerationStructure& dst, AccelerationStructure& src, Buffer& scratch, uint64_t scratchOffset); + void UpdateBottomLevelAccelerationStructure(uint32_t geometryObjectNum, const GeometryObject* geometryObjects, AccelerationStructureBuildBits flags, AccelerationStructure& dst, AccelerationStructure& src, Buffer& scratch, uint64_t scratchOffset); + void CopyAccelerationStructure(AccelerationStructure& dst, AccelerationStructure& src, CopyMode copyMode); + void WriteAccelerationStructureSize(const AccelerationStructure* const* accelerationStructures, uint32_t accelerationStructureNum, QueryPool& queryPool, uint32_t queryPoolOffset); + void DispatchRays(const DispatchRaysDesc& dispatchRaysDesc); + void DispatchRaysIndirect(const Buffer& buffer, uint64_t offset); + void DrawMeshTasks(const DrawMeshTasksDesc& drawMeshTasksDesc); + void DrawMeshTasksIndirect(const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride); + + ~CommandBufferMTL(); + + struct CmdIndexBuffer { + size_t m_Offset; + MTLIndexType m_Type; + struct BufferMTL* m_Buffer; + }; + + +private: + DeviceMTL& m_Device; + struct PipelineMTL* m_CurrentPipeline = nullptr; + + struct CmdIndexBuffer m_CurrentIndexCmd; + id m_Handle; + + id m_encoder; + + //id renderEncoder; +}; +}; + diff --git a/Source/Metal/CommandBufferMTL.hpp b/Source/Metal/CommandBufferMTL.hpp new file mode 100644 index 0000000..7aa867b --- /dev/null +++ b/Source/Metal/CommandBufferMTL.hpp @@ -0,0 +1,179 @@ + +#pragma region[ Core ] + +static void NRI_CALL SetCommandBufferDebugName(CommandBuffer& commandBuffer, const char* name) { + ((CommandBufferMTL&)commandBuffer).SetDebugName(name); +} + +static Result NRI_CALL BeginCommandBuffer(CommandBuffer& commandBuffer, const DescriptorPool* descriptorPool) { + return ((CommandBufferMTL&)commandBuffer).Begin(descriptorPool); +} + +static Result NRI_CALL EndCommandBuffer(CommandBuffer& commandBuffer) { + return ((CommandBufferMTL&)commandBuffer).End(); +} + +static void NRI_CALL CmdSetPipelineLayout(CommandBuffer& commandBuffer, const PipelineLayout& pipelineLayout) { + ((CommandBufferMTL&)commandBuffer).SetPipelineLayout(pipelineLayout); +} + +static void NRI_CALL CmdSetPipeline(CommandBuffer& commandBuffer, const Pipeline& pipeline) { + ((CommandBufferMTL&)commandBuffer).SetPipeline(pipeline); +} + +static void NRI_CALL CmdBarrier(CommandBuffer& commandBuffer, const BarrierGroupDesc& barrierGroupDesc) { + ((CommandBufferMTL&)commandBuffer).Barrier(barrierGroupDesc); +} + +static void NRI_CALL CmdSetDescriptorPool(CommandBuffer& commandBuffer, const DescriptorPool& descriptorPool) { + ((CommandBufferMTL&)commandBuffer).SetDescriptorPool(descriptorPool); +} + +static void NRI_CALL CmdSetDescriptorSet(CommandBuffer& commandBuffer, uint32_t setIndexInPipelineLayout, const DescriptorSet& descriptorSet, const uint32_t* dynamicConstantBufferOffsets) { + ((CommandBufferMTL&)commandBuffer).SetDescriptorSet(setIndexInPipelineLayout, descriptorSet, dynamicConstantBufferOffsets); +} + +static void NRI_CALL CmdSetConstants(CommandBuffer& commandBuffer, uint32_t pushConstantIndex, const void* data, uint32_t size) { + ((CommandBufferMTL&)commandBuffer).SetConstants(pushConstantIndex, data, size); +} + +static void NRI_CALL CmdBeginRendering(CommandBuffer& commandBuffer, const AttachmentsDesc& attachmentsDesc) { + ((CommandBufferMTL&)commandBuffer).BeginRendering(attachmentsDesc); +} + +static void NRI_CALL CmdEndRendering(CommandBuffer& commandBuffer) { + ((CommandBufferMTL&)commandBuffer).EndRendering(); +} + +static void NRI_CALL CmdSetViewports(CommandBuffer& commandBuffer, const Viewport* viewports, uint32_t viewportNum) { + ((CommandBufferMTL&)commandBuffer).SetViewports(viewports, viewportNum); +} + +static void NRI_CALL CmdSetScissors(CommandBuffer& commandBuffer, const nri::Rect* rects, uint32_t rectNum) { + ((CommandBufferMTL&)commandBuffer).SetScissors(rects, rectNum); +} + +static void NRI_CALL CmdSetDepthBounds(CommandBuffer& commandBuffer, float boundsMin, float boundsMax) { + ((CommandBufferMTL&)commandBuffer).SetDepthBounds(boundsMin, boundsMax); +} + +static void NRI_CALL CmdSetStencilReference(CommandBuffer& commandBuffer, uint8_t frontRef, uint8_t backRef) { + ((CommandBufferMTL&)commandBuffer).SetStencilReference(frontRef, backRef); +} + +static void NRI_CALL CmdSetSamplePositions(CommandBuffer& commandBuffer, const SamplePosition* positions, Sample_t positionNum, Sample_t sampleNum) { + ((CommandBufferMTL&)commandBuffer).SetSamplePositions(positions, positionNum, sampleNum); +} + +static void NRI_CALL CmdSetBlendConstants(CommandBuffer& commandBuffer, const Color32f& color) { + ((CommandBufferMTL&)commandBuffer).SetBlendConstants(color); +} + +static void NRI_CALL CmdSetShadingRate(CommandBuffer& commandBuffer, const ShadingRateDesc& shadingRateDesc) { + ((CommandBufferMTL&)commandBuffer).SetShadingRate(shadingRateDesc); +} + +static void NRI_CALL CmdSetDepthBias(CommandBuffer& commandBuffer, const DepthBiasDesc& depthBiasDesc) { + //((CommandBufferMTL&)commandBuffer).SetDepthBias(depthBiasDesc); +} + +static void NRI_CALL CmdClearAttachments(CommandBuffer& commandBuffer, const ClearDesc* clearDescs, uint32_t clearDescNum, const nri::Rect* rects, uint32_t rectNum) { + ((CommandBufferMTL&)commandBuffer).ClearAttachments(clearDescs, clearDescNum, rects, rectNum); +} + +static void NRI_CALL CmdSetIndexBuffer(CommandBuffer& commandBuffer, const Buffer& buffer, uint64_t offset, IndexType indexType) { + ((CommandBufferMTL&)commandBuffer).SetIndexBuffer(buffer, offset, indexType); +} + +static void NRI_CALL CmdSetVertexBuffers(CommandBuffer& commandBuffer, uint32_t baseSlot, uint32_t bufferNum, const Buffer* const* buffers, const uint64_t* offsets) { + ((CommandBufferMTL&)commandBuffer).SetVertexBuffers(baseSlot, bufferNum, buffers, offsets); +} + +static void NRI_CALL CmdDraw(CommandBuffer& commandBuffer, const DrawDesc& drawDesc) { + ((CommandBufferMTL&)commandBuffer).Draw(drawDesc); +} + +static void NRI_CALL CmdDrawIndexed(CommandBuffer& commandBuffer, const DrawIndexedDesc& drawIndexedDesc) { + ((CommandBufferMTL&)commandBuffer).DrawIndexed(drawIndexedDesc); +} + +static void NRI_CALL CmdDrawIndirect(CommandBuffer& commandBuffer, const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) { + ((CommandBufferMTL&)commandBuffer).DrawIndirect(buffer, offset, drawNum, stride, countBuffer, countBufferOffset); +} + +static void NRI_CALL CmdDrawIndexedIndirect(CommandBuffer& commandBuffer, const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) { + ((CommandBufferMTL&)commandBuffer).DrawIndexedIndirect(buffer, offset, drawNum, stride, countBuffer, countBufferOffset); +} + +static void NRI_CALL CmdDispatch(CommandBuffer& commandBuffer, const DispatchDesc& dispatchDesc) { + ((CommandBufferMTL&)commandBuffer).Dispatch(dispatchDesc); +} + +static void NRI_CALL CmdDispatchIndirect(CommandBuffer& commandBuffer, const Buffer& buffer, uint64_t offset) { + ((CommandBufferMTL&)commandBuffer).DispatchIndirect(buffer, offset); +} + +static void NRI_CALL CmdBeginQuery(CommandBuffer& commandBuffer, const QueryPool& queryPool, uint32_t offset) { + ((CommandBufferMTL&)commandBuffer).BeginQuery(queryPool, offset); +} + +static void NRI_CALL CmdEndQuery(CommandBuffer& commandBuffer, const QueryPool& queryPool, uint32_t offset) { + ((CommandBufferMTL&)commandBuffer).EndQuery(queryPool, offset); +} + +static void NRI_CALL CmdBeginAnnotation(CommandBuffer& commandBuffer, const char* name) { + ((CommandBufferMTL&)commandBuffer).BeginAnnotation(name); +} + +static void NRI_CALL CmdEndAnnotation(CommandBuffer& commandBuffer) { + ((CommandBufferMTL&)commandBuffer).EndAnnotation(); +} + +static void NRI_CALL CmdClearStorageBuffer(CommandBuffer& commandBuffer, const ClearStorageBufferDesc& clearDesc) { + ((CommandBufferMTL&)commandBuffer).ClearStorageBuffer(clearDesc); +} + +static void NRI_CALL CmdClearStorageTexture(CommandBuffer& commandBuffer, const ClearStorageTextureDesc& clearDesc) { + ((CommandBufferMTL&)commandBuffer).ClearStorageTexture(clearDesc); +} + +static void NRI_CALL CmdCopyBuffer(CommandBuffer& commandBuffer, Buffer& dstBuffer, uint64_t dstOffset, const Buffer& srcBuffer, uint64_t srcOffset, uint64_t size) { + ((CommandBufferMTL&)commandBuffer).CopyBuffer(dstBuffer, dstOffset, srcBuffer, srcOffset, size); +} + +static void NRI_CALL CmdCopyTexture( + CommandBuffer& commandBuffer, Texture& dstTexture, const TextureRegionDesc* dstRegionDesc, const Texture& srcTexture, const TextureRegionDesc* srcRegionDesc) { + ((CommandBufferMTL&)commandBuffer).CopyTexture(dstTexture, dstRegionDesc, srcTexture, srcRegionDesc); +} + +static void NRI_CALL CmdUploadBufferToTexture(CommandBuffer& commandBuffer, Texture& dstTexture, const TextureRegionDesc& dstRegionDesc, const Buffer& srcBuffer, const TextureDataLayoutDesc& srcDataLayoutDesc) { + ((CommandBufferMTL&)commandBuffer).UploadBufferToTexture(dstTexture, dstRegionDesc, srcBuffer, srcDataLayoutDesc); +} + +static void NRI_CALL CmdReadbackTextureToBuffer(CommandBuffer& commandBuffer, Buffer& dstBuffer, const TextureDataLayoutDesc& dstDataLayoutDesc, const Texture& srcTexture, const TextureRegionDesc& srcRegionDesc) { + //((CommandBufferMTL&)commandBuffer).ReadbackTextureToBuffer(dstBuffer, dstDataLayoutDesc, srcTexture, srcRegionDesc); +} + +static void NRI_CALL CmdCopyQueries(CommandBuffer& commandBuffer, const QueryPool& queryPool, uint32_t offset, uint32_t num, Buffer& dstBuffer, uint64_t dstOffset) { + ((CommandBufferMTL&)commandBuffer).CopyQueries(queryPool, offset, num, dstBuffer, dstOffset); +} + +static void NRI_CALL CmdResetQueries(CommandBuffer& commandBuffer, const QueryPool& queryPool, uint32_t offset, uint32_t num) { + ((CommandBufferMTL&)commandBuffer).ResetQueries(queryPool, offset, num); +} + +static void* NRI_CALL GetCommandBufferNativeObject(const CommandBuffer& commandBuffer) { + if (!(&commandBuffer)) + return nullptr; + + return nullptr; + // return (CommandBufferMTL)((CommandBufferMTL&)commandBuffer); +} + +#pragma endregion + + + + +Define_Core_CommandBuffer_PartiallyFillFunctionTable(VK); + diff --git a/Source/Metal/CommandBufferMTL.mm b/Source/Metal/CommandBufferMTL.mm new file mode 100644 index 0000000..92ee991 --- /dev/null +++ b/Source/Metal/CommandBufferMTL.mm @@ -0,0 +1,119 @@ +#include "SharedMTL.h" + +#include "CommandBufferMTL.h" + +//#include "AccelerationStructureVK.h" +#include "BufferMTL.h" +#include "CommandBufferMTL.h" +#include "CommandQueueMTL.h" +//#include "DescriptorSetMTL.h" +#include "DescriptorMTL.h" +#include "PipelineLayoutMTL.h" +#include "PipelineMTL.h" +//#include "QueryPoolMTL.h" +#include "TextureMTL.h" + +#include + +using namespace nri; + +CommandBufferMTL::~CommandBufferMTL() { + +} + +void CommandBufferMTL::SetDebugName(const char* name) { + [m_Handle setLabel:[NSString stringWithUTF8String:name]]; +} + +Result CommandBufferMTL::Begin(const DescriptorPool* descriptorPool) { + +} +Result CommandBufferMTL::End() { + +} +void CommandBufferMTL::SetPipeline(const Pipeline& pipeline) { + if (m_CurrentPipeline == (PipelineMTL*)&pipeline) + return; + PipelineMTL& pipelineImpl = (PipelineMTL&)pipeline; + m_CurrentPipeline = &pipelineImpl; + + +} +void CommandBufferMTL::SetPipelineLayout(const PipelineLayout& pipelineLayout) {} +void CommandBufferMTL::SetDescriptorSet(uint32_t setIndexInPipelineLayout, const DescriptorSet& descriptorSet, const uint32_t* dynamicConstantBufferOffsets) {} +void CommandBufferMTL::SetConstants(uint32_t pushConstantIndex, const void* data, uint32_t size) {} +void CommandBufferMTL::SetDescriptorPool(const DescriptorPool& descriptorPool) {} +void CommandBufferMTL::Barrier(const BarrierGroupDesc& barrierGroupDesc) {} +void CommandBufferMTL::BeginRendering(const AttachmentsDesc& attachmentsDesc) { + m_encoder = [m_Handle renderCommandEncoderWithDescriptor: NULL]; + +} +void CommandBufferMTL::EndRendering() {} +void CommandBufferMTL::SetViewports(const Viewport* viewports, uint32_t viewportNum) {} +void CommandBufferMTL::SetScissors(const Rect* rects, uint32_t rectNum) {} +void CommandBufferMTL::SetDepthBounds(float boundsMin, float boundsMax) {} +void CommandBufferMTL::SetStencilReference(uint8_t frontRef, uint8_t backRef) {} +void CommandBufferMTL::SetSamplePositions(const SamplePosition* positions, Sample_t positionNum, Sample_t sampleNum) {} +void CommandBufferMTL::SetBlendConstants(const Color32f& color) {} +void CommandBufferMTL::SetShadingRate(const ShadingRateDesc& shadingRateDesc) {} +void CommandBufferMTL::ClearAttachments(const ClearDesc* clearDescs, uint32_t clearDescNum, const Rect* rects, uint32_t rectNum) {} +void CommandBufferMTL::SetIndexBuffer(const Buffer& buffer, uint64_t offset, IndexType indexType) { + m_CurrentIndexCmd.m_Buffer = &(BufferMTL&)buffer; + switch(indexType) { + case IndexType::UINT16: + m_CurrentIndexCmd.m_Type = MTLIndexType::MTLIndexTypeUInt16; + break; + default: + case IndexType::UINT32: + m_CurrentIndexCmd.m_Type = MTLIndexType::MTLIndexTypeUInt32; + break; + } + m_CurrentIndexCmd.m_Offset = offset; +} +void CommandBufferMTL::SetVertexBuffers(uint32_t baseSlot, uint32_t bufferNum, const Buffer* const* buffers, const uint64_t* offsets) { +} +void CommandBufferMTL::Draw(const DrawDesc& drawDesc) { + + [m_encoder drawPrimitives: m_CurrentPipeline->m_graphics.m_primitiveType + vertexStart:drawDesc.baseVertex + vertexCount:drawDesc.vertexNum + instanceCount:drawDesc.instanceNum + baseInstance:0]; +} +void CommandBufferMTL::DrawIndexed(const DrawIndexedDesc& drawIndexedDesc) { + id indexBuffer = m_CurrentIndexCmd.m_Buffer->GetHandle(); + [m_encoder drawIndexedPrimitives: m_CurrentPipeline->m_graphics.m_primitiveType + indexCount:drawIndexedDesc.indexNum + indexType: m_CurrentIndexCmd.m_Type + indexBuffer: indexBuffer + indexBufferOffset: m_CurrentIndexCmd.m_Offset]; +} +void CommandBufferMTL::DrawIndirect(const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) {} +void CommandBufferMTL::DrawIndexedIndirect(const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) {} +void CommandBufferMTL::Dispatch(const DispatchDesc& dispatchDesc) {} +void CommandBufferMTL::DispatchIndirect(const Buffer& buffer, uint64_t offset) {} +void CommandBufferMTL::BeginQuery(const QueryPool& queryPool, uint32_t offset) {} +void CommandBufferMTL::EndQuery(const QueryPool& queryPool, uint32_t offset) {} +void CommandBufferMTL::BeginAnnotation(const char* name) {} +void CommandBufferMTL::EndAnnotation() {} +void CommandBufferMTL::ClearStorageBuffer(const ClearStorageBufferDesc& clearDesc) {} +void CommandBufferMTL::ClearStorageTexture(const ClearStorageTextureDesc& clearDesc) {} +void CommandBufferMTL::CopyBuffer(Buffer& dstBuffer, uint64_t dstOffset, const Buffer& srcBuffer, uint64_t srcOffset, uint64_t size) {} +void CommandBufferMTL::CopyTexture(Texture& dstTexture, const TextureRegionDesc* dstRegionDesc, const Texture& srcTexture, const TextureRegionDesc* srcRegionDesc) {} +void CommandBufferMTL::UploadBufferToTexture(Texture& dstTexture, const TextureRegionDesc& dstRegionDesc, const Buffer& srcBuffer, const TextureDataLayoutDesc& srcDataLayoutDesc) {} +void CommandBufferMTL::ReadbackTextureToBuffer(Buffer& dstBuffer, TextureDataLayoutDesc& dstDataLayoutDesc, const Texture& srcTexture, const TextureRegionDesc& srcRegionDesc) {} +void CommandBufferMTL::CopyQueries(const QueryPool& queryPool, uint32_t offset, uint32_t num, Buffer& dstBuffer, uint64_t dstOffset) {} +void CommandBufferMTL::ResetQueries(const QueryPool& queryPool, uint32_t offset, uint32_t num) {} +void CommandBufferMTL::BuildTopLevelAccelerationStructure(uint32_t instanceNum, const Buffer& buffer, uint64_t bufferOffset, AccelerationStructureBuildBits flags, AccelerationStructure& dst, Buffer& scratch, uint64_t scratchOffset) {} +void CommandBufferMTL::BuildBottomLevelAccelerationStructure(uint32_t geometryObjectNum, const GeometryObject* geometryObjects, AccelerationStructureBuildBits flags, AccelerationStructure& dst, Buffer& scratch, uint64_t scratchOffset) {} +void CommandBufferMTL::UpdateTopLevelAccelerationStructure(uint32_t instanceNum, const Buffer& buffer, uint64_t bufferOffset, AccelerationStructureBuildBits flags, AccelerationStructure& dst, AccelerationStructure& src, Buffer& scratch, uint64_t scratchOffset) {} +void CommandBufferMTL::UpdateBottomLevelAccelerationStructure(uint32_t geometryObjectNum, const GeometryObject* geometryObjects, AccelerationStructureBuildBits flags, AccelerationStructure& dst, AccelerationStructure& src, Buffer& scratch, uint64_t scratchOffset) {} +void CommandBufferMTL::CopyAccelerationStructure(AccelerationStructure& dst, AccelerationStructure& src, CopyMode copyMode) {} +void CommandBufferMTL::WriteAccelerationStructureSize(const AccelerationStructure* const* accelerationStructures, uint32_t accelerationStructureNum, QueryPool& queryPool, uint32_t queryPoolOffset) {} +void CommandBufferMTL::DispatchRays(const DispatchRaysDesc& dispatchRaysDesc) {} +void CommandBufferMTL::DispatchRaysIndirect(const Buffer& buffer, uint64_t offset) {} +void CommandBufferMTL::DrawMeshTasks(const DrawMeshTasksDesc& drawMeshTasksDesc) {} +void CommandBufferMTL::DrawMeshTasksIndirect(const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride) {} + +#include "CommandBufferMTL.hpp" + diff --git a/Source/Metal/ConversionMTL.h b/Source/Metal/ConversionMTL.h index a0c53d3..1079bbc 100644 --- a/Source/Metal/ConversionMTL.h +++ b/Source/Metal/ConversionMTL.h @@ -56,15 +56,15 @@ constexpr MTLColorWriteMask GetColorComponent(ColorWriteBits colorWriteMask) { } constexpr std::array DESCRIPTOR_TYPES = { - MTLDataTypeSampler, // SAMPLER - MTLDataTypeNone, // CONSTANT_BUFFER - MTLDataTypeTexture, // TEXTURE - MTLDataTypeNone, // STORAGE_TEXTURE - MTLDataTypeStruct, // BUFFER - MTLDataTypeStruct, // STORAGE_BUFFER - MTLDataTypeArray, // STRUCTURED_BUFFER - MTLDataTypeStruct, // STORAGE_STRUCTURED_BUFFER - MTLDataTypePrimitiveAccelerationStructure // ACCELERATION_STRUCTURE + MTLDataTypeSampler, // SAMPLER + MTLDataTypeNone, // CONSTANT_BUFFER + MTLDataTypeTexture, // TEXTURE + MTLDataTypeNone, // STORAGE_TEXTURE + MTLDataTypeStruct, // BUFFER + MTLDataTypeStruct, // STORAGE_BUFFER + MTLDataTypeArray, // STRUCTURED_BUFFER + MTLDataTypeStruct, // STORAGE_STRUCTURED_BUFFER + MTLDataTypePrimitiveAccelerationStructure // ACCELERATION_STRUCTURE }; constexpr MTLDataType GetDescriptorType(DescriptorType type) { @@ -135,7 +135,7 @@ constexpr MTLSamplerAddressMode GetSamplerAddressMode(AddressMode addressMode) { -constexpr std::array TOPOLOGIES = { +constexpr std::array TOPOLOGIES_CLASSES = { MTLPrimitiveTopologyClassPoint, // POINT_LIST MTLPrimitiveTopologyClassLine, // LINE_LIST MTLPrimitiveTopologyClassLine, // LINE_STRIP @@ -150,7 +150,7 @@ constexpr std::array TOPOL constexpr MTLPrimitiveTopologyClass GetTopologyMTL(Topology topology) { - return TOPOLOGIES[(size_t)topology]; + return TOPOLOGIES_CLASSES [(size_t)topology]; } inline MTLPixelFormat GetFormatMTL(Format format, bool demoteSrgb = false) { diff --git a/Source/Metal/DeviceMTL.h b/Source/Metal/DeviceMTL.h index de01369..b602711 100644 --- a/Source/Metal/DeviceMTL.h +++ b/Source/Metal/DeviceMTL.h @@ -37,7 +37,10 @@ struct DeviceMTL final : public DeviceBase { return result; } - + void GetMemoryDesc(const BufferDesc& bufferDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc); + void GetMemoryDesc(const TextureDesc& textureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc); + void GetMemoryDesc(const AccelerationStructureDesc& accelerationStructureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc); + Result FillFunctionTable(CoreInterface& table) const; Result FillFunctionTable(HelperInterface& table) const; Result FillFunctionTable(LowLatencyInterface& table) const; diff --git a/Source/Metal/DeviceMTL.hpp b/Source/Metal/DeviceMTL.hpp index 011c3bc..16770b3 100644 --- a/Source/Metal/DeviceMTL.hpp +++ b/Source/Metal/DeviceMTL.hpp @@ -29,10 +29,8 @@ static void NRI_CALL GetBufferMemoryDesc(const Device& device, const BufferDesc& } static void NRI_CALL GetTextureMemoryDesc(const Device& device, const TextureDesc& textureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { - //D3D12_RESOURCE_DESC desc = {}; - //GetResourceDesc(&desc, textureDesc); - - //((const DeviceD3D12&)device).GetMemoryDesc(memoryLocation, desc, memoryDesc); + //return ((const DeviceMTL&)device).GetMemoryDesc(textureDesc, memoryLocation, memoryDesc); + } static Result NRI_CALL GetCommandQueue(Device& device, CommandQueueType commandQueueType, CommandQueue*& commandQueue) { diff --git a/Source/Metal/DeviceMTL.mm b/Source/Metal/DeviceMTL.mm index 81174bb..39877b0 100644 --- a/Source/Metal/DeviceMTL.mm +++ b/Source/Metal/DeviceMTL.mm @@ -90,6 +90,18 @@ static bool FindMTLGpuFamily(id device, // } //} +void DeviceMTL::GetMemoryDesc(const BufferDesc& bufferDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { + +} + +void DeviceMTL::GetMemoryDesc(const TextureDesc& textureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { + +} + +void DeviceMTL::GetMemoryDesc(const AccelerationStructureDesc& accelerationStructureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { + +} + Result DeviceMTL::GetCommandQueue(CommandQueueType commandQueueType, CommandQueue*& commandQueue) { ExclusiveScope lock(m_Lock); diff --git a/Source/Metal/PipelineLayoutMTL.h b/Source/Metal/PipelineLayoutMTL.h index 3a575b8..2a4b080 100644 --- a/Source/Metal/PipelineLayoutMTL.h +++ b/Source/Metal/PipelineLayoutMTL.h @@ -12,18 +12,14 @@ struct PipelineLayoutMTL { } ~PipelineLayoutMTL(); -// - inline Result Create(const PipelineLayoutDesc& pipelineLayoutDesc) { - return CreateDesc(pipelineLayoutDesc); - } - + Result Create(const PipelineLayoutDesc& pipelineLayoutDesc); + struct PipelineDescriptorSet { NSMutableArray* m_ArgumentDescriptors; }; private: - Result CreateDesc(const PipelineLayoutDesc& pipelineLayoutDesc); DeviceMTL& m_Device; std::vector m_DescriptorSets; diff --git a/Source/Metal/PipelineLayoutMTL.mm b/Source/Metal/PipelineLayoutMTL.mm index 7a50767..33b4c76 100644 --- a/Source/Metal/PipelineLayoutMTL.mm +++ b/Source/Metal/PipelineLayoutMTL.mm @@ -8,7 +8,7 @@ } -Result PipelineLayoutMTL::CreateDesc(const PipelineLayoutDesc& pipelineLayoutDesc) { +Result PipelineLayoutMTL::Create(const PipelineLayoutDesc& pipelineLayoutDesc) { m_DescriptorSets.resize(pipelineLayoutDesc.descriptorSetNum); for (uint32_t i = 0; i < pipelineLayoutDesc.descriptorSetNum; i++) { const DescriptorSetDesc& descriptorSetDesc = pipelineLayoutDesc.descriptorSets[i]; diff --git a/Source/Metal/PipelineMTL.h b/Source/Metal/PipelineMTL.h index ccb7e15..5c9b322 100644 --- a/Source/Metal/PipelineMTL.h +++ b/Source/Metal/PipelineMTL.h @@ -8,12 +8,33 @@ struct DeviceMTL; struct PipelineLayoutMTL; struct PipelineMTL { + enum PiplineType { + None, + Graphics, + Compute, + Raytracing + }; + inline PipelineMTL(DeviceMTL& device) : m_Device(device) { } ~PipelineMTL(); Result Create(const GraphicsPipelineDesc& graphicsPipelineDesc); + Result Create(const ComputePipelineDesc& computePipelineDesc); + Result Create(const RayTracingPipelineDesc& rayTracingPipelineDesc); + + enum PiplineType m_type = None; + union { + struct { + MTLPrimitiveTopologyClass m_topologyClass; + MTLPrimitiveType m_primitiveType; + } m_graphics; + struct { + + } m_compute; + }; + private: DeviceMTL& m_Device; }; diff --git a/Source/Metal/PipelineMTL.mm b/Source/Metal/PipelineMTL.mm index 39b574c..f5ef7f4 100644 --- a/Source/Metal/PipelineMTL.mm +++ b/Source/Metal/PipelineMTL.mm @@ -8,8 +8,40 @@ } +Result PipelineMTL::Create(const ComputePipelineDesc& computePipelineDesc) { + return Result::SUCCESS; +} + +Result PipelineMTL::Create(const RayTracingPipelineDesc& rayTracingPipelineDesc) { + return Result::SUCCESS; +} + Result PipelineMTL::Create(const GraphicsPipelineDesc& graphicsPipelineDesc) { MTLRenderPipelineDescriptor *renderPipelineDesc = [[MTLRenderPipelineDescriptor alloc] init]; + + m_type = PipelineMTL::Graphics; + const InputAssemblyDesc& ia = graphicsPipelineDesc.inputAssembly; + switch (ia.topology) { + case Topology::POINT_LIST: + m_graphics.m_primitiveType = MTLPrimitiveType::MTLPrimitiveTypePoint; + break; + case Topology::LINE_LIST: + case Topology::LINE_STRIP: + case Topology::LINE_LIST_WITH_ADJACENCY: + case Topology::LINE_STRIP_WITH_ADJACENCY: + m_graphics.m_primitiveType = MTLPrimitiveType::MTLPrimitiveTypeLine; + break; + case Topology::TRIANGLE_LIST: + case Topology::TRIANGLE_STRIP: + case Topology::TRIANGLE_LIST_WITH_ADJACENCY: + case Topology::TRIANGLE_STRIP_WITH_ADJACENCY: + m_graphics.m_primitiveType = MTLPrimitiveType::MTLPrimitiveTypeTriangle; + break; + case Topology::PATCH_LIST: + default: + break; + } + for (uint32_t i = 0; i < graphicsPipelineDesc.shaderNum; i++) { } // Depth-stencil @@ -28,7 +60,6 @@ // } } - const InputAssemblyDesc& ia = graphicsPipelineDesc.inputAssembly; renderPipelineDesc.inputPrimitiveTopology = GetTopologyMTL(ia.topology); if (graphicsPipelineDesc.multisample) { @@ -56,5 +87,6 @@ renderPipelineDesc.colorAttachments[i].writeMask = GetColorComponent(attachmentDesc.colorWriteMask); } + return Result::SUCCESS; } From 3d0b30045c68ba4b534895095d5c51829d78175e Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Fri, 6 Sep 2024 08:02:58 -0700 Subject: [PATCH 14/24] add command buffer type --- Source/Metal/CommandBufferMTL.h | 4 ---- Source/Metal/CommandBufferMTL.mm | 27 ++++++++++++++++------- Source/Metal/PipelineMTL.h | 15 +++---------- Source/Metal/PipelineMTL.mm | 38 ++++++++++++++++---------------- 4 files changed, 41 insertions(+), 43 deletions(-) diff --git a/Source/Metal/CommandBufferMTL.h b/Source/Metal/CommandBufferMTL.h index c6fd170..ce67085 100644 --- a/Source/Metal/CommandBufferMTL.h +++ b/Source/Metal/CommandBufferMTL.h @@ -83,15 +83,11 @@ struct CommandBufferMTL { MTLIndexType m_Type; struct BufferMTL* m_Buffer; }; - - private: DeviceMTL& m_Device; struct PipelineMTL* m_CurrentPipeline = nullptr; - struct CmdIndexBuffer m_CurrentIndexCmd; id m_Handle; - id m_encoder; //id renderEncoder; diff --git a/Source/Metal/CommandBufferMTL.mm b/Source/Metal/CommandBufferMTL.mm index 92ee991..794126e 100644 --- a/Source/Metal/CommandBufferMTL.mm +++ b/Source/Metal/CommandBufferMTL.mm @@ -46,9 +46,10 @@ void CommandBufferMTL::Barrier(const BarrierGroupDesc& barrierGroupDesc) {} void CommandBufferMTL::BeginRendering(const AttachmentsDesc& attachmentsDesc) { m_encoder = [m_Handle renderCommandEncoderWithDescriptor: NULL]; - } -void CommandBufferMTL::EndRendering() {} +void CommandBufferMTL::EndRendering() { + [m_encoder endEncoding]; +} void CommandBufferMTL::SetViewports(const Viewport* viewports, uint32_t viewportNum) {} void CommandBufferMTL::SetScissors(const Rect* rects, uint32_t rectNum) {} void CommandBufferMTL::SetDepthBounds(float boundsMin, float boundsMax) {} @@ -71,25 +72,35 @@ m_CurrentIndexCmd.m_Offset = offset; } void CommandBufferMTL::SetVertexBuffers(uint32_t baseSlot, uint32_t bufferNum, const Buffer* const* buffers, const uint64_t* offsets) { + } void CommandBufferMTL::Draw(const DrawDesc& drawDesc) { - - [m_encoder drawPrimitives: m_CurrentPipeline->m_graphics.m_primitiveType + [m_encoder drawPrimitives: m_CurrentPipeline->m_primitiveType vertexStart:drawDesc.baseVertex vertexCount:drawDesc.vertexNum instanceCount:drawDesc.instanceNum - baseInstance:0]; + baseInstance:0]; } void CommandBufferMTL::DrawIndexed(const DrawIndexedDesc& drawIndexedDesc) { id indexBuffer = m_CurrentIndexCmd.m_Buffer->GetHandle(); - [m_encoder drawIndexedPrimitives: m_CurrentPipeline->m_graphics.m_primitiveType + [m_encoder drawIndexedPrimitives: m_CurrentPipeline->m_primitiveType indexCount:drawIndexedDesc.indexNum indexType: m_CurrentIndexCmd.m_Type indexBuffer: indexBuffer indexBufferOffset: m_CurrentIndexCmd.m_Offset]; } -void CommandBufferMTL::DrawIndirect(const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) {} -void CommandBufferMTL::DrawIndexedIndirect(const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) {} + +void CommandBufferMTL::DrawIndirect(const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) { + NSCAssert(!countBuffer, @"count buffer not supported"); + [m_encoder + drawPrimitives: m_CurrentPipeline->m_primitiveType + indirectBuffer:((BufferMTL&)buffer).GetHandle() + indirectBufferOffset: offset]; + +} +void CommandBufferMTL::DrawIndexedIndirect(const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) { + +} void CommandBufferMTL::Dispatch(const DispatchDesc& dispatchDesc) {} void CommandBufferMTL::DispatchIndirect(const Buffer& buffer, uint64_t offset) {} void CommandBufferMTL::BeginQuery(const QueryPool& queryPool, uint32_t offset) {} diff --git a/Source/Metal/PipelineMTL.h b/Source/Metal/PipelineMTL.h index 5c9b322..b274bc4 100644 --- a/Source/Metal/PipelineMTL.h +++ b/Source/Metal/PipelineMTL.h @@ -23,18 +23,9 @@ struct PipelineMTL { Result Create(const GraphicsPipelineDesc& graphicsPipelineDesc); Result Create(const ComputePipelineDesc& computePipelineDesc); Result Create(const RayTracingPipelineDesc& rayTracingPipelineDesc); - - enum PiplineType m_type = None; - union { - struct { - MTLPrimitiveTopologyClass m_topologyClass; - MTLPrimitiveType m_primitiveType; - } m_graphics; - struct { - - } m_compute; - }; - + + MTLPrimitiveTopologyClass m_topologyClass; + MTLPrimitiveType m_primitiveType; private: DeviceMTL& m_Device; }; diff --git a/Source/Metal/PipelineMTL.mm b/Source/Metal/PipelineMTL.mm index f5ef7f4..77418aa 100644 --- a/Source/Metal/PipelineMTL.mm +++ b/Source/Metal/PipelineMTL.mm @@ -19,27 +19,27 @@ Result PipelineMTL::Create(const GraphicsPipelineDesc& graphicsPipelineDesc) { MTLRenderPipelineDescriptor *renderPipelineDesc = [[MTLRenderPipelineDescriptor alloc] init]; - m_type = PipelineMTL::Graphics; + //m_type = PipelineMTL::Graphics; const InputAssemblyDesc& ia = graphicsPipelineDesc.inputAssembly; switch (ia.topology) { - case Topology::POINT_LIST: - m_graphics.m_primitiveType = MTLPrimitiveType::MTLPrimitiveTypePoint; - break; - case Topology::LINE_LIST: - case Topology::LINE_STRIP: - case Topology::LINE_LIST_WITH_ADJACENCY: - case Topology::LINE_STRIP_WITH_ADJACENCY: - m_graphics.m_primitiveType = MTLPrimitiveType::MTLPrimitiveTypeLine; - break; - case Topology::TRIANGLE_LIST: - case Topology::TRIANGLE_STRIP: - case Topology::TRIANGLE_LIST_WITH_ADJACENCY: - case Topology::TRIANGLE_STRIP_WITH_ADJACENCY: - m_graphics.m_primitiveType = MTLPrimitiveType::MTLPrimitiveTypeTriangle; - break; - case Topology::PATCH_LIST: - default: - break; + case Topology::POINT_LIST: + m_primitiveType = MTLPrimitiveType::MTLPrimitiveTypePoint; + break; + case Topology::LINE_LIST: + case Topology::LINE_STRIP: + case Topology::LINE_LIST_WITH_ADJACENCY: + case Topology::LINE_STRIP_WITH_ADJACENCY: + m_primitiveType = MTLPrimitiveType::MTLPrimitiveTypeLine; + break; + case Topology::TRIANGLE_LIST: + case Topology::TRIANGLE_STRIP: + case Topology::TRIANGLE_LIST_WITH_ADJACENCY: + case Topology::TRIANGLE_STRIP_WITH_ADJACENCY: + m_primitiveType = MTLPrimitiveType::MTLPrimitiveTypeTriangle; + break; + case Topology::PATCH_LIST: + default: + break; } for (uint32_t i = 0; i < graphicsPipelineDesc.shaderNum; i++) { From 5cdb7e038d8dfa6a8221b87fd76b4f87c7c4c1f5 Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Fri, 6 Sep 2024 22:56:17 -0700 Subject: [PATCH 15/24] start working on command buffer --- Source/Metal/CommandAllocatorMTL.h | 36 ++++++++++++ Source/Metal/CommandAllocatorMTL.hpp | 20 +++++++ Source/Metal/CommandAllocatorMTL.mm | 28 +++++++++ Source/Metal/CommandBufferMTL.h | 27 ++++++--- Source/Metal/CommandBufferMTL.mm | 86 ++++++++++++++++++++++------ Source/Metal/PipelineMTL.h | 8 +-- 6 files changed, 177 insertions(+), 28 deletions(-) create mode 100644 Source/Metal/CommandAllocatorMTL.h create mode 100644 Source/Metal/CommandAllocatorMTL.hpp create mode 100644 Source/Metal/CommandAllocatorMTL.mm diff --git a/Source/Metal/CommandAllocatorMTL.h b/Source/Metal/CommandAllocatorMTL.h new file mode 100644 index 0000000..d10a47a --- /dev/null +++ b/Source/Metal/CommandAllocatorMTL.h @@ -0,0 +1,36 @@ +// © 2021 NVIDIA Corporation + +#pragma once + +namespace nri { + +struct DeviceMTL; +struct CommandQueueMTL; + +struct CommandAllocatorMTL { + inline CommandAllocatorMTL(DeviceMTL& device) + : m_Device(device) { + } + + inline DeviceMTL& GetDevice() const { + return m_Device; + } + + ~CommandAllocatorMTL(); + + + Result Create(const CommandQueue& commandQueue); + + //================================================================================================================ + // NRI + //================================================================================================================ + + Result CreateCommandBuffer(CommandBuffer*& commandBuffer); + +private: + struct CommandQueueMTL* m_CommandQueue; + DeviceMTL& m_Device; +}; + +} + diff --git a/Source/Metal/CommandAllocatorMTL.hpp b/Source/Metal/CommandAllocatorMTL.hpp new file mode 100644 index 0000000..bbad79e --- /dev/null +++ b/Source/Metal/CommandAllocatorMTL.hpp @@ -0,0 +1,20 @@ +// © 2021 NVIDIA Corporation + +#pragma region[ Core ] + +static void NRI_CALL SetCommandAllocatorDebugName(CommandAllocator& commandAllocator, const char* name) { + //((CommandAllocatorVK&)commandAllocator).SetDebugName(name); +} + +static Result NRI_CALL CreateCommandBuffer(CommandAllocator& commandAllocator, CommandBuffer*& commandBuffer) { + return ((CommandAllocatorMTL&)commandAllocator).CreateCommandBuffer(commandBuffer); +} + +static void NRI_CALL ResetCommandAllocator(CommandAllocator& commandAllocator) { + //((CommandAllocatorVK&)commandAllocator).Reset(); +} + +#pragma endregion + +Define_Core_CommandAllocator_PartiallyFillFunctionTable(VK); + diff --git a/Source/Metal/CommandAllocatorMTL.mm b/Source/Metal/CommandAllocatorMTL.mm new file mode 100644 index 0000000..9532664 --- /dev/null +++ b/Source/Metal/CommandAllocatorMTL.mm @@ -0,0 +1,28 @@ +#include "SharedMTL.h" + +#include "CommandAllocatorMTL.h" + +#include "CommandQueueMTL.h" + +using namespace nri; + +CommandAllocatorMTL::~CommandAllocatorMTL() { + +} + +Result CommandAllocatorMTL::Create(const CommandQueue& commandQueue) { + m_CommandQueue = &(CommandQueueMTL&)commandQueue; + return Result::SUCCESS; +} + +//================================================================================================================ +// NRI +//================================================================================================================ + +Result CommandAllocatorMTL::CreateCommandBuffer(CommandBuffer*& commandBuffer) { + + + return Result::SUCCESS; +} + +#include "CommandAllocatorMTL.hpp" diff --git a/Source/Metal/CommandBufferMTL.h b/Source/Metal/CommandBufferMTL.h index ce67085..a11de62 100644 --- a/Source/Metal/CommandBufferMTL.h +++ b/Source/Metal/CommandBufferMTL.h @@ -2,6 +2,7 @@ #pragma once +#include #import namespace nri { @@ -13,15 +14,18 @@ struct PipelineLayoutMTL; struct TextureMTL; struct DescriptorMTL; + +NriBits(CommandBufferDirtyBits, uint8_t, + NONE = 0, + CMD_DIRTY_STENCIL = NriBit(0) +); + struct CommandBufferMTL { + inline CommandBufferMTL(DeviceMTL& device) : m_Device(device) { } - - // inline operator VkCommandBuffer() const { - // return m_Handle; - // } - + inline DeviceMTL& GetDevice() const { return m_Device; } @@ -77,20 +81,27 @@ struct CommandBufferMTL { void DrawMeshTasksIndirect(const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride); ~CommandBufferMTL(); - + + void Create(id cmd); + struct CmdIndexBuffer { size_t m_Offset; MTLIndexType m_Type; struct BufferMTL* m_Buffer; }; + private: + + void updateCommandBufferState(); + DeviceMTL& m_Device; struct PipelineMTL* m_CurrentPipeline = nullptr; struct CmdIndexBuffer m_CurrentIndexCmd; id m_Handle; - id m_encoder; + id m_RendererEncoder = nil; + id m_ComputeEncoder = nil; - //id renderEncoder; + CommandBufferDirtyBits m_DirtyBits = CommandBufferDirtyBits::NONE; }; }; diff --git a/Source/Metal/CommandBufferMTL.mm b/Source/Metal/CommandBufferMTL.mm index 794126e..7cf41d3 100644 --- a/Source/Metal/CommandBufferMTL.mm +++ b/Source/Metal/CommandBufferMTL.mm @@ -26,9 +26,11 @@ } Result CommandBufferMTL::Begin(const DescriptorPool* descriptorPool) { - + [m_Handle computeCommandEncoderWithDescriptor: NULL]; } Result CommandBufferMTL::End() { + m_ComputeEncoder = nil; + m_RendererEncoder = nil; } void CommandBufferMTL::SetPipeline(const Pipeline& pipeline) { @@ -36,7 +38,14 @@ return; PipelineMTL& pipelineImpl = (PipelineMTL&)pipeline; m_CurrentPipeline = &pipelineImpl; - + + switch(m_CurrentPipeline->m_pipelineType) { + case nri::PipelineMTL::Compute: + m_ComputeEncoder = [m_Handle computeCommandEncoderWithDescriptor: NULL]; + break; + default: + break; + } } void CommandBufferMTL::SetPipelineLayout(const PipelineLayout& pipelineLayout) {} @@ -45,19 +54,46 @@ void CommandBufferMTL::SetDescriptorPool(const DescriptorPool& descriptorPool) {} void CommandBufferMTL::Barrier(const BarrierGroupDesc& barrierGroupDesc) {} void CommandBufferMTL::BeginRendering(const AttachmentsDesc& attachmentsDesc) { - m_encoder = [m_Handle renderCommandEncoderWithDescriptor: NULL]; + m_RendererEncoder = [m_Handle renderCommandEncoderWithDescriptor: NULL]; } void CommandBufferMTL::EndRendering() { - [m_encoder endEncoding]; + [m_RendererEncoder endEncoding]; + m_RendererEncoder = nil; + m_ComputeEncoder = nil; } void CommandBufferMTL::SetViewports(const Viewport* viewports, uint32_t viewportNum) {} -void CommandBufferMTL::SetScissors(const Rect* rects, uint32_t rectNum) {} -void CommandBufferMTL::SetDepthBounds(float boundsMin, float boundsMax) {} -void CommandBufferMTL::SetStencilReference(uint8_t frontRef, uint8_t backRef) {} -void CommandBufferMTL::SetSamplePositions(const SamplePosition* positions, Sample_t positionNum, Sample_t sampleNum) {} -void CommandBufferMTL::SetBlendConstants(const Color32f& color) {} -void CommandBufferMTL::SetShadingRate(const ShadingRateDesc& shadingRateDesc) {} -void CommandBufferMTL::ClearAttachments(const ClearDesc* clearDescs, uint32_t clearDescNum, const Rect* rects, uint32_t rectNum) {} +void CommandBufferMTL::SetScissors(const Rect* rects, uint32_t rectNum) { + NSCAssert(m_RendererEncoder, @"encoder set"); + MTLScissorRect rect; + rect.x = rects[rectNum].x; + rect.y = rects[rectNum].y; + rect.width = rects[rectNum].width; + rect.height = rects[rectNum].height; + [m_RendererEncoder setScissorRect:rect]; +} +void CommandBufferMTL::SetDepthBounds(float boundsMin, float boundsMax) { +} +void CommandBufferMTL::SetStencilReference(uint8_t frontRef, uint8_t backRef) { + [m_RendererEncoder setStencilFrontReferenceValue: frontRef backReferenceValue:backRef]; +} +void CommandBufferMTL::SetSamplePositions(const SamplePosition* positions, Sample_t positionNum, Sample_t sampleNum) { + +} +void CommandBufferMTL::SetBlendConstants(const Color32f& color) { + [m_RendererEncoder + setBlendColorRed:color.x + green:color.y + blue:color.z + alpha:color.w + ]; +} +void CommandBufferMTL::SetShadingRate(const ShadingRateDesc& shadingRateDesc) { + +} + +void CommandBufferMTL::ClearAttachments(const ClearDesc* clearDescs, uint32_t clearDescNum, const Rect* rects, uint32_t rectNum) { +} + void CommandBufferMTL::SetIndexBuffer(const Buffer& buffer, uint64_t offset, IndexType indexType) { m_CurrentIndexCmd.m_Buffer = &(BufferMTL&)buffer; switch(indexType) { @@ -71,19 +107,28 @@ } m_CurrentIndexCmd.m_Offset = offset; } + void CommandBufferMTL::SetVertexBuffers(uint32_t baseSlot, uint32_t bufferNum, const Buffer* const* buffers, const uint64_t* offsets) { + for(size_t i = 0; i < bufferNum; i++) { + BufferMTL* mtlBuffer = (BufferMTL*)buffers[i]; + [m_RendererEncoder setVertexBuffer: mtlBuffer->GetHandle() + offset: offsets[i] + atIndex: i + baseSlot]; + } } + void CommandBufferMTL::Draw(const DrawDesc& drawDesc) { - [m_encoder drawPrimitives: m_CurrentPipeline->m_primitiveType + [m_RendererEncoder drawPrimitives: m_CurrentPipeline->m_primitiveType vertexStart:drawDesc.baseVertex vertexCount:drawDesc.vertexNum instanceCount:drawDesc.instanceNum baseInstance:0]; } + void CommandBufferMTL::DrawIndexed(const DrawIndexedDesc& drawIndexedDesc) { id indexBuffer = m_CurrentIndexCmd.m_Buffer->GetHandle(); - [m_encoder drawIndexedPrimitives: m_CurrentPipeline->m_primitiveType + [m_RendererEncoder drawIndexedPrimitives: m_CurrentPipeline->m_primitiveType indexCount:drawIndexedDesc.indexNum indexType: m_CurrentIndexCmd.m_Type indexBuffer: indexBuffer @@ -91,8 +136,9 @@ } void CommandBufferMTL::DrawIndirect(const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) { + // TODO: implement count Buffer NSCAssert(!countBuffer, @"count buffer not supported"); - [m_encoder + [m_RendererEncoder drawPrimitives: m_CurrentPipeline->m_primitiveType indirectBuffer:((BufferMTL&)buffer).GetHandle() indirectBufferOffset: offset]; @@ -101,7 +147,9 @@ void CommandBufferMTL::DrawIndexedIndirect(const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) { } -void CommandBufferMTL::Dispatch(const DispatchDesc& dispatchDesc) {} +void CommandBufferMTL::Dispatch(const DispatchDesc& dispatchDesc) { + +} void CommandBufferMTL::DispatchIndirect(const Buffer& buffer, uint64_t offset) {} void CommandBufferMTL::BeginQuery(const QueryPool& queryPool, uint32_t offset) {} void CommandBufferMTL::EndQuery(const QueryPool& queryPool, uint32_t offset) {} @@ -124,7 +172,13 @@ void CommandBufferMTL::DispatchRays(const DispatchRaysDesc& dispatchRaysDesc) {} void CommandBufferMTL::DispatchRaysIndirect(const Buffer& buffer, uint64_t offset) {} void CommandBufferMTL::DrawMeshTasks(const DrawMeshTasksDesc& drawMeshTasksDesc) {} -void CommandBufferMTL::DrawMeshTasksIndirect(const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride) {} +void CommandBufferMTL::DrawMeshTasksIndirect(const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride) { + +} + +void Create(id cmd); + + #include "CommandBufferMTL.hpp" diff --git a/Source/Metal/PipelineMTL.h b/Source/Metal/PipelineMTL.h index b274bc4..2d2d3d9 100644 --- a/Source/Metal/PipelineMTL.h +++ b/Source/Metal/PipelineMTL.h @@ -8,10 +8,9 @@ struct DeviceMTL; struct PipelineLayoutMTL; struct PipelineMTL { - enum PiplineType { - None, - Graphics, + enum PipelineType { Compute, + Graphics, Raytracing }; @@ -23,7 +22,8 @@ struct PipelineMTL { Result Create(const GraphicsPipelineDesc& graphicsPipelineDesc); Result Create(const ComputePipelineDesc& computePipelineDesc); Result Create(const RayTracingPipelineDesc& rayTracingPipelineDesc); - + + PipelineType m_pipelineType; MTLPrimitiveTopologyClass m_topologyClass; MTLPrimitiveType m_primitiveType; private: From 2c3918e74956b0d497b2f218d4cc692ac59e10ac Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Sun, 8 Sep 2024 10:52:08 -0700 Subject: [PATCH 16/24] feat: begin shader load logic Signed-off-by: Michael Pollind --- Source/Metal/CommandBufferMTL.mm | 67 ++++++++++++++++++++++++++------ Source/Metal/CommandQueueMTL.h | 10 +++++ Source/Metal/PipelineMTL.h | 12 +++--- Source/Metal/PipelineMTL.mm | 14 +++++++ 4 files changed, 86 insertions(+), 17 deletions(-) diff --git a/Source/Metal/CommandBufferMTL.mm b/Source/Metal/CommandBufferMTL.mm index 7cf41d3..2810030 100644 --- a/Source/Metal/CommandBufferMTL.mm +++ b/Source/Metal/CommandBufferMTL.mm @@ -39,20 +39,59 @@ PipelineMTL& pipelineImpl = (PipelineMTL&)pipeline; m_CurrentPipeline = &pipelineImpl; - switch(m_CurrentPipeline->m_pipelineType) { - case nri::PipelineMTL::Compute: - m_ComputeEncoder = [m_Handle computeCommandEncoderWithDescriptor: NULL]; - break; - default: - break; - } +// if(m_CurrentPipeline->m_pipelineType == nri::PipelineMTL::Compute) { + // m_ComputeEncoder = [m_Handle computeCommandEncoderWithDescriptor: NULL]; + // } + +} +void CommandBufferMTL::SetPipelineLayout(const PipelineLayout& pipelineLayout) { + +} +void CommandBufferMTL::SetDescriptorSet(uint32_t setIndexInPipelineLayout, const DescriptorSet& descriptorSet, const uint32_t* dynamicConstantBufferOffsets) { + +} +void CommandBufferMTL::SetConstants(uint32_t pushConstantIndex, const void* data, uint32_t size) { + //if (pDesc->mUsedStages & SHADER_STAGE_VERT) + //{ + // [m_RendererEncoder setVertexBytes:data length:size atIndex:pushConstantIndex]; + //} + + //if (pDesc->mUsedStages & SHADER_STAGE_FRAG) + //{ + // [m_RendererEncoder setFragmentBytes:data length:size atIndex:pushConstantIndex]; + //} + + //if (pDesc->mUsedStages & SHADER_STAGE_COMP) + //{ + // [m_RendererEncoder setBytes:data length:size atIndex:pushConstantIndex]; + //} } -void CommandBufferMTL::SetPipelineLayout(const PipelineLayout& pipelineLayout) {} -void CommandBufferMTL::SetDescriptorSet(uint32_t setIndexInPipelineLayout, const DescriptorSet& descriptorSet, const uint32_t* dynamicConstantBufferOffsets) {} -void CommandBufferMTL::SetConstants(uint32_t pushConstantIndex, const void* data, uint32_t size) {} void CommandBufferMTL::SetDescriptorPool(const DescriptorPool& descriptorPool) {} -void CommandBufferMTL::Barrier(const BarrierGroupDesc& barrierGroupDesc) {} +void CommandBufferMTL::Barrier(const BarrierGroupDesc& barrierGroupDesc) { + //if (pCmd->pQueue->mBarrierFlags & BARRIER_FLAG_BUFFERS) + { + [m_RendererEncoder memoryBarrierWithScope:MTLBarrierScopeBuffers + afterStages:MTLRenderStageFragment + beforeStages:MTLRenderStageVertex]; + } + + //if (pCmd->pQueue->mBarrierFlags & BARRIER_FLAG_TEXTURES) + { + [m_RendererEncoder memoryBarrierWithScope:MTLBarrierScopeTextures + afterStages:MTLRenderStageFragment + beforeStages:MTLRenderStageVertex]; + } + + //if (pCmd->pQueue->mBarrierFlags & BARRIER_FLAG_RENDERTARGETS) + { + [m_RendererEncoder memoryBarrierWithScope:MTLBarrierScopeRenderTargets + afterStages:MTLRenderStageFragment + beforeStages:MTLRenderStageVertex]; + } + + +} void CommandBufferMTL::BeginRendering(const AttachmentsDesc& attachmentsDesc) { m_RendererEncoder = [m_Handle renderCommandEncoderWithDescriptor: NULL]; } @@ -61,7 +100,11 @@ m_RendererEncoder = nil; m_ComputeEncoder = nil; } -void CommandBufferMTL::SetViewports(const Viewport* viewports, uint32_t viewportNum) {} +void CommandBufferMTL::SetViewports(const Viewport* viewports, uint32_t viewportNum) { + MTLViewport* mtlViewports = StackAlloc(MTLViewport, viewportNum); + + // [m_RendererEncoder setViewports:<#(const MTLViewport * _Nonnull)#> count:<#(NSUInteger)#> +} void CommandBufferMTL::SetScissors(const Rect* rects, uint32_t rectNum) { NSCAssert(m_RendererEncoder, @"encoder set"); MTLScissorRect rect; diff --git a/Source/Metal/CommandQueueMTL.h b/Source/Metal/CommandQueueMTL.h index 7d48be9..3be4838 100644 --- a/Source/Metal/CommandQueueMTL.h +++ b/Source/Metal/CommandQueueMTL.h @@ -7,6 +7,13 @@ namespace nri { struct DeviceMTL; +NriBits(QueueBarrierBits, uint8_t, + NONE = 0, + BARRIER_FLAG_BUFFERS = NriBit(0), + BARRIER_FLAG_TEXTURES = NriBit(1), + BARRIER_FLAG_RENDERTARGETS = NriBit(2), + BARRIER_FLAG_FENCE = NriBit(3)); + struct CommandQueueMTL { inline CommandQueueMTL(DeviceMTL& device) @@ -35,11 +42,14 @@ struct CommandQueueMTL { void SetDebugName(const char* name); Result Create(CommandQueueType type); + QueueBarrierBits m_BarrierBits = QueueBarrierBits::NONE; + private: DeviceMTL& m_Device; CommandQueueType m_Type = CommandQueueType(-1); id m_Handle; Lock m_Lock; + }; } diff --git a/Source/Metal/PipelineMTL.h b/Source/Metal/PipelineMTL.h index 2d2d3d9..785f948 100644 --- a/Source/Metal/PipelineMTL.h +++ b/Source/Metal/PipelineMTL.h @@ -7,12 +7,13 @@ namespace nri { struct DeviceMTL; struct PipelineLayoutMTL; +NriEnum(PipelineType, uint8_t, + Compute, + Graphics, + Raytracing +); + struct PipelineMTL { - enum PipelineType { - Compute, - Graphics, - Raytracing - }; inline PipelineMTL(DeviceMTL& device) : m_Device(device) { @@ -26,6 +27,7 @@ struct PipelineMTL { PipelineType m_pipelineType; MTLPrimitiveTopologyClass m_topologyClass; MTLPrimitiveType m_primitiveType; + StageBits m_usedBits; private: DeviceMTL& m_Device; }; diff --git a/Source/Metal/PipelineMTL.mm b/Source/Metal/PipelineMTL.mm index 77418aa..49d9876 100644 --- a/Source/Metal/PipelineMTL.mm +++ b/Source/Metal/PipelineMTL.mm @@ -43,6 +43,20 @@ } for (uint32_t i = 0; i < graphicsPipelineDesc.shaderNum; i++) { + const ShaderDesc& shader = graphicsPipelineDesc.shaders[i]; + m_usedBits |= shader.stage; + + dispatch_data_t byteCode = + dispatch_data_create(shader.bytecode, shader.size, nil, + DISPATCH_DATA_DESTRUCTOR_DEFAULT); + id lib = [m_Device newLibraryWithData:byteCode error:nil]; + + // Create a MTLFunction from the loaded MTLLibrary. + NSString *entryPointNStr = [lib functionNames][0]; + if (shader.entryPointName) { + entryPointNStr = + [[NSString alloc] initWithUTF8String:shader.entryPointName]; + } } // Depth-stencil const DepthAttachmentDesc& da = graphicsPipelineDesc.outputMerger.depth; From f0de1b2eb5a04c0b050a88e89b44ac50908bfb86 Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Tue, 1 Oct 2024 13:03:07 -0700 Subject: [PATCH 17/24] fix compiling errors --- Include/NRIDescs.h | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/Include/NRIDescs.h b/Include/NRIDescs.h index 9131f66..e7cbcd0 100644 --- a/Include/NRIDescs.h +++ b/Include/NRIDescs.h @@ -75,7 +75,8 @@ NriEnum(GraphicsAPI, uint8_t, NONE, // Supports everything, does nothing, returns dummy non-NULL objects and ~0-filled descs, available if "NRI_ENABLE_NONE_SUPPORT = ON" in CMake D3D11, // Direct3D 11 (feature set 11.1), available if "NRI_ENABLE_D3D11_SUPPORT = ON" in CMake D3D12, // Direct3D 12 (feature set 11.1+), available if "NRI_ENABLE_D3D12_SUPPORT = ON" in CMake - VK // Vulkan 1.3 or 1.2+ (can be used on MacOS via MoltenVK), available if "NRI_ENABLE_VK_SUPPORT = ON" in CMake + VK, // Vulkan 1.3 or 1.2+ (can be used on MacOS via MoltenVK), available if "NRI_ENABLE_VK_SUPPORT = ON" in CMake + MTL ); NriEnum(Result, uint8_t, @@ -1283,13 +1284,6 @@ NriStruct(PipelineStatisticsDesc) { #pragma region [ Device desc ] //============================================================================================================================================================================================ -NriEnum(GraphicsAPI, uint8_t, - D3D11, - D3D12, - VK, - MTL -); - // defined in apple framework #undef INTEL #undef AMD From b027a7573c4520b2e0d2bdaf3d7ae41b12f8215c Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Tue, 1 Oct 2024 20:20:47 -0700 Subject: [PATCH 18/24] feat: cleanup Signed-off-by: Michael Pollind --- Source/Metal/CommandBufferMTL.mm | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/Source/Metal/CommandBufferMTL.mm b/Source/Metal/CommandBufferMTL.mm index 2810030..4dbadb6 100644 --- a/Source/Metal/CommandBufferMTL.mm +++ b/Source/Metal/CommandBufferMTL.mm @@ -2,15 +2,12 @@ #include "CommandBufferMTL.h" -//#include "AccelerationStructureVK.h" #include "BufferMTL.h" #include "CommandBufferMTL.h" #include "CommandQueueMTL.h" -//#include "DescriptorSetMTL.h" #include "DescriptorMTL.h" #include "PipelineLayoutMTL.h" #include "PipelineMTL.h" -//#include "QueryPoolMTL.h" #include "TextureMTL.h" #include @@ -28,11 +25,13 @@ Result CommandBufferMTL::Begin(const DescriptorPool* descriptorPool) { [m_Handle computeCommandEncoderWithDescriptor: NULL]; } + Result CommandBufferMTL::End() { m_ComputeEncoder = nil; m_RendererEncoder = nil; } + void CommandBufferMTL::SetPipeline(const Pipeline& pipeline) { if (m_CurrentPipeline == (PipelineMTL*)&pipeline) return; @@ -93,6 +92,15 @@ } void CommandBufferMTL::BeginRendering(const AttachmentsDesc& attachmentsDesc) { + MTLRenderPassDescriptor* renderPassDescriptor = [MTLRenderPassDescriptor renderPassDescriptor]; + for(uint32_t i = 0; i < attachmentsDesc.colorNum; i++) { + + } + + //renderPassDescriptor.colorAttachments[ + + //renderPassDescriptor.colorAttachments + m_RendererEncoder = [m_Handle renderCommandEncoderWithDescriptor: NULL]; } void CommandBufferMTL::EndRendering() { @@ -182,10 +190,9 @@ // TODO: implement count Buffer NSCAssert(!countBuffer, @"count buffer not supported"); [m_RendererEncoder - drawPrimitives: m_CurrentPipeline->m_primitiveType - indirectBuffer:((BufferMTL&)buffer).GetHandle() + drawPrimitives: m_CurrentPipeline->m_primitiveType + indirectBuffer:((BufferMTL&)buffer).GetHandle() indirectBufferOffset: offset]; - } void CommandBufferMTL::DrawIndexedIndirect(const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) { From 56016017465e3a0b243e2501b8a0d363836f4346 Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Wed, 13 Nov 2024 22:09:00 -0800 Subject: [PATCH 19/24] feat: fix compiling errors Signed-off-by: Michael Pollind --- Include/NRIDescs.h | 5 + Source/Creation/Creation.cpp | 4 +- Source/Metal/CommandAllocatorMTL.hpp | 1 - Source/Metal/CommandBufferMTL.h | 2 +- Source/Metal/CommandBufferMTL.hpp | 354 +++++++++++++-------------- Source/Metal/CommandBufferMTL.mm | 7 +- Source/Metal/ConversionMTL.h | 82 +++++++ Source/Metal/ConversionMTL.mm | 5 +- Source/Metal/DeviceMTL.hpp | 29 +-- Source/Metal/ImplMTL.mm | 0 Source/Metal/PipelineMTL.mm | 42 ++-- 11 files changed, 316 insertions(+), 215 deletions(-) create mode 100644 Source/Metal/ImplMTL.mm diff --git a/Include/NRIDescs.h b/Include/NRIDescs.h index e7cbcd0..04227ee 100644 --- a/Include/NRIDescs.h +++ b/Include/NRIDescs.h @@ -685,9 +685,14 @@ NriStruct(VertexAttributeVK) { uint32_t location; }; +NriStruct(VertexAttributeMTL) { + uint32_t location; +}; + NriStruct(VertexAttributeDesc) { Nri(VertexAttributeD3D) d3d; Nri(VertexAttributeVK) vk; + Nri(VertexAttributeMTL) mtl; uint32_t offset; Nri(Format) format; uint16_t streamIndex; diff --git a/Source/Creation/Creation.cpp b/Source/Creation/Creation.cpp index ad81f93..68e704c 100644 --- a/Source/Creation/Creation.cpp +++ b/Source/Creation/Creation.cpp @@ -23,7 +23,7 @@ Result CreateDeviceMTL(const DeviceCreationDesc& deviceCreationDesc, DeviceBase* Result CreateDeviceMTL(const DeviceCreationMTLDesc& deviceCreationDesc, DeviceBase*& device); #endif -#if NRI_USE_VULKAN +#if NRI_USE_VK Result CreateDeviceVK(const DeviceCreationDesc& deviceCreationDesc, DeviceBase*& device); Result CreateDeviceVK(const DeviceCreationVKDesc& deviceDesc, DeviceBase*& device); #endif @@ -276,7 +276,7 @@ NRI_API Format NRI_CALL nriConvertDXGIFormatToNRI(uint32_t dxgiFormat) { NRI_API uint32_t NRI_CALL nriConvertNRIFormatToMTL(Format format) { MaybeUnused(format); -#if NRI_USE_VULKAN +#if NRI_USE_VK return NRIFormatToMTLFormat(format); #else return 0; diff --git a/Source/Metal/CommandAllocatorMTL.hpp b/Source/Metal/CommandAllocatorMTL.hpp index bbad79e..0239d98 100644 --- a/Source/Metal/CommandAllocatorMTL.hpp +++ b/Source/Metal/CommandAllocatorMTL.hpp @@ -16,5 +16,4 @@ static void NRI_CALL ResetCommandAllocator(CommandAllocator& commandAllocator) { #pragma endregion -Define_Core_CommandAllocator_PartiallyFillFunctionTable(VK); diff --git a/Source/Metal/CommandBufferMTL.h b/Source/Metal/CommandBufferMTL.h index a11de62..ac450a6 100644 --- a/Source/Metal/CommandBufferMTL.h +++ b/Source/Metal/CommandBufferMTL.h @@ -45,7 +45,7 @@ struct CommandBufferMTL { void SetScissors(const Rect* rects, uint32_t rectNum); void SetDepthBounds(float boundsMin, float boundsMax); void SetStencilReference(uint8_t frontRef, uint8_t backRef); - void SetSamplePositions(const SamplePosition* positions, Sample_t positionNum, Sample_t sampleNum); + // void SetSamplePositions(const SamplePosition* positions, Sample_t positionNum, Sample_t sampleNum); void SetBlendConstants(const Color32f& color); void SetShadingRate(const ShadingRateDesc& shadingRateDesc); void ClearAttachments(const ClearDesc* clearDescs, uint32_t clearDescNum, const Rect* rects, uint32_t rectNum); diff --git a/Source/Metal/CommandBufferMTL.hpp b/Source/Metal/CommandBufferMTL.hpp index 7aa867b..17f4af4 100644 --- a/Source/Metal/CommandBufferMTL.hpp +++ b/Source/Metal/CommandBufferMTL.hpp @@ -1,179 +1,179 @@ -#pragma region[ Core ] - -static void NRI_CALL SetCommandBufferDebugName(CommandBuffer& commandBuffer, const char* name) { - ((CommandBufferMTL&)commandBuffer).SetDebugName(name); -} - -static Result NRI_CALL BeginCommandBuffer(CommandBuffer& commandBuffer, const DescriptorPool* descriptorPool) { - return ((CommandBufferMTL&)commandBuffer).Begin(descriptorPool); -} - -static Result NRI_CALL EndCommandBuffer(CommandBuffer& commandBuffer) { - return ((CommandBufferMTL&)commandBuffer).End(); -} - -static void NRI_CALL CmdSetPipelineLayout(CommandBuffer& commandBuffer, const PipelineLayout& pipelineLayout) { - ((CommandBufferMTL&)commandBuffer).SetPipelineLayout(pipelineLayout); -} - -static void NRI_CALL CmdSetPipeline(CommandBuffer& commandBuffer, const Pipeline& pipeline) { - ((CommandBufferMTL&)commandBuffer).SetPipeline(pipeline); -} - -static void NRI_CALL CmdBarrier(CommandBuffer& commandBuffer, const BarrierGroupDesc& barrierGroupDesc) { - ((CommandBufferMTL&)commandBuffer).Barrier(barrierGroupDesc); -} - -static void NRI_CALL CmdSetDescriptorPool(CommandBuffer& commandBuffer, const DescriptorPool& descriptorPool) { - ((CommandBufferMTL&)commandBuffer).SetDescriptorPool(descriptorPool); -} - -static void NRI_CALL CmdSetDescriptorSet(CommandBuffer& commandBuffer, uint32_t setIndexInPipelineLayout, const DescriptorSet& descriptorSet, const uint32_t* dynamicConstantBufferOffsets) { - ((CommandBufferMTL&)commandBuffer).SetDescriptorSet(setIndexInPipelineLayout, descriptorSet, dynamicConstantBufferOffsets); -} - -static void NRI_CALL CmdSetConstants(CommandBuffer& commandBuffer, uint32_t pushConstantIndex, const void* data, uint32_t size) { - ((CommandBufferMTL&)commandBuffer).SetConstants(pushConstantIndex, data, size); -} - -static void NRI_CALL CmdBeginRendering(CommandBuffer& commandBuffer, const AttachmentsDesc& attachmentsDesc) { - ((CommandBufferMTL&)commandBuffer).BeginRendering(attachmentsDesc); -} - -static void NRI_CALL CmdEndRendering(CommandBuffer& commandBuffer) { - ((CommandBufferMTL&)commandBuffer).EndRendering(); -} - -static void NRI_CALL CmdSetViewports(CommandBuffer& commandBuffer, const Viewport* viewports, uint32_t viewportNum) { - ((CommandBufferMTL&)commandBuffer).SetViewports(viewports, viewportNum); -} - -static void NRI_CALL CmdSetScissors(CommandBuffer& commandBuffer, const nri::Rect* rects, uint32_t rectNum) { - ((CommandBufferMTL&)commandBuffer).SetScissors(rects, rectNum); -} - -static void NRI_CALL CmdSetDepthBounds(CommandBuffer& commandBuffer, float boundsMin, float boundsMax) { - ((CommandBufferMTL&)commandBuffer).SetDepthBounds(boundsMin, boundsMax); -} - -static void NRI_CALL CmdSetStencilReference(CommandBuffer& commandBuffer, uint8_t frontRef, uint8_t backRef) { - ((CommandBufferMTL&)commandBuffer).SetStencilReference(frontRef, backRef); -} - -static void NRI_CALL CmdSetSamplePositions(CommandBuffer& commandBuffer, const SamplePosition* positions, Sample_t positionNum, Sample_t sampleNum) { - ((CommandBufferMTL&)commandBuffer).SetSamplePositions(positions, positionNum, sampleNum); -} - -static void NRI_CALL CmdSetBlendConstants(CommandBuffer& commandBuffer, const Color32f& color) { - ((CommandBufferMTL&)commandBuffer).SetBlendConstants(color); -} - -static void NRI_CALL CmdSetShadingRate(CommandBuffer& commandBuffer, const ShadingRateDesc& shadingRateDesc) { - ((CommandBufferMTL&)commandBuffer).SetShadingRate(shadingRateDesc); -} - -static void NRI_CALL CmdSetDepthBias(CommandBuffer& commandBuffer, const DepthBiasDesc& depthBiasDesc) { - //((CommandBufferMTL&)commandBuffer).SetDepthBias(depthBiasDesc); -} - -static void NRI_CALL CmdClearAttachments(CommandBuffer& commandBuffer, const ClearDesc* clearDescs, uint32_t clearDescNum, const nri::Rect* rects, uint32_t rectNum) { - ((CommandBufferMTL&)commandBuffer).ClearAttachments(clearDescs, clearDescNum, rects, rectNum); -} - -static void NRI_CALL CmdSetIndexBuffer(CommandBuffer& commandBuffer, const Buffer& buffer, uint64_t offset, IndexType indexType) { - ((CommandBufferMTL&)commandBuffer).SetIndexBuffer(buffer, offset, indexType); -} - -static void NRI_CALL CmdSetVertexBuffers(CommandBuffer& commandBuffer, uint32_t baseSlot, uint32_t bufferNum, const Buffer* const* buffers, const uint64_t* offsets) { - ((CommandBufferMTL&)commandBuffer).SetVertexBuffers(baseSlot, bufferNum, buffers, offsets); -} - -static void NRI_CALL CmdDraw(CommandBuffer& commandBuffer, const DrawDesc& drawDesc) { - ((CommandBufferMTL&)commandBuffer).Draw(drawDesc); -} - -static void NRI_CALL CmdDrawIndexed(CommandBuffer& commandBuffer, const DrawIndexedDesc& drawIndexedDesc) { - ((CommandBufferMTL&)commandBuffer).DrawIndexed(drawIndexedDesc); -} - -static void NRI_CALL CmdDrawIndirect(CommandBuffer& commandBuffer, const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) { - ((CommandBufferMTL&)commandBuffer).DrawIndirect(buffer, offset, drawNum, stride, countBuffer, countBufferOffset); -} - -static void NRI_CALL CmdDrawIndexedIndirect(CommandBuffer& commandBuffer, const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) { - ((CommandBufferMTL&)commandBuffer).DrawIndexedIndirect(buffer, offset, drawNum, stride, countBuffer, countBufferOffset); -} - -static void NRI_CALL CmdDispatch(CommandBuffer& commandBuffer, const DispatchDesc& dispatchDesc) { - ((CommandBufferMTL&)commandBuffer).Dispatch(dispatchDesc); -} - -static void NRI_CALL CmdDispatchIndirect(CommandBuffer& commandBuffer, const Buffer& buffer, uint64_t offset) { - ((CommandBufferMTL&)commandBuffer).DispatchIndirect(buffer, offset); -} - -static void NRI_CALL CmdBeginQuery(CommandBuffer& commandBuffer, const QueryPool& queryPool, uint32_t offset) { - ((CommandBufferMTL&)commandBuffer).BeginQuery(queryPool, offset); -} - -static void NRI_CALL CmdEndQuery(CommandBuffer& commandBuffer, const QueryPool& queryPool, uint32_t offset) { - ((CommandBufferMTL&)commandBuffer).EndQuery(queryPool, offset); -} - -static void NRI_CALL CmdBeginAnnotation(CommandBuffer& commandBuffer, const char* name) { - ((CommandBufferMTL&)commandBuffer).BeginAnnotation(name); -} - -static void NRI_CALL CmdEndAnnotation(CommandBuffer& commandBuffer) { - ((CommandBufferMTL&)commandBuffer).EndAnnotation(); -} - -static void NRI_CALL CmdClearStorageBuffer(CommandBuffer& commandBuffer, const ClearStorageBufferDesc& clearDesc) { - ((CommandBufferMTL&)commandBuffer).ClearStorageBuffer(clearDesc); -} - -static void NRI_CALL CmdClearStorageTexture(CommandBuffer& commandBuffer, const ClearStorageTextureDesc& clearDesc) { - ((CommandBufferMTL&)commandBuffer).ClearStorageTexture(clearDesc); -} - -static void NRI_CALL CmdCopyBuffer(CommandBuffer& commandBuffer, Buffer& dstBuffer, uint64_t dstOffset, const Buffer& srcBuffer, uint64_t srcOffset, uint64_t size) { - ((CommandBufferMTL&)commandBuffer).CopyBuffer(dstBuffer, dstOffset, srcBuffer, srcOffset, size); -} - -static void NRI_CALL CmdCopyTexture( - CommandBuffer& commandBuffer, Texture& dstTexture, const TextureRegionDesc* dstRegionDesc, const Texture& srcTexture, const TextureRegionDesc* srcRegionDesc) { - ((CommandBufferMTL&)commandBuffer).CopyTexture(dstTexture, dstRegionDesc, srcTexture, srcRegionDesc); -} - -static void NRI_CALL CmdUploadBufferToTexture(CommandBuffer& commandBuffer, Texture& dstTexture, const TextureRegionDesc& dstRegionDesc, const Buffer& srcBuffer, const TextureDataLayoutDesc& srcDataLayoutDesc) { - ((CommandBufferMTL&)commandBuffer).UploadBufferToTexture(dstTexture, dstRegionDesc, srcBuffer, srcDataLayoutDesc); -} - -static void NRI_CALL CmdReadbackTextureToBuffer(CommandBuffer& commandBuffer, Buffer& dstBuffer, const TextureDataLayoutDesc& dstDataLayoutDesc, const Texture& srcTexture, const TextureRegionDesc& srcRegionDesc) { - //((CommandBufferMTL&)commandBuffer).ReadbackTextureToBuffer(dstBuffer, dstDataLayoutDesc, srcTexture, srcRegionDesc); -} - -static void NRI_CALL CmdCopyQueries(CommandBuffer& commandBuffer, const QueryPool& queryPool, uint32_t offset, uint32_t num, Buffer& dstBuffer, uint64_t dstOffset) { - ((CommandBufferMTL&)commandBuffer).CopyQueries(queryPool, offset, num, dstBuffer, dstOffset); -} - -static void NRI_CALL CmdResetQueries(CommandBuffer& commandBuffer, const QueryPool& queryPool, uint32_t offset, uint32_t num) { - ((CommandBufferMTL&)commandBuffer).ResetQueries(queryPool, offset, num); -} - -static void* NRI_CALL GetCommandBufferNativeObject(const CommandBuffer& commandBuffer) { - if (!(&commandBuffer)) - return nullptr; - - return nullptr; - // return (CommandBufferMTL)((CommandBufferMTL&)commandBuffer); -} - -#pragma endregion - - - - -Define_Core_CommandBuffer_PartiallyFillFunctionTable(VK); +//#pragma region[ Core ] +// +//static void NRI_CALL SetCommandBufferDebugName(CommandBuffer& commandBuffer, const char* name) { +// ((CommandBufferMTL&)commandBuffer).SetDebugName(name); +//} +// +//static Result NRI_CALL BeginCommandBuffer(CommandBuffer& commandBuffer, const DescriptorPool* descriptorPool) { +// return ((CommandBufferMTL&)commandBuffer).Begin(descriptorPool); +//} +// +//static Result NRI_CALL EndCommandBuffer(CommandBuffer& commandBuffer) { +// return ((CommandBufferMTL&)commandBuffer).End(); +//} +// +//static void NRI_CALL CmdSetPipelineLayout(CommandBuffer& commandBuffer, const PipelineLayout& pipelineLayout) { +// ((CommandBufferMTL&)commandBuffer).SetPipelineLayout(pipelineLayout); +//} +// +//static void NRI_CALL CmdSetPipeline(CommandBuffer& commandBuffer, const Pipeline& pipeline) { +// ((CommandBufferMTL&)commandBuffer).SetPipeline(pipeline); +//} +// +//static void NRI_CALL CmdBarrier(CommandBuffer& commandBuffer, const BarrierGroupDesc& barrierGroupDesc) { +// ((CommandBufferMTL&)commandBuffer).Barrier(barrierGroupDesc); +//} +// +//static void NRI_CALL CmdSetDescriptorPool(CommandBuffer& commandBuffer, const DescriptorPool& descriptorPool) { +// ((CommandBufferMTL&)commandBuffer).SetDescriptorPool(descriptorPool); +//} +// +//static void NRI_CALL CmdSetDescriptorSet(CommandBuffer& commandBuffer, uint32_t setIndexInPipelineLayout, const DescriptorSet& descriptorSet, const uint32_t* dynamicConstantBufferOffsets) { +// ((CommandBufferMTL&)commandBuffer).SetDescriptorSet(setIndexInPipelineLayout, descriptorSet, dynamicConstantBufferOffsets); +//} +// +//static void NRI_CALL CmdSetConstants(CommandBuffer& commandBuffer, uint32_t pushConstantIndex, const void* data, uint32_t size) { +// ((CommandBufferMTL&)commandBuffer).SetConstants(pushConstantIndex, data, size); +//} +// +//static void NRI_CALL CmdBeginRendering(CommandBuffer& commandBuffer, const AttachmentsDesc& attachmentsDesc) { +// ((CommandBufferMTL&)commandBuffer).BeginRendering(attachmentsDesc); +//} +// +//static void NRI_CALL CmdEndRendering(CommandBuffer& commandBuffer) { +// ((CommandBufferMTL&)commandBuffer).EndRendering(); +//} +// +//static void NRI_CALL CmdSetViewports(CommandBuffer& commandBuffer, const Viewport* viewports, uint32_t viewportNum) { +// ((CommandBufferMTL&)commandBuffer).SetViewports(viewports, viewportNum); +//} +// +//static void NRI_CALL CmdSetScissors(CommandBuffer& commandBuffer, const nri::Rect* rects, uint32_t rectNum) { +// ((CommandBufferMTL&)commandBuffer).SetScissors(rects, rectNum); +//} +// +//static void NRI_CALL CmdSetDepthBounds(CommandBuffer& commandBuffer, float boundsMin, float boundsMax) { +// ((CommandBufferMTL&)commandBuffer).SetDepthBounds(boundsMin, boundsMax); +//} +// +//static void NRI_CALL CmdSetStencilReference(CommandBuffer& commandBuffer, uint8_t frontRef, uint8_t backRef) { +// ((CommandBufferMTL&)commandBuffer).SetStencilReference(frontRef, backRef); +//} +// +//static void NRI_CALL CmdSetSamplePositions(CommandBuffer& commandBuffer, const SamplePosition* positions, Sample_t positionNum, Sample_t sampleNum) { +// ((CommandBufferMTL&)commandBuffer).SetSamplePositions(positions, positionNum, sampleNum); +//} +// +//static void NRI_CALL CmdSetBlendConstants(CommandBuffer& commandBuffer, const Color32f& color) { +// ((CommandBufferMTL&)commandBuffer).SetBlendConstants(color); +//} +// +//static void NRI_CALL CmdSetShadingRate(CommandBuffer& commandBuffer, const ShadingRateDesc& shadingRateDesc) { +// ((CommandBufferMTL&)commandBuffer).SetShadingRate(shadingRateDesc); +//} +// +//static void NRI_CALL CmdSetDepthBias(CommandBuffer& commandBuffer, const DepthBiasDesc& depthBiasDesc) { +// //((CommandBufferMTL&)commandBuffer).SetDepthBias(depthBiasDesc); +//} +// +//static void NRI_CALL CmdClearAttachments(CommandBuffer& commandBuffer, const ClearDesc* clearDescs, uint32_t clearDescNum, const nri::Rect* rects, uint32_t rectNum) { +// ((CommandBufferMTL&)commandBuffer).ClearAttachments(clearDescs, clearDescNum, rects, rectNum); +//} +// +//static void NRI_CALL CmdSetIndexBuffer(CommandBuffer& commandBuffer, const Buffer& buffer, uint64_t offset, IndexType indexType) { +// ((CommandBufferMTL&)commandBuffer).SetIndexBuffer(buffer, offset, indexType); +//} +// +//static void NRI_CALL CmdSetVertexBuffers(CommandBuffer& commandBuffer, uint32_t baseSlot, uint32_t bufferNum, const Buffer* const* buffers, const uint64_t* offsets) { +// ((CommandBufferMTL&)commandBuffer).SetVertexBuffers(baseSlot, bufferNum, buffers, offsets); +//} +// +//static void NRI_CALL CmdDraw(CommandBuffer& commandBuffer, const DrawDesc& drawDesc) { +// ((CommandBufferMTL&)commandBuffer).Draw(drawDesc); +//} +// +//static void NRI_CALL CmdDrawIndexed(CommandBuffer& commandBuffer, const DrawIndexedDesc& drawIndexedDesc) { +// ((CommandBufferMTL&)commandBuffer).DrawIndexed(drawIndexedDesc); +//} +// +//static void NRI_CALL CmdDrawIndirect(CommandBuffer& commandBuffer, const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) { +// ((CommandBufferMTL&)commandBuffer).DrawIndirect(buffer, offset, drawNum, stride, countBuffer, countBufferOffset); +//} +// +//static void NRI_CALL CmdDrawIndexedIndirect(CommandBuffer& commandBuffer, const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) { +// ((CommandBufferMTL&)commandBuffer).DrawIndexedIndirect(buffer, offset, drawNum, stride, countBuffer, countBufferOffset); +//} +// +//static void NRI_CALL CmdDispatch(CommandBuffer& commandBuffer, const DispatchDesc& dispatchDesc) { +// ((CommandBufferMTL&)commandBuffer).Dispatch(dispatchDesc); +//} +// +//static void NRI_CALL CmdDispatchIndirect(CommandBuffer& commandBuffer, const Buffer& buffer, uint64_t offset) { +// ((CommandBufferMTL&)commandBuffer).DispatchIndirect(buffer, offset); +//} +// +//static void NRI_CALL CmdBeginQuery(CommandBuffer& commandBuffer, const QueryPool& queryPool, uint32_t offset) { +// ((CommandBufferMTL&)commandBuffer).BeginQuery(queryPool, offset); +//} +// +//static void NRI_CALL CmdEndQuery(CommandBuffer& commandBuffer, const QueryPool& queryPool, uint32_t offset) { +// ((CommandBufferMTL&)commandBuffer).EndQuery(queryPool, offset); +//} +// +//static void NRI_CALL CmdBeginAnnotation(CommandBuffer& commandBuffer, const char* name) { +// ((CommandBufferMTL&)commandBuffer).BeginAnnotation(name); +//} +// +//static void NRI_CALL CmdEndAnnotation(CommandBuffer& commandBuffer) { +// ((CommandBufferMTL&)commandBuffer).EndAnnotation(); +//} +// +//static void NRI_CALL CmdClearStorageBuffer(CommandBuffer& commandBuffer, const ClearStorageBufferDesc& clearDesc) { +// ((CommandBufferMTL&)commandBuffer).ClearStorageBuffer(clearDesc); +//} +// +//static void NRI_CALL CmdClearStorageTexture(CommandBuffer& commandBuffer, const ClearStorageTextureDesc& clearDesc) { +// ((CommandBufferMTL&)commandBuffer).ClearStorageTexture(clearDesc); +//} +// +//static void NRI_CALL CmdCopyBuffer(CommandBuffer& commandBuffer, Buffer& dstBuffer, uint64_t dstOffset, const Buffer& srcBuffer, uint64_t srcOffset, uint64_t size) { +// ((CommandBufferMTL&)commandBuffer).CopyBuffer(dstBuffer, dstOffset, srcBuffer, srcOffset, size); +//} +// +//static void NRI_CALL CmdCopyTexture( +// CommandBuffer& commandBuffer, Texture& dstTexture, const TextureRegionDesc* dstRegionDesc, const Texture& srcTexture, const TextureRegionDesc* srcRegionDesc) { +// ((CommandBufferMTL&)commandBuffer).CopyTexture(dstTexture, dstRegionDesc, srcTexture, srcRegionDesc); +//} +// +//static void NRI_CALL CmdUploadBufferToTexture(CommandBuffer& commandBuffer, Texture& dstTexture, const TextureRegionDesc& dstRegionDesc, const Buffer& srcBuffer, const TextureDataLayoutDesc& srcDataLayoutDesc) { +// ((CommandBufferMTL&)commandBuffer).UploadBufferToTexture(dstTexture, dstRegionDesc, srcBuffer, srcDataLayoutDesc); +//} +// +//static void NRI_CALL CmdReadbackTextureToBuffer(CommandBuffer& commandBuffer, Buffer& dstBuffer, const TextureDataLayoutDesc& dstDataLayoutDesc, const Texture& srcTexture, const TextureRegionDesc& srcRegionDesc) { +// //((CommandBufferMTL&)commandBuffer).ReadbackTextureToBuffer(dstBuffer, dstDataLayoutDesc, srcTexture, srcRegionDesc); +//} +// +//static void NRI_CALL CmdCopyQueries(CommandBuffer& commandBuffer, const QueryPool& queryPool, uint32_t offset, uint32_t num, Buffer& dstBuffer, uint64_t dstOffset) { +// ((CommandBufferMTL&)commandBuffer).CopyQueries(queryPool, offset, num, dstBuffer, dstOffset); +//} +// +//static void NRI_CALL CmdResetQueries(CommandBuffer& commandBuffer, const QueryPool& queryPool, uint32_t offset, uint32_t num) { +// ((CommandBufferMTL&)commandBuffer).ResetQueries(queryPool, offset, num); +//} +// +//static void* NRI_CALL GetCommandBufferNativeObject(const CommandBuffer& commandBuffer) { +// if (!(&commandBuffer)) +// return nullptr; +// +// return nullptr; +// // return (CommandBufferMTL)((CommandBufferMTL&)commandBuffer); +//} +// +//#pragma endregion +// +// +// +// +//Define_Core_CommandBuffer_PartiallyFillFunctionTable(VK); diff --git a/Source/Metal/CommandBufferMTL.mm b/Source/Metal/CommandBufferMTL.mm index 4dbadb6..8cbfb0a 100644 --- a/Source/Metal/CommandBufferMTL.mm +++ b/Source/Metal/CommandBufferMTL.mm @@ -109,7 +109,7 @@ m_ComputeEncoder = nil; } void CommandBufferMTL::SetViewports(const Viewport* viewports, uint32_t viewportNum) { - MTLViewport* mtlViewports = StackAlloc(MTLViewport, viewportNum); + //MTLViewport* mtlViewports = StackAlloc(MTLViewport, viewportNum); // [m_RendererEncoder setViewports:<#(const MTLViewport * _Nonnull)#> count:<#(NSUInteger)#> } @@ -127,9 +127,8 @@ void CommandBufferMTL::SetStencilReference(uint8_t frontRef, uint8_t backRef) { [m_RendererEncoder setStencilFrontReferenceValue: frontRef backReferenceValue:backRef]; } -void CommandBufferMTL::SetSamplePositions(const SamplePosition* positions, Sample_t positionNum, Sample_t sampleNum) { - -} +//void CommandBufferMTL::SetSamplePositions(const SamplePosition* positions, Sample_t positionNum, Sample_t sampleNum) { +//} void CommandBufferMTL::SetBlendConstants(const Color32f& color) { [m_RendererEncoder setBlendColorRed:color.x diff --git a/Source/Metal/ConversionMTL.h b/Source/Metal/ConversionMTL.h index 1079bbc..7d29b47 100644 --- a/Source/Metal/ConversionMTL.h +++ b/Source/Metal/ConversionMTL.h @@ -4,6 +4,81 @@ namespace nri { +constexpr std::array MTL_NRI_FORMAT_TO_VERTEX_FORMAT = { + MTLVertexFormatInvalid, // UNKNOWN + MTLVertexFormatUCharNormalized, // R8_UNORM + MTLVertexFormatCharNormalized, // R8_SNORM + MTLVertexFormatUChar, // R8_UINT + MTLVertexFormatChar, // R8_SINT + MTLVertexFormatUChar2Normalized, // RG8_UNORM + MTLVertexFormatChar2Normalized, // RG8_SNORM + MTLVertexFormatUChar2, // RG8_UINT + MTLVertexFormatChar2, // RG8_SINT + MTLVertexFormatUChar4Normalized, // BGRA8_UNORM + MTLVertexFormatInvalid, // BGRA8_SRGB + MTLVertexFormatUChar4Normalized, // RGBA8_UNORM + MTLVertexFormatInvalid, // RGBA8_SRGB + MTLVertexFormatChar4Normalized, // RGBA8_SNORM + MTLVertexFormatUChar4, // RGBA8_UINT + MTLVertexFormatChar4, // RGBA8_SINT + MTLVertexFormatUShortNormalized, // R16_UNORM + MTLVertexFormatShortNormalized, // R16_SNORM + MTLVertexFormatUShort, // R16_UINT + MTLVertexFormatShort, // R16_SINT + MTLVertexFormatHalf, // R16_SFLOAT + MTLVertexFormatUShort2Normalized, // RG16_UNORM + MTLVertexFormatShort2Normalized, // RG16_SNORM + MTLVertexFormatUShort2, // RG16_UINT + MTLVertexFormatShort2, // RG16_SINT + MTLVertexFormatHalf2, // RG16_SFLOAT + MTLVertexFormatUShort4Normalized, // RGBA16_UNORM + MTLVertexFormatShort4Normalized, // RGBA16_SNORM + MTLVertexFormatUShort4, // RGBA16_UINT + MTLVertexFormatShort4, // RGBA16_SINT + MTLVertexFormatHalf4, // RGBA16_SFLOAT + MTLVertexFormatUInt, // R32_UINT + MTLVertexFormatInt, // R32_SINT + MTLVertexFormatFloat, // R32_SFLOAT + MTLVertexFormatUInt2, // RG32_UINT + MTLVertexFormatInt2, // RG32_SINT + MTLVertexFormatFloat2, // RG32_SFLOAT + MTLVertexFormatInvalid, // RGB32_UINT //TODO: lookup correct values + MTLVertexFormatInvalid, // RGB32_SINT //TODO: lookup correct values + MTLVertexFormatInvalid, // RGB32_SFLOAT //TODO: lookup correct values + MTLVertexFormatUInt4, // RGBA32_UINT + MTLVertexFormatInt4, // RGBA32_SINT + MTLVertexFormatFloat4, // RGBA32_SFLOAT + MTLVertexFormatInvalid, // B5_G6_R5_UNORM + MTLVertexFormatInvalid, // B5_G5_R5_A1_UNORM + MTLVertexFormatInvalid, // B4_G4_R4_A4_UNORM + MTLVertexFormatInvalid, // R10_G10_B10_A2_UNORM + MTLVertexFormatInvalid, // R10_G10_B10_A2_UINT + MTLVertexFormatInvalid, // R11_G11_B10_UFLOAT + MTLVertexFormatInvalid, // R9_G9_B9_E5_UFLOAT + MTLVertexFormatInvalid, // BC1_RGBA_UNORM + MTLVertexFormatInvalid, // BC1_RGBA_SRGB + MTLVertexFormatInvalid, // BC2_RGBA_UNORM + MTLVertexFormatInvalid, // BC2_RGBA_SRGB + MTLVertexFormatInvalid, // BC3_RGBA_UNORM + MTLVertexFormatInvalid, // BC3_RGBA_SRGB + MTLVertexFormatInvalid, // BC4_R_UNORM + MTLVertexFormatInvalid, // BC4_R_SNORM + MTLVertexFormatInvalid, // BC5_RG_UNORM + MTLVertexFormatInvalid, // BC5_RG_SNORM + MTLVertexFormatInvalid, // BC6H_RGB_UFLOAT + MTLVertexFormatInvalid, // BC6H_RGB_SFLOAT + MTLVertexFormatInvalid, // BC7_RGBA_UNORM + MTLVertexFormatInvalid, // BC7_RGBA_SRGB + MTLVertexFormatInvalid, // D16_UNORM + MTLVertexFormatInvalid, // D24_UNORM_S8_UINT + MTLVertexFormatInvalid, // D32_SFLOAT + MTLVertexFormatInvalid, // D32_SFLOAT_S8_UINT_X24 + MTLVertexFormatInvalid, // R24_UNORM_X8 + MTLVertexFormatInvalid, // X24_G8_UINT + MTLVertexFormatInvalid, // R32_SFLOAT_X8_X24 + MTLVertexFormatInvalid, // X32_G8_UINT_X24 +}; + constexpr std::array BLEND_OP = { MTLBlendOperationAdd, // ADD MTLBlendOperationSubtract, // SUBTRACT @@ -153,6 +228,13 @@ constexpr MTLPrimitiveTopologyClass GetTopologyMTL(Topology topology) { return TOPOLOGIES_CLASSES [(size_t)topology]; } + +inline MTLVertexFormat GetVertexFormatMTL(Format format) { + return (MTLVertexFormat)MTL_NRI_FORMAT_TO_VERTEX_FORMAT[(size_t)format]; +} + + + inline MTLPixelFormat GetFormatMTL(Format format, bool demoteSrgb = false) { if (demoteSrgb) { const FormatProps& formatProps = GetFormatProps(format); diff --git a/Source/Metal/ConversionMTL.mm b/Source/Metal/ConversionMTL.mm index 8e13b6d..ef20071 100644 --- a/Source/Metal/ConversionMTL.mm +++ b/Source/Metal/ConversionMTL.mm @@ -5,7 +5,7 @@ using namespace nri; // Each depth/stencil format is only compatible with itself in VK -constexpr std::array MTL_FORMAT = { +constexpr std::array MTL_PIXEL_FORMAT = { MTLPixelFormatInvalid, // UNKNOWN MTLPixelFormatR8Unorm, // R8_UNORM MTLPixelFormatR8Snorm, // R8_SNORM @@ -80,7 +80,8 @@ MTLPixelFormatDepth32Float_Stencil8, // X32_G8_UINT_X24 }; + uint32_t NRIFormatToMTLFormat(Format format) { - return (uint32_t)MTL_FORMAT[(uint32_t)format]; + return (uint32_t)MTL_PIXEL_FORMAT[(uint32_t)format]; } diff --git a/Source/Metal/DeviceMTL.hpp b/Source/Metal/DeviceMTL.hpp index 16770b3..cb6d497 100644 --- a/Source/Metal/DeviceMTL.hpp +++ b/Source/Metal/DeviceMTL.hpp @@ -1,6 +1,6 @@ // © 2021 NVIDIA Corporation -Declare_PartiallyFillFunctionTable_Functions(MTL); +//Declare_PartiallyFillFunctionTable_Functions(MTL); #pragma region[ Core ] @@ -200,18 +200,19 @@ static void* NRI_CALL GetDeviceNativeObject(const Device& device) { Result DeviceMTL::FillFunctionTable(CoreInterface& table) const { table = {}; - Core_Device_PartiallyFillFunctionTableMTL(table); - Core_Buffer_PartiallyFillFunctionTableMTL(table); - Core_CommandAllocator_PartiallyFillFunctionTableMTL(table); - Core_CommandBuffer_PartiallyFillFunctionTableMTL(table); - Core_CommandQueue_PartiallyFillFunctionTableMTL(table); - Core_Descriptor_PartiallyFillFunctionTableMTL(table); - Core_DescriptorPool_PartiallyFillFunctionTableMTL(table); - Core_DescriptorSet_PartiallyFillFunctionTableMTL(table); - Core_Fence_PartiallyFillFunctionTableMTL(table); - Core_QueryPool_PartiallyFillFunctionTableMTL(table); - Core_Texture_PartiallyFillFunctionTableMTL(table); - return ValidateFunctionTable(table); + // Core_Device_PartiallyFillFunctionTableMTL(table); + // Core_Buffer_PartiallyFillFunctionTableMTL(table); + // Core_CommandAllocator_PartiallyFillFunctionTableMTL(table); + // Core_CommandBuffer_PartiallyFillFunctionTableMTL(table); + // Core_CommandQueue_PartiallyFillFunctionTableMTL(table); + // Core_Descriptor_PartiallyFillFunctionTableMTL(table); + // Core_DescriptorPool_PartiallyFillFunctionTableMTL(table); + // Core_DescriptorSet_PartiallyFillFunctionTableMTL(table); + // Core_Fence_PartiallyFillFunctionTableMTL(table); + // Core_QueryPool_PartiallyFillFunctionTableMTL(table); + // Core_Texture_PartiallyFillFunctionTableMTL(table); + // return ValidateFunctionTable(table); + return Result::UNSUPPORTED; } #pragma endregion @@ -251,7 +252,7 @@ Result DeviceMTL::FillFunctionTable(ResourceAllocatorInterface& table) const { return Result::UNSUPPORTED; } -Define_Core_Device_PartiallyFillFunctionTable(MTL); +//Dfine_Core_Device_PartiallyFillFunctionTable(MTL); //Define_Helper_Device_PartiallyFillFunctionTable(MTL); //Define_RayTracing_Device_PartiallyFillFunctionTable(MTL); //Define_Streamer_Device_PartiallyFillFunctionTable(MTL); diff --git a/Source/Metal/ImplMTL.mm b/Source/Metal/ImplMTL.mm new file mode 100644 index 0000000..e69de29 diff --git a/Source/Metal/PipelineMTL.mm b/Source/Metal/PipelineMTL.mm index 49d9876..f5002f7 100644 --- a/Source/Metal/PipelineMTL.mm +++ b/Source/Metal/PipelineMTL.mm @@ -46,17 +46,24 @@ const ShaderDesc& shader = graphicsPipelineDesc.shaders[i]; m_usedBits |= shader.stage; - dispatch_data_t byteCode = - dispatch_data_create(shader.bytecode, shader.size, nil, - DISPATCH_DATA_DESTRUCTOR_DEFAULT); - id lib = [m_Device newLibraryWithData:byteCode error:nil]; - + dispatch_data_t byteCode = dispatch_data_create(shader.bytecode, shader.size, nil, DISPATCH_DATA_DESTRUCTOR_DEFAULT); + NSError *error; + id lib = [m_Device newLibraryWithData:byteCode error:&error]; + NSCAssert(lib, @"Failed to load Metal shader library %@", error); // not sure how to correctly report this + RETURN_ON_FAILURE(&m_Device, lib, Result::FAILURE, "Failed to Load Metal shader library"); + // Create a MTLFunction from the loaded MTLLibrary. NSString *entryPointNStr = [lib functionNames][0]; if (shader.entryPointName) { - entryPointNStr = - [[NSString alloc] initWithUTF8String:shader.entryPointName]; + entryPointNStr = [[NSString alloc] initWithUTF8String:shader.entryPointName]; + } + id entryPointFunc = [lib newFunctionWithName:entryPointNStr]; + if(shader.stage & nri::StageBits::VERTEX_SHADER) { + renderPipelineDesc.vertexFunction = entryPointFunc; + } else if(shader.stage & nri::StageBits::FRAGMENT_SHADER) { + renderPipelineDesc.fragmentFunction = entryPointFunc; } + } // Depth-stencil const DepthAttachmentDesc& da = graphicsPipelineDesc.outputMerger.depth; @@ -65,13 +72,20 @@ const PipelineLayout *pl = graphicsPipelineDesc.pipelineLayout; const VertexInputDesc *vi = graphicsPipelineDesc.vertexInput; if (vi) { + MTLVertexDescriptor *vertexDescriptor = [MTLVertexDescriptor new]; + for(size_t attIdx = 0; attIdx < vi->attributeNum; attIdx++) { + const nri::VertexAttributeDesc* attrib = &vi->attributes[attIdx]; + vertexDescriptor.attributes[attrib->mtl.location].offset = attrib->offset; + vertexDescriptor.attributes[attrib->mtl.location].format = GetVertexFormatMTL(attrib->format); + vertexDescriptor.attributes[attrib->mtl.location].bufferIndex = attrib->streamIndex; + } - // VkVertexInputBindingDescription* streams const_cast(vertexInputState.pVertexBindingDescriptions); - //for (uint32_t i = 0; i < vi->streamNum; i++) { - // const VertexStreamDesc &stream = vi->streams[i]; - // renderPipelineDesc.vertexDescriptor.layouts[attribute_desc.streamIndex].stride = stream.stride; - // renderPipelineDesc.vertexDescriptor.layouts[attribute_desc.streamIndex].stepRate = 1; - // } + for(size_t layoutIdx = 0; layoutIdx < vi->streamNum; layoutIdx++) { + const nri::VertexStreamDesc* stream = &vi->streams[layoutIdx]; + vertexDescriptor.layouts[stream->bindingSlot].stride = stream->stride; + vertexDescriptor.layouts[stream->bindingSlot].stepRate = static_cast(stream->stepRate); + } + renderPipelineDesc.vertexDescriptor = vertexDescriptor; } renderPipelineDesc.inputPrimitiveTopology = GetTopologyMTL(ia.topology); @@ -86,7 +100,7 @@ const OutputMergerDesc& om = graphicsPipelineDesc.outputMerger; for (uint32_t i = 0; i < om.colorNum; i++) { - const ColorAttachmentDesc& attachmentDesc = om.color[i]; + const ColorAttachmentDesc& attachmentDesc = om.colors[i]; renderPipelineDesc.colorAttachments[i].pixelFormat = GetFormatMTL(attachmentDesc.format, false); renderPipelineDesc.colorAttachments[i].blendingEnabled = attachmentDesc.blendEnabled; From b0ecb164eeaf5ba6bcab000653695a9acd8d439c Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Mon, 18 Nov 2024 21:05:03 -0800 Subject: [PATCH 20/24] feat: update desciprot and textureo Signed-off-by: Michael Pollind --- Source/Metal/CommandAllocatorMTL.h | 4 +++- Source/Metal/CommandAllocatorMTL.mm | 5 +++-- Source/Metal/CommandBufferMTL.mm | 26 +++++++++++++++++++++--- Source/Metal/DescriptorMTL.h | 26 +++++++++++++++++------- Source/Metal/DescriptorMTL.mm | 31 +++++++++++++++++++++++++++++ Source/Metal/PipelineMTL.mm | 5 ++++- Source/Metal/TextureMTL.h | 7 +++---- 7 files changed, 86 insertions(+), 18 deletions(-) diff --git a/Source/Metal/CommandAllocatorMTL.h b/Source/Metal/CommandAllocatorMTL.h index d10a47a..127c7ad 100644 --- a/Source/Metal/CommandAllocatorMTL.h +++ b/Source/Metal/CommandAllocatorMTL.h @@ -25,11 +25,13 @@ struct CommandAllocatorMTL { // NRI //================================================================================================================ + void SetDebugName(const char* name); Result CreateCommandBuffer(CommandBuffer*& commandBuffer); + void Reset(); private: - struct CommandQueueMTL* m_CommandQueue; DeviceMTL& m_Device; + struct CommandQueueMTL* m_CommandQueue; }; } diff --git a/Source/Metal/CommandAllocatorMTL.mm b/Source/Metal/CommandAllocatorMTL.mm index 9532664..9fc54bd 100644 --- a/Source/Metal/CommandAllocatorMTL.mm +++ b/Source/Metal/CommandAllocatorMTL.mm @@ -1,7 +1,7 @@ #include "SharedMTL.h" #include "CommandAllocatorMTL.h" - +#include "CommandBufferMTL.h" #include "CommandQueueMTL.h" using namespace nri; @@ -20,8 +20,9 @@ //================================================================================================================ Result CommandAllocatorMTL::CreateCommandBuffer(CommandBuffer*& commandBuffer) { - + CommandBufferMTL* commandBufferImpl = Allocate(m_Device.GetStdAllocator(), m_Device); + commandBuffer = (CommandBuffer*)commandBufferImpl; return Result::SUCCESS; } diff --git a/Source/Metal/CommandBufferMTL.mm b/Source/Metal/CommandBufferMTL.mm index 8cbfb0a..5cf1471 100644 --- a/Source/Metal/CommandBufferMTL.mm +++ b/Source/Metal/CommandBufferMTL.mm @@ -23,7 +23,7 @@ } Result CommandBufferMTL::Begin(const DescriptorPool* descriptorPool) { - [m_Handle computeCommandEncoderWithDescriptor: NULL]; + m_ComputeEncoder = [m_Handle computeCommandEncoderWithDescriptor: NULL]; } Result CommandBufferMTL::End() { @@ -93,15 +93,32 @@ } void CommandBufferMTL::BeginRendering(const AttachmentsDesc& attachmentsDesc) { MTLRenderPassDescriptor* renderPassDescriptor = [MTLRenderPassDescriptor renderPassDescriptor]; + for(uint32_t i = 0; i < attachmentsDesc.colorNum; i++) { + DescriptorMTL& descriptorMTL = *(DescriptorMTL*)attachmentsDesc.colors[i]; + + renderPassDescriptor.colorAttachments[i].texture = descriptorMTL.GetImageView() ; + renderPassDescriptor.colorAttachments[i].clearColor = MTLClearColorMake(0, 0, 0, 1); + renderPassDescriptor.colorAttachments[i].loadAction = MTLLoadActionClear; + renderPassDescriptor.colorAttachments[i].storeAction = MTLStoreActionStore; + + } + + if(attachmentsDesc.depthStencil) { + DescriptorMTL& descriptorMTL = *(DescriptorMTL*)attachmentsDesc.depthStencil; + renderPassDescriptor.depthAttachment.texture = descriptorMTL.GetImageView(); + // renderPassDescriptor.depthAttachment.clearColor = MTLClearColorMake(0, 0, 0, 1); + renderPassDescriptor.depthAttachment.loadAction = MTLLoadActionClear; + renderPassDescriptor.depthAttachment.storeAction = MTLStoreActionStore; + } //renderPassDescriptor.colorAttachments[ //renderPassDescriptor.colorAttachments - m_RendererEncoder = [m_Handle renderCommandEncoderWithDescriptor: NULL]; + m_RendererEncoder = [m_Handle renderCommandEncoderWithDescriptor: renderPassDescriptor]; } void CommandBufferMTL::EndRendering() { [m_RendererEncoder endEncoding]; @@ -110,8 +127,11 @@ } void CommandBufferMTL::SetViewports(const Viewport* viewports, uint32_t viewportNum) { //MTLViewport* mtlViewports = StackAlloc(MTLViewport, viewportNum); + + Scratch mtlViewports = AllocateScratch(m_Device, MTLViewport, viewportNum); + - // [m_RendererEncoder setViewports:<#(const MTLViewport * _Nonnull)#> count:<#(NSUInteger)#> + [m_RendererEncoder setViewports:mtlViewports count:viewportNum]; } void CommandBufferMTL::SetScissors(const Rect* rects, uint32_t rectNum) { NSCAssert(m_RendererEncoder, @"encoder set"); diff --git a/Source/Metal/DescriptorMTL.h b/Source/Metal/DescriptorMTL.h index 0cce5fe..0977fb3 100644 --- a/Source/Metal/DescriptorMTL.h +++ b/Source/Metal/DescriptorMTL.h @@ -6,20 +6,32 @@ namespace nri { struct DeviceMTL; +enum class DescriptorTypeMTL { + NONE, + IMAGE_VIEW +}; struct DescriptorMTL { - +public: inline DescriptorMTL (DeviceMTL& device) : m_Device(device) { } - - inline Result Create(const Texture1DViewDesc& textureViewDesc) {} - inline Result Create(const Texture2DViewDesc& textureViewDesc){} - inline Result Create(const Texture3DViewDesc& textureViewDesc){} - inline Result Create(const SamplerDesc& samplerDesc){} - + + inline id GetImageView() { + return m_texture; + } + + + Result Create(const BufferViewDesc& bufferViewDesc); + Result Create(const Texture1DViewDesc& textureViewDesc); + Result Create(const Texture2DViewDesc& textureViewDesc); + Result Create(const Texture3DViewDesc& textureViewDesc); + Result Create(const SamplerDesc& samplerDesc); private: DeviceMTL& m_Device; + + id m_texture; + DescriptorTypeMTL m_type = DescriptorTypeMTL::NONE; }; diff --git a/Source/Metal/DescriptorMTL.mm b/Source/Metal/DescriptorMTL.mm index e69de29..595a5d3 100644 --- a/Source/Metal/DescriptorMTL.mm +++ b/Source/Metal/DescriptorMTL.mm @@ -0,0 +1,31 @@ +#include "SharedMTL.h" + +#include "DescriptorMTL.h" + +#include "BufferMTL.h" + +namespace nri { + +Result DescriptorMTL::Create(const BufferViewDesc& bufferViewDesc) { + // m_Type = DescriptorTypeVK::BUFFER_VIEW; + const BufferMTL& buffer = *(const BufferMTL*)bufferViewDesc.buffer; + + return Result::SUCCESS; + +} +Result DescriptorMTL::Create(const Texture1DViewDesc& textureViewDesc) { + return Result::SUCCESS; + +} +Result DescriptorMTL::Create(const Texture2DViewDesc& textureViewDesc) { + + return Result::SUCCESS; +} +Result DescriptorMTL::Create(const Texture3DViewDesc& textureViewDesc){ + return Result::SUCCESS; +} +Result DescriptorMTL::Create(const SamplerDesc& samplerDesc){ + return Result::SUCCESS; +} + +} diff --git a/Source/Metal/PipelineMTL.mm b/Source/Metal/PipelineMTL.mm index f5002f7..9a74abc 100644 --- a/Source/Metal/PipelineMTL.mm +++ b/Source/Metal/PipelineMTL.mm @@ -63,7 +63,6 @@ } else if(shader.stage & nri::StageBits::FRAGMENT_SHADER) { renderPipelineDesc.fragmentFunction = entryPointFunc; } - } // Depth-stencil const DepthAttachmentDesc& da = graphicsPipelineDesc.outputMerger.depth; @@ -92,7 +91,11 @@ if (graphicsPipelineDesc.multisample) { // TODO: multisampling + // } + + // renderPipelineDesc.rasterSampleCount = pCreateInfo->pMultisampleState->pSampleMask[0]; + // Blending diff --git a/Source/Metal/TextureMTL.h b/Source/Metal/TextureMTL.h index a6a4f1e..a88c981 100644 --- a/Source/Metal/TextureMTL.h +++ b/Source/Metal/TextureMTL.h @@ -14,9 +14,9 @@ struct TextureMTL { } ~TextureMTL(); - //inline id GetHandle() const { - // return m_Handle; - //} + inline id GetHandle() const { + return m_Handle; + } inline DeviceMTL& GetDevice() const { return m_Device; @@ -27,7 +27,6 @@ struct TextureMTL { } Result Create(const TextureDesc& textureDesc); - //Result Create(const TextureMTLDesc& textureDesc); private: // Result CreateFromTextureDesc(const TextureDesc& textureDesc); From d8e29d31a292cc59206d9f4dc2ac7f6dfa7e595f Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Wed, 20 Nov 2024 21:25:31 -0800 Subject: [PATCH 21/24] feat: add command buffer impl progress Signed-off-by: Michael Pollind --- Source/Metal/BufferMTL.h | 5 +- Source/Metal/BufferMTL.mm | 19 ++ Source/Metal/CommandBufferMTL.h | 5 + Source/Metal/CommandBufferMTL.mm | 12 +- Source/Metal/CommandQueueMTL.h | 4 +- Source/Metal/CommandQueueMTL.mm | 16 +- Source/Metal/DeviceMTL.h | 28 +-- Source/Metal/ImplMTL.mm | 380 +++++++++++++++++++++++++++++++ 8 files changed, 449 insertions(+), 20 deletions(-) diff --git a/Source/Metal/BufferMTL.h b/Source/Metal/BufferMTL.h index 63be8c8..dac53dd 100644 --- a/Source/Metal/BufferMTL.h +++ b/Source/Metal/BufferMTL.h @@ -18,7 +18,6 @@ struct BufferMTL { return pBuffer; } - inline DeviceMTL& GetDevice() const { return m_Device; } @@ -27,6 +26,10 @@ struct BufferMTL { return m_Desc; } + void* Map(uint64_t offset, uint64_t size); + void Unmap(); + void SetDebugName(const char* name); + ~BufferMTL(); Result Create(const BufferDesc& bufferDesc); diff --git a/Source/Metal/BufferMTL.mm b/Source/Metal/BufferMTL.mm index 38e4759..70d623e 100644 --- a/Source/Metal/BufferMTL.mm +++ b/Source/Metal/BufferMTL.mm @@ -13,6 +13,25 @@ return Result::SUCCESS; } + +void* BufferMTL::Map(uint64_t offset, uint64_t size) { + return (uint8_t*)[pBuffer contents] + offset; +} + +void BufferMTL::Unmap() { + +} + + Result BufferMTL::Create(const AllocateBufferDesc& bufferDesc) { return Result::SUCCESS; } + +void BufferMTL::SetDebugName(const char* name) { + + NSString* str = [NSString stringWithUTF8String:name]; + + + //[pBuffer addDebugMarker:name range:] + +} diff --git a/Source/Metal/CommandBufferMTL.h b/Source/Metal/CommandBufferMTL.h index ac450a6..7034aa9 100644 --- a/Source/Metal/CommandBufferMTL.h +++ b/Source/Metal/CommandBufferMTL.h @@ -30,6 +30,11 @@ struct CommandBufferMTL { return m_Device; } + inline operator id() const { + return m_Handle; + } + + void SetDebugName(const char* name); Result Begin(const DescriptorPool* descriptorPool); Result End(); diff --git a/Source/Metal/CommandBufferMTL.mm b/Source/Metal/CommandBufferMTL.mm index 5cf1471..cffe549 100644 --- a/Source/Metal/CommandBufferMTL.mm +++ b/Source/Metal/CommandBufferMTL.mm @@ -121,15 +121,21 @@ m_RendererEncoder = [m_Handle renderCommandEncoderWithDescriptor: renderPassDescriptor]; } void CommandBufferMTL::EndRendering() { + NSCAssert(m_RendererEncoder, @"Renderer Encoderer Not Set"); [m_RendererEncoder endEncoding]; m_RendererEncoder = nil; m_ComputeEncoder = nil; } void CommandBufferMTL::SetViewports(const Viewport* viewports, uint32_t viewportNum) { - //MTLViewport* mtlViewports = StackAlloc(MTLViewport, viewportNum); - Scratch mtlViewports = AllocateScratch(m_Device, MTLViewport, viewportNum); - + for(size_t i = 0; i < viewportNum; i++) { + mtlViewports[i].originX = viewports[i].x; + mtlViewports[i].originY = viewports[i].y; + mtlViewports[i].width = viewports[i].width; + mtlViewports[i].height = viewports[i].height; + mtlViewports[i].znear = viewports[i].depthMin; + mtlViewports[i].zfar = viewports[i].depthMax; + } [m_RendererEncoder setViewports:mtlViewports count:viewportNum]; } diff --git a/Source/Metal/CommandQueueMTL.h b/Source/Metal/CommandQueueMTL.h index 3be4838..0486e73 100644 --- a/Source/Metal/CommandQueueMTL.h +++ b/Source/Metal/CommandQueueMTL.h @@ -38,9 +38,11 @@ struct CommandQueueMTL { return m_Lock; } - Result WaitForIdle(); void SetDebugName(const char* name); + void Submit(const QueueSubmitDesc& queueSubmitDesc, const SwapChain* swapChain); + Result WaitForIdle(); + Result Create(CommandQueueType type); QueueBarrierBits m_BarrierBits = QueueBarrierBits::NONE; diff --git a/Source/Metal/CommandQueueMTL.mm b/Source/Metal/CommandQueueMTL.mm index 1eb6305..6ad2415 100644 --- a/Source/Metal/CommandQueueMTL.mm +++ b/Source/Metal/CommandQueueMTL.mm @@ -3,6 +3,7 @@ #include "SharedMTL.h" #include "CommandQueueMTL.h" +#include "CommandBufferMTL.h" using namespace nri; @@ -24,7 +25,20 @@ return Result::SUCCESS; } -inline void CommandQueueMTL::SetDebugName(const char* name) { + +void CommandQueueMTL::Submit(const QueueSubmitDesc& queueSubmitDesc, const SwapChain* swapChain) { + + for(uint32_t i = 0; i < queueSubmitDesc.commandBufferNum; i++) { + id cmd = *(struct CommandBufferMTL*)queueSubmitDesc.commandBuffers[i]; + [cmd commit]; + + } + + +} + + +void CommandQueueMTL::SetDebugName(const char* name) { [m_Handle setLabel:[NSString stringWithUTF8String:name]]; } diff --git a/Source/Metal/DeviceMTL.h b/Source/Metal/DeviceMTL.h index b602711..67f3d34 100644 --- a/Source/Metal/DeviceMTL.h +++ b/Source/Metal/DeviceMTL.h @@ -16,13 +16,7 @@ struct DeviceMTL final : public DeviceBase { inline operator id() const { return m_Device; } - - inline const DeviceDesc& GetDesc() const { - return m_Desc; - } - void Destruct() override; - template inline Result CreateImplementation(Interface*& entity, const Args&... args) { Implementation* impl = Allocate(GetStdAllocator(), *this); @@ -41,14 +35,20 @@ struct DeviceMTL final : public DeviceBase { void GetMemoryDesc(const TextureDesc& textureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc); void GetMemoryDesc(const AccelerationStructureDesc& accelerationStructureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc); - Result FillFunctionTable(CoreInterface& table) const; - Result FillFunctionTable(HelperInterface& table) const; - Result FillFunctionTable(LowLatencyInterface& table) const; - Result FillFnctionTable(MeshShaderInterface& table) const; - Result FillFunctionTable(RayTracingInterface& table) const; - Result FillFunctionTable(StreamerInterface& table) const; - Result FillFunctionTable(SwapChainInterface& table) const; - Result FillFunctionTable(ResourceAllocatorInterface& table) const; + + const DeviceDesc& GetDesc() const override { + return m_Desc; + } + void Destruct() override; + + Result FillFunctionTable(CoreInterface& table) const override; + Result FillFunctionTable(HelperInterface& table) const override; + Result FillFunctionTable(LowLatencyInterface& table) const override; + Result FillFunctionTable(MeshShaderInterface& table) const override; + Result FillFunctionTable(RayTracingInterface& table) const override; + Result FillFunctionTable(StreamerInterface& table) const override; + Result FillFunctionTable(SwapChainInterface& table) const override; + Result FillFunctionTable(ResourceAllocatorInterface& table) const override; Result Create(const DeviceCreationDesc& deviceCreationDesc, const DeviceCreationMTLDesc& deviceCreationVKDesc, bool isWrapper); private: diff --git a/Source/Metal/ImplMTL.mm b/Source/Metal/ImplMTL.mm index e69de29..cdb30b9 100644 --- a/Source/Metal/ImplMTL.mm +++ b/Source/Metal/ImplMTL.mm @@ -0,0 +1,380 @@ +// © 2021 NVIDIA Corporation + +#include "SharedMTL.h" + +using namespace nri; + +#include "BufferMTL.h" +#include "CommandAllocatorMTL.h" +#include "CommandBufferMTL.h" +#include "DeviceMTL.h" + +Result CreateDeviceMTL(const DeviceCreationDesc& desc, DeviceBase*& device) { + StdAllocator allocator(desc.allocationCallbacks); + DeviceMTL* impl = Allocate(allocator, desc.callbackInterface, allocator); + Result result = impl->Create(desc, {}, false); + + if (result != Result::SUCCESS) { + Destroy(allocator, impl); + device = nullptr; + } else + device = (DeviceBase*)impl; + return result; +} + + +Result CreateDeviceMTL(const DeviceCreationMTLDesc& desc, DeviceBase*& device) { + return Result::SUCCESS; +} +//============================================================================================================================================================================================ +#pragma region[ Core ] + + +static void NRI_CALL SetBufferDebugName(Buffer& buffer, const char* name) { + ((BufferMTL&)buffer).SetDebugName(name); +} + +static uint64_t NRI_CALL GetBufferNativeObject(const Buffer& buffer) { + if (!(&buffer)) + return 0; + return uint64_t(((BufferMTL&)buffer).GetHandle()); +} + + +static void* NRI_CALL MapBuffer(Buffer& buffer, uint64_t offset, uint64_t size) { + return ((BufferMTL&)buffer).Map(offset, size); +} + +static void NRI_CALL UnmapBuffer(Buffer& buffer) { + ((BufferMTL&)buffer).Unmap(); +} + +static void NRI_CALL SetCommandAllocatorDebugName(CommandAllocator& commandAllocator, const char* name) { + // ((CommandAllocatorVK&)commandAllocator).SetDebugName(name); +} + +static Result NRI_CALL CreateCommandBuffer(CommandAllocator& commandAllocator, CommandBuffer*& commandBuffer) { + return ((CommandAllocatorMTL&)commandAllocator).CreateCommandBuffer(commandBuffer); +} + +static void NRI_CALL ResetCommandAllocator(CommandAllocator& commandAllocator) { + // ((CommandAllocatorVK&)commandAllocator).Reset(); +} + +static void NRI_CALL SetCommandBufferDebugName(CommandBuffer& commandBuffer, const char* name) { + // ((CommandBufferVK&)commandBuffer).SetDebugName(name); +} + +static Result NRI_CALL BeginCommandBuffer(CommandBuffer& commandBuffer, const DescriptorPool* descriptorPool) { + return ((CommandBufferMTL&)commandBuffer).Begin(descriptorPool); +} + +static Result NRI_CALL EndCommandBuffer(CommandBuffer& commandBuffer) { + return ((CommandBufferMTL&)commandBuffer).End(); +} + +static void NRI_CALL CmdSetPipelineLayout(CommandBuffer& commandBuffer, const PipelineLayout& pipelineLayout) { + ((CommandBufferMTL&)commandBuffer).SetPipelineLayout(pipelineLayout); +} + +static void NRI_CALL CmdSetPipeline(CommandBuffer& commandBuffer, const Pipeline& pipeline) { + ((CommandBufferMTL&)commandBuffer).SetPipeline(pipeline); +} + +static void NRI_CALL CmdBarrier(CommandBuffer& commandBuffer, const BarrierGroupDesc& barrierGroupDesc) { + ((CommandBufferMTL&)commandBuffer).Barrier(barrierGroupDesc); +} + +static void NRI_CALL CmdSetDescriptorPool(CommandBuffer& commandBuffer, const DescriptorPool& descriptorPool) { + ((CommandBufferMTL&)commandBuffer).SetDescriptorPool(descriptorPool); +} + +static void NRI_CALL CmdSetDescriptorSet(CommandBuffer& commandBuffer, uint32_t setIndex, const DescriptorSet& descriptorSet, const uint32_t* dynamicConstantBufferOffsets) { + ((CommandBufferMTL&)commandBuffer).SetDescriptorSet(setIndex, descriptorSet, dynamicConstantBufferOffsets); +} + +static void NRI_CALL CmdSetRootConstants(CommandBuffer& commandBuffer, uint32_t rootConstantIndex, const void* data, uint32_t size) { + //((CommandBufferMTL&)commandBuffer).SetRootConstants(rootConstantIndex, data, size); +} + +static void NRI_CALL CmdSetRootDescriptor(CommandBuffer& commandBuffer, uint32_t rootDescriptorIndex, Descriptor& descriptor) { + //((CommandBufferMTL&)commandBuffer).SetRootDescriptor(rootDescriptorIndex, descriptor); +} + +static void NRI_CALL CmdBeginRendering(CommandBuffer& commandBuffer, const AttachmentsDesc& attachmentsDesc) { + ((CommandBufferMTL&)commandBuffer).BeginRendering(attachmentsDesc); +} + +static void NRI_CALL CmdEndRendering(CommandBuffer& commandBuffer) { + ((CommandBufferMTL&)commandBuffer).EndRendering(); +} + +static void NRI_CALL CmdSetViewports(CommandBuffer& commandBuffer, const Viewport* viewports, uint32_t viewportNum) { + ((CommandBufferMTL&)commandBuffer).SetViewports(viewports, viewportNum); +} + +static void NRI_CALL CmdSetScissors(CommandBuffer& commandBuffer, const nri::Rect* rects, uint32_t rectNum) { + ((CommandBufferMTL&)commandBuffer).SetScissors(rects, rectNum); +} + +static void NRI_CALL CmdSetDepthBounds(CommandBuffer& commandBuffer, float boundsMin, float boundsMax) { + ((CommandBufferMTL&)commandBuffer).SetDepthBounds(boundsMin, boundsMax); +} + +static void NRI_CALL CmdSetStencilReference(CommandBuffer& commandBuffer, uint8_t frontRef, uint8_t backRef) { + ((CommandBufferMTL&)commandBuffer).SetStencilReference(frontRef, backRef); +} + +static void NRI_CALL CmdSetSampleLocations(CommandBuffer& commandBuffer, const SampleLocation* locations, Sample_t locationNum, Sample_t sampleNum) { + //((CommandBufferMTL&)commandBuffer).SetSampleLocations(locations, locationNum, sampleNum); +} + +static void NRI_CALL CmdSetBlendConstants(CommandBuffer& commandBuffer, const Color32f& color) { + ((CommandBufferMTL&)commandBuffer).SetBlendConstants(color); +} + +static void NRI_CALL CmdSetShadingRate(CommandBuffer& commandBuffer, const ShadingRateDesc& shadingRateDesc) { + ((CommandBufferMTL&)commandBuffer).SetShadingRate(shadingRateDesc); +} + +static void NRI_CALL CmdSetDepthBias(CommandBuffer& commandBuffer, const DepthBiasDesc& depthBiasDesc) { + // ((CommandBufferMTL&)commandBuffer).SetDepthBias(depthBiasDesc); +} + +static void NRI_CALL CmdClearAttachments(CommandBuffer& commandBuffer, const ClearDesc* clearDescs, uint32_t clearDescNum, const nri::Rect* rects, uint32_t rectNum) { + //((CommandBufferMTL&)commandBuffer).ClearAttachments(clearDescs, clearDescNum, rects, rectNum); +} + +static void NRI_CALL CmdSetIndexBuffer(CommandBuffer& commandBuffer, const Buffer& buffer, uint64_t offset, IndexType indexType) { + ((CommandBufferMTL&)commandBuffer).SetIndexBuffer(buffer, offset, indexType); +} + +static void NRI_CALL CmdSetVertexBuffers(CommandBuffer& commandBuffer, uint32_t baseSlot, uint32_t bufferNum, const Buffer* const* buffers, const uint64_t* offsets) { + ((CommandBufferMTL&)commandBuffer).SetVertexBuffers(baseSlot, bufferNum, buffers, offsets); +} + +static void NRI_CALL CmdDraw(CommandBuffer& commandBuffer, const DrawDesc& drawDesc) { + ((CommandBufferMTL&)commandBuffer).Draw(drawDesc); +} + +static void NRI_CALL CmdDrawIndexed(CommandBuffer& commandBuffer, const DrawIndexedDesc& drawIndexedDesc) { + ((CommandBufferMTL&)commandBuffer).DrawIndexed(drawIndexedDesc); +} + +static void NRI_CALL CmdDrawIndirect(CommandBuffer& commandBuffer, const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) { + ((CommandBufferMTL&)commandBuffer).DrawIndirect(buffer, offset, drawNum, stride, countBuffer, countBufferOffset); +} + +static void NRI_CALL CmdDrawIndexedIndirect(CommandBuffer& commandBuffer, const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) { + ((CommandBufferMTL&)commandBuffer).DrawIndexedIndirect(buffer, offset, drawNum, stride, countBuffer, countBufferOffset); +} + +static void NRI_CALL CmdDispatch(CommandBuffer& commandBuffer, const DispatchDesc& dispatchDesc) { + ((CommandBufferMTL&)commandBuffer).Dispatch(dispatchDesc); +} + +static void NRI_CALL CmdDispatchIndirect(CommandBuffer& commandBuffer, const Buffer& buffer, uint64_t offset) { + ((CommandBufferMTL&)commandBuffer).DispatchIndirect(buffer, offset); +} + +static void NRI_CALL CmdBeginQuery(CommandBuffer& commandBuffer, const QueryPool& queryPool, uint32_t offset) { + ((CommandBufferMTL&)commandBuffer).BeginQuery(queryPool, offset); +} + +static void NRI_CALL CmdEndQuery(CommandBuffer& commandBuffer, const QueryPool& queryPool, uint32_t offset) { + ((CommandBufferMTL&)commandBuffer).EndQuery(queryPool, offset); +} + +static void NRI_CALL CmdBeginAnnotation(CommandBuffer& commandBuffer, const char* name) { + ((CommandBufferMTL&)commandBuffer).BeginAnnotation(name); +} + +static void NRI_CALL CmdEndAnnotation(CommandBuffer& commandBuffer) { + ((CommandBufferMTL&)commandBuffer).EndAnnotation(); +} + +static void NRI_CALL CmdClearStorageBuffer(CommandBuffer& commandBuffer, const ClearStorageBufferDesc& clearDesc) { + ((CommandBufferMTL&)commandBuffer).ClearStorageBuffer(clearDesc); +} + +static void NRI_CALL CmdClearStorageTexture(CommandBuffer& commandBuffer, const ClearStorageTextureDesc& clearDesc) { + ((CommandBufferMTL&)commandBuffer).ClearStorageTexture(clearDesc); +} + +static void NRI_CALL CmdResolveTexture(CommandBuffer& commandBuffer, Texture& dstTexture, const TextureRegionDesc* dstRegionDesc, const Texture& srcTexture, const TextureRegionDesc* srcRegionDesc) { + //((CommandBufferMTL&)commandBuffer).ResolveTexture(dstTexture, dstRegionDesc, srcTexture, srcRegionDesc); +} + +static void NRI_CALL CmdCopyBuffer(CommandBuffer& commandBuffer, Buffer& dstBuffer, uint64_t dstOffset, const Buffer& srcBuffer, uint64_t srcOffset, uint64_t size) { + ((CommandBufferMTL&)commandBuffer).CopyBuffer(dstBuffer, dstOffset, srcBuffer, srcOffset, size); +} + +static void NRI_CALL CmdCopyTexture( + CommandBuffer& commandBuffer, Texture& dstTexture, const TextureRegionDesc* dstRegionDesc, const Texture& srcTexture, const TextureRegionDesc* srcRegionDesc) { + ((CommandBufferMTL&)commandBuffer).CopyTexture(dstTexture, dstRegionDesc, srcTexture, srcRegionDesc); +} + +static void NRI_CALL CmdUploadBufferToTexture(CommandBuffer& commandBuffer, Texture& dstTexture, const TextureRegionDesc& dstRegionDesc, const Buffer& srcBuffer, const TextureDataLayoutDesc& srcDataLayoutDesc) { + ((CommandBufferMTL&)commandBuffer).UploadBufferToTexture(dstTexture, dstRegionDesc, srcBuffer, srcDataLayoutDesc); +} + +static void NRI_CALL CmdReadbackTextureToBuffer(CommandBuffer& commandBuffer, Buffer& dstBuffer, const TextureDataLayoutDesc& dstDataLayoutDesc, const Texture& srcTexture, const TextureRegionDesc& srcRegionDesc) { + //((CommandBufferMTL&)commandBuffer).ReadbackTextureToBuffer(dstBuffer, dstDataLayoutDesc, srcTexture, srcRegionDesc); +} + +static void NRI_CALL CmdCopyQueries(CommandBuffer& commandBuffer, const QueryPool& queryPool, uint32_t offset, uint32_t num, Buffer& dstBuffer, uint64_t dstOffset) { + ((CommandBufferMTL&)commandBuffer).CopyQueries(queryPool, offset, num, dstBuffer, dstOffset); +} + +static void NRI_CALL CmdResetQueries(CommandBuffer& commandBuffer, const QueryPool& queryPool, uint32_t offset, uint32_t num) { + ((CommandBufferMTL&)commandBuffer).ResetQueries(queryPool, offset, num); +} + +static const DeviceDesc& NRI_CALL GetDeviceDesc(const Device& device) { + return ((DeviceMTL&)device).GetDesc(); +} + +//static void NRI_CALL QueueSubmit(CommandQueue& commandQueue, const QueueSubmitDesc& workSubmissionDesc) { +// ((CommandQueueMTL&)commandQueue).Submit(workSubmissionDesc, nullptr); +//} + +Result DeviceMTL::FillFunctionTable(CoreInterface& table) const { + table.GetDeviceDesc = ::GetDeviceDesc; + //table.GetBufferDesc = ::GetBufferDesc; + //table.GetTextureDesc = ::GetTextureDesc; + //table.GetFormatSupport = ::GetFormatSupport; + //table.GetQuerySize = ::GetQuerySize; + //table.GetBufferMemoryDesc = ::GetBufferMemoryDesc; + //table.GetTextureMemoryDesc = ::GetTextureMemoryDesc; + //table.GetCommandQueue = ::GetCommandQueue; + //table.CreateCommandAllocator = ::CreateCommandAllocator; + //table.CreateCommandBuffer = ::CreateCommandBuffer; + //table.CreateDescriptorPool = ::CreateDescriptorPool; + //table.CreateBuffer = ::CreateBuffer; + //table.CreateTexture = ::CreateTexture; + //table.CreateBufferView = ::CreateBufferView; + //table.CreateTexture1DView = ::CreateTexture1DView; + //table.CreateTexture2DView = ::CreateTexture2DView; + //table.CreateTexture3DView = ::CreateTexture3DView; + //table.CreateSampler = ::CreateSampler; + //table.CreatePipelineLayout = ::CreatePipelineLayout; + //table.CreateGraphicsPipeline = ::CreateGraphicsPipeline; +// table.CreateComputePipeline = ::CreateComputePipeline; +// table.CreateQueryPool = ::CreateQueryPool; +// table.CreateFence = ::CreateFence; +// table.DestroyCommandAllocator = ::DestroyCommandAllocator; +// table.DestroyCommandBuffer = ::DestroyCommandBuffer; +// table.DestroyDescriptorPool = ::DestroyDescriptorPool; +// table.DestroyBuffer = ::DestroyBuffer; +// table.DestroyTexture = ::DestroyTexture; +// table.DestroyDescriptor = ::DestroyDescriptor; +// table.DestroyPipelineLayout = ::DestroyPipelineLayout; +// table.DestroyPipeline = ::DestroyPipeline; +// table.DestroyQueryPool = ::DestroyQueryPool; +// table.DestroyFence = ::DestroyFence; +// table.AllocateMemory = ::AllocateMemory; +// table.BindBufferMemory = ::BindBufferMemory; +// table.BindTextureMemory = ::BindTextureMemory; +// table.FreeMemory = ::FreeMemory; + table.BeginCommandBuffer = ::BeginCommandBuffer; + table.CmdSetDescriptorPool = ::CmdSetDescriptorPool; + table.CmdSetDescriptorSet = ::CmdSetDescriptorSet; + table.CmdSetPipelineLayout = ::CmdSetPipelineLayout; + table.CmdSetPipeline = ::CmdSetPipeline; + table.CmdSetRootConstants = ::CmdSetRootConstants; + table.CmdSetRootDescriptor = ::CmdSetRootDescriptor; + table.CmdBarrier = ::CmdBarrier; + table.CmdSetIndexBuffer = ::CmdSetIndexBuffer; + table.CmdSetVertexBuffers = ::CmdSetVertexBuffers; + table.CmdSetViewports = ::CmdSetViewports; + table.CmdSetScissors = ::CmdSetScissors; + table.CmdSetStencilReference = ::CmdSetStencilReference; + table.CmdSetDepthBounds = ::CmdSetDepthBounds; + table.CmdSetBlendConstants = ::CmdSetBlendConstants; + table.CmdSetSampleLocations = ::CmdSetSampleLocations; + table.CmdSetShadingRate = ::CmdSetShadingRate; + table.CmdSetDepthBias = ::CmdSetDepthBias; + table.CmdBeginRendering = ::CmdBeginRendering; + table.CmdClearAttachments = ::CmdClearAttachments; + table.CmdDraw = ::CmdDraw; + table.CmdDrawIndexed = ::CmdDrawIndexed; + table.CmdDrawIndirect = ::CmdDrawIndirect; + table.CmdDrawIndexedIndirect = ::CmdDrawIndexedIndirect; + table.CmdEndRendering = ::CmdEndRendering; + table.CmdDispatch = ::CmdDispatch; + table.CmdDispatchIndirect = ::CmdDispatchIndirect; + table.CmdCopyBuffer = ::CmdCopyBuffer; + table.CmdCopyTexture = ::CmdCopyTexture; + table.CmdUploadBufferToTexture = ::CmdUploadBufferToTexture; + table.CmdReadbackTextureToBuffer = ::CmdReadbackTextureToBuffer; + table.CmdClearStorageBuffer = ::CmdClearStorageBuffer; + table.CmdClearStorageTexture = ::CmdClearStorageTexture; + table.CmdResolveTexture = ::CmdResolveTexture; + table.CmdResetQueries = ::CmdResetQueries; + table.CmdBeginQuery = ::CmdBeginQuery; + table.CmdEndQuery = ::CmdEndQuery; + table.CmdCopyQueries = ::CmdCopyQueries; + table.CmdBeginAnnotation = ::CmdBeginAnnotation; + table.CmdEndAnnotation = ::CmdEndAnnotation; + table.EndCommandBuffer = ::EndCommandBuffer; +// table.QueueSubmit = ::QueueSubmit; +// table.Wait = ::Wait; +// table.GetFenceValue = ::GetFenceValue; +// table.UpdateDescriptorRanges = ::UpdateDescriptorRanges; +// table.UpdateDynamicConstantBuffers = ::UpdateDynamicConstantBuffers; +// table.CopyDescriptorSet = ::CopyDescriptorSet; +// table.AllocateDescriptorSets = ::AllocateDescriptorSets; +// table.ResetDescriptorPool = ::ResetDescriptorPool; + table.ResetCommandAllocator = ::ResetCommandAllocator; + table.MapBuffer = ::MapBuffer; + table.UnmapBuffer = ::UnmapBuffer; +// table.SetDeviceDebugName = ::SetDeviceDebugName; +// table.SetFenceDebugName = ::SetFenceDebugName; +// table.SetDescriptorDebugName = ::SetDescriptorDebugName; +// table.SetPipelineDebugName = ::SetPipelineDebugName; + table.SetCommandBufferDebugName = ::SetCommandBufferDebugName; + table.SetBufferDebugName = ::SetBufferDebugName; +// table.SetTextureDebugName = ::SetTextureDebugName; +// table.SetCommandQueueDebugName = ::SetCommandQueueDebugName; + table.SetCommandAllocatorDebugName = ::SetCommandAllocatorDebugName; +// table.SetDescriptorPoolDebugName = ::SetDescriptorPoolDebugName; +// table.SetPipelineLayoutDebugName = ::SetPipelineLayoutDebugName; +// table.SetQueryPoolDebugName = ::SetQueryPoolDebugName; +// table.SetDescriptorSetDebugName = ::SetDescriptorSetDebugName; +// table.SetMemoryDebugName = ::SetMemoryDebugName; +// table.GetDeviceNativeObject = ::GetDeviceNativeObject; +// table.GetCommandBufferNativeObject = ::GetCommandBufferNativeObject; + table.GetBufferNativeObject = ::GetBufferNativeObject; +// table.GetTextureNativeObject = ::GetTextureNativeObject; +// table.GetDescriptorNativeObject = ::GetDescriptorNativeObject; + + return Result::SUCCESS; +} + + +#pragma endregion + +Result DeviceMTL::FillFunctionTable(HelperInterface& table) const { + return Result::SUCCESS; +} +Result DeviceMTL::FillFunctionTable(LowLatencyInterface& table) const { + + return Result::SUCCESS; +} +Result DeviceMTL::FillFunctionTable(MeshShaderInterface& table) const { + + return Result::SUCCESS; +} +Result DeviceMTL::FillFunctionTable(RayTracingInterface& table) const { + return Result::SUCCESS; +} +Result DeviceMTL::FillFunctionTable(StreamerInterface& table) const { + return Result::SUCCESS; +} +Result DeviceMTL::FillFunctionTable(SwapChainInterface& table) const { + return Result::SUCCESS; +} +Result DeviceMTL::FillFunctionTable(ResourceAllocatorInterface& table) const { + + return Result::SUCCESS; +} From 177fae3a944f0f995f6aa9e38e48f70fe559db90 Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Tue, 26 Nov 2024 21:14:48 -0800 Subject: [PATCH 22/24] feat: add memory mtl Signed-off-by: Michael Pollind --- Include/Extensions/NRIWrapperMTL.h | 14 +- Source/Metal/ConversionMTL.h | 26 +- Source/Metal/DescriptorMTL.h | 2 + Source/Metal/DescriptorMTL.mm | 4 + Source/Metal/DeviceMTL.h | 7 +- Source/Metal/DeviceMTL.hpp | 512 ++++++++++++++--------------- Source/Metal/DeviceMTL.mm | 27 +- Source/Metal/ImplMTL.mm | 26 ++ Source/Metal/MemoryMTL.h | 9 +- Source/Metal/MemoryMTL.mm | 15 +- Source/Metal/SharedMTL.h | 11 +- Source/Metal/SwapChainMTL.h | 11 +- Source/Metal/SwapChainMTL.mm | 15 + Source/Metal/TextureMTL.h | 4 +- Source/Metal/TextureMTL.mm | 28 +- 15 files changed, 410 insertions(+), 301 deletions(-) diff --git a/Include/Extensions/NRIWrapperMTL.h b/Include/Extensions/NRIWrapperMTL.h index 3425a15..a560999 100644 --- a/Include/Extensions/NRIWrapperMTL.h +++ b/Include/Extensions/NRIWrapperMTL.h @@ -2,12 +2,17 @@ #pragma once +#include "NRIMacro.h" #include "NRIDeviceCreation.h" + NriNamespaceBegin -typedef void* MTLBufferHandle; -typedef void* MTLTextureHandle; + +NonNriForwardStruct(MTLHeap); + +typedef void* MTLBufferHandle; // id +typedef void* MTLTextureHandle; typedef void* MTLDeviceHandle; NriStruct(DeviceCreationMTLDesc) @@ -36,8 +41,9 @@ NriStruct(TextureMTLDesc) NriStruct(MemoryMTLDesc) { - MTLBufferHandle buffer; - void* mappedMemory; + uint64_t size; + // MTLStorageMode storage; + //MTLResourceOptions options; }; diff --git a/Source/Metal/ConversionMTL.h b/Source/Metal/ConversionMTL.h index 7d29b47..64a45c6 100644 --- a/Source/Metal/ConversionMTL.h +++ b/Source/Metal/ConversionMTL.h @@ -4,6 +4,28 @@ namespace nri { +constexpr std::array DEFAULT_MEMORY_RESOURCE_OPTION_MEMORY_LOCATION ={ + MTLResourceStorageModePrivate, // DEVICE + MTLResourceStorageModeShared | MTLResourceCPUCacheModeWriteCombined, // DEVICE_UPLOAD + MTLResourceStorageModeShared | MTLResourceCPUCacheModeWriteCombined, // HOST_UPLOAD + MTLResourceStorageModeShared | MTLResourceCPUCacheModeDefaultCache // HOST_READBACK +}; + +constexpr std::array DEFAULT_CACHE_MODE_MEMORY_LOCATION ={ + MTLCPUCacheModeDefaultCache, // DEVICE + MTLCPUCacheModeWriteCombined, // DEVICE_UPLOAD + MTLCPUCacheModeWriteCombined, // HOST_UPLOAD + MTLCPUCacheModeDefaultCache // HOST_READBACK +}; + +constexpr std::array DEFAULT_STORAGE_MODE_MEMORY_LOCATION ={ + MTLStorageModePrivate, // DEVICE + MTLStorageModeShared, // DEVICE_UPLOAD + MTLStorageModeShared, // HOST_UPLOAD + MTLStorageModeShared // HOST_READBACK +}; + + constexpr std::array MTL_NRI_FORMAT_TO_VERTEX_FORMAT = { MTLVertexFormatInvalid, // UNKNOWN MTLVertexFormatUCharNormalized, // R8_UNORM @@ -208,8 +230,6 @@ constexpr MTLSamplerAddressMode GetSamplerAddressMode(AddressMode addressMode) { return SAMPLER_ADDRESS_MODE[(size_t)addressMode]; } - - constexpr std::array TOPOLOGIES_CLASSES = { MTLPrimitiveTopologyClassPoint, // POINT_LIST MTLPrimitiveTopologyClassLine, // LINE_LIST @@ -233,8 +253,6 @@ inline MTLVertexFormat GetVertexFormatMTL(Format format) { return (MTLVertexFormat)MTL_NRI_FORMAT_TO_VERTEX_FORMAT[(size_t)format]; } - - inline MTLPixelFormat GetFormatMTL(Format format, bool demoteSrgb = false) { if (demoteSrgb) { const FormatProps& formatProps = GetFormatProps(format); diff --git a/Source/Metal/DescriptorMTL.h b/Source/Metal/DescriptorMTL.h index 0977fb3..5ffe9a1 100644 --- a/Source/Metal/DescriptorMTL.h +++ b/Source/Metal/DescriptorMTL.h @@ -17,6 +17,8 @@ struct DescriptorMTL { : m_Device(device) { } + ~DescriptorMTL(); + inline id GetImageView() { return m_texture; } diff --git a/Source/Metal/DescriptorMTL.mm b/Source/Metal/DescriptorMTL.mm index 595a5d3..7fabc05 100644 --- a/Source/Metal/DescriptorMTL.mm +++ b/Source/Metal/DescriptorMTL.mm @@ -6,6 +6,10 @@ namespace nri { +DescriptorMTL::~DescriptorMTL() { + +} + Result DescriptorMTL::Create(const BufferViewDesc& bufferViewDesc) { // m_Type = DescriptorTypeVK::BUFFER_VIEW; const BufferMTL& buffer = *(const BufferMTL*)bufferViewDesc.buffer; diff --git a/Source/Metal/DeviceMTL.h b/Source/Metal/DeviceMTL.h index 67f3d34..e99738f 100644 --- a/Source/Metal/DeviceMTL.h +++ b/Source/Metal/DeviceMTL.h @@ -30,11 +30,12 @@ struct DeviceMTL final : public DeviceBase { return result; } - + + //void GetMemoryTypeInfo(MemoryLocation memoryLocation, MemoryDesc& memoryDesc) const; void GetMemoryDesc(const BufferDesc& bufferDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc); void GetMemoryDesc(const TextureDesc& textureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc); void GetMemoryDesc(const AccelerationStructureDesc& accelerationStructureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc); - + //bool GetMemoryTypeInfo(MemoryLocation memoryLocation, MemoryTypeInfo& memoryTypeInfo) const; const DeviceDesc& GetDesc() const override { return m_Desc; @@ -52,7 +53,7 @@ struct DeviceMTL final : public DeviceBase { Result Create(const DeviceCreationDesc& deviceCreationDesc, const DeviceCreationMTLDesc& deviceCreationVKDesc, bool isWrapper); private: - Lock m_Lock; + //Lock m_Lock; id m_Device; std::array m_CommandQueues = {}; DeviceDesc m_Desc = {}; diff --git a/Source/Metal/DeviceMTL.hpp b/Source/Metal/DeviceMTL.hpp index cb6d497..c6dd5d9 100644 --- a/Source/Metal/DeviceMTL.hpp +++ b/Source/Metal/DeviceMTL.hpp @@ -1,260 +1,260 @@ // © 2021 NVIDIA Corporation //Declare_PartiallyFillFunctionTable_Functions(MTL); - -#pragma region[ Core ] - -static const DeviceDesc& NRI_CALL GetDeviceDesc(const Device& device) { - return ((const DeviceMTL&)device).GetDesc(); -} - -static const BufferDesc& NRI_CALL GetBufferDesc(const Buffer& buffer) { - return ((const BufferMTL&)buffer).GetDesc(); -} - -static const TextureDesc& NRI_CALL GetTextureDesc(const Texture& texture) { - return ((const TextureMTL&)texture).GetDesc(); -} - -static FormatSupportBits NRI_CALL GetFormatSupport(const Device& device, Format format) { - return (FormatSupportBits)0; - //return ((const DeviceDesc&)device).GetFormatSupport(format); -} - -static void NRI_CALL GetBufferMemoryDesc(const Device& device, const BufferDesc& bufferDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { - //D3D12_RESOURCE_DESC desc = {}; - //GetResourceDesc(&desc, bufferDesc); - - //((const DeviceD3D12&)device).GetMemoryDesc(memoryLocation, desc, memoryDesc); -} - -static void NRI_CALL GetTextureMemoryDesc(const Device& device, const TextureDesc& textureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { - //return ((const DeviceMTL&)device).GetMemoryDesc(textureDesc, memoryLocation, memoryDesc); - -} - -static Result NRI_CALL GetCommandQueue(Device& device, CommandQueueType commandQueueType, CommandQueue*& commandQueue) { - return ((DeviceMTL&)device).GetCommandQueue(commandQueueType, commandQueue); -} - -static Result NRI_CALL CreateCommandAllocator(const CommandQueue& commandQueue, CommandAllocator*& commandAllocator) { - //DeviceMTL& device = ((CommandQueueD3D12&)commandQueue).GetDevice(); - //return device.CreateImplementation(commandAllocator, commandQueue); - return Result::SUCCESS; -} - -static Result NRI_CALL CreateDescriptorPool(Device& device, const DescriptorPoolDesc& descriptorPoolDesc, DescriptorPool*& descriptorPool) { - //return ((DeviceMTL&)device).CreateImplementation(descriptorPool, descriptorPoolDesc); - return Result::SUCCESS; -} - -static Result NRI_CALL CreateBuffer(Device& device, const BufferDesc& bufferDesc, Buffer*& buffer) { - return ((DeviceMTL&)device).CreateImplementation(buffer, bufferDesc); -} - -static Result NRI_CALL CreateTexture(Device& device, const TextureDesc& textureDesc, Texture*& texture) { - return ((DeviceMTL&)device).CreateImplementation(texture, textureDesc); -} - -static Result NRI_CALL CreateBufferView(const BufferViewDesc& bufferViewDesc, Descriptor*& bufferView) { - //DeviceMTL& device = ((const BufferD3D12*)bufferViewDesc.buffer)->GetDevice(); - //return device.CreateImplementation(bufferView, bufferViewDesc); - return Result::SUCCESS; -} - - -static Result NRI_CALL CreateTexture1DView(const Texture1DViewDesc& textureViewDesc, Descriptor*& textureView) { - //DeviceMTL& device = ((const TextureMTL*)textureViewDesc.texture)->GetDevice(); - //return device.CreateImplementation(textureView, textureViewDesc); - - - //DeviceMTL& device = ((const TextureD3D12*)textureViewDesc.texture)->GetDevice(); - //return device.CreateImplementation(textureView, textureViewDesc); - return Result::SUCCESS; -} - -static Result NRI_CALL CreateTexture2DView(const Texture2DViewDesc& textureViewDesc, Descriptor*& textureView) { - //DeviceMTL& device = ((const TextureD3D12*)textureViewDesc.texture)->GetDevice(); - //return device.CreateImplementation(textureView, textureViewDesc); - return Result::SUCCESS; -} - -static Result NRI_CALL CreateTexture3DView(const Texture3DViewDesc& textureViewDesc, Descriptor*& textureView) { - //DeviceMTL& device = ((const TextureD3D12*)textureViewDesc.texture)->GetDevice(); - //return device.CreateImplementation(textureView, textureViewDesc); - return Result::SUCCESS; -} - -static Result NRI_CALL CreateSampler(Device& device, const SamplerDesc& samplerDesc, Descriptor*& sampler) { - //return ((DeviceMTL&)device).CreateImplementation(sampler, samplerDesc); - return Result::SUCCESS; -} - -static Result NRI_CALL CreatePipelineLayout(Device& device, const PipelineLayoutDesc& pipelineLayoutDesc, PipelineLayout*& pipelineLayout) { - //return ((DeviceMTL&)device).CreateImplementation(pipelineLayout, pipelineLayoutDesc); - return Result::SUCCESS; -} - -static Result NRI_CALL CreateGraphicsPipeline(Device& device, const GraphicsPipelineDesc& graphicsPipelineDesc, Pipeline*& pipeline) { - //return ((DeviceMTL&)device).CreateImplementation(pipeline, graphicsPipelineDesc); - return Result::SUCCESS; -} - -static Result NRI_CALL CreateComputePipeline(Device& device, const ComputePipelineDesc& computePipelineDesc, Pipeline*& pipeline) { - //return ((DeviceMTL&)device).CreateImplementation(pipeline, computePipelineDesc); - return Result::SUCCESS; -} - -static Result NRI_CALL CreateFence(Device& device, uint64_t initialValue, Fence*& fence) { - //return ((DeviceMTL&)device).CreateImplementation(fence, initialValue); - return Result::SUCCESS; -} - -static Result NRI_CALL CreateQueryPool(Device& device, const QueryPoolDesc& queryPoolDesc, QueryPool*& queryPool) { - //return ((DeviceMTL&)device).CreateImplementation(queryPool, queryPoolDesc); - return Result::SUCCESS; -} - -static void NRI_CALL DestroyCommandBuffer(CommandBuffer& commandBuffer) { - //Destroy((CommandBufferD3D12*)&commandBuffer); -} - -static void NRI_CALL DestroyCommandAllocator(CommandAllocator& commandAllocator) { - //Destroy((CommandAllocatorD3D12*)&commandAllocator); -} - -static void NRI_CALL DestroyDescriptorPool(DescriptorPool& descriptorPool) { - //Destroy((DescriptorPoolD3D12*)&descriptorPool); -} - -static void NRI_CALL DestroyBuffer(Buffer& buffer) { - //Destroy((BufferD3D12*)&buffer); -} - -static void NRI_CALL DestroyTexture(Texture& texture) { - //Destroy((TextureD3D12*)&texture); -} - -static void NRI_CALL DestroyDescriptor(Descriptor& descriptor) { - //Destroy((DescriptorD3D12*)&descriptor); -} - -static void NRI_CALL DestroyPipelineLayout(PipelineLayout& pipelineLayout) { - //Destroy((PipelineLayoutD3D12*)&pipelineLayout); -} - -static void NRI_CALL DestroyPipeline(Pipeline& pipeline) { - //Destroy((PipelineD3D12*)&pipeline); -} - -static void NRI_CALL DestroyQueryPool(QueryPool& queryPool) { - //Destroy((QueryPoolD3D12*)&queryPool); -} - -static void NRI_CALL DestroyFence(Fence& fence) { - Destroy((FenceMTL*)&fence); -} - -static Result NRI_CALL AllocateMemory(Device& device, const AllocateMemoryDesc& allocateMemoryDesc, Memory*& memory) { - return Result::SUCCESS; - //return ((DeviceMTL&)device).CreateImplementation(memory, allocateMemoryDesc); -} - -static Result NRI_CALL BindBufferMemory(Device& device, const BufferMemoryBindingDesc* memoryBindingDescs, uint32_t memoryBindingDescNum) { - //return ((DeviceMTL&)device).BindBufferMemory(memoryBindingDescs, memoryBindingDescNum); - return Result::SUCCESS; -} - -static Result NRI_CALL BindTextureMemory(Device& device, const TextureMemoryBindingDesc* memoryBindingDescs, uint32_t memoryBindingDescNum) { - //return ((DeviceMTL&)device).BindTextureMemory(memoryBindingDescs, memoryBindingDescNum); - return Result::SUCCESS; -} - -static void NRI_CALL FreeMemory(Memory& memory) { -// Destroy((MemoryD3D12*)&memory); -} - -static void NRI_CALL SetDeviceDebugName(Device& device, const char* name) { -// ((DeviceMTL&)device).SetDebugName(name); -} - -static void NRI_CALL SetPipelineDebugName(Pipeline& pipeline, const char* name) { -// ((PipelineD3D12&)pipeline).SetDebugName(name); -} - -static void NRI_CALL SetPipelineLayoutDebugName(PipelineLayout& pipelineLayout, const char* name) { -// ((PipelineLayoutD3D12&)pipelineLayout).SetDebugName(name); -} - -static void NRI_CALL SetMemoryDebugName(Memory& memory, const char* name) { -// ((MemoryMetal&)memory).SetDebugName(name); -} - -static void* NRI_CALL GetDeviceNativeObject(const Device& device) { - if (!(&device)) - return nullptr; - return (DeviceMTL*)&((DeviceMTL&)device); - - //return ((DeviceMetal&)device).GetNativeObject(); -} - -Result DeviceMTL::FillFunctionTable(CoreInterface& table) const { - table = {}; - // Core_Device_PartiallyFillFunctionTableMTL(table); - // Core_Buffer_PartiallyFillFunctionTableMTL(table); - // Core_CommandAllocator_PartiallyFillFunctionTableMTL(table); - // Core_CommandBuffer_PartiallyFillFunctionTableMTL(table); - // Core_CommandQueue_PartiallyFillFunctionTableMTL(table); - // Core_Descriptor_PartiallyFillFunctionTableMTL(table); - // Core_DescriptorPool_PartiallyFillFunctionTableMTL(table); - // Core_DescriptorSet_PartiallyFillFunctionTableMTL(table); - // Core_Fence_PartiallyFillFunctionTableMTL(table); - // Core_QueryPool_PartiallyFillFunctionTableMTL(table); - // Core_Texture_PartiallyFillFunctionTableMTL(table); - // return ValidateFunctionTable(table); - return Result::UNSUPPORTED; -} - -#pragma endregion - -Result DeviceMTL::FillFunctionTable(HelperInterface& table) const { - table = {}; - return Result::UNSUPPORTED; -} - -Result DeviceMTL::FillFunctionTable(LowLatencyInterface& table) const { - table = {}; - return Result::UNSUPPORTED; -} - -//Result DeviceMTL::FillFunctionTable(MeshShaderInterface& table) const { -// table = {}; -// return Result::UNSUPPORTED; +// +//#pragma region[ Core ] +// +//static const DeviceDesc& NRI_CALL GetDeviceDesc(const Device& device) { +// return ((const DeviceMTL&)device).GetDesc(); //} - -Result DeviceMTL::FillFunctionTable(RayTracingInterface& table) const { - table = {}; - return Result::UNSUPPORTED; -} - -Result DeviceMTL::FillFunctionTable(StreamerInterface& table) const { - table = {}; - return Result::UNSUPPORTED; -} - -Result DeviceMTL::FillFunctionTable(SwapChainInterface& table) const { - table = {}; - return Result::UNSUPPORTED; -} - -Result DeviceMTL::FillFunctionTable(ResourceAllocatorInterface& table) const { - table = {}; - return Result::UNSUPPORTED; -} - -//Dfine_Core_Device_PartiallyFillFunctionTable(MTL); -//Define_Helper_Device_PartiallyFillFunctionTable(MTL); -//Define_RayTracing_Device_PartiallyFillFunctionTable(MTL); -//Define_Streamer_Device_PartiallyFillFunctionTable(MTL); -//Define_SwapChain_Device_PartiallyFillFunctionTable(MTL); -//Define_ResourceAllocator_Device_PartiallyFillFunctionTable(MTL); +// +//static const BufferDesc& NRI_CALL GetBufferDesc(const Buffer& buffer) { +// return ((const BufferMTL&)buffer).GetDesc(); +//} +// +//static const TextureDesc& NRI_CALL GetTextureDesc(const Texture& texture) { +// return ((const TextureMTL&)texture).GetDesc(); +//} +// +//static FormatSupportBits NRI_CALL GetFormatSupport(const Device& device, Format format) { +// return (FormatSupportBits)0; +// //return ((const DeviceDesc&)device).GetFormatSupport(format); +//} +// +//static void NRI_CALL GetBufferMemoryDesc(const Device& device, const BufferDesc& bufferDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { +// //D3D12_RESOURCE_DESC desc = {}; +// //GetResourceDesc(&desc, bufferDesc); +// +// //((const DeviceD3D12&)device).GetMemoryDesc(memoryLocation, desc, memoryDesc); +//} +// +//static void NRI_CALL GetTextureMemoryDesc(const Device& device, const TextureDesc& textureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { +// //return ((const DeviceMTL&)device).GetMemoryDesc(textureDesc, memoryLocation, memoryDesc); +// +//} +// +//static Result NRI_CALL GetCommandQueue(Device& device, CommandQueueType commandQueueType, CommandQueue*& commandQueue) { +// return ((DeviceMTL&)device).GetCommandQueue(commandQueueType, commandQueue); +//} +// +//static Result NRI_CALL CreateCommandAllocator(const CommandQueue& commandQueue, CommandAllocator*& commandAllocator) { +// //DeviceMTL& device = ((CommandQueueD3D12&)commandQueue).GetDevice(); +// //return device.CreateImplementation(commandAllocator, commandQueue); +// return Result::SUCCESS; +//} +// +//static Result NRI_CALL CreateDescriptorPool(Device& device, const DescriptorPoolDesc& descriptorPoolDesc, DescriptorPool*& descriptorPool) { +// //return ((DeviceMTL&)device).CreateImplementation(descriptorPool, descriptorPoolDesc); +// return Result::SUCCESS; +//} +// +//static Result NRI_CALL CreateBuffer(Device& device, const BufferDesc& bufferDesc, Buffer*& buffer) { +// return ((DeviceMTL&)device).CreateImplementation(buffer, bufferDesc); +//} +// +//static Result NRI_CALL CreateTexture(Device& device, const TextureDesc& textureDesc, Texture*& texture) { +// return ((DeviceMTL&)device).CreateImplementation(texture, textureDesc); +//} +// +//static Result NRI_CALL CreateBufferView(const BufferViewDesc& bufferViewDesc, Descriptor*& bufferView) { +// //DeviceMTL& device = ((const BufferD3D12*)bufferViewDesc.buffer)->GetDevice(); +// //return device.CreateImplementation(bufferView, bufferViewDesc); +// return Result::SUCCESS; +//} +// +// +//static Result NRI_CALL CreateTexture1DView(const Texture1DViewDesc& textureViewDesc, Descriptor*& textureView) { +// //DeviceMTL& device = ((const TextureMTL*)textureViewDesc.texture)->GetDevice(); +// //return device.CreateImplementation(textureView, textureViewDesc); +// +// +// //DeviceMTL& device = ((const TextureD3D12*)textureViewDesc.texture)->GetDevice(); +// //return device.CreateImplementation(textureView, textureViewDesc); +// return Result::SUCCESS; +//} +// +//static Result NRI_CALL CreateTexture2DView(const Texture2DViewDesc& textureViewDesc, Descriptor*& textureView) { +// //DeviceMTL& device = ((const TextureD3D12*)textureViewDesc.texture)->GetDevice(); +// //return device.CreateImplementation(textureView, textureViewDesc); +// return Result::SUCCESS; +//} +// +//static Result NRI_CALL CreateTexture3DView(const Texture3DViewDesc& textureViewDesc, Descriptor*& textureView) { +// //DeviceMTL& device = ((const TextureD3D12*)textureViewDesc.texture)->GetDevice(); +// //return device.CreateImplementation(textureView, textureViewDesc); +// return Result::SUCCESS; +//} +// +//static Result NRI_CALL CreateSampler(Device& device, const SamplerDesc& samplerDesc, Descriptor*& sampler) { +// //return ((DeviceMTL&)device).CreateImplementation(sampler, samplerDesc); +// return Result::SUCCESS; +//} +// +//static Result NRI_CALL CreatePipelineLayout(Device& device, const PipelineLayoutDesc& pipelineLayoutDesc, PipelineLayout*& pipelineLayout) { +// //return ((DeviceMTL&)device).CreateImplementation(pipelineLayout, pipelineLayoutDesc); +// return Result::SUCCESS; +//} +// +//static Result NRI_CALL CreateGraphicsPipeline(Device& device, const GraphicsPipelineDesc& graphicsPipelineDesc, Pipeline*& pipeline) { +// //return ((DeviceMTL&)device).CreateImplementation(pipeline, graphicsPipelineDesc); +// return Result::SUCCESS; +//} +// +//static Result NRI_CALL CreateComputePipeline(Device& device, const ComputePipelineDesc& computePipelineDesc, Pipeline*& pipeline) { +// //return ((DeviceMTL&)device).CreateImplementation(pipeline, computePipelineDesc); +// return Result::SUCCESS; +//} +// +//static Result NRI_CALL CreateFence(Device& device, uint64_t initialValue, Fence*& fence) { +// //return ((DeviceMTL&)device).CreateImplementation(fence, initialValue); +// return Result::SUCCESS; +//} +// +//static Result NRI_CALL CreateQueryPool(Device& device, const QueryPoolDesc& queryPoolDesc, QueryPool*& queryPool) { +// //return ((DeviceMTL&)device).CreateImplementation(queryPool, queryPoolDesc); +// return Result::SUCCESS; +//} +// +//static void NRI_CALL DestroyCommandBuffer(CommandBuffer& commandBuffer) { +// //Destroy((CommandBufferD3D12*)&commandBuffer); +//} +// +//static void NRI_CALL DestroyCommandAllocator(CommandAllocator& commandAllocator) { +// //Destroy((CommandAllocatorD3D12*)&commandAllocator); +//} +// +//static void NRI_CALL DestroyDescriptorPool(DescriptorPool& descriptorPool) { +// //Destroy((DescriptorPoolD3D12*)&descriptorPool); +//} +// +//static void NRI_CALL DestroyBuffer(Buffer& buffer) { +// //Destroy((BufferD3D12*)&buffer); +//} +// +//static void NRI_CALL DestroyTexture(Texture& texture) { +// //Destroy((TextureD3D12*)&texture); +//} +// +//static void NRI_CALL DestroyDescriptor(Descriptor& descriptor) { +// //Destroy((DescriptorD3D12*)&descriptor); +//} +// +//static void NRI_CALL DestroyPipelineLayout(PipelineLayout& pipelineLayout) { +// //Destroy((PipelineLayoutD3D12*)&pipelineLayout); +//} +// +//static void NRI_CALL DestroyPipeline(Pipeline& pipeline) { +// //Destroy((PipelineD3D12*)&pipeline); +//} +// +//static void NRI_CALL DestroyQueryPool(QueryPool& queryPool) { +// //Destroy((QueryPoolD3D12*)&queryPool); +//} +// +//static void NRI_CALL DestroyFence(Fence& fence) { +// Destroy((FenceMTL*)&fence); +//} +// +//static Result NRI_CALL AllocateMemory(Device& device, const AllocateMemoryDesc& allocateMemoryDesc, Memory*& memory) { +// return Result::SUCCESS; +// //return ((DeviceMTL&)device).CreateImplementation(memory, allocateMemoryDesc); +//} +// +//static Result NRI_CALL BindBufferMemory(Device& device, const BufferMemoryBindingDesc* memoryBindingDescs, uint32_t memoryBindingDescNum) { +// //return ((DeviceMTL&)device).BindBufferMemory(memoryBindingDescs, memoryBindingDescNum); +// return Result::SUCCESS; +//} +// +//static Result NRI_CALL BindTextureMemory(Device& device, const TextureMemoryBindingDesc* memoryBindingDescs, uint32_t memoryBindingDescNum) { +// //return ((DeviceMTL&)device).BindTextureMemory(memoryBindingDescs, memoryBindingDescNum); +// return Result::SUCCESS; +//} +// +//static void NRI_CALL FreeMemory(Memory& memory) { +//// Destroy((MemoryD3D12*)&memory); +//} +// +//static void NRI_CALL SetDeviceDebugName(Device& device, const char* name) { +//// ((DeviceMTL&)device).SetDebugName(name); +//} +// +//static void NRI_CALL SetPipelineDebugName(Pipeline& pipeline, const char* name) { +//// ((PipelineD3D12&)pipeline).SetDebugName(name); +//} +// +//static void NRI_CALL SetPipelineLayoutDebugName(PipelineLayout& pipelineLayout, const char* name) { +//// ((PipelineLayoutD3D12&)pipelineLayout).SetDebugName(name); +//} +// +//static void NRI_CALL SetMemoryDebugName(Memory& memory, const char* name) { +//// ((MemoryMetal&)memory).SetDebugName(name); +//} +// +//static void* NRI_CALL GetDeviceNativeObject(const Device& device) { +// if (!(&device)) +// return nullptr; +// return (DeviceMTL*)&((DeviceMTL&)device); +// +// //return ((DeviceMetal&)device).GetNativeObject(); +//} +// +////Result DeviceMTL::FillFunctionTable(CoreInterface& table) const { +//// table = {}; +//// // Core_Device_PartiallyFillFunctionTableMTL(table); +//// // Core_Buffer_PartiallyFillFunctionTableMTL(table); +//// // Core_CommandAllocator_PartiallyFillFunctionTableMTL(table); +//// // Core_CommandBuffer_PartiallyFillFunctionTableMTL(table); +//// // Core_CommandQueue_PartiallyFillFunctionTableMTL(table); +//// // Core_Descriptor_PartiallyFillFunctionTableMTL(table); +//// // Core_DescriptorPool_PartiallyFillFunctionTableMTL(table); +//// // Core_DescriptorSet_PartiallyFillFunctionTableMTL(table); +//// // Core_Fence_PartiallyFillFunctionTableMTL(table); +//// // Core_QueryPool_PartiallyFillFunctionTableMTL(table); +//// // Core_Texture_PartiallyFillFunctionTableMTL(table); +//// // return ValidateFunctionTable(table); +//// return Result::UNSUPPORTED; +////} +// +//#pragma endregion +// +////Result DeviceMTL::FillFunctionTable(HelperInterface& table) const { +//// table = {}; +//// return Result::UNSUPPORTED; +////} +//// +////Result DeviceMTL::FillFunctionTable(LowLatencyInterface& table) const { +//// table = {}; +//// return Result::UNSUPPORTED; +////} +// +////Result DeviceMTL::FillFunctionTable(MeshShaderInterface& table) const { +//// table = {}; +//// return Result::UNSUPPORTED; +////} +// +////Result DeviceMTL::FillFunctionTable(RayTracingInterface& table) const { +//// table = {}; +//// return Result::UNSUPPORTED; +////} +//// +////Result DeviceMTL::FillFunctionTable(StreamerInterface& table) const { +//// table = {}; +//// return Result::UNSUPPORTED; +////} +//// +////Result DeviceMTL::FillFunctionTable(SwapChainInterface& table) const { +//// table = {}; +//// return Result::UNSUPPORTED; +////} +//// +////Result DeviceMTL::FillFunctionTable(ResourceAllocatorInterface& table) const { +//// table = {}; +//// return Result::UNSUPPORTED; +////} +// +////Dfine_Core_Device_PartiallyFillFunctionTable(MTL); +////Define_Helper_Device_PartiallyFillFunctionTable(MTL); +////Define_RayTracing_Device_PartiallyFillFunctionTable(MTL); +////Define_Streamer_Device_PartiallyFillFunctionTable(MTL); +////Define_SwapChain_Device_PartiallyFillFunctionTable(MTL); +////Define_ResourceAllocator_Device_PartiallyFillFunctionTable(MTL); diff --git a/Source/Metal/DeviceMTL.mm b/Source/Metal/DeviceMTL.mm index 39877b0..0b13e89 100644 --- a/Source/Metal/DeviceMTL.mm +++ b/Source/Metal/DeviceMTL.mm @@ -63,6 +63,7 @@ static bool FindMTLGpuFamily(id device, + DeviceMTL::DeviceMTL(const CallbackInterface& callbacks, const StdAllocator& stdAllocator) : DeviceBase(callbacks, stdAllocator) { m_Desc.graphicsAPI = GraphicsAPI::VK; m_Desc.nriVersionMajor = NRI_VERSION_MAJOR; @@ -90,12 +91,24 @@ static bool FindMTLGpuFamily(id device, // } //} + void DeviceMTL::GetMemoryDesc(const BufferDesc& bufferDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { } void DeviceMTL::GetMemoryDesc(const TextureDesc& textureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { + MTLTextureDescriptor* mtlTextureDesc = [[MTLTextureDescriptor alloc] init]; + + MemoryTypeInfo memoryTypeInfo; + memoryTypeInfo.options = DEFAULT_MEMORY_RESOURCE_OPTION_MEMORY_LOCATION[(size_t)memoryLocation]; + memoryTypeInfo.cacheMode = DEFAULT_CACHE_MODE_MEMORY_LOCATION[(size_t)memoryLocation]; + memoryTypeInfo.storageMode = DEFAULT_STORAGE_MODE_MEMORY_LOCATION[(size_t)memoryLocation]; + nri::fillMTLTextureDescriptor(textureDesc, mtlTextureDesc); + const MTLSizeAndAlign sizeAlign = [m_Device heapTextureSizeAndAlignWithDescriptor: mtlTextureDesc]; + memoryDesc.size = sizeAlign.size; + memoryDesc.alignment = sizeAlign.align; + memoryDesc.type = memoryTypeInfo.value; } void DeviceMTL::GetMemoryDesc(const AccelerationStructureDesc& accelerationStructureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { @@ -104,7 +117,7 @@ static bool FindMTLGpuFamily(id device, Result DeviceMTL::GetCommandQueue(CommandQueueType commandQueueType, CommandQueue*& commandQueue) { - ExclusiveScope lock(m_Lock); + // ExclusiveScope lock(m_Lock); // Check if already created (or wrapped) uint32_t index = (uint32_t)commandQueueType; @@ -112,18 +125,6 @@ static bool FindMTLGpuFamily(id device, commandQueue = (CommandQueue*)m_CommandQueues[index]; return Result::SUCCESS; } - - // Check if supported - //uint32_t queueFamilyIndex = m_QueueFamilyIndices[index]; - //if (queueFamilyIndex == INVALID_FAMILY_INDEX) { - // commandQueue = nullptr; - // return Result::UNSUPPORTED; - //} - - // Create - //VkQueue handle = VK_NULL_HANDLE; - //m_VK.GetDeviceQueue(m_Device, queueFamilyIndex, 0, &handle); - Result result = CreateImplementation(commandQueue, commandQueueType); if (result == Result::SUCCESS) m_CommandQueues[index] = (CommandQueueMTL*)commandQueue; diff --git a/Source/Metal/ImplMTL.mm b/Source/Metal/ImplMTL.mm index cdb30b9..33c119f 100644 --- a/Source/Metal/ImplMTL.mm +++ b/Source/Metal/ImplMTL.mm @@ -8,12 +8,17 @@ #include "CommandAllocatorMTL.h" #include "CommandBufferMTL.h" #include "DeviceMTL.h" +#include "DescriptorMTL.h" +#include "TextureMTL.h" Result CreateDeviceMTL(const DeviceCreationDesc& desc, DeviceBase*& device) { StdAllocator allocator(desc.allocationCallbacks); DeviceMTL* impl = Allocate(allocator, desc.callbackInterface, allocator); Result result = impl->Create(desc, {}, false); + + MTLPurgeableState a; + MTLStorageMode mode; if (result != Result::SUCCESS) { Destroy(allocator, impl); device = nullptr; @@ -234,6 +239,27 @@ static void NRI_CALL CmdResetQueries(CommandBuffer& commandBuffer, const QueryPo return ((DeviceMTL&)device).GetDesc(); } +//static Result NRI_CALL CreateBufferView(const BufferViewDesc& bufferViewDesc, Descriptor*& bufferView) { +// DeviceMTL& device = ((const BufferMTL*)bufferViewDesc.buffer)->GetDevice(); +// return device.CreateImplementation(bufferView, bufferViewDesc); +//} +// +//static Result NRI_CALL CreateTexture1DView(const Texture1DViewDesc& textureViewDesc, Descriptor*& textureView) { +// DeviceMTL& device = ((const TextureMTL*)textureViewDesc.texture)->GetDevice(); +// return device.CreateImplementation(textureView, textureViewDesc); +//} +// +//static Result NRI_CALL CreateTexture2DView(const Texture2DViewDesc& textureViewDesc, Descriptor*& textureView) { +// DeviceMTL& device = ((const TextureMTL*)textureViewDesc.texture)->GetDevice(); +// return device.CreateImplementation(textureView, textureViewDesc); +//} +// +//static Result NRI_CALL CreateTexture3DView(const Texture3DViewDesc& textureViewDesc, Descriptor*& textureView) { +// DeviceMTL& device = ((const TextureMTL*)textureViewDesc.texture)->GetDevice(); +// return device.CreateImplementation(textureView, textureViewDesc); +//} + + //static void NRI_CALL QueueSubmit(CommandQueue& commandQueue, const QueueSubmitDesc& workSubmissionDesc) { // ((CommandQueueMTL&)commandQueue).Submit(workSubmissionDesc, nullptr); //} diff --git a/Source/Metal/MemoryMTL.h b/Source/Metal/MemoryMTL.h index 9ab89d5..a8deeb2 100644 --- a/Source/Metal/MemoryMTL.h +++ b/Source/Metal/MemoryMTL.h @@ -16,8 +16,8 @@ struct MemoryMTL { : m_Device(device) { } - inline id GetHandle() const { - return m_Buffer; + inline id GetHandle() const { + return m_Handle; } inline DeviceMTL& GetDevice() const { @@ -33,7 +33,7 @@ struct MemoryMTL { } ~MemoryMTL(); - + Result Create(const MemoryMTLDesc& memoryDesc); Result Create(const AllocateMemoryDesc& allocateMemoryDesc); //Result CreateDedicated(const BufferVK& buffer); @@ -42,12 +42,11 @@ struct MemoryMTL { //================================================================================================================ // NRI //================================================================================================================ - void SetDebugName(const char* name); private: DeviceMTL& m_Device; - id m_Buffer; + id m_Handle; uint8_t* m_MappedMemory = nullptr; MemoryType m_Type = std::numeric_limits::max(); float m_Priority = 0.0f; diff --git a/Source/Metal/MemoryMTL.mm b/Source/Metal/MemoryMTL.mm index b94511c..18aa052 100644 --- a/Source/Metal/MemoryMTL.mm +++ b/Source/Metal/MemoryMTL.mm @@ -12,7 +12,18 @@ //} } +Result MemoryMTL::Create(const AllocateMemoryDesc& allocateMemoryDesc) { + MTLHeapDescriptor* heapDescriptor = [[MTLHeapDescriptor alloc] init]; + [heapDescriptor setSize:allocateMemoryDesc.size]; + +} + Result MemoryMTL::Create(const MemoryMTLDesc& memoryDesc) { + MTLHeapDescriptor* heapDescriptor = [[MTLHeapDescriptor alloc] init]; + [heapDescriptor setSize:memoryDesc.size]; + + // [heapDescriptor setStorageMode:memoryDesc.storage]; + // if (!memoryDesc.vkDeviceMemory) // return Result::INVALID_ARGUMENT; @@ -21,9 +32,9 @@ //bool found = m_Device.GetMemoryTypeByIndex(memoryDesc.memoryTypeIndex, memoryTypeInfo); //RETURN_ON_FAILURE(&m_Device, found, Result::INVALID_ARGUMENT, "Can't find memory by index"); - m_OwnsNativeObjects = false; +// m_OwnsNativeObjects = false; // m_Buffer = memoryDesc.buffer; - m_MappedMemory = (uint8_t*)memoryDesc.mappedMemory; +// m_MappedMemory = (uint8_t*)memoryDesc.mappedMemory; // m_Type = memoryDesc.options; // const auto& mtl = m_Device.GetDispatchTable(); diff --git a/Source/Metal/SharedMTL.h b/Source/Metal/SharedMTL.h index 58262f0..4c23611 100644 --- a/Source/Metal/SharedMTL.h +++ b/Source/Metal/SharedMTL.h @@ -5,4 +5,13 @@ #include "ConversionMTL.h" #include "DeviceMTL.h" - +struct MemoryTypeInfo { + union { + uint32_t value; + struct { + uint32_t options: 16; // MTLResourceOptions + uint32_t storageMode: 4; // MTLStorageMode + uint32_t cacheMode: 2; // MTLCPUCacheMode + }; + }; +}; diff --git a/Source/Metal/SwapChainMTL.h b/Source/Metal/SwapChainMTL.h index b2de4e6..567d03b 100644 --- a/Source/Metal/SwapChainMTL.h +++ b/Source/Metal/SwapChainMTL.h @@ -1,5 +1,3 @@ -// © 2021 NVIDIA Corporation - #pragma once namespace nri { @@ -8,12 +6,17 @@ namespace nri { constexpr uint32_t MAX_NUMBER_OF_FRAMES_IN_FLIGHT = 8; struct SwapChainMTL: public DisplayDescHelper { - SwapChainVK(DeviceMTL& device); - ~SwapChainVK(); + SwapChainMTL(DeviceMTL& device) + : m_Device(device) { + + } + ~SwapChainMTL(); Result Create(const SwapChainDesc& swapChainDesc); private: + CAMetalLayer* m_MetalLayer; + DeviceMTL& m_Device; uint64_t m_PresentId = 0; uint32_t m_TextureIndex = 0; diff --git a/Source/Metal/SwapChainMTL.mm b/Source/Metal/SwapChainMTL.mm index e69de29..f2bad95 100644 --- a/Source/Metal/SwapChainMTL.mm +++ b/Source/Metal/SwapChainMTL.mm @@ -0,0 +1,15 @@ +#include "SharedMTL.h" + +#include "SwapChainMTL.h" + +using namespace nri; + + +SwapChainMTL::~SwapChainMTL() { + +} + +Result SwapChainMTL::Create(const SwapChainDesc& swapChainDesc) { + m_MetalLayer = (CAMetalLayer*)swapChainDesc.window.metal.caMetalLayer; + +} diff --git a/Source/Metal/TextureMTL.h b/Source/Metal/TextureMTL.h index a88c981..7f60993 100644 --- a/Source/Metal/TextureMTL.h +++ b/Source/Metal/TextureMTL.h @@ -7,8 +7,10 @@ namespace nri { struct DeviceMTL; -struct TextureMTL { +void fillMTLTextureDescriptor(const TextureDesc& textureDesc, MTLTextureDescriptor* mtlDescriptor); +struct TextureMTL { +public: inline TextureMTL(DeviceMTL& device) : m_Device(device) { } diff --git a/Source/Metal/TextureMTL.mm b/Source/Metal/TextureMTL.mm index b66fcb0..ed6ec63 100644 --- a/Source/Metal/TextureMTL.mm +++ b/Source/Metal/TextureMTL.mm @@ -8,6 +8,16 @@ m_Handle = nil; } +void nri::fillMTLTextureDescriptor(const TextureDesc& textureDesc, MTLTextureDescriptor* info) { + info.textureType = ::GetImageTypeMTL(textureDesc.type); + info.pixelFormat = ::GetFormatMTL(textureDesc.format, true); + info.width = textureDesc.width; + info.height = textureDesc.height; + info.depth = textureDesc.depth; + info.mipmapLevelCount = textureDesc.mipNum; + info.sampleCount = textureDesc.sampleNum; + info.arrayLength = textureDesc.layerNum; +} //Result TextureMTL::Create(const TextureMTLDesc& textureDesc) { // m_Handle = texturedesc.texture; @@ -17,15 +27,17 @@ Result TextureMTL::Create(const TextureDesc& textureDesc) { MTLTextureDescriptor* info = [[MTLTextureDescriptor alloc] init]; - info.textureType = ::GetImageTypeMTL(textureDesc.type); - info.pixelFormat = ::GetFormatMTL(textureDesc.format, true); - info.width = textureDesc.width; - info.height = textureDesc.height; - info.depth = textureDesc.depth; - info.mipmapLevelCount = textureDesc.mipNum; - info.sampleCount = textureDesc.sampleNum; - info.arrayLength = textureDesc.layerNum; + fillMTLTextureDescriptor(textureDesc, info); +// info.textureType = ::GetImageTypeMTL(textureDesc.type); +// info.pixelFormat = ::GetFormatMTL(textureDesc.format, true); +// info.width = textureDesc.width; +// info.height = textureDesc.height; +// info.depth = textureDesc.depth; +// info.mipmapLevelCount = textureDesc.mipNum; +// info.sampleCount = textureDesc.sampleNum; +// info.arrayLength = textureDesc.layerNum; +// m_Handle = [m_Device newTextureWithDescriptor:info]; m_Desc = textureDesc; From 4b283c0b60445e633807cd633abc6b91505f8a49 Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Thu, 28 Nov 2024 21:02:53 -0800 Subject: [PATCH 23/24] feat: more progress Signed-off-by: Michael Pollind --- Include/Extensions/NRIWrapperMTL.h | 5 +- Source/Metal/BufferMTL.h | 21 +- Source/Metal/BufferMTL.mm | 41 ++-- Source/Metal/CommandBufferMTL.h | 2 + Source/Metal/CommandBufferMTL.mm | 35 +-- Source/Metal/ConversionMTL.h | 18 +- Source/Metal/DescriptorMTL.h | 42 +++- Source/Metal/DescriptorMTL.mm | 68 +++++- Source/Metal/DescriptorPoolMTL.h | 47 ++++ Source/Metal/DescriptorPoolMTL.mm | 29 +++ Source/Metal/DescriptorSetMTL.h | 29 +++ Source/Metal/DescriptorSetMTL.mm | 36 +++ Source/Metal/DeviceMTL.h | 15 +- Source/Metal/DeviceMTL.mm | 338 +++++++++++++++++++++-------- Source/Metal/ImplMTL.mm | 113 ++++++++-- Source/Metal/MemoryMTL.h | 15 +- Source/Metal/MemoryMTL.mm | 68 +++--- Source/Metal/PipelineMTL.h | 13 +- Source/Metal/PipelineMTL.mm | 45 ++++ Source/Metal/TextureMTL.h | 15 +- Source/Metal/TextureMTL.mm | 41 ++-- Source/Shared/SharedExternal.h | 2 + 22 files changed, 818 insertions(+), 220 deletions(-) create mode 100644 Source/Metal/DescriptorPoolMTL.h create mode 100644 Source/Metal/DescriptorPoolMTL.mm create mode 100644 Source/Metal/DescriptorSetMTL.h create mode 100644 Source/Metal/DescriptorSetMTL.mm diff --git a/Include/Extensions/NRIWrapperMTL.h b/Include/Extensions/NRIWrapperMTL.h index a560999..277be62 100644 --- a/Include/Extensions/NRIWrapperMTL.h +++ b/Include/Extensions/NRIWrapperMTL.h @@ -9,11 +9,10 @@ NriNamespaceBegin -NonNriForwardStruct(MTLHeap); - +typedef void* MTLHeap; +typedef void* MTLDeviceHandle; // id typedef void* MTLBufferHandle; // id typedef void* MTLTextureHandle; -typedef void* MTLDeviceHandle; NriStruct(DeviceCreationMTLDesc) { diff --git a/Source/Metal/BufferMTL.h b/Source/Metal/BufferMTL.h index dac53dd..9604cef 100644 --- a/Source/Metal/BufferMTL.h +++ b/Source/Metal/BufferMTL.h @@ -14,8 +14,10 @@ struct BufferMTL { : m_Device(device) { } + ~BufferMTL(); + inline id GetHandle() const { - return pBuffer; + return m_Handle; } inline DeviceMTL& GetDevice() const { @@ -28,17 +30,22 @@ struct BufferMTL { void* Map(uint64_t offset, uint64_t size); void Unmap(); - void SetDebugName(const char* name); - - ~BufferMTL(); + void FinishMemoryBinding(MemoryMTL& memory, uint64_t memoryOffset); Result Create(const BufferDesc& bufferDesc); - Result Create(const BufferVKDesc& bufferDesc); - Result Create(const AllocateBufferDesc& bufferDesc); + //================================================================================================================ + // NRI + //================================================================================================================ + + void SetDebugName(const char* name); + private: + void UpdateLabel(); + + NSString* m_Label = nullptr; DeviceMTL& m_Device; - id pBuffer; + id m_Handle; uint8_t* m_MappedMemory = nullptr; uint64_t m_MappedMemoryOffset = 0; uint64_t m_MappedMemoryRangeSize = 0; diff --git a/Source/Metal/BufferMTL.mm b/Source/Metal/BufferMTL.mm index 70d623e..2d7ae57 100644 --- a/Source/Metal/BufferMTL.mm +++ b/Source/Metal/BufferMTL.mm @@ -1,37 +1,44 @@ #include "SharedMTL.h" #include "BufferMTL.h" +#include "MemoryMTL.h" using namespace nri; - -Result BufferMTL::Create(const BufferDesc& bufferDesc) { - return Result::SUCCESS; -} - -Result BufferMTL::Create(const BufferVKDesc& bufferDesc) { - return Result::SUCCESS; +void* BufferMTL::Map(uint64_t offset, uint64_t size) { + return (uint8_t*)[m_Handle contents] + offset; } - -void* BufferMTL::Map(uint64_t offset, uint64_t size) { - return (uint8_t*)[pBuffer contents] + offset; +BufferMTL::~BufferMTL() { + [m_Label release]; } void BufferMTL::Unmap() { } +void BufferMTL::FinishMemoryBinding(MemoryMTL& memory, uint64_t memoryOffset) { + m_Handle = [memory.GetHandle() + newBufferWithLength: m_Desc.size + options: MTLResourceCPUCacheModeDefaultCache + offset: memoryOffset]; + UpdateLabel(); +} -Result BufferMTL::Create(const AllocateBufferDesc& bufferDesc) { - return Result::SUCCESS; +void BufferMTL::UpdateLabel() { + if(m_Handle && m_Label) { + [m_Handle setLabel: m_Label]; + } } -void BufferMTL::SetDebugName(const char* name) { - - NSString* str = [NSString stringWithUTF8String:name]; - //[pBuffer addDebugMarker:name range:] - +Result BufferMTL::Create(const BufferDesc& bufferDesc) { + m_Desc = bufferDesc; +} + +void BufferMTL::SetDebugName(const char* name) { + m_Label = [NSString stringWithUTF8String:name]; + [m_Label retain]; + UpdateLabel(); } diff --git a/Source/Metal/CommandBufferMTL.h b/Source/Metal/CommandBufferMTL.h index 7034aa9..f4f0349 100644 --- a/Source/Metal/CommandBufferMTL.h +++ b/Source/Metal/CommandBufferMTL.h @@ -106,6 +106,8 @@ struct CommandBufferMTL { id m_RendererEncoder = nil; id m_ComputeEncoder = nil; + //id + CommandBufferDirtyBits m_DirtyBits = CommandBufferDirtyBits::NONE; }; }; diff --git a/Source/Metal/CommandBufferMTL.mm b/Source/Metal/CommandBufferMTL.mm index cffe549..66bd664 100644 --- a/Source/Metal/CommandBufferMTL.mm +++ b/Source/Metal/CommandBufferMTL.mm @@ -97,7 +97,7 @@ for(uint32_t i = 0; i < attachmentsDesc.colorNum; i++) { DescriptorMTL& descriptorMTL = *(DescriptorMTL*)attachmentsDesc.colors[i]; - renderPassDescriptor.colorAttachments[i].texture = descriptorMTL.GetImageView() ; + renderPassDescriptor.colorAttachments[i].texture = descriptorMTL.GetTextureHandle(); renderPassDescriptor.colorAttachments[i].clearColor = MTLClearColorMake(0, 0, 0, 1); renderPassDescriptor.colorAttachments[i].loadAction = MTLLoadActionClear; renderPassDescriptor.colorAttachments[i].storeAction = MTLStoreActionStore; @@ -107,17 +107,13 @@ if(attachmentsDesc.depthStencil) { DescriptorMTL& descriptorMTL = *(DescriptorMTL*)attachmentsDesc.depthStencil; - renderPassDescriptor.depthAttachment.texture = descriptorMTL.GetImageView(); + renderPassDescriptor.depthAttachment.texture = descriptorMTL.GetTextureHandle(); // renderPassDescriptor.depthAttachment.clearColor = MTLClearColorMake(0, 0, 0, 1); renderPassDescriptor.depthAttachment.loadAction = MTLLoadActionClear; renderPassDescriptor.depthAttachment.storeAction = MTLStoreActionStore; } - - //renderPassDescriptor.colorAttachments[ - - //renderPassDescriptor.colorAttachments - + m_RendererEncoder = [m_Handle renderCommandEncoderWithDescriptor: renderPassDescriptor]; } void CommandBufferMTL::EndRendering() { @@ -136,8 +132,7 @@ mtlViewports[i].znear = viewports[i].depthMin; mtlViewports[i].zfar = viewports[i].depthMax; } - - [m_RendererEncoder setViewports:mtlViewports count:viewportNum]; + [m_RendererEncoder setViewports: mtlViewports count: viewportNum]; } void CommandBufferMTL::SetScissors(const Rect* rects, uint32_t rectNum) { NSCAssert(m_RendererEncoder, @"encoder set"); @@ -146,9 +141,10 @@ rect.y = rects[rectNum].y; rect.width = rects[rectNum].width; rect.height = rects[rectNum].height; - [m_RendererEncoder setScissorRect:rect]; + [m_RendererEncoder setScissorRect: rect]; } void CommandBufferMTL::SetDepthBounds(float boundsMin, float boundsMax) { + } void CommandBufferMTL::SetStencilReference(uint8_t frontRef, uint8_t backRef) { [m_RendererEncoder setStencilFrontReferenceValue: frontRef backReferenceValue:backRef]; @@ -205,7 +201,7 @@ void CommandBufferMTL::DrawIndexed(const DrawIndexedDesc& drawIndexedDesc) { id indexBuffer = m_CurrentIndexCmd.m_Buffer->GetHandle(); [m_RendererEncoder drawIndexedPrimitives: m_CurrentPipeline->m_primitiveType - indexCount:drawIndexedDesc.indexNum + indexCount: drawIndexedDesc.indexNum indexType: m_CurrentIndexCmd.m_Type indexBuffer: indexBuffer indexBufferOffset: m_CurrentIndexCmd.m_Offset]; @@ -214,13 +210,24 @@ void CommandBufferMTL::DrawIndirect(const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) { // TODO: implement count Buffer NSCAssert(!countBuffer, @"count buffer not supported"); + [m_RendererEncoder - drawPrimitives: m_CurrentPipeline->m_primitiveType - indirectBuffer:((BufferMTL&)buffer).GetHandle() - indirectBufferOffset: offset]; + drawPrimitives: m_CurrentPipeline->m_primitiveType + indirectBuffer:((BufferMTL&)buffer).GetHandle() + indirectBufferOffset: offset]; } void CommandBufferMTL::DrawIndexedIndirect(const Buffer& buffer, uint64_t offset, uint32_t drawNum, uint32_t stride, const Buffer* countBuffer, uint64_t countBufferOffset) { + // m_CurrentPipeline-> + id indexBuffer = m_CurrentIndexCmd.m_Buffer->GetHandle(); + const BufferMTL& bufferImpl = (const BufferMTL&)buffer; + //const BufferMTL& bufferImpl = (const BufferMTL&)buffer; +// [m_RendererEncoder drawIndexedPrimitives: m_CurrentPipeline->m_primitiveType +// indexCount: drawIndexedDesc.indexNum +// indexType: m_CurrentIndexCmd.m_Type +// indexBuffer: indexBuffer +// indexBufferOffset: m_CurrentIndexCmd.m_Offset +// ]; } void CommandBufferMTL::Dispatch(const DispatchDesc& dispatchDesc) { diff --git a/Source/Metal/ConversionMTL.h b/Source/Metal/ConversionMTL.h index 64a45c6..f8d1e8b 100644 --- a/Source/Metal/ConversionMTL.h +++ b/Source/Metal/ConversionMTL.h @@ -220,12 +220,22 @@ constexpr MTLTriangleFillMode GetPolygonMode(FillMode fillMode) { } constexpr std::array SAMPLER_ADDRESS_MODE = { - MTLSamplerAddressModeRepeat, // REPEAT - MTLSamplerAddressModeMirrorRepeat, // MIRRORED_REPEAT - MTLSamplerAddressModeClampToEdge, // CLAMP_TO_EDGE - MTLSamplerAddressModeClampToZero // CLAMP_TO_BORDER + MTLSamplerAddressModeRepeat, // REPEAT, + MTLSamplerAddressModeMirrorRepeat, // MIRRORED_REPEAT, + MTLSamplerAddressModeClampToEdge, // CLAMP_TO_EDGE, + MTLSamplerAddressModeClampToBorderColor, // CLAMP_TO_BORDER, + MTLSamplerAddressModeClampToEdge // MIRROR_CLAMP_TO_EDGE }; +constexpr std::array MIN_MAG_FILTER = { + MTLSamplerMinMagFilterNearest, // NEAREST + MTLSamplerMinMagFilterLinear // LINEAR +}; + +constexpr MTLSamplerMinMagFilter GetFilter(Filter filter) { + return MIN_MAG_FILTER[(size_t)filter]; +} + constexpr MTLSamplerAddressMode GetSamplerAddressMode(AddressMode addressMode) { return SAMPLER_ADDRESS_MODE[(size_t)addressMode]; } diff --git a/Source/Metal/DescriptorMTL.h b/Source/Metal/DescriptorMTL.h index 5ffe9a1..d0af5c8 100644 --- a/Source/Metal/DescriptorMTL.h +++ b/Source/Metal/DescriptorMTL.h @@ -6,11 +6,20 @@ namespace nri { struct DeviceMTL; + +struct DescriptorView { +}; + enum class DescriptorTypeMTL { NONE, - IMAGE_VIEW + IMAGE_VIEW_1D, + IMAGE_VIEW_2D, + IMAGE_VIEW_3D, + SAMPLER, + BUFFER_VIEW }; + struct DescriptorMTL { public: inline DescriptorMTL (DeviceMTL& device) @@ -18,22 +27,43 @@ struct DescriptorMTL { } ~DescriptorMTL(); - - inline id GetImageView() { - return m_texture; + inline DescriptorTypeMTL GetType() { + return m_Type; + } + inline id GetTextureHandle() { + return m_Texture; + } + inline id GetBufferHandle() { + return m_Buffer; + } + inline id GetSamplerStateHandler() { + return m_SamplerState; } + inline struct BufferViewDesc& BufferView() { + return m_BufferViewDesc; + } Result Create(const BufferViewDesc& bufferViewDesc); Result Create(const Texture1DViewDesc& textureViewDesc); Result Create(const Texture2DViewDesc& textureViewDesc); Result Create(const Texture3DViewDesc& textureViewDesc); Result Create(const SamplerDesc& samplerDesc); + + private: + DeviceMTL& m_Device; + DescriptorTypeMTL m_Type = DescriptorTypeMTL::NONE; + id m_Texture; + id m_Buffer; + id m_SamplerState; + + union { + BufferViewDesc m_BufferViewDesc; + SamplerDesc m_SamplerViewDesc; + }; - id m_texture; - DescriptorTypeMTL m_type = DescriptorTypeMTL::NONE; }; diff --git a/Source/Metal/DescriptorMTL.mm b/Source/Metal/DescriptorMTL.mm index 7fabc05..fe9c189 100644 --- a/Source/Metal/DescriptorMTL.mm +++ b/Source/Metal/DescriptorMTL.mm @@ -3,6 +3,9 @@ #include "DescriptorMTL.h" #include "BufferMTL.h" +#include "TextureMTL.h" + +#include "ConversionMTL.h" namespace nri { @@ -10,25 +13,88 @@ } + Result DescriptorMTL::Create(const BufferViewDesc& bufferViewDesc) { - // m_Type = DescriptorTypeVK::BUFFER_VIEW; + m_Type = DescriptorTypeMTL::BUFFER_VIEW; const BufferMTL& buffer = *(const BufferMTL*)bufferViewDesc.buffer; return Result::SUCCESS; } + + Result DescriptorMTL::Create(const Texture1DViewDesc& textureViewDesc) { + TextureMTL& texture = *(TextureMTL*)textureViewDesc.texture; + const Mip_t remainingMips = textureViewDesc.mipNum - textureViewDesc.mipOffset; + const Dim_t remainingLayers = textureViewDesc.layerNum - textureViewDesc.layerOffset; + + NSRange level; + level.location = textureViewDesc.mipOffset; + level.length = textureViewDesc.mipNum == REMAINING_MIPS ? remainingMips: textureViewDesc.mipNum; + NSRange slices; + slices.location = textureViewDesc.layerNum; + slices.length = textureViewDesc.layerNum == REMAINING_LAYERS ? remainingLayers : textureViewDesc.layerNum; + m_Texture = [texture.GetHandle() + newTextureViewWithPixelFormat: GetFormatMTL(textureViewDesc.format) + textureType: MTLTextureType1D + levels:level + slices:slices]; + return Result::SUCCESS; } Result DescriptorMTL::Create(const Texture2DViewDesc& textureViewDesc) { + TextureMTL& texture = *(TextureMTL*)textureViewDesc.texture; + const Mip_t remainingMips = textureViewDesc.mipNum - textureViewDesc.mipOffset; + const Dim_t remainingLayers = textureViewDesc.layerNum - textureViewDesc.layerOffset; + + NSRange level; + level.location = textureViewDesc.mipOffset; + level.length = textureViewDesc.mipNum == REMAINING_MIPS ? remainingMips: textureViewDesc.mipNum; + NSRange slices; + slices.location = textureViewDesc.layerNum; + slices.length = textureViewDesc.layerNum == REMAINING_LAYERS ? remainingLayers : textureViewDesc.layerNum; + m_Texture = [texture.GetHandle() + newTextureViewWithPixelFormat: GetFormatMTL(textureViewDesc.format) + textureType: MTLTextureType2D + levels:level + slices:slices]; return Result::SUCCESS; } Result DescriptorMTL::Create(const Texture3DViewDesc& textureViewDesc){ + TextureMTL& texture = *(TextureMTL*)textureViewDesc.texture; + const Mip_t remainingMips = textureViewDesc.mipNum - textureViewDesc.mipOffset; + const Dim_t remainingLayers = textureViewDesc.sliceNum - textureViewDesc.sliceOffset; + + NSRange level; + level.location = textureViewDesc.mipOffset; + level.length = textureViewDesc.mipNum == REMAINING_MIPS ? remainingMips: textureViewDesc.mipNum; + NSRange slices; + slices.location = textureViewDesc.sliceOffset; + slices.length = textureViewDesc.sliceNum == REMAINING_LAYERS ? remainingLayers : textureViewDesc.sliceOffset; + m_Texture = [texture.GetHandle() + newTextureViewWithPixelFormat: GetFormatMTL(textureViewDesc.format) + textureType: MTLTextureType3D + levels:level + slices:slices]; + return Result::SUCCESS; } + Result DescriptorMTL::Create(const SamplerDesc& samplerDesc){ + MTLSamplerDescriptor* mtlDesc = [[MTLSamplerDescriptor alloc] init]; + [mtlDesc setMagFilter: GetFilter(samplerDesc.filters.mag)]; + [mtlDesc setMinFilter: GetFilter(samplerDesc.filters.min)]; + [mtlDesc setRAddressMode: GetSamplerAddressMode(samplerDesc.addressModes.w)]; + [mtlDesc setSAddressMode: GetSamplerAddressMode(samplerDesc.addressModes.u)]; + [mtlDesc setTAddressMode: GetSamplerAddressMode(samplerDesc.addressModes.v)]; + [mtlDesc setMaxAnisotropy: samplerDesc.anisotropy]; + [mtlDesc setCompareFunction: GetCompareOp(samplerDesc.compareFunc)]; + [mtlDesc setLodMinClamp: samplerDesc.mipMin]; + [mtlDesc setLodMaxClamp: samplerDesc.mipMax]; + m_SamplerState = [m_Device newSamplerStateWithDescriptor: mtlDesc]; + return Result::SUCCESS; } diff --git a/Source/Metal/DescriptorPoolMTL.h b/Source/Metal/DescriptorPoolMTL.h new file mode 100644 index 0000000..060fad1 --- /dev/null +++ b/Source/Metal/DescriptorPoolMTL.h @@ -0,0 +1,47 @@ +// © 2021 NVIDIA Corporation + +#pragma once + +#import + +namespace nri { + +struct DeviceMTL; +struct DescriptorSetMTL; + +struct DescriptorPoolMTL { + inline DescriptorPoolMTL(DeviceMTL& device) + : m_Device(device) + , m_AllocatedSets(device.GetStdAllocator()) { + m_AllocatedSets.reserve(64); + } +// +// inline operator VkDescriptorPool() const { +// return m_Handle; +// } +// + inline DeviceMTL& GetDevice() const { + return m_Device; + } + + ~DescriptorPoolMTL(); + + Result Create(const DescriptorPoolDesc& descriptorPoolDesc); + + //================================================================================================================ + // NRI + //================================================================================================================ + + void SetDebugName(const char* name); + void Reset(); + Result AllocateDescriptorSets(const PipelineLayout& pipelineLayout, uint32_t setIndex, DescriptorSet** descriptorSets, uint32_t instanceNum, uint32_t variableDescriptorNum); + +private: + DeviceMTL& m_Device; + Vector m_AllocatedSets; + //VkDescriptorPool m_Handle = VK_NULL_HANDLE; + uint32_t m_UsedSets = 0; + bool m_OwnsNativeObjects = true; +}; + +} // namespace nri diff --git a/Source/Metal/DescriptorPoolMTL.mm b/Source/Metal/DescriptorPoolMTL.mm new file mode 100644 index 0000000..05dd2d5 --- /dev/null +++ b/Source/Metal/DescriptorPoolMTL.mm @@ -0,0 +1,29 @@ + +#include "SharedMTL.h" +#include "DescriptorPoolMTL.h" + +using namespace nri; + + +DescriptorPoolMTL::~DescriptorPoolMTL() { + +} + +Result DescriptorPoolMTL::Create(const DescriptorPoolDesc& descriptorPoolDesc) { + +} + +//================================================================================================================ +// NRI +//================================================================================================================ + +void DescriptorPoolMTL::SetDebugName(const char* name) { + +} +void DescriptorPoolMTL::Reset() { + +} +Result DescriptorPoolMTL::AllocateDescriptorSets(const PipelineLayout& pipelineLayout, uint32_t setIndex, DescriptorSet** descriptorSets, uint32_t instanceNum, uint32_t variableDescriptorNum) { + return Result::SUCCESS; +} + diff --git a/Source/Metal/DescriptorSetMTL.h b/Source/Metal/DescriptorSetMTL.h new file mode 100644 index 0000000..61cce70 --- /dev/null +++ b/Source/Metal/DescriptorSetMTL.h @@ -0,0 +1,29 @@ +// © 2021 NVIDIA Corporation + +#pragma once + +namespace nri { + +struct DeviceVK; +struct DescriptorSetMTL { +public: + inline DescriptorSetMTL (DeviceMTL& device) + : m_Device(device) { + } + + + void UpdateDescriptorRanges(uint32_t rangeOffset, uint32_t rangeNum, const DescriptorRangeUpdateDesc* rangeUpdateDescs); + + inline id GetArgumentHandle() { + return m_ArgumentEncoder; + } + +private: + DeviceMTL& m_Device; + id m_ArgumentEncoder; + +}; + + +} // namespace nri + diff --git a/Source/Metal/DescriptorSetMTL.mm b/Source/Metal/DescriptorSetMTL.mm new file mode 100644 index 0000000..5c5b2cd --- /dev/null +++ b/Source/Metal/DescriptorSetMTL.mm @@ -0,0 +1,36 @@ + +#include "SharedMTL.h" + +#include "DescriptorSetMTL.h" +#include "DescriptorMTL.h" + +using namespace nri; + + +void DescriptorSetMTL::UpdateDescriptorRanges(uint32_t rangeOffset, uint32_t rangeNum, const DescriptorRangeUpdateDesc* rangeUpdateDescs) { + + for(size_t j = 0; j < rangeNum; j++) { + const DescriptorRangeUpdateDesc& update = rangeUpdateDescs[j]; + +// uint32_t offset = update.baseDescriptor + descriptorOffset; + + for(size_t descIdx = 0; descIdx < update.descriptorNum; descIdx++) { + + DescriptorMTL& descriptorImpl = *(DescriptorMTL*)&update.descriptors[descIdx]; + switch(descriptorImpl.GetType()) { + case DescriptorTypeMTL::IMAGE_VIEW_1D: + [m_ArgumentEncoder setTexture: descriptorImpl.GetTextureHandle() atIndex:0]; +// [m_ArgumentEncoder setTextures:<#(id _Nullable const * _Nonnull)#> withRange:<#(NSRange)#>] + break; + case DescriptorTypeMTL::IMAGE_VIEW_2D: + [m_ArgumentEncoder setTexture: descriptorImpl.GetTextureHandle() atIndex:0]; + break; + case DescriptorTypeMTL::BUFFER_VIEW: +// [m_ArgumentEncoder setBuffer: offset:<#(NSUInteger)#> atIndex:<#(NSUInteger)#>] + break; + } + +// update.descriptors[descIdx]; + } + } +} diff --git a/Source/Metal/DeviceMTL.h b/Source/Metal/DeviceMTL.h index e99738f..6839d00 100644 --- a/Source/Metal/DeviceMTL.h +++ b/Source/Metal/DeviceMTL.h @@ -7,6 +7,7 @@ namespace nri { struct CommandQueueMTL; struct DeviceMTL final : public DeviceBase { +public: DeviceMTL(const CallbackInterface& callbacks, const StdAllocator& stdAllocator); ~DeviceMTL(); @@ -17,6 +18,10 @@ struct DeviceMTL final : public DeviceBase { return m_Device; } + inline id GetHandle() const { + return m_Device; + } + template inline Result CreateImplementation(Interface*& entity, const Args&... args) { Implementation* impl = Allocate(GetStdAllocator(), *this); @@ -32,16 +37,17 @@ struct DeviceMTL final : public DeviceBase { } //void GetMemoryTypeInfo(MemoryLocation memoryLocation, MemoryDesc& memoryDesc) const; - void GetMemoryDesc(const BufferDesc& bufferDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc); - void GetMemoryDesc(const TextureDesc& textureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc); - void GetMemoryDesc(const AccelerationStructureDesc& accelerationStructureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc); + void GetMemoryDesc(const BufferDesc& bufferDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) const; + void GetMemoryDesc(const TextureDesc& textureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) const; + void GetMemoryDesc(const AccelerationStructureDesc& accelerationStructureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) const; //bool GetMemoryTypeInfo(MemoryLocation memoryLocation, MemoryTypeInfo& memoryTypeInfo) const; const DeviceDesc& GetDesc() const override { return m_Desc; } + + void Destruct() override; - Result FillFunctionTable(CoreInterface& table) const override; Result FillFunctionTable(HelperInterface& table) const override; Result FillFunctionTable(LowLatencyInterface& table) const override; @@ -59,5 +65,6 @@ struct DeviceMTL final : public DeviceBase { DeviceDesc m_Desc = {}; MTLGPUFamily m_Family; bool m_OwnsNativeObjects = true; + Lock m_Lock; }; }; // namespace nri diff --git a/Source/Metal/DeviceMTL.mm b/Source/Metal/DeviceMTL.mm index 0b13e89..244faea 100644 --- a/Source/Metal/DeviceMTL.mm +++ b/Source/Metal/DeviceMTL.mm @@ -1,74 +1,64 @@ + + #include "SharedMTL.h" #include "CommandQueueMTL.h" - #include "DeviceMTL.h" - -//#include "AccelerationStructureVK.h" #include "BufferMTL.h" -//#include "CommandAllocatorVK.h" -//#include "CommandBufferMTL.h" #include "CommandQueueMTL.h" -//#include "DescriptorPoolMTL.h" #include "TextureMTL.h" #include "FenceMTL.h" #include "MemoryMTL.h" #include "PipelineLayoutMTL.h" #include "PipelineMTL.h" - using namespace nri; + static bool FindMTLGpuFamily(id device, - MTLGPUFamily *family) { - // https://developer.apple.com/documentation/metal/mtldevice/detecting_gpu_features_and_metal_software_versions?language=objc - if (@available(macOS 10.15, iOS 10.13, *)) { - if ([device supportsFamily:MTLGPUFamilyApple7]) { - (*family) = MTLGPUFamily::MTLGPUFamilyApple7; - return true; - } - if ([device supportsFamily:MTLGPUFamilyApple6]) { - (*family) = MTLGPUFamily::MTLGPUFamilyApple6; - return true; - } - if ([device supportsFamily:MTLGPUFamilyApple5]) { - (*family) = MTLGPUFamily::MTLGPUFamilyApple5; + const MTLGPUFamily *families, size_t len, + MTLGPUFamily* current) { + for(size_t i = 0; i < len; i++) { + if( [device supportsFamily: families[i]]) { + *current = families[i]; return true; } - if ([device supportsFamily:MTLGPUFamilyApple4]) { - (*family) = MTLGPUFamily::MTLGPUFamilyApple4; - return true; - } - if ([device supportsFamily:MTLGPUFamilyApple3]) { - (*family) = MTLGPUFamily::MTLGPUFamilyApple3; - return true; - } - if ([device supportsFamily:MTLGPUFamilyApple2]) { - (*family) = MTLGPUFamily::MTLGPUFamilyApple2; - return true; - } - if ([device supportsFamily:MTLGPUFamilyApple1]) { - (*family) = MTLGPUFamily::MTLGPUFamilyApple1; - return true; - } - - // This family is no longer supported in the macOS 10.15 SDK but still - // exists so default to it. - // return MTLGPUFamily::Mac1; - (*family) = MTLGPUFamily::MTLGPUFamilyMac1; - return true; } return false; } +// referenced from Molten VK +static uint32_t GetEntryProperty(io_registry_entry_t entry, CFStringRef propertyName) { + uint32_t value = 0; + CFTypeRef cfProp = IORegistryEntrySearchCFProperty(entry, + kIOServicePlane, + propertyName, + kCFAllocatorDefault, + kIORegistryIterateRecursively | + kIORegistryIterateParents); + if (cfProp) { + const uint32_t* pValue = reinterpret_cast(CFDataGetBytePtr((CFDataRef)cfProp)); + if (pValue) { value = *pValue; } + CFRelease(cfProp); + } -DeviceMTL::DeviceMTL(const CallbackInterface& callbacks, const StdAllocator& stdAllocator) : DeviceBase(callbacks, stdAllocator) { - m_Desc.graphicsAPI = GraphicsAPI::VK; + return value; +} + + + + +DeviceMTL::DeviceMTL(const CallbackInterface& callbacks, const StdAllocator& stdAllocator) + : DeviceBase(callbacks, stdAllocator) { + + for (uint32_t i = 0; i < m_CommandQueues.size(); i++) + Destroy(GetStdAllocator(), m_CommandQueues[i]); + + m_Desc.graphicsAPI = GraphicsAPI::MTL; m_Desc.nriVersionMajor = NRI_VERSION_MAJOR; m_Desc.nriVersionMinor = NRI_VERSION_MINOR; - } @@ -92,11 +82,21 @@ static bool FindMTLGpuFamily(id device, //} -void DeviceMTL::GetMemoryDesc(const BufferDesc& bufferDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { +void DeviceMTL::GetMemoryDesc(const BufferDesc& bufferDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) const { + MemoryTypeInfo memoryTypeInfo; + memoryTypeInfo.options = DEFAULT_MEMORY_RESOURCE_OPTION_MEMORY_LOCATION[(size_t)memoryLocation]; + memoryTypeInfo.cacheMode = DEFAULT_CACHE_MODE_MEMORY_LOCATION[(size_t)memoryLocation]; + memoryTypeInfo.storageMode = DEFAULT_STORAGE_MODE_MEMORY_LOCATION[(size_t)memoryLocation]; + MTLTextureDescriptor* mtlTextureDesc = [[MTLTextureDescriptor alloc] init]; + MTLSizeAndAlign sizeAlign = [m_Device heapBufferSizeAndAlignWithLength: bufferDesc.size options: (MTLResourceOptions)memoryTypeInfo.options]; + + memoryDesc.size = sizeAlign.size; + memoryDesc.alignment = sizeAlign.align; + memoryDesc.type = memoryTypeInfo.value; } -void DeviceMTL::GetMemoryDesc(const TextureDesc& textureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { +void DeviceMTL::GetMemoryDesc(const TextureDesc& textureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) const { MTLTextureDescriptor* mtlTextureDesc = [[MTLTextureDescriptor alloc] init]; MemoryTypeInfo memoryTypeInfo; @@ -111,13 +111,17 @@ static bool FindMTLGpuFamily(id device, memoryDesc.type = memoryTypeInfo.value; } -void DeviceMTL::GetMemoryDesc(const AccelerationStructureDesc& accelerationStructureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { +void DeviceMTL::GetMemoryDesc(const AccelerationStructureDesc& accelerationStructureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) const { +// MTLAccelerationStructureDescriptor* mtlAcceleration = [[MTLAccelerationStructureDescriptor alloc] init]; +// [mtlAcceleration set] + // [m_Device heapAccelerationStructureSizeAndAlignWithSize: accelerationStructureDesc.geometryObjects] + // TODO: need to add ray traced } Result DeviceMTL::GetCommandQueue(CommandQueueType commandQueueType, CommandQueue*& commandQueue) { - // ExclusiveScope lock(m_Lock); + ExclusiveScope lock(m_Lock); // Check if already created (or wrapped) uint32_t index = (uint32_t)commandQueueType; @@ -132,22 +136,11 @@ static bool FindMTLGpuFamily(id device, return result; } -//void DeviceMTL::FillCreateInfo(const TextureDesc& textureDesc, MTLTextureDescriptor* info) const { -// info.textureType = ::GetImageTypeMTL(textureDesc.type); -// //info.pixelFormat = ::GetFormatMTL(textureDesc.format, true); -// //info.width = pDesc->mWidth; -// //info.height = pDesc->mHeight; -// //info.depth = pDesc->mDepth; -// //info.mipmapLevelCount = mipLevels; -// //info.sampleCount = pDesc->mSampleCount; -// //info.arrayLength = pDesc->mArraySize; -//} Result DeviceMTL::Create(const DeviceCreationDesc& deviceCreationDesc, const DeviceCreationMTLDesc& deviceCreationMTLDesc, bool isWrapper) { m_OwnsNativeObjects = !isWrapper; - if(isWrapper) { - // m_Device = deviceCreationMTLDesc.MtlDevice; + m_Device = *(id*)&deviceCreationMTLDesc.MtlDevice; } strncpy(m_Desc.adapterDesc.name, [m_Device.name UTF8String], sizeof(m_Desc.adapterDesc.name)); @@ -156,39 +149,210 @@ static bool FindMTLGpuFamily(id device, m_Desc.adapterDesc.vendor = nri::Vendor::APPLE; } - const uint64_t regID = [m_Device registryID]; if (regID) { - // IORef entry =AcquireIORef(IOServiceGetMatchingService(kIOMasterPortDefault, IORegistryEntryIDMatching(regID))); - // if (entry) - // { - // That returned the IOGraphicsAccelerator nub. Its parent, then, is the actual PCI device. - // IORef deviceEntry; - // if (IORegistryEntryGetParentEntry(entry, kIOServicePlane, &deviceEntry) == kIOReturnSuccess) - // { - // m_Desc.adapterDesc.vendor = GetVendorFromID(GetEntryProperty(deviceEntry, CFSTR("vendor-id"))); - // m_Desc.adapterDesc.deviceId = GetEntryProperty(deviceEntry, CFSTR("device-id")); - // } - // } + io_registry_entry_t entry = IOServiceGetMatchingService(MACH_PORT_NULL, IORegistryEntryIDMatching(regID)); + if (entry) + { + // That returned the IOGraphicsAccelerator nub. Its parent, then, is the actual PCI device. + io_registry_entry_t deviceEntry; + if (IORegistryEntryGetParentEntry(entry, kIOServicePlane, &deviceEntry) == kIOReturnSuccess) + { + m_Desc.adapterDesc.vendor = GetVendorFromID(GetEntryProperty(deviceEntry, CFSTR("vendor-id"))) ; + m_Desc.adapterDesc.deviceId = GetEntryProperty(deviceEntry, CFSTR("device-id")); + } + } + } else { + m_Desc.adapterDesc.vendor = nri::Vendor::APPLE; } - MTLGPUFamily family; - // if(!FindMTLGpuFamily(m_Device, family)) { - // return Result::UNSUPPORTED; - //} - // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf - //TODO: fill desc - switch(family) { - // case MTLGPUFamily::Apple1: - // break; - default: - break; + + MTLArgumentBuffersTier argumentBufferTier = MTLArgumentBuffersTier1; + if ([m_Device respondsToSelector: @selector(argumentBuffersSupport)]) { + argumentBufferTier = [m_Device argumentBuffersSupport]; } + + for (uint32_t sc = 1; sc <= 64; sc <<= 1) { + if([m_Device supportsTextureSampleCount: sc]) { + m_Desc.colorSampleMaxNum |= sc; + m_Desc.depthSampleMaxNum |= sc; + m_Desc.stencilSampleMaxNum |= sc; + m_Desc.zeroAttachmentsSampleMaxNum |= sc; + m_Desc.textureColorSampleMaxNum |= sc; + m_Desc.textureIntegerSampleMaxNum |= sc; + m_Desc.textureDepthSampleMaxNum |= sc; + m_Desc.textureStencilSampleMaxNum |= sc; + m_Desc.storageTextureSampleMaxNum |= sc; + } + } + + + m_Desc.viewportMaxNum = 16; + m_Desc.viewportBoundsRange[0] = -32768; + m_Desc.viewportBoundsRange[1] = 32767; + + m_Desc.attachmentMaxDim = 16384; + m_Desc.attachmentLayerMaxNum = 2048; + m_Desc.colorAttachmentMaxNum = 8; + + m_Desc.colorSampleMaxNum = 32; + m_Desc.depthSampleMaxNum = 32; + m_Desc.stencilSampleMaxNum = 32; + m_Desc.zeroAttachmentsSampleMaxNum = 32; + m_Desc.textureColorSampleMaxNum = 32; + m_Desc.textureIntegerSampleMaxNum = 32; + m_Desc.textureDepthSampleMaxNum = 32; + m_Desc.textureStencilSampleMaxNum = 32; + m_Desc.storageTextureSampleMaxNum = 32; + + m_Desc.textureArrayLayerMaxNum = 16384; + m_Desc.typedBufferMaxDim = uint32_t(-1); + + m_Desc.deviceUploadHeapSize = 256 * 1024 * 1024; + m_Desc.memoryAllocationMaxNum = uint32_t(-1); + m_Desc.samplerAllocationMaxNum = 4096; + m_Desc.constantBufferMaxRange = 64 * 1024; + m_Desc.storageBufferMaxRange = uint32_t(-1); + m_Desc.bufferTextureGranularity = 1; + m_Desc.bufferMaxSize = [m_Device maxBufferLength]; + + m_Desc.uploadBufferTextureRowAlignment = 1; + m_Desc.uploadBufferTextureSliceAlignment = 1; + m_Desc.bufferShaderResourceOffsetAlignment = 1; + m_Desc.constantBufferOffsetAlignment = 1; + m_Desc.shaderBindingTableAlignment = 1; + m_Desc.scratchBufferOffsetAlignment = 1; + + m_Desc.pipelineLayoutDescriptorSetMaxNum = 64; + m_Desc.pipelineLayoutRootConstantMaxSize = 256; + m_Desc.pipelineLayoutRootDescriptorMaxNum = 64; + + m_Desc.perStageDescriptorSamplerMaxNum = 1000000; + m_Desc.perStageDescriptorConstantBufferMaxNum = 1000000; + m_Desc.perStageDescriptorStorageBufferMaxNum = 1000000; + m_Desc.perStageDescriptorTextureMaxNum = 1000000; + m_Desc.perStageDescriptorStorageTextureMaxNum = 1000000; + m_Desc.perStageResourceMaxNum = 1000000; + + m_Desc.descriptorSetSamplerMaxNum = m_Desc.perStageDescriptorSamplerMaxNum; + m_Desc.descriptorSetConstantBufferMaxNum = m_Desc.perStageDescriptorConstantBufferMaxNum; + m_Desc.descriptorSetStorageBufferMaxNum = m_Desc.perStageDescriptorStorageBufferMaxNum; + m_Desc.descriptorSetTextureMaxNum = m_Desc.perStageDescriptorTextureMaxNum; + m_Desc.descriptorSetStorageTextureMaxNum = m_Desc.perStageDescriptorStorageTextureMaxNum; + + m_Desc.vertexShaderAttributeMaxNum = 32; + m_Desc.vertexShaderStreamMaxNum = 32; + m_Desc.vertexShaderOutputComponentMaxNum = 128; - m_Desc.adapterDesc.luid = 0; - m_Desc.adapterDesc.videoMemorySize = 0; - m_Desc.adapterDesc.systemMemorySize = 0; + m_Desc.tessControlShaderGenerationMaxLevel = 64.0f; + m_Desc.tessControlShaderPatchPointMaxNum = 32; + m_Desc.tessControlShaderPerVertexInputComponentMaxNum = 128; + m_Desc.tessControlShaderPerVertexOutputComponentMaxNum = 128; + m_Desc.tessControlShaderPerPatchOutputComponentMaxNum = 128; + m_Desc.tessControlShaderTotalOutputComponentMaxNum = m_Desc.tessControlShaderPatchPointMaxNum * m_Desc.tessControlShaderPerVertexOutputComponentMaxNum + m_Desc.tessControlShaderPerPatchOutputComponentMaxNum; + + m_Desc.tessEvaluationShaderInputComponentMaxNum = 128; + m_Desc.tessEvaluationShaderOutputComponentMaxNum = 128; + + m_Desc.geometryShaderInvocationMaxNum = 32; + m_Desc.geometryShaderInputComponentMaxNum = 128; + m_Desc.geometryShaderOutputComponentMaxNum = 128; + m_Desc.geometryShaderOutputVertexMaxNum = 1024; + m_Desc.geometryShaderTotalOutputComponentMaxNum = 1024; + + m_Desc.fragmentShaderInputComponentMaxNum = 128; + m_Desc.fragmentShaderOutputAttachmentMaxNum = 8; + m_Desc.fragmentShaderDualSourceAttachmentMaxNum = 1; + + +// m_Desc.computeShaderSharedMemoryMaxSize = [m_Device maxThreadgroupMemoryLength]; +// const MTLSize threadGroupSize = [m_Device maxThreadsPerThreadgroup]; +// //familiesm_Desc.computeShaderWorkGroupMaxNum = threadGroupSize.width; +// m_Desc.computeShaderWorkGroupMaxNum[0] = threadGroupSize.width; +// m_Desc.computeShaderWorkGroupMaxNum[1] = threadGroupSize.height; +// m_Desc.computeShaderWorkGroupMaxNum[2] = threadGroupSize.depth; + m_Desc.computeShaderSharedMemoryMaxSize = 64 * 1024; + m_Desc.computeShaderWorkGroupMaxNum[0] = 64 * 1024; + m_Desc.computeShaderWorkGroupMaxNum[1] = 64 * 1024; + m_Desc.computeShaderWorkGroupMaxNum[2] = 64 * 1024; + m_Desc.computeShaderWorkGroupInvocationMaxNum = 64 * 1024; + m_Desc.computeShaderWorkGroupMaxDim[0] = 64 * 1024; + m_Desc.computeShaderWorkGroupMaxDim[1] = 64 * 1024; + m_Desc.computeShaderWorkGroupMaxDim[2] = 64 * 1024; + + m_Desc.rayTracingShaderGroupIdentifierSize = 32; + m_Desc.rayTracingShaderTableMaxStride = (uint32_t)(-1); + m_Desc.rayTracingShaderRecursionMaxDepth = 31; + m_Desc.rayTracingGeometryObjectMaxNum = (uint32_t)(-1); + + m_Desc.meshControlSharedMemoryMaxSize = 64 * 1024; + m_Desc.meshControlWorkGroupInvocationMaxNum = 128; + m_Desc.meshControlPayloadMaxSize = 64 * 1024; + m_Desc.meshEvaluationOutputVerticesMaxNum = 256; + m_Desc.meshEvaluationOutputPrimitiveMaxNum = 256; + m_Desc.meshEvaluationOutputComponentMaxNum = 128; + m_Desc.meshEvaluationSharedMemoryMaxSize = 64 * 1024; + m_Desc.meshEvaluationWorkGroupInvocationMaxNum = 128; + + m_Desc.viewportPrecisionBits = 8; + m_Desc.subPixelPrecisionBits = 8; + m_Desc.subTexelPrecisionBits = 8; + m_Desc.mipmapPrecisionBits = 8; + + m_Desc.drawIndirectMaxNum = uint32_t(-1); + m_Desc.samplerLodBiasMin = -16.0f; + m_Desc.samplerLodBiasMax = 16.0f; + m_Desc.samplerAnisotropyMax = 16; + m_Desc.texelOffsetMin = -8; + m_Desc.texelOffsetMax = 7; + m_Desc.texelGatherOffsetMin = -8; + m_Desc.texelGatherOffsetMax = 7; + m_Desc.clipDistanceMaxNum = 8; + m_Desc.cullDistanceMaxNum = 8; + m_Desc.combinedClipAndCullDistanceMaxNum = 8; + m_Desc.shadingRateAttachmentTileSize = 16; + m_Desc.shaderModel = 69; + + m_Desc.conservativeRasterTier = 3; + m_Desc.sampleLocationsTier = 2; + m_Desc.shadingRateTier = 2; + m_Desc.bindlessTier = 2; + m_Desc.bindlessTier = 2; + + m_Desc.isRayTracingSupported = [m_Device supportsRaytracing]; + + const MTLGPUFamily appleFamilyGPUs[] = { + MTLGPUFamilyApple9, + MTLGPUFamilyApple8, + MTLGPUFamilyApple7, + MTLGPUFamilyApple6, + MTLGPUFamilyApple5, + MTLGPUFamilyApple4, + MTLGPUFamilyApple3, + MTLGPUFamilyApple2, + MTLGPUFamilyApple1 + }; + + const MTLGPUFamily macFamilyGPUs[] = { + MTLGPUFamilyMac2 + }; + + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf + MTLGPUFamily maxSelectedGPU; + m_Desc.texture3DMaxDim = 2048; + if(FindMTLGpuFamily(m_Device, appleFamilyGPUs, GetCountOf(appleFamilyGPUs), &maxSelectedGPU)) { + m_Desc.texture2DMaxDim = (maxSelectedGPU >= MTLGPUFamilyApple3) ? 16384 : 8192; + m_Desc.texture1DMaxDim = (maxSelectedGPU >= MTLGPUFamilyApple3) ? 16384 : 8192; + + } else if(FindMTLGpuFamily(m_Device, macFamilyGPUs, GetCountOf(macFamilyGPUs), &maxSelectedGPU)) { + m_Desc.texture2DMaxDim = 16384; + m_Desc.texture1DMaxDim = 16384; + } else { + return Result::UNSUPPORTED; + } + + return Result::SUCCESS; } diff --git a/Source/Metal/ImplMTL.mm b/Source/Metal/ImplMTL.mm index 33c119f..bca2a33 100644 --- a/Source/Metal/ImplMTL.mm +++ b/Source/Metal/ImplMTL.mm @@ -10,6 +10,10 @@ #include "DeviceMTL.h" #include "DescriptorMTL.h" #include "TextureMTL.h" +#include "PipelineLayoutMTL.h" +#include "PipelineMTL.h" +#include "DescriptorMTL.h" +#include "MemoryMTL.h" Result CreateDeviceMTL(const DeviceCreationDesc& desc, DeviceBase*& device) { StdAllocator allocator(desc.allocationCallbacks); @@ -67,7 +71,7 @@ static void NRI_CALL ResetCommandAllocator(CommandAllocator& commandAllocator) { } static void NRI_CALL SetCommandBufferDebugName(CommandBuffer& commandBuffer, const char* name) { - // ((CommandBufferVK&)commandBuffer).SetDebugName(name); + ((CommandBufferMTL&)commandBuffer).SetDebugName(name); } static Result NRI_CALL BeginCommandBuffer(CommandBuffer& commandBuffer, const DescriptorPool* descriptorPool) { @@ -264,14 +268,87 @@ static void NRI_CALL CmdResetQueries(CommandBuffer& commandBuffer, const QueryPo // ((CommandQueueMTL&)commandQueue).Submit(workSubmissionDesc, nullptr); //} + +static void NRI_CALL DestroyCommandBuffer(CommandBuffer& commandBuffer) { + Destroy((CommandBufferMTL*)&commandBuffer); +} + +static void NRI_CALL DestroyCommandAllocator(CommandAllocator& commandAllocator) { + Destroy((CommandAllocatorMTL*)&commandAllocator); +} + +static void NRI_CALL DestroyDescriptorPool(DescriptorPool& descriptorPool) { + //Destroy((DescriptorPoolM*)&descriptorPool); +} + +static void NRI_CALL DestroyBuffer(Buffer& buffer) { + Destroy((BufferMTL*)&buffer); +} + +static void NRI_CALL DestroyTexture(Texture& texture) { + Destroy((TextureMTL*)&texture); +} + +static void NRI_CALL DestroyDescriptor(Descriptor& descriptor) { + // Destroy((DescriptorMTL*)&descriptor); +} + +static void NRI_CALL DestroyPipelineLayout(PipelineLayout& pipelineLayout) { + // Destroy((PipelineLayoutMTL*)&pipelineLayout); +} + +static void NRI_CALL DestroyPipeline(Pipeline& pipeline) { + //Destroy((PipelineMTL*)&pipeline); +} + +static void NRI_CALL DestroyQueryPool(QueryPool& queryPool) { + //Destroy((QueryPoolVK*)&queryPool); +} + +static void NRI_CALL DestroyFence(Fence& fence) { + // Destroy((Fenc*)&fence); +} + +static void NRI_CALL FreeMemory(Memory& memory) { + Destroy((MemoryMTL*)&memory); +} + +static const BufferDesc& NRI_CALL GetBufferDesc(const Buffer& buffer) { + return ((const BufferMTL&)buffer).GetDesc(); +} + +static const TextureDesc& NRI_CALL GetTextureDesc(const Texture& texture) { + return ((const TextureMTL&)texture).GetDesc(); +} + + +static void NRI_CALL GetBufferMemoryDesc(const Device& device, const BufferDesc& bufferDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { + ((const DeviceMTL&)device).GetMemoryDesc(bufferDesc, memoryLocation, memoryDesc); +} + +static void NRI_CALL GetTextureMemoryDesc(const Device& device, const TextureDesc& textureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) { + ((const DeviceMTL&)device).GetMemoryDesc(textureDesc, memoryLocation, memoryDesc); +} + +static Result NRI_CALL CreateGraphicsPipeline(Device& device, const GraphicsPipelineDesc& graphicsPipelineDesc, Pipeline*& pipeline) { + return ((DeviceMTL&)device).CreateImplementation(pipeline, graphicsPipelineDesc); +} + +static Result NRI_CALL AllocateDescriptorSets(DescriptorPool& descriptorPool, const PipelineLayout& pipelineLayout, uint32_t setIndex, DescriptorSet** descriptorSets, uint32_t instanceNum, uint32_t variableDescriptorNum) { + return Result::SUCCESS; + //return ((DescriptorPoolMTL&)descriptorPool).AllocateDescriptorSets(pipelineLayout, setIndex, descriptorSets, instanceNum, variableDescriptorNum); +} + + + Result DeviceMTL::FillFunctionTable(CoreInterface& table) const { table.GetDeviceDesc = ::GetDeviceDesc; - //table.GetBufferDesc = ::GetBufferDesc; - //table.GetTextureDesc = ::GetTextureDesc; + table.GetBufferDesc = ::GetBufferDesc; + table.GetTextureDesc = ::GetTextureDesc; //table.GetFormatSupport = ::GetFormatSupport; //table.GetQuerySize = ::GetQuerySize; - //table.GetBufferMemoryDesc = ::GetBufferMemoryDesc; - //table.GetTextureMemoryDesc = ::GetTextureMemoryDesc; + table.GetBufferMemoryDesc = ::GetBufferMemoryDesc; + table.GetTextureMemoryDesc = ::GetTextureMemoryDesc; //table.GetCommandQueue = ::GetCommandQueue; //table.CreateCommandAllocator = ::CreateCommandAllocator; //table.CreateCommandBuffer = ::CreateCommandBuffer; @@ -284,24 +361,24 @@ static void NRI_CALL CmdResetQueries(CommandBuffer& commandBuffer, const QueryPo //table.CreateTexture3DView = ::CreateTexture3DView; //table.CreateSampler = ::CreateSampler; //table.CreatePipelineLayout = ::CreatePipelineLayout; - //table.CreateGraphicsPipeline = ::CreateGraphicsPipeline; + table.CreateGraphicsPipeline = ::CreateGraphicsPipeline; // table.CreateComputePipeline = ::CreateComputePipeline; // table.CreateQueryPool = ::CreateQueryPool; // table.CreateFence = ::CreateFence; -// table.DestroyCommandAllocator = ::DestroyCommandAllocator; -// table.DestroyCommandBuffer = ::DestroyCommandBuffer; -// table.DestroyDescriptorPool = ::DestroyDescriptorPool; -// table.DestroyBuffer = ::DestroyBuffer; -// table.DestroyTexture = ::DestroyTexture; -// table.DestroyDescriptor = ::DestroyDescriptor; -// table.DestroyPipelineLayout = ::DestroyPipelineLayout; -// table.DestroyPipeline = ::DestroyPipeline; -// table.DestroyQueryPool = ::DestroyQueryPool; -// table.DestroyFence = ::DestroyFence; + table.DestroyCommandAllocator = ::DestroyCommandAllocator; + table.DestroyCommandBuffer = ::DestroyCommandBuffer; + table.DestroyDescriptorPool = ::DestroyDescriptorPool; + table.DestroyBuffer = ::DestroyBuffer; + table.DestroyTexture = ::DestroyTexture; + table.DestroyDescriptor = ::DestroyDescriptor; + table.DestroyPipelineLayout = ::DestroyPipelineLayout; + table.DestroyPipeline = ::DestroyPipeline; + table.DestroyQueryPool = ::DestroyQueryPool; + table.DestroyFence = ::DestroyFence; // table.AllocateMemory = ::AllocateMemory; // table.BindBufferMemory = ::BindBufferMemory; // table.BindTextureMemory = ::BindTextureMemory; -// table.FreeMemory = ::FreeMemory; + table.FreeMemory = ::FreeMemory; table.BeginCommandBuffer = ::BeginCommandBuffer; table.CmdSetDescriptorPool = ::CmdSetDescriptorPool; table.CmdSetDescriptorSet = ::CmdSetDescriptorSet; @@ -349,7 +426,7 @@ static void NRI_CALL CmdResetQueries(CommandBuffer& commandBuffer, const QueryPo // table.UpdateDescriptorRanges = ::UpdateDescriptorRanges; // table.UpdateDynamicConstantBuffers = ::UpdateDynamicConstantBuffers; // table.CopyDescriptorSet = ::CopyDescriptorSet; -// table.AllocateDescriptorSets = ::AllocateDescriptorSets; + table.AllocateDescriptorSets = ::AllocateDescriptorSets; // table.ResetDescriptorPool = ::ResetDescriptorPool; table.ResetCommandAllocator = ::ResetCommandAllocator; table.MapBuffer = ::MapBuffer; diff --git a/Source/Metal/MemoryMTL.h b/Source/Metal/MemoryMTL.h index a8deeb2..db196a9 100644 --- a/Source/Metal/MemoryMTL.h +++ b/Source/Metal/MemoryMTL.h @@ -28,16 +28,16 @@ struct MemoryMTL { return m_Type; } - inline uint8_t* GetMappedMemory() const { - return m_MappedMemory; - } +// inline uint8_t* GetMappedMemory() const { +// return m_MappedMemory; +// } ~MemoryMTL(); - Result Create(const MemoryMTLDesc& memoryDesc); + // Result Create(const MemoryMTLDesc& memoryDesc); Result Create(const AllocateMemoryDesc& allocateMemoryDesc); - //Result CreateDedicated(const BufferVK& buffer); - //Result CreateDedicated(const TextureVK& texture); + // Result CreateDedicated(const BufferVK& buffer); + // Result CreateDedicated(const TextureVK& texture); //================================================================================================================ // NRI @@ -47,8 +47,7 @@ struct MemoryMTL { private: DeviceMTL& m_Device; id m_Handle; - uint8_t* m_MappedMemory = nullptr; - MemoryType m_Type = std::numeric_limits::max(); + MemoryType m_Type; float m_Priority = 0.0f; bool m_OwnsNativeObjects = true; }; diff --git a/Source/Metal/MemoryMTL.mm b/Source/Metal/MemoryMTL.mm index 18aa052..00accab 100644 --- a/Source/Metal/MemoryMTL.mm +++ b/Source/Metal/MemoryMTL.mm @@ -14,35 +14,49 @@ Result MemoryMTL::Create(const AllocateMemoryDesc& allocateMemoryDesc) { MTLHeapDescriptor* heapDescriptor = [[MTLHeapDescriptor alloc] init]; - [heapDescriptor setSize:allocateMemoryDesc.size]; - + MemoryTypeInfo typeInfo; + typeInfo.value = allocateMemoryDesc.type; + [heapDescriptor setCpuCacheMode: (MTLCPUCacheMode)typeInfo.cacheMode]; + [heapDescriptor setStorageMode: (MTLStorageMode)typeInfo.storageMode]; + [heapDescriptor setResourceOptions: (MTLResourceOptions)typeInfo.options]; + [heapDescriptor setSize: allocateMemoryDesc.size]; + m_Handle = [m_Device newHeapWithDescriptor: heapDescriptor]; + m_Type = allocateMemoryDesc.type; + m_Priority = allocateMemoryDesc.priority; } -Result MemoryMTL::Create(const MemoryMTLDesc& memoryDesc) { - MTLHeapDescriptor* heapDescriptor = [[MTLHeapDescriptor alloc] init]; - [heapDescriptor setSize:memoryDesc.size]; - - // [heapDescriptor setStorageMode:memoryDesc.storage]; - - // if (!memoryDesc.vkDeviceMemory) - // return Result::INVALID_ARGUMENT; - - // MemoryTypeInfo memoryTypeInfo = {}; - - //bool found = m_Device.GetMemoryTypeByIndex(memoryDesc.memoryTypeIndex, memoryTypeInfo); - //RETURN_ON_FAILURE(&m_Device, found, Result::INVALID_ARGUMENT, "Can't find memory by index"); - -// m_OwnsNativeObjects = false; - // m_Buffer = memoryDesc.buffer; -// m_MappedMemory = (uint8_t*)memoryDesc.mappedMemory; - // m_Type = memoryDesc.options; +void MemoryMTL::SetDebugName(const char* name) { + NSString* str = [NSString stringWithUTF8String:name]; + [m_Handle setLabel: str]; +} - // const auto& mtl = m_Device.GetDispatchTable(); - //if (!m_MappedMemory && IsHostVisibleMemory(memoryTypeInfo.location)) { - // VkResult result = mtl.MapMemory(m_Device, m_Handle, 0, memoryDesc.size, 0, (void**)&m_MappedMemory); - // RETURN_ON_FAILURE(&m_Device, result == VK_SUCCESS, GetReturnCode(result), "vkMapMemory returned %d", (int32_t)result); - //} - return Result::SUCCESS; -} +//Result MemoryMTL::Create(const MemoryMTLDesc& memoryDesc) { +// MTLHeapDescriptor* heapDescriptor = [[MTLHeapDescriptor alloc] init]; +// +// [heapDescriptor setSize:memoryDesc.size]; +// +// // [heapDescriptor setStorageMode:memoryDesc.storage]; +// +// // if (!memoryDesc.vkDeviceMemory) +// // return Result::INVALID_ARGUMENT; +// +// // MemoryTypeInfo memoryTypeInfo = {}; +// +// //bool found = m_Device.GetMemoryTypeByIndex(memoryDesc.memoryTypeIndex, memoryTypeInfo); +// //RETURN_ON_FAILURE(&m_Device, found, Result::INVALID_ARGUMENT, "Can't find memory by index"); +// +//// m_OwnsNativeObjects = false; +// // m_Buffer = memoryDesc.buffer; +//// m_MappedMemory = (uint8_t*)memoryDesc.mappedMemory; +// // m_Type = memoryDesc.options; +// +// // const auto& mtl = m_Device.GetDispatchTable(); +// //if (!m_MappedMemory && IsHostVisibleMemory(memoryTypeInfo.location)) { +// // VkResult result = mtl.MapMemory(m_Device, m_Handle, 0, memoryDesc.size, 0, (void**)&m_MappedMemory); +// // RETURN_ON_FAILURE(&m_Device, result == VK_SUCCESS, GetReturnCode(result), "vkMapMemory returned %d", (int32_t)result); +// //} +// +// return Result::SUCCESS; +//} diff --git a/Source/Metal/PipelineMTL.h b/Source/Metal/PipelineMTL.h index 785f948..4351886 100644 --- a/Source/Metal/PipelineMTL.h +++ b/Source/Metal/PipelineMTL.h @@ -14,21 +14,30 @@ NriEnum(PipelineType, uint8_t, ); struct PipelineMTL { - +public: inline PipelineMTL(DeviceMTL& device) : m_Device(device) { } ~PipelineMTL(); + + inline PipelineType GetPipelineType() { + return m_PipelineType; + } Result Create(const GraphicsPipelineDesc& graphicsPipelineDesc); Result Create(const ComputePipelineDesc& computePipelineDesc); Result Create(const RayTracingPipelineDesc& rayTracingPipelineDesc); - PipelineType m_pipelineType; MTLPrimitiveTopologyClass m_topologyClass; MTLPrimitiveType m_primitiveType; StageBits m_usedBits; + private: + PipelineType m_PipelineType; + union{ + id m_ComputePipeline = nil; + id m_GraphicsPipeline; + }; DeviceMTL& m_Device; }; diff --git a/Source/Metal/PipelineMTL.mm b/Source/Metal/PipelineMTL.mm index 9a74abc..61d72f4 100644 --- a/Source/Metal/PipelineMTL.mm +++ b/Source/Metal/PipelineMTL.mm @@ -1,14 +1,54 @@ #include "SharedMTL.h" #include "PipelineMTL.h" +#include "PipelineLayoutMTL.h" using namespace nri; PipelineMTL::~PipelineMTL() { + switch(m_PipelineType) { + case PipelineType::Graphics: + m_GraphicsPipeline = nil; + break; + case PipelineType::Compute: + m_ComputePipeline = nil; + break; + case PipelineType::Raytracing: + break; + default: + break; + } } Result PipelineMTL::Create(const ComputePipelineDesc& computePipelineDesc) { + MTLComputePipelineDescriptor* pipelineDesc = [[MTLComputePipelineDescriptor alloc] init]; + NSError* error = nil; + + dispatch_data_t byteCode = dispatch_data_create( + computePipelineDesc.shader.bytecode, + computePipelineDesc.shader.size, nil, DISPATCH_DATA_DESTRUCTOR_DEFAULT); + + id lib = [m_Device newLibraryWithData: byteCode error:&error]; + NSCAssert(lib, @"Failed to load Metal shader library %@", error); // not sure how to correctly report this + RETURN_ON_FAILURE(&m_Device, lib, Result::FAILURE, "Failed to Load Metal shader library"); + // Create a MTLFunction from the loaded MTLLibrary. + NSString *entryPointNStr = [lib functionNames][0]; + if (computePipelineDesc.shader.entryPointName) { + entryPointNStr = [[NSString alloc] initWithUTF8String:computePipelineDesc.shader.entryPointName]; + } + id entryPointFunc = [lib newFunctionWithName:entryPointNStr]; + + m_PipelineType = PipelineType::Compute; + pipelineDesc.computeFunction = entryPointFunc; + NSCAssert(pipelineDesc.computeFunction, @"Failed to create Metal kernel function %@: %@", entryPointNStr, error); + + + m_ComputePipeline = [m_Device newComputePipelineStateWithDescriptor: pipelineDesc + options: MTLPipelineOptionNone + reflection: nil + error:&error]; + NSCAssert(m_ComputePipeline, @"Failed to create pipeline state: %@", error); return Result::SUCCESS; } @@ -118,6 +158,11 @@ renderPipelineDesc.colorAttachments[i].writeMask = GetColorComponent(attachmentDesc.colorWriteMask); } + NSError* error = nil; + m_GraphicsPipeline = [m_Device newRenderPipelineStateWithDescriptor:renderPipelineDesc error: &error]; + NSCAssert(m_GraphicsPipeline, @"Failed to create pipeline state: %@", error); + + return Result::SUCCESS; } diff --git a/Source/Metal/TextureMTL.h b/Source/Metal/TextureMTL.h index 7f60993..834c258 100644 --- a/Source/Metal/TextureMTL.h +++ b/Source/Metal/TextureMTL.h @@ -5,7 +5,9 @@ namespace nri { -struct DeviceMTL; +struct DeviceMTL; + +class MemoryMTL; void fillMTLTextureDescriptor(const TextureDesc& textureDesc, MTLTextureDescriptor* mtlDescriptor); @@ -29,13 +31,22 @@ struct TextureMTL { } Result Create(const TextureDesc& textureDesc); + void FinishMemoryBinding(MemoryMTL& memory, uint64_t memoryOffset); + + //================================================================================================================ + // NRI + //================================================================================================================ + void SetDebugName(const char* name); + private: - // Result CreateFromTextureDesc(const TextureDesc& textureDesc); + void UpdateLabel(); + NSString* m_Label = nullptr; DeviceMTL& m_Device; TextureDesc m_Desc = {}; id m_Handle; + NSString* m_label; }; } // namespace nri diff --git a/Source/Metal/TextureMTL.mm b/Source/Metal/TextureMTL.mm index ed6ec63..b6f7fe1 100644 --- a/Source/Metal/TextureMTL.mm +++ b/Source/Metal/TextureMTL.mm @@ -1,11 +1,13 @@ #include "SharedMTL.h" #include "TextureMTL.h" +#include "MemoryMTL.h" using namespace nri; TextureMTL::~TextureMTL() { m_Handle = nil; + [m_label release]; } void nri::fillMTLTextureDescriptor(const TextureDesc& textureDesc, MTLTextureDescriptor* info) { @@ -19,29 +21,28 @@ info.arrayLength = textureDesc.layerNum; } -//Result TextureMTL::Create(const TextureMTLDesc& textureDesc) { -// m_Handle = texturedesc.texture; -// return Result::SUCCESS; -//} +Result TextureMTL::Create(const TextureDesc& textureDesc) { + m_Desc = textureDesc; + + return Result::SUCCESS; +} -Result TextureMTL::Create(const TextureDesc& textureDesc) { +void TextureMTL::FinishMemoryBinding(MemoryMTL& memory, uint64_t memoryOffset) { MTLTextureDescriptor* info = [[MTLTextureDescriptor alloc] init]; - fillMTLTextureDescriptor(textureDesc, info); - -// info.textureType = ::GetImageTypeMTL(textureDesc.type); -// info.pixelFormat = ::GetFormatMTL(textureDesc.format, true); -// info.width = textureDesc.width; -// info.height = textureDesc.height; -// info.depth = textureDesc.depth; -// info.mipmapLevelCount = textureDesc.mipNum; -// info.sampleCount = textureDesc.sampleNum; -// info.arrayLength = textureDesc.layerNum; -// - m_Handle = [m_Device newTextureWithDescriptor:info]; - m_Desc = textureDesc; + fillMTLTextureDescriptor(m_Desc, info); + m_Handle = [memory.GetHandle() newTextureWithDescriptor:info offset:memoryOffset]; + UpdateLabel(); +} - //m_Handle = [m_Device newTextureWithDescriptor:textureDesc]; - return Result::SUCCESS; +void TextureMTL::UpdateLabel() { + if(m_Handle && m_Label) { + [m_Handle setLabel: m_Label]; + } } +void TextureMTL::SetDebugName(const char* name) { + m_label = [NSString stringWithUTF8String:name]; + [m_label retain]; + UpdateLabel(); +} diff --git a/Source/Shared/SharedExternal.h b/Source/Shared/SharedExternal.h index 48eecd8..8cbb3c9 100644 --- a/Source/Shared/SharedExternal.h +++ b/Source/Shared/SharedExternal.h @@ -176,6 +176,8 @@ inline nri::Vendor GetVendorFromID(uint32_t vendorID) { return nri::Vendor::AMD; case 0x8086: return nri::Vendor::INTEL; + case 0x106b: + return nri::Vendor::APPLE; } return nri::Vendor::UNKNOWN; From b4079f3ac9c8a0e441d3948b8d28231727a3ca2c Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Sat, 30 Nov 2024 21:11:41 -0800 Subject: [PATCH 24/24] feat: add descriptor binding logic Signed-off-by: Michael Pollind --- Source/Metal/DescriptorMTL.h | 1 - Source/Metal/DescriptorPoolMTL.h | 14 +++--- Source/Metal/DescriptorPoolMTL.mm | 45 +++++++++++++++++++- Source/Metal/DescriptorSetMTL.h | 12 +++--- Source/Metal/DescriptorSetMTL.mm | 41 ++++++++++++------ Source/Metal/PipelineLayoutMTL.h | 48 ++++++++++++++++++--- Source/Metal/PipelineLayoutMTL.mm | 71 +++++++++++++++++++++++++------ 7 files changed, 184 insertions(+), 48 deletions(-) diff --git a/Source/Metal/DescriptorMTL.h b/Source/Metal/DescriptorMTL.h index d0af5c8..903fb9c 100644 --- a/Source/Metal/DescriptorMTL.h +++ b/Source/Metal/DescriptorMTL.h @@ -50,7 +50,6 @@ struct DescriptorMTL { Result Create(const Texture3DViewDesc& textureViewDesc); Result Create(const SamplerDesc& samplerDesc); - private: DeviceMTL& m_Device; diff --git a/Source/Metal/DescriptorPoolMTL.h b/Source/Metal/DescriptorPoolMTL.h index 060fad1..c21b0fb 100644 --- a/Source/Metal/DescriptorPoolMTL.h +++ b/Source/Metal/DescriptorPoolMTL.h @@ -15,31 +15,29 @@ struct DescriptorPoolMTL { , m_AllocatedSets(device.GetStdAllocator()) { m_AllocatedSets.reserve(64); } -// -// inline operator VkDescriptorPool() const { -// return m_Handle; -// } -// + inline DeviceMTL& GetDevice() const { return m_Device; } ~DescriptorPoolMTL(); - Result Create(const DescriptorPoolDesc& descriptorPoolDesc); //================================================================================================================ // NRI //================================================================================================================ - + +// size_t GetNumberOfArugmentsAlloc(); void SetDebugName(const char* name); void Reset(); Result AllocateDescriptorSets(const PipelineLayout& pipelineLayout, uint32_t setIndex, DescriptorSet** descriptorSets, uint32_t instanceNum, uint32_t variableDescriptorNum); private: DeviceMTL& m_Device; + size_t m_ArgumentOffset = 0; Vector m_AllocatedSets; - //VkDescriptorPool m_Handle = VK_NULL_HANDLE; + id m_ArgumentBuffer; + uint32_t m_UsedSets = 0; bool m_OwnsNativeObjects = true; }; diff --git a/Source/Metal/DescriptorPoolMTL.mm b/Source/Metal/DescriptorPoolMTL.mm index 05dd2d5..adb6488 100644 --- a/Source/Metal/DescriptorPoolMTL.mm +++ b/Source/Metal/DescriptorPoolMTL.mm @@ -1,6 +1,8 @@ #include "SharedMTL.h" #include "DescriptorPoolMTL.h" +#include "DescriptorSetMTL.h" +#include "PipelineLayoutMTL.h" using namespace nri; @@ -10,9 +12,25 @@ } Result DescriptorPoolMTL::Create(const DescriptorPoolDesc& descriptorPoolDesc) { - + size_t numArgs = descriptorPoolDesc.samplerMaxNum + + descriptorPoolDesc.constantBufferMaxNum + + descriptorPoolDesc.dynamicConstantBufferMaxNum + + descriptorPoolDesc.textureMaxNum + + descriptorPoolDesc.storageTextureMaxNum + + descriptorPoolDesc.bufferMaxNum + + descriptorPoolDesc.storageBufferMaxNum + + descriptorPoolDesc.structuredBufferMaxNum + + descriptorPoolDesc.accelerationStructureMaxNum; + + m_ArgumentBuffer = [m_Device + newBufferWithLength: numArgs * sizeof(uint32_t) options:MTLResourceStorageModeShared]; } + +//size_t DescriptorPoolMTL::GetNumberOfArugmentsAlloc() { +// return [m_ArgumentBuffer length] / sizeof(uint32_t); +//} + //================================================================================================================ // NRI //================================================================================================================ @@ -23,7 +41,32 @@ void DescriptorPoolMTL::Reset() { } + Result DescriptorPoolMTL::AllocateDescriptorSets(const PipelineLayout& pipelineLayout, uint32_t setIndex, DescriptorSet** descriptorSets, uint32_t instanceNum, uint32_t variableDescriptorNum) { + PipelineLayoutMTL* pipelineLayoutMTL = (PipelineLayoutMTL*)&pipelineLayout; + + uint32_t freeSetNum = (uint32_t)m_AllocatedSets.size() - m_UsedSets; + if (freeSetNum < instanceNum) { + uint32_t newSetNum = instanceNum - freeSetNum; + uint32_t prevSetNum = (uint32_t)m_AllocatedSets.size(); + m_AllocatedSets.resize(prevSetNum + newSetNum); + for (size_t i = 0; i < newSetNum; i++) { + Construct(m_AllocatedSets[prevSetNum + i], 1, m_Device); + } + } + + struct DescriptorSetLayout* setLayoutMTL = pipelineLayoutMTL->GetDescriptorSetLayout(setIndex); + for(uint32_t i = 0; i < instanceNum; i++) { + descriptorSets[i] = (DescriptorSet*)m_AllocatedSets[m_UsedSets++]; + ((DescriptorSetMTL*)descriptorSets[i])->Create( + m_ArgumentOffset, + m_ArgumentBuffer, + setLayoutMTL->m_ArgumentDescriptors, + &setLayoutMTL->m_DescriptorSetDesc); + m_ArgumentOffset += ((DescriptorSetMTL*)descriptorSets[i])->getDescriptorLength(); + } + + return Result::SUCCESS; } diff --git a/Source/Metal/DescriptorSetMTL.h b/Source/Metal/DescriptorSetMTL.h index 61cce70..dfb520d 100644 --- a/Source/Metal/DescriptorSetMTL.h +++ b/Source/Metal/DescriptorSetMTL.h @@ -11,19 +11,21 @@ struct DescriptorSetMTL { : m_Device(device) { } - + void Create(size_t argumentBufferOffset, id argumentBuffer, NSArray* argDesc, const struct DescriptorSetDesc* desc); void UpdateDescriptorRanges(uint32_t rangeOffset, uint32_t rangeNum, const DescriptorRangeUpdateDesc* rangeUpdateDescs); - inline id GetArgumentHandle() { return m_ArgumentEncoder; } + size_t getDescriptorLength(); private: DeviceMTL& m_Device; - id m_ArgumentEncoder; - + id m_ArgumentEncoder; + id m_ArgumentBuffer; + size_t m_ArgumentBufferOffset; + NSArray* m_ArgumentDescriptor; + const DescriptorSetDesc* m_Desc = nullptr; }; - } // namespace nri diff --git a/Source/Metal/DescriptorSetMTL.mm b/Source/Metal/DescriptorSetMTL.mm index 5c5b2cd..9ae3d47 100644 --- a/Source/Metal/DescriptorSetMTL.mm +++ b/Source/Metal/DescriptorSetMTL.mm @@ -7,30 +7,45 @@ using namespace nri; +void DescriptorSetMTL::Create(size_t argumentBufferOffset, id argumentBuffer, NSArray* argDesc, const struct DescriptorSetDesc* desc) { + m_ArgumentDescriptor = argDesc; + m_ArgumentBuffer = argumentBuffer; + m_ArgumentBufferOffset = argumentBufferOffset; + m_Desc = desc; + m_ArgumentEncoder = [m_Device newArgumentEncoderWithArguments: argDesc]; + [m_ArgumentEncoder setArgumentBuffer:m_ArgumentBuffer offset:argumentBufferOffset]; +} + +size_t DescriptorSetMTL::getDescriptorLength() { + return [m_ArgumentEncoder encodedLength]; +} + void DescriptorSetMTL::UpdateDescriptorRanges(uint32_t rangeOffset, uint32_t rangeNum, const DescriptorRangeUpdateDesc* rangeUpdateDescs) { for(size_t j = 0; j < rangeNum; j++) { const DescriptorRangeUpdateDesc& update = rangeUpdateDescs[j]; - -// uint32_t offset = update.baseDescriptor + descriptorOffset; - for(size_t descIdx = 0; descIdx < update.descriptorNum; descIdx++) { + DescriptorMTL* descriptorImpl = (DescriptorMTL*)&update.descriptors[descIdx]; + const DescriptorRangeDesc& rangeDesc = m_Desc->ranges[rangeOffset + j]; - DescriptorMTL& descriptorImpl = *(DescriptorMTL*)&update.descriptors[descIdx]; - switch(descriptorImpl.GetType()) { + switch(descriptorImpl->GetType()) { case DescriptorTypeMTL::IMAGE_VIEW_1D: - [m_ArgumentEncoder setTexture: descriptorImpl.GetTextureHandle() atIndex:0]; -// [m_ArgumentEncoder setTextures:<#(id _Nullable const * _Nonnull)#> withRange:<#(NSRange)#>] - break; case DescriptorTypeMTL::IMAGE_VIEW_2D: - [m_ArgumentEncoder setTexture: descriptorImpl.GetTextureHandle() atIndex:0]; + case DescriptorTypeMTL::IMAGE_VIEW_3D: + [m_ArgumentEncoder setTexture: descriptorImpl->GetTextureHandle() atIndex: rangeDesc.baseRegisterIndex + descIdx]; break; - case DescriptorTypeMTL::BUFFER_VIEW: -// [m_ArgumentEncoder setBuffer: offset:<#(NSUInteger)#> atIndex:<#(NSUInteger)#>] + case DescriptorTypeMTL::SAMPLER: + [m_ArgumentEncoder setSamplerState: descriptorImpl->GetSamplerStateHandler() atIndex:rangeDesc.baseRegisterIndex + descIdx]; // not sure if this is correct + break; + case DescriptorTypeMTL::BUFFER_VIEW: { + BufferViewDesc* view = &descriptorImpl->BufferView(); + [m_ArgumentEncoder setBuffer: descriptorImpl->GetBufferHandle() offset: view->offset atIndex: rangeDesc.baseRegisterIndex + descIdx]; + break; + } + default: break; } - -// update.descriptors[descIdx]; + } } } diff --git a/Source/Metal/PipelineLayoutMTL.h b/Source/Metal/PipelineLayoutMTL.h index 2a4b080..436549d 100644 --- a/Source/Metal/PipelineLayoutMTL.h +++ b/Source/Metal/PipelineLayoutMTL.h @@ -6,23 +6,57 @@ namespace nri { struct DeviceMTL; + +// +//struct BindingInfo { +// BindingInfo(StdAllocator& allocator); +//// Vector pushConstantBindings; +//// Vector pushDescriptorBindings; +//}; + +struct DescriptorSetLayout { + DescriptorSetDesc m_DescriptorSetDesc; + NSMutableArray* m_ArgumentDescriptors; +}; + struct PipelineLayoutMTL { + inline PipelineLayoutMTL (DeviceMTL& device) - : m_Device(device) { + : m_Device(device) + , m_HasVariableDescriptorNum(device.GetStdAllocator()) + , m_DescriptorSetRangeDescs(device.GetStdAllocator()) + , m_DynamicConstantBufferDescs(device.GetStdAllocator()) + , m_DescriptorSets(device.GetStdAllocator()) + { } ~PipelineLayoutMTL(); - - Result Create(const PipelineLayoutDesc& pipelineLayoutDesc); - struct PipelineDescriptorSet { - NSMutableArray* m_ArgumentDescriptors; - }; + inline DeviceMTL& GetDevice() const { + return m_Device; + } + + inline struct DescriptorSetLayout* GetDescriptorSetLayout(uint32_t setIndex) { + return &m_DescriptorSets[setIndex]; + } + +// inline struct DescriptorSetDesc* GetDescriptorSetDesc(uint32_t setIndex) { +// return &m_DescriptorSetDesc[setIndex]; +// } + + Result Create(const PipelineLayoutDesc& pipelineLayoutDesc); + private: DeviceMTL& m_Device; - std::vector m_DescriptorSets; + Vector m_HasVariableDescriptorNum; + Vector m_DescriptorSetRangeDescs; + Vector m_DynamicConstantBufferDescs; +// Vector m_DescriptorSetDesc; + Vector m_DescriptorSets; + +// BindingInfo m_BindingInfo; }; } diff --git a/Source/Metal/PipelineLayoutMTL.mm b/Source/Metal/PipelineLayoutMTL.mm index 33b4c76..aefa22c 100644 --- a/Source/Metal/PipelineLayoutMTL.mm +++ b/Source/Metal/PipelineLayoutMTL.mm @@ -4,31 +4,76 @@ using namespace nri; +// +//BindingInfo::BindingInfo(StdAllocator& allocator) +// : hasVariableDescriptorNum(allocator) +// , descriptorSetRangeDescs(allocator) +// , dynamicConstantBufferDescs(allocator) +// , descriptorSetDescs(allocator) { +// +//} +// + PipelineLayoutMTL::~PipelineLayoutMTL() { } Result PipelineLayoutMTL::Create(const PipelineLayoutDesc& pipelineLayoutDesc) { + + + size_t rangeNum = 0; + size_t dynamicConstantBufferNum = 0; + for (uint32_t i = 0; i < pipelineLayoutDesc.descriptorSetNum; i++) { + rangeNum += pipelineLayoutDesc.descriptorSets[i].rangeNum; + dynamicConstantBufferNum += pipelineLayoutDesc.descriptorSets[i].dynamicConstantBufferNum; + } + m_DescriptorSets.resize(pipelineLayoutDesc.descriptorSetNum); + m_HasVariableDescriptorNum.resize(pipelineLayoutDesc.descriptorSetNum); + m_DescriptorSetRangeDescs.reserve(rangeNum); + m_DynamicConstantBufferDescs.reserve(dynamicConstantBufferNum); + for (uint32_t i = 0; i < pipelineLayoutDesc.descriptorSetNum; i++) { const DescriptorSetDesc& descriptorSetDesc = pipelineLayoutDesc.descriptorSets[i]; - NSMutableArray* argumentDescriptors = [[NSMutableArray alloc] init]; - MTLArgumentDescriptor* argDescriptor = [MTLArgumentDescriptor argumentDescriptor]; + // Binding info + m_HasVariableDescriptorNum[i] = false; + m_DescriptorSets[i].m_DescriptorSetDesc = descriptorSetDesc; + m_DescriptorSets[i].m_DescriptorSetDesc.ranges = m_DescriptorSetRangeDescs.data() +m_DescriptorSetRangeDescs.size(); + m_DescriptorSets[i].m_DescriptorSetDesc.dynamicConstantBuffers = m_DynamicConstantBufferDescs.data() + m_DynamicConstantBufferDescs.size(); + m_DescriptorSetRangeDescs.insert(m_DescriptorSetRangeDescs.end(), descriptorSetDesc.ranges, descriptorSetDesc.ranges + descriptorSetDesc.rangeNum); + m_DynamicConstantBufferDescs.insert(m_DynamicConstantBufferDescs.end(), descriptorSetDesc.dynamicConstantBuffers, descriptorSetDesc.dynamicConstantBuffers + descriptorSetDesc.dynamicConstantBufferNum); + NSMutableArray* argumentDescriptors = [[NSMutableArray alloc] init]; for(size_t r = 0; r < descriptorSetDesc.rangeNum; r++) { - + MTLArgumentDescriptor* argDescriptor = [MTLArgumentDescriptor argumentDescriptor]; + const DescriptorRangeDesc* range = &descriptorSetDesc.ranges[r]; + argDescriptor.arrayLength = range->descriptorNum; + argDescriptor.access = MTLBindingAccessReadWrite; + argDescriptor.index = range->baseRegisterIndex; + switch(range->descriptorType) { + case DescriptorType::TEXTURE: + argDescriptor.dataType = MTLDataTypeTexture; + argDescriptor.textureType = MTLTextureType2D; // descriptor type does not have this + break; + case DescriptorType::SAMPLER: + argDescriptor.dataType = MTLDataTypeSampler; + break; + case DescriptorType::CONSTANT_BUFFER: + case DescriptorType::STORAGE_TEXTURE: + case DescriptorType::BUFFER: + case DescriptorType::STORAGE_BUFFER: + case DescriptorType::STRUCTURED_BUFFER: + case DescriptorType::STORAGE_STRUCTURED_BUFFER: + argDescriptor.dataType = MTLDataTypeStruct; + break; + case DescriptorType::ACCELERATION_STRUCTURE: + argDescriptor.dataType = MTLDataTypePrimitiveAccelerationStructure; + break; + default: + break; + } } - - - //argDescriptor.access = memberDescriptor.mAccessType; - //argDescriptor.arrayLength = memberDescriptor.mArrayLength; - //argDescriptor.constantBlockAlignment = memberDescriptor.mAlignment; - //argDescriptor.dataType = memberDescriptor.mDataType; - //argDescriptor.index = memberDescriptor.mArgumentIndex; - //argDescriptor.textureType = memberDescriptor.mTextureType; - - [argumentDescriptors addObject:argDescriptor]; m_DescriptorSets[i].m_ArgumentDescriptors = argumentDescriptors; }