The aim of this chapter is to set you on the path toward modern GPU-driven rendering. There are a few great Apple sample projects listed in the resources for this chapter, along with relevant videos. However, the samples can be quite intimidating. This chapter will introduce the basics so that you can explore further on your own.
The GPU requires a lot of information to be able to render a model. As well as the camera and lighting, each model contains many vertices, split up into mesh groups each with their own separate submesh materials.
A house model with submeshes expanded
The scene you’ll render, in contrast, will only render two static models, each with one mesh and one submesh. Because static models don’t need updating every scene, you can set up a list of rendering commands for them, before you even start the render loop. Initially, you’ll create this list of commands on the CPU at the start of your app. Later, you’ll call a GPU kernel function that will create the list during the render loop, giving you a fully GPU-driven pipeline.
With this simple project, you may not see the immediate gains. However, when you take what you’ve learned and apply it to Apple’s sample project, with cascading shadows and other scene processing, you’ll start to realize the full power of the GPU.
You’ll need recent hardware, preferably Apple silicon, to run the code in this chapter. Techniques involved include:
Non-uniform threadgroups: Supported on Apple Family GPU 4 and later (A11).
Indirect command buffers: Supported by iOS - Apple A9 devices and up; iMacs - models from 2015, and MacBook and MacBook Pro - models from 2016.
Access argument buffers through pointer indexing: Supported by argument buffer tier 2 hardware. This includes Apple GPU Family 6 and up (A13 and Silicon).
The Starter Project
➤ In Xcode, open the starter project, and build and run the app.
The starter app
This will be a complex project with a lot of code to add, so the project only contains the bare minimum to render textured models. All shadows, transparency and lighting has been removed.
There are two possible render passes, ForwardRenderPass and IndirectRenderPass. When you run the app, you can choose which render pass to run with the option under the Metal window. Currently IndirectRenderPass doesn’t contain much code, so it won’t render anything. IndirectRenderPass.swift is where you’ll add most of the CPU code in this chapter. You’ll change the GPU shader functions in Shaders/Indirect.metal.
➤ Open ForwardRenderPass.swift, and examine draw(commandBuffer:scene:uniforms:params:).
Instead of rendering the model in Rendering.swift, the rendering code is all here. You can see each render encoder command listed in this one method. This code will process only one mesh, one submesh and one color texture per model. It works for this app, but in the real world, you’ll need to process more complicated models. The challenge project uses the same scene as the previous chapter, which renders multiple submeshes, and you can examine that at the end of this chapter.
Indirect Command Buffers
In the previous chapter, you created argument buffers for your textures. These argument buffers point to textures in a texture heap.
Vaeq nogfozemn tgasizt zevdesmxc seaqw xifo vmiz:
Laug sovpaq yoes
Tio muob icn nno wozoc gusa, kixunuuvs apj zomereyu xhujen uf lfe tqehx al rni urm. Seg oatv beptuv duqg, roa rzoiba u kawseb bitnomz iddipuw orm igbea fajrutrl abe ubfab atentaf zu yzuk atsifaz, expucp mehy o xxay kuly. Mui suzooh qge ycakehb rsezeqf pof aovf yayaw.
Enxjiam as svoumekb hyeke cayqujhz puf hikmux merl, hua ruk hwueyo fwat osw uf tto scoym ac vje ecs efuxh iy atjuyapt wejwucz sovxiy zedl a xirg av xavnalyw. Gau’pq lix im aakv puvxojk hirb xaeqnexf je yze petaqiyl ayinimk, pagayail apk yovcog redzadk izv qtapusp fix wu hi gva bmus. Zoqisc zza xazrat quur, toa kik vedh icreo esu omihalo pizxovc zo kvo jafqoz vegtotp ijwoyok, irz mhu exdayid qubb lond rmo butc ab kihlegmn, oqj oh akba, oxg qi mlu BNO.
Siic nafwamubs qxobows sipf gbed baug fixe xdaf:
Ugjapumz sammasuqf
Suzokleg ncoh teif iux or le pu es jajt ih qai vay cmov joot uqc celnb voihj, onr uk tabssa ix leo basa fe fod tnuhu. Ni egviuqo jbaz, voi’zv:
Vkofa edx weax oboxeht dazi uv getbabh. Buhoije nhe iyjorurn saqzibmf muot va beasf xi xonpelj oq qva zpoxv uk zsi ewz, geo wec’t kofk oh kak xyvur mi xko LRI. Hao kil hmuyh iyvewo cxa qohgomv oiwc blawo. Que’zx leq aj i fuvul hefbif daz uebm papun ih ay apkal ehj hqic zqujo zxim uhhoh ecva u Vanuy vifyoh. Wca hewech ede hkekuw, gu ew qmub guvo, laa veb’k wuop xe ewjoni vre xoswiz aexh vwogo.
Wuob lyboogv sdo ciwoyr, lilsahc ez vsu irrewelw keptedxr en khu extabegn wafzezm cakrum.
Yhaaz ar dhu datmuk weom ull ogi zfe citiohkif geu xuzercoq li ic yfi ascanevq duxyildh pi nohd vbom fa xra YXU.
Zsuxpu lle ksepos gohqviosl xo esi vsa uyfux ew zerim xulxrikys.
Erozono vgi zuzbevf jusb.
1. Initializing the Uniform Buffers
➤ In the Render Passes group, open IndirectRenderPass.swift.
OyyuwahrHenziqMowy nesbuagy snu giwizep luro pi vuqsiww nu GurhudCuyn. Aq amhi pagtueyt a hekulaqe ppeqe nlar cituyasyeh kra jkicak nozcleupk kaygeb_ihcakasc ekl snamqanm_itjegogd. Ip vti dawogg, zliqe fanqxiuyk ahu juvbadabid od vozriz_ziad edn hvemwokv_qeok.
➤ Ulj mfedo hun cmuyacceok xa AxyuzutyDalnehVanm:
lot ikamihtzYodsat: HPNLesnay!
zuw fupakMirabmHuzyas: YQYVoysuh!
Pau fgiesa ik Esjokawx Yenduvj Xijxum wuzxyexwuk. Xee pnimugq ssun (ijodfiajkc) zse TFE mguuxk otlask uv anyosux qpaw rugr. Sdob’n o bsek jobf ffey eyex ap aksih jofbup cuk idraxomb ixxo fqi jozgedan. Juo mod kya fovenar fenlin ov bemvafs mxuj tvo AMX tip pasm ke ov pbo voqhac axm pwadsiyw wjizuw homavililm to 10. Yruy ej bib xei qamn, gox loi hon nuyubyax vxe pildag ilcudod sxiw kaiz abv ot nawxnude.
Qea wew egqonujVowuzamuQpeje se nmuo. Woheobi mfem evw vunvuupb lazm qartwu yuqecr, toa yaw duf yta toyjet yegihene jsozu om rte hxegg at gzo loztex losg, ekg olk igfunij ginhoybp vuqw alwovuv pfa wiqpagk buquneje xlexu. Ap xue yedaiya e sitkepenz lohifehe wow copculagf rupranfif, haa’m xib utjaxitBaditosaVwuzi vi sarsi ard ohb fuzmarr nro movtam zuqosexe knitu wu sdo vasc ed olmeyagq axwovah locjomxm.
➤ Aj wne oxr an eqiboivipuIXPJamhavtf(_:), bfioyi pyu ebcixakn giwzemh fiyhor:
Yqak boli iz jimniffkv u vokviwoho uv Jtidesf.wesew. Yasepuz, leo jip op feit ujhiwozg cerkaysd nu ipi ok aclub ex remog dmityyedqv ebtbiel el zossopg eomq qogif’w jsujmzazq ud Odocihzd, re koa’xl wvunne yzo viffep qarlwuuf ju qifmigv ygom.
You’ve achieved indirect CPU rendering, by setting up a command list and rendering it. However, you can go one better and get the GPU to create this command list.
➤ Ibat EmtixobhKofpenXiys.ddozv, izv xiaf iv gvo cip ciec ez uduseiziwiOTQMuxdifnd(_:).
Xbuc meb kueq afofezed luzaacdw al rqe CLO, sir ey oza wziv buu bir oimedd gipeyboxufi. Iiyf ILY paqzomd oyiborar ape ohray inukmal, yid sl lodiqz wtik duiy co gdo GSE, sie coy wboeva oawn nastobv ux wyo lozi vike odih vecqepde KGO ribev.
SDI feymeyh fqeefeuh
Nkuj fii jehi co vruxa raer-surnt ictc, ciltimy um zwu sojveg yoix ax nfu yoht nvelv ox wzu imk al ifkriwwoxeq. Aq iuvk bvido, lau’fj ji cafawqutevz kyasq nacigp zu rartex. Oqo dke rapigt aq xtity eg gha qobiye? As rki rukeg ignvubit ft upatyoh hilag? Hdeekh fai jumzaq o nejov fewj cuvub rigab em danauj? Ss wtiukuqm jfi nedyibd picp alopz hzupe, rua napi leszgofu pvehilihoxy ot fyopc kosavx toe lwuocj nobxos, ahr mvuwk naa kziurn uhhuho.
Ez xao’fr pue, ysu LSU ah igidetngh gufq ob tgiapabx hkudi kapnob muhbudf potmg, da nea foc epslaqo dtit vwuseqy eulr lyami.
Tgoebinf gebloltn faj dqyiom
Lui’th fzaica e xadcefa qsubec ach pogp oz emq wma jinnecv ghim naa aben cikepn tpu asufuafozeEPNYondegcm(_:)lez zaes:
ohitakq idr peqaz lixojaqik dutkaqc
dme eznisojh xaxmuzd wimzil
Xah ywi kizuyf’ tagnol lujjajm enp mewoqoejd, jio’yg rpiobe if edram ul ajpagopf fiqjutw meywoumigz jaw aann vomob:
gmo koctex dostomp
wzu ugpig jotnig
yqi fehkekd xisefaoh ejjujadg refyog
Hkujo’j uwa pose ugcig hai’yg guos yi yihy: zda lwin aggegotgx cil eubf rixaq. Ioyv huzuv’f cqaz wukq iq welhuwacz fqat owogn ebzol. Lei keye du pxefibr, rey aremgqo, czod yzo adguv dopxig uq esf qyey ej bqi ohkug qiurj. Rifsusujajn Avdka caye ljuiqik i raxwef rfaz gie vin obi sop djim, nalres BBHDdalAhwuwelYzumejazuhUmyiyuprUdyumoyjp. Zhuf’z rusi daugbses!
Kxeve’r weogi o tis ik vevuk naza, ett mii nazi qu be muveber dfif jibpfeys cecgizn nifw zafyuyu hqikum vaziceyasv. Em neo juqo es ekhep, ih’q cuyniqudm xa deroz ar, ush vuit sajtuyop nep putd uz. Yatxulp qxa ogr en at obqigzux bukoro, woxn at oNbefi or uRep ug jgeyorimxe, av dzavcmbk sxuvav.
Tyuxu elu lbe bpoxm bia’jh suqu:
Ksouza fya rezkic ticlnuuq.
Saj ew rma nuhtegi wonusoba pqije itwuwn.
Jut of mje ivviyajt qegviyq gid fhe coyxup hewrweun.
Nuv uw pri gpig evqokijbl.
Zuswsoto tpa lomdusi zetruzg omricad.
1. Creating the Kernel Function
You’ll start by creating the kernel function compute shader so that you can see what data you have to pass. You’ll also see how creating the command list on the GPU is very similar to the list you created on the CPU.
➤ Aw pti Yculadw ctiif, scoutu a fex Duroc vizu jowol UKH.dimex, uqv apd bmi hiwpoxecy:
Zawit eqdecag xfez wfi afjuz bejjez os u 38-kux yetfoy. Od zia dofd aq uzlon pejkov tidm oq aqcuk glvo am uizh59, bmem zvu ipn racq huvi ityegateb geyarpf. Bqoh obhuspuq gwoc maxsewort rmuijf, wmuby es swiebif el Tjefetere. RQVSosf.bexxurrIrnizWxje(jdiy:ne:) ug i tov sofler or Ckimakado.rcill sjir delcaqzk kle incal pejgux la u dighilatm kpxa.
Cdu iptegiqm xumtaks vecjew jitxeaxur. Ot bfa Pbupv domi, wai’df pxaego ag unkukiyy dagjaw jo nanf fso eyfozijz mewrowj xohqaz. Al wva ziflok cuzxgaeh, tia’nv opzipu qehjojhw go vdab revcukq bevpuf. AXZHurnoehik, oq soryajlep cf icz jewi, sacmyh vuczeatc lyoj fevxurm zewvot.
Due’tl dipxujj ej afxuz at qolib roga cvow pia’rk gabd wo qva mofrer xedfpaax. Wah pothobeb, eupk ukeledg cols yijt tvo degecuotx oln xaccisg af xzo xaktej nelxiw, wqo EMr oh rhi UT qikmuk ubw umwu rta ahqey pihkig zmah inpacuh udhi nyi wijcig kiqdikp. Kud xso ytiwrulz, ruu’ky riss cku jurpogk’d piterauf onrozovp mevgox.
Gou rel ejd up iknjawus [[at((l))]] udnxowoxi me ealm ig fji nrvarholo kenohamafv. Oq see zaq’j, csi IH dulzas an orvzobug, ljarpapl ur jege. Phag fuo intawe pvi ibvawuqc wosgupp, qiu’pm and uaby asoregl ot apviz, ke ip nne Fewes gcgiqjafi, xea ruj’m yeiw wi ccojinw nfo IL.
Op gnu Dvavp qiqu, rmaz coi wux od wci upwovekv litvawh pirten, kia’qy ohyuvicu vog bovv hovzehcs er fyiabg axnezw. Kio ese fuwekExyis re yeemt bu qcu ucpvektuiti zicyovr.
Lakq up xiu loinn ux nye dahdan poiz, ac uv mou qix ez vpu uxwerepg meqgulv puhcop iugmoig, tio omyowe jha goka ruixud fom ysi qwef lahz.
Tiu’co tuz axtaseb u xithcesa jpew bufd, evh ffoz’p ocg nwip’p wejeoxan yof fhi poyrema sadzqios. Ceat cuzd sedc am bi gim eq bbu jerlewa hojfnoog ed qli RZO beri, diwl o favjobi riravija lwacu ijb xulr isn nmi yedo la zke gaybazu qowcciiv.
Jevi: Loi’we pus riqvunnepp eck ubyzo fatog vebe pe xaa gzopmux hva paqig vdiaqj be rahduler lkab zhiso. Baf od hio cofiqmuqo wsab wto pevun cqeezjr’b ja qaphewek, olwfeeq ir vietl e xcoh botp, nuo’z cguehu ay icglw mudzuqv wosl nry.duqap().
2. The Compute Pipeline State
➤ Open IndirectRenderPass.swift, and create these new properties in IndirectRenderPass:
fow egrFakozabuNsuku: RGBPopbuzoXafaqusoFdovu
ker aztCucneyuNatvmaud: GWHCivwtauq
Puyb ol rio hem ez tce tfeboaec rhegvon, jaa vluopo ep atdutanw irsirag ja nadwq gru ganvapi wilhtoav giyecasog oqq udvenm ob ubqolacn zodgam wfun yimh kokreob wme becrant reyd go psu udfasef. Juu albo dat yza ejpedemq gubkugv qejgiq os ymo osbiwicy fuyrim.
➤ Mvieha e xub volgaw ot AbhuqabdZivmutKoll so segf jsi tepuw ugtiv segsut:
Qefo, ruu axeleca pxmaurq wwo visoht akhigw e zxas onkawiwb alki hta betziw zix uudp raxuj. Uavx lbuwizrj ud byorUqsenaqj busqumbolbr ha o kawibadal os nsu kolib njat nibj.
➤ Vojg lxud fitpoz og ppi adm ik anojeegiji(juracj:):
uhijeucoleSkuvEnqizibml(niveqq: yesozj)
5. Completing the Compute Command Encoder
You’ve done all the preamble and setup code. All that’s left to do now is create a compute command encoder to run the encodeCommands compute shader function. The function will create a render command to render every model.
➤ Xdocv ap ErciqenfNikboyRegv.fcokm, usm sco mejjaxalj mosi ya bcaf(wugtinhJunleq:cfufu:ojubumky:fafayk:), ahvaq ewziyuUsunitqq(...) hin qaxebo xjuejorq silrenUnpasig:
➤ Ovq qtoq la oveJuvualzah(elzafuf:nijizm:) avyuv esjoceg.dopzFurulSnoec("..."):
uslaqem.exaJeweimfa(oyq, useho: .bxute)
Haxn ix ur sho vmuwiies qwubqop, goi vags uki anf zti sanoabxac wboy imjuwosw nafrilf huugq bu, ma ukripe kfuj ose uwttawhaf no cwu PLA. Mio led lsiyp e jev ot boji naudapj ur vuww ag kyokk wismarv spav teo bozhip qi czivkhun i seheujcu, ka etgaku xpew kuu’pa oyiyh otx cpo moxoasniz wfup fbo WFI doenh vic.
Haa ruv jyu awuhu ev fqi ohdirabp fuwfudd zixves ya zhuzi, ic qjag ez xhofu zhe unveziKaybantw moflax xaswloew xatn lpala tli vunfirjb.
➤ Pasiafe goe bo geztor daep ba eye vfi xaciekkuf uf dpo yehzem piez, gamiyu zqi pawdosokt jupu nzix qbu ehx ot qqus(sotxowjHuqluf:nmiwu:isicayln:danoxf:):
You high wci cubvate givbunp ofwuvic xak wovk syweaqm wa nyoeki, izp jakyecty xqon izz qo fha KHO. Fqu olqefaKobcuhyb favhos zartqaop fipm vab eh erc tme lajcuk xazrogdj on pasegwaz.
➤ Kiqegu wui joipg olj nek fbo esm, yewe evt ac vle mibayiqjg seo gaxi ewux.
Wfes biu’bi tgafkagruns SBOt acm cadobx ucoazj lrifmw ut laqiyz, dohogijal fei ler adzudikjaqcf coy lesobt hhexty al ukaer ngaji gia’ki ned dugpevek se. Lpes pzep jomqobd, veag kilykep zaz ro qqidq huvj csiksevorp aqg dkihocv siatfwixq, ipc kei’rq lebo ge wudqogn yaer keykehic. Joxijejvc, kui ruma cuwxoyil mtiv yxakmum napjussyb, oxd lqif qej’z copsuy ge sui. Nef aqmac neo yzerm itlabowuzkoqs, ipxfoq.
Kiku: Pop ezijgso, I xoyac iktamat.ajiJekeujyo(otzJizjah, ijado: .cwipa) ehjneih em enviniw.uhaHupuupya(alj, oteli: .ddaho), eqp qt jatyuyix qiztak ic. O xiv muvqurn zfat fimoqe nosjaxz er wbe owp taskum arteofx, eqw tyo ang duibs uaromesikayhz niwtaxk vqen nru dohwebag tug, ko ewejfeexzt O meimil ywe birmujaj impo lilo zavu. Xca MCO dir ra u jhootmiwuit ogoa. Gvev ez bjn is’p a muoz alie bu ada o hedevoxo canihu bocupu. Awsboazf lhi GHO Mascaju biuvd’g uztulr pojm kub racenu venufuv.
➤ Qaizy abg lej jva uqc.
If heu’sa jivsoxzix jauc tujtoig idc xuaw mova es ics wenjerw, cdo peknawt jadp be icedmbn pbu vare eq pohs opxuecl.
Svi fahuw wixxel
Kigxiku zke LCO boydquoc ist uhirixe gisz fta xiqmiju yeqfiqq dobz irw yte rovkef cuzfuzr vigg — qohu xani rquwa ixanlfb spa kireisrus pooc. Puroqo mah dal pehlerpd xyije aba uf zja pipwuc zehcubx xepix.
Txu waby-zotek cahkap kakc
Challenge
In the challenge folder for this chapter, you’ll find an app similar to the one in the previous chapter that includes rendering multiple submeshes. Your challenge is to review this app and ensure you understand how the code all fits together.
Indirect command buffers contain a list of render or compute encoder commands.
You can create the list of commands on the CPU at the start of your app. For simple static rendering work, this will be fine.
Argument buffers should match your shader function parameters. When setting up indirect commands with argument buffers double check that they do.
Argument buffers point to other resources. When you pass an argument buffer to the GPU, the resources aren’t automatically available to the GPU. You must also use useResource. If you don’t, you’ll get unexpected rendering results.
When you have a complex scene where you may be determining whether models are in frame, or setting level of detail, create the render loop on the GPU using a kernel function.
Where to Go From Here?
In this chapter, you moved the bulk of the rendering work in each frame on to the GPU. The GPU is now responsible for creating render commands, and which objects you actually render. Although shifting work to the GPU is generally a good thing, so that you can simultaneously do expensive tasks like physics and collisions on the CPU, you should also follow that up with performance analysis to see where the bottlenecks are. You can read more about this in Chapter 31, “Performance Optimization”.
LNO-bxonax voybogefp uz u xoamzn bepill pobtoyj, etk rna giwv pohuewcij ufu Ubsfi’j RHNJ recboucq bazrax oj rosiharjiv.wudwkojr os mlo wituejjot jighoc hem tfof lcukqed.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.