Path: blob/master/drivers/metal/rendering_device_driver_metal.h
9973 views
/**************************************************************************/1/* rendering_device_driver_metal.h */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#pragma once3132#import "metal_objects.h"33#import "rendering_shader_container_metal.h"3435#include "servers/rendering/rendering_device_driver.h"3637#import <Metal/Metal.h>38#import <variant>3940#ifdef DEBUG_ENABLED41#ifndef _DEBUG42#define _DEBUG43#endif44#endif4546class RenderingContextDriverMetal;4748class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) RenderingDeviceDriverMetal : public RenderingDeviceDriver {49friend struct ShaderCacheEntry;5051template <typename T>52using Result = std::variant<T, Error>;5354#pragma mark - Generic5556RenderingContextDriverMetal *context_driver = nullptr;57RenderingContextDriver::Device context_device;58id<MTLDevice> device = nil;5960MetalDeviceProperties *device_properties = nullptr;61MetalDeviceProfile device_profile;62RenderingShaderContainerFormatMetal *shader_container_format = nullptr;63PixelFormats *pixel_formats = nullptr;64std::unique_ptr<MDResourceCache> resource_cache;6566RDD::Capabilities capabilities;67RDD::MultiviewCapabilities multiview_capabilities;68RDD::FragmentShadingRateCapabilities fsr_capabilities;69RDD::FragmentDensityMapCapabilities fdm_capabilities;7071id<MTLBinaryArchive> archive = nil;72uint32_t archive_count = 0;7374id<MTLCommandQueue> device_queue = nil;75id<MTLCaptureScope> device_scope = nil;7677String pipeline_cache_id;7879Error _create_device();80void _check_capabilities();8182#pragma mark - Shader Cache8384ShaderLoadStrategy _shader_load_strategy = ShaderLoadStrategy::DEFAULT;8586/**87* The shader cache is a map of hashes of the Metal source to shader cache entries.88*89* To prevent unbounded growth of the cache, cache entries are automatically freed when90* there are no more references to the MDLibrary associated with the cache entry.91*/92HashMap<SHA256Digest, ShaderCacheEntry *, HashableHasher<SHA256Digest>> _shader_cache;93void shader_cache_free_entry(const SHA256Digest &key);9495public:96Error initialize(uint32_t p_device_index, uint32_t p_frame_count) override final;9798#pragma mark - Memory99100#pragma mark - Buffers101102public:103virtual BufferID buffer_create(uint64_t p_size, BitField<BufferUsageBits> p_usage, MemoryAllocationType p_allocation_type) override final;104virtual bool buffer_set_texel_format(BufferID p_buffer, DataFormat p_format) override final;105virtual void buffer_free(BufferID p_buffer) override final;106virtual uint64_t buffer_get_allocation_size(BufferID p_buffer) override final;107virtual uint8_t *buffer_map(BufferID p_buffer) override final;108virtual void buffer_unmap(BufferID p_buffer) override final;109virtual uint64_t buffer_get_device_address(BufferID p_buffer) override final;110111#pragma mark - Texture112113private:114// Returns true if the texture is a valid linear format.115Result<bool> is_valid_linear(TextureFormat const &p_format) const;116void _get_sub_resource(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) const;117118public:119virtual TextureID texture_create(const TextureFormat &p_format, const TextureView &p_view) override final;120virtual TextureID texture_create_from_extension(uint64_t p_native_texture, TextureType p_type, DataFormat p_format, uint32_t p_array_layers, bool p_depth_stencil, uint32_t p_mipmaps) override final;121virtual TextureID texture_create_shared(TextureID p_original_texture, const TextureView &p_view) override final;122virtual TextureID texture_create_shared_from_slice(TextureID p_original_texture, const TextureView &p_view, TextureSliceType p_slice_type, uint32_t p_layer, uint32_t p_layers, uint32_t p_mipmap, uint32_t p_mipmaps) override final;123virtual void texture_free(TextureID p_texture) override final;124virtual uint64_t texture_get_allocation_size(TextureID p_texture) override final;125virtual void texture_get_copyable_layout(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) override final;126virtual uint8_t *texture_map(TextureID p_texture, const TextureSubresource &p_subresource) override final;127virtual void texture_unmap(TextureID p_texture) override final;128virtual BitField<TextureUsageBits> texture_get_usages_supported_by_format(DataFormat p_format, bool p_cpu_readable) override final;129virtual bool texture_can_make_shared_with_format(TextureID p_texture, DataFormat p_format, bool &r_raw_reinterpretation) override final;130131#pragma mark - Sampler132133public:134virtual SamplerID sampler_create(const SamplerState &p_state) final override;135virtual void sampler_free(SamplerID p_sampler) final override;136virtual bool sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_filter) override final;137138#pragma mark - Vertex Array139140private:141public:142virtual VertexFormatID vertex_format_create(VectorView<VertexAttribute> p_vertex_attribs) override final;143virtual void vertex_format_free(VertexFormatID p_vertex_format) override final;144145#pragma mark - Barriers146147virtual void command_pipeline_barrier(148CommandBufferID p_cmd_buffer,149BitField<PipelineStageBits> p_src_stages,150BitField<PipelineStageBits> p_dst_stages,151VectorView<MemoryBarrier> p_memory_barriers,152VectorView<BufferBarrier> p_buffer_barriers,153VectorView<TextureBarrier> p_texture_barriers) override final;154155#pragma mark - Fences156157private:158struct Fence {159dispatch_semaphore_t semaphore;160Fence() :161semaphore(dispatch_semaphore_create(0)) {}162};163164public:165virtual FenceID fence_create() override final;166virtual Error fence_wait(FenceID p_fence) override final;167virtual void fence_free(FenceID p_fence) override final;168169#pragma mark - Semaphores170171public:172virtual SemaphoreID semaphore_create() override final;173virtual void semaphore_free(SemaphoreID p_semaphore) override final;174175#pragma mark - Commands176// ----- QUEUE FAMILY -----177178virtual CommandQueueFamilyID command_queue_family_get(BitField<CommandQueueFamilyBits> p_cmd_queue_family_bits, RenderingContextDriver::SurfaceID p_surface = 0) override final;179180// ----- QUEUE -----181public:182virtual CommandQueueID command_queue_create(CommandQueueFamilyID p_cmd_queue_family, bool p_identify_as_main_queue = false) override final;183virtual Error command_queue_execute_and_present(CommandQueueID p_cmd_queue, VectorView<SemaphoreID> p_wait_semaphores, VectorView<CommandBufferID> p_cmd_buffers, VectorView<SemaphoreID> p_cmd_semaphores, FenceID p_cmd_fence, VectorView<SwapChainID> p_swap_chains) override final;184virtual void command_queue_free(CommandQueueID p_cmd_queue) override final;185186// ----- POOL -----187188virtual CommandPoolID command_pool_create(CommandQueueFamilyID p_cmd_queue_family, CommandBufferType p_cmd_buffer_type) override final;189virtual bool command_pool_reset(CommandPoolID p_cmd_pool) override final;190virtual void command_pool_free(CommandPoolID p_cmd_pool) override final;191192// ----- BUFFER -----193194private:195// Used to maintain references.196Vector<MDCommandBuffer *> command_buffers;197198public:199virtual CommandBufferID command_buffer_create(CommandPoolID p_cmd_pool) override final;200virtual bool command_buffer_begin(CommandBufferID p_cmd_buffer) override final;201virtual bool command_buffer_begin_secondary(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, uint32_t p_subpass, FramebufferID p_framebuffer) override final;202virtual void command_buffer_end(CommandBufferID p_cmd_buffer) override final;203virtual void command_buffer_execute_secondary(CommandBufferID p_cmd_buffer, VectorView<CommandBufferID> p_secondary_cmd_buffers) override final;204205#pragma mark - Swapchain206207private:208struct SwapChain {209RenderingContextDriver::SurfaceID surface = RenderingContextDriver::SurfaceID();210RenderPassID render_pass;211RDD::DataFormat data_format = DATA_FORMAT_MAX;212SwapChain() :213render_pass(nullptr) {}214};215216void _swap_chain_release(SwapChain *p_swap_chain);217void _swap_chain_release_buffers(SwapChain *p_swap_chain);218219public:220virtual SwapChainID swap_chain_create(RenderingContextDriver::SurfaceID p_surface) override final;221virtual Error swap_chain_resize(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, uint32_t p_desired_framebuffer_count) override final;222virtual FramebufferID swap_chain_acquire_framebuffer(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, bool &r_resize_required) override final;223virtual RenderPassID swap_chain_get_render_pass(SwapChainID p_swap_chain) override final;224virtual DataFormat swap_chain_get_format(SwapChainID p_swap_chain) override final;225virtual void swap_chain_set_max_fps(SwapChainID p_swap_chain, int p_max_fps) override final;226virtual void swap_chain_free(SwapChainID p_swap_chain) override final;227228#pragma mark - Frame Buffer229230virtual FramebufferID framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height) override final;231virtual void framebuffer_free(FramebufferID p_framebuffer) override final;232233#pragma mark - Shader234235private:236// Serialization types need access to private state.237238friend struct ShaderStageData;239friend struct SpecializationConstantData;240friend struct UniformData;241friend struct ShaderBinaryData;242friend struct PushConstantData;243244public:245virtual ShaderID shader_create_from_container(const Ref<RenderingShaderContainer> &p_shader_container, const Vector<ImmutableSampler> &p_immutable_samplers) override final;246virtual void shader_free(ShaderID p_shader) override final;247virtual void shader_destroy_modules(ShaderID p_shader) override final;248virtual const RenderingShaderContainerFormat &get_shader_container_format() const override final;249250#pragma mark - Uniform Set251252public:253virtual UniformSetID uniform_set_create(VectorView<BoundUniform> p_uniforms, ShaderID p_shader, uint32_t p_set_index, int p_linear_pool_index) override final;254virtual void uniform_set_free(UniformSetID p_uniform_set) override final;255256#pragma mark - Commands257258virtual void command_uniform_set_prepare_for_use(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;259260#pragma mark Transfer261262private:263enum class CopySource {264Buffer,265Texture,266};267void _copy_texture_buffer(CommandBufferID p_cmd_buffer,268CopySource p_source,269TextureID p_texture,270BufferID p_buffer,271VectorView<BufferTextureCopyRegion> p_regions);272273public:274virtual void command_clear_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, uint64_t p_offset, uint64_t p_size) override final;275virtual void command_copy_buffer(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, BufferID p_dst_buffer, VectorView<BufferCopyRegion> p_regions) override final;276277virtual void command_copy_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView<TextureCopyRegion> p_regions) override final;278virtual void command_resolve_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, uint32_t p_src_layer, uint32_t p_src_mipmap, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, uint32_t p_dst_layer, uint32_t p_dst_mipmap) override final;279virtual void command_clear_color_texture(CommandBufferID p_cmd_buffer, TextureID p_texture, TextureLayout p_texture_layout, const Color &p_color, const TextureSubresourceRange &p_subresources) override final;280281virtual void command_copy_buffer_to_texture(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView<BufferTextureCopyRegion> p_regions) override final;282virtual void command_copy_texture_to_buffer(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, BufferID p_dst_buffer, VectorView<BufferTextureCopyRegion> p_regions) override final;283284#pragma mark Pipeline285286private:287Result<id<MTLFunction>> _create_function(MDLibrary *p_library, NSString *p_name, VectorView<PipelineSpecializationConstant> &p_specialization_constants);288289public:290virtual void pipeline_free(PipelineID p_pipeline_id) override final;291292// ----- BINDING -----293294virtual void command_bind_push_constants(CommandBufferID p_cmd_buffer, ShaderID p_shader, uint32_t p_first_index, VectorView<uint32_t> p_data) override final;295296// ----- CACHE -----297private:298String _pipeline_get_cache_path() const;299300public:301virtual bool pipeline_cache_create(const Vector<uint8_t> &p_data) override final;302virtual void pipeline_cache_free() override final;303virtual size_t pipeline_cache_query_size() override final;304virtual Vector<uint8_t> pipeline_cache_serialize() override final;305306#pragma mark Rendering307308// ----- SUBPASS -----309310virtual RenderPassID render_pass_create(VectorView<Attachment> p_attachments, VectorView<Subpass> p_subpasses, VectorView<SubpassDependency> p_subpass_dependencies, uint32_t p_view_count, AttachmentReference p_fragment_density_map_attachment) override final;311virtual void render_pass_free(RenderPassID p_render_pass) override final;312313// ----- COMMANDS -----314315public:316virtual void command_begin_render_pass(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, FramebufferID p_framebuffer, CommandBufferType p_cmd_buffer_type, const Rect2i &p_rect, VectorView<RenderPassClearValue> p_clear_values) override final;317virtual void command_end_render_pass(CommandBufferID p_cmd_buffer) override final;318virtual void command_next_render_subpass(CommandBufferID p_cmd_buffer, CommandBufferType p_cmd_buffer_type) override final;319virtual void command_render_set_viewport(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_viewports) override final;320virtual void command_render_set_scissor(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_scissors) override final;321virtual void command_render_clear_attachments(CommandBufferID p_cmd_buffer, VectorView<AttachmentClear> p_attachment_clears, VectorView<Rect2i> p_rects) override final;322323// Binding.324virtual void command_bind_render_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final;325virtual void command_bind_render_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;326virtual void command_bind_render_uniform_sets(CommandBufferID p_cmd_buffer, VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count) override final;327328// Drawing.329virtual void command_render_draw(CommandBufferID p_cmd_buffer, uint32_t p_vertex_count, uint32_t p_instance_count, uint32_t p_base_vertex, uint32_t p_first_instance) override final;330virtual void command_render_draw_indexed(CommandBufferID p_cmd_buffer, uint32_t p_index_count, uint32_t p_instance_count, uint32_t p_first_index, int32_t p_vertex_offset, uint32_t p_first_instance) override final;331virtual void command_render_draw_indexed_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) override final;332virtual void command_render_draw_indexed_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) override final;333virtual void command_render_draw_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) override final;334virtual void command_render_draw_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) override final;335336// Buffer binding.337virtual void command_render_bind_vertex_buffers(CommandBufferID p_cmd_buffer, uint32_t p_binding_count, const BufferID *p_buffers, const uint64_t *p_offsets) override final;338virtual void command_render_bind_index_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, IndexBufferFormat p_format, uint64_t p_offset) override final;339340// Dynamic state.341virtual void command_render_set_blend_constants(CommandBufferID p_cmd_buffer, const Color &p_constants) override final;342virtual void command_render_set_line_width(CommandBufferID p_cmd_buffer, float p_width) override final;343344// ----- PIPELINE -----345346virtual PipelineID render_pipeline_create(347ShaderID p_shader,348VertexFormatID p_vertex_format,349RenderPrimitive p_render_primitive,350PipelineRasterizationState p_rasterization_state,351PipelineMultisampleState p_multisample_state,352PipelineDepthStencilState p_depth_stencil_state,353PipelineColorBlendState p_blend_state,354VectorView<int32_t> p_color_attachments,355BitField<PipelineDynamicStateFlags> p_dynamic_state,356RenderPassID p_render_pass,357uint32_t p_render_subpass,358VectorView<PipelineSpecializationConstant> p_specialization_constants) override final;359360#pragma mark - Compute361362// ----- COMMANDS -----363364// Binding.365virtual void command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final;366virtual void command_bind_compute_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;367virtual void command_bind_compute_uniform_sets(CommandBufferID p_cmd_buffer, VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count) override final;368369// Dispatching.370virtual void command_compute_dispatch(CommandBufferID p_cmd_buffer, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) override final;371virtual void command_compute_dispatch_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset) override final;372373// ----- PIPELINE -----374375virtual PipelineID compute_pipeline_create(ShaderID p_shader, VectorView<PipelineSpecializationConstant> p_specialization_constants) override final;376377#pragma mark - Queries378379// ----- TIMESTAMP -----380381// Basic.382virtual QueryPoolID timestamp_query_pool_create(uint32_t p_query_count) override final;383virtual void timestamp_query_pool_free(QueryPoolID p_pool_id) override final;384virtual void timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) override final;385virtual uint64_t timestamp_query_result_to_time(uint64_t p_result) override final;386387// Commands.388virtual void command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) override final;389virtual void command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) override final;390391#pragma mark - Labels392393virtual void command_begin_label(CommandBufferID p_cmd_buffer, const char *p_label_name, const Color &p_color) override final;394virtual void command_end_label(CommandBufferID p_cmd_buffer) override final;395396#pragma mark - Debug397398virtual void command_insert_breadcrumb(CommandBufferID p_cmd_buffer, uint32_t p_data) override final;399400#pragma mark - Submission401402virtual void begin_segment(uint32_t p_frame_index, uint32_t p_frames_drawn) override final;403virtual void end_segment() override final;404405#pragma mark - Miscellaneous406407virtual void set_object_name(ObjectType p_type, ID p_driver_id, const String &p_name) override final;408virtual uint64_t get_resource_native_handle(DriverResource p_type, ID p_driver_id) override final;409virtual uint64_t get_total_memory_used() override final;410virtual uint64_t get_lazily_memory_used() override final;411virtual uint64_t limit_get(Limit p_limit) override final;412virtual uint64_t api_trait_get(ApiTrait p_trait) override final;413virtual bool has_feature(Features p_feature) override final;414virtual const MultiviewCapabilities &get_multiview_capabilities() override final;415virtual const FragmentShadingRateCapabilities &get_fragment_shading_rate_capabilities() override final;416virtual const FragmentDensityMapCapabilities &get_fragment_density_map_capabilities() override final;417virtual String get_api_name() const override final { return "Metal"; }418virtual String get_api_version() const override final;419virtual String get_pipeline_cache_uuid() const override final;420virtual const Capabilities &get_capabilities() const override final;421virtual bool is_composite_alpha_supported(CommandQueueID p_queue) const override final;422423// Metal-specific.424id<MTLDevice> get_device() const { return device; }425PixelFormats &get_pixel_formats() const { return *pixel_formats; }426MDResourceCache &get_resource_cache() const { return *resource_cache; }427MetalDeviceProperties const &get_device_properties() const { return *device_properties; }428429_FORCE_INLINE_ uint32_t get_metal_buffer_index_for_vertex_attribute_binding(uint32_t p_binding) {430return (device_properties->limits.maxPerStageBufferCount - 1) - p_binding;431}432433size_t get_texel_buffer_alignment_for_format(RDD::DataFormat p_format) const;434size_t get_texel_buffer_alignment_for_format(MTLPixelFormat p_format) const;435436/******************/437RenderingDeviceDriverMetal(RenderingContextDriverMetal *p_context_driver);438~RenderingDeviceDriverMetal();439};440441442