metal_objects.h 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  1. /**************************************************************************/
  2. /* metal_objects.h */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #pragma once
  31. /**************************************************************************/
  32. /* */
  33. /* Portions of this code were derived from MoltenVK. */
  34. /* */
  35. /* Copyright (c) 2015-2023 The Brenwill Workshop Ltd. */
  36. /* (http://www.brenwill.com) */
  37. /* */
  38. /* Licensed under the Apache License, Version 2.0 (the "License"); */
  39. /* you may not use this file except in compliance with the License. */
  40. /* You may obtain a copy of the License at */
  41. /* */
  42. /* http://www.apache.org/licenses/LICENSE-2.0 */
  43. /* */
  44. /* Unless required by applicable law or agreed to in writing, software */
  45. /* distributed under the License is distributed on an "AS IS" BASIS, */
  46. /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
  47. /* implied. See the License for the specific language governing */
  48. /* permissions and limitations under the License. */
  49. /**************************************************************************/
  50. #import "metal_device_properties.h"
  51. #import "metal_utils.h"
  52. #import "pixel_formats.h"
  53. #include "servers/rendering/rendering_device_driver.h"
  54. #import <CommonCrypto/CommonDigest.h>
  55. #import <Foundation/Foundation.h>
  56. #import <Metal/Metal.h>
  57. #import <QuartzCore/CAMetalLayer.h>
  58. #import <simd/simd.h>
  59. #import <zlib.h>
  60. #import <initializer_list>
  61. #import <optional>
  62. // These types can be used in Vector and other containers that use
  63. // pointer operations not supported by ARC.
  64. namespace MTL {
  65. #define MTL_CLASS(name) \
  66. class name { \
  67. public: \
  68. name(id<MTL##name> obj = nil) : m_obj(obj) {} \
  69. operator id<MTL##name>() const { \
  70. return m_obj; \
  71. } \
  72. id<MTL##name> m_obj; \
  73. };
  74. MTL_CLASS(Texture)
  75. } //namespace MTL
  76. /// Metal buffer index for the view mask when rendering multi-view.
  77. const uint32_t VIEW_MASK_BUFFER_INDEX = 24;
  78. enum ShaderStageUsage : uint32_t {
  79. None = 0,
  80. Vertex = RDD::SHADER_STAGE_VERTEX_BIT,
  81. Fragment = RDD::SHADER_STAGE_FRAGMENT_BIT,
  82. TesselationControl = RDD::SHADER_STAGE_TESSELATION_CONTROL_BIT,
  83. TesselationEvaluation = RDD::SHADER_STAGE_TESSELATION_EVALUATION_BIT,
  84. Compute = RDD::SHADER_STAGE_COMPUTE_BIT,
  85. };
  86. _FORCE_INLINE_ ShaderStageUsage &operator|=(ShaderStageUsage &p_a, int p_b) {
  87. p_a = ShaderStageUsage(uint32_t(p_a) | uint32_t(p_b));
  88. return p_a;
  89. }
  90. enum StageResourceUsage : uint32_t {
  91. VertexRead = (MTLResourceUsageRead << RDD::SHADER_STAGE_VERTEX * 2),
  92. VertexWrite = (MTLResourceUsageWrite << RDD::SHADER_STAGE_VERTEX * 2),
  93. FragmentRead = (MTLResourceUsageRead << RDD::SHADER_STAGE_FRAGMENT * 2),
  94. FragmentWrite = (MTLResourceUsageWrite << RDD::SHADER_STAGE_FRAGMENT * 2),
  95. TesselationControlRead = (MTLResourceUsageRead << RDD::SHADER_STAGE_TESSELATION_CONTROL * 2),
  96. TesselationControlWrite = (MTLResourceUsageWrite << RDD::SHADER_STAGE_TESSELATION_CONTROL * 2),
  97. TesselationEvaluationRead = (MTLResourceUsageRead << RDD::SHADER_STAGE_TESSELATION_EVALUATION * 2),
  98. TesselationEvaluationWrite = (MTLResourceUsageWrite << RDD::SHADER_STAGE_TESSELATION_EVALUATION * 2),
  99. ComputeRead = (MTLResourceUsageRead << RDD::SHADER_STAGE_COMPUTE * 2),
  100. ComputeWrite = (MTLResourceUsageWrite << RDD::SHADER_STAGE_COMPUTE * 2),
  101. };
  102. typedef LocalVector<__unsafe_unretained id<MTLResource>> ResourceVector;
  103. typedef HashMap<StageResourceUsage, ResourceVector> ResourceUsageMap;
  104. enum class MDCommandBufferStateType {
  105. None,
  106. Render,
  107. Compute,
  108. Blit,
  109. };
  110. enum class MDPipelineType {
  111. None,
  112. Render,
  113. Compute,
  114. };
  115. class MDRenderPass;
  116. class MDPipeline;
  117. class MDRenderPipeline;
  118. class MDComputePipeline;
  119. class MDFrameBuffer;
  120. class RenderingDeviceDriverMetal;
  121. class MDUniformSet;
  122. class MDShader;
  123. #pragma mark - Resource Factory
  124. struct ClearAttKey {
  125. const static uint32_t COLOR_COUNT = MAX_COLOR_ATTACHMENT_COUNT;
  126. const static uint32_t DEPTH_INDEX = COLOR_COUNT;
  127. const static uint32_t STENCIL_INDEX = DEPTH_INDEX + 1;
  128. const static uint32_t ATTACHMENT_COUNT = STENCIL_INDEX + 1;
  129. enum Flags : uint16_t {
  130. CLEAR_FLAGS_NONE = 0,
  131. CLEAR_FLAGS_LAYERED = 1 << 0,
  132. };
  133. Flags flags = CLEAR_FLAGS_NONE;
  134. uint16_t sample_count = 0;
  135. uint16_t pixel_formats[ATTACHMENT_COUNT] = { 0 };
  136. _FORCE_INLINE_ void set_color_format(uint32_t p_idx, MTLPixelFormat p_fmt) { pixel_formats[p_idx] = p_fmt; }
  137. _FORCE_INLINE_ void set_depth_format(MTLPixelFormat p_fmt) { pixel_formats[DEPTH_INDEX] = p_fmt; }
  138. _FORCE_INLINE_ void set_stencil_format(MTLPixelFormat p_fmt) { pixel_formats[STENCIL_INDEX] = p_fmt; }
  139. _FORCE_INLINE_ MTLPixelFormat depth_format() const { return (MTLPixelFormat)pixel_formats[DEPTH_INDEX]; }
  140. _FORCE_INLINE_ MTLPixelFormat stencil_format() const { return (MTLPixelFormat)pixel_formats[STENCIL_INDEX]; }
  141. _FORCE_INLINE_ void enable_layered_rendering() { flags::set(flags, CLEAR_FLAGS_LAYERED); }
  142. _FORCE_INLINE_ bool is_enabled(uint32_t p_idx) const { return pixel_formats[p_idx] != 0; }
  143. _FORCE_INLINE_ bool is_depth_enabled() const { return pixel_formats[DEPTH_INDEX] != 0; }
  144. _FORCE_INLINE_ bool is_stencil_enabled() const { return pixel_formats[STENCIL_INDEX] != 0; }
  145. _FORCE_INLINE_ bool is_layered_rendering_enabled() const { return flags::any(flags, CLEAR_FLAGS_LAYERED); }
  146. _FORCE_INLINE_ bool operator==(const ClearAttKey &p_rhs) const {
  147. return memcmp(this, &p_rhs, sizeof(ClearAttKey)) == 0;
  148. }
  149. uint32_t hash() const {
  150. uint32_t h = hash_murmur3_one_32(flags);
  151. h = hash_murmur3_one_32(sample_count, h);
  152. h = hash_murmur3_buffer(pixel_formats, ATTACHMENT_COUNT * sizeof(pixel_formats[0]), h);
  153. return hash_fmix32(h);
  154. }
  155. };
  156. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDResourceFactory {
  157. private:
  158. RenderingDeviceDriverMetal *device_driver;
  159. id<MTLFunction> new_func(NSString *p_source, NSString *p_name, NSError **p_error);
  160. id<MTLFunction> new_clear_vert_func(ClearAttKey &p_key);
  161. id<MTLFunction> new_clear_frag_func(ClearAttKey &p_key);
  162. NSString *get_format_type_string(MTLPixelFormat p_fmt);
  163. public:
  164. id<MTLRenderPipelineState> new_clear_pipeline_state(ClearAttKey &p_key, NSError **p_error);
  165. id<MTLDepthStencilState> new_depth_stencil_state(bool p_use_depth, bool p_use_stencil);
  166. MDResourceFactory(RenderingDeviceDriverMetal *p_device_driver) :
  167. device_driver(p_device_driver) {}
  168. ~MDResourceFactory() = default;
  169. };
  170. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDResourceCache {
  171. private:
  172. typedef HashMap<ClearAttKey, id<MTLRenderPipelineState>, HashableHasher<ClearAttKey>> HashMap;
  173. std::unique_ptr<MDResourceFactory> resource_factory;
  174. HashMap clear_states;
  175. struct {
  176. id<MTLDepthStencilState> all;
  177. id<MTLDepthStencilState> depth_only;
  178. id<MTLDepthStencilState> stencil_only;
  179. id<MTLDepthStencilState> none;
  180. } clear_depth_stencil_state;
  181. public:
  182. id<MTLRenderPipelineState> get_clear_render_pipeline_state(ClearAttKey &p_key, NSError **p_error);
  183. id<MTLDepthStencilState> get_depth_stencil_state(bool p_use_depth, bool p_use_stencil);
  184. explicit MDResourceCache(RenderingDeviceDriverMetal *p_device_driver) :
  185. resource_factory(new MDResourceFactory(p_device_driver)) {}
  186. ~MDResourceCache() = default;
  187. };
  188. enum class MDAttachmentType : uint8_t {
  189. None = 0,
  190. Color = 1 << 0,
  191. Depth = 1 << 1,
  192. Stencil = 1 << 2,
  193. };
  194. _FORCE_INLINE_ MDAttachmentType &operator|=(MDAttachmentType &p_a, MDAttachmentType p_b) {
  195. flags::set(p_a, p_b);
  196. return p_a;
  197. }
  198. _FORCE_INLINE_ bool operator&(MDAttachmentType p_a, MDAttachmentType p_b) {
  199. return uint8_t(p_a) & uint8_t(p_b);
  200. }
  201. struct MDSubpass {
  202. uint32_t subpass_index = 0;
  203. uint32_t view_count = 0;
  204. LocalVector<RDD::AttachmentReference> input_references;
  205. LocalVector<RDD::AttachmentReference> color_references;
  206. RDD::AttachmentReference depth_stencil_reference;
  207. LocalVector<RDD::AttachmentReference> resolve_references;
  208. MTLFmtCaps getRequiredFmtCapsForAttachmentAt(uint32_t p_index) const;
  209. };
  210. struct API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDAttachment {
  211. private:
  212. uint32_t index = 0;
  213. uint32_t firstUseSubpassIndex = 0;
  214. uint32_t lastUseSubpassIndex = 0;
  215. public:
  216. MTLPixelFormat format = MTLPixelFormatInvalid;
  217. MDAttachmentType type = MDAttachmentType::None;
  218. MTLLoadAction loadAction = MTLLoadActionDontCare;
  219. MTLStoreAction storeAction = MTLStoreActionDontCare;
  220. MTLLoadAction stencilLoadAction = MTLLoadActionDontCare;
  221. MTLStoreAction stencilStoreAction = MTLStoreActionDontCare;
  222. uint32_t samples = 1;
  223. /*!
  224. * @brief Returns true if this attachment is first used in the given subpass.
  225. * @param p_subpass
  226. * @return
  227. */
  228. _FORCE_INLINE_ bool isFirstUseOf(MDSubpass const &p_subpass) const {
  229. return p_subpass.subpass_index == firstUseSubpassIndex;
  230. }
  231. /*!
  232. * @brief Returns true if this attachment is last used in the given subpass.
  233. * @param p_subpass
  234. * @return
  235. */
  236. _FORCE_INLINE_ bool isLastUseOf(MDSubpass const &p_subpass) const {
  237. return p_subpass.subpass_index == lastUseSubpassIndex;
  238. }
  239. void linkToSubpass(MDRenderPass const &p_pass);
  240. MTLStoreAction getMTLStoreAction(MDSubpass const &p_subpass,
  241. bool p_is_rendering_entire_area,
  242. bool p_has_resolve,
  243. bool p_can_resolve,
  244. bool p_is_stencil) const;
  245. bool configureDescriptor(MTLRenderPassAttachmentDescriptor *p_desc,
  246. PixelFormats &p_pf,
  247. MDSubpass const &p_subpass,
  248. id<MTLTexture> p_attachment,
  249. bool p_is_rendering_entire_area,
  250. bool p_has_resolve,
  251. bool p_can_resolve,
  252. bool p_is_stencil) const;
  253. /** Returns whether this attachment should be cleared in the subpass. */
  254. bool shouldClear(MDSubpass const &p_subpass, bool p_is_stencil) const;
  255. };
  256. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDRenderPass {
  257. public:
  258. Vector<MDAttachment> attachments;
  259. Vector<MDSubpass> subpasses;
  260. uint32_t get_sample_count() const {
  261. return attachments.is_empty() ? 1 : attachments[0].samples;
  262. }
  263. MDRenderPass(Vector<MDAttachment> &p_attachments, Vector<MDSubpass> &p_subpasses);
  264. };
  265. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDCommandBuffer {
  266. private:
  267. RenderingDeviceDriverMetal *device_driver = nullptr;
  268. id<MTLCommandQueue> queue = nil;
  269. id<MTLCommandBuffer> commandBuffer = nil;
  270. void _end_compute_dispatch();
  271. void _end_blit();
  272. #pragma mark - Render
  273. void _render_set_dirty_state();
  274. void _render_bind_uniform_sets();
  275. void _populate_vertices(simd::float4 *p_vertices, Size2i p_fb_size, VectorView<Rect2i> p_rects);
  276. uint32_t _populate_vertices(simd::float4 *p_vertices, uint32_t p_index, Rect2i const &p_rect, Size2i p_fb_size);
  277. void _end_render_pass();
  278. void _render_clear_render_area();
  279. public:
  280. MDCommandBufferStateType type = MDCommandBufferStateType::None;
  281. struct RenderState {
  282. MDRenderPass *pass = nullptr;
  283. MDFrameBuffer *frameBuffer = nullptr;
  284. MDRenderPipeline *pipeline = nullptr;
  285. LocalVector<RDD::RenderPassClearValue> clear_values;
  286. LocalVector<MTLViewport> viewports;
  287. LocalVector<MTLScissorRect> scissors;
  288. std::optional<Color> blend_constants;
  289. uint32_t current_subpass = UINT32_MAX;
  290. Rect2i render_area = {};
  291. bool is_rendering_entire_area = false;
  292. MTLRenderPassDescriptor *desc = nil;
  293. id<MTLRenderCommandEncoder> encoder = nil;
  294. id<MTLBuffer> __unsafe_unretained index_buffer = nil; // Buffer is owned by RDD.
  295. MTLIndexType index_type = MTLIndexTypeUInt16;
  296. uint32_t index_offset = 0;
  297. LocalVector<id<MTLBuffer> __unsafe_unretained> vertex_buffers;
  298. LocalVector<NSUInteger> vertex_offsets;
  299. ResourceUsageMap resource_usage;
  300. // clang-format off
  301. enum DirtyFlag: uint8_t {
  302. DIRTY_NONE = 0b0000'0000,
  303. DIRTY_PIPELINE = 0b0000'0001, //! pipeline state
  304. DIRTY_UNIFORMS = 0b0000'0010, //! uniform sets
  305. DIRTY_DEPTH = 0b0000'0100, //! depth / stenci state
  306. DIRTY_VERTEX = 0b0000'1000, //! vertex buffers
  307. DIRTY_VIEWPORT = 0b0001'0000, //! viewport rectangles
  308. DIRTY_SCISSOR = 0b0010'0000, //! scissor rectangles
  309. DIRTY_BLEND = 0b0100'0000, //! blend state
  310. DIRTY_RASTER = 0b1000'0000, //! encoder state like cull mode
  311. DIRTY_ALL = 0xff,
  312. };
  313. // clang-format on
  314. BitField<DirtyFlag> dirty = DIRTY_NONE;
  315. LocalVector<MDUniformSet *> uniform_sets;
  316. // Bit mask of the uniform sets that are dirty, to prevent redundant binding.
  317. uint64_t uniform_set_mask = 0;
  318. _FORCE_INLINE_ void reset();
  319. void end_encoding();
  320. _ALWAYS_INLINE_ const MDSubpass &get_subpass() const {
  321. DEV_ASSERT(pass != nullptr);
  322. return pass->subpasses[current_subpass];
  323. }
  324. _FORCE_INLINE_ void mark_viewport_dirty() {
  325. if (viewports.is_empty()) {
  326. return;
  327. }
  328. dirty.set_flag(DirtyFlag::DIRTY_VIEWPORT);
  329. }
  330. _FORCE_INLINE_ void mark_scissors_dirty() {
  331. if (scissors.is_empty()) {
  332. return;
  333. }
  334. dirty.set_flag(DirtyFlag::DIRTY_SCISSOR);
  335. }
  336. _FORCE_INLINE_ void mark_vertex_dirty() {
  337. if (vertex_buffers.is_empty()) {
  338. return;
  339. }
  340. dirty.set_flag(DirtyFlag::DIRTY_VERTEX);
  341. }
  342. _FORCE_INLINE_ void mark_uniforms_dirty(std::initializer_list<uint32_t> l) {
  343. if (uniform_sets.is_empty()) {
  344. return;
  345. }
  346. for (uint32_t i : l) {
  347. if (i < uniform_sets.size() && uniform_sets[i] != nullptr) {
  348. uniform_set_mask |= 1 << i;
  349. }
  350. }
  351. dirty.set_flag(DirtyFlag::DIRTY_UNIFORMS);
  352. }
  353. _FORCE_INLINE_ void mark_uniforms_dirty(void) {
  354. if (uniform_sets.is_empty()) {
  355. return;
  356. }
  357. for (uint32_t i = 0; i < uniform_sets.size(); i++) {
  358. if (uniform_sets[i] != nullptr) {
  359. uniform_set_mask |= 1 << i;
  360. }
  361. }
  362. dirty.set_flag(DirtyFlag::DIRTY_UNIFORMS);
  363. }
  364. _FORCE_INLINE_ void mark_blend_dirty() {
  365. if (!blend_constants.has_value()) {
  366. return;
  367. }
  368. dirty.set_flag(DirtyFlag::DIRTY_BLEND);
  369. }
  370. MTLScissorRect clip_to_render_area(MTLScissorRect p_rect) const {
  371. uint32_t raLeft = render_area.position.x;
  372. uint32_t raRight = raLeft + render_area.size.width;
  373. uint32_t raBottom = render_area.position.y;
  374. uint32_t raTop = raBottom + render_area.size.height;
  375. p_rect.x = CLAMP(p_rect.x, raLeft, MAX(raRight - 1, raLeft));
  376. p_rect.y = CLAMP(p_rect.y, raBottom, MAX(raTop - 1, raBottom));
  377. p_rect.width = MIN(p_rect.width, raRight - p_rect.x);
  378. p_rect.height = MIN(p_rect.height, raTop - p_rect.y);
  379. return p_rect;
  380. }
  381. Rect2i clip_to_render_area(Rect2i p_rect) const {
  382. int32_t raLeft = render_area.position.x;
  383. int32_t raRight = raLeft + render_area.size.width;
  384. int32_t raBottom = render_area.position.y;
  385. int32_t raTop = raBottom + render_area.size.height;
  386. p_rect.position.x = CLAMP(p_rect.position.x, raLeft, MAX(raRight - 1, raLeft));
  387. p_rect.position.y = CLAMP(p_rect.position.y, raBottom, MAX(raTop - 1, raBottom));
  388. p_rect.size.width = MIN(p_rect.size.width, raRight - p_rect.position.x);
  389. p_rect.size.height = MIN(p_rect.size.height, raTop - p_rect.position.y);
  390. return p_rect;
  391. }
  392. } render;
  393. // State specific for a compute pass.
  394. struct ComputeState {
  395. MDComputePipeline *pipeline = nullptr;
  396. id<MTLComputeCommandEncoder> encoder = nil;
  397. ResourceUsageMap resource_usage;
  398. _FORCE_INLINE_ void reset() {
  399. pipeline = nil;
  400. encoder = nil;
  401. // Keep the keys, as they are likely to be used again.
  402. for (KeyValue<StageResourceUsage, LocalVector<__unsafe_unretained id<MTLResource>>> &kv : resource_usage) {
  403. kv.value.clear();
  404. }
  405. }
  406. void end_encoding();
  407. } compute;
  408. // State specific to a blit pass.
  409. struct {
  410. id<MTLBlitCommandEncoder> encoder = nil;
  411. _FORCE_INLINE_ void reset() {
  412. encoder = nil;
  413. }
  414. } blit;
  415. _FORCE_INLINE_ id<MTLCommandBuffer> get_command_buffer() const {
  416. return commandBuffer;
  417. }
  418. void begin();
  419. void commit();
  420. void end();
  421. id<MTLBlitCommandEncoder> blit_command_encoder();
  422. void encodeRenderCommandEncoderWithDescriptor(MTLRenderPassDescriptor *p_desc, NSString *p_label);
  423. void bind_pipeline(RDD::PipelineID p_pipeline);
  424. #pragma mark - Render Commands
  425. void render_bind_uniform_set(RDD::UniformSetID p_uniform_set, RDD::ShaderID p_shader, uint32_t p_set_index);
  426. void render_bind_uniform_sets(VectorView<RDD::UniformSetID> p_uniform_sets, RDD::ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count);
  427. void render_clear_attachments(VectorView<RDD::AttachmentClear> p_attachment_clears, VectorView<Rect2i> p_rects);
  428. void render_set_viewport(VectorView<Rect2i> p_viewports);
  429. void render_set_scissor(VectorView<Rect2i> p_scissors);
  430. void render_set_blend_constants(const Color &p_constants);
  431. void render_begin_pass(RDD::RenderPassID p_render_pass,
  432. RDD::FramebufferID p_frameBuffer,
  433. RDD::CommandBufferType p_cmd_buffer_type,
  434. const Rect2i &p_rect,
  435. VectorView<RDD::RenderPassClearValue> p_clear_values);
  436. void render_next_subpass();
  437. void render_draw(uint32_t p_vertex_count,
  438. uint32_t p_instance_count,
  439. uint32_t p_base_vertex,
  440. uint32_t p_first_instance);
  441. void render_bind_vertex_buffers(uint32_t p_binding_count, const RDD::BufferID *p_buffers, const uint64_t *p_offsets);
  442. void render_bind_index_buffer(RDD::BufferID p_buffer, RDD::IndexBufferFormat p_format, uint64_t p_offset);
  443. void render_draw_indexed(uint32_t p_index_count,
  444. uint32_t p_instance_count,
  445. uint32_t p_first_index,
  446. int32_t p_vertex_offset,
  447. uint32_t p_first_instance);
  448. void render_draw_indexed_indirect(RDD::BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride);
  449. void render_draw_indexed_indirect_count(RDD::BufferID p_indirect_buffer, uint64_t p_offset, RDD::BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride);
  450. void render_draw_indirect(RDD::BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride);
  451. void render_draw_indirect_count(RDD::BufferID p_indirect_buffer, uint64_t p_offset, RDD::BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride);
  452. void render_end_pass();
  453. #pragma mark - Compute Commands
  454. void compute_bind_uniform_set(RDD::UniformSetID p_uniform_set, RDD::ShaderID p_shader, uint32_t p_set_index);
  455. void compute_bind_uniform_sets(VectorView<RDD::UniformSetID> p_uniform_sets, RDD::ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count);
  456. void compute_dispatch(uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups);
  457. void compute_dispatch_indirect(RDD::BufferID p_indirect_buffer, uint64_t p_offset);
  458. MDCommandBuffer(id<MTLCommandQueue> p_queue, RenderingDeviceDriverMetal *p_device_driver) :
  459. device_driver(p_device_driver), queue(p_queue) {
  460. type = MDCommandBufferStateType::None;
  461. }
  462. MDCommandBuffer() = default;
  463. };
  464. #if (TARGET_OS_OSX && __MAC_OS_X_VERSION_MAX_ALLOWED < 140000) || (TARGET_OS_IOS && __IPHONE_OS_VERSION_MAX_ALLOWED < 170000)
  465. #define MTLBindingAccess MTLArgumentAccess
  466. #define MTLBindingAccessReadOnly MTLArgumentAccessReadOnly
  467. #define MTLBindingAccessReadWrite MTLArgumentAccessReadWrite
  468. #define MTLBindingAccessWriteOnly MTLArgumentAccessWriteOnly
  469. #endif
  470. struct API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) BindingInfo {
  471. MTLDataType dataType = MTLDataTypeNone;
  472. uint32_t index = 0;
  473. MTLBindingAccess access = MTLBindingAccessReadOnly;
  474. MTLResourceUsage usage = 0;
  475. MTLTextureType textureType = MTLTextureType2D;
  476. int imageFormat = 0;
  477. uint32_t arrayLength = 0;
  478. bool isMultisampled = false;
  479. inline MTLArgumentDescriptor *new_argument_descriptor() const {
  480. MTLArgumentDescriptor *desc = MTLArgumentDescriptor.argumentDescriptor;
  481. desc.dataType = dataType;
  482. desc.index = index;
  483. desc.access = access;
  484. desc.textureType = textureType;
  485. desc.arrayLength = arrayLength;
  486. return desc;
  487. }
  488. size_t serialize_size() const {
  489. return sizeof(uint32_t) * 8 /* 8 uint32_t fields */;
  490. }
  491. template <typename W>
  492. void serialize(W &p_writer) const {
  493. p_writer.write((uint32_t)dataType);
  494. p_writer.write(index);
  495. p_writer.write((uint32_t)access);
  496. p_writer.write((uint32_t)usage);
  497. p_writer.write((uint32_t)textureType);
  498. p_writer.write(imageFormat);
  499. p_writer.write(arrayLength);
  500. p_writer.write(isMultisampled);
  501. }
  502. template <typename R>
  503. void deserialize(R &p_reader) {
  504. p_reader.read((uint32_t &)dataType);
  505. p_reader.read(index);
  506. p_reader.read((uint32_t &)access);
  507. p_reader.read((uint32_t &)usage);
  508. p_reader.read((uint32_t &)textureType);
  509. p_reader.read((uint32_t &)imageFormat);
  510. p_reader.read(arrayLength);
  511. p_reader.read(isMultisampled);
  512. }
  513. };
  514. using RDC = RenderingDeviceCommons;
  515. typedef API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) HashMap<RDC::ShaderStage, BindingInfo> BindingInfoMap;
  516. struct API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) UniformInfo {
  517. uint32_t binding;
  518. ShaderStageUsage active_stages = None;
  519. BindingInfoMap bindings;
  520. BindingInfoMap bindings_secondary;
  521. };
  522. struct API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) UniformSet {
  523. LocalVector<UniformInfo> uniforms;
  524. uint32_t buffer_size = 0;
  525. HashMap<RDC::ShaderStage, uint32_t> offsets;
  526. HashMap<RDC::ShaderStage, id<MTLArgumentEncoder>> encoders;
  527. };
  528. struct ShaderCacheEntry;
  529. enum class ShaderLoadStrategy {
  530. DEFAULT,
  531. LAZY,
  532. };
  533. /// A Metal shader library.
  534. @interface MDLibrary : NSObject {
  535. ShaderCacheEntry *_entry;
  536. };
  537. - (id<MTLLibrary>)library;
  538. - (NSError *)error;
  539. - (void)setLabel:(NSString *)label;
  540. + (instancetype)newLibraryWithCacheEntry:(ShaderCacheEntry *)entry
  541. device:(id<MTLDevice>)device
  542. source:(NSString *)source
  543. options:(MTLCompileOptions *)options
  544. strategy:(ShaderLoadStrategy)strategy;
  545. @end
  546. struct SHA256Digest {
  547. unsigned char data[CC_SHA256_DIGEST_LENGTH];
  548. uint32_t hash() const {
  549. uint32_t c = crc32(0, data, CC_SHA256_DIGEST_LENGTH);
  550. return c;
  551. }
  552. SHA256Digest() {
  553. bzero(data, CC_SHA256_DIGEST_LENGTH);
  554. }
  555. SHA256Digest(const char *p_data, size_t p_length) {
  556. CC_SHA256(p_data, (CC_LONG)p_length, data);
  557. }
  558. _FORCE_INLINE_ uint32_t short_sha() const {
  559. return __builtin_bswap32(*(uint32_t *)&data[0]);
  560. }
  561. };
  562. template <>
  563. struct HashMapComparatorDefault<SHA256Digest> {
  564. static bool compare(const SHA256Digest &p_lhs, const SHA256Digest &p_rhs) {
  565. return memcmp(p_lhs.data, p_rhs.data, CC_SHA256_DIGEST_LENGTH) == 0;
  566. }
  567. };
  568. /// A cache entry for a Metal shader library.
  569. struct ShaderCacheEntry {
  570. RenderingDeviceDriverMetal &owner;
  571. /// A hash of the Metal shader source code.
  572. SHA256Digest key;
  573. CharString name;
  574. RD::ShaderStage stage = RD::SHADER_STAGE_VERTEX;
  575. /// This reference must be weak, to ensure that when the last strong reference to the library
  576. /// is released, the cache entry is freed.
  577. MDLibrary *__weak library = nil;
  578. /// Notify the cache that this entry is no longer needed.
  579. void notify_free() const;
  580. ShaderCacheEntry(RenderingDeviceDriverMetal &p_owner, SHA256Digest p_key) :
  581. owner(p_owner), key(p_key) {
  582. }
  583. ~ShaderCacheEntry() = default;
  584. };
  585. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDShader {
  586. public:
  587. CharString name;
  588. Vector<UniformSet> sets;
  589. bool uses_argument_buffers = true;
  590. virtual void encode_push_constant_data(VectorView<uint32_t> p_data, MDCommandBuffer *p_cb) = 0;
  591. MDShader(CharString p_name, Vector<UniformSet> p_sets, bool p_uses_argument_buffers) :
  592. name(p_name), sets(p_sets), uses_argument_buffers(p_uses_argument_buffers) {}
  593. virtual ~MDShader() = default;
  594. };
  595. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDComputeShader final : public MDShader {
  596. public:
  597. struct {
  598. uint32_t binding = -1;
  599. uint32_t size = 0;
  600. } push_constants;
  601. MTLSize local = {};
  602. MDLibrary *kernel;
  603. #if DEV_ENABLED
  604. CharString kernel_source;
  605. #endif
  606. void encode_push_constant_data(VectorView<uint32_t> p_data, MDCommandBuffer *p_cb) final;
  607. MDComputeShader(CharString p_name, Vector<UniformSet> p_sets, bool p_uses_argument_buffers, MDLibrary *p_kernel);
  608. };
  609. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDRenderShader final : public MDShader {
  610. public:
  611. struct {
  612. struct {
  613. int32_t binding = -1;
  614. uint32_t size = 0;
  615. } vert;
  616. struct {
  617. int32_t binding = -1;
  618. uint32_t size = 0;
  619. } frag;
  620. } push_constants;
  621. bool needs_view_mask_buffer = false;
  622. MDLibrary *vert;
  623. MDLibrary *frag;
  624. #if DEV_ENABLED
  625. CharString vert_source;
  626. CharString frag_source;
  627. #endif
  628. void encode_push_constant_data(VectorView<uint32_t> p_data, MDCommandBuffer *p_cb) final;
  629. MDRenderShader(CharString p_name,
  630. Vector<UniformSet> p_sets,
  631. bool p_needs_view_mask_buffer,
  632. bool p_uses_argument_buffers,
  633. MDLibrary *p_vert, MDLibrary *p_frag);
  634. };
  635. _FORCE_INLINE_ StageResourceUsage &operator|=(StageResourceUsage &p_a, uint32_t p_b) {
  636. p_a = StageResourceUsage(uint32_t(p_a) | p_b);
  637. return p_a;
  638. }
  639. _FORCE_INLINE_ StageResourceUsage stage_resource_usage(RDC::ShaderStage p_stage, MTLResourceUsage p_usage) {
  640. return StageResourceUsage(p_usage << (p_stage * 2));
  641. }
  642. _FORCE_INLINE_ MTLResourceUsage resource_usage_for_stage(StageResourceUsage p_usage, RDC::ShaderStage p_stage) {
  643. return MTLResourceUsage((p_usage >> (p_stage * 2)) & 0b11);
  644. }
  645. template <>
  646. struct HashMapComparatorDefault<RDD::ShaderID> {
  647. static bool compare(const RDD::ShaderID &p_lhs, const RDD::ShaderID &p_rhs) {
  648. return p_lhs.id == p_rhs.id;
  649. }
  650. };
  651. struct BoundUniformSet {
  652. id<MTLBuffer> buffer;
  653. ResourceUsageMap usage_to_resources;
  654. /// Perform a 2-way merge each key of `ResourceVector` resources from this set into the
  655. /// destination set.
  656. ///
  657. /// Assumes the vectors of resources are sorted.
  658. void merge_into(ResourceUsageMap &p_dst) const;
  659. };
  660. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDUniformSet {
  661. private:
  662. void bind_uniforms_argument_buffers(MDShader *p_shader, MDCommandBuffer::RenderState &p_state, uint32_t p_set_index);
  663. void bind_uniforms_direct(MDShader *p_shader, MDCommandBuffer::RenderState &p_state, uint32_t p_set_index);
  664. void bind_uniforms_argument_buffers(MDShader *p_shader, MDCommandBuffer::ComputeState &p_state, uint32_t p_set_index);
  665. void bind_uniforms_direct(MDShader *p_shader, MDCommandBuffer::ComputeState &p_state, uint32_t p_set_index);
  666. public:
  667. uint32_t index;
  668. LocalVector<RDD::BoundUniform> uniforms;
  669. HashMap<MDShader *, BoundUniformSet> bound_uniforms;
  670. void bind_uniforms(MDShader *p_shader, MDCommandBuffer::RenderState &p_state, uint32_t p_set_index);
  671. void bind_uniforms(MDShader *p_shader, MDCommandBuffer::ComputeState &p_state, uint32_t p_set_index);
  672. BoundUniformSet &bound_uniform_set(MDShader *p_shader, id<MTLDevice> p_device, ResourceUsageMap &p_resource_usage, uint32_t p_set_index);
  673. };
  674. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDPipeline {
  675. public:
  676. MDPipelineType type;
  677. explicit MDPipeline(MDPipelineType p_type) :
  678. type(p_type) {}
  679. virtual ~MDPipeline() = default;
  680. };
  681. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDRenderPipeline final : public MDPipeline {
  682. public:
  683. id<MTLRenderPipelineState> state = nil;
  684. id<MTLDepthStencilState> depth_stencil = nil;
  685. uint32_t push_constant_size = 0;
  686. uint32_t push_constant_stages_mask = 0;
  687. SampleCount sample_count = SampleCount1;
  688. struct {
  689. MTLCullMode cull_mode = MTLCullModeNone;
  690. MTLTriangleFillMode fill_mode = MTLTriangleFillModeFill;
  691. MTLDepthClipMode clip_mode = MTLDepthClipModeClip;
  692. MTLWinding winding = MTLWindingClockwise;
  693. MTLPrimitiveType render_primitive = MTLPrimitiveTypePoint;
  694. struct {
  695. bool enabled = false;
  696. } depth_test;
  697. struct {
  698. bool enabled = false;
  699. float depth_bias = 0.0;
  700. float slope_scale = 0.0;
  701. float clamp = 0.0;
  702. _FORCE_INLINE_ void apply(id<MTLRenderCommandEncoder> __unsafe_unretained p_enc) const {
  703. if (!enabled) {
  704. return;
  705. }
  706. [p_enc setDepthBias:depth_bias slopeScale:slope_scale clamp:clamp];
  707. }
  708. } depth_bias;
  709. struct {
  710. bool enabled = false;
  711. uint32_t front_reference = 0;
  712. uint32_t back_reference = 0;
  713. _FORCE_INLINE_ void apply(id<MTLRenderCommandEncoder> __unsafe_unretained p_enc) const {
  714. if (!enabled) {
  715. return;
  716. }
  717. [p_enc setStencilFrontReferenceValue:front_reference backReferenceValue:back_reference];
  718. }
  719. } stencil;
  720. struct {
  721. bool enabled = false;
  722. float r = 0.0;
  723. float g = 0.0;
  724. float b = 0.0;
  725. float a = 0.0;
  726. _FORCE_INLINE_ void apply(id<MTLRenderCommandEncoder> __unsafe_unretained p_enc) const {
  727. //if (!enabled)
  728. // return;
  729. [p_enc setBlendColorRed:r green:g blue:b alpha:a];
  730. }
  731. } blend;
  732. _FORCE_INLINE_ void apply(id<MTLRenderCommandEncoder> __unsafe_unretained p_enc) const {
  733. [p_enc setCullMode:cull_mode];
  734. [p_enc setTriangleFillMode:fill_mode];
  735. [p_enc setDepthClipMode:clip_mode];
  736. [p_enc setFrontFacingWinding:winding];
  737. depth_bias.apply(p_enc);
  738. stencil.apply(p_enc);
  739. blend.apply(p_enc);
  740. }
  741. } raster_state;
  742. MDRenderShader *shader = nil;
  743. MDRenderPipeline() :
  744. MDPipeline(MDPipelineType::Render) {}
  745. ~MDRenderPipeline() final = default;
  746. };
  747. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDComputePipeline final : public MDPipeline {
  748. public:
  749. id<MTLComputePipelineState> state = nil;
  750. struct {
  751. MTLSize local = {};
  752. } compute_state;
  753. MDComputeShader *shader = nil;
  754. explicit MDComputePipeline(id<MTLComputePipelineState> p_state) :
  755. MDPipeline(MDPipelineType::Compute), state(p_state) {}
  756. ~MDComputePipeline() final = default;
  757. };
  758. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDFrameBuffer {
  759. Vector<MTL::Texture> textures;
  760. public:
  761. Size2i size;
  762. MDFrameBuffer(Vector<MTL::Texture> p_textures, Size2i p_size) :
  763. textures(p_textures), size(p_size) {}
  764. MDFrameBuffer() {}
  765. /// Returns the texture at the given index.
  766. _ALWAYS_INLINE_ MTL::Texture get_texture(uint32_t p_idx) const {
  767. return textures[p_idx];
  768. }
  769. /// Returns true if the texture at the given index is not nil.
  770. _ALWAYS_INLINE_ bool has_texture(uint32_t p_idx) const {
  771. return textures[p_idx] != nil;
  772. }
  773. /// Set the texture at the given index.
  774. _ALWAYS_INLINE_ void set_texture(uint32_t p_idx, MTL::Texture p_texture) {
  775. textures.write[p_idx] = p_texture;
  776. }
  777. /// Unset or nil the texture at the given index.
  778. _ALWAYS_INLINE_ void unset_texture(uint32_t p_idx) {
  779. textures.write[p_idx] = nil;
  780. }
  781. /// Resizes buffers to the specified size.
  782. _ALWAYS_INLINE_ void set_texture_count(uint32_t p_size) {
  783. textures.resize(p_size);
  784. }
  785. virtual ~MDFrameBuffer() = default;
  786. };
  787. // These functions are used to convert between Objective-C objects and
  788. // the RIDs used by Godot, respecting automatic reference counting.
  789. namespace rid {
  790. // Converts an Objective-C object to a pointer, and incrementing the
  791. // reference count.
  792. _FORCE_INLINE_ void *owned(id p_id) {
  793. return (__bridge_retained void *)p_id;
  794. }
  795. #define MAKE_ID(FROM, TO) \
  796. _FORCE_INLINE_ TO make(FROM p_obj) { \
  797. return TO(owned(p_obj)); \
  798. }
  799. MAKE_ID(id<MTLTexture>, RDD::TextureID)
  800. MAKE_ID(id<MTLBuffer>, RDD::BufferID)
  801. MAKE_ID(id<MTLSamplerState>, RDD::SamplerID)
  802. MAKE_ID(MTLVertexDescriptor *, RDD::VertexFormatID)
  803. MAKE_ID(id<MTLCommandQueue>, RDD::CommandPoolID)
  804. // Converts a pointer to an Objective-C object without changing the reference count.
  805. _FORCE_INLINE_ auto get(RDD::ID p_id) {
  806. return (p_id.id) ? (__bridge ::id)(void *)p_id.id : nil;
  807. }
  808. // Converts a pointer to an Objective-C object, and decrements the reference count.
  809. _FORCE_INLINE_ auto release(RDD::ID p_id) {
  810. return (__bridge_transfer ::id)(void *)p_id.id;
  811. }
  812. } // namespace rid