rendering_device_driver_metal.mm 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960
  1. /**************************************************************************/
  2. /* rendering_device_driver_metal.mm */
  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. /**************************************************************************/
  31. /* */
  32. /* Portions of this code were derived from MoltenVK. */
  33. /* */
  34. /* Copyright (c) 2015-2023 The Brenwill Workshop Ltd. */
  35. /* (http://www.brenwill.com) */
  36. /* */
  37. /* Licensed under the Apache License, Version 2.0 (the "License"); */
  38. /* you may not use this file except in compliance with the License. */
  39. /* You may obtain a copy of the License at */
  40. /* */
  41. /* http://www.apache.org/licenses/LICENSE-2.0 */
  42. /* */
  43. /* Unless required by applicable law or agreed to in writing, software */
  44. /* distributed under the License is distributed on an "AS IS" BASIS, */
  45. /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
  46. /* implied. See the License for the specific language governing */
  47. /* permissions and limitations under the License. */
  48. /**************************************************************************/
  49. #import "rendering_device_driver_metal.h"
  50. #import "pixel_formats.h"
  51. #import "rendering_context_driver_metal.h"
  52. #import "rendering_shader_container_metal.h"
  53. #include "core/io/compression.h"
  54. #include "core/io/marshalls.h"
  55. #include "core/string/ustring.h"
  56. #include "core/templates/hash_map.h"
  57. #include "drivers/apple/foundation_helpers.h"
  58. #import <Metal/MTLTexture.h>
  59. #import <Metal/Metal.h>
  60. #import <os/log.h>
  61. #import <os/signpost.h>
  62. #import <spirv.hpp>
  63. #import <spirv_msl.hpp>
  64. #import <spirv_parser.hpp>
  65. #pragma mark - Logging
  66. os_log_t LOG_DRIVER;
  67. // Used for dynamic tracing.
  68. os_log_t LOG_INTERVALS;
  69. __attribute__((constructor)) static void InitializeLogging(void) {
  70. LOG_DRIVER = os_log_create("org.godotengine.godot.metal", OS_LOG_CATEGORY_POINTS_OF_INTEREST);
  71. LOG_INTERVALS = os_log_create("org.godotengine.godot.metal", "events");
  72. }
  73. /*****************/
  74. /**** GENERIC ****/
  75. /*****************/
  76. // RDD::CompareOperator == VkCompareOp.
  77. static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_NEVER, MTLCompareFunctionNever));
  78. static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_LESS, MTLCompareFunctionLess));
  79. static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_EQUAL, MTLCompareFunctionEqual));
  80. static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_LESS_OR_EQUAL, MTLCompareFunctionLessEqual));
  81. static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_GREATER, MTLCompareFunctionGreater));
  82. static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_NOT_EQUAL, MTLCompareFunctionNotEqual));
  83. static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_GREATER_OR_EQUAL, MTLCompareFunctionGreaterEqual));
  84. static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_ALWAYS, MTLCompareFunctionAlways));
  85. _FORCE_INLINE_ MTLSize mipmapLevelSizeFromTexture(id<MTLTexture> p_tex, NSUInteger p_level) {
  86. MTLSize lvlSize;
  87. lvlSize.width = MAX(p_tex.width >> p_level, 1UL);
  88. lvlSize.height = MAX(p_tex.height >> p_level, 1UL);
  89. lvlSize.depth = MAX(p_tex.depth >> p_level, 1UL);
  90. return lvlSize;
  91. }
  92. _FORCE_INLINE_ MTLSize mipmapLevelSizeFromSize(MTLSize p_size, NSUInteger p_level) {
  93. if (p_level == 0) {
  94. return p_size;
  95. }
  96. MTLSize lvlSize;
  97. lvlSize.width = MAX(p_size.width >> p_level, 1UL);
  98. lvlSize.height = MAX(p_size.height >> p_level, 1UL);
  99. lvlSize.depth = MAX(p_size.depth >> p_level, 1UL);
  100. return lvlSize;
  101. }
  102. _FORCE_INLINE_ static bool operator==(MTLSize p_a, MTLSize p_b) {
  103. return p_a.width == p_b.width && p_a.height == p_b.height && p_a.depth == p_b.depth;
  104. }
  105. /*****************/
  106. /**** BUFFERS ****/
  107. /*****************/
  108. RDD::BufferID RenderingDeviceDriverMetal::buffer_create(uint64_t p_size, BitField<BufferUsageBits> p_usage, MemoryAllocationType p_allocation_type) {
  109. MTLResourceOptions options = MTLResourceHazardTrackingModeTracked;
  110. switch (p_allocation_type) {
  111. case MEMORY_ALLOCATION_TYPE_CPU:
  112. options |= MTLResourceStorageModeShared;
  113. break;
  114. case MEMORY_ALLOCATION_TYPE_GPU:
  115. options |= MTLResourceStorageModePrivate;
  116. break;
  117. }
  118. id<MTLBuffer> obj = [device newBufferWithLength:p_size options:options];
  119. ERR_FAIL_NULL_V_MSG(obj, BufferID(), "Can't create buffer of size: " + itos(p_size));
  120. return rid::make(obj);
  121. }
  122. bool RenderingDeviceDriverMetal::buffer_set_texel_format(BufferID p_buffer, DataFormat p_format) {
  123. // Nothing to do.
  124. return true;
  125. }
  126. void RenderingDeviceDriverMetal::buffer_free(BufferID p_buffer) {
  127. rid::release(p_buffer);
  128. }
  129. uint64_t RenderingDeviceDriverMetal::buffer_get_allocation_size(BufferID p_buffer) {
  130. id<MTLBuffer> obj = rid::get(p_buffer);
  131. return obj.allocatedSize;
  132. }
  133. uint8_t *RenderingDeviceDriverMetal::buffer_map(BufferID p_buffer) {
  134. id<MTLBuffer> obj = rid::get(p_buffer);
  135. ERR_FAIL_COND_V_MSG(obj.storageMode != MTLStorageModeShared, nullptr, "Unable to map private buffers");
  136. return (uint8_t *)obj.contents;
  137. }
  138. void RenderingDeviceDriverMetal::buffer_unmap(BufferID p_buffer) {
  139. // Nothing to do.
  140. }
  141. uint64_t RenderingDeviceDriverMetal::buffer_get_device_address(BufferID p_buffer) {
  142. if (@available(iOS 16.0, macOS 13.0, *)) {
  143. id<MTLBuffer> obj = rid::get(p_buffer);
  144. return obj.gpuAddress;
  145. } else {
  146. #if DEV_ENABLED
  147. WARN_PRINT_ONCE("buffer_get_device_address is not supported on this OS version.");
  148. #endif
  149. return 0;
  150. }
  151. }
  152. #pragma mark - Texture
  153. #pragma mark - Format Conversions
  154. static const MTLTextureType TEXTURE_TYPE[RD::TEXTURE_TYPE_MAX] = {
  155. MTLTextureType1D,
  156. MTLTextureType2D,
  157. MTLTextureType3D,
  158. MTLTextureTypeCube,
  159. MTLTextureType1DArray,
  160. MTLTextureType2DArray,
  161. MTLTextureTypeCubeArray,
  162. };
  163. RenderingDeviceDriverMetal::Result<bool> RenderingDeviceDriverMetal::is_valid_linear(TextureFormat const &p_format) const {
  164. if (!flags::any(p_format.usage_bits, TEXTURE_USAGE_CPU_READ_BIT)) {
  165. return false;
  166. }
  167. PixelFormats &pf = *pixel_formats;
  168. MTLFormatType ft = pf.getFormatType(p_format.format);
  169. // Requesting a linear format, which has further restrictions, similar to Vulkan
  170. // when specifying VK_IMAGE_TILING_LINEAR.
  171. ERR_FAIL_COND_V_MSG(p_format.texture_type != TEXTURE_TYPE_2D, ERR_CANT_CREATE, "Linear (TEXTURE_USAGE_CPU_READ_BIT) textures must be 2D");
  172. ERR_FAIL_COND_V_MSG(ft != MTLFormatType::DepthStencil, ERR_CANT_CREATE, "Linear (TEXTURE_USAGE_CPU_READ_BIT) textures must not be a depth/stencil format");
  173. ERR_FAIL_COND_V_MSG(ft != MTLFormatType::Compressed, ERR_CANT_CREATE, "Linear (TEXTURE_USAGE_CPU_READ_BIT) textures must not be a compressed format");
  174. ERR_FAIL_COND_V_MSG(p_format.mipmaps != 1, ERR_CANT_CREATE, "Linear (TEXTURE_USAGE_CPU_READ_BIT) textures must have 1 mipmap level");
  175. ERR_FAIL_COND_V_MSG(p_format.array_layers != 1, ERR_CANT_CREATE, "Linear (TEXTURE_USAGE_CPU_READ_BIT) textures must have 1 array layer");
  176. ERR_FAIL_COND_V_MSG(p_format.samples != TEXTURE_SAMPLES_1, ERR_CANT_CREATE, "Linear (TEXTURE_USAGE_CPU_READ_BIT) textures must have 1 sample");
  177. return true;
  178. }
  179. RDD::TextureID RenderingDeviceDriverMetal::texture_create(const TextureFormat &p_format, const TextureView &p_view) {
  180. MTLTextureDescriptor *desc = [MTLTextureDescriptor new];
  181. desc.textureType = TEXTURE_TYPE[p_format.texture_type];
  182. PixelFormats &formats = *pixel_formats;
  183. desc.pixelFormat = formats.getMTLPixelFormat(p_format.format);
  184. MTLFmtCaps format_caps = formats.getCapabilities(desc.pixelFormat);
  185. desc.width = p_format.width;
  186. desc.height = p_format.height;
  187. desc.depth = p_format.depth;
  188. desc.mipmapLevelCount = p_format.mipmaps;
  189. if (p_format.texture_type == TEXTURE_TYPE_1D_ARRAY ||
  190. p_format.texture_type == TEXTURE_TYPE_2D_ARRAY) {
  191. desc.arrayLength = p_format.array_layers;
  192. } else if (p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY) {
  193. desc.arrayLength = p_format.array_layers / 6;
  194. }
  195. // TODO(sgc): Evaluate lossy texture support (perhaps as a project option?)
  196. // https://developer.apple.com/videos/play/tech-talks/10876?time=459
  197. // desc.compressionType = MTLTextureCompressionTypeLossy;
  198. if (p_format.samples > TEXTURE_SAMPLES_1) {
  199. SampleCount supported = (*device_properties).find_nearest_supported_sample_count(p_format.samples);
  200. if (supported > SampleCount1) {
  201. bool ok = p_format.texture_type == TEXTURE_TYPE_2D || p_format.texture_type == TEXTURE_TYPE_2D_ARRAY;
  202. if (ok) {
  203. switch (p_format.texture_type) {
  204. case TEXTURE_TYPE_2D:
  205. desc.textureType = MTLTextureType2DMultisample;
  206. break;
  207. case TEXTURE_TYPE_2D_ARRAY:
  208. desc.textureType = MTLTextureType2DMultisampleArray;
  209. break;
  210. default:
  211. break;
  212. }
  213. desc.sampleCount = (NSUInteger)supported;
  214. if (p_format.mipmaps > 1) {
  215. // For a buffer-backed or multi-sample texture, the value must be 1.
  216. WARN_PRINT("mipmaps == 1 for multi-sample textures");
  217. desc.mipmapLevelCount = 1;
  218. }
  219. } else {
  220. WARN_PRINT("Unsupported multi-sample texture type; disabling multi-sample");
  221. }
  222. }
  223. }
  224. static const MTLTextureSwizzle COMPONENT_SWIZZLE[TEXTURE_SWIZZLE_MAX] = {
  225. static_cast<MTLTextureSwizzle>(255), // IDENTITY
  226. MTLTextureSwizzleZero,
  227. MTLTextureSwizzleOne,
  228. MTLTextureSwizzleRed,
  229. MTLTextureSwizzleGreen,
  230. MTLTextureSwizzleBlue,
  231. MTLTextureSwizzleAlpha,
  232. };
  233. MTLTextureSwizzleChannels swizzle = MTLTextureSwizzleChannelsMake(
  234. p_view.swizzle_r != TEXTURE_SWIZZLE_IDENTITY ? COMPONENT_SWIZZLE[p_view.swizzle_r] : MTLTextureSwizzleRed,
  235. p_view.swizzle_g != TEXTURE_SWIZZLE_IDENTITY ? COMPONENT_SWIZZLE[p_view.swizzle_g] : MTLTextureSwizzleGreen,
  236. p_view.swizzle_b != TEXTURE_SWIZZLE_IDENTITY ? COMPONENT_SWIZZLE[p_view.swizzle_b] : MTLTextureSwizzleBlue,
  237. p_view.swizzle_a != TEXTURE_SWIZZLE_IDENTITY ? COMPONENT_SWIZZLE[p_view.swizzle_a] : MTLTextureSwizzleAlpha);
  238. // Represents a swizzle operation that is a no-op.
  239. static MTLTextureSwizzleChannels IDENTITY_SWIZZLE = {
  240. .red = MTLTextureSwizzleRed,
  241. .green = MTLTextureSwizzleGreen,
  242. .blue = MTLTextureSwizzleBlue,
  243. .alpha = MTLTextureSwizzleAlpha,
  244. };
  245. bool no_swizzle = memcmp(&IDENTITY_SWIZZLE, &swizzle, sizeof(MTLTextureSwizzleChannels)) == 0;
  246. if (!no_swizzle) {
  247. desc.swizzle = swizzle;
  248. }
  249. // Usage.
  250. MTLResourceOptions options = 0;
  251. #if defined(VISIONOS_ENABLED)
  252. const bool supports_memoryless = true;
  253. #else
  254. const bool supports_memoryless = (*device_properties).features.highestFamily >= MTLGPUFamilyApple2 && (*device_properties).features.highestFamily < MTLGPUFamilyMac1;
  255. #endif
  256. if (supports_memoryless && p_format.usage_bits & TEXTURE_USAGE_TRANSIENT_BIT) {
  257. options = MTLResourceStorageModeMemoryless | MTLResourceHazardTrackingModeTracked;
  258. desc.storageMode = MTLStorageModeMemoryless;
  259. } else {
  260. options = MTLResourceCPUCacheModeDefaultCache | MTLResourceHazardTrackingModeTracked;
  261. if (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) {
  262. options |= MTLResourceStorageModeShared;
  263. } else {
  264. options |= MTLResourceStorageModePrivate;
  265. }
  266. }
  267. desc.resourceOptions = options;
  268. if (p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT) {
  269. desc.usage |= MTLTextureUsageShaderRead;
  270. }
  271. if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT) {
  272. desc.usage |= MTLTextureUsageShaderWrite;
  273. }
  274. bool can_be_attachment = flags::any(format_caps, (kMTLFmtCapsColorAtt | kMTLFmtCapsDSAtt));
  275. if (flags::any(p_format.usage_bits, TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) &&
  276. can_be_attachment) {
  277. desc.usage |= MTLTextureUsageRenderTarget;
  278. }
  279. if (p_format.usage_bits & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT) {
  280. desc.usage |= MTLTextureUsageShaderRead;
  281. }
  282. if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_ATOMIC_BIT) {
  283. ERR_FAIL_COND_V_MSG((format_caps & kMTLFmtCapsAtomic) == 0, RDD::TextureID(), "Atomic operations on this texture format are not supported.");
  284. ERR_FAIL_COND_V_MSG(!device_properties->features.supports_native_image_atomics, RDD::TextureID(), "Atomic operations on textures are not supported on this OS version. Check SUPPORTS_IMAGE_ATOMIC_32_BIT.");
  285. // If supports_native_image_atomics is true, this condition should always succeed, as it is set the same.
  286. if (@available(macOS 14.0, iOS 17.0, tvOS 17.0, *)) {
  287. desc.usage |= MTLTextureUsageShaderAtomic;
  288. }
  289. }
  290. if (p_format.usage_bits & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) {
  291. ERR_FAIL_V_MSG(RDD::TextureID(), "unsupported: TEXTURE_USAGE_VRS_ATTACHMENT_BIT");
  292. }
  293. if (flags::any(p_format.usage_bits, TEXTURE_USAGE_CAN_UPDATE_BIT | TEXTURE_USAGE_CAN_COPY_TO_BIT) &&
  294. can_be_attachment && no_swizzle) {
  295. // Per MoltenVK, can be cleared as a render attachment.
  296. desc.usage |= MTLTextureUsageRenderTarget;
  297. }
  298. if (p_format.usage_bits & TEXTURE_USAGE_CAN_COPY_FROM_BIT) {
  299. // Covered by blits.
  300. }
  301. // Create texture views with a different component layout.
  302. if (!p_format.shareable_formats.is_empty()) {
  303. desc.usage |= MTLTextureUsagePixelFormatView;
  304. }
  305. // Allocate memory.
  306. bool is_linear;
  307. {
  308. Result<bool> is_linear_or_err = is_valid_linear(p_format);
  309. ERR_FAIL_COND_V(std::holds_alternative<Error>(is_linear_or_err), TextureID());
  310. is_linear = std::get<bool>(is_linear_or_err);
  311. }
  312. id<MTLTexture> obj = nil;
  313. if (is_linear) {
  314. // Linear textures are restricted to 2D textures, a single mipmap level and a single array layer.
  315. MTLPixelFormat pixel_format = desc.pixelFormat;
  316. size_t row_alignment = get_texel_buffer_alignment_for_format(p_format.format);
  317. size_t bytes_per_row = formats.getBytesPerRow(pixel_format, p_format.width);
  318. bytes_per_row = round_up_to_alignment(bytes_per_row, row_alignment);
  319. size_t bytes_per_layer = formats.getBytesPerLayer(pixel_format, bytes_per_row, p_format.height);
  320. size_t byte_count = bytes_per_layer * p_format.depth * p_format.array_layers;
  321. id<MTLBuffer> buf = [device newBufferWithLength:byte_count options:options];
  322. obj = [buf newTextureWithDescriptor:desc offset:0 bytesPerRow:bytes_per_row];
  323. } else {
  324. obj = [device newTextureWithDescriptor:desc];
  325. }
  326. ERR_FAIL_NULL_V_MSG(obj, TextureID(), "Unable to create texture.");
  327. return rid::make(obj);
  328. }
  329. RDD::TextureID RenderingDeviceDriverMetal::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) {
  330. id<MTLTexture> res = (__bridge id<MTLTexture>)(void *)(uintptr_t)p_native_texture;
  331. // If the requested format is different, we need to create a view.
  332. MTLPixelFormat format = pixel_formats->getMTLPixelFormat(p_format);
  333. if (res.pixelFormat != format) {
  334. MTLTextureSwizzleChannels swizzle = MTLTextureSwizzleChannelsMake(
  335. MTLTextureSwizzleRed,
  336. MTLTextureSwizzleGreen,
  337. MTLTextureSwizzleBlue,
  338. MTLTextureSwizzleAlpha);
  339. res = [res newTextureViewWithPixelFormat:format
  340. textureType:res.textureType
  341. levels:NSMakeRange(0, res.mipmapLevelCount)
  342. slices:NSMakeRange(0, p_array_layers)
  343. swizzle:swizzle];
  344. ERR_FAIL_NULL_V_MSG(res, TextureID(), "Unable to create texture view.");
  345. }
  346. return rid::make(res);
  347. }
  348. RDD::TextureID RenderingDeviceDriverMetal::texture_create_shared(TextureID p_original_texture, const TextureView &p_view) {
  349. id<MTLTexture> src_texture = rid::get(p_original_texture);
  350. NSUInteger slices = src_texture.arrayLength;
  351. if (src_texture.textureType == MTLTextureTypeCube) {
  352. // Metal expects Cube textures to have a slice count of 6.
  353. slices = 6;
  354. } else if (src_texture.textureType == MTLTextureTypeCubeArray) {
  355. // Metal expects Cube Array textures to have 6 slices per layer.
  356. slices *= 6;
  357. }
  358. #if DEV_ENABLED
  359. if (src_texture.sampleCount > 1) {
  360. // TODO(sgc): is it ok to create a shared texture from a multi-sample texture?
  361. WARN_PRINT("Is it safe to create a shared texture from multi-sample texture?");
  362. }
  363. #endif
  364. MTLPixelFormat format = pixel_formats->getMTLPixelFormat(p_view.format);
  365. static const MTLTextureSwizzle component_swizzle[TEXTURE_SWIZZLE_MAX] = {
  366. static_cast<MTLTextureSwizzle>(255), // IDENTITY
  367. MTLTextureSwizzleZero,
  368. MTLTextureSwizzleOne,
  369. MTLTextureSwizzleRed,
  370. MTLTextureSwizzleGreen,
  371. MTLTextureSwizzleBlue,
  372. MTLTextureSwizzleAlpha,
  373. };
  374. #define SWIZZLE(C, CHAN) (p_view.swizzle_##C != TEXTURE_SWIZZLE_IDENTITY ? component_swizzle[p_view.swizzle_##C] : MTLTextureSwizzle##CHAN)
  375. MTLTextureSwizzleChannels swizzle = MTLTextureSwizzleChannelsMake(
  376. SWIZZLE(r, Red),
  377. SWIZZLE(g, Green),
  378. SWIZZLE(b, Blue),
  379. SWIZZLE(a, Alpha));
  380. #undef SWIZZLE
  381. id<MTLTexture> obj = [src_texture newTextureViewWithPixelFormat:format
  382. textureType:src_texture.textureType
  383. levels:NSMakeRange(0, src_texture.mipmapLevelCount)
  384. slices:NSMakeRange(0, slices)
  385. swizzle:swizzle];
  386. ERR_FAIL_NULL_V_MSG(obj, TextureID(), "Unable to create shared texture");
  387. return rid::make(obj);
  388. }
  389. RDD::TextureID RenderingDeviceDriverMetal::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) {
  390. id<MTLTexture> src_texture = rid::get(p_original_texture);
  391. static const MTLTextureType VIEW_TYPES[] = {
  392. MTLTextureType1D, // MTLTextureType1D
  393. MTLTextureType1D, // MTLTextureType1DArray
  394. MTLTextureType2D, // MTLTextureType2D
  395. MTLTextureType2D, // MTLTextureType2DArray
  396. MTLTextureType2D, // MTLTextureType2DMultisample
  397. MTLTextureType2D, // MTLTextureTypeCube
  398. MTLTextureType2D, // MTLTextureTypeCubeArray
  399. MTLTextureType2D, // MTLTextureType3D
  400. MTLTextureType2D, // MTLTextureType2DMultisampleArray
  401. };
  402. MTLTextureType textureType = VIEW_TYPES[src_texture.textureType];
  403. switch (p_slice_type) {
  404. case TEXTURE_SLICE_2D: {
  405. textureType = MTLTextureType2D;
  406. } break;
  407. case TEXTURE_SLICE_3D: {
  408. textureType = MTLTextureType3D;
  409. } break;
  410. case TEXTURE_SLICE_CUBEMAP: {
  411. textureType = MTLTextureTypeCube;
  412. } break;
  413. case TEXTURE_SLICE_2D_ARRAY: {
  414. textureType = MTLTextureType2DArray;
  415. } break;
  416. case TEXTURE_SLICE_MAX: {
  417. ERR_FAIL_V_MSG(TextureID(), "Invalid texture slice type");
  418. } break;
  419. }
  420. MTLPixelFormat format = pixel_formats->getMTLPixelFormat(p_view.format);
  421. static const MTLTextureSwizzle component_swizzle[TEXTURE_SWIZZLE_MAX] = {
  422. static_cast<MTLTextureSwizzle>(255), // IDENTITY
  423. MTLTextureSwizzleZero,
  424. MTLTextureSwizzleOne,
  425. MTLTextureSwizzleRed,
  426. MTLTextureSwizzleGreen,
  427. MTLTextureSwizzleBlue,
  428. MTLTextureSwizzleAlpha,
  429. };
  430. #define SWIZZLE(C, CHAN) (p_view.swizzle_##C != TEXTURE_SWIZZLE_IDENTITY ? component_swizzle[p_view.swizzle_##C] : MTLTextureSwizzle##CHAN)
  431. MTLTextureSwizzleChannels swizzle = MTLTextureSwizzleChannelsMake(
  432. SWIZZLE(r, Red),
  433. SWIZZLE(g, Green),
  434. SWIZZLE(b, Blue),
  435. SWIZZLE(a, Alpha));
  436. #undef SWIZZLE
  437. id<MTLTexture> obj = [src_texture newTextureViewWithPixelFormat:format
  438. textureType:textureType
  439. levels:NSMakeRange(p_mipmap, p_mipmaps)
  440. slices:NSMakeRange(p_layer, p_layers)
  441. swizzle:swizzle];
  442. ERR_FAIL_NULL_V_MSG(obj, TextureID(), "Unable to create shared texture");
  443. return rid::make(obj);
  444. }
  445. void RenderingDeviceDriverMetal::texture_free(TextureID p_texture) {
  446. rid::release(p_texture);
  447. }
  448. uint64_t RenderingDeviceDriverMetal::texture_get_allocation_size(TextureID p_texture) {
  449. id<MTLTexture> obj = rid::get(p_texture);
  450. return obj.allocatedSize;
  451. }
  452. void RenderingDeviceDriverMetal::_get_sub_resource(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) const {
  453. id<MTLTexture> obj = rid::get(p_texture);
  454. *r_layout = {};
  455. PixelFormats &pf = *pixel_formats;
  456. size_t row_alignment = get_texel_buffer_alignment_for_format(obj.pixelFormat);
  457. size_t offset = 0;
  458. size_t array_layers = obj.arrayLength;
  459. MTLSize size = MTLSizeMake(obj.width, obj.height, obj.depth);
  460. MTLPixelFormat pixel_format = obj.pixelFormat;
  461. // First skip over the mipmap levels.
  462. for (uint32_t mipLvl = 0; mipLvl < p_subresource.mipmap; mipLvl++) {
  463. MTLSize mip_size = mipmapLevelSizeFromSize(size, mipLvl);
  464. size_t bytes_per_row = pf.getBytesPerRow(pixel_format, mip_size.width);
  465. bytes_per_row = round_up_to_alignment(bytes_per_row, row_alignment);
  466. size_t bytes_per_layer = pf.getBytesPerLayer(pixel_format, bytes_per_row, mip_size.height);
  467. offset += bytes_per_layer * mip_size.depth * array_layers;
  468. }
  469. // Get current mipmap.
  470. MTLSize mip_size = mipmapLevelSizeFromSize(size, p_subresource.mipmap);
  471. size_t bytes_per_row = pf.getBytesPerRow(pixel_format, mip_size.width);
  472. bytes_per_row = round_up_to_alignment(bytes_per_row, row_alignment);
  473. size_t bytes_per_layer = pf.getBytesPerLayer(pixel_format, bytes_per_row, mip_size.height);
  474. r_layout->size = bytes_per_layer * mip_size.depth;
  475. r_layout->offset = offset + (r_layout->size * p_subresource.layer - 1);
  476. r_layout->depth_pitch = bytes_per_layer;
  477. r_layout->row_pitch = bytes_per_row;
  478. r_layout->layer_pitch = r_layout->size * array_layers;
  479. }
  480. void RenderingDeviceDriverMetal::texture_get_copyable_layout(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) {
  481. id<MTLTexture> obj = rid::get(p_texture);
  482. *r_layout = {};
  483. if ((obj.resourceOptions & MTLResourceStorageModePrivate) != 0) {
  484. MTLSize sz = MTLSizeMake(obj.width, obj.height, obj.depth);
  485. PixelFormats &pf = *pixel_formats;
  486. DataFormat format = pf.getDataFormat(obj.pixelFormat);
  487. if (p_subresource.mipmap > 0) {
  488. r_layout->offset = get_image_format_required_size(format, sz.width, sz.height, sz.depth, p_subresource.mipmap);
  489. }
  490. sz = mipmapLevelSizeFromSize(sz, p_subresource.mipmap);
  491. uint32_t bw = 0, bh = 0;
  492. get_compressed_image_format_block_dimensions(format, bw, bh);
  493. uint32_t sbw = 0, sbh = 0;
  494. r_layout->size = get_image_format_required_size(format, sz.width, sz.height, sz.depth, 1, &sbw, &sbh);
  495. r_layout->row_pitch = r_layout->size / ((sbh / bh) * sz.depth);
  496. r_layout->depth_pitch = r_layout->size / sz.depth;
  497. uint32_t array_length = obj.arrayLength;
  498. if (obj.textureType == MTLTextureTypeCube) {
  499. array_length = 6;
  500. } else if (obj.textureType == MTLTextureTypeCubeArray) {
  501. array_length *= 6;
  502. }
  503. r_layout->layer_pitch = r_layout->size / array_length;
  504. } else {
  505. CRASH_NOW_MSG("need to calculate layout for shared texture");
  506. }
  507. }
  508. uint8_t *RenderingDeviceDriverMetal::texture_map(TextureID p_texture, const TextureSubresource &p_subresource) {
  509. id<MTLTexture> obj = rid::get(p_texture);
  510. ERR_FAIL_NULL_V_MSG(obj.buffer, nullptr, "texture is not created from a buffer");
  511. TextureCopyableLayout layout;
  512. _get_sub_resource(p_texture, p_subresource, &layout);
  513. return (uint8_t *)(obj.buffer.contents) + layout.offset;
  514. PixelFormats &pf = *pixel_formats;
  515. size_t row_alignment = get_texel_buffer_alignment_for_format(obj.pixelFormat);
  516. size_t offset = 0;
  517. size_t array_layers = obj.arrayLength;
  518. MTLSize size = MTLSizeMake(obj.width, obj.height, obj.depth);
  519. MTLPixelFormat pixel_format = obj.pixelFormat;
  520. // First skip over the mipmap levels.
  521. for (uint32_t mipLvl = 0; mipLvl < p_subresource.mipmap; mipLvl++) {
  522. MTLSize mipExtent = mipmapLevelSizeFromSize(size, mipLvl);
  523. size_t bytes_per_row = pf.getBytesPerRow(pixel_format, mipExtent.width);
  524. bytes_per_row = round_up_to_alignment(bytes_per_row, row_alignment);
  525. size_t bytes_per_layer = pf.getBytesPerLayer(pixel_format, bytes_per_row, mipExtent.height);
  526. offset += bytes_per_layer * mipExtent.depth * array_layers;
  527. }
  528. if (p_subresource.layer > 1) {
  529. // Calculate offset to desired layer.
  530. MTLSize mipExtent = mipmapLevelSizeFromSize(size, p_subresource.mipmap);
  531. size_t bytes_per_row = pf.getBytesPerRow(pixel_format, mipExtent.width);
  532. bytes_per_row = round_up_to_alignment(bytes_per_row, row_alignment);
  533. size_t bytes_per_layer = pf.getBytesPerLayer(pixel_format, bytes_per_row, mipExtent.height);
  534. offset += bytes_per_layer * mipExtent.depth * (p_subresource.layer - 1);
  535. }
  536. // TODO: Confirm with rendering team that there is no other way Godot may attempt to map a texture with multiple mipmaps or array layers.
  537. // NOTE: It is not possible to create a buffer-backed texture with mipmaps or array layers,
  538. // as noted in the is_valid_linear function, so the offset calculation SHOULD always be zero.
  539. // Given that, this code should be simplified.
  540. return (uint8_t *)(obj.buffer.contents) + offset;
  541. }
  542. void RenderingDeviceDriverMetal::texture_unmap(TextureID p_texture) {
  543. // Nothing to do.
  544. }
  545. BitField<RDD::TextureUsageBits> RenderingDeviceDriverMetal::texture_get_usages_supported_by_format(DataFormat p_format, bool p_cpu_readable) {
  546. PixelFormats &pf = *pixel_formats;
  547. if (pf.getMTLPixelFormat(p_format) == MTLPixelFormatInvalid) {
  548. return 0;
  549. }
  550. MTLFmtCaps caps = pf.getCapabilities(p_format);
  551. // Everything supported by default makes an all-or-nothing check easier for the caller.
  552. BitField<RDD::TextureUsageBits> supported = INT64_MAX;
  553. supported.clear_flag(TEXTURE_USAGE_VRS_ATTACHMENT_BIT); // No VRS support for Metal.
  554. if (!flags::any(caps, kMTLFmtCapsColorAtt)) {
  555. supported.clear_flag(TEXTURE_USAGE_COLOR_ATTACHMENT_BIT);
  556. }
  557. if (!flags::any(caps, kMTLFmtCapsDSAtt)) {
  558. supported.clear_flag(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
  559. }
  560. if (!flags::any(caps, kMTLFmtCapsRead)) {
  561. supported.clear_flag(TEXTURE_USAGE_SAMPLING_BIT);
  562. }
  563. if (!flags::any(caps, kMTLFmtCapsAtomic)) {
  564. supported.clear_flag(TEXTURE_USAGE_STORAGE_ATOMIC_BIT);
  565. }
  566. return supported;
  567. }
  568. bool RenderingDeviceDriverMetal::texture_can_make_shared_with_format(TextureID p_texture, DataFormat p_format, bool &r_raw_reinterpretation) {
  569. r_raw_reinterpretation = false;
  570. return true;
  571. }
  572. #pragma mark - Sampler
  573. static const MTLCompareFunction COMPARE_OPERATORS[RD::COMPARE_OP_MAX] = {
  574. MTLCompareFunctionNever,
  575. MTLCompareFunctionLess,
  576. MTLCompareFunctionEqual,
  577. MTLCompareFunctionLessEqual,
  578. MTLCompareFunctionGreater,
  579. MTLCompareFunctionNotEqual,
  580. MTLCompareFunctionGreaterEqual,
  581. MTLCompareFunctionAlways,
  582. };
  583. static const MTLStencilOperation STENCIL_OPERATIONS[RD::STENCIL_OP_MAX] = {
  584. MTLStencilOperationKeep,
  585. MTLStencilOperationZero,
  586. MTLStencilOperationReplace,
  587. MTLStencilOperationIncrementClamp,
  588. MTLStencilOperationDecrementClamp,
  589. MTLStencilOperationInvert,
  590. MTLStencilOperationIncrementWrap,
  591. MTLStencilOperationDecrementWrap,
  592. };
  593. static const MTLBlendFactor BLEND_FACTORS[RD::BLEND_FACTOR_MAX] = {
  594. MTLBlendFactorZero,
  595. MTLBlendFactorOne,
  596. MTLBlendFactorSourceColor,
  597. MTLBlendFactorOneMinusSourceColor,
  598. MTLBlendFactorDestinationColor,
  599. MTLBlendFactorOneMinusDestinationColor,
  600. MTLBlendFactorSourceAlpha,
  601. MTLBlendFactorOneMinusSourceAlpha,
  602. MTLBlendFactorDestinationAlpha,
  603. MTLBlendFactorOneMinusDestinationAlpha,
  604. MTLBlendFactorBlendColor,
  605. MTLBlendFactorOneMinusBlendColor,
  606. MTLBlendFactorBlendAlpha,
  607. MTLBlendFactorOneMinusBlendAlpha,
  608. MTLBlendFactorSourceAlphaSaturated,
  609. MTLBlendFactorSource1Color,
  610. MTLBlendFactorOneMinusSource1Color,
  611. MTLBlendFactorSource1Alpha,
  612. MTLBlendFactorOneMinusSource1Alpha,
  613. };
  614. static const MTLBlendOperation BLEND_OPERATIONS[RD::BLEND_OP_MAX] = {
  615. MTLBlendOperationAdd,
  616. MTLBlendOperationSubtract,
  617. MTLBlendOperationReverseSubtract,
  618. MTLBlendOperationMin,
  619. MTLBlendOperationMax,
  620. };
  621. static const API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MTLSamplerAddressMode ADDRESS_MODES[RD::SAMPLER_REPEAT_MODE_MAX] = {
  622. MTLSamplerAddressModeRepeat,
  623. MTLSamplerAddressModeMirrorRepeat,
  624. MTLSamplerAddressModeClampToEdge,
  625. MTLSamplerAddressModeClampToBorderColor,
  626. MTLSamplerAddressModeMirrorClampToEdge,
  627. };
  628. static const API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MTLSamplerBorderColor SAMPLER_BORDER_COLORS[RD::SAMPLER_BORDER_COLOR_MAX] = {
  629. MTLSamplerBorderColorTransparentBlack,
  630. MTLSamplerBorderColorTransparentBlack,
  631. MTLSamplerBorderColorOpaqueBlack,
  632. MTLSamplerBorderColorOpaqueBlack,
  633. MTLSamplerBorderColorOpaqueWhite,
  634. MTLSamplerBorderColorOpaqueWhite,
  635. };
  636. RDD::SamplerID RenderingDeviceDriverMetal::sampler_create(const SamplerState &p_state) {
  637. MTLSamplerDescriptor *desc = [MTLSamplerDescriptor new];
  638. desc.supportArgumentBuffers = YES;
  639. desc.magFilter = p_state.mag_filter == SAMPLER_FILTER_LINEAR ? MTLSamplerMinMagFilterLinear : MTLSamplerMinMagFilterNearest;
  640. desc.minFilter = p_state.min_filter == SAMPLER_FILTER_LINEAR ? MTLSamplerMinMagFilterLinear : MTLSamplerMinMagFilterNearest;
  641. desc.mipFilter = p_state.mip_filter == SAMPLER_FILTER_LINEAR ? MTLSamplerMipFilterLinear : MTLSamplerMipFilterNearest;
  642. desc.sAddressMode = ADDRESS_MODES[p_state.repeat_u];
  643. desc.tAddressMode = ADDRESS_MODES[p_state.repeat_v];
  644. desc.rAddressMode = ADDRESS_MODES[p_state.repeat_w];
  645. if (p_state.use_anisotropy) {
  646. desc.maxAnisotropy = p_state.anisotropy_max;
  647. }
  648. desc.compareFunction = COMPARE_OPERATORS[p_state.compare_op];
  649. desc.lodMinClamp = p_state.min_lod;
  650. desc.lodMaxClamp = p_state.max_lod;
  651. desc.borderColor = SAMPLER_BORDER_COLORS[p_state.border_color];
  652. desc.normalizedCoordinates = !p_state.unnormalized_uvw;
  653. if (p_state.lod_bias != 0.0) {
  654. WARN_PRINT_ONCE("Metal does not support LOD bias for samplers.");
  655. }
  656. id<MTLSamplerState> obj = [device newSamplerStateWithDescriptor:desc];
  657. ERR_FAIL_NULL_V_MSG(obj, SamplerID(), "newSamplerStateWithDescriptor failed");
  658. return rid::make(obj);
  659. }
  660. void RenderingDeviceDriverMetal::sampler_free(SamplerID p_sampler) {
  661. rid::release(p_sampler);
  662. }
  663. bool RenderingDeviceDriverMetal::sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_filter) {
  664. switch (p_filter) {
  665. case SAMPLER_FILTER_NEAREST:
  666. return true;
  667. case SAMPLER_FILTER_LINEAR: {
  668. MTLFmtCaps caps = pixel_formats->getCapabilities(p_format);
  669. return flags::any(caps, kMTLFmtCapsFilter);
  670. }
  671. }
  672. }
  673. #pragma mark - Vertex Array
  674. RDD::VertexFormatID RenderingDeviceDriverMetal::vertex_format_create(VectorView<VertexAttribute> p_vertex_attribs) {
  675. MTLVertexDescriptor *desc = MTLVertexDescriptor.vertexDescriptor;
  676. for (uint32_t i = 0; i < p_vertex_attribs.size(); i++) {
  677. VertexAttribute const &vf = p_vertex_attribs[i];
  678. ERR_FAIL_COND_V_MSG(get_format_vertex_size(vf.format) == 0, VertexFormatID(),
  679. "Data format for attachment (" + itos(i) + "), '" + FORMAT_NAMES[vf.format] + "', is not valid for a vertex array.");
  680. desc.attributes[vf.location].format = pixel_formats->getMTLVertexFormat(vf.format);
  681. desc.attributes[vf.location].offset = vf.offset;
  682. uint32_t idx = get_metal_buffer_index_for_vertex_attribute_binding(i);
  683. desc.attributes[vf.location].bufferIndex = idx;
  684. if (vf.stride == 0) {
  685. desc.layouts[idx].stepFunction = MTLVertexStepFunctionConstant;
  686. desc.layouts[idx].stepRate = 0;
  687. desc.layouts[idx].stride = pixel_formats->getBytesPerBlock(vf.format);
  688. } else {
  689. desc.layouts[idx].stepFunction = vf.frequency == VERTEX_FREQUENCY_VERTEX ? MTLVertexStepFunctionPerVertex : MTLVertexStepFunctionPerInstance;
  690. desc.layouts[idx].stepRate = 1;
  691. desc.layouts[idx].stride = vf.stride;
  692. }
  693. }
  694. return rid::make(desc);
  695. }
  696. void RenderingDeviceDriverMetal::vertex_format_free(VertexFormatID p_vertex_format) {
  697. rid::release(p_vertex_format);
  698. }
  699. #pragma mark - Barriers
  700. void RenderingDeviceDriverMetal::command_pipeline_barrier(
  701. CommandBufferID p_cmd_buffer,
  702. BitField<PipelineStageBits> p_src_stages,
  703. BitField<PipelineStageBits> p_dst_stages,
  704. VectorView<MemoryBarrier> p_memory_barriers,
  705. VectorView<BufferBarrier> p_buffer_barriers,
  706. VectorView<TextureBarrier> p_texture_barriers) {
  707. WARN_PRINT_ONCE("not implemented");
  708. }
  709. #pragma mark - Fences
  710. RDD::FenceID RenderingDeviceDriverMetal::fence_create() {
  711. Fence *fence = memnew(Fence);
  712. return FenceID(fence);
  713. }
  714. Error RenderingDeviceDriverMetal::fence_wait(FenceID p_fence) {
  715. Fence *fence = (Fence *)(p_fence.id);
  716. // Wait forever, so this function is infallible.
  717. dispatch_semaphore_wait(fence->semaphore, DISPATCH_TIME_FOREVER);
  718. return OK;
  719. }
  720. void RenderingDeviceDriverMetal::fence_free(FenceID p_fence) {
  721. Fence *fence = (Fence *)(p_fence.id);
  722. memdelete(fence);
  723. }
  724. #pragma mark - Semaphores
  725. RDD::SemaphoreID RenderingDeviceDriverMetal::semaphore_create() {
  726. // Metal doesn't use semaphores, as their purpose within Godot is to ensure ordering of command buffer execution.
  727. return SemaphoreID(1);
  728. }
  729. void RenderingDeviceDriverMetal::semaphore_free(SemaphoreID p_semaphore) {
  730. }
  731. #pragma mark - Queues
  732. RDD::CommandQueueFamilyID RenderingDeviceDriverMetal::command_queue_family_get(BitField<CommandQueueFamilyBits> p_cmd_queue_family_bits, RenderingContextDriver::SurfaceID p_surface) {
  733. if (p_cmd_queue_family_bits.has_flag(COMMAND_QUEUE_FAMILY_GRAPHICS_BIT) || (p_surface != 0)) {
  734. return CommandQueueFamilyID(COMMAND_QUEUE_FAMILY_GRAPHICS_BIT);
  735. } else if (p_cmd_queue_family_bits.has_flag(COMMAND_QUEUE_FAMILY_COMPUTE_BIT)) {
  736. return CommandQueueFamilyID(COMMAND_QUEUE_FAMILY_COMPUTE_BIT);
  737. } else if (p_cmd_queue_family_bits.has_flag(COMMAND_QUEUE_FAMILY_TRANSFER_BIT)) {
  738. return CommandQueueFamilyID(COMMAND_QUEUE_FAMILY_TRANSFER_BIT);
  739. } else {
  740. return CommandQueueFamilyID();
  741. }
  742. }
  743. RDD::CommandQueueID RenderingDeviceDriverMetal::command_queue_create(CommandQueueFamilyID p_cmd_queue_family, bool p_identify_as_main_queue) {
  744. return CommandQueueID(1);
  745. }
  746. Error RenderingDeviceDriverMetal::command_queue_execute_and_present(CommandQueueID p_cmd_queue, VectorView<SemaphoreID>, VectorView<CommandBufferID> p_cmd_buffers, VectorView<SemaphoreID>, FenceID p_cmd_fence, VectorView<SwapChainID> p_swap_chains) {
  747. uint32_t size = p_cmd_buffers.size();
  748. if (size == 0) {
  749. return OK;
  750. }
  751. for (uint32_t i = 0; i < size - 1; i++) {
  752. MDCommandBuffer *cmd_buffer = (MDCommandBuffer *)(p_cmd_buffers[i].id);
  753. cmd_buffer->commit();
  754. }
  755. // The last command buffer will signal the fence and semaphores.
  756. MDCommandBuffer *cmd_buffer = (MDCommandBuffer *)(p_cmd_buffers[size - 1].id);
  757. Fence *fence = (Fence *)(p_cmd_fence.id);
  758. if (fence != nullptr) {
  759. id<MTLCommandBuffer> cb = cmd_buffer->get_command_buffer();
  760. if (cb == nil) {
  761. // If there is nothing to do, signal the fence immediately.
  762. dispatch_semaphore_signal(fence->semaphore);
  763. } else {
  764. [cb addCompletedHandler:^(id<MTLCommandBuffer> buffer) {
  765. dispatch_semaphore_signal(fence->semaphore);
  766. }];
  767. }
  768. }
  769. for (uint32_t i = 0; i < p_swap_chains.size(); i++) {
  770. SwapChain *swap_chain = (SwapChain *)(p_swap_chains[i].id);
  771. RenderingContextDriverMetal::Surface *metal_surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
  772. metal_surface->present(cmd_buffer);
  773. }
  774. cmd_buffer->commit();
  775. if (p_swap_chains.size() > 0) {
  776. // Used as a signal that we're presenting, so this is the end of a frame.
  777. [device_scope endScope];
  778. [device_scope beginScope];
  779. }
  780. return OK;
  781. }
  782. void RenderingDeviceDriverMetal::command_queue_free(CommandQueueID p_cmd_queue) {
  783. }
  784. #pragma mark - Command Buffers
  785. // ----- POOL -----
  786. RDD::CommandPoolID RenderingDeviceDriverMetal::command_pool_create(CommandQueueFamilyID p_cmd_queue_family, CommandBufferType p_cmd_buffer_type) {
  787. DEV_ASSERT(p_cmd_buffer_type == COMMAND_BUFFER_TYPE_PRIMARY);
  788. return rid::make(device_queue);
  789. }
  790. bool RenderingDeviceDriverMetal::command_pool_reset(CommandPoolID p_cmd_pool) {
  791. return true;
  792. }
  793. void RenderingDeviceDriverMetal::command_pool_free(CommandPoolID p_cmd_pool) {
  794. rid::release(p_cmd_pool);
  795. }
  796. // ----- BUFFER -----
  797. RDD::CommandBufferID RenderingDeviceDriverMetal::command_buffer_create(CommandPoolID p_cmd_pool) {
  798. id<MTLCommandQueue> queue = rid::get(p_cmd_pool);
  799. MDCommandBuffer *obj = new MDCommandBuffer(queue, this);
  800. command_buffers.push_back(obj);
  801. return CommandBufferID(obj);
  802. }
  803. bool RenderingDeviceDriverMetal::command_buffer_begin(CommandBufferID p_cmd_buffer) {
  804. MDCommandBuffer *obj = (MDCommandBuffer *)(p_cmd_buffer.id);
  805. obj->begin();
  806. return true;
  807. }
  808. bool RenderingDeviceDriverMetal::command_buffer_begin_secondary(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, uint32_t p_subpass, FramebufferID p_framebuffer) {
  809. ERR_FAIL_V_MSG(false, "not implemented");
  810. }
  811. void RenderingDeviceDriverMetal::command_buffer_end(CommandBufferID p_cmd_buffer) {
  812. MDCommandBuffer *obj = (MDCommandBuffer *)(p_cmd_buffer.id);
  813. obj->end();
  814. }
  815. void RenderingDeviceDriverMetal::command_buffer_execute_secondary(CommandBufferID p_cmd_buffer, VectorView<CommandBufferID> p_secondary_cmd_buffers) {
  816. ERR_FAIL_MSG("not implemented");
  817. }
  818. #pragma mark - Swap Chain
  819. void RenderingDeviceDriverMetal::_swap_chain_release(SwapChain *p_swap_chain) {
  820. _swap_chain_release_buffers(p_swap_chain);
  821. }
  822. void RenderingDeviceDriverMetal::_swap_chain_release_buffers(SwapChain *p_swap_chain) {
  823. }
  824. RDD::SwapChainID RenderingDeviceDriverMetal::swap_chain_create(RenderingContextDriver::SurfaceID p_surface) {
  825. RenderingContextDriverMetal::Surface const *surface = (RenderingContextDriverMetal::Surface *)(p_surface);
  826. // Create the render pass that will be used to draw to the swap chain's framebuffers.
  827. RDD::Attachment attachment;
  828. attachment.format = pixel_formats->getDataFormat(surface->get_pixel_format());
  829. attachment.samples = RDD::TEXTURE_SAMPLES_1;
  830. attachment.load_op = RDD::ATTACHMENT_LOAD_OP_CLEAR;
  831. attachment.store_op = RDD::ATTACHMENT_STORE_OP_STORE;
  832. RDD::Subpass subpass;
  833. RDD::AttachmentReference color_ref;
  834. color_ref.attachment = 0;
  835. color_ref.aspect.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT);
  836. subpass.color_references.push_back(color_ref);
  837. RenderPassID render_pass = render_pass_create(attachment, subpass, {}, 1, RDD::AttachmentReference());
  838. ERR_FAIL_COND_V(!render_pass, SwapChainID());
  839. // Create the empty swap chain until it is resized.
  840. SwapChain *swap_chain = memnew(SwapChain);
  841. swap_chain->surface = p_surface;
  842. swap_chain->data_format = attachment.format;
  843. swap_chain->render_pass = render_pass;
  844. return SwapChainID(swap_chain);
  845. }
  846. Error RenderingDeviceDriverMetal::swap_chain_resize(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, uint32_t p_desired_framebuffer_count) {
  847. DEV_ASSERT(p_cmd_queue.id != 0);
  848. DEV_ASSERT(p_swap_chain.id != 0);
  849. SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
  850. RenderingContextDriverMetal::Surface *surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
  851. surface->resize(p_desired_framebuffer_count);
  852. // Once everything's been created correctly, indicate the surface no longer needs to be resized.
  853. context_driver->surface_set_needs_resize(swap_chain->surface, false);
  854. return OK;
  855. }
  856. RDD::FramebufferID RenderingDeviceDriverMetal::swap_chain_acquire_framebuffer(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, bool &r_resize_required) {
  857. DEV_ASSERT(p_cmd_queue.id != 0);
  858. DEV_ASSERT(p_swap_chain.id != 0);
  859. SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
  860. if (context_driver->surface_get_needs_resize(swap_chain->surface)) {
  861. r_resize_required = true;
  862. return FramebufferID();
  863. }
  864. RenderingContextDriverMetal::Surface *metal_surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
  865. return metal_surface->acquire_next_frame_buffer();
  866. }
  867. RDD::RenderPassID RenderingDeviceDriverMetal::swap_chain_get_render_pass(SwapChainID p_swap_chain) {
  868. const SwapChain *swap_chain = (const SwapChain *)(p_swap_chain.id);
  869. return swap_chain->render_pass;
  870. }
  871. RDD::DataFormat RenderingDeviceDriverMetal::swap_chain_get_format(SwapChainID p_swap_chain) {
  872. const SwapChain *swap_chain = (const SwapChain *)(p_swap_chain.id);
  873. return swap_chain->data_format;
  874. }
  875. void RenderingDeviceDriverMetal::swap_chain_set_max_fps(SwapChainID p_swap_chain, int p_max_fps) {
  876. SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
  877. RenderingContextDriverMetal::Surface *metal_surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
  878. metal_surface->set_max_fps(p_max_fps);
  879. }
  880. void RenderingDeviceDriverMetal::swap_chain_free(SwapChainID p_swap_chain) {
  881. SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
  882. _swap_chain_release(swap_chain);
  883. render_pass_free(swap_chain->render_pass);
  884. memdelete(swap_chain);
  885. }
  886. #pragma mark - Frame buffer
  887. RDD::FramebufferID RenderingDeviceDriverMetal::framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height) {
  888. MDRenderPass *pass = (MDRenderPass *)(p_render_pass.id);
  889. Vector<MTL::Texture> textures;
  890. textures.resize(p_attachments.size());
  891. for (uint32_t i = 0; i < p_attachments.size(); i += 1) {
  892. MDAttachment const &a = pass->attachments[i];
  893. id<MTLTexture> tex = rid::get(p_attachments[i]);
  894. if (tex == nil) {
  895. #if DEV_ENABLED
  896. WARN_PRINT("Invalid texture for attachment " + itos(i));
  897. #endif
  898. }
  899. if (a.samples > 1) {
  900. if (tex.sampleCount != a.samples) {
  901. #if DEV_ENABLED
  902. WARN_PRINT("Mismatched sample count for attachment " + itos(i) + "; expected " + itos(a.samples) + ", got " + itos(tex.sampleCount));
  903. #endif
  904. }
  905. }
  906. textures.write[i] = tex;
  907. }
  908. MDFrameBuffer *fb = new MDFrameBuffer(textures, Size2i(p_width, p_height));
  909. return FramebufferID(fb);
  910. }
  911. void RenderingDeviceDriverMetal::framebuffer_free(FramebufferID p_framebuffer) {
  912. MDFrameBuffer *obj = (MDFrameBuffer *)(p_framebuffer.id);
  913. delete obj;
  914. }
  915. #pragma mark - Shader
  916. void RenderingDeviceDriverMetal::shader_cache_free_entry(const SHA256Digest &key) {
  917. if (ShaderCacheEntry **pentry = _shader_cache.getptr(key); pentry != nullptr) {
  918. ShaderCacheEntry *entry = *pentry;
  919. _shader_cache.erase(key);
  920. entry->library = nil;
  921. memdelete(entry);
  922. }
  923. }
  924. API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0))
  925. static BindingInfo from_binding_info_data(const RenderingShaderContainerMetal::BindingInfoData &p_data) {
  926. BindingInfo bi;
  927. bi.dataType = static_cast<MTLDataType>(p_data.data_type);
  928. bi.index = p_data.index;
  929. bi.access = static_cast<MTLBindingAccess>(p_data.access);
  930. bi.usage = static_cast<MTLResourceUsage>(p_data.usage);
  931. bi.textureType = static_cast<MTLTextureType>(p_data.texture_type);
  932. bi.imageFormat = p_data.image_format;
  933. bi.arrayLength = p_data.array_length;
  934. bi.isMultisampled = p_data.is_multisampled;
  935. return bi;
  936. }
  937. RDD::ShaderID RenderingDeviceDriverMetal::shader_create_from_container(const Ref<RenderingShaderContainer> &p_shader_container, const Vector<ImmutableSampler> &p_immutable_samplers) {
  938. Ref<RenderingShaderContainerMetal> shader_container = p_shader_container;
  939. using RSCM = RenderingShaderContainerMetal;
  940. CharString shader_name = shader_container->shader_name;
  941. RSCM::HeaderData &mtl_reflection_data = shader_container->mtl_reflection_data;
  942. Vector<RenderingShaderContainer::Shader> &shaders = shader_container->shaders;
  943. Vector<RSCM::StageData> &mtl_shaders = shader_container->mtl_shaders;
  944. // We need to regenerate the shader if the cache is moved to an incompatible device.
  945. ERR_FAIL_COND_V_MSG(device_properties->features.argument_buffers_tier < MTLArgumentBuffersTier2 && mtl_reflection_data.uses_argument_buffers(),
  946. RDD::ShaderID(),
  947. "Shader was generated with argument buffers, but device has limited support");
  948. MTLCompileOptions *options = [MTLCompileOptions new];
  949. uint32_t major = mtl_reflection_data.msl_version / 10000;
  950. uint32_t minor = (mtl_reflection_data.msl_version / 100) % 100;
  951. options.languageVersion = MTLLanguageVersion((major << 0x10) + minor);
  952. HashMap<RD::ShaderStage, MDLibrary *> libraries;
  953. bool is_compute = false;
  954. Vector<uint8_t> decompressed_code;
  955. for (uint32_t shader_index = 0; shader_index < shaders.size(); shader_index++) {
  956. const RenderingShaderContainer::Shader &shader = shaders[shader_index];
  957. const RSCM::StageData &shader_data = mtl_shaders[shader_index];
  958. if (shader.shader_stage == RD::ShaderStage::SHADER_STAGE_COMPUTE) {
  959. is_compute = true;
  960. }
  961. if (ShaderCacheEntry **p = _shader_cache.getptr(shader_data.hash); p != nullptr) {
  962. libraries[shader.shader_stage] = (*p)->library;
  963. continue;
  964. }
  965. if (shader.code_decompressed_size > 0) {
  966. decompressed_code.resize(shader.code_decompressed_size);
  967. bool decompressed = shader_container->decompress_code(shader.code_compressed_bytes.ptr(), shader.code_compressed_bytes.size(), shader.code_compression_flags, decompressed_code.ptrw(), decompressed_code.size());
  968. ERR_FAIL_COND_V_MSG(!decompressed, RDD::ShaderID(), vformat("Failed to decompress code on shader stage %s.", String(RDD::SHADER_STAGE_NAMES[shader.shader_stage])));
  969. } else {
  970. decompressed_code = shader.code_compressed_bytes;
  971. }
  972. ShaderCacheEntry *cd = memnew(ShaderCacheEntry(*this, shader_data.hash));
  973. cd->name = shader_name;
  974. cd->stage = shader.shader_stage;
  975. NSString *source = [[NSString alloc] initWithBytes:(void *)decompressed_code.ptr()
  976. length:shader_data.source_size
  977. encoding:NSUTF8StringEncoding];
  978. MDLibrary *library = nil;
  979. if (shader_data.library_size > 0) {
  980. dispatch_data_t binary = dispatch_data_create(decompressed_code.ptr() + shader_data.source_size, shader_data.library_size, dispatch_get_main_queue(), DISPATCH_DATA_DESTRUCTOR_DEFAULT);
  981. library = [MDLibrary newLibraryWithCacheEntry:cd
  982. device:device
  983. #if DEV_ENABLED
  984. source:source
  985. #endif
  986. data:binary];
  987. } else {
  988. options.preserveInvariance = shader_data.is_position_invariant;
  989. #if defined(VISIONOS_ENABLED)
  990. options.mathMode = MTLMathModeFast;
  991. #else
  992. options.fastMathEnabled = YES;
  993. #endif
  994. library = [MDLibrary newLibraryWithCacheEntry:cd
  995. device:device
  996. source:source
  997. options:options
  998. strategy:_shader_load_strategy];
  999. }
  1000. _shader_cache[shader_data.hash] = cd;
  1001. libraries[shader.shader_stage] = library;
  1002. }
  1003. ShaderReflection refl = shader_container->get_shader_reflection();
  1004. RSCM::MetalShaderReflection mtl_refl = shader_container->get_metal_shader_reflection();
  1005. Vector<UniformSet> uniform_sets;
  1006. uint32_t uniform_sets_count = mtl_refl.uniform_sets.size();
  1007. uniform_sets.resize(uniform_sets_count);
  1008. // Create sets.
  1009. for (uint32_t i = 0; i < uniform_sets_count; i++) {
  1010. UniformSet &set = uniform_sets.write[i];
  1011. const Vector<ShaderUniform> &refl_set = refl.uniform_sets.ptr()[i];
  1012. const Vector<RSCM::UniformData> &mtl_set = mtl_refl.uniform_sets.ptr()[i];
  1013. uint32_t set_size = mtl_set.size();
  1014. set.uniforms.resize(set_size);
  1015. LocalVector<UniformInfo>::Iterator iter = set.uniforms.begin();
  1016. for (uint32_t j = 0; j < set_size; j++) {
  1017. const ShaderUniform &uniform = refl_set.ptr()[j];
  1018. const RSCM::UniformData &bind = mtl_set.ptr()[j];
  1019. UniformInfo &ui = *iter;
  1020. ++iter;
  1021. ui.binding = uniform.binding;
  1022. ui.active_stages = static_cast<ShaderStageUsage>(bind.active_stages);
  1023. for (const RSCM::BindingInfoData &info : bind.bindings) {
  1024. if (info.shader_stage == UINT32_MAX) {
  1025. continue;
  1026. }
  1027. BindingInfo bi = from_binding_info_data(info);
  1028. ui.bindings.insert((RDC::ShaderStage)info.shader_stage, bi);
  1029. }
  1030. for (const RSCM::BindingInfoData &info : bind.bindings_secondary) {
  1031. if (info.shader_stage == UINT32_MAX) {
  1032. continue;
  1033. }
  1034. BindingInfo bi = from_binding_info_data(info);
  1035. ui.bindings_secondary.insert((RDC::ShaderStage)info.shader_stage, bi);
  1036. }
  1037. }
  1038. }
  1039. for (uint32_t i = 0; i < uniform_sets_count; i++) {
  1040. UniformSet &set = uniform_sets.write[i];
  1041. // Make encoders.
  1042. for (RenderingShaderContainer::Shader const &shader : shaders) {
  1043. RD::ShaderStage stage = shader.shader_stage;
  1044. NSMutableArray<MTLArgumentDescriptor *> *descriptors = [NSMutableArray new];
  1045. for (UniformInfo const &uniform : set.uniforms) {
  1046. BindingInfo const *binding_info = uniform.bindings.getptr(stage);
  1047. if (binding_info == nullptr) {
  1048. continue;
  1049. }
  1050. [descriptors addObject:binding_info->new_argument_descriptor()];
  1051. BindingInfo const *secondary_binding_info = uniform.bindings_secondary.getptr(stage);
  1052. if (secondary_binding_info != nullptr) {
  1053. [descriptors addObject:secondary_binding_info->new_argument_descriptor()];
  1054. }
  1055. }
  1056. if (descriptors.count == 0) {
  1057. // No bindings.
  1058. continue;
  1059. }
  1060. // Sort by index.
  1061. [descriptors sortUsingComparator:^NSComparisonResult(MTLArgumentDescriptor *a, MTLArgumentDescriptor *b) {
  1062. if (a.index < b.index) {
  1063. return NSOrderedAscending;
  1064. } else if (a.index > b.index) {
  1065. return NSOrderedDescending;
  1066. } else {
  1067. return NSOrderedSame;
  1068. }
  1069. }];
  1070. id<MTLArgumentEncoder> enc = [device newArgumentEncoderWithArguments:descriptors];
  1071. set.encoders[stage] = enc;
  1072. set.offsets[stage] = set.buffer_size;
  1073. set.buffer_size += enc.encodedLength;
  1074. }
  1075. }
  1076. MDShader *shader = nullptr;
  1077. if (is_compute) {
  1078. const RSCM::StageData &stage_data = mtl_shaders[0];
  1079. MDComputeShader *cs = new MDComputeShader(
  1080. shader_name,
  1081. uniform_sets,
  1082. mtl_reflection_data.uses_argument_buffers(),
  1083. libraries[RD::ShaderStage::SHADER_STAGE_COMPUTE]);
  1084. if (stage_data.push_constant_binding != UINT32_MAX) {
  1085. cs->push_constants.size = refl.push_constant_size;
  1086. cs->push_constants.binding = stage_data.push_constant_binding;
  1087. }
  1088. cs->local = MTLSizeMake(refl.compute_local_size[0], refl.compute_local_size[1], refl.compute_local_size[2]);
  1089. shader = cs;
  1090. } else {
  1091. MDRenderShader *rs = new MDRenderShader(
  1092. shader_name,
  1093. uniform_sets,
  1094. mtl_reflection_data.needs_view_mask_buffer(),
  1095. mtl_reflection_data.uses_argument_buffers(),
  1096. libraries[RD::ShaderStage::SHADER_STAGE_VERTEX],
  1097. libraries[RD::ShaderStage::SHADER_STAGE_FRAGMENT]);
  1098. for (uint32_t j = 0; j < shaders.size(); j++) {
  1099. const RSCM::StageData &stage_data = mtl_shaders[j];
  1100. switch (shaders[j].shader_stage) {
  1101. case RD::ShaderStage::SHADER_STAGE_VERTEX: {
  1102. if (stage_data.push_constant_binding != UINT32_MAX) {
  1103. rs->push_constants.vert.size = refl.push_constant_size;
  1104. rs->push_constants.vert.binding = stage_data.push_constant_binding;
  1105. }
  1106. } break;
  1107. case RD::ShaderStage::SHADER_STAGE_FRAGMENT: {
  1108. if (stage_data.push_constant_binding != UINT32_MAX) {
  1109. rs->push_constants.frag.size = refl.push_constant_size;
  1110. rs->push_constants.frag.binding = stage_data.push_constant_binding;
  1111. }
  1112. } break;
  1113. default: {
  1114. ERR_FAIL_V_MSG(RDD::ShaderID(), "Invalid shader stage");
  1115. } break;
  1116. }
  1117. }
  1118. shader = rs;
  1119. }
  1120. return RDD::ShaderID(shader);
  1121. }
  1122. void RenderingDeviceDriverMetal::shader_free(ShaderID p_shader) {
  1123. MDShader *obj = (MDShader *)p_shader.id;
  1124. delete obj;
  1125. }
  1126. void RenderingDeviceDriverMetal::shader_destroy_modules(ShaderID p_shader) {
  1127. // TODO.
  1128. }
  1129. /*********************/
  1130. /**** UNIFORM SET ****/
  1131. /*********************/
  1132. RDD::UniformSetID RenderingDeviceDriverMetal::uniform_set_create(VectorView<BoundUniform> p_uniforms, ShaderID p_shader, uint32_t p_set_index, int p_linear_pool_index) {
  1133. //p_linear_pool_index = -1; // TODO:? Linear pools not implemented or not supported by API backend.
  1134. MDUniformSet *set = memnew(MDUniformSet);
  1135. Vector<BoundUniform> bound_uniforms;
  1136. bound_uniforms.resize(p_uniforms.size());
  1137. for (uint32_t i = 0; i < p_uniforms.size(); i += 1) {
  1138. bound_uniforms.write[i] = p_uniforms[i];
  1139. }
  1140. set->uniforms = bound_uniforms;
  1141. set->index = p_set_index;
  1142. return UniformSetID(set);
  1143. }
  1144. void RenderingDeviceDriverMetal::uniform_set_free(UniformSetID p_uniform_set) {
  1145. MDUniformSet *obj = (MDUniformSet *)p_uniform_set.id;
  1146. memdelete(obj);
  1147. }
  1148. void RenderingDeviceDriverMetal::command_uniform_set_prepare_for_use(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) {
  1149. }
  1150. #pragma mark - Transfer
  1151. void RenderingDeviceDriverMetal::command_clear_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, uint64_t p_offset, uint64_t p_size) {
  1152. MDCommandBuffer *cmd = (MDCommandBuffer *)(p_cmd_buffer.id);
  1153. id<MTLBuffer> buffer = rid::get(p_buffer);
  1154. id<MTLBlitCommandEncoder> blit = cmd->blit_command_encoder();
  1155. [blit fillBuffer:buffer
  1156. range:NSMakeRange(p_offset, p_size)
  1157. value:0];
  1158. }
  1159. void RenderingDeviceDriverMetal::command_copy_buffer(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, BufferID p_dst_buffer, VectorView<BufferCopyRegion> p_regions) {
  1160. MDCommandBuffer *cmd = (MDCommandBuffer *)(p_cmd_buffer.id);
  1161. id<MTLBuffer> src = rid::get(p_src_buffer);
  1162. id<MTLBuffer> dst = rid::get(p_dst_buffer);
  1163. id<MTLBlitCommandEncoder> blit = cmd->blit_command_encoder();
  1164. for (uint32_t i = 0; i < p_regions.size(); i++) {
  1165. BufferCopyRegion region = p_regions[i];
  1166. [blit copyFromBuffer:src
  1167. sourceOffset:region.src_offset
  1168. toBuffer:dst
  1169. destinationOffset:region.dst_offset
  1170. size:region.size];
  1171. }
  1172. }
  1173. MTLSize MTLSizeFromVector3i(Vector3i p_size) {
  1174. return MTLSizeMake(p_size.x, p_size.y, p_size.z);
  1175. }
  1176. MTLOrigin MTLOriginFromVector3i(Vector3i p_origin) {
  1177. return MTLOriginMake(p_origin.x, p_origin.y, p_origin.z);
  1178. }
  1179. // Clamps the size so that the sum of the origin and size do not exceed the maximum size.
  1180. static inline MTLSize clampMTLSize(MTLSize p_size, MTLOrigin p_origin, MTLSize p_max_size) {
  1181. MTLSize clamped;
  1182. clamped.width = MIN(p_size.width, p_max_size.width - p_origin.x);
  1183. clamped.height = MIN(p_size.height, p_max_size.height - p_origin.y);
  1184. clamped.depth = MIN(p_size.depth, p_max_size.depth - p_origin.z);
  1185. return clamped;
  1186. }
  1187. void RenderingDeviceDriverMetal::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) {
  1188. MDCommandBuffer *cmd = (MDCommandBuffer *)(p_cmd_buffer.id);
  1189. id<MTLTexture> src = rid::get(p_src_texture);
  1190. id<MTLTexture> dst = rid::get(p_dst_texture);
  1191. id<MTLBlitCommandEncoder> blit = cmd->blit_command_encoder();
  1192. PixelFormats &pf = *pixel_formats;
  1193. MTLPixelFormat src_fmt = src.pixelFormat;
  1194. bool src_is_compressed = pf.getFormatType(src_fmt) == MTLFormatType::Compressed;
  1195. MTLPixelFormat dst_fmt = dst.pixelFormat;
  1196. bool dst_is_compressed = pf.getFormatType(dst_fmt) == MTLFormatType::Compressed;
  1197. // Validate copy.
  1198. if (src.sampleCount != dst.sampleCount || pf.getBytesPerBlock(src_fmt) != pf.getBytesPerBlock(dst_fmt)) {
  1199. ERR_FAIL_MSG("Cannot copy between incompatible pixel formats, such as formats of different pixel sizes, or between images with different sample counts.");
  1200. }
  1201. // If source and destination have different formats and at least one is compressed, a temporary buffer is required.
  1202. bool need_tmp_buffer = (src_fmt != dst_fmt) && (src_is_compressed || dst_is_compressed);
  1203. if (need_tmp_buffer) {
  1204. ERR_FAIL_MSG("not implemented: copy with intermediate buffer");
  1205. }
  1206. if (src_fmt != dst_fmt) {
  1207. // Map the source pixel format to the dst through a texture view on the source texture.
  1208. src = [src newTextureViewWithPixelFormat:dst_fmt];
  1209. }
  1210. for (uint32_t i = 0; i < p_regions.size(); i++) {
  1211. TextureCopyRegion region = p_regions[i];
  1212. MTLSize extent = MTLSizeFromVector3i(region.size);
  1213. // If copies can be performed using direct texture-texture copying, do so.
  1214. uint32_t src_level = region.src_subresources.mipmap;
  1215. uint32_t src_base_layer = region.src_subresources.base_layer;
  1216. MTLSize src_extent = mipmapLevelSizeFromTexture(src, src_level);
  1217. uint32_t dst_level = region.dst_subresources.mipmap;
  1218. uint32_t dst_base_layer = region.dst_subresources.base_layer;
  1219. MTLSize dst_extent = mipmapLevelSizeFromTexture(dst, dst_level);
  1220. // All layers may be copied at once, if the extent completely covers both images.
  1221. if (src_extent == extent && dst_extent == extent) {
  1222. [blit copyFromTexture:src
  1223. sourceSlice:src_base_layer
  1224. sourceLevel:src_level
  1225. toTexture:dst
  1226. destinationSlice:dst_base_layer
  1227. destinationLevel:dst_level
  1228. sliceCount:region.src_subresources.layer_count
  1229. levelCount:1];
  1230. } else {
  1231. MTLOrigin src_origin = MTLOriginFromVector3i(region.src_offset);
  1232. MTLSize src_size = clampMTLSize(extent, src_origin, src_extent);
  1233. uint32_t layer_count = 0;
  1234. if ((src.textureType == MTLTextureType3D) != (dst.textureType == MTLTextureType3D)) {
  1235. // In the case, the number of layers to copy is in extent.depth. Use that value,
  1236. // then clamp the depth, so we don't try to copy more than Metal will allow.
  1237. layer_count = extent.depth;
  1238. src_size.depth = 1;
  1239. } else {
  1240. layer_count = region.src_subresources.layer_count;
  1241. }
  1242. MTLOrigin dst_origin = MTLOriginFromVector3i(region.dst_offset);
  1243. for (uint32_t layer = 0; layer < layer_count; layer++) {
  1244. // We can copy between a 3D and a 2D image easily. Just copy between
  1245. // one slice of the 2D image and one plane of the 3D image at a time.
  1246. if ((src.textureType == MTLTextureType3D) == (dst.textureType == MTLTextureType3D)) {
  1247. [blit copyFromTexture:src
  1248. sourceSlice:src_base_layer + layer
  1249. sourceLevel:src_level
  1250. sourceOrigin:src_origin
  1251. sourceSize:src_size
  1252. toTexture:dst
  1253. destinationSlice:dst_base_layer + layer
  1254. destinationLevel:dst_level
  1255. destinationOrigin:dst_origin];
  1256. } else if (src.textureType == MTLTextureType3D) {
  1257. [blit copyFromTexture:src
  1258. sourceSlice:src_base_layer
  1259. sourceLevel:src_level
  1260. sourceOrigin:MTLOriginMake(src_origin.x, src_origin.y, src_origin.z + layer)
  1261. sourceSize:src_size
  1262. toTexture:dst
  1263. destinationSlice:dst_base_layer + layer
  1264. destinationLevel:dst_level
  1265. destinationOrigin:dst_origin];
  1266. } else {
  1267. DEV_ASSERT(dst.textureType == MTLTextureType3D);
  1268. [blit copyFromTexture:src
  1269. sourceSlice:src_base_layer + layer
  1270. sourceLevel:src_level
  1271. sourceOrigin:src_origin
  1272. sourceSize:src_size
  1273. toTexture:dst
  1274. destinationSlice:dst_base_layer
  1275. destinationLevel:dst_level
  1276. destinationOrigin:MTLOriginMake(dst_origin.x, dst_origin.y, dst_origin.z + layer)];
  1277. }
  1278. }
  1279. }
  1280. }
  1281. }
  1282. void RenderingDeviceDriverMetal::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) {
  1283. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1284. id<MTLTexture> src_tex = rid::get(p_src_texture);
  1285. id<MTLTexture> dst_tex = rid::get(p_dst_texture);
  1286. MTLRenderPassDescriptor *mtlRPD = [MTLRenderPassDescriptor renderPassDescriptor];
  1287. MTLRenderPassColorAttachmentDescriptor *mtlColorAttDesc = mtlRPD.colorAttachments[0];
  1288. mtlColorAttDesc.loadAction = MTLLoadActionLoad;
  1289. mtlColorAttDesc.storeAction = MTLStoreActionMultisampleResolve;
  1290. mtlColorAttDesc.texture = src_tex;
  1291. mtlColorAttDesc.resolveTexture = dst_tex;
  1292. mtlColorAttDesc.level = p_src_mipmap;
  1293. mtlColorAttDesc.slice = p_src_layer;
  1294. mtlColorAttDesc.resolveLevel = p_dst_mipmap;
  1295. mtlColorAttDesc.resolveSlice = p_dst_layer;
  1296. cb->encodeRenderCommandEncoderWithDescriptor(mtlRPD, @"Resolve Image");
  1297. }
  1298. void RenderingDeviceDriverMetal::command_clear_color_texture(CommandBufferID p_cmd_buffer, TextureID p_texture, TextureLayout p_texture_layout, const Color &p_color, const TextureSubresourceRange &p_subresources) {
  1299. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1300. id<MTLTexture> src_tex = rid::get(p_texture);
  1301. if (src_tex.parentTexture) {
  1302. // Clear via the parent texture rather than the view.
  1303. src_tex = src_tex.parentTexture;
  1304. }
  1305. PixelFormats &pf = *pixel_formats;
  1306. if (pf.isDepthFormat(src_tex.pixelFormat) || pf.isStencilFormat(src_tex.pixelFormat)) {
  1307. ERR_FAIL_MSG("invalid: depth or stencil texture format");
  1308. }
  1309. MTLRenderPassDescriptor *desc = MTLRenderPassDescriptor.renderPassDescriptor;
  1310. if (p_subresources.aspect.has_flag(TEXTURE_ASPECT_COLOR_BIT)) {
  1311. MTLRenderPassColorAttachmentDescriptor *caDesc = desc.colorAttachments[0];
  1312. caDesc.texture = src_tex;
  1313. caDesc.loadAction = MTLLoadActionClear;
  1314. caDesc.storeAction = MTLStoreActionStore;
  1315. caDesc.clearColor = MTLClearColorMake(p_color.r, p_color.g, p_color.b, p_color.a);
  1316. // Extract the mipmap levels that are to be updated.
  1317. uint32_t mipLvlStart = p_subresources.base_mipmap;
  1318. uint32_t mipLvlCnt = p_subresources.mipmap_count;
  1319. uint32_t mipLvlEnd = mipLvlStart + mipLvlCnt;
  1320. uint32_t levelCount = src_tex.mipmapLevelCount;
  1321. // Extract the cube or array layers (slices) that are to be updated.
  1322. bool is3D = src_tex.textureType == MTLTextureType3D;
  1323. uint32_t layerStart = is3D ? 0 : p_subresources.base_layer;
  1324. uint32_t layerCnt = p_subresources.layer_count;
  1325. uint32_t layerEnd = layerStart + layerCnt;
  1326. MetalFeatures const &features = (*device_properties).features;
  1327. // Iterate across mipmap levels and layers, and perform and empty render to clear each.
  1328. for (uint32_t mipLvl = mipLvlStart; mipLvl < mipLvlEnd; mipLvl++) {
  1329. ERR_FAIL_INDEX_MSG(mipLvl, levelCount, "mip level out of range");
  1330. caDesc.level = mipLvl;
  1331. // If a 3D image, we need to get the depth for each level.
  1332. if (is3D) {
  1333. layerCnt = mipmapLevelSizeFromTexture(src_tex, mipLvl).depth;
  1334. layerEnd = layerStart + layerCnt;
  1335. }
  1336. if ((features.layeredRendering && src_tex.sampleCount == 1) || features.multisampleLayeredRendering) {
  1337. // We can clear all layers at once.
  1338. if (is3D) {
  1339. caDesc.depthPlane = layerStart;
  1340. } else {
  1341. caDesc.slice = layerStart;
  1342. }
  1343. desc.renderTargetArrayLength = layerCnt;
  1344. cb->encodeRenderCommandEncoderWithDescriptor(desc, @"Clear Image");
  1345. } else {
  1346. for (uint32_t layer = layerStart; layer < layerEnd; layer++) {
  1347. if (is3D) {
  1348. caDesc.depthPlane = layer;
  1349. } else {
  1350. caDesc.slice = layer;
  1351. }
  1352. cb->encodeRenderCommandEncoderWithDescriptor(desc, @"Clear Image");
  1353. }
  1354. }
  1355. }
  1356. }
  1357. }
  1358. API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0))
  1359. bool isArrayTexture(MTLTextureType p_type) {
  1360. return (p_type == MTLTextureType3D ||
  1361. p_type == MTLTextureType2DArray ||
  1362. p_type == MTLTextureType2DMultisampleArray ||
  1363. p_type == MTLTextureType1DArray);
  1364. }
  1365. void RenderingDeviceDriverMetal::_copy_texture_buffer(CommandBufferID p_cmd_buffer,
  1366. CopySource p_source,
  1367. TextureID p_texture,
  1368. BufferID p_buffer,
  1369. VectorView<BufferTextureCopyRegion> p_regions) {
  1370. MDCommandBuffer *cmd = (MDCommandBuffer *)(p_cmd_buffer.id);
  1371. id<MTLBuffer> buffer = rid::get(p_buffer);
  1372. id<MTLTexture> texture = rid::get(p_texture);
  1373. id<MTLBlitCommandEncoder> enc = cmd->blit_command_encoder();
  1374. PixelFormats &pf = *pixel_formats;
  1375. MTLPixelFormat mtlPixFmt = texture.pixelFormat;
  1376. MTLBlitOption options = MTLBlitOptionNone;
  1377. if (pf.isPVRTCFormat(mtlPixFmt)) {
  1378. options |= MTLBlitOptionRowLinearPVRTC;
  1379. }
  1380. for (uint32_t i = 0; i < p_regions.size(); i++) {
  1381. BufferTextureCopyRegion region = p_regions[i];
  1382. uint32_t mip_level = region.texture_subresources.mipmap;
  1383. MTLOrigin txt_origin = MTLOriginMake(region.texture_offset.x, region.texture_offset.y, region.texture_offset.z);
  1384. MTLSize src_extent = mipmapLevelSizeFromTexture(texture, mip_level);
  1385. MTLSize txt_size = clampMTLSize(MTLSizeMake(region.texture_region_size.x, region.texture_region_size.y, region.texture_region_size.z),
  1386. txt_origin,
  1387. src_extent);
  1388. uint32_t buffImgWd = region.texture_region_size.x;
  1389. uint32_t buffImgHt = region.texture_region_size.y;
  1390. NSUInteger bytesPerRow = pf.getBytesPerRow(mtlPixFmt, buffImgWd);
  1391. NSUInteger bytesPerImg = pf.getBytesPerLayer(mtlPixFmt, bytesPerRow, buffImgHt);
  1392. MTLBlitOption blit_options = options;
  1393. if (pf.isDepthFormat(mtlPixFmt) && pf.isStencilFormat(mtlPixFmt)) {
  1394. bool want_depth = flags::all(region.texture_subresources.aspect, TEXTURE_ASPECT_DEPTH_BIT);
  1395. bool want_stencil = flags::all(region.texture_subresources.aspect, TEXTURE_ASPECT_STENCIL_BIT);
  1396. // The stencil component is always 1 byte per pixel.
  1397. // Don't reduce depths of 32-bit depth/stencil formats.
  1398. if (want_depth && !want_stencil) {
  1399. if (pf.getBytesPerTexel(mtlPixFmt) != 4) {
  1400. bytesPerRow -= buffImgWd;
  1401. bytesPerImg -= buffImgWd * buffImgHt;
  1402. }
  1403. blit_options |= MTLBlitOptionDepthFromDepthStencil;
  1404. } else if (want_stencil && !want_depth) {
  1405. bytesPerRow = buffImgWd;
  1406. bytesPerImg = buffImgWd * buffImgHt;
  1407. blit_options |= MTLBlitOptionStencilFromDepthStencil;
  1408. }
  1409. }
  1410. if (!isArrayTexture(texture.textureType)) {
  1411. bytesPerImg = 0;
  1412. }
  1413. if (p_source == CopySource::Buffer) {
  1414. for (uint32_t lyrIdx = 0; lyrIdx < region.texture_subresources.layer_count; lyrIdx++) {
  1415. [enc copyFromBuffer:buffer
  1416. sourceOffset:region.buffer_offset + (bytesPerImg * lyrIdx)
  1417. sourceBytesPerRow:bytesPerRow
  1418. sourceBytesPerImage:bytesPerImg
  1419. sourceSize:txt_size
  1420. toTexture:texture
  1421. destinationSlice:region.texture_subresources.base_layer + lyrIdx
  1422. destinationLevel:mip_level
  1423. destinationOrigin:txt_origin
  1424. options:blit_options];
  1425. }
  1426. } else {
  1427. for (uint32_t lyrIdx = 0; lyrIdx < region.texture_subresources.layer_count; lyrIdx++) {
  1428. [enc copyFromTexture:texture
  1429. sourceSlice:region.texture_subresources.base_layer + lyrIdx
  1430. sourceLevel:mip_level
  1431. sourceOrigin:txt_origin
  1432. sourceSize:txt_size
  1433. toBuffer:buffer
  1434. destinationOffset:region.buffer_offset + (bytesPerImg * lyrIdx)
  1435. destinationBytesPerRow:bytesPerRow
  1436. destinationBytesPerImage:bytesPerImg
  1437. options:blit_options];
  1438. }
  1439. }
  1440. }
  1441. }
  1442. void RenderingDeviceDriverMetal::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) {
  1443. _copy_texture_buffer(p_cmd_buffer, CopySource::Buffer, p_dst_texture, p_src_buffer, p_regions);
  1444. }
  1445. void RenderingDeviceDriverMetal::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) {
  1446. _copy_texture_buffer(p_cmd_buffer, CopySource::Texture, p_src_texture, p_dst_buffer, p_regions);
  1447. }
  1448. #pragma mark - Pipeline
  1449. void RenderingDeviceDriverMetal::pipeline_free(PipelineID p_pipeline_id) {
  1450. MDPipeline *obj = (MDPipeline *)(p_pipeline_id.id);
  1451. delete obj;
  1452. }
  1453. // ----- BINDING -----
  1454. void RenderingDeviceDriverMetal::command_bind_push_constants(CommandBufferID p_cmd_buffer, ShaderID p_shader, uint32_t p_dst_first_index, VectorView<uint32_t> p_data) {
  1455. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1456. cb->encode_push_constant_data(p_shader, p_data);
  1457. }
  1458. // ----- CACHE -----
  1459. String RenderingDeviceDriverMetal::_pipeline_get_cache_path() const {
  1460. String path = OS::get_singleton()->get_user_data_dir() + "/metal/pipelines";
  1461. path += "." + context_device.name.validate_filename().replace_char(' ', '_').to_lower();
  1462. if (Engine::get_singleton()->is_editor_hint()) {
  1463. path += ".editor";
  1464. }
  1465. path += ".cache";
  1466. return path;
  1467. }
  1468. bool RenderingDeviceDriverMetal::pipeline_cache_create(const Vector<uint8_t> &p_data) {
  1469. return false;
  1470. CharString path = _pipeline_get_cache_path().utf8();
  1471. NSString *nPath = [[NSString alloc] initWithBytesNoCopy:path.ptrw()
  1472. length:path.length()
  1473. encoding:NSUTF8StringEncoding
  1474. freeWhenDone:NO];
  1475. MTLBinaryArchiveDescriptor *desc = [MTLBinaryArchiveDescriptor new];
  1476. if ([[NSFileManager defaultManager] fileExistsAtPath:nPath]) {
  1477. desc.url = [NSURL fileURLWithPath:nPath];
  1478. }
  1479. NSError *error = nil;
  1480. archive = [device newBinaryArchiveWithDescriptor:desc error:&error];
  1481. return true;
  1482. }
  1483. void RenderingDeviceDriverMetal::pipeline_cache_free() {
  1484. archive = nil;
  1485. }
  1486. size_t RenderingDeviceDriverMetal::pipeline_cache_query_size() {
  1487. return archive_count * 1024;
  1488. }
  1489. Vector<uint8_t> RenderingDeviceDriverMetal::pipeline_cache_serialize() {
  1490. if (!archive) {
  1491. return Vector<uint8_t>();
  1492. }
  1493. CharString path = _pipeline_get_cache_path().utf8();
  1494. NSString *nPath = [[NSString alloc] initWithBytesNoCopy:path.ptrw()
  1495. length:path.length()
  1496. encoding:NSUTF8StringEncoding
  1497. freeWhenDone:NO];
  1498. NSURL *target = [NSURL fileURLWithPath:nPath];
  1499. NSError *error = nil;
  1500. if ([archive serializeToURL:target error:&error]) {
  1501. return Vector<uint8_t>();
  1502. } else {
  1503. print_line(error.localizedDescription.UTF8String);
  1504. return Vector<uint8_t>();
  1505. }
  1506. }
  1507. #pragma mark - Rendering
  1508. // ----- SUBPASS -----
  1509. RDD::RenderPassID RenderingDeviceDriverMetal::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) {
  1510. PixelFormats &pf = *pixel_formats;
  1511. size_t subpass_count = p_subpasses.size();
  1512. Vector<MDSubpass> subpasses;
  1513. subpasses.resize(subpass_count);
  1514. for (uint32_t i = 0; i < subpass_count; i++) {
  1515. MDSubpass &subpass = subpasses.write[i];
  1516. subpass.subpass_index = i;
  1517. subpass.view_count = p_view_count;
  1518. subpass.input_references = p_subpasses[i].input_references;
  1519. subpass.color_references = p_subpasses[i].color_references;
  1520. subpass.depth_stencil_reference = p_subpasses[i].depth_stencil_reference;
  1521. subpass.resolve_references = p_subpasses[i].resolve_references;
  1522. }
  1523. static const MTLLoadAction LOAD_ACTIONS[] = {
  1524. [ATTACHMENT_LOAD_OP_LOAD] = MTLLoadActionLoad,
  1525. [ATTACHMENT_LOAD_OP_CLEAR] = MTLLoadActionClear,
  1526. [ATTACHMENT_LOAD_OP_DONT_CARE] = MTLLoadActionDontCare,
  1527. };
  1528. static const MTLStoreAction STORE_ACTIONS[] = {
  1529. [ATTACHMENT_STORE_OP_STORE] = MTLStoreActionStore,
  1530. [ATTACHMENT_STORE_OP_DONT_CARE] = MTLStoreActionDontCare,
  1531. };
  1532. Vector<MDAttachment> attachments;
  1533. attachments.resize(p_attachments.size());
  1534. for (uint32_t i = 0; i < p_attachments.size(); i++) {
  1535. Attachment const &a = p_attachments[i];
  1536. MDAttachment &mda = attachments.write[i];
  1537. MTLPixelFormat format = pf.getMTLPixelFormat(a.format);
  1538. mda.format = format;
  1539. if (a.samples > TEXTURE_SAMPLES_1) {
  1540. mda.samples = (*device_properties).find_nearest_supported_sample_count(a.samples);
  1541. }
  1542. mda.loadAction = LOAD_ACTIONS[a.load_op];
  1543. mda.storeAction = STORE_ACTIONS[a.store_op];
  1544. bool is_depth = pf.isDepthFormat(format);
  1545. if (is_depth) {
  1546. mda.type |= MDAttachmentType::Depth;
  1547. }
  1548. bool is_stencil = pf.isStencilFormat(format);
  1549. if (is_stencil) {
  1550. mda.type |= MDAttachmentType::Stencil;
  1551. mda.stencilLoadAction = LOAD_ACTIONS[a.stencil_load_op];
  1552. mda.stencilStoreAction = STORE_ACTIONS[a.stencil_store_op];
  1553. }
  1554. if (!is_depth && !is_stencil) {
  1555. mda.type |= MDAttachmentType::Color;
  1556. }
  1557. }
  1558. MDRenderPass *obj = new MDRenderPass(attachments, subpasses);
  1559. return RenderPassID(obj);
  1560. }
  1561. void RenderingDeviceDriverMetal::render_pass_free(RenderPassID p_render_pass) {
  1562. MDRenderPass *obj = (MDRenderPass *)(p_render_pass.id);
  1563. delete obj;
  1564. }
  1565. // ----- COMMANDS -----
  1566. void RenderingDeviceDriverMetal::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) {
  1567. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1568. cb->render_begin_pass(p_render_pass, p_framebuffer, p_cmd_buffer_type, p_rect, p_clear_values);
  1569. }
  1570. void RenderingDeviceDriverMetal::command_end_render_pass(CommandBufferID p_cmd_buffer) {
  1571. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1572. cb->render_end_pass();
  1573. }
  1574. void RenderingDeviceDriverMetal::command_next_render_subpass(CommandBufferID p_cmd_buffer, CommandBufferType p_cmd_buffer_type) {
  1575. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1576. cb->render_next_subpass();
  1577. }
  1578. void RenderingDeviceDriverMetal::command_render_set_viewport(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_viewports) {
  1579. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1580. cb->render_set_viewport(p_viewports);
  1581. }
  1582. void RenderingDeviceDriverMetal::command_render_set_scissor(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_scissors) {
  1583. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1584. cb->render_set_scissor(p_scissors);
  1585. }
  1586. void RenderingDeviceDriverMetal::command_render_clear_attachments(CommandBufferID p_cmd_buffer, VectorView<AttachmentClear> p_attachment_clears, VectorView<Rect2i> p_rects) {
  1587. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1588. cb->render_clear_attachments(p_attachment_clears, p_rects);
  1589. }
  1590. void RenderingDeviceDriverMetal::command_bind_render_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) {
  1591. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1592. cb->bind_pipeline(p_pipeline);
  1593. }
  1594. void RenderingDeviceDriverMetal::command_bind_render_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) {
  1595. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1596. cb->render_bind_uniform_set(p_uniform_set, p_shader, p_set_index);
  1597. }
  1598. void RenderingDeviceDriverMetal::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) {
  1599. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1600. cb->render_bind_uniform_sets(p_uniform_sets, p_shader, p_first_set_index, p_set_count);
  1601. }
  1602. void RenderingDeviceDriverMetal::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) {
  1603. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1604. cb->render_draw(p_vertex_count, p_instance_count, p_base_vertex, p_first_instance);
  1605. }
  1606. void RenderingDeviceDriverMetal::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) {
  1607. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1608. cb->render_draw_indexed(p_index_count, p_instance_count, p_first_index, p_vertex_offset, p_first_instance);
  1609. }
  1610. void RenderingDeviceDriverMetal::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) {
  1611. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1612. cb->render_draw_indexed_indirect(p_indirect_buffer, p_offset, p_draw_count, p_stride);
  1613. }
  1614. void RenderingDeviceDriverMetal::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) {
  1615. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1616. cb->render_draw_indexed_indirect_count(p_indirect_buffer, p_offset, p_count_buffer, p_count_buffer_offset, p_max_draw_count, p_stride);
  1617. }
  1618. void RenderingDeviceDriverMetal::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) {
  1619. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1620. cb->render_draw_indirect(p_indirect_buffer, p_offset, p_draw_count, p_stride);
  1621. }
  1622. void RenderingDeviceDriverMetal::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) {
  1623. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1624. cb->render_draw_indirect_count(p_indirect_buffer, p_offset, p_count_buffer, p_count_buffer_offset, p_max_draw_count, p_stride);
  1625. }
  1626. void RenderingDeviceDriverMetal::command_render_bind_vertex_buffers(CommandBufferID p_cmd_buffer, uint32_t p_binding_count, const BufferID *p_buffers, const uint64_t *p_offsets) {
  1627. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1628. cb->render_bind_vertex_buffers(p_binding_count, p_buffers, p_offsets);
  1629. }
  1630. void RenderingDeviceDriverMetal::command_render_bind_index_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, IndexBufferFormat p_format, uint64_t p_offset) {
  1631. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1632. cb->render_bind_index_buffer(p_buffer, p_format, p_offset);
  1633. }
  1634. void RenderingDeviceDriverMetal::command_render_set_blend_constants(CommandBufferID p_cmd_buffer, const Color &p_constants) {
  1635. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  1636. cb->render_set_blend_constants(p_constants);
  1637. }
  1638. void RenderingDeviceDriverMetal::command_render_set_line_width(CommandBufferID p_cmd_buffer, float p_width) {
  1639. if (!Math::is_equal_approx(p_width, 1.0f)) {
  1640. ERR_FAIL_MSG("Setting line widths other than 1.0 is not supported by the Metal rendering driver.");
  1641. }
  1642. }
  1643. // ----- PIPELINE -----
  1644. RenderingDeviceDriverMetal::Result<id<MTLFunction>> RenderingDeviceDriverMetal::_create_function(MDLibrary *p_library, NSString *p_name, VectorView<PipelineSpecializationConstant> &p_specialization_constants) {
  1645. id<MTLLibrary> library = p_library.library;
  1646. if (!library) {
  1647. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Failed to compile Metal library");
  1648. }
  1649. id<MTLFunction> function = [library newFunctionWithName:p_name];
  1650. ERR_FAIL_NULL_V_MSG(function, ERR_CANT_CREATE, "No function named main0");
  1651. if (function.functionConstantsDictionary.count == 0) {
  1652. return function;
  1653. }
  1654. NSArray<MTLFunctionConstant *> *constants = function.functionConstantsDictionary.allValues;
  1655. bool is_sorted = true;
  1656. for (uint32_t i = 1; i < constants.count; i++) {
  1657. if (constants[i - 1].index > constants[i].index) {
  1658. is_sorted = false;
  1659. break;
  1660. }
  1661. }
  1662. if (!is_sorted) {
  1663. constants = [constants sortedArrayUsingComparator:^NSComparisonResult(MTLFunctionConstant *a, MTLFunctionConstant *b) {
  1664. if (a.index < b.index) {
  1665. return NSOrderedAscending;
  1666. } else if (a.index > b.index) {
  1667. return NSOrderedDescending;
  1668. } else {
  1669. return NSOrderedSame;
  1670. }
  1671. }];
  1672. }
  1673. // Initialize an array of integers representing the indexes of p_specialization_constants
  1674. uint32_t *indexes = (uint32_t *)alloca(p_specialization_constants.size() * sizeof(uint32_t));
  1675. for (uint32_t i = 0; i < p_specialization_constants.size(); i++) {
  1676. indexes[i] = i;
  1677. }
  1678. // Sort the array of integers based on the values in p_specialization_constants
  1679. std::sort(indexes, &indexes[p_specialization_constants.size()], [&](int a, int b) {
  1680. return p_specialization_constants[a].constant_id < p_specialization_constants[b].constant_id;
  1681. });
  1682. MTLFunctionConstantValues *constantValues = [MTLFunctionConstantValues new];
  1683. uint32_t i = 0;
  1684. uint32_t j = 0;
  1685. while (i < constants.count && j < p_specialization_constants.size()) {
  1686. MTLFunctionConstant *curr = constants[i];
  1687. PipelineSpecializationConstant const &sc = p_specialization_constants[indexes[j]];
  1688. if (curr.index == sc.constant_id) {
  1689. switch (curr.type) {
  1690. case MTLDataTypeBool:
  1691. case MTLDataTypeFloat:
  1692. case MTLDataTypeInt:
  1693. case MTLDataTypeUInt: {
  1694. [constantValues setConstantValue:&sc.int_value
  1695. type:curr.type
  1696. atIndex:sc.constant_id];
  1697. } break;
  1698. default:
  1699. ERR_FAIL_V_MSG(function, "Invalid specialization constant type");
  1700. }
  1701. i++;
  1702. j++;
  1703. } else if (curr.index < sc.constant_id) {
  1704. i++;
  1705. } else {
  1706. j++;
  1707. }
  1708. }
  1709. if (i != constants.count) {
  1710. MTLFunctionConstant *curr = constants[i];
  1711. if (curr.index == R32UI_ALIGNMENT_CONSTANT_ID) {
  1712. uint32_t alignment = 16; // TODO(sgc): is this always correct?
  1713. [constantValues setConstantValue:&alignment
  1714. type:curr.type
  1715. atIndex:curr.index];
  1716. i++;
  1717. }
  1718. }
  1719. NSError *err = nil;
  1720. function = [library newFunctionWithName:@"main0"
  1721. constantValues:constantValues
  1722. error:&err];
  1723. ERR_FAIL_NULL_V_MSG(function, ERR_CANT_CREATE, String("specialized function failed: ") + err.localizedDescription.UTF8String);
  1724. return function;
  1725. }
  1726. // RDD::PolygonCullMode == MTLCullMode.
  1727. static_assert(ENUM_MEMBERS_EQUAL(RDD::POLYGON_CULL_DISABLED, MTLCullModeNone));
  1728. static_assert(ENUM_MEMBERS_EQUAL(RDD::POLYGON_CULL_FRONT, MTLCullModeFront));
  1729. static_assert(ENUM_MEMBERS_EQUAL(RDD::POLYGON_CULL_BACK, MTLCullModeBack));
  1730. // RDD::StencilOperation == MTLStencilOperation.
  1731. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_KEEP, MTLStencilOperationKeep));
  1732. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_ZERO, MTLStencilOperationZero));
  1733. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_REPLACE, MTLStencilOperationReplace));
  1734. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_INCREMENT_AND_CLAMP, MTLStencilOperationIncrementClamp));
  1735. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_DECREMENT_AND_CLAMP, MTLStencilOperationDecrementClamp));
  1736. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_INVERT, MTLStencilOperationInvert));
  1737. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_INCREMENT_AND_WRAP, MTLStencilOperationIncrementWrap));
  1738. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_DECREMENT_AND_WRAP, MTLStencilOperationDecrementWrap));
  1739. // RDD::BlendOperation == MTLBlendOperation.
  1740. static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_ADD, MTLBlendOperationAdd));
  1741. static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_SUBTRACT, MTLBlendOperationSubtract));
  1742. static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_REVERSE_SUBTRACT, MTLBlendOperationReverseSubtract));
  1743. static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_MINIMUM, MTLBlendOperationMin));
  1744. static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_MAXIMUM, MTLBlendOperationMax));
  1745. RDD::PipelineID RenderingDeviceDriverMetal::render_pipeline_create(
  1746. ShaderID p_shader,
  1747. VertexFormatID p_vertex_format,
  1748. RenderPrimitive p_render_primitive,
  1749. PipelineRasterizationState p_rasterization_state,
  1750. PipelineMultisampleState p_multisample_state,
  1751. PipelineDepthStencilState p_depth_stencil_state,
  1752. PipelineColorBlendState p_blend_state,
  1753. VectorView<int32_t> p_color_attachments,
  1754. BitField<PipelineDynamicStateFlags> p_dynamic_state,
  1755. RenderPassID p_render_pass,
  1756. uint32_t p_render_subpass,
  1757. VectorView<PipelineSpecializationConstant> p_specialization_constants) {
  1758. MDRenderShader *shader = (MDRenderShader *)(p_shader.id);
  1759. MTLVertexDescriptor *vert_desc = rid::get(p_vertex_format);
  1760. MDRenderPass *pass = (MDRenderPass *)(p_render_pass.id);
  1761. os_signpost_id_t reflect_id = os_signpost_id_make_with_pointer(LOG_INTERVALS, shader);
  1762. os_signpost_interval_begin(LOG_INTERVALS, reflect_id, "render_pipeline_create", "shader_name=%{public}s", shader->name.get_data());
  1763. DEFER([=]() {
  1764. os_signpost_interval_end(LOG_INTERVALS, reflect_id, "render_pipeline_create");
  1765. });
  1766. os_signpost_event_emit(LOG_DRIVER, OS_SIGNPOST_ID_EXCLUSIVE, "create_pipeline");
  1767. MTLRenderPipelineDescriptor *desc = [MTLRenderPipelineDescriptor new];
  1768. {
  1769. MDSubpass const &subpass = pass->subpasses[p_render_subpass];
  1770. for (uint32_t i = 0; i < subpass.color_references.size(); i++) {
  1771. uint32_t attachment = subpass.color_references[i].attachment;
  1772. if (attachment != AttachmentReference::UNUSED) {
  1773. MDAttachment const &a = pass->attachments[attachment];
  1774. desc.colorAttachments[i].pixelFormat = a.format;
  1775. }
  1776. }
  1777. if (subpass.depth_stencil_reference.attachment != AttachmentReference::UNUSED) {
  1778. uint32_t attachment = subpass.depth_stencil_reference.attachment;
  1779. MDAttachment const &a = pass->attachments[attachment];
  1780. if (a.type & MDAttachmentType::Depth) {
  1781. desc.depthAttachmentPixelFormat = a.format;
  1782. }
  1783. if (a.type & MDAttachmentType::Stencil) {
  1784. desc.stencilAttachmentPixelFormat = a.format;
  1785. }
  1786. }
  1787. }
  1788. desc.vertexDescriptor = vert_desc;
  1789. desc.label = [NSString stringWithUTF8String:shader->name.get_data()];
  1790. // Input assembly & tessellation.
  1791. MDRenderPipeline *pipeline = new MDRenderPipeline();
  1792. switch (p_render_primitive) {
  1793. case RENDER_PRIMITIVE_POINTS:
  1794. desc.inputPrimitiveTopology = MTLPrimitiveTopologyClassPoint;
  1795. break;
  1796. case RENDER_PRIMITIVE_LINES:
  1797. case RENDER_PRIMITIVE_LINES_WITH_ADJACENCY:
  1798. case RENDER_PRIMITIVE_LINESTRIPS_WITH_ADJACENCY:
  1799. case RENDER_PRIMITIVE_LINESTRIPS:
  1800. desc.inputPrimitiveTopology = MTLPrimitiveTopologyClassLine;
  1801. break;
  1802. case RENDER_PRIMITIVE_TRIANGLES:
  1803. case RENDER_PRIMITIVE_TRIANGLE_STRIPS:
  1804. case RENDER_PRIMITIVE_TRIANGLES_WITH_ADJACENCY:
  1805. case RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_AJACENCY:
  1806. case RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX:
  1807. desc.inputPrimitiveTopology = MTLPrimitiveTopologyClassTriangle;
  1808. break;
  1809. case RENDER_PRIMITIVE_TESSELATION_PATCH:
  1810. desc.maxTessellationFactor = p_rasterization_state.patch_control_points;
  1811. desc.tessellationPartitionMode = MTLTessellationPartitionModeInteger;
  1812. ERR_FAIL_V_MSG(PipelineID(), "tessellation not implemented");
  1813. break;
  1814. case RENDER_PRIMITIVE_MAX:
  1815. default:
  1816. desc.inputPrimitiveTopology = MTLPrimitiveTopologyClassUnspecified;
  1817. break;
  1818. }
  1819. switch (p_render_primitive) {
  1820. case RENDER_PRIMITIVE_POINTS:
  1821. pipeline->raster_state.render_primitive = MTLPrimitiveTypePoint;
  1822. break;
  1823. case RENDER_PRIMITIVE_LINES:
  1824. case RENDER_PRIMITIVE_LINES_WITH_ADJACENCY:
  1825. pipeline->raster_state.render_primitive = MTLPrimitiveTypeLine;
  1826. break;
  1827. case RENDER_PRIMITIVE_LINESTRIPS:
  1828. case RENDER_PRIMITIVE_LINESTRIPS_WITH_ADJACENCY:
  1829. pipeline->raster_state.render_primitive = MTLPrimitiveTypeLineStrip;
  1830. break;
  1831. case RENDER_PRIMITIVE_TRIANGLES:
  1832. case RENDER_PRIMITIVE_TRIANGLES_WITH_ADJACENCY:
  1833. pipeline->raster_state.render_primitive = MTLPrimitiveTypeTriangle;
  1834. break;
  1835. case RENDER_PRIMITIVE_TRIANGLE_STRIPS:
  1836. case RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_AJACENCY:
  1837. case RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX:
  1838. pipeline->raster_state.render_primitive = MTLPrimitiveTypeTriangleStrip;
  1839. break;
  1840. default:
  1841. break;
  1842. }
  1843. // Rasterization.
  1844. desc.rasterizationEnabled = !p_rasterization_state.discard_primitives;
  1845. pipeline->raster_state.clip_mode = p_rasterization_state.enable_depth_clamp ? MTLDepthClipModeClamp : MTLDepthClipModeClip;
  1846. pipeline->raster_state.fill_mode = p_rasterization_state.wireframe ? MTLTriangleFillModeLines : MTLTriangleFillModeFill;
  1847. static const MTLCullMode CULL_MODE[3] = {
  1848. MTLCullModeNone,
  1849. MTLCullModeFront,
  1850. MTLCullModeBack,
  1851. };
  1852. pipeline->raster_state.cull_mode = CULL_MODE[p_rasterization_state.cull_mode];
  1853. pipeline->raster_state.winding = (p_rasterization_state.front_face == POLYGON_FRONT_FACE_CLOCKWISE) ? MTLWindingClockwise : MTLWindingCounterClockwise;
  1854. pipeline->raster_state.depth_bias.enabled = p_rasterization_state.depth_bias_enabled;
  1855. pipeline->raster_state.depth_bias.depth_bias = p_rasterization_state.depth_bias_constant_factor;
  1856. pipeline->raster_state.depth_bias.slope_scale = p_rasterization_state.depth_bias_slope_factor;
  1857. pipeline->raster_state.depth_bias.clamp = p_rasterization_state.depth_bias_clamp;
  1858. // In Metal there is no line width.
  1859. if (!Math::is_equal_approx(p_rasterization_state.line_width, 1.0f)) {
  1860. WARN_PRINT("unsupported: line width");
  1861. }
  1862. // Multisample.
  1863. if (p_multisample_state.enable_sample_shading) {
  1864. WARN_PRINT("unsupported: multi-sample shading");
  1865. }
  1866. if (p_multisample_state.sample_count > TEXTURE_SAMPLES_1) {
  1867. pipeline->sample_count = (*device_properties).find_nearest_supported_sample_count(p_multisample_state.sample_count);
  1868. }
  1869. desc.rasterSampleCount = static_cast<NSUInteger>(pipeline->sample_count);
  1870. desc.alphaToCoverageEnabled = p_multisample_state.enable_alpha_to_coverage;
  1871. desc.alphaToOneEnabled = p_multisample_state.enable_alpha_to_one;
  1872. // Depth buffer.
  1873. bool depth_enabled = p_depth_stencil_state.enable_depth_test && desc.depthAttachmentPixelFormat != MTLPixelFormatInvalid;
  1874. bool stencil_enabled = p_depth_stencil_state.enable_stencil && desc.stencilAttachmentPixelFormat != MTLPixelFormatInvalid;
  1875. if (depth_enabled || stencil_enabled) {
  1876. MTLDepthStencilDescriptor *ds_desc = [MTLDepthStencilDescriptor new];
  1877. pipeline->raster_state.depth_test.enabled = depth_enabled;
  1878. ds_desc.depthWriteEnabled = p_depth_stencil_state.enable_depth_write;
  1879. ds_desc.depthCompareFunction = COMPARE_OPERATORS[p_depth_stencil_state.depth_compare_operator];
  1880. if (p_depth_stencil_state.enable_depth_range) {
  1881. WARN_PRINT("unsupported: depth range");
  1882. }
  1883. if (stencil_enabled) {
  1884. pipeline->raster_state.stencil.enabled = true;
  1885. pipeline->raster_state.stencil.front_reference = p_depth_stencil_state.front_op.reference;
  1886. pipeline->raster_state.stencil.back_reference = p_depth_stencil_state.back_op.reference;
  1887. {
  1888. // Front.
  1889. MTLStencilDescriptor *sd = [MTLStencilDescriptor new];
  1890. sd.stencilFailureOperation = STENCIL_OPERATIONS[p_depth_stencil_state.front_op.fail];
  1891. sd.depthStencilPassOperation = STENCIL_OPERATIONS[p_depth_stencil_state.front_op.pass];
  1892. sd.depthFailureOperation = STENCIL_OPERATIONS[p_depth_stencil_state.front_op.depth_fail];
  1893. sd.stencilCompareFunction = COMPARE_OPERATORS[p_depth_stencil_state.front_op.compare];
  1894. sd.readMask = p_depth_stencil_state.front_op.compare_mask;
  1895. sd.writeMask = p_depth_stencil_state.front_op.write_mask;
  1896. ds_desc.frontFaceStencil = sd;
  1897. }
  1898. {
  1899. // Back.
  1900. MTLStencilDescriptor *sd = [MTLStencilDescriptor new];
  1901. sd.stencilFailureOperation = STENCIL_OPERATIONS[p_depth_stencil_state.back_op.fail];
  1902. sd.depthStencilPassOperation = STENCIL_OPERATIONS[p_depth_stencil_state.back_op.pass];
  1903. sd.depthFailureOperation = STENCIL_OPERATIONS[p_depth_stencil_state.back_op.depth_fail];
  1904. sd.stencilCompareFunction = COMPARE_OPERATORS[p_depth_stencil_state.back_op.compare];
  1905. sd.readMask = p_depth_stencil_state.back_op.compare_mask;
  1906. sd.writeMask = p_depth_stencil_state.back_op.write_mask;
  1907. ds_desc.backFaceStencil = sd;
  1908. }
  1909. }
  1910. pipeline->depth_stencil = [device newDepthStencilStateWithDescriptor:ds_desc];
  1911. ERR_FAIL_NULL_V_MSG(pipeline->depth_stencil, PipelineID(), "Failed to create depth stencil state");
  1912. } else {
  1913. // TODO(sgc): FB13671991 raised as Apple docs state calling setDepthStencilState:nil is valid, but currently generates an exception
  1914. pipeline->depth_stencil = get_resource_cache().get_depth_stencil_state(false, false);
  1915. }
  1916. // Blend state.
  1917. {
  1918. for (uint32_t i = 0; i < p_color_attachments.size(); i++) {
  1919. if (p_color_attachments[i] == ATTACHMENT_UNUSED) {
  1920. continue;
  1921. }
  1922. const PipelineColorBlendState::Attachment &bs = p_blend_state.attachments[i];
  1923. MTLRenderPipelineColorAttachmentDescriptor *ca_desc = desc.colorAttachments[p_color_attachments[i]];
  1924. ca_desc.blendingEnabled = bs.enable_blend;
  1925. ca_desc.sourceRGBBlendFactor = BLEND_FACTORS[bs.src_color_blend_factor];
  1926. ca_desc.destinationRGBBlendFactor = BLEND_FACTORS[bs.dst_color_blend_factor];
  1927. ca_desc.rgbBlendOperation = BLEND_OPERATIONS[bs.color_blend_op];
  1928. ca_desc.sourceAlphaBlendFactor = BLEND_FACTORS[bs.src_alpha_blend_factor];
  1929. ca_desc.destinationAlphaBlendFactor = BLEND_FACTORS[bs.dst_alpha_blend_factor];
  1930. ca_desc.alphaBlendOperation = BLEND_OPERATIONS[bs.alpha_blend_op];
  1931. ca_desc.writeMask = MTLColorWriteMaskNone;
  1932. if (bs.write_r) {
  1933. ca_desc.writeMask |= MTLColorWriteMaskRed;
  1934. }
  1935. if (bs.write_g) {
  1936. ca_desc.writeMask |= MTLColorWriteMaskGreen;
  1937. }
  1938. if (bs.write_b) {
  1939. ca_desc.writeMask |= MTLColorWriteMaskBlue;
  1940. }
  1941. if (bs.write_a) {
  1942. ca_desc.writeMask |= MTLColorWriteMaskAlpha;
  1943. }
  1944. }
  1945. pipeline->raster_state.blend.r = p_blend_state.blend_constant.r;
  1946. pipeline->raster_state.blend.g = p_blend_state.blend_constant.g;
  1947. pipeline->raster_state.blend.b = p_blend_state.blend_constant.b;
  1948. pipeline->raster_state.blend.a = p_blend_state.blend_constant.a;
  1949. }
  1950. // Dynamic state.
  1951. if (p_dynamic_state.has_flag(DYNAMIC_STATE_DEPTH_BIAS)) {
  1952. pipeline->raster_state.depth_bias.enabled = true;
  1953. }
  1954. if (p_dynamic_state.has_flag(DYNAMIC_STATE_BLEND_CONSTANTS)) {
  1955. pipeline->raster_state.blend.enabled = true;
  1956. }
  1957. if (p_dynamic_state.has_flag(DYNAMIC_STATE_DEPTH_BOUNDS)) {
  1958. // TODO(sgc): ??
  1959. }
  1960. if (p_dynamic_state.has_flag(DYNAMIC_STATE_STENCIL_COMPARE_MASK)) {
  1961. // TODO(sgc): ??
  1962. }
  1963. if (p_dynamic_state.has_flag(DYNAMIC_STATE_STENCIL_WRITE_MASK)) {
  1964. // TODO(sgc): ??
  1965. }
  1966. if (p_dynamic_state.has_flag(DYNAMIC_STATE_STENCIL_REFERENCE)) {
  1967. pipeline->raster_state.stencil.enabled = true;
  1968. }
  1969. if (shader->vert != nil) {
  1970. Result<id<MTLFunction>> function_or_err = _create_function(shader->vert, @"main0", p_specialization_constants);
  1971. ERR_FAIL_COND_V(std::holds_alternative<Error>(function_or_err), PipelineID());
  1972. desc.vertexFunction = std::get<id<MTLFunction>>(function_or_err);
  1973. }
  1974. if (shader->frag != nil) {
  1975. Result<id<MTLFunction>> function_or_err = _create_function(shader->frag, @"main0", p_specialization_constants);
  1976. ERR_FAIL_COND_V(std::holds_alternative<Error>(function_or_err), PipelineID());
  1977. desc.fragmentFunction = std::get<id<MTLFunction>>(function_or_err);
  1978. }
  1979. if (archive) {
  1980. desc.binaryArchives = @[ archive ];
  1981. }
  1982. NSError *error = nil;
  1983. pipeline->state = [device newRenderPipelineStateWithDescriptor:desc
  1984. error:&error];
  1985. pipeline->shader = shader;
  1986. ERR_FAIL_COND_V_MSG(error != nil, PipelineID(), ([NSString stringWithFormat:@"error creating pipeline: %@", error.localizedDescription].UTF8String));
  1987. if (archive) {
  1988. if ([archive addRenderPipelineFunctionsWithDescriptor:desc error:&error]) {
  1989. archive_count += 1;
  1990. } else {
  1991. print_error(error.localizedDescription.UTF8String);
  1992. }
  1993. }
  1994. return PipelineID(pipeline);
  1995. }
  1996. #pragma mark - Compute
  1997. // ----- COMMANDS -----
  1998. void RenderingDeviceDriverMetal::command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) {
  1999. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2000. cb->bind_pipeline(p_pipeline);
  2001. }
  2002. void RenderingDeviceDriverMetal::command_bind_compute_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) {
  2003. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2004. cb->compute_bind_uniform_set(p_uniform_set, p_shader, p_set_index);
  2005. }
  2006. void RenderingDeviceDriverMetal::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) {
  2007. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2008. cb->compute_bind_uniform_sets(p_uniform_sets, p_shader, p_first_set_index, p_set_count);
  2009. }
  2010. void RenderingDeviceDriverMetal::command_compute_dispatch(CommandBufferID p_cmd_buffer, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) {
  2011. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2012. cb->compute_dispatch(p_x_groups, p_y_groups, p_z_groups);
  2013. }
  2014. void RenderingDeviceDriverMetal::command_compute_dispatch_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset) {
  2015. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2016. cb->compute_dispatch_indirect(p_indirect_buffer, p_offset);
  2017. }
  2018. // ----- PIPELINE -----
  2019. RDD::PipelineID RenderingDeviceDriverMetal::compute_pipeline_create(ShaderID p_shader, VectorView<PipelineSpecializationConstant> p_specialization_constants) {
  2020. MDComputeShader *shader = (MDComputeShader *)(p_shader.id);
  2021. os_signpost_id_t reflect_id = os_signpost_id_make_with_pointer(LOG_INTERVALS, shader);
  2022. os_signpost_interval_begin(LOG_INTERVALS, reflect_id, "compute_pipeline_create", "shader_name=%{public}s", shader->name.get_data());
  2023. DEFER([=]() {
  2024. os_signpost_interval_end(LOG_INTERVALS, reflect_id, "compute_pipeline_create");
  2025. });
  2026. os_signpost_event_emit(LOG_DRIVER, OS_SIGNPOST_ID_EXCLUSIVE, "create_pipeline");
  2027. Result<id<MTLFunction>> function_or_err = _create_function(shader->kernel, @"main0", p_specialization_constants);
  2028. ERR_FAIL_COND_V(std::holds_alternative<Error>(function_or_err), PipelineID());
  2029. id<MTLFunction> function = std::get<id<MTLFunction>>(function_or_err);
  2030. MTLComputePipelineDescriptor *desc = [MTLComputePipelineDescriptor new];
  2031. desc.computeFunction = function;
  2032. desc.label = conv::to_nsstring(shader->name);
  2033. if (archive) {
  2034. desc.binaryArchives = @[ archive ];
  2035. }
  2036. NSError *error;
  2037. id<MTLComputePipelineState> state = [device newComputePipelineStateWithDescriptor:desc
  2038. options:MTLPipelineOptionNone
  2039. reflection:nil
  2040. error:&error];
  2041. ERR_FAIL_COND_V_MSG(error != nil, PipelineID(), ([NSString stringWithFormat:@"error creating pipeline: %@", error.localizedDescription].UTF8String));
  2042. MDComputePipeline *pipeline = new MDComputePipeline(state);
  2043. pipeline->compute_state.local = shader->local;
  2044. pipeline->shader = shader;
  2045. if (archive) {
  2046. if ([archive addComputePipelineFunctionsWithDescriptor:desc error:&error]) {
  2047. archive_count += 1;
  2048. } else {
  2049. print_error(error.localizedDescription.UTF8String);
  2050. }
  2051. }
  2052. return PipelineID(pipeline);
  2053. }
  2054. #pragma mark - Queries
  2055. // ----- TIMESTAMP -----
  2056. RDD::QueryPoolID RenderingDeviceDriverMetal::timestamp_query_pool_create(uint32_t p_query_count) {
  2057. return QueryPoolID(1);
  2058. }
  2059. void RenderingDeviceDriverMetal::timestamp_query_pool_free(QueryPoolID p_pool_id) {
  2060. }
  2061. void RenderingDeviceDriverMetal::timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) {
  2062. // Metal doesn't support timestamp queries, so we just clear the buffer.
  2063. bzero(r_results, p_query_count * sizeof(uint64_t));
  2064. }
  2065. uint64_t RenderingDeviceDriverMetal::timestamp_query_result_to_time(uint64_t p_result) {
  2066. return p_result;
  2067. }
  2068. void RenderingDeviceDriverMetal::command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) {
  2069. }
  2070. void RenderingDeviceDriverMetal::command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) {
  2071. }
  2072. #pragma mark - Labels
  2073. void RenderingDeviceDriverMetal::command_begin_label(CommandBufferID p_cmd_buffer, const char *p_label_name, const Color &p_color) {
  2074. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2075. NSString *s = [[NSString alloc] initWithBytesNoCopy:(void *)p_label_name length:strlen(p_label_name) encoding:NSUTF8StringEncoding freeWhenDone:NO];
  2076. [cb->get_command_buffer() pushDebugGroup:s];
  2077. }
  2078. void RenderingDeviceDriverMetal::command_end_label(CommandBufferID p_cmd_buffer) {
  2079. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2080. [cb->get_command_buffer() popDebugGroup];
  2081. }
  2082. #pragma mark - Debug
  2083. void RenderingDeviceDriverMetal::command_insert_breadcrumb(CommandBufferID p_cmd_buffer, uint32_t p_data) {
  2084. // TODO: Implement.
  2085. }
  2086. #pragma mark - Submission
  2087. void RenderingDeviceDriverMetal::begin_segment(uint32_t p_frame_index, uint32_t p_frames_drawn) {
  2088. }
  2089. void RenderingDeviceDriverMetal::end_segment() {
  2090. }
  2091. #pragma mark - Misc
  2092. void RenderingDeviceDriverMetal::set_object_name(ObjectType p_type, ID p_driver_id, const String &p_name) {
  2093. switch (p_type) {
  2094. case OBJECT_TYPE_TEXTURE: {
  2095. id<MTLTexture> tex = rid::get(p_driver_id);
  2096. tex.label = [NSString stringWithUTF8String:p_name.utf8().get_data()];
  2097. } break;
  2098. case OBJECT_TYPE_SAMPLER: {
  2099. // Can't set label after creation.
  2100. } break;
  2101. case OBJECT_TYPE_BUFFER: {
  2102. id<MTLBuffer> buffer = rid::get(p_driver_id);
  2103. buffer.label = [NSString stringWithUTF8String:p_name.utf8().get_data()];
  2104. } break;
  2105. case OBJECT_TYPE_SHADER: {
  2106. NSString *label = [NSString stringWithUTF8String:p_name.utf8().get_data()];
  2107. MDShader *shader = (MDShader *)(p_driver_id.id);
  2108. if (MDRenderShader *rs = dynamic_cast<MDRenderShader *>(shader); rs != nullptr) {
  2109. [rs->vert setLabel:label];
  2110. [rs->frag setLabel:label];
  2111. } else if (MDComputeShader *cs = dynamic_cast<MDComputeShader *>(shader); cs != nullptr) {
  2112. [cs->kernel setLabel:label];
  2113. } else {
  2114. DEV_ASSERT(false);
  2115. }
  2116. } break;
  2117. case OBJECT_TYPE_UNIFORM_SET: {
  2118. MDUniformSet *set = (MDUniformSet *)(p_driver_id.id);
  2119. for (KeyValue<MDShader *, BoundUniformSet> &keyval : set->bound_uniforms) {
  2120. keyval.value.buffer.label = [NSString stringWithUTF8String:p_name.utf8().get_data()];
  2121. }
  2122. } break;
  2123. case OBJECT_TYPE_PIPELINE: {
  2124. // Can't set label after creation.
  2125. } break;
  2126. default: {
  2127. DEV_ASSERT(false);
  2128. }
  2129. }
  2130. }
  2131. uint64_t RenderingDeviceDriverMetal::get_resource_native_handle(DriverResource p_type, ID p_driver_id) {
  2132. switch (p_type) {
  2133. case DRIVER_RESOURCE_LOGICAL_DEVICE: {
  2134. return (uint64_t)(uintptr_t)(__bridge void *)device;
  2135. }
  2136. case DRIVER_RESOURCE_PHYSICAL_DEVICE: {
  2137. return 0;
  2138. }
  2139. case DRIVER_RESOURCE_TOPMOST_OBJECT: {
  2140. return 0;
  2141. }
  2142. case DRIVER_RESOURCE_COMMAND_QUEUE: {
  2143. return (uint64_t)(uintptr_t)(__bridge void *)device_queue;
  2144. }
  2145. case DRIVER_RESOURCE_QUEUE_FAMILY: {
  2146. return 0;
  2147. }
  2148. case DRIVER_RESOURCE_TEXTURE: {
  2149. return p_driver_id.id;
  2150. }
  2151. case DRIVER_RESOURCE_TEXTURE_VIEW: {
  2152. return p_driver_id.id;
  2153. }
  2154. case DRIVER_RESOURCE_TEXTURE_DATA_FORMAT: {
  2155. return 0;
  2156. }
  2157. case DRIVER_RESOURCE_SAMPLER: {
  2158. return p_driver_id.id;
  2159. }
  2160. case DRIVER_RESOURCE_UNIFORM_SET: {
  2161. return 0;
  2162. }
  2163. case DRIVER_RESOURCE_BUFFER: {
  2164. return p_driver_id.id;
  2165. }
  2166. case DRIVER_RESOURCE_COMPUTE_PIPELINE: {
  2167. MDComputePipeline *pipeline = (MDComputePipeline *)(p_driver_id.id);
  2168. return (uint64_t)(uintptr_t)(__bridge void *)pipeline->state;
  2169. }
  2170. case DRIVER_RESOURCE_RENDER_PIPELINE: {
  2171. MDRenderPipeline *pipeline = (MDRenderPipeline *)(p_driver_id.id);
  2172. return (uint64_t)(uintptr_t)(__bridge void *)pipeline->state;
  2173. }
  2174. default: {
  2175. return 0;
  2176. }
  2177. }
  2178. }
  2179. uint64_t RenderingDeviceDriverMetal::get_total_memory_used() {
  2180. return device.currentAllocatedSize;
  2181. }
  2182. uint64_t RenderingDeviceDriverMetal::get_lazily_memory_used() {
  2183. return 0; // TODO: Track this (grep for memoryless in Godot's Metal backend).
  2184. }
  2185. uint64_t RenderingDeviceDriverMetal::limit_get(Limit p_limit) {
  2186. MetalDeviceProperties const &props = (*device_properties);
  2187. MetalLimits const &limits = props.limits;
  2188. uint64_t safe_unbounded = ((uint64_t)1 << 30);
  2189. #if defined(DEV_ENABLED)
  2190. #define UNKNOWN(NAME) \
  2191. case NAME: \
  2192. WARN_PRINT_ONCE("Returning maximum value for unknown limit " #NAME "."); \
  2193. return safe_unbounded;
  2194. #else
  2195. #define UNKNOWN(NAME) \
  2196. case NAME: \
  2197. return safe_unbounded
  2198. #endif
  2199. // clang-format off
  2200. switch (p_limit) {
  2201. case LIMIT_MAX_BOUND_UNIFORM_SETS:
  2202. return limits.maxBoundDescriptorSets;
  2203. case LIMIT_MAX_FRAMEBUFFER_COLOR_ATTACHMENTS:
  2204. return limits.maxColorAttachments;
  2205. case LIMIT_MAX_TEXTURES_PER_UNIFORM_SET:
  2206. return limits.maxTexturesPerArgumentBuffer;
  2207. case LIMIT_MAX_SAMPLERS_PER_UNIFORM_SET:
  2208. return limits.maxSamplersPerArgumentBuffer;
  2209. case LIMIT_MAX_STORAGE_BUFFERS_PER_UNIFORM_SET:
  2210. return limits.maxBuffersPerArgumentBuffer;
  2211. case LIMIT_MAX_STORAGE_IMAGES_PER_UNIFORM_SET:
  2212. return limits.maxTexturesPerArgumentBuffer;
  2213. case LIMIT_MAX_UNIFORM_BUFFERS_PER_UNIFORM_SET:
  2214. return limits.maxBuffersPerArgumentBuffer;
  2215. case LIMIT_MAX_DRAW_INDEXED_INDEX:
  2216. return limits.maxDrawIndexedIndexValue;
  2217. case LIMIT_MAX_FRAMEBUFFER_HEIGHT:
  2218. return limits.maxFramebufferHeight;
  2219. case LIMIT_MAX_FRAMEBUFFER_WIDTH:
  2220. return limits.maxFramebufferWidth;
  2221. case LIMIT_MAX_TEXTURE_ARRAY_LAYERS:
  2222. return limits.maxImageArrayLayers;
  2223. case LIMIT_MAX_TEXTURE_SIZE_1D:
  2224. return limits.maxImageDimension1D;
  2225. case LIMIT_MAX_TEXTURE_SIZE_2D:
  2226. return limits.maxImageDimension2D;
  2227. case LIMIT_MAX_TEXTURE_SIZE_3D:
  2228. return limits.maxImageDimension3D;
  2229. case LIMIT_MAX_TEXTURE_SIZE_CUBE:
  2230. return limits.maxImageDimensionCube;
  2231. case LIMIT_MAX_TEXTURES_PER_SHADER_STAGE:
  2232. return limits.maxTexturesPerArgumentBuffer;
  2233. case LIMIT_MAX_SAMPLERS_PER_SHADER_STAGE:
  2234. return limits.maxSamplersPerArgumentBuffer;
  2235. case LIMIT_MAX_STORAGE_BUFFERS_PER_SHADER_STAGE:
  2236. return limits.maxBuffersPerArgumentBuffer;
  2237. case LIMIT_MAX_STORAGE_IMAGES_PER_SHADER_STAGE:
  2238. return limits.maxTexturesPerArgumentBuffer;
  2239. case LIMIT_MAX_UNIFORM_BUFFERS_PER_SHADER_STAGE:
  2240. return limits.maxBuffersPerArgumentBuffer;
  2241. case LIMIT_MAX_PUSH_CONSTANT_SIZE:
  2242. return limits.maxBufferLength;
  2243. case LIMIT_MAX_UNIFORM_BUFFER_SIZE:
  2244. return limits.maxBufferLength;
  2245. case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTE_OFFSET:
  2246. return limits.maxVertexDescriptorLayoutStride;
  2247. case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTES:
  2248. return limits.maxVertexInputAttributes;
  2249. case LIMIT_MAX_VERTEX_INPUT_BINDINGS:
  2250. return limits.maxVertexInputBindings;
  2251. case LIMIT_MAX_VERTEX_INPUT_BINDING_STRIDE:
  2252. return limits.maxVertexInputBindingStride;
  2253. case LIMIT_MIN_UNIFORM_BUFFER_OFFSET_ALIGNMENT:
  2254. return limits.minUniformBufferOffsetAlignment;
  2255. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X:
  2256. return limits.maxComputeWorkGroupCount.width;
  2257. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y:
  2258. return limits.maxComputeWorkGroupCount.height;
  2259. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z:
  2260. return limits.maxComputeWorkGroupCount.depth;
  2261. case LIMIT_MAX_COMPUTE_WORKGROUP_INVOCATIONS:
  2262. return std::max({ limits.maxThreadsPerThreadGroup.width, limits.maxThreadsPerThreadGroup.height, limits.maxThreadsPerThreadGroup.depth });
  2263. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X:
  2264. return limits.maxThreadsPerThreadGroup.width;
  2265. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y:
  2266. return limits.maxThreadsPerThreadGroup.height;
  2267. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z:
  2268. return limits.maxThreadsPerThreadGroup.depth;
  2269. case LIMIT_MAX_COMPUTE_SHARED_MEMORY_SIZE:
  2270. return limits.maxThreadGroupMemoryAllocation;
  2271. case LIMIT_MAX_VIEWPORT_DIMENSIONS_X:
  2272. return limits.maxViewportDimensionX;
  2273. case LIMIT_MAX_VIEWPORT_DIMENSIONS_Y:
  2274. return limits.maxViewportDimensionY;
  2275. case LIMIT_SUBGROUP_SIZE:
  2276. // MoltenVK sets the subgroupSize to the same as the maxSubgroupSize.
  2277. return limits.maxSubgroupSize;
  2278. case LIMIT_SUBGROUP_MIN_SIZE:
  2279. return limits.minSubgroupSize;
  2280. case LIMIT_SUBGROUP_MAX_SIZE:
  2281. return limits.maxSubgroupSize;
  2282. case LIMIT_SUBGROUP_IN_SHADERS:
  2283. return (uint64_t)limits.subgroupSupportedShaderStages;
  2284. case LIMIT_SUBGROUP_OPERATIONS:
  2285. return (uint64_t)limits.subgroupSupportedOperations;
  2286. case LIMIT_METALFX_TEMPORAL_SCALER_MIN_SCALE:
  2287. return (uint64_t)((1.0 / limits.temporalScalerInputContentMaxScale) * 1000'000);
  2288. case LIMIT_METALFX_TEMPORAL_SCALER_MAX_SCALE:
  2289. return (uint64_t)((1.0 / limits.temporalScalerInputContentMinScale) * 1000'000);
  2290. case LIMIT_MAX_SHADER_VARYINGS:
  2291. return limits.maxShaderVaryings;
  2292. default: {
  2293. #ifdef DEV_ENABLED
  2294. WARN_PRINT("Returning maximum value for unknown limit " + itos(p_limit) + ".");
  2295. #endif
  2296. return safe_unbounded;
  2297. }
  2298. }
  2299. // clang-format on
  2300. return 0;
  2301. }
  2302. uint64_t RenderingDeviceDriverMetal::api_trait_get(ApiTrait p_trait) {
  2303. switch (p_trait) {
  2304. case API_TRAIT_HONORS_PIPELINE_BARRIERS:
  2305. return 0;
  2306. default:
  2307. return RenderingDeviceDriver::api_trait_get(p_trait);
  2308. }
  2309. }
  2310. bool RenderingDeviceDriverMetal::has_feature(Features p_feature) {
  2311. switch (p_feature) {
  2312. case SUPPORTS_HALF_FLOAT:
  2313. return true;
  2314. case SUPPORTS_FRAGMENT_SHADER_WITH_ONLY_SIDE_EFFECTS:
  2315. return true;
  2316. case SUPPORTS_BUFFER_DEVICE_ADDRESS:
  2317. return device_properties->features.supports_gpu_address;
  2318. case SUPPORTS_METALFX_SPATIAL:
  2319. return device_properties->features.metal_fx_spatial;
  2320. case SUPPORTS_METALFX_TEMPORAL:
  2321. return device_properties->features.metal_fx_temporal;
  2322. case SUPPORTS_IMAGE_ATOMIC_32_BIT:
  2323. return device_properties->features.supports_native_image_atomics;
  2324. case SUPPORTS_VULKAN_MEMORY_MODEL:
  2325. return true;
  2326. default:
  2327. return false;
  2328. }
  2329. }
  2330. const RDD::MultiviewCapabilities &RenderingDeviceDriverMetal::get_multiview_capabilities() {
  2331. return multiview_capabilities;
  2332. }
  2333. const RDD::FragmentShadingRateCapabilities &RenderingDeviceDriverMetal::get_fragment_shading_rate_capabilities() {
  2334. return fsr_capabilities;
  2335. }
  2336. const RDD::FragmentDensityMapCapabilities &RenderingDeviceDriverMetal::get_fragment_density_map_capabilities() {
  2337. return fdm_capabilities;
  2338. }
  2339. String RenderingDeviceDriverMetal::get_api_version() const {
  2340. return vformat("%d.%d", capabilities.version_major, capabilities.version_minor);
  2341. }
  2342. String RenderingDeviceDriverMetal::get_pipeline_cache_uuid() const {
  2343. return pipeline_cache_id;
  2344. }
  2345. const RDD::Capabilities &RenderingDeviceDriverMetal::get_capabilities() const {
  2346. return capabilities;
  2347. }
  2348. bool RenderingDeviceDriverMetal::is_composite_alpha_supported(CommandQueueID p_queue) const {
  2349. // The CAMetalLayer.opaque property is configured according to this global setting.
  2350. return OS::get_singleton()->is_layered_allowed();
  2351. }
  2352. size_t RenderingDeviceDriverMetal::get_texel_buffer_alignment_for_format(RDD::DataFormat p_format) const {
  2353. return [device minimumLinearTextureAlignmentForPixelFormat:pixel_formats->getMTLPixelFormat(p_format)];
  2354. }
  2355. size_t RenderingDeviceDriverMetal::get_texel_buffer_alignment_for_format(MTLPixelFormat p_format) const {
  2356. return [device minimumLinearTextureAlignmentForPixelFormat:p_format];
  2357. }
  2358. /******************/
  2359. RenderingDeviceDriverMetal::RenderingDeviceDriverMetal(RenderingContextDriverMetal *p_context_driver) :
  2360. context_driver(p_context_driver) {
  2361. DEV_ASSERT(p_context_driver != nullptr);
  2362. #if TARGET_OS_OSX
  2363. if (String res = OS::get_singleton()->get_environment("GODOT_MTL_SHADER_LOAD_STRATEGY"); res == U"lazy") {
  2364. _shader_load_strategy = ShaderLoadStrategy::LAZY;
  2365. }
  2366. #else
  2367. // Always use the lazy strategy on other OSs like iOS, tvOS, or visionOS.
  2368. _shader_load_strategy = ShaderLoadStrategy::LAZY;
  2369. #endif
  2370. }
  2371. RenderingDeviceDriverMetal::~RenderingDeviceDriverMetal() {
  2372. for (MDCommandBuffer *cb : command_buffers) {
  2373. delete cb;
  2374. }
  2375. for (KeyValue<SHA256Digest, ShaderCacheEntry *> &kv : _shader_cache) {
  2376. memdelete(kv.value);
  2377. }
  2378. if (shader_container_format != nullptr) {
  2379. memdelete(shader_container_format);
  2380. }
  2381. if (pixel_formats != nullptr) {
  2382. memdelete(pixel_formats);
  2383. }
  2384. if (device_properties != nullptr) {
  2385. memdelete(device_properties);
  2386. }
  2387. }
  2388. #pragma mark - Initialization
  2389. Error RenderingDeviceDriverMetal::_create_device() {
  2390. device = context_driver->get_metal_device();
  2391. device_queue = [device newCommandQueue];
  2392. ERR_FAIL_NULL_V(device_queue, ERR_CANT_CREATE);
  2393. device_scope = [MTLCaptureManager.sharedCaptureManager newCaptureScopeWithCommandQueue:device_queue];
  2394. device_scope.label = @"Godot Frame";
  2395. [device_scope beginScope]; // Allow Xcode to capture the first frame, if desired.
  2396. resource_cache = std::make_unique<MDResourceCache>(this);
  2397. return OK;
  2398. }
  2399. void RenderingDeviceDriverMetal::_check_capabilities() {
  2400. capabilities.device_family = DEVICE_METAL;
  2401. capabilities.version_major = device_properties->features.mslVersionMajor;
  2402. capabilities.version_minor = device_properties->features.mslVersionMinor;
  2403. }
  2404. API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0))
  2405. static MetalDeviceProfile device_profile_from_properties(MetalDeviceProperties *p_device_properties) {
  2406. using DP = MetalDeviceProfile;
  2407. MetalDeviceProfile res;
  2408. #if TARGET_OS_OSX
  2409. res.platform = DP::Platform::macOS;
  2410. res.features = {
  2411. .mslVersionMajor = p_device_properties->features.mslVersionMajor,
  2412. .mslVersionMinor = p_device_properties->features.mslVersionMinor,
  2413. .argument_buffers_tier = DP::ArgumentBuffersTier::Tier2,
  2414. .simdPermute = true
  2415. };
  2416. #else
  2417. res.platform = DP::Platform::iOS;
  2418. res.features = {
  2419. .mslVersionMajor = p_device_properties->features.mslVersionMajor,
  2420. .mslVersionMinor = p_device_properties->features.mslVersionMinor,
  2421. .argument_buffers_tier = p_device_properties->features.argument_buffers_tier == MTLArgumentBuffersTier1 ? DP::ArgumentBuffersTier::Tier1 : DP::ArgumentBuffersTier::Tier2,
  2422. .simdPermute = p_device_properties->features.simdPermute,
  2423. };
  2424. #endif
  2425. // highestFamily will only be set to an Apple GPU family
  2426. switch (p_device_properties->features.highestFamily) {
  2427. case MTLGPUFamilyApple1:
  2428. res.gpu = DP::GPU::Apple1;
  2429. break;
  2430. case MTLGPUFamilyApple2:
  2431. res.gpu = DP::GPU::Apple2;
  2432. break;
  2433. case MTLGPUFamilyApple3:
  2434. res.gpu = DP::GPU::Apple3;
  2435. break;
  2436. case MTLGPUFamilyApple4:
  2437. res.gpu = DP::GPU::Apple4;
  2438. break;
  2439. case MTLGPUFamilyApple5:
  2440. res.gpu = DP::GPU::Apple5;
  2441. break;
  2442. case MTLGPUFamilyApple6:
  2443. res.gpu = DP::GPU::Apple6;
  2444. break;
  2445. case MTLGPUFamilyApple7:
  2446. res.gpu = DP::GPU::Apple7;
  2447. break;
  2448. case MTLGPUFamilyApple8:
  2449. res.gpu = DP::GPU::Apple8;
  2450. break;
  2451. case MTLGPUFamilyApple9:
  2452. res.gpu = DP::GPU::Apple9;
  2453. break;
  2454. default: {
  2455. // Programming error if the default case is hit.
  2456. CRASH_NOW_MSG("Unsupported GPU family");
  2457. } break;
  2458. }
  2459. return res;
  2460. }
  2461. Error RenderingDeviceDriverMetal::initialize(uint32_t p_device_index, uint32_t p_frame_count) {
  2462. context_device = context_driver->device_get(p_device_index);
  2463. Error err = _create_device();
  2464. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  2465. device_properties = memnew(MetalDeviceProperties(device));
  2466. device_profile = device_profile_from_properties(device_properties);
  2467. shader_container_format = memnew(RenderingShaderContainerFormatMetal(&device_profile));
  2468. _check_capabilities();
  2469. // Set the pipeline cache ID based on the Metal version.
  2470. pipeline_cache_id = "metal-driver-" + get_api_version();
  2471. pixel_formats = memnew(PixelFormats(device, device_properties->features));
  2472. if (device_properties->features.layeredRendering) {
  2473. multiview_capabilities.is_supported = true;
  2474. multiview_capabilities.max_view_count = device_properties->limits.maxViewports;
  2475. // NOTE: I'm not sure what the limit is as I don't see it referenced anywhere
  2476. multiview_capabilities.max_instance_count = UINT32_MAX;
  2477. print_verbose("- Metal multiview supported:");
  2478. print_verbose(" max view count: " + itos(multiview_capabilities.max_view_count));
  2479. print_verbose(" max instances: " + itos(multiview_capabilities.max_instance_count));
  2480. } else {
  2481. print_verbose("- Metal multiview not supported");
  2482. }
  2483. // The Metal renderer requires Apple4 family. This is 2017 era A11 chips and newer.
  2484. if (device_properties->features.highestFamily < MTLGPUFamilyApple4) {
  2485. String error_string = vformat("Your Apple GPU does not support the following features, which are required to use Metal-based renderers in Godot:\n\n");
  2486. if (!device_properties->features.imageCubeArray) {
  2487. error_string += "- No support for image cube arrays.\n";
  2488. }
  2489. #if defined(APPLE_EMBEDDED_ENABLED)
  2490. // Apple Embedded platforms exports currently don't exit themselves when this method returns `ERR_CANT_CREATE`.
  2491. OS::get_singleton()->alert(error_string + "\nClick OK to exit (black screen will be visible).");
  2492. #else
  2493. OS::get_singleton()->alert(error_string + "\nClick OK to exit.");
  2494. #endif
  2495. return ERR_CANT_CREATE;
  2496. }
  2497. return OK;
  2498. }
  2499. const RenderingShaderContainerFormat &RenderingDeviceDriverMetal::get_shader_container_format() const {
  2500. return *shader_container_format;
  2501. }