renderer_mtl.mm 144 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894
  1. /*
  2. * Copyright 2011-2016 Attila Kocsis. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include "bgfx_p.h"
  6. #if BGFX_CONFIG_RENDERER_METAL
  7. #include "renderer_mtl.h"
  8. #include "renderer.h"
  9. #if BX_PLATFORM_OSX
  10. # include <Cocoa/Cocoa.h>
  11. #endif
  12. #import <Foundation/Foundation.h>
  13. #define UNIFORM_BUFFER_SIZE (8*1024*1024)
  14. namespace bgfx { namespace mtl
  15. {
  16. static char s_viewName[BGFX_CONFIG_MAX_VIEWS][BGFX_CONFIG_MAX_VIEW_NAME];
  17. inline void setViewType(ViewId _view, const bx::StringView _str)
  18. {
  19. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION || BGFX_CONFIG_PROFILER) )
  20. {
  21. bx::memCopy(&s_viewName[_view][3], _str.getPtr(), _str.getLength() );
  22. }
  23. }
  24. struct PrimInfo
  25. {
  26. MTLPrimitiveType m_type;
  27. uint32_t m_min;
  28. uint32_t m_div;
  29. uint32_t m_sub;
  30. };
  31. static const PrimInfo s_primInfo[] =
  32. {
  33. { MTLPrimitiveTypeTriangle, 3, 3, 0 },
  34. { MTLPrimitiveTypeTriangleStrip, 3, 1, 2 },
  35. { MTLPrimitiveTypeLine, 2, 2, 0 },
  36. { MTLPrimitiveTypeLineStrip, 2, 1, 1 },
  37. { MTLPrimitiveTypePoint, 1, 1, 0 },
  38. };
  39. BX_STATIC_ASSERT(Topology::Count == BX_COUNTOF(s_primInfo) );
  40. static const char* s_attribName[] =
  41. {
  42. "a_position",
  43. "a_normal",
  44. "a_tangent",
  45. "a_bitangent",
  46. "a_color0",
  47. "a_color1",
  48. "a_color2",
  49. "a_color3",
  50. "a_indices",
  51. "a_weight",
  52. "a_texcoord0",
  53. "a_texcoord1",
  54. "a_texcoord2",
  55. "a_texcoord3",
  56. "a_texcoord4",
  57. "a_texcoord5",
  58. "a_texcoord6",
  59. "a_texcoord7",
  60. };
  61. BX_STATIC_ASSERT(Attrib::Count == BX_COUNTOF(s_attribName) );
  62. static const char* s_instanceDataName[] =
  63. {
  64. "i_data0",
  65. "i_data1",
  66. "i_data2",
  67. "i_data3",
  68. "i_data4",
  69. };
  70. BX_STATIC_ASSERT(BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT == BX_COUNTOF(s_instanceDataName) );
  71. static const MTLVertexFormat s_attribType[][4][2] = //type, count, normalized
  72. {
  73. // Uint8
  74. {
  75. { MTLVertexFormatUChar2, MTLVertexFormatUChar2Normalized },
  76. { MTLVertexFormatUChar2, MTLVertexFormatUChar2Normalized },
  77. { MTLVertexFormatUChar3, MTLVertexFormatUChar3Normalized },
  78. { MTLVertexFormatUChar4, MTLVertexFormatUChar4Normalized },
  79. },
  80. //Uint10
  81. //Note: unnormalized is handled as normalized now
  82. {
  83. { MTLVertexFormatUInt1010102Normalized, MTLVertexFormatUInt1010102Normalized },
  84. { MTLVertexFormatUInt1010102Normalized, MTLVertexFormatUInt1010102Normalized },
  85. { MTLVertexFormatUInt1010102Normalized, MTLVertexFormatUInt1010102Normalized },
  86. { MTLVertexFormatUInt1010102Normalized, MTLVertexFormatUInt1010102Normalized },
  87. },
  88. //Int16
  89. {
  90. { MTLVertexFormatShort2, MTLVertexFormatShort2Normalized },
  91. { MTLVertexFormatShort2, MTLVertexFormatShort2Normalized },
  92. { MTLVertexFormatShort3, MTLVertexFormatShort3Normalized },
  93. { MTLVertexFormatShort4, MTLVertexFormatShort4Normalized },
  94. },
  95. //Half
  96. {
  97. { MTLVertexFormatHalf2, MTLVertexFormatHalf2 },
  98. { MTLVertexFormatHalf2, MTLVertexFormatHalf2 },
  99. { MTLVertexFormatHalf3, MTLVertexFormatHalf3 },
  100. { MTLVertexFormatHalf4, MTLVertexFormatHalf4 },
  101. },
  102. //Float
  103. {
  104. { MTLVertexFormatFloat, MTLVertexFormatFloat },
  105. { MTLVertexFormatFloat2, MTLVertexFormatFloat2 },
  106. { MTLVertexFormatFloat3, MTLVertexFormatFloat3 },
  107. { MTLVertexFormatFloat4, MTLVertexFormatFloat4 },
  108. },
  109. };
  110. BX_STATIC_ASSERT(AttribType::Count == BX_COUNTOF(s_attribType) );
  111. static const MTLCullMode s_cullMode[] =
  112. {
  113. MTLCullModeNone,
  114. MTLCullModeFront,
  115. MTLCullModeBack,
  116. MTLCullModeNone
  117. };
  118. static const MTLBlendFactor s_blendFactor[][2] =
  119. {
  120. { (MTLBlendFactor)0, (MTLBlendFactor)0 }, // ignored
  121. { MTLBlendFactorZero, MTLBlendFactorZero }, // ZERO
  122. { MTLBlendFactorOne, MTLBlendFactorOne }, // ONE
  123. { MTLBlendFactorSourceColor, MTLBlendFactorSourceAlpha }, // SRC_COLOR
  124. { MTLBlendFactorOneMinusSourceColor, MTLBlendFactorOneMinusSourceAlpha }, // INV_SRC_COLOR
  125. { MTLBlendFactorSourceAlpha, MTLBlendFactorSourceAlpha }, // SRC_ALPHA
  126. { MTLBlendFactorOneMinusSourceAlpha, MTLBlendFactorOneMinusSourceAlpha }, // INV_SRC_ALPHA
  127. { MTLBlendFactorDestinationAlpha, MTLBlendFactorDestinationAlpha }, // DST_ALPHA
  128. { MTLBlendFactorOneMinusDestinationAlpha, MTLBlendFactorOneMinusDestinationAlpha }, // INV_DST_ALPHA
  129. { MTLBlendFactorDestinationColor, MTLBlendFactorDestinationAlpha }, // DST_COLOR
  130. { MTLBlendFactorOneMinusDestinationColor, MTLBlendFactorOneMinusDestinationAlpha }, // INV_DST_COLOR
  131. { MTLBlendFactorSourceAlphaSaturated, MTLBlendFactorOne }, // SRC_ALPHA_SAT
  132. { MTLBlendFactorBlendColor, MTLBlendFactorBlendColor }, // FACTOR
  133. { MTLBlendFactorOneMinusBlendColor, MTLBlendFactorOneMinusBlendColor }, // INV_FACTOR
  134. };
  135. static const MTLBlendOperation s_blendEquation[] =
  136. {
  137. MTLBlendOperationAdd,
  138. MTLBlendOperationSubtract,
  139. MTLBlendOperationReverseSubtract,
  140. MTLBlendOperationMin,
  141. MTLBlendOperationMax,
  142. };
  143. static const MTLCompareFunction s_cmpFunc[] =
  144. {
  145. MTLCompareFunctionAlways,
  146. MTLCompareFunctionLess,
  147. MTLCompareFunctionLessEqual,
  148. MTLCompareFunctionEqual,
  149. MTLCompareFunctionGreaterEqual,
  150. MTLCompareFunctionGreater,
  151. MTLCompareFunctionNotEqual,
  152. MTLCompareFunctionNever,
  153. MTLCompareFunctionAlways,
  154. };
  155. static const MTLStencilOperation s_stencilOp[] =
  156. {
  157. MTLStencilOperationZero,
  158. MTLStencilOperationKeep,
  159. MTLStencilOperationReplace,
  160. MTLStencilOperationIncrementWrap,
  161. MTLStencilOperationIncrementClamp,
  162. MTLStencilOperationDecrementWrap,
  163. MTLStencilOperationDecrementClamp,
  164. MTLStencilOperationInvert,
  165. };
  166. static const MTLSamplerAddressMode s_textureAddress[] =
  167. {
  168. MTLSamplerAddressModeRepeat,
  169. MTLSamplerAddressModeMirrorRepeat,
  170. MTLSamplerAddressModeClampToEdge,
  171. MTLSamplerAddressModeClampToZero,
  172. };
  173. static const MTLSamplerMinMagFilter s_textureFilterMinMag[] =
  174. {
  175. MTLSamplerMinMagFilterLinear,
  176. MTLSamplerMinMagFilterNearest,
  177. MTLSamplerMinMagFilterLinear,
  178. };
  179. static const MTLSamplerMipFilter s_textureFilterMip[] =
  180. {
  181. MTLSamplerMipFilterLinear,
  182. MTLSamplerMipFilterNearest,
  183. };
  184. struct TextureFormatInfo
  185. {
  186. MTLPixelFormat m_fmt;
  187. MTLPixelFormat m_fmtSrgb;
  188. };
  189. static TextureFormatInfo s_textureFormat[] =
  190. {
  191. { MTLPixelFormat(130/*BC1_RGBA*/), MTLPixelFormat(131/*BC1_RGBA_sRGB*/) }, // BC1
  192. { MTLPixelFormat(132/*BC2_RGBA*/), MTLPixelFormat(133/*BC2_RGBA_sRGB*/) }, // BC2
  193. { MTLPixelFormat(134/*BC3_RGBA*/), MTLPixelFormat(135/*BC3_RGBA_sRGB*/) }, // BC3
  194. { MTLPixelFormat(140/*BC4_RUnorm*/), MTLPixelFormatInvalid }, // BC4
  195. { MTLPixelFormat(142/*BC5_RGUnorm*/), MTLPixelFormatInvalid }, // BC5
  196. { MTLPixelFormat(150/*BC6H_RGBFloat*/), MTLPixelFormatInvalid }, // BC6H
  197. { MTLPixelFormat(152/*BC7_RGBAUnorm*/), MTLPixelFormat(153/*BC7_RGBAUnorm_sRGB*/) }, // BC7
  198. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ETC1
  199. { MTLPixelFormat(180/*ETC2_RGB8*/), MTLPixelFormat(181/*ETC2_RGB8_sRGB*/) }, // ETC2
  200. { MTLPixelFormat(178/*EAC_RGBA8*/), MTLPixelFormat(179/*EAC_RGBA8_sRGB*/) }, // ETC2A
  201. { MTLPixelFormat(182/*ETC2_RGB8A1*/), MTLPixelFormat(183/*ETC2_RGB8A1_sRGB*/) }, // ETC2A1
  202. { MTLPixelFormat(160/*PVRTC_RGB_2BPP*/), MTLPixelFormat(161/*PVRTC_RGB_2BPP_sRGB*/) }, // PTC12
  203. { MTLPixelFormat(162/*PVRTC_RGB_4BPP*/), MTLPixelFormat(163/*PVRTC_RGB_4BPP_sRGB*/) }, // PTC14
  204. { MTLPixelFormat(164/*PVRTC_RGBA_2BPP*/), MTLPixelFormat(165/*PVRTC_RGBA_2BPP_sRGB*/) }, // PTC12A
  205. { MTLPixelFormat(166/*PVRTC_RGBA_4BPP*/), MTLPixelFormat(167/*PVRTC_RGBA_4BPP_sRGB*/) }, // PTC14A
  206. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // PTC22
  207. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // PTC24
  208. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ATC
  209. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ATCE
  210. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ATCI
  211. #if BX_PLATFORM_IOS && !TARGET_OS_MACCATALYST
  212. { MTLPixelFormatASTC_4x4_LDR, MTLPixelFormatASTC_4x4_sRGB }, // ASTC4x4
  213. { MTLPixelFormatASTC_5x5_LDR, MTLPixelFormatASTC_5x5_sRGB }, // ASTC5x5
  214. { MTLPixelFormatASTC_6x6_LDR, MTLPixelFormatASTC_6x6_sRGB }, // ASTC6x6
  215. { MTLPixelFormatASTC_8x5_LDR, MTLPixelFormatASTC_8x5_sRGB }, // ASTC8x5
  216. { MTLPixelFormatASTC_8x6_LDR, MTLPixelFormatASTC_8x6_sRGB }, // ASTC8x6
  217. { MTLPixelFormatASTC_10x5_LDR, MTLPixelFormatASTC_10x5_sRGB }, // ASTC10x5
  218. #else
  219. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC4x4
  220. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC5x5
  221. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC6x6
  222. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC8x5
  223. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC8x6
  224. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC10x5
  225. #endif // BX_PLATFORM_IOS && !TARGET_OS_MACCATALYST
  226. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // Unknown
  227. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // R1
  228. { MTLPixelFormatA8Unorm, MTLPixelFormatInvalid }, // A8
  229. { MTLPixelFormatR8Unorm, MTLPixelFormat(11/*R8Unorm_sRGB*/) }, // R8
  230. { MTLPixelFormatR8Sint, MTLPixelFormatInvalid }, // R8I
  231. { MTLPixelFormatR8Uint, MTLPixelFormatInvalid }, // R8U
  232. { MTLPixelFormatR8Snorm, MTLPixelFormatInvalid }, // R8S
  233. { MTLPixelFormatR16Unorm, MTLPixelFormatInvalid }, // R16
  234. { MTLPixelFormatR16Sint, MTLPixelFormatInvalid }, // R16I
  235. { MTLPixelFormatR16Uint, MTLPixelFormatInvalid }, // R16U
  236. { MTLPixelFormatR16Float, MTLPixelFormatInvalid }, // R16F
  237. { MTLPixelFormatR16Snorm, MTLPixelFormatInvalid }, // R16S
  238. { MTLPixelFormatR32Sint, MTLPixelFormatInvalid }, // R32I
  239. { MTLPixelFormatR32Uint, MTLPixelFormatInvalid }, // R32U
  240. { MTLPixelFormatR32Float, MTLPixelFormatInvalid }, // R32F
  241. { MTLPixelFormatRG8Unorm, MTLPixelFormat(31/*RG8Unorm_sRGB*/) }, // RG8
  242. { MTLPixelFormatRG8Sint, MTLPixelFormatInvalid }, // RG8I
  243. { MTLPixelFormatRG8Uint, MTLPixelFormatInvalid }, // RG8U
  244. { MTLPixelFormatRG8Snorm, MTLPixelFormatInvalid }, // RG8S
  245. { MTLPixelFormatRG16Unorm, MTLPixelFormatInvalid }, // RG16
  246. { MTLPixelFormatRG16Sint, MTLPixelFormatInvalid }, // RG16I
  247. { MTLPixelFormatRG16Uint, MTLPixelFormatInvalid }, // RG16U
  248. { MTLPixelFormatRG16Float, MTLPixelFormatInvalid }, // RG16F
  249. { MTLPixelFormatRG16Snorm, MTLPixelFormatInvalid }, // RG16S
  250. { MTLPixelFormatRG32Sint, MTLPixelFormatInvalid }, // RG32I
  251. { MTLPixelFormatRG32Uint, MTLPixelFormatInvalid }, // RG32U
  252. { MTLPixelFormatRG32Float, MTLPixelFormatInvalid }, // RG32F
  253. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // RGB8
  254. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // RGB8I
  255. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // RGB8U
  256. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // RGB8S
  257. { MTLPixelFormatRGB9E5Float, MTLPixelFormatInvalid }, // RGB9E5F
  258. { MTLPixelFormatBGRA8Unorm, MTLPixelFormatBGRA8Unorm_sRGB }, // BGRA8
  259. { MTLPixelFormatRGBA8Unorm, MTLPixelFormatRGBA8Unorm_sRGB }, // RGBA8
  260. { MTLPixelFormatRGBA8Sint, MTLPixelFormatInvalid }, // RGBA8I
  261. { MTLPixelFormatRGBA8Uint, MTLPixelFormatInvalid }, // RGBA8U
  262. { MTLPixelFormatRGBA8Snorm, MTLPixelFormatInvalid }, // RGBA8S
  263. { MTLPixelFormatRGBA16Unorm, MTLPixelFormatInvalid }, // RGBA16
  264. { MTLPixelFormatRGBA16Sint, MTLPixelFormatInvalid }, // RGBA16I
  265. { MTLPixelFormatRGBA16Uint, MTLPixelFormatInvalid }, // RGBA16U
  266. { MTLPixelFormatRGBA16Float, MTLPixelFormatInvalid }, // RGBA16F
  267. { MTLPixelFormatRGBA16Snorm, MTLPixelFormatInvalid }, // RGBA16S
  268. { MTLPixelFormatRGBA32Sint, MTLPixelFormatInvalid }, // RGBA32I
  269. { MTLPixelFormatRGBA32Uint, MTLPixelFormatInvalid }, // RGBA32U
  270. { MTLPixelFormatRGBA32Float, MTLPixelFormatInvalid }, // RGBA32F
  271. { MTLPixelFormat(40/*B5G6R5Unorm*/), MTLPixelFormatInvalid }, // R5G6B5
  272. { MTLPixelFormat(42/*ABGR4Unorm*/), MTLPixelFormatInvalid }, // RGBA4
  273. { MTLPixelFormat(41/*A1BGR5Unorm*/), MTLPixelFormatInvalid }, // RGB5A1
  274. { MTLPixelFormatRGB10A2Unorm, MTLPixelFormatInvalid }, // RGB10A2
  275. { MTLPixelFormatRG11B10Float, MTLPixelFormatInvalid }, // RG11B10F
  276. { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // UnknownDepth
  277. { MTLPixelFormatDepth32Float, MTLPixelFormatInvalid }, // D16
  278. { MTLPixelFormatDepth32Float, MTLPixelFormatInvalid }, // D24
  279. { MTLPixelFormat(255/*Depth24Unorm_Stencil8*/), MTLPixelFormatInvalid }, // D24S8
  280. { MTLPixelFormatDepth32Float, MTLPixelFormatInvalid }, // D32
  281. { MTLPixelFormatDepth32Float, MTLPixelFormatInvalid }, // D16F
  282. { MTLPixelFormatDepth32Float, MTLPixelFormatInvalid }, // D24F
  283. { MTLPixelFormatDepth32Float, MTLPixelFormatInvalid }, // D32F
  284. { MTLPixelFormatStencil8, MTLPixelFormatInvalid }, // D0S8
  285. };
  286. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_textureFormat) );
  287. int32_t s_msaa[] =
  288. {
  289. 1,
  290. 2,
  291. 4,
  292. 8,
  293. 16,
  294. };
  295. static UniformType::Enum convertMtlType(MTLDataType _type)
  296. {
  297. switch (_type)
  298. {
  299. case MTLDataTypeUInt:
  300. case MTLDataTypeInt:
  301. return UniformType::Sampler;
  302. case MTLDataTypeFloat:
  303. case MTLDataTypeFloat2:
  304. case MTLDataTypeFloat3:
  305. case MTLDataTypeFloat4:
  306. return UniformType::Vec4;
  307. case MTLDataTypeFloat3x3:
  308. return UniformType::Mat3;
  309. case MTLDataTypeFloat4x4:
  310. return UniformType::Mat4;
  311. default:
  312. break;
  313. };
  314. BX_ASSERT(false, "Unrecognized Mtl Data type 0x%04x.", _type);
  315. return UniformType::End;
  316. }
  317. #define SHADER_FUNCTION_NAME ("xlatMtlMain")
  318. #define SHADER_UNIFORM_NAME ("_mtl_u")
  319. struct RendererContextMtl;
  320. static RendererContextMtl* s_renderMtl;
  321. struct RendererContextMtl : public RendererContextI
  322. {
  323. RendererContextMtl()
  324. : m_bufferIndex(0)
  325. , m_numWindows(0)
  326. , m_rtMsaa(false)
  327. , m_capture(NULL)
  328. , m_captureSize(0)
  329. {
  330. bx::memSet(&m_windows, 0xff, sizeof(m_windows) );
  331. }
  332. ~RendererContextMtl()
  333. {
  334. }
  335. bool init(const Init& _init)
  336. {
  337. BX_UNUSED(_init);
  338. BX_TRACE("Init.");
  339. m_fbh.idx = kInvalidHandle;
  340. bx::memSet(m_uniforms, 0, sizeof(m_uniforms) );
  341. bx::memSet(&m_resolution, 0, sizeof(m_resolution) );
  342. m_device = (id<MTLDevice>)g_platformData.context;
  343. if (NULL == m_device)
  344. {
  345. m_device = MTLCreateSystemDefaultDevice();
  346. }
  347. if (NULL == m_device)
  348. {
  349. BX_WARN(NULL != m_device, "Unable to create Metal device.");
  350. return false;
  351. }
  352. retain(m_device);
  353. m_mainFrameBuffer.create(
  354. 0
  355. , g_platformData.nwh
  356. , _init.resolution.width
  357. , _init.resolution.height
  358. , TextureFormat::Unknown
  359. , TextureFormat::UnknownDepth
  360. );
  361. m_numWindows = 1;
  362. if (NULL == m_mainFrameBuffer.m_swapChain->m_metalLayer)
  363. {
  364. release(m_device);
  365. return false;
  366. }
  367. m_cmd.init(m_device);
  368. BGFX_FATAL(NULL != m_cmd.m_commandQueue, Fatal::UnableToInitialize, "Unable to create Metal device.");
  369. m_renderPipelineDescriptor = newRenderPipelineDescriptor();
  370. m_depthStencilDescriptor = newDepthStencilDescriptor();
  371. m_frontFaceStencilDescriptor = newStencilDescriptor();
  372. m_backFaceStencilDescriptor = newStencilDescriptor();
  373. m_vertexDescriptor = newVertexDescriptor();
  374. m_textureDescriptor = newTextureDescriptor();
  375. m_samplerDescriptor = newSamplerDescriptor();
  376. for (uint8_t ii = 0; ii < BGFX_CONFIG_MAX_FRAME_LATENCY; ++ii)
  377. {
  378. m_uniformBuffers[ii] = m_device.newBufferWithLength(UNIFORM_BUFFER_SIZE, 0);
  379. }
  380. m_uniformBufferVertexOffset = 0;
  381. m_uniformBufferFragmentOffset = 0;
  382. const char* vshSource =
  383. "using namespace metal;\n"
  384. "struct xlatMtlShaderOutput { float4 gl_Position [[position]]; float2 v_texcoord0; }; \n"
  385. "vertex xlatMtlShaderOutput xlatMtlMain (uint v_id [[ vertex_id ]]) \n"
  386. "{\n"
  387. " xlatMtlShaderOutput _mtl_o;\n"
  388. " if (v_id==0) { _mtl_o.gl_Position = float4(-1.0,-1.0,0.0,1.0); _mtl_o.v_texcoord0 = float2(0.0,1.0); } \n"
  389. " else if (v_id==1) { _mtl_o.gl_Position = float4(3.0,-1.0,0.0,1.0); _mtl_o.v_texcoord0 = float2(2.0,1.0); } \n"
  390. " else { _mtl_o.gl_Position = float4(-1.0,3.0,0.0,1.0); _mtl_o.v_texcoord0 = float2(0.0,-1.0); }\n"
  391. " return _mtl_o;\n"
  392. "}\n"
  393. ;
  394. const char* fshSource =
  395. "using namespace metal;\n"
  396. "struct xlatMtlShaderInput { float2 v_texcoord0; };\n"
  397. "fragment half4 xlatMtlMain (xlatMtlShaderInput _mtl_i[[stage_in]], texture2d<float> s_texColor [[texture(0)]], sampler _mtlsmp_s_texColor [[sampler(0)]] )\n"
  398. "{\n"
  399. " return half4(s_texColor.sample(_mtlsmp_s_texColor, _mtl_i.v_texcoord0) );\n"
  400. "}\n"
  401. ;
  402. Library lib = m_device.newLibraryWithSource(vshSource);
  403. if (NULL != lib)
  404. {
  405. m_screenshotBlitProgramVsh.m_function = lib.newFunctionWithName(SHADER_FUNCTION_NAME);
  406. release(lib);
  407. }
  408. lib = m_device.newLibraryWithSource(fshSource);
  409. if (NULL != lib)
  410. {
  411. m_screenshotBlitProgramFsh.m_function = lib.newFunctionWithName(SHADER_FUNCTION_NAME);
  412. release(lib);
  413. }
  414. m_screenshotBlitProgram.create(&m_screenshotBlitProgramVsh, &m_screenshotBlitProgramFsh);
  415. reset(m_renderPipelineDescriptor);
  416. m_renderPipelineDescriptor.colorAttachments[0].pixelFormat = m_mainFrameBuffer.m_swapChain->m_metalLayer.pixelFormat;
  417. m_renderPipelineDescriptor.vertexFunction = m_screenshotBlitProgram.m_vsh->m_function;
  418. m_renderPipelineDescriptor.fragmentFunction = m_screenshotBlitProgram.m_fsh->m_function;
  419. m_screenshotBlitRenderPipelineState = m_device.newRenderPipelineStateWithDescriptor(m_renderPipelineDescriptor);
  420. g_caps.supported |= (0
  421. | BGFX_CAPS_ALPHA_TO_COVERAGE
  422. | BGFX_CAPS_BLEND_INDEPENDENT
  423. | BGFX_CAPS_COMPUTE
  424. | BGFX_CAPS_FRAGMENT_DEPTH
  425. | BGFX_CAPS_INDEX32
  426. | BGFX_CAPS_INSTANCING
  427. | BGFX_CAPS_OCCLUSION_QUERY
  428. | BGFX_CAPS_SWAP_CHAIN
  429. | BGFX_CAPS_TEXTURE_2D_ARRAY
  430. | BGFX_CAPS_TEXTURE_3D
  431. | BGFX_CAPS_TEXTURE_BLIT
  432. | BGFX_CAPS_TEXTURE_COMPARE_ALL
  433. | BGFX_CAPS_TEXTURE_COMPARE_LEQUAL
  434. | BGFX_CAPS_TEXTURE_READ_BACK
  435. | BGFX_CAPS_VERTEX_ATTRIB_HALF
  436. | BGFX_CAPS_VERTEX_ATTRIB_UINT10
  437. | BGFX_CAPS_VERTEX_ID
  438. );
  439. if (BX_ENABLED(BX_PLATFORM_IOS) )
  440. {
  441. if (iOSVersionEqualOrGreater("9.0.0") )
  442. {
  443. g_caps.limits.maxTextureSize = m_device.supportsFeatureSet( (MTLFeatureSet)4 /* iOS_GPUFamily3_v1 */) ? 16384 : 8192;
  444. }
  445. else
  446. {
  447. g_caps.limits.maxTextureSize = 4096;
  448. }
  449. g_caps.limits.maxFBAttachments = uint8_t(bx::uint32_min(m_device.supportsFeatureSet( (MTLFeatureSet)1 /* MTLFeatureSet_iOS_GPUFamily2_v1 */) ? 8 : 4, BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS) );
  450. g_caps.supported |= m_device.supportsFeatureSet( (MTLFeatureSet)4 /* MTLFeatureSet_iOS_GPUFamily3_v1 */)
  451. ? BGFX_CAPS_DRAW_INDIRECT
  452. : 0
  453. ;
  454. g_caps.supported |= m_device.supportsFeatureSet( (MTLFeatureSet)11 /* MTLFeatureSet_iOS_GPUFamily4_v1 */)
  455. ? BGFX_CAPS_TEXTURE_CUBE_ARRAY
  456. : 0
  457. ;
  458. }
  459. else if (BX_ENABLED(BX_PLATFORM_OSX) )
  460. {
  461. g_caps.limits.maxTextureSize = 16384;
  462. g_caps.limits.maxFBAttachments = 8;
  463. g_caps.supported |= BGFX_CAPS_TEXTURE_CUBE_ARRAY;
  464. g_caps.supported |= m_device.supportsFeatureSet( (MTLFeatureSet)10001 /* MTLFeatureSet_macOS_GPUFamily1_v2 */)
  465. ? BGFX_CAPS_DRAW_INDIRECT
  466. : 0
  467. ;
  468. }
  469. g_caps.limits.maxTextureLayers = 2048;
  470. g_caps.limits.maxVertexStreams = BGFX_CONFIG_MAX_VERTEX_STREAMS;
  471. // Maximum number of entries in the buffer argument table, per graphics or compute function are 31.
  472. // It is decremented by 1 because 1 entry is used for uniforms.
  473. g_caps.limits.maxComputeBindings = bx::uint32_min(30, BGFX_MAX_COMPUTE_BINDINGS);
  474. m_hasPixelFormatDepth32Float_Stencil8 = false
  475. || BX_ENABLED(BX_PLATFORM_OSX)
  476. || (BX_ENABLED(BX_PLATFORM_IOS) && iOSVersionEqualOrGreater("9.0.0") )
  477. ;
  478. m_hasStoreActionStoreAndMultisampleResolve = false
  479. || (BX_ENABLED(BX_PLATFORM_OSX) && macOSVersionEqualOrGreater(10, 12, 0) )
  480. || (BX_ENABLED(BX_PLATFORM_IOS) && iOSVersionEqualOrGreater("10.0.0") )
  481. ;
  482. m_macOS11Runtime = true
  483. && BX_ENABLED(BX_PLATFORM_OSX)
  484. && macOSVersionEqualOrGreater(10, 11, 0)
  485. ;
  486. m_iOS9Runtime = true
  487. && BX_ENABLED(BX_PLATFORM_IOS)
  488. && iOSVersionEqualOrGreater("9.0.0")
  489. ;
  490. if (BX_ENABLED(BX_PLATFORM_OSX) )
  491. {
  492. s_textureFormat[TextureFormat::R8].m_fmtSrgb = MTLPixelFormatInvalid;
  493. s_textureFormat[TextureFormat::RG8].m_fmtSrgb = MTLPixelFormatInvalid;
  494. }
  495. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  496. {
  497. uint16_t support = 0;
  498. support |= MTLPixelFormatInvalid != s_textureFormat[ii].m_fmt
  499. ? BGFX_CAPS_FORMAT_TEXTURE_2D
  500. | BGFX_CAPS_FORMAT_TEXTURE_3D
  501. | BGFX_CAPS_FORMAT_TEXTURE_CUBE
  502. | BGFX_CAPS_FORMAT_TEXTURE_VERTEX
  503. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  504. ;
  505. support |= MTLPixelFormatInvalid != s_textureFormat[ii].m_fmtSrgb
  506. ? BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB
  507. | BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB
  508. | BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB
  509. | BGFX_CAPS_FORMAT_TEXTURE_VERTEX
  510. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  511. ;
  512. if (!bimg::isCompressed(bimg::TextureFormat::Enum(ii) ) )
  513. {
  514. support |= 0
  515. | BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER
  516. | BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA
  517. ;
  518. }
  519. g_caps.formats[ii] = support;
  520. }
  521. g_caps.formats[TextureFormat::A8 ] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER | BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  522. g_caps.formats[TextureFormat::RG32I ] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  523. g_caps.formats[TextureFormat::RG32U ] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  524. g_caps.formats[TextureFormat::RGBA32I] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  525. g_caps.formats[TextureFormat::RGBA32U] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  526. if (BX_ENABLED(BX_PLATFORM_IOS) )
  527. {
  528. s_textureFormat[TextureFormat::D24S8].m_fmt = MTLPixelFormatDepth32Float_Stencil8;
  529. g_caps.formats[TextureFormat::BC1 ] =
  530. g_caps.formats[TextureFormat::BC2 ] =
  531. g_caps.formats[TextureFormat::BC3 ] =
  532. g_caps.formats[TextureFormat::BC4 ] =
  533. g_caps.formats[TextureFormat::BC5 ] =
  534. g_caps.formats[TextureFormat::BC6H] =
  535. g_caps.formats[TextureFormat::BC7 ] = BGFX_CAPS_FORMAT_TEXTURE_NONE;
  536. g_caps.formats[TextureFormat::RG32F ] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  537. g_caps.formats[TextureFormat::RGBA32F] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  538. }
  539. if (BX_ENABLED(BX_PLATFORM_OSX) )
  540. {
  541. s_textureFormat[TextureFormat::D24S8].m_fmt = (MTLPixelFormat)(m_device.depth24Stencil8PixelFormatSupported()
  542. ? 255 /* Depth24Unorm_Stencil8 */
  543. : MTLPixelFormatDepth32Float_Stencil8)
  544. ;
  545. g_caps.formats[TextureFormat::ETC2 ] =
  546. g_caps.formats[TextureFormat::ETC2A ] =
  547. g_caps.formats[TextureFormat::ETC2A1] =
  548. g_caps.formats[TextureFormat::PTC12 ] =
  549. g_caps.formats[TextureFormat::PTC14 ] =
  550. g_caps.formats[TextureFormat::PTC12A] =
  551. g_caps.formats[TextureFormat::PTC14A] =
  552. g_caps.formats[TextureFormat::R5G6B5] =
  553. g_caps.formats[TextureFormat::RGBA4 ] =
  554. g_caps.formats[TextureFormat::RGB5A1] = BGFX_CAPS_FORMAT_TEXTURE_NONE;
  555. g_caps.formats[TextureFormat::RGB9E5F] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER | BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  556. }
  557. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  558. {
  559. if (BGFX_CAPS_FORMAT_TEXTURE_NONE == g_caps.formats[ii])
  560. {
  561. s_textureFormat[ii].m_fmt = MTLPixelFormatInvalid;
  562. s_textureFormat[ii].m_fmtSrgb = MTLPixelFormatInvalid;
  563. }
  564. }
  565. for (uint32_t ii = 1, last = 0; ii < BX_COUNTOF(s_msaa); ++ii)
  566. {
  567. const int32_t sampleCount = 1<<ii;
  568. if (m_device.supportsTextureSampleCount(sampleCount) )
  569. {
  570. s_msaa[ii] = sampleCount;
  571. last = ii;
  572. }
  573. else
  574. {
  575. s_msaa[ii] = s_msaa[last];
  576. }
  577. }
  578. // Init reserved part of view name.
  579. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  580. {
  581. bx::snprintf(s_viewName[ii], BGFX_CONFIG_MAX_VIEW_NAME_RESERVED+1, "%3d ", ii);
  582. }
  583. m_occlusionQuery.preReset();
  584. m_gpuTimer.init();
  585. g_internalData.context = m_device;
  586. return true;
  587. }
  588. void shutdown()
  589. {
  590. m_occlusionQuery.postReset();
  591. m_gpuTimer.shutdown();
  592. m_pipelineStateCache.invalidate();
  593. m_pipelineProgram.clear();
  594. m_depthStencilStateCache.invalidate();
  595. m_samplerStateCache.invalidate();
  596. for (uint32_t ii = 0; ii < BX_COUNTOF(m_shaders); ++ii)
  597. {
  598. m_shaders[ii].destroy();
  599. }
  600. for (uint32_t ii = 0; ii < BX_COUNTOF(m_textures); ++ii)
  601. {
  602. m_textures[ii].destroy();
  603. }
  604. m_screenshotBlitProgramVsh.destroy();
  605. m_screenshotBlitProgramFsh.destroy();
  606. m_screenshotBlitProgram.destroy();
  607. MTL_RELEASE(m_screenshotBlitRenderPipelineState);
  608. captureFinish();
  609. MTL_RELEASE(m_depthStencilDescriptor);
  610. MTL_RELEASE(m_frontFaceStencilDescriptor);
  611. MTL_RELEASE(m_backFaceStencilDescriptor);
  612. MTL_RELEASE(m_renderPipelineDescriptor);
  613. MTL_RELEASE(m_vertexDescriptor);
  614. MTL_RELEASE(m_textureDescriptor);
  615. MTL_RELEASE(m_samplerDescriptor);
  616. m_mainFrameBuffer.destroy();
  617. for (uint8_t i=0; i < BGFX_CONFIG_MAX_FRAME_LATENCY; ++i)
  618. {
  619. MTL_RELEASE(m_uniformBuffers[i]);
  620. }
  621. m_cmd.shutdown();
  622. MTL_RELEASE(m_device);
  623. }
  624. RendererType::Enum getRendererType() const override
  625. {
  626. return RendererType::Metal;
  627. }
  628. const char* getRendererName() const override
  629. {
  630. return BGFX_RENDERER_METAL_NAME;
  631. }
  632. void createIndexBuffer(IndexBufferHandle _handle, const Memory* _mem, uint16_t _flags) override
  633. {
  634. m_indexBuffers[_handle.idx].create(_mem->size, _mem->data, _flags);
  635. }
  636. void destroyIndexBuffer(IndexBufferHandle _handle) override
  637. {
  638. m_indexBuffers[_handle.idx].destroy();
  639. }
  640. void createVertexLayout(VertexLayoutHandle _handle, const VertexLayout& _layout) override
  641. {
  642. VertexLayout& layout = m_vertexLayouts[_handle.idx];
  643. bx::memCopy(&layout, &_layout, sizeof(VertexLayout) );
  644. dump(layout);
  645. }
  646. void destroyVertexLayout(VertexLayoutHandle /*_handle*/) override
  647. {
  648. }
  649. void createVertexBuffer(VertexBufferHandle _handle, const Memory* _mem, VertexLayoutHandle _layoutHandle, uint16_t _flags) override
  650. {
  651. m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _layoutHandle, _flags);
  652. }
  653. void destroyVertexBuffer(VertexBufferHandle _handle) override
  654. {
  655. m_vertexBuffers[_handle.idx].destroy();
  656. }
  657. void createDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size, uint16_t _flags) override
  658. {
  659. m_indexBuffers[_handle.idx].create(_size, NULL, _flags);
  660. }
  661. void updateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, const Memory* _mem) override
  662. {
  663. m_indexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  664. }
  665. void destroyDynamicIndexBuffer(IndexBufferHandle _handle) override
  666. {
  667. m_indexBuffers[_handle.idx].destroy();
  668. }
  669. void createDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size, uint16_t _flags) override
  670. {
  671. VertexLayoutHandle layoutHandle = BGFX_INVALID_HANDLE;
  672. m_vertexBuffers[_handle.idx].create(_size, NULL, layoutHandle, _flags);
  673. }
  674. void updateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, const Memory* _mem) override
  675. {
  676. m_vertexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  677. }
  678. void destroyDynamicVertexBuffer(VertexBufferHandle _handle) override
  679. {
  680. m_vertexBuffers[_handle.idx].destroy();
  681. }
  682. void createShader(ShaderHandle _handle, const Memory* _mem) override
  683. {
  684. m_shaders[_handle.idx].create(_mem);
  685. }
  686. void destroyShader(ShaderHandle _handle) override
  687. {
  688. m_shaders[_handle.idx].destroy();
  689. }
  690. void createProgram(ProgramHandle _handle, ShaderHandle _vsh, ShaderHandle _fsh) override
  691. {
  692. m_program[_handle.idx].create(&m_shaders[_vsh.idx], isValid(_fsh) ? &m_shaders[_fsh.idx] : NULL);
  693. }
  694. void destroyProgram(ProgramHandle _handle) override
  695. {
  696. for (PipelineProgramArray::iterator it = m_pipelineProgram.begin(); it != m_pipelineProgram.end();)
  697. {
  698. if (it->program.idx == _handle.idx)
  699. {
  700. m_pipelineStateCache.invalidate(it->key);
  701. it = m_pipelineProgram.erase(it);
  702. }
  703. else
  704. {
  705. ++it;
  706. }
  707. }
  708. m_program[_handle.idx].destroy();
  709. }
  710. void* createTexture(TextureHandle _handle, const Memory* _mem, uint64_t _flags, uint8_t _skip) override
  711. {
  712. m_textures[_handle.idx].create(_mem, _flags, _skip);
  713. return NULL;
  714. }
  715. void updateTextureBegin(TextureHandle /*_handle*/, uint8_t /*_side*/, uint8_t /*_mip*/) override
  716. {
  717. }
  718. void updateTexture(TextureHandle _handle, uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem) override
  719. {
  720. m_textures[_handle.idx].update(_side, _mip, _rect, _z, _depth, _pitch, _mem);
  721. }
  722. void updateTextureEnd() override
  723. {
  724. }
  725. void readTexture(TextureHandle _handle, void* _data, uint8_t _mip) override
  726. {
  727. const TextureMtl& texture = m_textures[_handle.idx];
  728. #if BX_PLATFORM_OSX
  729. BlitCommandEncoder bce = s_renderMtl->getBlitCommandEncoder();
  730. bce.synchronizeTexture(texture.m_ptr, 0, _mip);
  731. endEncoding();
  732. #endif // BX_PLATFORM_OSX
  733. m_cmd.kick(false, true);
  734. m_commandBuffer = m_cmd.alloc();
  735. BX_ASSERT(_mip<texture.m_numMips,"Invalid mip: %d num mips:",_mip,texture.m_numMips);
  736. uint32_t srcWidth = bx::uint32_max(1, texture.m_ptr.width() >> _mip);
  737. uint32_t srcHeight = bx::uint32_max(1, texture.m_ptr.height() >> _mip);
  738. const uint8_t bpp = bimg::getBitsPerPixel(bimg::TextureFormat::Enum(texture.m_textureFormat) );
  739. MTLRegion region =
  740. {
  741. { 0, 0, 0 },
  742. { srcWidth, srcHeight, 1 },
  743. };
  744. texture.m_ptr.getBytes(_data, srcWidth*bpp/8, 0, region, _mip, 0);
  745. }
  746. void resizeTexture(TextureHandle _handle, uint16_t _width, uint16_t _height, uint8_t _numMips, uint16_t _numLayers) override
  747. {
  748. TextureMtl& texture = m_textures[_handle.idx];
  749. uint32_t size = sizeof(uint32_t) + sizeof(TextureCreate);
  750. const Memory* mem = alloc(size);
  751. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  752. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  753. bx::write(&writer, magic);
  754. TextureCreate tc;
  755. tc.m_width = _width;
  756. tc.m_height = _height;
  757. tc.m_depth = 0;
  758. tc.m_numLayers = _numLayers;
  759. tc.m_numMips = _numMips;
  760. tc.m_format = TextureFormat::Enum(texture.m_requestedFormat);
  761. tc.m_cubeMap = false;
  762. tc.m_mem = NULL;
  763. bx::write(&writer, tc);
  764. texture.destroy();
  765. texture.create(mem, texture.m_flags, 0);
  766. release(mem);
  767. }
  768. void overrideInternal(TextureHandle _handle, uintptr_t _ptr) override
  769. {
  770. m_textures[_handle.idx].overrideInternal(_ptr);
  771. }
  772. uintptr_t getInternal(TextureHandle _handle) override
  773. {
  774. return uintptr_t(id<MTLTexture>(m_textures[_handle.idx].m_ptr));
  775. }
  776. void destroyTexture(TextureHandle _handle) override
  777. {
  778. m_textures[_handle.idx].destroy();
  779. }
  780. void createFrameBuffer(FrameBufferHandle _handle, uint8_t _num, const Attachment* _attachment) override
  781. {
  782. m_frameBuffers[_handle.idx].create(_num, _attachment);
  783. }
  784. void createFrameBuffer(FrameBufferHandle _handle, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _format, TextureFormat::Enum _depthFormat) override
  785. {
  786. for (uint32_t ii = 0, num = m_numWindows; ii < num; ++ii)
  787. {
  788. FrameBufferHandle handle = m_windows[ii];
  789. if (isValid(handle)
  790. && m_frameBuffers[handle.idx].m_nwh == _nwh)
  791. {
  792. destroyFrameBuffer(handle);
  793. }
  794. }
  795. uint16_t denseIdx = m_numWindows++;
  796. m_windows[denseIdx] = _handle;
  797. FrameBufferMtl& fb = m_frameBuffers[_handle.idx];
  798. fb.create(denseIdx, _nwh, _width, _height, _format, _depthFormat);
  799. fb.m_swapChain->resize(m_frameBuffers[_handle.idx], _width, _height, m_resolution.reset);
  800. }
  801. void destroyFrameBuffer(FrameBufferHandle _handle) override
  802. {
  803. uint16_t denseIdx = m_frameBuffers[_handle.idx].destroy();
  804. if (UINT16_MAX != denseIdx)
  805. {
  806. --m_numWindows;
  807. if (m_numWindows > 1)
  808. {
  809. FrameBufferHandle handle = m_windows[m_numWindows];
  810. m_windows[m_numWindows] = {kInvalidHandle};
  811. if (m_numWindows != denseIdx)
  812. {
  813. m_windows[denseIdx] = handle;
  814. m_frameBuffers[handle.idx].m_denseIdx = denseIdx;
  815. }
  816. }
  817. }
  818. }
  819. void createUniform(UniformHandle _handle, UniformType::Enum _type, uint16_t _num, const char* _name) override
  820. {
  821. if (NULL != m_uniforms[_handle.idx])
  822. {
  823. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  824. }
  825. const uint32_t size = bx::alignUp(g_uniformTypeSize[_type]*_num, 16);
  826. void* data = BX_ALLOC(g_allocator, size);
  827. bx::memSet(data, 0, size);
  828. m_uniforms[_handle.idx] = data;
  829. m_uniformReg.add(_handle, _name);
  830. }
  831. void destroyUniform(UniformHandle _handle) override
  832. {
  833. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  834. m_uniforms[_handle.idx] = NULL;
  835. m_uniformReg.remove(_handle);
  836. }
  837. void requestScreenShot(FrameBufferHandle _handle, const char* _filePath) override
  838. {
  839. BX_UNUSED(_handle);
  840. if (NULL == m_screenshotTarget)
  841. {
  842. return;
  843. }
  844. #if BX_PLATFORM_OSX
  845. m_blitCommandEncoder = getBlitCommandEncoder();
  846. m_blitCommandEncoder.synchronizeResource(m_screenshotTarget);
  847. m_blitCommandEncoder.endEncoding();
  848. m_blitCommandEncoder = 0;
  849. #endif // BX_PLATFORM_OSX
  850. m_cmd.kick(false, true);
  851. m_commandBuffer = 0;
  852. uint32_t width = m_screenshotTarget.width();
  853. uint32_t height = m_screenshotTarget.height();
  854. uint32_t length = width*height*4;
  855. uint8_t* data = (uint8_t*)BX_ALLOC(g_allocator, length);
  856. MTLRegion region = { { 0, 0, 0 }, { width, height, 1 } };
  857. m_screenshotTarget.getBytes(data, 4*width, 0, region, 0, 0);
  858. g_callback->screenShot(
  859. _filePath
  860. , m_screenshotTarget.width()
  861. , m_screenshotTarget.height()
  862. , width*4
  863. , data
  864. , length
  865. , false
  866. );
  867. BX_FREE(g_allocator, data);
  868. m_commandBuffer = m_cmd.alloc();
  869. }
  870. void updateViewName(ViewId _id, const char* _name) override
  871. {
  872. bx::strCopy(
  873. &s_viewName[_id][BGFX_CONFIG_MAX_VIEW_NAME_RESERVED]
  874. , BX_COUNTOF(s_viewName[0])-BGFX_CONFIG_MAX_VIEW_NAME_RESERVED
  875. , _name
  876. );
  877. }
  878. void updateUniform(uint16_t _loc, const void* _data, uint32_t _size) override
  879. {
  880. bx::memCopy(m_uniforms[_loc], _data, _size);
  881. }
  882. void invalidateOcclusionQuery(OcclusionQueryHandle _handle) override
  883. {
  884. m_occlusionQuery.invalidate(_handle);
  885. }
  886. void setMarker(const char* _marker, uint16_t _len) override
  887. {
  888. BX_UNUSED(_len);
  889. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION) )
  890. {
  891. m_renderCommandEncoder.insertDebugSignpost(_marker);
  892. }
  893. }
  894. virtual void setName(Handle _handle, const char* _name, uint16_t _len) override
  895. {
  896. BX_UNUSED(_len);
  897. switch (_handle.type)
  898. {
  899. case Handle::IndexBuffer:
  900. m_indexBuffers[_handle.idx].m_ptr.setLabel(_name);
  901. break;
  902. case Handle::Shader:
  903. m_shaders[_handle.idx].m_function.setLabel(_name);
  904. break;
  905. case Handle::Texture:
  906. m_textures[_handle.idx].m_ptr.setLabel(_name);
  907. break;
  908. case Handle::VertexBuffer:
  909. m_vertexBuffers[_handle.idx].m_ptr.setLabel(_name);
  910. break;
  911. default:
  912. BX_ASSERT(false, "Invalid handle type?! %d", _handle.type);
  913. break;
  914. }
  915. }
  916. void submitBlit(BlitState& _bs, uint16_t _view);
  917. void submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter) override;
  918. void blitSetup(TextVideoMemBlitter& _blitter) override
  919. {
  920. BX_UNUSED(_blitter);
  921. }
  922. void blitRender(TextVideoMemBlitter& _blitter, uint32_t _numIndices) override
  923. {
  924. const uint32_t numVertices = _numIndices*4/6;
  925. if (0 < numVertices)
  926. {
  927. m_indexBuffers [_blitter.m_ib->handle.idx].update(
  928. 0
  929. , bx::strideAlign(_numIndices*2, 4)
  930. , _blitter.m_ib->data
  931. , true
  932. );
  933. m_vertexBuffers[_blitter.m_vb->handle.idx].update(
  934. 0
  935. , numVertices*_blitter.m_layout.m_stride
  936. , _blitter.m_vb->data
  937. , true
  938. );
  939. endEncoding();
  940. uint32_t width = m_resolution.width;
  941. uint32_t height = m_resolution.height;
  942. FrameBufferHandle fbh = BGFX_INVALID_HANDLE;
  943. RenderPassDescriptor renderPassDescriptor = newRenderPassDescriptor();
  944. setFrameBuffer(renderPassDescriptor, fbh);
  945. renderPassDescriptor.colorAttachments[0].loadAction = MTLLoadActionLoad;
  946. renderPassDescriptor.colorAttachments[0].storeAction =
  947. NULL != renderPassDescriptor.colorAttachments[0].resolveTexture
  948. ? MTLStoreActionMultisampleResolve
  949. : MTLStoreActionStore
  950. ;
  951. RenderCommandEncoder rce = m_commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor);
  952. m_renderCommandEncoder = rce;
  953. m_renderCommandEncoderFrameBufferHandle = fbh;
  954. MTL_RELEASE(renderPassDescriptor);
  955. MTLViewport viewport = { 0.0f, 0.0f, (float)width, (float)height, 0.0f, 1.0f};
  956. rce.setViewport(viewport);
  957. MTLScissorRect rc = { 0,0,width,height };
  958. rce.setScissorRect(rc);
  959. rce.setCullMode(MTLCullModeNone);
  960. uint64_t state = 0
  961. | BGFX_STATE_WRITE_RGB
  962. | BGFX_STATE_WRITE_A
  963. | BGFX_STATE_DEPTH_TEST_ALWAYS
  964. ;
  965. setDepthStencilState(state);
  966. PipelineStateMtl* pso = getPipelineState(
  967. state
  968. , 0
  969. , fbh
  970. , _blitter.m_vb->layoutHandle
  971. , _blitter.m_program
  972. , 0
  973. );
  974. rce.setRenderPipelineState(pso->m_rps);
  975. const uint32_t vertexUniformBufferSize = pso->m_vshConstantBufferSize;
  976. const uint32_t fragmentUniformBufferSize = pso->m_fshConstantBufferSize;
  977. if (vertexUniformBufferSize)
  978. {
  979. m_uniformBufferVertexOffset = bx::alignUp(
  980. m_uniformBufferVertexOffset
  981. , pso->m_vshConstantBufferAlignment
  982. );
  983. rce.setVertexBuffer(m_uniformBuffer, m_uniformBufferVertexOffset, 0);
  984. }
  985. m_uniformBufferFragmentOffset = m_uniformBufferVertexOffset + vertexUniformBufferSize;
  986. if (0 != fragmentUniformBufferSize)
  987. {
  988. m_uniformBufferFragmentOffset = bx::alignUp(
  989. m_uniformBufferFragmentOffset
  990. , pso->m_fshConstantBufferAlignment
  991. );
  992. rce.setFragmentBuffer(m_uniformBuffer, m_uniformBufferFragmentOffset, 0);
  993. }
  994. float proj[16];
  995. bx::mtxOrtho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f, 0.0f, false);
  996. PredefinedUniform& predefined = pso->m_predefined[0];
  997. uint8_t flags = predefined.m_type;
  998. setShaderUniform(flags, predefined.m_loc, proj, 4);
  999. m_textures[_blitter.m_texture.idx].commit(0, false, true);
  1000. VertexBufferMtl& vb = m_vertexBuffers[_blitter.m_vb->handle.idx];
  1001. m_renderCommandEncoder.setVertexBuffer(vb.m_ptr, 0, 1);
  1002. m_renderCommandEncoder.drawIndexedPrimitives(
  1003. MTLPrimitiveTypeTriangle
  1004. , _numIndices
  1005. , MTLIndexTypeUInt16
  1006. , m_indexBuffers[_blitter.m_ib->handle.idx].m_ptr
  1007. , 0
  1008. , 1
  1009. );
  1010. }
  1011. }
  1012. bool isDeviceRemoved() override
  1013. {
  1014. return false;
  1015. }
  1016. void flip() override
  1017. {
  1018. if (NULL == m_commandBuffer)
  1019. {
  1020. return;
  1021. }
  1022. for (uint32_t ii = 0, num = m_numWindows; ii < num; ++ii)
  1023. {
  1024. FrameBufferMtl& frameBuffer = ii == 0 ? m_mainFrameBuffer : m_frameBuffers[m_windows[ii].idx];
  1025. if (NULL != frameBuffer.m_swapChain
  1026. && frameBuffer.m_swapChain->m_drawableTexture)
  1027. {
  1028. MTL_RELEASE(frameBuffer.m_swapChain->m_drawableTexture);
  1029. if (NULL != frameBuffer.m_swapChain->m_drawable)
  1030. {
  1031. m_commandBuffer.presentDrawable(frameBuffer.m_swapChain->m_drawable);
  1032. MTL_RELEASE(frameBuffer.m_swapChain->m_drawable);
  1033. }
  1034. }
  1035. }
  1036. m_cmd.kick(true);
  1037. m_commandBuffer = 0;
  1038. }
  1039. void updateResolution(const Resolution& _resolution)
  1040. {
  1041. m_mainFrameBuffer.m_swapChain->m_maxAnisotropy = !!(_resolution.reset & BGFX_RESET_MAXANISOTROPY)
  1042. ? 16
  1043. : 1
  1044. ;
  1045. const uint32_t maskFlags = ~(0
  1046. | BGFX_RESET_MAXANISOTROPY
  1047. | BGFX_RESET_DEPTH_CLAMP
  1048. | BGFX_RESET_SUSPEND
  1049. );
  1050. if (m_resolution.width != _resolution.width
  1051. || m_resolution.height != _resolution.height
  1052. || (m_resolution.reset&maskFlags) != (_resolution.reset&maskFlags) )
  1053. {
  1054. MTLPixelFormat prevMetalLayerPixelFormat = m_mainFrameBuffer.m_swapChain->m_metalLayer.pixelFormat;
  1055. m_resolution = _resolution;
  1056. if (m_resolution.reset & BGFX_RESET_INTERNAL_FORCE
  1057. && m_mainFrameBuffer.m_swapChain->m_nwh != g_platformData.nwh)
  1058. {
  1059. m_mainFrameBuffer.m_swapChain->init(g_platformData.nwh);
  1060. }
  1061. m_resolution.reset &= ~BGFX_RESET_INTERNAL_FORCE;
  1062. m_mainFrameBuffer.m_swapChain->resize(m_mainFrameBuffer, _resolution.width, _resolution.height, _resolution.reset);
  1063. for (uint32_t ii = 0; ii < BX_COUNTOF(m_frameBuffers); ++ii)
  1064. {
  1065. m_frameBuffers[ii].postReset();
  1066. }
  1067. updateCapture();
  1068. m_textVideoMem.resize(false, _resolution.width, _resolution.height);
  1069. m_textVideoMem.clear();
  1070. if (prevMetalLayerPixelFormat != m_mainFrameBuffer.m_swapChain->m_metalLayer.pixelFormat)
  1071. {
  1072. MTL_RELEASE(m_screenshotBlitRenderPipelineState)
  1073. reset(m_renderPipelineDescriptor);
  1074. m_renderPipelineDescriptor.colorAttachments[0].pixelFormat = m_mainFrameBuffer.m_swapChain->m_metalLayer.pixelFormat;
  1075. m_renderPipelineDescriptor.vertexFunction = m_screenshotBlitProgram.m_vsh->m_function;
  1076. m_renderPipelineDescriptor.fragmentFunction = m_screenshotBlitProgram.m_fsh->m_function;
  1077. m_screenshotBlitRenderPipelineState = m_device.newRenderPipelineStateWithDescriptor(m_renderPipelineDescriptor);
  1078. }
  1079. }
  1080. }
  1081. void invalidateCompute()
  1082. {
  1083. if (m_computeCommandEncoder)
  1084. {
  1085. m_computeCommandEncoder.endEncoding();
  1086. m_computeCommandEncoder = NULL;
  1087. }
  1088. }
  1089. void updateCapture()
  1090. {
  1091. if (m_resolution.reset&BGFX_RESET_CAPTURE)
  1092. {
  1093. m_captureSize = m_resolution.width*m_resolution.height*4;
  1094. m_capture = BX_REALLOC(g_allocator, m_capture, m_captureSize);
  1095. g_callback->captureBegin(m_resolution.width, m_resolution.height, m_resolution.width*4, TextureFormat::BGRA8, false);
  1096. }
  1097. else
  1098. {
  1099. captureFinish();
  1100. }
  1101. }
  1102. void capture()
  1103. {
  1104. if (NULL != m_capture)
  1105. {
  1106. if (NULL == m_screenshotTarget)
  1107. {
  1108. return;
  1109. }
  1110. m_renderCommandEncoder.endEncoding();
  1111. m_cmd.kick(false, true);
  1112. m_commandBuffer = 0;
  1113. MTLRegion region = { { 0, 0, 0 }, { m_resolution.width, m_resolution.height, 1 } };
  1114. m_screenshotTarget.getBytes(m_capture, 4*m_resolution.width, 0, region, 0, 0);
  1115. m_commandBuffer = m_cmd.alloc();
  1116. if (m_screenshotTarget.pixelFormat() == MTLPixelFormatRGBA8Uint)
  1117. {
  1118. bimg::imageSwizzleBgra8(
  1119. m_capture
  1120. , m_resolution.width*4
  1121. , m_resolution.width
  1122. , m_resolution.height
  1123. , m_capture
  1124. , m_resolution.width*4
  1125. );
  1126. }
  1127. g_callback->captureFrame(m_capture, m_captureSize);
  1128. RenderPassDescriptor renderPassDescriptor = newRenderPassDescriptor();
  1129. setFrameBuffer(renderPassDescriptor, m_renderCommandEncoderFrameBufferHandle);
  1130. for (uint32_t ii = 0; ii < g_caps.limits.maxFBAttachments; ++ii)
  1131. {
  1132. MTLRenderPassColorAttachmentDescriptor* desc = renderPassDescriptor.colorAttachments[ii];
  1133. if (NULL != desc.texture)
  1134. {
  1135. desc.loadAction = MTLLoadActionLoad;
  1136. desc.storeAction = desc.resolveTexture == nil
  1137. ? MTLStoreActionStore
  1138. : MTLStoreActionMultisampleResolve
  1139. ;
  1140. }
  1141. }
  1142. RenderPassDepthAttachmentDescriptor depthAttachment = renderPassDescriptor.depthAttachment;
  1143. if (NULL != depthAttachment.texture)
  1144. {
  1145. depthAttachment.loadAction = MTLLoadActionLoad;
  1146. depthAttachment.storeAction = depthAttachment.resolveTexture == nil
  1147. ? MTLStoreActionStore
  1148. : MTLStoreActionMultisampleResolve
  1149. ;
  1150. }
  1151. RenderPassStencilAttachmentDescriptor stencilAttachment = renderPassDescriptor.stencilAttachment;
  1152. if (NULL != stencilAttachment.texture)
  1153. {
  1154. stencilAttachment.loadAction = MTLLoadActionLoad;
  1155. stencilAttachment.storeAction = stencilAttachment.resolveTexture == nil
  1156. ? MTLStoreActionStore
  1157. : MTLStoreActionMultisampleResolve
  1158. ;
  1159. }
  1160. m_renderCommandEncoder = m_commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor);
  1161. MTL_RELEASE(renderPassDescriptor);
  1162. }
  1163. }
  1164. void captureFinish()
  1165. {
  1166. if (NULL != m_capture)
  1167. {
  1168. g_callback->captureEnd();
  1169. BX_FREE(g_allocator, m_capture);
  1170. m_capture = NULL;
  1171. m_captureSize = 0;
  1172. }
  1173. }
  1174. void setShaderUniform(uint8_t _flags, uint32_t _loc, const void* _val, uint32_t _numRegs)
  1175. {
  1176. uint32_t offset = 0 != (_flags&kUniformFragmentBit)
  1177. ? m_uniformBufferFragmentOffset
  1178. : m_uniformBufferVertexOffset
  1179. ;
  1180. uint8_t* dst = (uint8_t*)m_uniformBuffer.contents();
  1181. bx::memCopy(&dst[offset + _loc], _val, _numRegs*16);
  1182. }
  1183. void setShaderUniform4f(uint8_t _flags, uint32_t _loc, const void* _val, uint32_t _numRegs)
  1184. {
  1185. setShaderUniform(_flags, _loc, _val, _numRegs);
  1186. }
  1187. void setShaderUniform4x4f(uint8_t _flags, uint32_t _loc, const void* _val, uint32_t _numRegs)
  1188. {
  1189. setShaderUniform(_flags, _loc, _val, _numRegs);
  1190. }
  1191. void commit(UniformBuffer& _uniformBuffer)
  1192. {
  1193. _uniformBuffer.reset();
  1194. for (;;)
  1195. {
  1196. uint32_t opcode = _uniformBuffer.read();
  1197. if (UniformType::End == opcode)
  1198. {
  1199. break;
  1200. }
  1201. UniformType::Enum type;
  1202. uint16_t loc;
  1203. uint16_t num;
  1204. uint16_t copy;
  1205. UniformBuffer::decodeOpcode(opcode, type, loc, num, copy);
  1206. const char* data;
  1207. if (copy)
  1208. {
  1209. data = _uniformBuffer.read(g_uniformTypeSize[type]*num);
  1210. }
  1211. else
  1212. {
  1213. UniformHandle handle;
  1214. bx::memCopy(&handle, _uniformBuffer.read(sizeof(UniformHandle) ), sizeof(UniformHandle) );
  1215. data = (const char*)m_uniforms[handle.idx];
  1216. }
  1217. #define CASE_IMPLEMENT_UNIFORM(_uniform, _dxsuffix, _type) \
  1218. case UniformType::_uniform: \
  1219. case UniformType::_uniform|kUniformFragmentBit: \
  1220. { \
  1221. setShaderUniform(uint8_t(type), loc, data, num); \
  1222. } \
  1223. break;
  1224. switch ( (uint32_t)type)
  1225. {
  1226. case UniformType::Mat3:
  1227. case UniformType::Mat3|kUniformFragmentBit:
  1228. {
  1229. float* value = (float*)data;
  1230. for (uint32_t ii = 0, count = num/3; ii < count; ++ii, loc += 3*16, value += 9)
  1231. {
  1232. Matrix4 mtx;
  1233. mtx.un.val[ 0] = value[0];
  1234. mtx.un.val[ 1] = value[1];
  1235. mtx.un.val[ 2] = value[2];
  1236. mtx.un.val[ 3] = 0.0f;
  1237. mtx.un.val[ 4] = value[3];
  1238. mtx.un.val[ 5] = value[4];
  1239. mtx.un.val[ 6] = value[5];
  1240. mtx.un.val[ 7] = 0.0f;
  1241. mtx.un.val[ 8] = value[6];
  1242. mtx.un.val[ 9] = value[7];
  1243. mtx.un.val[10] = value[8];
  1244. mtx.un.val[11] = 0.0f;
  1245. setShaderUniform(uint8_t(type), loc, &mtx.un.val[0], 3);
  1246. }
  1247. }
  1248. break;
  1249. CASE_IMPLEMENT_UNIFORM(Sampler, I, int);
  1250. CASE_IMPLEMENT_UNIFORM(Vec4, F, float);
  1251. CASE_IMPLEMENT_UNIFORM(Mat4, F, float);
  1252. case UniformType::End:
  1253. break;
  1254. default:
  1255. BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", _uniformBuffer.getPos(), opcode, type, loc, num, copy);
  1256. break;
  1257. }
  1258. #undef CASE_IMPLEMENT_UNIFORM
  1259. }
  1260. }
  1261. void clearQuad(ClearQuad& _clearQuad, const Rect& /*_rect*/, const Clear& _clear, const float _palette[][4])
  1262. {
  1263. uint32_t width;
  1264. uint32_t height;
  1265. if (isValid(m_fbh) )
  1266. {
  1267. const FrameBufferMtl& fb = m_frameBuffers[m_fbh.idx];
  1268. width = fb.m_width;
  1269. height = fb.m_height;
  1270. }
  1271. else
  1272. {
  1273. width = m_resolution.width;
  1274. height = m_resolution.height;
  1275. }
  1276. uint64_t state = 0;
  1277. state |= _clear.m_flags & BGFX_CLEAR_COLOR ? BGFX_STATE_WRITE_RGB|BGFX_STATE_WRITE_A : 0;
  1278. state |= _clear.m_flags & BGFX_CLEAR_DEPTH ? BGFX_STATE_DEPTH_TEST_ALWAYS|BGFX_STATE_WRITE_Z : 0;
  1279. uint64_t stencil = 0;
  1280. stencil |= _clear.m_flags & BGFX_CLEAR_STENCIL ? 0
  1281. | BGFX_STENCIL_TEST_ALWAYS
  1282. | BGFX_STENCIL_FUNC_REF(_clear.m_stencil)
  1283. | BGFX_STENCIL_FUNC_RMASK(0xff)
  1284. | BGFX_STENCIL_OP_FAIL_S_REPLACE
  1285. | BGFX_STENCIL_OP_FAIL_Z_REPLACE
  1286. | BGFX_STENCIL_OP_PASS_Z_REPLACE
  1287. : 0
  1288. ;
  1289. setDepthStencilState(state, stencil);
  1290. uint32_t numMrt = 1;
  1291. FrameBufferHandle fbh = m_fbh;
  1292. if (isValid(fbh) && m_frameBuffers[fbh.idx].m_swapChain == NULL)
  1293. {
  1294. const FrameBufferMtl& fb = m_frameBuffers[fbh.idx];
  1295. numMrt = bx::uint32_max(1, fb.m_num);
  1296. }
  1297. const VertexLayout* layout = &_clearQuad.m_layout;
  1298. const PipelineStateMtl* pso = getPipelineState(
  1299. state
  1300. , 0
  1301. , fbh
  1302. , 1
  1303. , &layout
  1304. , _clearQuad.m_program[numMrt-1]
  1305. , 0
  1306. );
  1307. m_renderCommandEncoder.setRenderPipelineState(pso->m_rps);
  1308. const uint32_t vertexUniformBufferSize = pso->m_vshConstantBufferSize;
  1309. const uint32_t fragmentUniformBufferSize = pso->m_fshConstantBufferSize;
  1310. if (0 != vertexUniformBufferSize)
  1311. {
  1312. m_uniformBufferVertexOffset = bx::alignUp(
  1313. m_uniformBufferVertexOffset
  1314. , pso->m_vshConstantBufferAlignment
  1315. );
  1316. m_renderCommandEncoder.setVertexBuffer(m_uniformBuffer, m_uniformBufferVertexOffset, 0);
  1317. }
  1318. m_uniformBufferFragmentOffset = m_uniformBufferVertexOffset + vertexUniformBufferSize;
  1319. if (fragmentUniformBufferSize)
  1320. {
  1321. m_uniformBufferFragmentOffset = bx::alignUp(
  1322. m_uniformBufferFragmentOffset
  1323. , pso->m_fshConstantBufferAlignment
  1324. );
  1325. m_renderCommandEncoder.setFragmentBuffer(m_uniformBuffer, m_uniformBufferFragmentOffset, 0);
  1326. }
  1327. float mrtClearColor[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS][4];
  1328. float mrtClearDepth[4] = { _clear.m_depth };
  1329. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  1330. {
  1331. for (uint32_t ii = 0; ii < numMrt; ++ii)
  1332. {
  1333. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE-1, _clear.m_index[ii]);
  1334. bx::memCopy(mrtClearColor[ii], _palette[index], 16);
  1335. }
  1336. }
  1337. else
  1338. {
  1339. float rgba[4] =
  1340. {
  1341. _clear.m_index[0]*1.0f/255.0f,
  1342. _clear.m_index[1]*1.0f/255.0f,
  1343. _clear.m_index[2]*1.0f/255.0f,
  1344. _clear.m_index[3]*1.0f/255.0f,
  1345. };
  1346. for (uint32_t ii = 0; ii < numMrt; ++ii)
  1347. {
  1348. bx::memCopy(mrtClearColor[ii], rgba, 16);
  1349. }
  1350. }
  1351. bx::memCopy(
  1352. (uint8_t*)m_uniformBuffer.contents() + m_uniformBufferVertexOffset
  1353. , mrtClearDepth
  1354. , bx::uint32_min(vertexUniformBufferSize, sizeof(mrtClearDepth) )
  1355. );
  1356. bx::memCopy(
  1357. (uint8_t*)m_uniformBuffer.contents() + m_uniformBufferFragmentOffset
  1358. , mrtClearColor
  1359. , bx::uint32_min(fragmentUniformBufferSize, sizeof(mrtClearColor) )
  1360. );
  1361. m_uniformBufferFragmentOffset += fragmentUniformBufferSize;
  1362. m_uniformBufferVertexOffset = m_uniformBufferFragmentOffset;
  1363. const VertexBufferMtl& vb = m_vertexBuffers[_clearQuad.m_vb.idx];
  1364. m_renderCommandEncoder.setCullMode(MTLCullModeNone);
  1365. m_renderCommandEncoder.setVertexBuffer(vb.m_ptr, 0, 1);
  1366. m_renderCommandEncoder.drawPrimitives(MTLPrimitiveTypeTriangleStrip, 0, 4, 1);
  1367. }
  1368. void setAttachment(MTLRenderPassAttachmentDescriptor* _attachmentDescriptor, const Attachment& _at, uint8_t _textureType, bool _resolve)
  1369. {
  1370. _attachmentDescriptor.level = _at.mip;
  1371. if (TextureMtl::Texture3D == _textureType)
  1372. {
  1373. _attachmentDescriptor.depthPlane = _at.layer;
  1374. }
  1375. else
  1376. {
  1377. _attachmentDescriptor.slice = _at.layer;
  1378. }
  1379. if (_resolve)
  1380. {
  1381. _attachmentDescriptor.resolveLevel = _at.mip;
  1382. if (TextureMtl::Texture3D == _textureType)
  1383. {
  1384. _attachmentDescriptor.resolveDepthPlane = _at.layer;
  1385. }
  1386. else
  1387. {
  1388. _attachmentDescriptor.resolveSlice = _at.layer;
  1389. }
  1390. }
  1391. }
  1392. void setFrameBuffer(RenderPassDescriptor _renderPassDescriptor, FrameBufferHandle _fbh, bool _msaa = true)
  1393. {
  1394. if (!isValid(_fbh)
  1395. || m_frameBuffers[_fbh.idx].m_swapChain)
  1396. {
  1397. SwapChainMtl* swapChain = !isValid(_fbh)
  1398. ? m_mainFrameBuffer.m_swapChain
  1399. : m_frameBuffers[_fbh.idx].m_swapChain
  1400. ;
  1401. if (NULL != swapChain->m_backBufferColorMsaa)
  1402. {
  1403. _renderPassDescriptor.colorAttachments[0].texture = swapChain->m_backBufferColorMsaa;
  1404. _renderPassDescriptor.colorAttachments[0].resolveTexture = NULL != m_screenshotTarget
  1405. ? m_screenshotTarget.m_obj
  1406. : swapChain->currentDrawableTexture()
  1407. ;
  1408. }
  1409. else
  1410. {
  1411. _renderPassDescriptor.colorAttachments[0].texture = NULL != m_screenshotTarget
  1412. ? m_screenshotTarget.m_obj
  1413. : swapChain->currentDrawableTexture()
  1414. ;
  1415. }
  1416. _renderPassDescriptor.depthAttachment.texture = swapChain->m_backBufferDepth;
  1417. _renderPassDescriptor.stencilAttachment.texture = swapChain->m_backBufferStencil;
  1418. }
  1419. else
  1420. {
  1421. FrameBufferMtl& frameBuffer = m_frameBuffers[_fbh.idx];
  1422. for (uint32_t ii = 0; ii < frameBuffer.m_num; ++ii)
  1423. {
  1424. const TextureMtl& texture = m_textures[frameBuffer.m_colorHandle[ii].idx];
  1425. _renderPassDescriptor.colorAttachments[ii].texture = texture.m_ptrMsaa
  1426. ? texture.m_ptrMsaa
  1427. : texture.m_ptr
  1428. ;
  1429. _renderPassDescriptor.colorAttachments[ii].resolveTexture = texture.m_ptrMsaa
  1430. ? texture.m_ptr.m_obj
  1431. : NULL
  1432. ;
  1433. setAttachment(_renderPassDescriptor.colorAttachments[ii], frameBuffer.m_colorAttachment[ii], texture.m_type, texture.m_ptrMsaa != NULL);
  1434. }
  1435. if (isValid(frameBuffer.m_depthHandle) )
  1436. {
  1437. const TextureMtl& texture = m_textures[frameBuffer.m_depthHandle.idx];
  1438. _renderPassDescriptor.depthAttachment.texture = texture.m_ptrMsaa
  1439. ? texture.m_ptrMsaa
  1440. : texture.m_ptr
  1441. ;
  1442. _renderPassDescriptor.stencilAttachment.texture = texture.m_ptrStencil;
  1443. setAttachment(_renderPassDescriptor.depthAttachment, frameBuffer.m_depthAttachment, texture.m_type, NULL != texture.m_ptrMsaa);
  1444. setAttachment(_renderPassDescriptor.stencilAttachment, frameBuffer.m_depthAttachment, texture.m_type, NULL != texture.m_ptrMsaa);
  1445. if (texture.m_textureFormat == TextureFormat::D24S8)
  1446. {
  1447. if (texture.m_ptr.pixelFormat() == 255 /* Depth24Unorm_Stencil8 */
  1448. || texture.m_ptr.pixelFormat() == 260 /* Depth32Float_Stencil8 */)
  1449. {
  1450. _renderPassDescriptor.stencilAttachment.texture = _renderPassDescriptor.depthAttachment.texture;
  1451. }
  1452. else
  1453. {
  1454. _renderPassDescriptor.stencilAttachment.texture = texture.m_ptrMsaa
  1455. ? texture.m_ptrMsaa
  1456. : texture.m_ptrStencil
  1457. ;
  1458. }
  1459. }
  1460. }
  1461. }
  1462. m_fbh = _fbh;
  1463. m_rtMsaa = _msaa;
  1464. }
  1465. void setDepthStencilState(uint64_t _state, uint64_t _stencil = 0)
  1466. {
  1467. _state &= BGFX_STATE_WRITE_Z|BGFX_STATE_DEPTH_TEST_MASK;
  1468. uint32_t fstencil = unpackStencil(0, _stencil);
  1469. uint32_t ref = (fstencil&BGFX_STENCIL_FUNC_REF_MASK)>>BGFX_STENCIL_FUNC_REF_SHIFT;
  1470. _stencil &= packStencil(~BGFX_STENCIL_FUNC_REF_MASK, ~BGFX_STENCIL_FUNC_REF_MASK);
  1471. bx::HashMurmur2A murmur;
  1472. murmur.begin();
  1473. murmur.add(_state);
  1474. murmur.add(_stencil);
  1475. uint32_t hash = murmur.end();
  1476. DepthStencilState dss = m_depthStencilStateCache.find(hash);
  1477. if (NULL == dss)
  1478. {
  1479. DepthStencilDescriptor desc = m_depthStencilDescriptor;
  1480. uint32_t func = (_state&BGFX_STATE_DEPTH_TEST_MASK)>>BGFX_STATE_DEPTH_TEST_SHIFT;
  1481. desc.depthWriteEnabled = !!(BGFX_STATE_WRITE_Z & _state);
  1482. desc.depthCompareFunction = s_cmpFunc[func];
  1483. uint32_t bstencil = unpackStencil(1, _stencil);
  1484. uint32_t frontAndBack = bstencil != BGFX_STENCIL_NONE && bstencil != fstencil;
  1485. bstencil = frontAndBack ? bstencil : fstencil;
  1486. if (0 != _stencil)
  1487. {
  1488. StencilDescriptor frontFaceDesc = m_frontFaceStencilDescriptor;
  1489. StencilDescriptor backfaceDesc = m_backFaceStencilDescriptor;
  1490. uint32_t readMask = (fstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  1491. uint32_t writeMask = 0xff;
  1492. frontFaceDesc.stencilFailureOperation = s_stencilOp[(fstencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT];
  1493. frontFaceDesc.depthFailureOperation = s_stencilOp[(fstencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT];
  1494. frontFaceDesc.depthStencilPassOperation = s_stencilOp[(fstencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT];
  1495. frontFaceDesc.stencilCompareFunction = s_cmpFunc[(fstencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT];
  1496. frontFaceDesc.readMask = readMask;
  1497. frontFaceDesc.writeMask = writeMask;
  1498. backfaceDesc.stencilFailureOperation = s_stencilOp[(bstencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT];
  1499. backfaceDesc.depthFailureOperation = s_stencilOp[(bstencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT];
  1500. backfaceDesc.depthStencilPassOperation = s_stencilOp[(bstencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT];
  1501. backfaceDesc.stencilCompareFunction = s_cmpFunc[(bstencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT];
  1502. backfaceDesc.readMask = readMask;
  1503. backfaceDesc.writeMask = writeMask;
  1504. desc.frontFaceStencil = frontFaceDesc;
  1505. desc.backFaceStencil = backfaceDesc;
  1506. }
  1507. else
  1508. {
  1509. desc.backFaceStencil = NULL;
  1510. desc.frontFaceStencil = NULL;
  1511. }
  1512. dss = m_device.newDepthStencilStateWithDescriptor(desc);
  1513. m_depthStencilStateCache.add(hash, dss);
  1514. }
  1515. m_renderCommandEncoder.setDepthStencilState(dss);
  1516. m_renderCommandEncoder.setStencilReferenceValue(ref);
  1517. }
  1518. void processArguments(
  1519. PipelineStateMtl* ps
  1520. , NSArray <MTLArgument *>* _vertexArgs
  1521. , NSArray <MTLArgument *>* _fragmentArgs
  1522. )
  1523. {
  1524. ps->m_numPredefined = 0;
  1525. for (uint32_t shaderType = 0; shaderType < 2; ++shaderType)
  1526. {
  1527. UniformBuffer*& constantBuffer = shaderType == 0
  1528. ? ps->m_vshConstantBuffer
  1529. : ps->m_fshConstantBuffer
  1530. ;
  1531. const int8_t fragmentBit = (1 == shaderType ? kUniformFragmentBit : 0);
  1532. for (MTLArgument* arg in (shaderType == 0 ? _vertexArgs : _fragmentArgs) )
  1533. {
  1534. BX_TRACE("arg: %s type:%d", utf8String(arg.name), arg.type);
  1535. if (arg.active)
  1536. {
  1537. if (arg.type == MTLArgumentTypeBuffer
  1538. && 0 == bx::strCmp(utf8String(arg.name), SHADER_UNIFORM_NAME) )
  1539. {
  1540. BX_ASSERT(arg.index == 0, "Uniform buffer must be in the buffer slot 0.");
  1541. BX_ASSERT(MTLDataTypeStruct == arg.bufferDataType, "%s's type must be a struct",SHADER_UNIFORM_NAME );
  1542. if (MTLDataTypeStruct == arg.bufferDataType)
  1543. {
  1544. if (shaderType == 0)
  1545. {
  1546. ps->m_vshConstantBufferSize = uint32_t(arg.bufferDataSize);
  1547. ps->m_vshConstantBufferAlignment = uint32_t(arg.bufferAlignment);
  1548. }
  1549. else
  1550. {
  1551. ps->m_fshConstantBufferSize = uint32_t(arg.bufferDataSize);
  1552. ps->m_fshConstantBufferAlignment = uint32_t(arg.bufferAlignment);
  1553. }
  1554. for (MTLStructMember* uniform in arg.bufferStructType.members )
  1555. {
  1556. const char* name = utf8String(uniform.name);
  1557. BX_TRACE("uniform: %s type:%d", name, uniform.dataType);
  1558. MTLDataType dataType = uniform.dataType;
  1559. uint32_t num = 1;
  1560. if (dataType == MTLDataTypeArray)
  1561. {
  1562. dataType = uniform.arrayType.elementType;
  1563. num = (uint32_t)uniform.arrayType.arrayLength;
  1564. }
  1565. switch (dataType)
  1566. {
  1567. case MTLDataTypeFloat4: num *= 1; break;
  1568. case MTLDataTypeFloat4x4: num *= 4; break;
  1569. case MTLDataTypeFloat3x3: num *= 3; break;
  1570. default:
  1571. BX_WARN(0, "Unsupported uniform MTLDataType: %d", uniform.dataType);
  1572. break;
  1573. }
  1574. const PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name);
  1575. if (PredefinedUniform::Count != predefined)
  1576. {
  1577. ps->m_predefined[ps->m_numPredefined].m_loc = uint32_t(uniform.offset);
  1578. ps->m_predefined[ps->m_numPredefined].m_count = uint16_t(num);
  1579. ps->m_predefined[ps->m_numPredefined].m_type = uint8_t(predefined|fragmentBit);
  1580. ++ps->m_numPredefined;
  1581. }
  1582. else
  1583. {
  1584. const UniformRegInfo* info = s_renderMtl->m_uniformReg.find(name);
  1585. BX_WARN(NULL != info, "User defined uniform '%s' is not found, it won't be set.", name);
  1586. if (NULL != info)
  1587. {
  1588. if (NULL == constantBuffer)
  1589. {
  1590. constantBuffer = UniformBuffer::create(1024);
  1591. }
  1592. UniformType::Enum type = convertMtlType(dataType);
  1593. constantBuffer->writeUniformHandle( (UniformType::Enum)(type|fragmentBit), uint32_t(uniform.offset), info->m_handle, uint16_t(num) );
  1594. BX_TRACE("store %s %d offset:%d", name, info->m_handle, uint32_t(uniform.offset) );
  1595. }
  1596. }
  1597. }
  1598. }
  1599. }
  1600. else if (arg.type == MTLArgumentTypeBuffer
  1601. && arg.index > 0
  1602. && NULL != arg.bufferStructType)
  1603. {
  1604. const char* name = utf8String(arg.name);
  1605. if (arg.index >= BGFX_CONFIG_MAX_TEXTURE_SAMPLERS)
  1606. {
  1607. BX_WARN(false, "Binding index is too large %d max is %d. User defined uniform '%s' won't be set.", int(arg.index - 1), BGFX_CONFIG_MAX_TEXTURE_SAMPLERS - 1, name);
  1608. }
  1609. else
  1610. {
  1611. ps->m_bindingTypes[arg.index-1] = fragmentBit ? PipelineStateMtl::BindToFragmentShader : PipelineStateMtl::BindToVertexShader;
  1612. BX_TRACE("buffer %s index:%d", name, uint32_t(arg.index-1) );
  1613. }
  1614. }
  1615. else if (arg.type == MTLArgumentTypeTexture)
  1616. {
  1617. const char* name = utf8String(arg.name);
  1618. const UniformRegInfo* info = s_renderMtl->m_uniformReg.find(name);
  1619. BX_WARN(NULL != info, "User defined uniform '%s' is not found, it won't be set.", name);
  1620. if (NULL != info)
  1621. {
  1622. if (arg.index >= BGFX_CONFIG_MAX_TEXTURE_SAMPLERS)
  1623. {
  1624. BX_WARN(false, "Binding index is too large %d max is %d. User defined uniform '%s' won't be set.", int(arg.index), BGFX_CONFIG_MAX_TEXTURE_SAMPLERS - 1, name);
  1625. }
  1626. else
  1627. {
  1628. ps->m_bindingTypes[arg.index] = fragmentBit ? PipelineStateMtl::BindToFragmentShader : PipelineStateMtl::BindToVertexShader;
  1629. BX_TRACE("texture %s %d index:%d", name, info->m_handle, uint32_t(arg.index) );
  1630. }
  1631. }
  1632. }
  1633. else if (arg.type == MTLArgumentTypeSampler)
  1634. {
  1635. BX_TRACE("sampler: %s index:%d", utf8String(arg.name), arg.index);
  1636. }
  1637. }
  1638. }
  1639. if (NULL != constantBuffer)
  1640. {
  1641. constantBuffer->finish();
  1642. }
  1643. }
  1644. }
  1645. PipelineStateMtl* getPipelineState(
  1646. uint64_t _state
  1647. , uint32_t _rgba
  1648. , FrameBufferHandle _fbh
  1649. , uint8_t _numStreams
  1650. , const VertexLayout** _layouts
  1651. , ProgramHandle _program
  1652. , uint8_t _numInstanceData
  1653. )
  1654. {
  1655. _state &= (0
  1656. | BGFX_STATE_BLEND_MASK
  1657. | BGFX_STATE_BLEND_EQUATION_MASK
  1658. | BGFX_STATE_WRITE_RGB
  1659. | BGFX_STATE_WRITE_A
  1660. | BGFX_STATE_BLEND_INDEPENDENT
  1661. | BGFX_STATE_MSAA
  1662. | BGFX_STATE_BLEND_ALPHA_TO_COVERAGE
  1663. );
  1664. const bool independentBlendEnable = !!(BGFX_STATE_BLEND_INDEPENDENT & _state);
  1665. const ProgramMtl& program = m_program[_program.idx];
  1666. bx::HashMurmur2A murmur;
  1667. murmur.begin();
  1668. murmur.add(_state);
  1669. murmur.add(independentBlendEnable ? _rgba : 0);
  1670. murmur.add(_numInstanceData);
  1671. if (!isValid(_fbh) )
  1672. {
  1673. murmur.add(m_mainFrameBuffer.m_pixelFormatHash);
  1674. }
  1675. else
  1676. {
  1677. FrameBufferMtl& frameBuffer = m_frameBuffers[_fbh.idx];
  1678. murmur.add(frameBuffer.m_pixelFormatHash);
  1679. }
  1680. murmur.add(program.m_vsh->m_hash);
  1681. if (NULL != program.m_fsh)
  1682. {
  1683. murmur.add(program.m_fsh->m_hash);
  1684. }
  1685. for (uint8_t ii = 0; ii < _numStreams; ++ii)
  1686. {
  1687. murmur.add(_layouts[ii]->m_hash);
  1688. }
  1689. uint32_t hash = murmur.end();
  1690. PipelineStateMtl* pso = m_pipelineStateCache.find(hash);
  1691. if (NULL == pso)
  1692. {
  1693. pso = BX_NEW(g_allocator, PipelineStateMtl);
  1694. RenderPipelineDescriptor pd = m_renderPipelineDescriptor;
  1695. reset(pd);
  1696. pd.alphaToCoverageEnabled = !!(BGFX_STATE_BLEND_ALPHA_TO_COVERAGE & _state);
  1697. uint32_t frameBufferAttachment = 1;
  1698. if (!isValid(_fbh)
  1699. || s_renderMtl->m_frameBuffers[_fbh.idx].m_swapChain)
  1700. {
  1701. SwapChainMtl* swapChain = !isValid(_fbh)
  1702. ? s_renderMtl->m_mainFrameBuffer.m_swapChain
  1703. : s_renderMtl->m_frameBuffers[_fbh.idx].m_swapChain
  1704. ;
  1705. pd.sampleCount = NULL != swapChain->m_backBufferColorMsaa
  1706. ? swapChain->m_backBufferColorMsaa.sampleCount()
  1707. : 1
  1708. ;
  1709. pd.colorAttachments[0].pixelFormat = swapChain->currentDrawableTexture().pixelFormat;
  1710. pd.depthAttachmentPixelFormat = swapChain->m_backBufferDepth.m_obj.pixelFormat;
  1711. pd.stencilAttachmentPixelFormat = swapChain->m_backBufferStencil.m_obj.pixelFormat;
  1712. }
  1713. else
  1714. {
  1715. const FrameBufferMtl& frameBuffer = m_frameBuffers[_fbh.idx];
  1716. frameBufferAttachment = frameBuffer.m_num;
  1717. for (uint32_t ii = 0; ii < frameBuffer.m_num; ++ii)
  1718. {
  1719. const TextureMtl& texture = m_textures[frameBuffer.m_colorHandle[ii].idx];
  1720. pd.sampleCount = NULL != texture.m_ptrMsaa
  1721. ? texture.m_ptrMsaa.sampleCount()
  1722. : 1
  1723. ;
  1724. pd.colorAttachments[ii].pixelFormat = texture.m_ptr.m_obj.pixelFormat;
  1725. }
  1726. if (isValid(frameBuffer.m_depthHandle) )
  1727. {
  1728. const TextureMtl& texture = m_textures[frameBuffer.m_depthHandle.idx];
  1729. pd.depthAttachmentPixelFormat = texture.m_ptr.m_obj.pixelFormat;
  1730. if (NULL != texture.m_ptrStencil)
  1731. {
  1732. pd.stencilAttachmentPixelFormat = texture.m_ptrStencil.m_obj.pixelFormat;
  1733. }
  1734. else
  1735. {
  1736. if (texture.m_textureFormat == TextureFormat::D24S8)
  1737. {
  1738. pd.stencilAttachmentPixelFormat = texture.m_ptr.m_obj.pixelFormat;
  1739. }
  1740. }
  1741. }
  1742. }
  1743. const uint32_t blend = uint32_t( (_state&BGFX_STATE_BLEND_MASK )>>BGFX_STATE_BLEND_SHIFT);
  1744. const uint32_t equation = uint32_t( (_state&BGFX_STATE_BLEND_EQUATION_MASK)>>BGFX_STATE_BLEND_EQUATION_SHIFT);
  1745. const uint32_t srcRGB = (blend )&0xf;
  1746. const uint32_t dstRGB = (blend>> 4)&0xf;
  1747. const uint32_t srcA = (blend>> 8)&0xf;
  1748. const uint32_t dstA = (blend>>12)&0xf;
  1749. const uint32_t equRGB = (equation )&0x7;
  1750. const uint32_t equA = (equation>>3)&0x7;
  1751. uint8_t writeMask = 0;
  1752. writeMask |= (_state&BGFX_STATE_WRITE_R) ? MTLColorWriteMaskRed : 0;
  1753. writeMask |= (_state&BGFX_STATE_WRITE_G) ? MTLColorWriteMaskGreen : 0;
  1754. writeMask |= (_state&BGFX_STATE_WRITE_B) ? MTLColorWriteMaskBlue : 0;
  1755. writeMask |= (_state&BGFX_STATE_WRITE_A) ? MTLColorWriteMaskAlpha : 0;
  1756. for (uint32_t ii = 0; ii < (independentBlendEnable ? 1 : frameBufferAttachment); ++ii)
  1757. {
  1758. RenderPipelineColorAttachmentDescriptor drt = pd.colorAttachments[ii];
  1759. drt.blendingEnabled = !!(BGFX_STATE_BLEND_MASK & _state);
  1760. drt.sourceRGBBlendFactor = s_blendFactor[srcRGB][0];
  1761. drt.destinationRGBBlendFactor = s_blendFactor[dstRGB][0];
  1762. drt.rgbBlendOperation = s_blendEquation[equRGB];
  1763. drt.sourceAlphaBlendFactor = s_blendFactor[srcA][1];
  1764. drt.destinationAlphaBlendFactor = s_blendFactor[dstA][1];
  1765. drt.alphaBlendOperation = s_blendEquation[equA];
  1766. drt.writeMask = writeMask;
  1767. }
  1768. if (independentBlendEnable)
  1769. {
  1770. for (uint32_t ii = 1, rgba = _rgba; ii < frameBufferAttachment; ++ii, rgba >>= 11)
  1771. {
  1772. RenderPipelineColorAttachmentDescriptor drt = pd.colorAttachments[ii];
  1773. drt.blendingEnabled = 0 != (rgba&0x7ff);
  1774. const uint32_t src = (rgba )&0xf;
  1775. const uint32_t dst = (rgba>>4)&0xf;
  1776. const uint32_t equationIndex = (rgba>>8)&0x7;
  1777. drt.sourceRGBBlendFactor = s_blendFactor[src][0];
  1778. drt.destinationRGBBlendFactor = s_blendFactor[dst][0];
  1779. drt.rgbBlendOperation = s_blendEquation[equationIndex];
  1780. drt.sourceAlphaBlendFactor = s_blendFactor[src][1];
  1781. drt.destinationAlphaBlendFactor = s_blendFactor[dst][1];
  1782. drt.alphaBlendOperation = s_blendEquation[equationIndex];
  1783. drt.writeMask = writeMask;
  1784. }
  1785. }
  1786. pd.vertexFunction = program.m_vsh->m_function;
  1787. pd.fragmentFunction = program.m_fsh != NULL ? program.m_fsh->m_function : NULL;
  1788. VertexDescriptor vertexDesc = m_vertexDescriptor;
  1789. reset(vertexDesc);
  1790. bool attrSet[Attrib::Count] = {};
  1791. uint8_t stream = 0;
  1792. for (; stream < _numStreams; ++stream)
  1793. {
  1794. const VertexLayout& layout = *_layouts[stream];
  1795. bool streamUsed = false;
  1796. for (uint32_t ii = 0; Attrib::Count != program.m_used[ii]; ++ii)
  1797. {
  1798. Attrib::Enum attr = Attrib::Enum(program.m_used[ii]);
  1799. if (attrSet[attr])
  1800. continue;
  1801. const uint32_t loc = program.m_attributes[attr];
  1802. uint8_t num;
  1803. AttribType::Enum type;
  1804. bool normalized;
  1805. bool asInt;
  1806. layout.decode(attr, num, type, normalized, asInt);
  1807. BX_ASSERT(num <= 4, "num must be <= 4");
  1808. if (UINT16_MAX != layout.m_attributes[attr])
  1809. {
  1810. vertexDesc.attributes[loc].format = s_attribType[type][num-1][normalized?1:0];
  1811. vertexDesc.attributes[loc].bufferIndex = stream+1;
  1812. vertexDesc.attributes[loc].offset = layout.m_offset[attr];
  1813. BX_TRACE("attrib: %s format: %d offset: %d", s_attribName[attr], (int)vertexDesc.attributes[loc].format, (int)vertexDesc.attributes[loc].offset);
  1814. attrSet[attr] = true;
  1815. streamUsed = true;
  1816. }
  1817. }
  1818. if (streamUsed) {
  1819. vertexDesc.layouts[stream+1].stride = layout.getStride();
  1820. vertexDesc.layouts[stream+1].stepFunction = MTLVertexStepFunctionPerVertex;
  1821. }
  1822. }
  1823. for (uint32_t ii = 0; Attrib::Count != program.m_used[ii]; ++ii)
  1824. {
  1825. Attrib::Enum attr = Attrib::Enum(program.m_used[ii]);
  1826. const uint32_t loc = program.m_attributes[attr];
  1827. if (!attrSet[attr])
  1828. {
  1829. vertexDesc.attributes[loc].format = MTLVertexFormatUChar2;
  1830. vertexDesc.attributes[loc].bufferIndex = 1;
  1831. vertexDesc.attributes[loc].offset = 0;
  1832. }
  1833. }
  1834. if (0 < _numInstanceData)
  1835. {
  1836. for (uint32_t ii = 0; UINT16_MAX != program.m_instanceData[ii]; ++ii)
  1837. {
  1838. const uint32_t loc = program.m_instanceData[ii];
  1839. vertexDesc.attributes[loc].format = MTLVertexFormatFloat4;
  1840. vertexDesc.attributes[loc].bufferIndex = stream+1;
  1841. vertexDesc.attributes[loc].offset = ii*16;
  1842. }
  1843. vertexDesc.layouts[stream+1].stride = _numInstanceData * 16;
  1844. vertexDesc.layouts[stream+1].stepFunction = MTLVertexStepFunctionPerInstance;
  1845. vertexDesc.layouts[stream+1].stepRate = 1;
  1846. }
  1847. pd.vertexDescriptor = vertexDesc;
  1848. {
  1849. RenderPipelineReflection reflection = NULL;
  1850. pso->m_rps = m_device.newRenderPipelineStateWithDescriptor(pd, MTLPipelineOptionBufferTypeInfo, &reflection);
  1851. if (NULL != reflection)
  1852. {
  1853. processArguments(pso, reflection.vertexArguments, reflection.fragmentArguments);
  1854. }
  1855. }
  1856. m_pipelineStateCache.add(hash, pso);
  1857. m_pipelineProgram.push_back({hash, _program});
  1858. }
  1859. return pso;
  1860. }
  1861. PipelineStateMtl* getPipelineState(
  1862. uint64_t _state
  1863. , uint32_t _rgba
  1864. , FrameBufferHandle _fbh
  1865. , VertexLayoutHandle _layoutHandle
  1866. , ProgramHandle _program
  1867. , uint16_t _numInstanceData
  1868. )
  1869. {
  1870. const VertexLayout* layout = &m_vertexLayouts[_layoutHandle.idx];
  1871. return getPipelineState(
  1872. _state
  1873. , _rgba
  1874. , _fbh
  1875. , 1
  1876. , &layout
  1877. , _program
  1878. , _numInstanceData
  1879. );
  1880. }
  1881. PipelineStateMtl* getComputePipelineState(ProgramHandle _program)
  1882. {
  1883. ProgramMtl& program = m_program[_program.idx];
  1884. if (NULL == program.m_computePS)
  1885. {
  1886. PipelineStateMtl* pso = BX_NEW(g_allocator, PipelineStateMtl);
  1887. program.m_computePS = pso;
  1888. ComputePipelineReflection reflection = NULL;
  1889. pso->m_cps = m_device.newComputePipelineStateWithFunction(program.m_vsh->m_function, MTLPipelineOptionBufferTypeInfo, &reflection);
  1890. processArguments(pso, reflection.arguments, NULL);
  1891. for (uint32_t ii = 0; ii < 3; ++ii)
  1892. {
  1893. pso->m_numThreads[ii] = program.m_vsh->m_numThreads[ii];
  1894. }
  1895. }
  1896. return program.m_computePS;
  1897. }
  1898. SamplerState getSamplerState(uint32_t _flags)
  1899. {
  1900. _flags &= BGFX_SAMPLER_BITS_MASK;
  1901. SamplerState sampler = m_samplerStateCache.find(_flags);
  1902. if (NULL == sampler)
  1903. {
  1904. m_samplerDescriptor.sAddressMode = s_textureAddress[(_flags&BGFX_SAMPLER_U_MASK)>>BGFX_SAMPLER_U_SHIFT];
  1905. m_samplerDescriptor.tAddressMode = s_textureAddress[(_flags&BGFX_SAMPLER_V_MASK)>>BGFX_SAMPLER_V_SHIFT];
  1906. m_samplerDescriptor.rAddressMode = s_textureAddress[(_flags&BGFX_SAMPLER_W_MASK)>>BGFX_SAMPLER_W_SHIFT];
  1907. m_samplerDescriptor.minFilter = s_textureFilterMinMag[(_flags&BGFX_SAMPLER_MIN_MASK)>>BGFX_SAMPLER_MIN_SHIFT];
  1908. m_samplerDescriptor.magFilter = s_textureFilterMinMag[(_flags&BGFX_SAMPLER_MAG_MASK)>>BGFX_SAMPLER_MAG_SHIFT];
  1909. m_samplerDescriptor.mipFilter = s_textureFilterMip[(_flags&BGFX_SAMPLER_MIP_MASK)>>BGFX_SAMPLER_MIP_SHIFT];
  1910. m_samplerDescriptor.lodMinClamp = 0;
  1911. m_samplerDescriptor.lodMaxClamp = FLT_MAX;
  1912. m_samplerDescriptor.normalizedCoordinates = TRUE;
  1913. m_samplerDescriptor.maxAnisotropy = (0 != (_flags & (BGFX_SAMPLER_MIN_ANISOTROPIC|BGFX_SAMPLER_MAG_ANISOTROPIC) ) ) ? m_mainFrameBuffer.m_swapChain->m_maxAnisotropy : 1;
  1914. if (m_macOS11Runtime
  1915. || [m_device supportsFeatureSet:(MTLFeatureSet)4 /*MTLFeatureSet_iOS_GPUFamily3_v1*/])
  1916. {
  1917. const uint32_t cmpFunc = (_flags&BGFX_SAMPLER_COMPARE_MASK)>>BGFX_SAMPLER_COMPARE_SHIFT;
  1918. m_samplerDescriptor.compareFunction = 0 == cmpFunc
  1919. ? MTLCompareFunctionNever
  1920. : s_cmpFunc[cmpFunc]
  1921. ;
  1922. }
  1923. sampler = m_device.newSamplerStateWithDescriptor(m_samplerDescriptor);
  1924. m_samplerStateCache.add(_flags, sampler);
  1925. }
  1926. return sampler;
  1927. }
  1928. bool isVisible(Frame* _render, OcclusionQueryHandle _handle, bool _visible)
  1929. {
  1930. m_occlusionQuery.resolve(_render);
  1931. return _visible == (0 != _render->m_occlusion[_handle.idx]);
  1932. }
  1933. BlitCommandEncoder getBlitCommandEncoder()
  1934. {
  1935. if (NULL == m_blitCommandEncoder)
  1936. {
  1937. endEncoding();
  1938. if (NULL == m_commandBuffer)
  1939. {
  1940. m_commandBuffer = m_cmd.alloc();
  1941. }
  1942. m_blitCommandEncoder = m_commandBuffer.blitCommandEncoder();
  1943. }
  1944. return m_blitCommandEncoder;
  1945. }
  1946. void endEncoding()
  1947. {
  1948. if (0 != m_renderCommandEncoder)
  1949. {
  1950. m_renderCommandEncoder.endEncoding();
  1951. m_renderCommandEncoder = 0;
  1952. }
  1953. if (0 != m_computeCommandEncoder)
  1954. {
  1955. m_computeCommandEncoder.endEncoding();
  1956. m_computeCommandEncoder = 0;
  1957. }
  1958. if (0 != m_blitCommandEncoder)
  1959. {
  1960. m_blitCommandEncoder.endEncoding();
  1961. m_blitCommandEncoder = 0;
  1962. }
  1963. }
  1964. Device m_device;
  1965. OcclusionQueryMTL m_occlusionQuery;
  1966. TimerQueryMtl m_gpuTimer;
  1967. CommandQueueMtl m_cmd;
  1968. bool m_iOS9Runtime;
  1969. bool m_macOS11Runtime;
  1970. bool m_hasPixelFormatDepth32Float_Stencil8;
  1971. bool m_hasStoreActionStoreAndMultisampleResolve;
  1972. Buffer m_uniformBuffer;
  1973. Buffer m_uniformBuffers[BGFX_CONFIG_MAX_FRAME_LATENCY];
  1974. uint32_t m_uniformBufferVertexOffset;
  1975. uint32_t m_uniformBufferFragmentOffset;
  1976. uint8_t m_bufferIndex;
  1977. uint16_t m_numWindows;
  1978. FrameBufferHandle m_windows[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  1979. IndexBufferMtl m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS];
  1980. VertexBufferMtl m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS];
  1981. ShaderMtl m_shaders[BGFX_CONFIG_MAX_SHADERS];
  1982. ProgramMtl m_program[BGFX_CONFIG_MAX_PROGRAMS];
  1983. TextureMtl m_textures[BGFX_CONFIG_MAX_TEXTURES];
  1984. FrameBufferMtl m_mainFrameBuffer;
  1985. FrameBufferMtl m_frameBuffers[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  1986. VertexLayout m_vertexLayouts[BGFX_CONFIG_MAX_VERTEX_LAYOUTS];
  1987. UniformRegistry m_uniformReg;
  1988. void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS];
  1989. struct PipelineProgram
  1990. {
  1991. uint64_t key;
  1992. ProgramHandle program;
  1993. };
  1994. typedef stl::vector<PipelineProgram> PipelineProgramArray;
  1995. PipelineProgramArray m_pipelineProgram;
  1996. StateCacheT<PipelineStateMtl*> m_pipelineStateCache;
  1997. StateCacheT<DepthStencilState> m_depthStencilStateCache;
  1998. StateCacheT<SamplerState> m_samplerStateCache;
  1999. TextVideoMem m_textVideoMem;
  2000. FrameBufferHandle m_fbh;
  2001. bool m_rtMsaa;
  2002. Resolution m_resolution;
  2003. void* m_capture;
  2004. uint32_t m_captureSize;
  2005. // descriptors
  2006. RenderPipelineDescriptor m_renderPipelineDescriptor;
  2007. DepthStencilDescriptor m_depthStencilDescriptor;
  2008. StencilDescriptor m_frontFaceStencilDescriptor;
  2009. StencilDescriptor m_backFaceStencilDescriptor;
  2010. VertexDescriptor m_vertexDescriptor;
  2011. TextureDescriptor m_textureDescriptor;
  2012. SamplerDescriptor m_samplerDescriptor;
  2013. // currently active objects data
  2014. Texture m_screenshotTarget;
  2015. ShaderMtl m_screenshotBlitProgramVsh;
  2016. ShaderMtl m_screenshotBlitProgramFsh;
  2017. ProgramMtl m_screenshotBlitProgram;
  2018. RenderPipelineState m_screenshotBlitRenderPipelineState;
  2019. CommandBuffer m_commandBuffer;
  2020. BlitCommandEncoder m_blitCommandEncoder;
  2021. RenderCommandEncoder m_renderCommandEncoder;
  2022. ComputeCommandEncoder m_computeCommandEncoder;
  2023. FrameBufferHandle m_renderCommandEncoderFrameBufferHandle;
  2024. };
  2025. RendererContextI* rendererCreate(const Init& _init)
  2026. {
  2027. s_renderMtl = BX_NEW(g_allocator, RendererContextMtl);
  2028. if (!s_renderMtl->init(_init) )
  2029. {
  2030. BX_DELETE(g_allocator, s_renderMtl);
  2031. s_renderMtl = NULL;
  2032. }
  2033. return s_renderMtl;
  2034. }
  2035. void rendererDestroy()
  2036. {
  2037. s_renderMtl->shutdown();
  2038. BX_DELETE(g_allocator, s_renderMtl);
  2039. s_renderMtl = NULL;
  2040. }
  2041. void writeString(bx::WriterI* _writer, const char* _str)
  2042. {
  2043. bx::write(_writer, _str, (int32_t)bx::strLen(_str) );
  2044. }
  2045. void ShaderMtl::create(const Memory* _mem)
  2046. {
  2047. bx::MemoryReader reader(_mem->data, _mem->size);
  2048. uint32_t magic;
  2049. bx::read(&reader, magic);
  2050. uint32_t hashIn;
  2051. bx::read(&reader, hashIn);
  2052. uint32_t hashOut;
  2053. if (isShaderVerLess(magic, 6) )
  2054. {
  2055. hashOut = hashIn;
  2056. }
  2057. else
  2058. {
  2059. bx::read(&reader, hashOut);
  2060. }
  2061. uint16_t count;
  2062. bx::read(&reader, count);
  2063. BX_TRACE("%s Shader consts %d"
  2064. , getShaderTypeName(magic)
  2065. , count
  2066. );
  2067. for (uint32_t ii = 0; ii < count; ++ii)
  2068. {
  2069. uint8_t nameSize;
  2070. bx::read(&reader, nameSize);
  2071. char name[256];
  2072. bx::read(&reader, &name, nameSize);
  2073. name[nameSize] = '\0';
  2074. uint8_t type;
  2075. bx::read(&reader, type);
  2076. uint8_t num;
  2077. bx::read(&reader, num);
  2078. uint16_t regIndex;
  2079. bx::read(&reader, regIndex);
  2080. uint16_t regCount;
  2081. bx::read(&reader, regCount);
  2082. if (!isShaderVerLess(magic, 8) )
  2083. {
  2084. uint16_t texInfo = 0;
  2085. bx::read(&reader, texInfo);
  2086. }
  2087. if (!isShaderVerLess(magic, 10) )
  2088. {
  2089. uint16_t texFormat = 0;
  2090. bx::read(&reader, texFormat);
  2091. }
  2092. }
  2093. if (isShaderType(magic, 'C'))
  2094. {
  2095. for (uint32_t ii = 0; ii < 3; ++ii)
  2096. {
  2097. bx::read(&reader, m_numThreads[ii]);
  2098. }
  2099. }
  2100. uint32_t shaderSize;
  2101. bx::read(&reader, shaderSize);
  2102. const char* code = (const char*)reader.getDataPtr();
  2103. bx::skip(&reader, shaderSize+1);
  2104. Library lib = s_renderMtl->m_device.newLibraryWithSource(code);
  2105. if (NULL != lib)
  2106. {
  2107. m_function = lib.newFunctionWithName(SHADER_FUNCTION_NAME);
  2108. release(lib);
  2109. }
  2110. BGFX_FATAL(NULL != m_function
  2111. , bgfx::Fatal::InvalidShader
  2112. , "Failed to create %s shader."
  2113. , getShaderTypeName(magic)
  2114. );
  2115. bx::HashMurmur2A murmur;
  2116. murmur.begin();
  2117. murmur.add(hashIn);
  2118. murmur.add(hashOut);
  2119. murmur.add(code, shaderSize);
  2120. // murmur.add(numAttrs);
  2121. // murmur.add(m_attrMask, numAttrs);
  2122. m_hash = murmur.end();
  2123. }
  2124. void ProgramMtl::create(const ShaderMtl* _vsh, const ShaderMtl* _fsh)
  2125. {
  2126. BX_ASSERT(NULL != _vsh->m_function.m_obj, "Vertex shader doesn't exist.");
  2127. m_vsh = _vsh;
  2128. m_fsh = _fsh;
  2129. // get attributes
  2130. bx::memSet(m_attributes, 0xff, sizeof(m_attributes) );
  2131. uint32_t used = 0;
  2132. uint32_t instUsed = 0;
  2133. if (NULL != _vsh->m_function.m_obj)
  2134. {
  2135. for (MTLVertexAttribute* attrib in _vsh->m_function.m_obj.vertexAttributes)
  2136. {
  2137. if (attrib.active)
  2138. {
  2139. const char* name = utf8String(attrib.name);
  2140. uint32_t loc = (uint32_t)attrib.attributeIndex;
  2141. BX_TRACE("attr %s: %d", name, loc);
  2142. for (uint8_t ii = 0; ii < Attrib::Count; ++ii)
  2143. {
  2144. if (0 == bx::strCmp(s_attribName[ii],name) )
  2145. {
  2146. m_attributes[ii] = loc;
  2147. m_used[used++] = ii;
  2148. break;
  2149. }
  2150. }
  2151. for (uint32_t ii = 0; ii < BX_COUNTOF(s_instanceDataName); ++ii)
  2152. {
  2153. if (0 == bx::strCmp(s_instanceDataName[ii],name) )
  2154. {
  2155. m_instanceData[instUsed++] = loc;
  2156. }
  2157. }
  2158. }
  2159. }
  2160. }
  2161. m_used[used] = Attrib::Count;
  2162. m_instanceData[instUsed] = UINT16_MAX;
  2163. }
  2164. void ProgramMtl::destroy()
  2165. {
  2166. m_vsh = NULL;
  2167. m_fsh = NULL;
  2168. if (NULL != m_computePS)
  2169. {
  2170. BX_DELETE(g_allocator, m_computePS);
  2171. m_computePS = NULL;
  2172. }
  2173. }
  2174. void BufferMtl::create(uint32_t _size, void* _data, uint16_t _flags, uint16_t _stride, bool _vertex)
  2175. {
  2176. BX_UNUSED(_stride);
  2177. m_size = _size;
  2178. m_flags = _flags;
  2179. m_vertex = _vertex;
  2180. if (NULL == _data)
  2181. {
  2182. m_ptr = s_renderMtl->m_device.newBufferWithLength(_size, 0);
  2183. }
  2184. else
  2185. {
  2186. m_ptr = s_renderMtl->m_device.newBufferWithBytes(_data, _size, 0);
  2187. }
  2188. }
  2189. void BufferMtl::update(uint32_t _offset, uint32_t _size, void* _data, bool _discard)
  2190. {
  2191. BlitCommandEncoder bce = s_renderMtl->getBlitCommandEncoder();
  2192. if (!m_vertex
  2193. && !_discard)
  2194. {
  2195. if (NULL == m_dynamic)
  2196. {
  2197. m_dynamic = (uint8_t*)BX_ALLOC(g_allocator, m_size);
  2198. }
  2199. bx::memCopy(m_dynamic + _offset, _data, _size);
  2200. uint32_t start = _offset & 4;
  2201. uint32_t end = bx::strideAlign(_offset + _size, 4);
  2202. Buffer temp = s_renderMtl->m_device.newBufferWithBytes(m_dynamic, end - start, 0);
  2203. bce.copyFromBuffer(temp, 0, m_ptr, start, end - start);
  2204. s_renderMtl->m_cmd.release(temp);
  2205. }
  2206. else
  2207. {
  2208. Buffer temp = s_renderMtl->m_device.newBufferWithBytes(_data, _size, 0);
  2209. bce.copyFromBuffer(temp, 0, m_ptr, _offset, _size);
  2210. s_renderMtl->m_cmd.release(temp);
  2211. }
  2212. }
  2213. void VertexBufferMtl::create(uint32_t _size, void* _data, VertexLayoutHandle _layoutHandle, uint16_t _flags)
  2214. {
  2215. m_layoutHandle = _layoutHandle;
  2216. uint16_t stride = isValid(_layoutHandle)
  2217. ? s_renderMtl->m_vertexLayouts[_layoutHandle.idx].m_stride
  2218. : 0
  2219. ;
  2220. BufferMtl::create(_size, _data, _flags, stride, true);
  2221. }
  2222. void TextureMtl::create(const Memory* _mem, uint64_t _flags, uint8_t _skip)
  2223. {
  2224. m_sampler = s_renderMtl->getSamplerState(uint32_t(_flags) );
  2225. bimg::ImageContainer imageContainer;
  2226. if (bimg::imageParse(imageContainer, _mem->data, _mem->size) )
  2227. {
  2228. const bimg::ImageBlockInfo& blockInfo = getBlockInfo(bimg::TextureFormat::Enum(imageContainer.m_format) );
  2229. const uint8_t startLod = bx::min<uint8_t>(_skip, imageContainer.m_numMips-1);
  2230. bimg::TextureInfo ti;
  2231. bimg::imageGetSize(
  2232. &ti
  2233. , uint16_t(imageContainer.m_width >>startLod)
  2234. , uint16_t(imageContainer.m_height>>startLod)
  2235. , uint16_t(imageContainer.m_depth >>startLod)
  2236. , imageContainer.m_cubeMap
  2237. , 1 < imageContainer.m_numMips
  2238. , imageContainer.m_numLayers
  2239. , imageContainer.m_format
  2240. );
  2241. ti.numMips = bx::min<uint8_t>(imageContainer.m_numMips-startLod, ti.numMips);
  2242. m_flags = _flags;
  2243. m_width = ti.width;
  2244. m_height = ti.height;
  2245. m_depth = ti.depth;
  2246. m_requestedFormat = uint8_t(imageContainer.m_format);
  2247. m_textureFormat = uint8_t(getViableTextureFormat(imageContainer) );
  2248. const bool convert = m_textureFormat != m_requestedFormat;
  2249. const uint8_t bpp = bimg::getBitsPerPixel(bimg::TextureFormat::Enum(m_textureFormat) );
  2250. TextureDescriptor desc = s_renderMtl->m_textureDescriptor;
  2251. if (1 < ti.numLayers)
  2252. {
  2253. if (imageContainer.m_cubeMap)
  2254. {
  2255. desc.textureType = MTLTextureType(6); // MTLTextureTypeCubeArray
  2256. m_type = TextureCube;
  2257. }
  2258. else
  2259. {
  2260. desc.textureType = MTLTextureType2DArray;
  2261. m_type = Texture2D;
  2262. }
  2263. }
  2264. else if (imageContainer.m_cubeMap)
  2265. {
  2266. desc.textureType = MTLTextureTypeCube;
  2267. m_type = TextureCube;
  2268. }
  2269. else if (1 < imageContainer.m_depth)
  2270. {
  2271. desc.textureType = MTLTextureType3D;
  2272. m_type = Texture3D;
  2273. }
  2274. else
  2275. {
  2276. desc.textureType = MTLTextureType2D;
  2277. m_type = Texture2D;
  2278. }
  2279. m_numMips = ti.numMips;
  2280. const uint16_t numSides = ti.numLayers * (imageContainer.m_cubeMap ? 6 : 1);
  2281. const bool compressed = bimg::isCompressed(bimg::TextureFormat::Enum(m_textureFormat) );
  2282. const bool writeOnly = 0 != (_flags&BGFX_TEXTURE_RT_WRITE_ONLY);
  2283. const bool computeWrite = 0 != (_flags&BGFX_TEXTURE_COMPUTE_WRITE);
  2284. const bool renderTarget = 0 != (_flags&BGFX_TEXTURE_RT_MASK);
  2285. const bool srgb = 0 != (_flags&BGFX_TEXTURE_SRGB);
  2286. BX_TRACE("Texture %3d: %s (requested: %s), layers %d, %dx%d%s RT[%c], WO[%c], CW[%c], sRGB[%c]"
  2287. , this - s_renderMtl->m_textures
  2288. , getName( (TextureFormat::Enum)m_textureFormat)
  2289. , getName( (TextureFormat::Enum)m_requestedFormat)
  2290. , ti.numLayers
  2291. , ti.width
  2292. , ti.height
  2293. , imageContainer.m_cubeMap ? "x6" : ""
  2294. , renderTarget ? 'x' : ' '
  2295. , writeOnly ? 'x' : ' '
  2296. , computeWrite ? 'x' : ' '
  2297. , srgb ? 'x' : ' '
  2298. );
  2299. const uint32_t msaaQuality = bx::uint32_satsub( (_flags&BGFX_TEXTURE_RT_MSAA_MASK)>>BGFX_TEXTURE_RT_MSAA_SHIFT, 1);
  2300. const int32_t sampleCount = s_msaa[msaaQuality];
  2301. MTLPixelFormat format = MTLPixelFormatInvalid;
  2302. if (srgb)
  2303. {
  2304. format = s_textureFormat[m_textureFormat].m_fmtSrgb;
  2305. BX_WARN(format != MTLPixelFormatInvalid
  2306. , "sRGB not supported for texture format %d"
  2307. , m_textureFormat
  2308. );
  2309. }
  2310. if (format == MTLPixelFormatInvalid)
  2311. {
  2312. // not swizzled and not sRGB, or sRGB unsupported
  2313. format = s_textureFormat[m_textureFormat].m_fmt;
  2314. }
  2315. desc.pixelFormat = format;
  2316. desc.width = ti.width;
  2317. desc.height = ti.height;
  2318. desc.depth = bx::uint32_max(1,imageContainer.m_depth);
  2319. desc.mipmapLevelCount = ti.numMips;
  2320. desc.sampleCount = 1;
  2321. desc.arrayLength = ti.numLayers;
  2322. if (s_renderMtl->m_iOS9Runtime
  2323. || s_renderMtl->m_macOS11Runtime)
  2324. {
  2325. desc.cpuCacheMode = MTLCPUCacheModeDefaultCache;
  2326. desc.storageMode = (MTLStorageMode)(false
  2327. || writeOnly
  2328. || bimg::isDepth(bimg::TextureFormat::Enum(m_textureFormat) )
  2329. ? 2 /* MTLStorageModePrivate */
  2330. : (BX_ENABLED(BX_PLATFORM_IOS)
  2331. ? 0 /* MTLStorageModeShared */
  2332. : 1 /* MTLStorageModeManaged */
  2333. ) );
  2334. desc.usage = MTLTextureUsageShaderRead;
  2335. if (computeWrite)
  2336. {
  2337. desc.usage |= MTLTextureUsageShaderWrite;
  2338. }
  2339. if (renderTarget)
  2340. {
  2341. desc.usage |= MTLTextureUsageRenderTarget;
  2342. }
  2343. }
  2344. m_ptr = s_renderMtl->m_device.newTextureWithDescriptor(desc);
  2345. if (sampleCount > 1)
  2346. {
  2347. desc.textureType = MTLTextureType2DMultisample;
  2348. desc.sampleCount = sampleCount;
  2349. if (s_renderMtl->m_iOS9Runtime
  2350. || s_renderMtl->m_macOS11Runtime)
  2351. {
  2352. desc.storageMode = (MTLStorageMode)(2 /* MTLStorageModePrivate */);
  2353. }
  2354. m_ptrMsaa = s_renderMtl->m_device.newTextureWithDescriptor(desc);
  2355. }
  2356. if (m_requestedFormat == TextureFormat::D24S8
  2357. && desc.pixelFormat == MTLPixelFormatDepth32Float)
  2358. {
  2359. desc.pixelFormat = MTLPixelFormatStencil8;
  2360. m_ptrStencil = s_renderMtl->m_device.newTextureWithDescriptor(desc);
  2361. }
  2362. uint8_t* temp = NULL;
  2363. if (convert)
  2364. {
  2365. temp = (uint8_t*)BX_ALLOC(g_allocator, ti.width*ti.height*4);
  2366. }
  2367. for (uint8_t side = 0; side < numSides; ++side)
  2368. {
  2369. uint32_t width = ti.width;
  2370. uint32_t height = ti.height;
  2371. uint32_t depth = ti.depth;
  2372. for (uint8_t lod = 0, num = ti.numMips; lod < num; ++lod)
  2373. {
  2374. width = bx::max(1u, width);
  2375. height = bx::max(1u, height);
  2376. depth = bx::max(1u, depth);
  2377. bimg::ImageMip mip;
  2378. if (bimg::imageGetRawData(imageContainer, side, lod+startLod, _mem->data, _mem->size, mip) )
  2379. {
  2380. const uint8_t* data = mip.m_data;
  2381. if (convert)
  2382. {
  2383. bimg::imageDecodeToBgra8(
  2384. g_allocator
  2385. , temp
  2386. , mip.m_data
  2387. , mip.m_width
  2388. , mip.m_height
  2389. , mip.m_width*4
  2390. , mip.m_format
  2391. );
  2392. data = temp;
  2393. }
  2394. MTLRegion region = { { 0, 0, 0 }, { width, height, depth } };
  2395. uint32_t bytesPerRow = 0;
  2396. uint32_t bytesPerImage = 0;
  2397. if (compressed && !convert)
  2398. {
  2399. if (format >= 160 /*PVRTC_RGB_2BPP*/
  2400. && format <= 167 /*PVRTC_RGBA_4BPP_sRGB*/)
  2401. {
  2402. bytesPerRow = 0;
  2403. bytesPerImage = 0;
  2404. }
  2405. else
  2406. {
  2407. bytesPerRow = (mip.m_width / blockInfo.blockWidth)*mip.m_blockSize;
  2408. bytesPerImage = desc.textureType == MTLTextureType3D
  2409. ? (mip.m_height/blockInfo.blockHeight)*bytesPerRow
  2410. : 0
  2411. ;
  2412. }
  2413. }
  2414. else
  2415. {
  2416. bytesPerRow = width * bpp / 8;
  2417. bytesPerImage = desc.textureType == MTLTextureType3D
  2418. ? bytesPerRow * height
  2419. : 0
  2420. ;
  2421. }
  2422. m_ptr.replaceRegion(region, lod, side, data, bytesPerRow, bytesPerImage);
  2423. }
  2424. width >>= 1;
  2425. height >>= 1;
  2426. depth >>= 1;
  2427. }
  2428. }
  2429. if (NULL != temp)
  2430. {
  2431. BX_FREE(g_allocator, temp);
  2432. }
  2433. }
  2434. }
  2435. void TextureMtl::update(uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem)
  2436. {
  2437. const uint32_t bpp = bimg::getBitsPerPixel(bimg::TextureFormat::Enum(m_textureFormat) );
  2438. uint32_t rectpitch = _rect.m_width*bpp/8;
  2439. if (bimg::isCompressed(bimg::TextureFormat::Enum(m_textureFormat)))
  2440. {
  2441. if (m_ptr.pixelFormat() >= 160 /*PVRTC_RGB_2BPP*/
  2442. && m_ptr.pixelFormat() <= 167 /*PVRTC_RGBA_4BPP_sRGB*/)
  2443. {
  2444. rectpitch = 0;
  2445. }
  2446. else
  2447. {
  2448. const bimg::ImageBlockInfo& blockInfo = bimg::getBlockInfo(bimg::TextureFormat::Enum(m_textureFormat));
  2449. rectpitch = (_rect.m_width / blockInfo.blockWidth)*blockInfo.blockSize;
  2450. }
  2451. }
  2452. const uint32_t srcpitch = UINT16_MAX == _pitch ? rectpitch : _pitch;
  2453. const uint32_t slice = ( (m_type == Texture3D) ? 0 : _side + _z * (m_type == TextureCube ? 6 : 1) );
  2454. const uint16_t zz = (m_type == Texture3D) ? _z : 0 ;
  2455. const bool convert = m_textureFormat != m_requestedFormat;
  2456. uint8_t* data = _mem->data;
  2457. uint8_t* temp = NULL;
  2458. if (convert)
  2459. {
  2460. temp = (uint8_t*)BX_ALLOC(g_allocator, rectpitch*_rect.m_height);
  2461. bimg::imageDecodeToBgra8(
  2462. g_allocator
  2463. , temp
  2464. , data
  2465. , _rect.m_width
  2466. , _rect.m_height
  2467. , srcpitch
  2468. , bimg::TextureFormat::Enum(m_requestedFormat)
  2469. );
  2470. data = temp;
  2471. }
  2472. if (NULL != s_renderMtl->m_renderCommandEncoder)
  2473. {
  2474. s_renderMtl->m_cmd.finish(true);
  2475. MTLRegion region =
  2476. {
  2477. { _rect.m_x, _rect.m_y, zz },
  2478. { _rect.m_width, _rect.m_height, _depth },
  2479. };
  2480. m_ptr.replaceRegion(region, _mip, slice, data, srcpitch, srcpitch * _rect.m_height);
  2481. }
  2482. else
  2483. {
  2484. BlitCommandEncoder bce = s_renderMtl->getBlitCommandEncoder();
  2485. TextureDescriptor desc = s_renderMtl->m_textureDescriptor;
  2486. desc.textureType = _depth > 1 ? MTLTextureType3D : MTLTextureType2D;
  2487. desc.pixelFormat = m_ptr.pixelFormat();
  2488. desc.width = _rect.m_width;
  2489. desc.height = _rect.m_height;
  2490. desc.depth = _depth;
  2491. desc.mipmapLevelCount = 1;
  2492. desc.sampleCount = 1;
  2493. desc.arrayLength = 1;
  2494. if (s_renderMtl->m_iOS9Runtime
  2495. || s_renderMtl->m_macOS11Runtime)
  2496. {
  2497. desc.cpuCacheMode = MTLCPUCacheModeDefaultCache;
  2498. desc.storageMode = BX_ENABLED(BX_PLATFORM_IOS)
  2499. ? (MTLStorageMode)0 // MTLStorageModeShared
  2500. : (MTLStorageMode)1 // MTLStorageModeManaged
  2501. ;
  2502. desc.usage = 0;
  2503. }
  2504. Texture tempTexture = s_renderMtl->m_device.newTextureWithDescriptor(desc);
  2505. MTLRegion region =
  2506. {
  2507. { 0, 0, 0 },
  2508. { _rect.m_width, _rect.m_height, _depth },
  2509. };
  2510. tempTexture.replaceRegion(region, 0, 0, data, srcpitch, srcpitch * _rect.m_height);
  2511. bce.copyFromTexture(tempTexture, 0, 0, MTLOriginMake(0,0,0), MTLSizeMake(_rect.m_width, _rect.m_height, _depth),
  2512. m_ptr, slice, _mip, MTLOriginMake(_rect.m_x, _rect.m_y, zz));
  2513. release(tempTexture);
  2514. }
  2515. if (NULL != temp)
  2516. {
  2517. BX_FREE(g_allocator, temp);
  2518. }
  2519. }
  2520. void TextureMtl::commit(uint8_t _stage, bool _vertex, bool _fragment, uint32_t _flags)
  2521. {
  2522. if (_vertex)
  2523. {
  2524. s_renderMtl->m_renderCommandEncoder.setVertexTexture(m_ptr, _stage);
  2525. s_renderMtl->m_renderCommandEncoder.setVertexSamplerState(
  2526. 0 == (BGFX_SAMPLER_INTERNAL_DEFAULT & _flags)
  2527. ? s_renderMtl->getSamplerState(_flags)
  2528. : m_sampler
  2529. , _stage
  2530. );
  2531. }
  2532. if (_fragment)
  2533. {
  2534. s_renderMtl->m_renderCommandEncoder.setFragmentTexture(m_ptr, _stage);
  2535. s_renderMtl->m_renderCommandEncoder.setFragmentSamplerState(
  2536. 0 == (BGFX_SAMPLER_INTERNAL_DEFAULT & _flags)
  2537. ? s_renderMtl->getSamplerState(_flags)
  2538. : m_sampler
  2539. , _stage
  2540. );
  2541. }
  2542. }
  2543. Texture TextureMtl::getTextureMipLevel(int _mip)
  2544. {
  2545. if (_mip >= 0
  2546. && _mip < m_numMips
  2547. && NULL != m_ptr)
  2548. {
  2549. if (NULL == m_ptrMips[_mip])
  2550. {
  2551. if (TextureCube == m_type)
  2552. {
  2553. m_ptrMips[_mip] = m_ptr.newTextureViewWithPixelFormat(
  2554. m_ptr.pixelFormat()
  2555. , MTLTextureType2DArray
  2556. , NSMakeRange(_mip,1)
  2557. , NSMakeRange(0,m_ptr.arrayLength() * 6)
  2558. );
  2559. }
  2560. else
  2561. {
  2562. m_ptrMips[_mip] = m_ptr.newTextureViewWithPixelFormat(
  2563. m_ptr.pixelFormat()
  2564. , m_ptr.textureType()
  2565. , NSMakeRange(_mip,1)
  2566. , NSMakeRange(0,m_ptr.arrayLength())
  2567. );
  2568. }
  2569. }
  2570. return m_ptrMips[_mip];
  2571. }
  2572. return 0;
  2573. }
  2574. SwapChainMtl::~SwapChainMtl()
  2575. {
  2576. MTL_RELEASE(m_metalLayer);
  2577. MTL_RELEASE(m_drawable);
  2578. MTL_RELEASE(m_drawableTexture);
  2579. MTL_RELEASE(m_backBufferDepth);
  2580. MTL_RELEASE(m_backBufferStencil);
  2581. if (NULL != m_backBufferColorMsaa)
  2582. {
  2583. MTL_RELEASE(m_backBufferColorMsaa);
  2584. }
  2585. }
  2586. void SwapChainMtl::init(void* _nwh)
  2587. {
  2588. if (m_metalLayer)
  2589. {
  2590. release(m_metalLayer);
  2591. }
  2592. if (NULL != NSClassFromString(@"MTKView") )
  2593. {
  2594. MTKView *view = (MTKView *)_nwh;
  2595. if (NULL != view && [view isKindOfClass:NSClassFromString(@"MTKView")])
  2596. {
  2597. m_metalLayer = (CAMetalLayer *)view.layer;
  2598. }
  2599. }
  2600. if (NULL != NSClassFromString(@"CAMetalLayer") )
  2601. {
  2602. if (NULL == m_metalLayer)
  2603. #if BX_PLATFORM_IOS
  2604. {
  2605. CAMetalLayer* metalLayer = (CAMetalLayer*)_nwh;
  2606. if (NULL == metalLayer
  2607. || ![metalLayer isKindOfClass:NSClassFromString(@"CAMetalLayer")])
  2608. {
  2609. BX_WARN(false, "Unable to create Metal device. Please set platform data window to a CAMetalLayer");
  2610. return;
  2611. }
  2612. m_metalLayer = metalLayer;
  2613. }
  2614. #elif BX_PLATFORM_OSX
  2615. {
  2616. NSObject* nvh = (NSObject*)_nwh;
  2617. if ([nvh isKindOfClass:[CAMetalLayer class]])
  2618. {
  2619. CAMetalLayer* metalLayer = (CAMetalLayer*)_nwh;
  2620. m_metalLayer = metalLayer;
  2621. }
  2622. else
  2623. {
  2624. NSView *contentView;
  2625. if ([nvh isKindOfClass:[NSView class]])
  2626. {
  2627. contentView = (NSView*)nvh;
  2628. }
  2629. else if ([nvh isKindOfClass:[NSWindow class]])
  2630. {
  2631. NSWindow* nsWindow = (NSWindow*)nvh;
  2632. contentView = [nsWindow contentView];
  2633. }
  2634. else
  2635. {
  2636. BX_WARN(0, "Unable to create Metal device. Please set platform data window to an NSWindow, NSView, or CAMetalLayer");
  2637. return;
  2638. }
  2639. void (^setLayer)(void) = ^{
  2640. CALayer* layer = contentView.layer;
  2641. if(NULL != layer && [layer isKindOfClass:NSClassFromString(@"CAMetalLayer")])
  2642. {
  2643. m_metalLayer = (CAMetalLayer*)layer;
  2644. }
  2645. else
  2646. {
  2647. [contentView setWantsLayer:YES];
  2648. m_metalLayer = [CAMetalLayer layer];
  2649. [contentView setLayer:m_metalLayer];
  2650. }
  2651. };
  2652. if ([NSThread isMainThread])
  2653. {
  2654. setLayer();
  2655. }
  2656. else
  2657. {
  2658. bx::Semaphore semaphore;
  2659. bx::Semaphore* psemaphore = &semaphore;
  2660. CFRunLoopPerformBlock([[NSRunLoop mainRunLoop] getCFRunLoop],
  2661. kCFRunLoopCommonModes,
  2662. ^{
  2663. setLayer();
  2664. psemaphore->post();
  2665. });
  2666. semaphore.wait();
  2667. }
  2668. }
  2669. }
  2670. #endif // BX_PLATFORM_*
  2671. }
  2672. if (NULL == m_metalLayer)
  2673. {
  2674. BX_WARN(NULL != s_renderMtl->m_device, "Unable to create Metal device.");
  2675. return;
  2676. }
  2677. m_metalLayer.device = s_renderMtl->m_device;
  2678. m_metalLayer.pixelFormat = MTLPixelFormatBGRA8Unorm;
  2679. m_metalLayer.magnificationFilter = kCAFilterNearest;
  2680. m_nwh = _nwh;
  2681. retain(m_metalLayer);
  2682. }
  2683. void SwapChainMtl::resize(FrameBufferMtl &_frameBuffer, uint32_t _width, uint32_t _height, uint32_t _flags)
  2684. {
  2685. const int32_t sampleCount = s_msaa[(_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT];
  2686. #if BX_PLATFORM_OSX
  2687. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101300
  2688. if (@available(macOS 10.13, *))
  2689. {
  2690. m_metalLayer.displaySyncEnabled = 0 != (_flags&BGFX_RESET_VSYNC);
  2691. }
  2692. #endif // __MAC_OS_X_VERSION_MAX_ALLOWED >= 101300
  2693. #endif // BX_PLATFORM_OSX
  2694. m_metalLayer.drawableSize = CGSizeMake(_width, _height);
  2695. m_metalLayer.pixelFormat = (_flags & BGFX_RESET_SRGB_BACKBUFFER)
  2696. ? MTLPixelFormatBGRA8Unorm_sRGB
  2697. : MTLPixelFormatBGRA8Unorm
  2698. ;
  2699. TextureDescriptor desc = s_renderMtl->m_textureDescriptor;
  2700. desc.textureType = sampleCount > 1 ? MTLTextureType2DMultisample : MTLTextureType2D;
  2701. if (s_renderMtl->m_hasPixelFormatDepth32Float_Stencil8)
  2702. {
  2703. desc.pixelFormat = MTLPixelFormatDepth32Float_Stencil8;
  2704. }
  2705. else
  2706. {
  2707. desc.pixelFormat = MTLPixelFormatDepth32Float;
  2708. }
  2709. desc.width = _width;
  2710. desc.height = _height;
  2711. desc.depth = 1;
  2712. desc.mipmapLevelCount = 1;
  2713. desc.sampleCount = sampleCount;
  2714. desc.arrayLength = 1;
  2715. if (s_renderMtl->m_iOS9Runtime
  2716. || s_renderMtl->m_macOS11Runtime)
  2717. {
  2718. desc.cpuCacheMode = MTLCPUCacheModeDefaultCache;
  2719. desc.storageMode = MTLStorageModePrivate;
  2720. desc.usage = MTLTextureUsageRenderTarget;
  2721. }
  2722. if (NULL != m_backBufferDepth)
  2723. {
  2724. release(m_backBufferDepth);
  2725. }
  2726. m_backBufferDepth = s_renderMtl->m_device.newTextureWithDescriptor(desc);
  2727. if (NULL != m_backBufferStencil)
  2728. {
  2729. release(m_backBufferStencil);
  2730. }
  2731. if (s_renderMtl->m_hasPixelFormatDepth32Float_Stencil8)
  2732. {
  2733. m_backBufferStencil = m_backBufferDepth;
  2734. retain(m_backBufferStencil);
  2735. }
  2736. else
  2737. {
  2738. desc.pixelFormat = MTLPixelFormatStencil8;
  2739. m_backBufferStencil = s_renderMtl->m_device.newTextureWithDescriptor(desc);
  2740. }
  2741. if (sampleCount > 1)
  2742. {
  2743. if (NULL != m_backBufferColorMsaa)
  2744. {
  2745. release(m_backBufferColorMsaa);
  2746. }
  2747. desc.pixelFormat = m_metalLayer.pixelFormat;
  2748. m_backBufferColorMsaa = s_renderMtl->m_device.newTextureWithDescriptor(desc);
  2749. }
  2750. bx::HashMurmur2A murmur;
  2751. murmur.begin();
  2752. murmur.add(1);
  2753. murmur.add( (uint32_t)m_metalLayer.pixelFormat);
  2754. murmur.add( (uint32_t)m_backBufferDepth.pixelFormat());
  2755. murmur.add( (uint32_t)m_backBufferStencil.pixelFormat());
  2756. murmur.add( (uint32_t)sampleCount);
  2757. _frameBuffer.m_pixelFormatHash = murmur.end();
  2758. }
  2759. id <MTLTexture> SwapChainMtl::currentDrawableTexture()
  2760. {
  2761. if (NULL == m_drawableTexture)
  2762. {
  2763. m_drawable = m_metalLayer.nextDrawable;
  2764. if (m_drawable != NULL)
  2765. {
  2766. m_drawableTexture = m_drawable.texture;
  2767. retain(m_drawableTexture);
  2768. retain(m_drawable); // keep alive to be useable at 'flip'
  2769. }
  2770. else
  2771. {
  2772. TextureDescriptor desc = s_renderMtl->m_textureDescriptor;
  2773. desc.textureType = MTLTextureType2D;
  2774. desc.pixelFormat = m_metalLayer.pixelFormat;
  2775. desc.width = m_metalLayer.drawableSize.width;
  2776. desc.height = m_metalLayer.drawableSize.height;
  2777. desc.depth = 1;
  2778. desc.mipmapLevelCount = 1;
  2779. desc.sampleCount = 1;
  2780. desc.arrayLength = 1;
  2781. if (s_renderMtl->m_iOS9Runtime
  2782. || s_renderMtl->m_macOS11Runtime)
  2783. {
  2784. desc.cpuCacheMode = MTLCPUCacheModeDefaultCache;
  2785. desc.storageMode = BX_ENABLED(BX_PLATFORM_IOS)
  2786. ? (MTLStorageMode)0 // MTLStorageModeShared
  2787. : (MTLStorageMode)1 // MTLStorageModeManaged
  2788. ;
  2789. desc.usage = MTLTextureUsageRenderTarget;
  2790. }
  2791. m_drawableTexture = s_renderMtl->m_device.newTextureWithDescriptor(desc);
  2792. }
  2793. }
  2794. return m_drawableTexture;
  2795. }
  2796. void FrameBufferMtl::create(uint8_t _num, const Attachment* _attachment)
  2797. {
  2798. m_swapChain = NULL;
  2799. m_denseIdx = UINT16_MAX;
  2800. m_num = 0;
  2801. m_width = 0;
  2802. m_height = 0;
  2803. for (uint32_t ii = 0; ii < _num; ++ii)
  2804. {
  2805. const Attachment& at = _attachment[ii];
  2806. TextureHandle handle = at.handle;
  2807. if (isValid(handle) )
  2808. {
  2809. const TextureMtl& texture = s_renderMtl->m_textures[handle.idx];
  2810. if (0 == m_width)
  2811. {
  2812. m_width = texture.m_width;
  2813. m_height = texture.m_height;
  2814. }
  2815. if (bimg::isDepth(bimg::TextureFormat::Enum(texture.m_textureFormat) ) )
  2816. {
  2817. m_depthHandle = handle;
  2818. m_depthAttachment = at;
  2819. }
  2820. else
  2821. {
  2822. m_colorHandle[m_num] = handle;
  2823. m_colorAttachment[m_num] = at;
  2824. m_num++;
  2825. }
  2826. }
  2827. }
  2828. bx::HashMurmur2A murmur;
  2829. murmur.begin();
  2830. murmur.add(m_num);
  2831. for (uint32_t ii = 0; ii < m_num; ++ii)
  2832. {
  2833. const TextureMtl& texture = s_renderMtl->m_textures[m_colorHandle[ii].idx];
  2834. murmur.add(uint32_t(texture.m_ptr.pixelFormat() ) );
  2835. }
  2836. if (!isValid(m_depthHandle) )
  2837. {
  2838. murmur.add(uint32_t(MTLPixelFormatInvalid) );
  2839. murmur.add(uint32_t(MTLPixelFormatInvalid) );
  2840. }
  2841. else
  2842. {
  2843. const TextureMtl& depthTexture = s_renderMtl->m_textures[m_depthHandle.idx];
  2844. murmur.add(uint32_t(depthTexture.m_ptr.pixelFormat() ) );
  2845. murmur.add(NULL != depthTexture.m_ptrStencil
  2846. ? uint32_t(depthTexture.m_ptrStencil.pixelFormat() )
  2847. : uint32_t(MTLPixelFormatInvalid)
  2848. );
  2849. }
  2850. murmur.add(1); // SampleCount
  2851. m_pixelFormatHash = murmur.end();
  2852. }
  2853. void FrameBufferMtl::create(uint16_t _denseIdx, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _format, TextureFormat::Enum _depthFormat)
  2854. {
  2855. BX_UNUSED(_format, _depthFormat);
  2856. m_swapChain = BX_NEW(g_allocator, SwapChainMtl);
  2857. m_num = 0;
  2858. m_width = _width;
  2859. m_height = _height;
  2860. m_nwh = _nwh;
  2861. m_denseIdx = _denseIdx;
  2862. m_swapChain->init(_nwh);
  2863. }
  2864. void FrameBufferMtl::postReset()
  2865. {
  2866. }
  2867. uint16_t FrameBufferMtl::destroy()
  2868. {
  2869. if (NULL != m_swapChain)
  2870. {
  2871. BX_DELETE(g_allocator, m_swapChain);
  2872. m_swapChain = NULL;
  2873. }
  2874. m_num = 0;
  2875. m_nwh = NULL;
  2876. m_depthHandle.idx = kInvalidHandle;
  2877. uint16_t denseIdx = m_denseIdx;
  2878. m_denseIdx = UINT16_MAX;
  2879. return denseIdx;
  2880. }
  2881. void CommandQueueMtl::init(Device _device)
  2882. {
  2883. m_commandQueue = _device.newCommandQueue();
  2884. m_framesSemaphore.post(BGFX_CONFIG_MAX_FRAME_LATENCY);
  2885. }
  2886. void CommandQueueMtl::shutdown()
  2887. {
  2888. finish(true);
  2889. MTL_RELEASE(m_commandQueue);
  2890. }
  2891. CommandBuffer CommandQueueMtl::alloc()
  2892. {
  2893. m_activeCommandBuffer = m_commandQueue.commandBuffer();
  2894. retain(m_activeCommandBuffer);
  2895. return m_activeCommandBuffer;
  2896. }
  2897. inline void commandBufferFinishedCallback(void* _data)
  2898. {
  2899. CommandQueueMtl* queue = (CommandQueueMtl*)_data;
  2900. if (queue)
  2901. {
  2902. queue->m_framesSemaphore.post();
  2903. }
  2904. }
  2905. void CommandQueueMtl::kick(bool _endFrame, bool _waitForFinish)
  2906. {
  2907. if (m_activeCommandBuffer)
  2908. {
  2909. if (_endFrame)
  2910. {
  2911. m_releaseWriteIndex = (m_releaseWriteIndex + 1) % BGFX_CONFIG_MAX_FRAME_LATENCY;
  2912. m_activeCommandBuffer.addCompletedHandler(commandBufferFinishedCallback, this);
  2913. }
  2914. m_activeCommandBuffer.commit();
  2915. if (_waitForFinish)
  2916. {
  2917. m_activeCommandBuffer.waitUntilCompleted();
  2918. }
  2919. MTL_RELEASE(m_activeCommandBuffer);
  2920. }
  2921. }
  2922. void CommandQueueMtl::finish(bool _finishAll)
  2923. {
  2924. if (_finishAll)
  2925. {
  2926. uint32_t count = m_activeCommandBuffer != NULL
  2927. ? 2
  2928. : 3
  2929. ;
  2930. for (uint32_t ii = 0; ii < count; ++ii)
  2931. {
  2932. consume();
  2933. }
  2934. m_framesSemaphore.post(count);
  2935. }
  2936. else
  2937. {
  2938. consume();
  2939. }
  2940. }
  2941. void CommandQueueMtl::release(NSObject* _ptr)
  2942. {
  2943. m_release[m_releaseWriteIndex].push_back(_ptr);
  2944. }
  2945. void CommandQueueMtl::consume()
  2946. {
  2947. m_framesSemaphore.wait();
  2948. m_releaseReadIndex = (m_releaseReadIndex + 1) % BGFX_CONFIG_MAX_FRAME_LATENCY;
  2949. ResourceArray& ra = m_release[m_releaseReadIndex];
  2950. for (ResourceArray::iterator it = ra.begin(), itEnd = ra.end(); it != itEnd; ++it)
  2951. {
  2952. bgfx::mtl::release(*it);
  2953. }
  2954. ra.clear();
  2955. }
  2956. void TimerQueryMtl::init()
  2957. {
  2958. m_frequency = bx::getHPFrequency();
  2959. }
  2960. void TimerQueryMtl::shutdown()
  2961. {
  2962. }
  2963. uint32_t TimerQueryMtl::begin(uint32_t _resultIdx)
  2964. {
  2965. BX_UNUSED(_resultIdx);
  2966. return 0;
  2967. }
  2968. void TimerQueryMtl::end(uint32_t _idx)
  2969. {
  2970. BX_UNUSED(_idx);
  2971. }
  2972. static void setTimestamp(void* _data)
  2973. {
  2974. *( (int64_t*)_data) = bx::getHPCounter();
  2975. }
  2976. void TimerQueryMtl::addHandlers(CommandBuffer& _commandBuffer)
  2977. {
  2978. while (0 == m_control.reserve(1) )
  2979. {
  2980. m_control.consume(1);
  2981. }
  2982. uint32_t offset = m_control.m_current;
  2983. _commandBuffer.addScheduledHandler(setTimestamp, &m_result[offset].m_begin);
  2984. _commandBuffer.addCompletedHandler(setTimestamp, &m_result[offset].m_end);
  2985. m_control.commit(1);
  2986. }
  2987. bool TimerQueryMtl::get()
  2988. {
  2989. if (0 != m_control.available() )
  2990. {
  2991. uint32_t offset = m_control.m_read;
  2992. m_begin = m_result[offset].m_begin;
  2993. m_end = m_result[offset].m_end;
  2994. m_elapsed = m_end - m_begin;
  2995. m_control.consume(1);
  2996. return true;
  2997. }
  2998. return false;
  2999. }
  3000. void OcclusionQueryMTL::postReset()
  3001. {
  3002. MTL_RELEASE(m_buffer);
  3003. }
  3004. void OcclusionQueryMTL::preReset()
  3005. {
  3006. m_buffer = s_renderMtl->m_device.newBufferWithLength(BX_COUNTOF(m_query) * 8, 0);
  3007. }
  3008. void OcclusionQueryMTL::begin(RenderCommandEncoder& _rce, Frame* _render, OcclusionQueryHandle _handle)
  3009. {
  3010. while (0 == m_control.reserve(1) )
  3011. {
  3012. resolve(_render, true);
  3013. }
  3014. Query& query = m_query[m_control.m_current];
  3015. query.m_handle = _handle;
  3016. uint32_t offset = _handle.idx * 8;
  3017. _rce.setVisibilityResultMode(MTLVisibilityResultModeBoolean, offset);
  3018. }
  3019. void OcclusionQueryMTL::end(RenderCommandEncoder& _rce)
  3020. {
  3021. Query& query = m_query[m_control.m_current];
  3022. uint32_t offset = query.m_handle.idx * 8;
  3023. _rce.setVisibilityResultMode(MTLVisibilityResultModeDisabled, offset);
  3024. m_control.commit(1);
  3025. }
  3026. void OcclusionQueryMTL::resolve(Frame* _render, bool _wait)
  3027. {
  3028. BX_UNUSED(_wait);
  3029. while (0 != m_control.available() )
  3030. {
  3031. Query& query = m_query[m_control.m_read];
  3032. if (isValid(query.m_handle) )
  3033. {
  3034. uint64_t result = ( (uint64_t*)m_buffer.contents() )[query.m_handle.idx];
  3035. _render->m_occlusion[query.m_handle.idx] = int32_t(result);
  3036. }
  3037. m_control.consume(1);
  3038. }
  3039. }
  3040. void OcclusionQueryMTL::invalidate(OcclusionQueryHandle _handle)
  3041. {
  3042. const uint32_t size = m_control.m_size;
  3043. for (uint32_t ii = 0, num = m_control.available(); ii < num; ++ii)
  3044. {
  3045. Query& query = m_query[(m_control.m_read + ii) % size];
  3046. if (query.m_handle.idx == _handle.idx)
  3047. {
  3048. query.m_handle.idx = bgfx::kInvalidHandle;
  3049. }
  3050. }
  3051. }
  3052. void RendererContextMtl::submitBlit(BlitState& _bs, uint16_t _view)
  3053. {
  3054. if (!_bs.hasItem(_view) )
  3055. {
  3056. return;
  3057. }
  3058. endEncoding();
  3059. m_blitCommandEncoder = getBlitCommandEncoder();
  3060. while (_bs.hasItem(_view) )
  3061. {
  3062. const BlitItem& blit = _bs.advance();
  3063. const TextureMtl& src = m_textures[blit.m_src.idx];
  3064. const TextureMtl& dst = m_textures[blit.m_dst.idx];
  3065. #if BX_PLATFORM_OSX
  3066. bool readBack = !!(dst.m_flags & BGFX_TEXTURE_READ_BACK);
  3067. #endif // BX_PLATFORM_OSX
  3068. if (MTLTextureType3D == src.m_ptr.textureType() )
  3069. {
  3070. m_blitCommandEncoder.copyFromTexture(
  3071. src.m_ptr
  3072. , 0
  3073. , 0
  3074. , MTLOriginMake(blit.m_srcX, blit.m_srcY, blit.m_srcZ)
  3075. , MTLSizeMake(blit.m_width, blit.m_height, bx::uint32_imax(blit.m_depth, 1) )
  3076. , dst.m_ptr
  3077. , 0
  3078. , 0
  3079. , MTLOriginMake(blit.m_dstX, blit.m_dstY, blit.m_dstZ)
  3080. );
  3081. #if BX_PLATFORM_OSX
  3082. if (m_macOS11Runtime
  3083. && readBack)
  3084. {
  3085. m_blitCommandEncoder.synchronizeResource(dst.m_ptr);
  3086. }
  3087. #endif // BX_PLATFORM_OSX
  3088. }
  3089. else
  3090. {
  3091. m_blitCommandEncoder.copyFromTexture(
  3092. src.m_ptr
  3093. , blit.m_srcZ
  3094. , blit.m_srcMip
  3095. , MTLOriginMake(blit.m_srcX, blit.m_srcY, 0)
  3096. , MTLSizeMake(blit.m_width, blit.m_height, 1)
  3097. , dst.m_ptr
  3098. , blit.m_dstZ
  3099. , blit.m_dstMip
  3100. , MTLOriginMake(blit.m_dstX, blit.m_dstY, 0)
  3101. );
  3102. #if BX_PLATFORM_OSX
  3103. if (m_macOS11Runtime
  3104. && readBack)
  3105. {
  3106. m_blitCommandEncoder.synchronizeTexture(dst.m_ptr, 0, blit.m_dstMip);
  3107. }
  3108. #endif // BX_PLATFORM_OSX
  3109. }
  3110. }
  3111. if (0 != m_blitCommandEncoder)
  3112. {
  3113. m_blitCommandEncoder.endEncoding();
  3114. m_blitCommandEncoder = 0;
  3115. }
  3116. }
  3117. void RendererContextMtl::submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter)
  3118. {
  3119. m_cmd.finish(false);
  3120. if (NULL == m_commandBuffer)
  3121. {
  3122. m_commandBuffer = m_cmd.alloc();
  3123. }
  3124. BGFX_MTL_PROFILER_BEGIN_LITERAL("rendererSubmit", kColorFrame);
  3125. int64_t timeBegin = bx::getHPCounter();
  3126. int64_t captureElapsed = 0;
  3127. m_gpuTimer.addHandlers(m_commandBuffer);
  3128. if (m_blitCommandEncoder)
  3129. {
  3130. m_blitCommandEncoder.endEncoding();
  3131. m_blitCommandEncoder = 0;
  3132. }
  3133. updateResolution(_render->m_resolution);
  3134. if (0 != _render->m_numScreenShots
  3135. || NULL != m_capture)
  3136. {
  3137. if (m_screenshotTarget)
  3138. {
  3139. if (m_screenshotTarget.width() != m_resolution.width
  3140. || m_screenshotTarget.height() != m_resolution.height)
  3141. {
  3142. MTL_RELEASE(m_screenshotTarget);
  3143. }
  3144. }
  3145. if (NULL == m_screenshotTarget)
  3146. {
  3147. m_textureDescriptor.textureType = MTLTextureType2D;
  3148. m_textureDescriptor.pixelFormat = m_mainFrameBuffer.m_swapChain->m_metalLayer.pixelFormat;
  3149. m_textureDescriptor.width = m_resolution.width;
  3150. m_textureDescriptor.height = m_resolution.height;
  3151. m_textureDescriptor.depth = 1;
  3152. m_textureDescriptor.mipmapLevelCount = 1;
  3153. m_textureDescriptor.sampleCount = 1;
  3154. m_textureDescriptor.arrayLength = 1;
  3155. if (m_iOS9Runtime
  3156. || m_macOS11Runtime)
  3157. {
  3158. m_textureDescriptor.cpuCacheMode = MTLCPUCacheModeDefaultCache;
  3159. m_textureDescriptor.storageMode = BX_ENABLED(BX_PLATFORM_IOS)
  3160. ? (MTLStorageMode)0 // MTLStorageModeShared
  3161. : (MTLStorageMode)1 // MTLStorageModeManaged
  3162. ;
  3163. m_textureDescriptor.usage = 0
  3164. | MTLTextureUsageRenderTarget
  3165. | MTLTextureUsageShaderRead
  3166. ;
  3167. }
  3168. m_screenshotTarget = m_device.newTextureWithDescriptor(m_textureDescriptor);
  3169. }
  3170. }
  3171. else
  3172. {
  3173. MTL_RELEASE(m_screenshotTarget);
  3174. }
  3175. m_uniformBuffer = m_uniformBuffers[m_bufferIndex];
  3176. m_bufferIndex = (m_bufferIndex + 1) % BGFX_CONFIG_MAX_FRAME_LATENCY;
  3177. m_uniformBufferVertexOffset = 0;
  3178. m_uniformBufferFragmentOffset = 0;
  3179. if (0 < _render->m_iboffset)
  3180. {
  3181. BGFX_PROFILER_SCOPE("bgfx/Update transient index buffer", kColorResource);
  3182. TransientIndexBuffer* ib = _render->m_transientIb;
  3183. m_indexBuffers[ib->handle.idx].update(0, bx::strideAlign(_render->m_iboffset,4), ib->data, true);
  3184. }
  3185. if (0 < _render->m_vboffset)
  3186. {
  3187. BGFX_PROFILER_SCOPE("bgfx/Update transient vertex buffer", kColorResource);
  3188. TransientVertexBuffer* vb = _render->m_transientVb;
  3189. m_vertexBuffers[vb->handle.idx].update(0, bx::strideAlign(_render->m_vboffset,4), vb->data, true);
  3190. }
  3191. _render->sort();
  3192. RenderDraw currentState;
  3193. currentState.clear();
  3194. currentState.m_stateFlags = BGFX_STATE_NONE;
  3195. currentState.m_stencil = packStencil(BGFX_STENCIL_NONE, BGFX_STENCIL_NONE);
  3196. RenderBind currentBind;
  3197. currentBind.clear();
  3198. static ViewState viewState;
  3199. viewState.reset(_render);
  3200. uint32_t blendFactor = 0;
  3201. bool wireframe = !!(_render->m_debug&BGFX_DEBUG_WIREFRAME);
  3202. ProgramHandle currentProgram = BGFX_INVALID_HANDLE;
  3203. SortKey key;
  3204. uint16_t view = UINT16_MAX;
  3205. FrameBufferHandle fbh = { BGFX_CONFIG_MAX_FRAME_BUFFERS };
  3206. BlitState bs(_render);
  3207. const uint64_t primType = 0;
  3208. uint8_t primIndex = uint8_t(primType>>BGFX_STATE_PT_SHIFT);
  3209. PrimInfo prim = s_primInfo[primIndex];
  3210. const uint32_t maxComputeBindings = g_caps.limits.maxComputeBindings;
  3211. const uint32_t maxTextureSamplers = g_caps.limits.maxTextureSamplers;
  3212. RenderCommandEncoder rce;
  3213. PipelineStateMtl* currentPso = NULL;
  3214. bool wasCompute = false;
  3215. bool viewHasScissor = false;
  3216. Rect viewScissorRect;
  3217. viewScissorRect.clear();
  3218. uint32_t statsNumPrimsSubmitted[BX_COUNTOF(s_primInfo)] = {};
  3219. uint32_t statsNumPrimsRendered[BX_COUNTOF(s_primInfo)] = {};
  3220. uint32_t statsNumInstances[BX_COUNTOF(s_primInfo)] = {};
  3221. uint32_t statsNumDrawIndirect[BX_COUNTOF(s_primInfo)] = {};
  3222. uint32_t statsNumIndices = 0;
  3223. uint32_t statsKeyType[2] = {};
  3224. Profiler<TimerQueryMtl> profiler(
  3225. _render
  3226. , m_gpuTimer
  3227. , s_viewName
  3228. );
  3229. m_occlusionQuery.resolve(_render);
  3230. if (0 == (_render->m_debug&BGFX_DEBUG_IFH) )
  3231. {
  3232. viewState.m_rect = _render->m_view[0].m_rect;
  3233. int32_t numItems = _render->m_numRenderItems;
  3234. for (int32_t item = 0; item < numItems;)
  3235. {
  3236. const uint64_t encodedKey = _render->m_sortKeys[item];
  3237. const bool isCompute = key.decode(encodedKey, _render->m_viewRemap);
  3238. statsKeyType[isCompute]++;
  3239. const bool viewChanged = 0
  3240. || key.m_view != view
  3241. || item == numItems
  3242. ;
  3243. const uint32_t itemIdx = _render->m_sortValues[item];
  3244. const RenderItem& renderItem = _render->m_renderItem[itemIdx];
  3245. const RenderBind& renderBind = _render->m_renderItemBind[itemIdx];
  3246. ++item;
  3247. if (viewChanged
  3248. || (!isCompute && wasCompute) )
  3249. {
  3250. view = key.m_view;
  3251. currentProgram = BGFX_INVALID_HANDLE;
  3252. if (item > 1)
  3253. {
  3254. profiler.end();
  3255. }
  3256. BGFX_MTL_PROFILER_END();
  3257. setViewType(view, " ");
  3258. BGFX_MTL_PROFILER_BEGIN(view, kColorView);
  3259. profiler.begin(view);
  3260. viewState.m_rect = _render->m_view[view].m_rect;
  3261. submitBlit(bs, view);
  3262. if (!isCompute)
  3263. {
  3264. const Rect& scissorRect = _render->m_view[view].m_scissor;
  3265. viewHasScissor = !scissorRect.isZero();
  3266. viewScissorRect = viewHasScissor ? scissorRect : viewState.m_rect;
  3267. Clear& clr = _render->m_view[view].m_clear;
  3268. Rect viewRect = viewState.m_rect;
  3269. bool clearWithRenderPass = false;
  3270. if ((NULL == m_renderCommandEncoder
  3271. || fbh.idx != _render->m_view[view].m_fbh.idx))
  3272. {
  3273. endEncoding();
  3274. RenderPassDescriptor renderPassDescriptor = newRenderPassDescriptor();
  3275. renderPassDescriptor.visibilityResultBuffer = m_occlusionQuery.m_buffer;
  3276. fbh = _render->m_view[view].m_fbh;
  3277. uint32_t width = m_resolution.width;
  3278. uint32_t height = m_resolution.height;
  3279. if (isValid(fbh) )
  3280. {
  3281. FrameBufferMtl& frameBuffer = m_frameBuffers[fbh.idx];
  3282. width = frameBuffer.m_width;
  3283. height = frameBuffer.m_height;
  3284. }
  3285. clearWithRenderPass = true
  3286. && 0 == viewRect.m_x
  3287. && 0 == viewRect.m_y
  3288. && width == viewRect.m_width
  3289. && height == viewRect.m_height
  3290. ;
  3291. setFrameBuffer(renderPassDescriptor, fbh);
  3292. if (clearWithRenderPass)
  3293. {
  3294. for (uint32_t ii = 0; ii < g_caps.limits.maxFBAttachments; ++ii)
  3295. {
  3296. MTLRenderPassColorAttachmentDescriptor* desc = renderPassDescriptor.colorAttachments[ii];
  3297. if (desc.texture != NULL)
  3298. {
  3299. if (0 != (BGFX_CLEAR_COLOR & clr.m_flags) )
  3300. {
  3301. if (0 != (BGFX_CLEAR_COLOR_USE_PALETTE & clr.m_flags) )
  3302. {
  3303. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE-1, clr.m_index[ii]);
  3304. const float* rgba = _render->m_colorPalette[index];
  3305. const float rr = rgba[0];
  3306. const float gg = rgba[1];
  3307. const float bb = rgba[2];
  3308. const float aa = rgba[3];
  3309. desc.clearColor = MTLClearColorMake(rr, gg, bb, aa);
  3310. }
  3311. else
  3312. {
  3313. float rr = clr.m_index[0]*1.0f/255.0f;
  3314. float gg = clr.m_index[1]*1.0f/255.0f;
  3315. float bb = clr.m_index[2]*1.0f/255.0f;
  3316. float aa = clr.m_index[3]*1.0f/255.0f;
  3317. desc.clearColor = MTLClearColorMake(rr, gg, bb, aa);
  3318. }
  3319. desc.loadAction = MTLLoadActionClear;
  3320. }
  3321. else
  3322. {
  3323. desc.loadAction = MTLLoadActionLoad;
  3324. }
  3325. if (NULL != m_capture
  3326. && !isValid(fbh)
  3327. && m_hasStoreActionStoreAndMultisampleResolve)
  3328. {
  3329. desc.storeAction = desc.texture.sampleCount > 1 ? MTLStoreActionStoreAndMultisampleResolve : MTLStoreActionStore;
  3330. }
  3331. else
  3332. {
  3333. desc.storeAction = desc.texture.sampleCount > 1 ? MTLStoreActionMultisampleResolve : MTLStoreActionStore;
  3334. }
  3335. }
  3336. }
  3337. RenderPassDepthAttachmentDescriptor depthAttachment = renderPassDescriptor.depthAttachment;
  3338. if (NULL != depthAttachment.texture)
  3339. {
  3340. depthAttachment.clearDepth = clr.m_depth;
  3341. depthAttachment.loadAction = 0 != (BGFX_CLEAR_DEPTH & clr.m_flags)
  3342. ? MTLLoadActionClear
  3343. : MTLLoadActionLoad
  3344. ;
  3345. depthAttachment.storeAction = NULL != m_mainFrameBuffer.m_swapChain->m_backBufferColorMsaa
  3346. ? MTLStoreActionDontCare
  3347. : MTLStoreActionStore
  3348. ;
  3349. }
  3350. RenderPassStencilAttachmentDescriptor stencilAttachment = renderPassDescriptor.stencilAttachment;
  3351. if (NULL != stencilAttachment.texture)
  3352. {
  3353. stencilAttachment.clearStencil = clr.m_stencil;
  3354. stencilAttachment.loadAction = 0 != (BGFX_CLEAR_STENCIL & clr.m_flags)
  3355. ? MTLLoadActionClear
  3356. : MTLLoadActionLoad
  3357. ;
  3358. stencilAttachment.storeAction = NULL != m_mainFrameBuffer.m_swapChain->m_backBufferColorMsaa
  3359. ? MTLStoreActionDontCare
  3360. : MTLStoreActionStore
  3361. ;
  3362. }
  3363. }
  3364. else
  3365. {
  3366. for (uint32_t ii = 0; ii < g_caps.limits.maxFBAttachments; ++ii)
  3367. {
  3368. MTLRenderPassColorAttachmentDescriptor* desc = renderPassDescriptor.colorAttachments[ii];
  3369. if (desc.texture != NULL)
  3370. {
  3371. desc.loadAction = MTLLoadActionLoad;
  3372. }
  3373. }
  3374. RenderPassDepthAttachmentDescriptor depthAttachment = renderPassDescriptor.depthAttachment;
  3375. if (NULL != depthAttachment.texture)
  3376. {
  3377. depthAttachment.loadAction = MTLLoadActionLoad;
  3378. depthAttachment.storeAction = MTLStoreActionStore;
  3379. }
  3380. RenderPassStencilAttachmentDescriptor stencilAttachment = renderPassDescriptor.stencilAttachment;
  3381. if (NULL != stencilAttachment.texture)
  3382. {
  3383. stencilAttachment.loadAction = MTLLoadActionLoad;
  3384. stencilAttachment.storeAction = MTLStoreActionStore;
  3385. }
  3386. }
  3387. rce = m_commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor);
  3388. m_renderCommandEncoder = rce;
  3389. m_renderCommandEncoderFrameBufferHandle = fbh;
  3390. MTL_RELEASE(renderPassDescriptor);
  3391. }
  3392. else if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION) )
  3393. {
  3394. rce.popDebugGroup();
  3395. }
  3396. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION) )
  3397. {
  3398. rce.pushDebugGroup(s_viewName[view]);
  3399. }
  3400. rce.setTriangleFillMode(wireframe ? MTLTriangleFillModeLines : MTLTriangleFillModeFill);
  3401. MTLViewport vp;
  3402. vp.originX = viewState.m_rect.m_x;
  3403. vp.originY = viewState.m_rect.m_y;
  3404. vp.width = viewState.m_rect.m_width;
  3405. vp.height = viewState.m_rect.m_height;
  3406. vp.znear = 0.0f;
  3407. vp.zfar = 1.0f;
  3408. rce.setViewport(vp);
  3409. MTLScissorRect sciRect = {
  3410. viewState.m_rect.m_x,
  3411. viewState.m_rect.m_y,
  3412. viewState.m_rect.m_width,
  3413. viewState.m_rect.m_height
  3414. };
  3415. rce.setScissorRect(sciRect);
  3416. if (BGFX_CLEAR_NONE != (clr.m_flags & BGFX_CLEAR_MASK)
  3417. && !clearWithRenderPass)
  3418. {
  3419. clearQuad(_clearQuad, viewState.m_rect, clr, _render->m_colorPalette);
  3420. }
  3421. }
  3422. }
  3423. if (isCompute)
  3424. {
  3425. if (!wasCompute)
  3426. {
  3427. wasCompute = true;
  3428. endEncoding();
  3429. rce = NULL;
  3430. setViewType(view, "C");
  3431. BGFX_MTL_PROFILER_END();
  3432. BGFX_MTL_PROFILER_BEGIN(view, kColorCompute);
  3433. m_computeCommandEncoder = m_commandBuffer.computeCommandEncoder();
  3434. }
  3435. else if (viewChanged && BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION) )
  3436. {
  3437. m_computeCommandEncoder.popDebugGroup();
  3438. }
  3439. if (viewChanged
  3440. && BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION) )
  3441. {
  3442. s_viewName[view][3] = L'C';
  3443. m_computeCommandEncoder.pushDebugGroup(s_viewName[view]);
  3444. s_viewName[view][3] = L' ';
  3445. }
  3446. const RenderCompute& compute = renderItem.compute;
  3447. bool programChanged = false;
  3448. rendererUpdateUniforms(this, _render->m_uniformBuffer[compute.m_uniformIdx], compute.m_uniformBegin, compute.m_uniformEnd);
  3449. if (key.m_program.idx != currentProgram.idx)
  3450. {
  3451. currentProgram = key.m_program;
  3452. currentPso = getComputePipelineState(currentProgram);
  3453. if (NULL == currentPso)
  3454. {
  3455. currentProgram = BGFX_INVALID_HANDLE;
  3456. continue;
  3457. }
  3458. m_computeCommandEncoder.setComputePipelineState(currentPso->m_cps);
  3459. programChanged = true;
  3460. }
  3461. if (isValid(currentProgram)
  3462. && NULL != currentPso)
  3463. {
  3464. uint32_t vertexUniformBufferSize = currentPso->m_vshConstantBufferSize;
  3465. if (0 != vertexUniformBufferSize)
  3466. {
  3467. m_uniformBufferVertexOffset = bx::alignUp(
  3468. m_uniformBufferVertexOffset
  3469. , currentPso->m_vshConstantBufferAlignment
  3470. );
  3471. m_computeCommandEncoder.setBuffer(m_uniformBuffer, m_uniformBufferVertexOffset, 0);
  3472. }
  3473. UniformBuffer* vcb = currentPso->m_vshConstantBuffer;
  3474. if (NULL != vcb)
  3475. {
  3476. commit(*vcb);
  3477. }
  3478. viewState.setPredefined<4>(this, view, *currentPso, _render, compute);
  3479. m_uniformBufferVertexOffset += vertexUniformBufferSize;
  3480. }
  3481. BX_UNUSED(programChanged);
  3482. for (uint8_t stage = 0; stage < maxComputeBindings; ++stage)
  3483. {
  3484. const Binding& bind = renderBind.m_bind[stage];
  3485. if (kInvalidHandle != bind.m_idx)
  3486. {
  3487. switch (bind.m_type)
  3488. {
  3489. case Binding::Image:
  3490. {
  3491. TextureMtl& texture = m_textures[bind.m_idx];
  3492. m_computeCommandEncoder.setTexture(texture.getTextureMipLevel(bind.m_mip), stage);
  3493. }
  3494. break;
  3495. case Binding::Texture:
  3496. {
  3497. TextureMtl& texture = m_textures[bind.m_idx];
  3498. uint32_t flags = bind.m_samplerFlags;
  3499. m_computeCommandEncoder.setTexture(texture.m_ptr, stage);
  3500. m_computeCommandEncoder.setSamplerState(
  3501. 0 == (BGFX_SAMPLER_INTERNAL_DEFAULT & flags)
  3502. ? getSamplerState(flags)
  3503. : texture.m_sampler
  3504. , stage
  3505. );
  3506. }
  3507. break;
  3508. case Binding::IndexBuffer:
  3509. case Binding::VertexBuffer:
  3510. {
  3511. const BufferMtl& buffer = Binding::IndexBuffer == bind.m_type
  3512. ? m_indexBuffers[bind.m_idx]
  3513. : m_vertexBuffers[bind.m_idx]
  3514. ;
  3515. m_computeCommandEncoder.setBuffer(buffer.m_ptr, 0, stage + 1);
  3516. }
  3517. break;
  3518. }
  3519. }
  3520. }
  3521. MTLSize threadsPerGroup = MTLSizeMake(
  3522. currentPso->m_numThreads[0]
  3523. , currentPso->m_numThreads[1]
  3524. , currentPso->m_numThreads[2]
  3525. );
  3526. if (isValid(compute.m_indirectBuffer) )
  3527. {
  3528. const VertexBufferMtl& vb = m_vertexBuffers[compute.m_indirectBuffer.idx];
  3529. uint32_t numDrawIndirect = UINT16_MAX == compute.m_numIndirect
  3530. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  3531. : compute.m_numIndirect
  3532. ;
  3533. uint32_t args = compute.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  3534. for (uint32_t ii = 0; ii < numDrawIndirect; ++ii)
  3535. {
  3536. m_computeCommandEncoder.dispatchThreadgroupsWithIndirectBuffer(
  3537. vb.m_ptr
  3538. , args
  3539. , threadsPerGroup
  3540. );
  3541. args += BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  3542. }
  3543. }
  3544. else
  3545. {
  3546. m_computeCommandEncoder.dispatchThreadgroups(
  3547. MTLSizeMake(compute.m_numX, compute.m_numY, compute.m_numZ)
  3548. , threadsPerGroup
  3549. );
  3550. }
  3551. continue;
  3552. }
  3553. bool resetState = viewChanged || wasCompute;
  3554. if (wasCompute)
  3555. {
  3556. wasCompute = false;
  3557. currentProgram = BGFX_INVALID_HANDLE;
  3558. setViewType(view, " ");
  3559. BGFX_MTL_PROFILER_END();
  3560. BGFX_MTL_PROFILER_BEGIN(view, kColorDraw);
  3561. }
  3562. const RenderDraw& draw = renderItem.draw;
  3563. const bool hasOcclusionQuery = 0 != (draw.m_stateFlags & BGFX_STATE_INTERNAL_OCCLUSION_QUERY);
  3564. {
  3565. const bool occluded = true
  3566. && isValid(draw.m_occlusionQuery)
  3567. && !hasOcclusionQuery
  3568. && !isVisible(_render, draw.m_occlusionQuery, 0 != (draw.m_submitFlags&BGFX_SUBMIT_INTERNAL_OCCLUSION_VISIBLE) )
  3569. ;
  3570. if (occluded
  3571. || _render->m_frameCache.isZeroArea(viewScissorRect, draw.m_scissor) )
  3572. {
  3573. if (resetState)
  3574. {
  3575. currentState.clear();
  3576. currentState.m_scissor = !draw.m_scissor;
  3577. currentBind.clear();
  3578. }
  3579. continue;
  3580. }
  3581. }
  3582. const uint64_t newFlags = draw.m_stateFlags;
  3583. uint64_t changedFlags = currentState.m_stateFlags ^ draw.m_stateFlags;
  3584. currentState.m_stateFlags = newFlags;
  3585. const uint64_t newStencil = draw.m_stencil;
  3586. uint64_t changedStencil = currentState.m_stencil ^ draw.m_stencil;
  3587. currentState.m_stencil = newStencil;
  3588. if (resetState)
  3589. {
  3590. currentState.clear();
  3591. currentState.m_scissor = !draw.m_scissor;
  3592. changedFlags = BGFX_STATE_MASK;
  3593. changedStencil = packStencil(BGFX_STENCIL_MASK, BGFX_STENCIL_MASK);
  3594. currentState.m_stateFlags = newFlags;
  3595. currentState.m_stencil = newStencil;
  3596. currentBind.clear();
  3597. currentProgram = BGFX_INVALID_HANDLE;
  3598. setDepthStencilState(newFlags, packStencil(BGFX_STENCIL_DEFAULT, BGFX_STENCIL_DEFAULT) );
  3599. const uint64_t pt = newFlags&BGFX_STATE_PT_MASK;
  3600. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  3601. }
  3602. if (prim.m_type != s_primInfo[primIndex].m_type)
  3603. {
  3604. prim = s_primInfo[primIndex];
  3605. }
  3606. uint16_t scissor = draw.m_scissor;
  3607. if (currentState.m_scissor != scissor)
  3608. {
  3609. currentState.m_scissor = scissor;
  3610. MTLScissorRect rc;
  3611. if (UINT16_MAX == scissor)
  3612. {
  3613. if (viewHasScissor)
  3614. {
  3615. rc.x = viewScissorRect.m_x;
  3616. rc.y = viewScissorRect.m_y;
  3617. rc.width = viewScissorRect.m_width;
  3618. rc.height = viewScissorRect.m_height;
  3619. }
  3620. else
  3621. { // can't disable: set to view rect
  3622. rc.x = viewState.m_rect.m_x;
  3623. rc.y = viewState.m_rect.m_y;
  3624. rc.width = viewState.m_rect.m_width;
  3625. rc.height = viewState.m_rect.m_height;
  3626. }
  3627. }
  3628. else
  3629. {
  3630. Rect scissorRect;
  3631. scissorRect.setIntersect(viewScissorRect, _render->m_frameCache.m_rectCache.m_cache[scissor]);
  3632. rc.x = scissorRect.m_x;
  3633. rc.y = scissorRect.m_y;
  3634. rc.width = scissorRect.m_width;
  3635. rc.height = scissorRect.m_height;
  3636. }
  3637. rce.setScissorRect(rc);
  3638. }
  3639. if ( (0
  3640. | BGFX_STATE_WRITE_Z
  3641. | BGFX_STATE_DEPTH_TEST_MASK
  3642. ) & changedFlags
  3643. || 0 != changedStencil)
  3644. {
  3645. setDepthStencilState(newFlags,newStencil);
  3646. }
  3647. if ( (0
  3648. | BGFX_STATE_CULL_MASK
  3649. | BGFX_STATE_ALPHA_REF_MASK
  3650. | BGFX_STATE_PT_MASK
  3651. | BGFX_STATE_FRONT_CCW
  3652. ) & changedFlags)
  3653. {
  3654. if (BGFX_STATE_FRONT_CCW & changedFlags)
  3655. {
  3656. rce.setFrontFacingWinding((newFlags&BGFX_STATE_FRONT_CCW) ? MTLWindingCounterClockwise : MTLWindingClockwise);
  3657. }
  3658. if (BGFX_STATE_CULL_MASK & changedFlags)
  3659. {
  3660. const uint64_t pt = newFlags&BGFX_STATE_CULL_MASK;
  3661. const uint8_t cullIndex = uint8_t(pt>>BGFX_STATE_CULL_SHIFT);
  3662. rce.setCullMode(s_cullMode[cullIndex]);
  3663. }
  3664. if (BGFX_STATE_ALPHA_REF_MASK & changedFlags)
  3665. {
  3666. uint32_t ref = (newFlags&BGFX_STATE_ALPHA_REF_MASK)>>BGFX_STATE_ALPHA_REF_SHIFT;
  3667. viewState.m_alphaRef = ref/255.0f;
  3668. }
  3669. const uint64_t pt = newFlags&BGFX_STATE_PT_MASK;
  3670. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  3671. if (prim.m_type != s_primInfo[primIndex].m_type)
  3672. {
  3673. prim = s_primInfo[primIndex];
  3674. }
  3675. }
  3676. if (blendFactor != draw.m_rgba
  3677. && !(newFlags & BGFX_STATE_BLEND_INDEPENDENT) )
  3678. {
  3679. const uint32_t rgba = draw.m_rgba;
  3680. float rr = ( (rgba>>24) )/255.0f;
  3681. float gg = ( (rgba>>16)&0xff)/255.0f;
  3682. float bb = ( (rgba>> 8)&0xff)/255.0f;
  3683. float aa = ( (rgba )&0xff)/255.0f;
  3684. rce.setBlendColor(rr,gg,bb,aa);
  3685. blendFactor = draw.m_rgba;
  3686. }
  3687. bool programChanged = false;
  3688. rendererUpdateUniforms(this, _render->m_uniformBuffer[draw.m_uniformIdx], draw.m_uniformBegin, draw.m_uniformEnd);
  3689. bool vertexStreamChanged = hasVertexStreamChanged(currentState, draw);
  3690. if (key.m_program.idx != currentProgram.idx
  3691. || vertexStreamChanged
  3692. || (0
  3693. | BGFX_STATE_BLEND_MASK
  3694. | BGFX_STATE_BLEND_EQUATION_MASK
  3695. | BGFX_STATE_WRITE_RGB
  3696. | BGFX_STATE_WRITE_A
  3697. | BGFX_STATE_BLEND_INDEPENDENT
  3698. | BGFX_STATE_MSAA
  3699. | BGFX_STATE_BLEND_ALPHA_TO_COVERAGE
  3700. ) & changedFlags
  3701. || ( (blendFactor != draw.m_rgba) && !!(newFlags & BGFX_STATE_BLEND_INDEPENDENT) ) )
  3702. {
  3703. currentProgram = key.m_program;
  3704. currentState.m_streamMask = draw.m_streamMask;
  3705. currentState.m_instanceDataBuffer.idx = draw.m_instanceDataBuffer.idx;
  3706. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  3707. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  3708. const VertexLayout* layouts[BGFX_CONFIG_MAX_VERTEX_STREAMS];
  3709. uint32_t numVertices = draw.m_numVertices;
  3710. uint8_t numStreams = 0;
  3711. for (uint32_t idx = 0, streamMask = draw.m_streamMask
  3712. ; 0 != streamMask
  3713. ; streamMask >>= 1, idx += 1, ++numStreams
  3714. )
  3715. {
  3716. const uint32_t ntz = bx::uint32_cnttz(streamMask);
  3717. streamMask >>= ntz;
  3718. idx += ntz;
  3719. currentState.m_stream[idx].m_layoutHandle = draw.m_stream[idx].m_layoutHandle;
  3720. currentState.m_stream[idx].m_handle = draw.m_stream[idx].m_handle;
  3721. currentState.m_stream[idx].m_startVertex = draw.m_stream[idx].m_startVertex;
  3722. const uint16_t handle = draw.m_stream[idx].m_handle.idx;
  3723. const VertexBufferMtl& vb = m_vertexBuffers[handle];
  3724. const uint16_t decl = isValid(draw.m_stream[idx].m_layoutHandle)
  3725. ? draw.m_stream[idx].m_layoutHandle.idx
  3726. : vb.m_layoutHandle.idx;
  3727. const VertexLayout& layout = m_vertexLayouts[decl];
  3728. const uint32_t stride = layout.m_stride;
  3729. layouts[numStreams] = &layout;
  3730. numVertices = bx::uint32_min(UINT32_MAX == draw.m_numVertices
  3731. ? vb.m_size/stride
  3732. : draw.m_numVertices
  3733. , numVertices
  3734. );
  3735. const uint32_t offset = draw.m_stream[idx].m_startVertex * stride;
  3736. rce.setVertexBuffer(vb.m_ptr, offset, idx+1);
  3737. }
  3738. if (!isValid(currentProgram) )
  3739. {
  3740. continue;
  3741. }
  3742. else
  3743. {
  3744. currentPso = NULL;
  3745. if (0 < numStreams)
  3746. {
  3747. currentPso = getPipelineState(
  3748. newFlags
  3749. , draw.m_rgba
  3750. , fbh
  3751. , numStreams
  3752. , layouts
  3753. , currentProgram
  3754. , draw.m_instanceDataStride/16
  3755. );
  3756. }
  3757. if (NULL == currentPso)
  3758. {
  3759. currentProgram = BGFX_INVALID_HANDLE;
  3760. continue;
  3761. }
  3762. rce.setRenderPipelineState(currentPso->m_rps);
  3763. }
  3764. if (isValid(draw.m_instanceDataBuffer) )
  3765. {
  3766. const VertexBufferMtl& inst = m_vertexBuffers[draw.m_instanceDataBuffer.idx];
  3767. rce.setVertexBuffer(inst.m_ptr, draw.m_instanceDataOffset, numStreams+1);
  3768. }
  3769. programChanged = true;
  3770. }
  3771. if (isValid(currentProgram) )
  3772. {
  3773. const uint32_t vertexUniformBufferSize = currentPso->m_vshConstantBufferSize;
  3774. const uint32_t fragmentUniformBufferSize = currentPso->m_fshConstantBufferSize;
  3775. if (0 != vertexUniformBufferSize)
  3776. {
  3777. m_uniformBufferVertexOffset = bx::alignUp(
  3778. m_uniformBufferVertexOffset
  3779. , currentPso->m_vshConstantBufferAlignment
  3780. );
  3781. rce.setVertexBuffer(m_uniformBuffer, m_uniformBufferVertexOffset, 0);
  3782. }
  3783. m_uniformBufferFragmentOffset = m_uniformBufferVertexOffset + vertexUniformBufferSize;
  3784. if (0 != fragmentUniformBufferSize)
  3785. {
  3786. m_uniformBufferFragmentOffset = bx::alignUp(
  3787. m_uniformBufferFragmentOffset
  3788. , currentPso->m_fshConstantBufferAlignment
  3789. );
  3790. rce.setFragmentBuffer(m_uniformBuffer, m_uniformBufferFragmentOffset, 0);
  3791. }
  3792. UniformBuffer* vcb = currentPso->m_vshConstantBuffer;
  3793. if (NULL != vcb)
  3794. {
  3795. commit(*vcb);
  3796. }
  3797. UniformBuffer* fcb = currentPso->m_fshConstantBuffer;
  3798. if (NULL != fcb)
  3799. {
  3800. commit(*fcb);
  3801. }
  3802. viewState.setPredefined<4>(this, view, *currentPso, _render, draw);
  3803. m_uniformBufferFragmentOffset += fragmentUniformBufferSize;
  3804. m_uniformBufferVertexOffset = m_uniformBufferFragmentOffset;
  3805. }
  3806. if (isValid(currentProgram) )
  3807. {
  3808. uint8_t* bindingTypes = currentPso->m_bindingTypes;
  3809. for (uint8_t stage = 0; stage < maxTextureSamplers; ++stage)
  3810. {
  3811. const Binding& bind = renderBind.m_bind[stage];
  3812. Binding& current = currentBind.m_bind[stage];
  3813. if (current.m_idx != bind.m_idx
  3814. || current.m_type != bind.m_type
  3815. || current.m_samplerFlags != bind.m_samplerFlags
  3816. || programChanged)
  3817. {
  3818. if (kInvalidHandle != bind.m_idx)
  3819. {
  3820. switch (bind.m_type)
  3821. {
  3822. case Binding::Texture:
  3823. {
  3824. TextureMtl& texture = m_textures[bind.m_idx];
  3825. texture.commit(stage
  3826. , 0 != (bindingTypes[stage] & PipelineStateMtl::BindToVertexShader)
  3827. , 0 != (bindingTypes[stage] & PipelineStateMtl::BindToFragmentShader)
  3828. , bind.m_samplerFlags
  3829. );
  3830. }
  3831. break;
  3832. case Binding::IndexBuffer:
  3833. case Binding::VertexBuffer:
  3834. {
  3835. const BufferMtl& buffer = Binding::IndexBuffer == bind.m_type
  3836. ? m_indexBuffers[bind.m_idx]
  3837. : m_vertexBuffers[bind.m_idx]
  3838. ;
  3839. if (0 != (bindingTypes[stage] & PipelineStateMtl::BindToVertexShader))
  3840. rce.setVertexBuffer(buffer.m_ptr, 0, stage + 1);
  3841. if (0 != (bindingTypes[stage] & PipelineStateMtl::BindToFragmentShader))
  3842. rce.setFragmentBuffer(buffer.m_ptr, 0, stage + 1);
  3843. }
  3844. break;
  3845. }
  3846. }
  3847. }
  3848. current = bind;
  3849. }
  3850. }
  3851. if (0 != currentState.m_streamMask)
  3852. {
  3853. uint32_t numVertices = draw.m_numVertices;
  3854. if (UINT32_MAX == numVertices)
  3855. {
  3856. const VertexBufferMtl& vb = m_vertexBuffers[currentState.m_stream[0].m_handle.idx];
  3857. uint16_t decl = !isValid(vb.m_layoutHandle) ? draw.m_stream[0].m_layoutHandle.idx : vb.m_layoutHandle.idx;
  3858. const VertexLayout& layout = m_vertexLayouts[decl];
  3859. numVertices = vb.m_size/layout.m_stride;
  3860. }
  3861. uint32_t numIndices = 0;
  3862. uint32_t numPrimsSubmitted = 0;
  3863. uint32_t numInstances = 0;
  3864. uint32_t numPrimsRendered = 0;
  3865. uint32_t numDrawIndirect = 0;
  3866. if (hasOcclusionQuery)
  3867. {
  3868. m_occlusionQuery.begin(rce, _render, draw.m_occlusionQuery);
  3869. }
  3870. if (isValid(draw.m_indirectBuffer) )
  3871. {
  3872. const VertexBufferMtl& vb = m_vertexBuffers[draw.m_indirectBuffer.idx];
  3873. if (isValid(draw.m_indexBuffer) )
  3874. {
  3875. const bool isIndex16 = draw.isIndex16();
  3876. const MTLIndexType indexFormat = isIndex16 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32;
  3877. const IndexBufferMtl& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  3878. numDrawIndirect = UINT16_MAX == draw.m_numIndirect
  3879. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  3880. : draw.m_numIndirect
  3881. ;
  3882. for (uint32_t ii = 0; ii < numDrawIndirect; ++ii)
  3883. {
  3884. rce.drawIndexedPrimitives(prim.m_type, indexFormat, ib.m_ptr, 0, vb.m_ptr, (draw.m_startIndirect + ii )* BGFX_CONFIG_DRAW_INDIRECT_STRIDE);
  3885. }
  3886. }
  3887. else
  3888. {
  3889. numDrawIndirect = UINT16_MAX == draw.m_numIndirect
  3890. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  3891. : draw.m_numIndirect
  3892. ;
  3893. for (uint32_t ii = 0; ii < numDrawIndirect; ++ii)
  3894. {
  3895. rce.drawPrimitives(prim.m_type, vb.m_ptr, (draw.m_startIndirect + ii) * BGFX_CONFIG_DRAW_INDIRECT_STRIDE);
  3896. }
  3897. }
  3898. }
  3899. else
  3900. {
  3901. if (isValid(draw.m_indexBuffer) )
  3902. {
  3903. const bool isIndex16 = draw.isIndex16();
  3904. const uint32_t indexSize = isIndex16 ? 2 : 4;
  3905. const MTLIndexType indexFormat = isIndex16 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32;
  3906. const IndexBufferMtl& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  3907. if (UINT32_MAX == draw.m_numIndices)
  3908. {
  3909. numIndices = ib.m_size/indexSize;
  3910. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  3911. numInstances = draw.m_numInstances;
  3912. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  3913. rce.drawIndexedPrimitives(prim.m_type, numIndices, indexFormat, ib.m_ptr, 0, draw.m_numInstances);
  3914. }
  3915. else if (prim.m_min <= draw.m_numIndices)
  3916. {
  3917. numIndices = draw.m_numIndices;
  3918. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  3919. numInstances = draw.m_numInstances;
  3920. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  3921. rce.drawIndexedPrimitives(prim.m_type, numIndices, indexFormat, ib.m_ptr, draw.m_startIndex * indexSize,numInstances);
  3922. }
  3923. }
  3924. else
  3925. {
  3926. numPrimsSubmitted = numVertices/prim.m_div - prim.m_sub;
  3927. numInstances = draw.m_numInstances;
  3928. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  3929. rce.drawPrimitives(prim.m_type, 0, numVertices, draw.m_numInstances);
  3930. }
  3931. }
  3932. if (hasOcclusionQuery)
  3933. {
  3934. m_occlusionQuery.end(rce);
  3935. }
  3936. statsNumPrimsSubmitted[primIndex] += numPrimsSubmitted;
  3937. statsNumPrimsRendered[primIndex] += numPrimsRendered;
  3938. statsNumInstances[primIndex] += numInstances;
  3939. statsNumDrawIndirect[primIndex] += numDrawIndirect;
  3940. statsNumIndices += numIndices;
  3941. }
  3942. }
  3943. if (wasCompute)
  3944. {
  3945. invalidateCompute();
  3946. setViewType(view, "C");
  3947. BGFX_MTL_PROFILER_END();
  3948. BGFX_MTL_PROFILER_BEGIN(view, kColorCompute);
  3949. }
  3950. submitBlit(bs, BGFX_CONFIG_MAX_VIEWS);
  3951. if (0 < _render->m_numRenderItems)
  3952. {
  3953. captureElapsed = -bx::getHPCounter();
  3954. capture();
  3955. rce = m_renderCommandEncoder;
  3956. captureElapsed += bx::getHPCounter();
  3957. profiler.end();
  3958. }
  3959. }
  3960. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION) )
  3961. {
  3962. if (0 < _render->m_numRenderItems)
  3963. {
  3964. rce.popDebugGroup();
  3965. }
  3966. }
  3967. BGFX_MTL_PROFILER_END();
  3968. int64_t timeEnd = bx::getHPCounter();
  3969. int64_t frameTime = timeEnd - timeBegin;
  3970. static int64_t min = frameTime;
  3971. static int64_t max = frameTime;
  3972. min = bx::min<int64_t>(min, frameTime);
  3973. max = bx::max<int64_t>(max, frameTime);
  3974. static uint32_t maxGpuLatency = 0;
  3975. static double maxGpuElapsed = 0.0f;
  3976. double elapsedGpuMs = 0.0;
  3977. do
  3978. {
  3979. double toGpuMs = 1000.0 / double(m_gpuTimer.m_frequency);
  3980. elapsedGpuMs = m_gpuTimer.m_elapsed * toGpuMs;
  3981. maxGpuElapsed = elapsedGpuMs > maxGpuElapsed ? elapsedGpuMs : maxGpuElapsed;
  3982. }
  3983. while (m_gpuTimer.get() );
  3984. maxGpuLatency = bx::uint32_imax(maxGpuLatency, m_gpuTimer.m_control.available()-1);
  3985. const int64_t timerFreq = bx::getHPFrequency();
  3986. Stats& perfStats = _render->m_perfStats;
  3987. perfStats.cpuTimeBegin = timeBegin;
  3988. perfStats.cpuTimeEnd = timeEnd;
  3989. perfStats.cpuTimerFreq = timerFreq;
  3990. perfStats.gpuTimeBegin = m_gpuTimer.m_begin;
  3991. perfStats.gpuTimeEnd = m_gpuTimer.m_end;
  3992. perfStats.gpuTimerFreq = m_gpuTimer.m_frequency;
  3993. perfStats.numDraw = statsKeyType[0];
  3994. perfStats.numCompute = statsKeyType[1];
  3995. perfStats.numBlit = _render->m_numBlitItems;
  3996. perfStats.maxGpuLatency = maxGpuLatency;
  3997. bx::memCopy(perfStats.numPrims, statsNumPrimsRendered, sizeof(perfStats.numPrims) );
  3998. perfStats.gpuMemoryMax = -INT64_MAX;
  3999. perfStats.gpuMemoryUsed = -INT64_MAX;
  4000. rce.setTriangleFillMode(MTLTriangleFillModeFill);
  4001. if (_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  4002. {
  4003. rce.pushDebugGroup("debugstats");
  4004. TextVideoMem& tvm = m_textVideoMem;
  4005. static int64_t next = timeEnd;
  4006. if (timeEnd >= next)
  4007. {
  4008. next = timeEnd + timerFreq;
  4009. double freq = double(timerFreq);
  4010. double toMs = 1000.0/freq;
  4011. tvm.clear();
  4012. uint16_t pos = 0;
  4013. tvm.printf(0, pos++, BGFX_CONFIG_DEBUG ? 0x8c : 0x8f
  4014. , " %s / " BX_COMPILER_NAME
  4015. " / " BX_CPU_NAME
  4016. " / " BX_ARCH_NAME
  4017. " / " BX_PLATFORM_NAME
  4018. " / Version 1.%d.%d (commit: " BGFX_REV_SHA1 ")"
  4019. , getRendererName()
  4020. , BGFX_API_VERSION
  4021. , BGFX_REV_NUMBER
  4022. );
  4023. pos = 10;
  4024. tvm.printf(10, pos++, 0x8b, " Frame: %7.3f, % 7.3f \x1f, % 7.3f \x1e [ms] / % 6.2f FPS "
  4025. , double(frameTime)*toMs
  4026. , double(min)*toMs
  4027. , double(max)*toMs
  4028. , freq/frameTime
  4029. );
  4030. const uint32_t msaa = (m_resolution.reset&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  4031. tvm.printf(10, pos++, 0x8b, " Reset flags: [%c] vsync, [%c] MSAAx%d, [%c] MaxAnisotropy "
  4032. , !!(m_resolution.reset&BGFX_RESET_VSYNC) ? '\xfe' : ' '
  4033. , 0 != msaa ? '\xfe' : ' '
  4034. , 1<<msaa
  4035. , !!(m_resolution.reset&BGFX_RESET_MAXANISOTROPY) ? '\xfe' : ' '
  4036. );
  4037. double elapsedCpuMs = double(frameTime)*toMs;
  4038. tvm.printf(10, pos++, 0x8b, " Submitted: %4d (draw %4d, compute %4d) / CPU %3.4f [ms] %c GPU %3.4f [ms] (latency %d)"
  4039. , _render->m_numRenderItems
  4040. , statsKeyType[0]
  4041. , statsKeyType[1]
  4042. , elapsedCpuMs
  4043. , elapsedCpuMs > maxGpuElapsed ? '>' : '<'
  4044. , maxGpuElapsed
  4045. , maxGpuLatency
  4046. );
  4047. maxGpuLatency = 0;
  4048. maxGpuElapsed = 0.0;
  4049. for (uint32_t ii = 0; ii < Topology::Count; ++ii)
  4050. {
  4051. tvm.printf(10, pos++, 0x8b, " %10s: %7d (#inst: %5d), submitted: %7d"
  4052. , getName(Topology::Enum(ii) )
  4053. , statsNumPrimsRendered[ii]
  4054. , statsNumInstances[ii]
  4055. , statsNumPrimsSubmitted[ii]
  4056. );
  4057. }
  4058. tvm.printf(10, pos++, 0x8b, " Indices: %7d ", statsNumIndices);
  4059. // tvm.printf(10, pos++, 0x8b, " Uniform size: %7d, Max: %7d ", _render->m_uniformEnd, _render->m_uniformMax);
  4060. tvm.printf(10, pos++, 0x8b, " DVB size: %7d ", _render->m_vboffset);
  4061. tvm.printf(10, pos++, 0x8b, " DIB size: %7d ", _render->m_iboffset);
  4062. pos++;
  4063. double captureMs = double(captureElapsed)*toMs;
  4064. tvm.printf(10, pos++, 0x8b, " Capture: %3.4f [ms]", captureMs);
  4065. uint8_t attr[2] = { 0x8c, 0x8a };
  4066. uint8_t attrIndex = _render->m_waitSubmit < _render->m_waitRender;
  4067. tvm.printf(10, pos++, attr[attrIndex &1], " Submit wait: %3.4f [ms]", _render->m_waitSubmit*toMs);
  4068. tvm.printf(10, pos++, attr[(attrIndex+1)&1], " Render wait: %3.4f [ms]", _render->m_waitRender*toMs);
  4069. min = frameTime;
  4070. max = frameTime;
  4071. }
  4072. blit(this, _textVideoMemBlitter, tvm);
  4073. rce = m_renderCommandEncoder;
  4074. rce.popDebugGroup();
  4075. }
  4076. else if (_render->m_debug & BGFX_DEBUG_TEXT)
  4077. {
  4078. rce.pushDebugGroup("debugtext");
  4079. blit(this, _textVideoMemBlitter, _render->m_textVideoMem);
  4080. rce = m_renderCommandEncoder;
  4081. rce.popDebugGroup();
  4082. }
  4083. endEncoding();
  4084. m_renderCommandEncoderFrameBufferHandle.idx = kInvalidHandle;
  4085. if (m_screenshotTarget)
  4086. {
  4087. RenderPassDescriptor renderPassDescriptor = newRenderPassDescriptor();
  4088. renderPassDescriptor.colorAttachments[0].texture = m_mainFrameBuffer.m_swapChain->currentDrawableTexture();
  4089. renderPassDescriptor.colorAttachments[0].storeAction = MTLStoreActionStore;
  4090. rce = m_commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor);
  4091. MTL_RELEASE(renderPassDescriptor);
  4092. rce.setCullMode(MTLCullModeNone);
  4093. rce.setRenderPipelineState(m_screenshotBlitRenderPipelineState);
  4094. rce.setFragmentSamplerState(getSamplerState(BGFX_SAMPLER_U_CLAMP|BGFX_SAMPLER_V_CLAMP|BGFX_SAMPLER_MIN_POINT|BGFX_SAMPLER_MAG_POINT|BGFX_SAMPLER_MIP_POINT), 0);
  4095. rce.setFragmentTexture(m_screenshotTarget, 0);
  4096. rce.drawPrimitives(MTLPrimitiveTypeTriangle, 0, 3, 1);
  4097. rce.endEncoding();
  4098. }
  4099. }
  4100. } /* namespace mtl */ } // namespace bgfx
  4101. #else
  4102. namespace bgfx { namespace mtl
  4103. {
  4104. RendererContextI* rendererCreate(const Init& _init)
  4105. {
  4106. BX_UNUSED(_init);
  4107. return NULL;
  4108. }
  4109. void rendererDestroy()
  4110. {
  4111. }
  4112. } /* namespace mtl */ } // namespace bgfx
  4113. #endif // BGFX_CONFIG_RENDERER_METAL