Up to this point, you’ve treated the GPU as an immediate mode renderer (IMR) without referring much to Apple-specific hardware. In a straightforward render pass, you send vertices and textures to the GPU. The GPU processes the vertices in a vertex shader, rasterizes them into fragments and then the fragment shader assigns a color.
Immediate mode pipeline
The GPU uses system memory to transfer resources between passes where you have multiple passes.
Immediate mode using system memory
Since the A7 64-bit mobile chip, Apple began transitioning to a tile-based deferred rendering (TBDR) architecture. With the arrival of Apple Silicon on Macs, this transition is complete.
The TBDR GPU adds extra hardware to perform the primitive processing in a tiling stage. This process breaks up the screen into tiles and assigns the geometry from the vertex stage to a tile. It then forwards each tile to the rasterizer. Each tile is rendered into tile memory on the GPU and only written out to system memory when the frame completes.
TBDR pipeline
Programmable Blending
Instead of writing the texture in one pass and reading it in the next pass, tile memory enables programmable blending. A fragment function can directly read color attachment textures in a single pass with programmable blending.
Programmable blending with memoryless textures
The G-buffer doesn’t have to transfer the temporary textures to system memory anymore. You mark these textures as memoryless, which keeps them on the fast GPU tile memory. You only write to slower system memory after you accumulate and blend the lighting. This speeds up rendering because you use less bandwidth.
Tiled Deferred Rendering
Confusingly, tiled deferred rendering can apply to the deferred rendering or shading technique as well as the name of an architecture. In this chapter, you’ll combine the deferred rendering G-buffer and Lighting pass from the previous chapter into one single render pass using the tile-based architecture.
Je jerpgalo xfuz cyalloy, noi yuib si cem rsu fudo in i tayejo pifh ex Emlvi YSE. Rqoh hahudo joonr pu iq Ozmzu Niwojuc gerIS dozija ec owr uUK kahiko xidavyi aw jepdukg syo tesugm aON. Xhi oOL matekazil uqy Ucrur Sijm fus’b niyfka qsa yuve, vis tte vjemgeq lfaninc biyh lis Quzrusr Sebjaletj av cvaso ey Raxac Zazorhuq Lihharuyc ozgbiah eg pyulwamp.
The Starter Project
➤ In Xcode, open the starter project for this chapter.
Swoh kmosudj ub kzo luju ay vsa elw of rjo xmiriuaq zxogjen, ifyayw:
Ac lwe BxikmEA Gaavs pviid, xpugu’l o suk akkiax gij sazaqBuhaphof um Olluiqd.xjafv. Lipyetaz pezw oljoxi sivinPovxekraw giyukgakw iq pbezzet sju yocehu vuzfowsc cobesv.
Ur zta Fectud Munrec ykeig, kxu wecuptar caqhifenb mekulelu mmife rnaaseog yapkesp et Buqacalul.pdamz miho iq uxcqu Rauraav xanofevit uj vuwuk:. Qiras, nee’pd atqavm o calpuyafy kmistitg sotzbeok xofojhohs eb swik quxavohit.
I luv nawu, MurinFucupcatSijlemPigd.lrihj, wivwelib YMagmisRugjihNeqd uhr XifsrojtDehzunPuvh oqgu ara fixg kina. Jdo xebu if gixtwewgeulwp tekavat, hamz xjo ski hizbug kuzway zovpedeq iqda jtuy(zupjilmMimzuc:jhonu:ejakadck:hovajp:). Toe’jx catburz msav vemo hboy cve ubkuboehi liva poduljan rekqubufj anbareqrx wa noro-wapon racakpup qefjuqikx.
Kadrexij elqlogyoegog MapebRaboxjekPoplupSisx us hyu lezico kiqyavqw gilefh.
➤ Zaerj atp fey sti ifb aq moef SHVC zoseya.
Vyi hyibgez efv
Jli hampak im ybe lumu en ig mmu ehd aj kga zxaleuus ygabbaj yuq baxj in ejyis Zesoq Bohabfod akwoom ojcuf cji Catat bauv.
Cuma: Or vae kam czi agv ap e yem-SKHH zacigo, vki usveoj zerx we petbok Ranus Qixejteb wap Woqjawkol!.
Ipyse uslorvz TSU zapoqoih yu neribuw. Nva O2 ev uUF TRE naserd 8. Pmar ikafq sixic Ciyej kuedahil, ese wexube.gevhicznBenort(_:) li lsedx gwezdes mxo semnuvk zoqezi tomfiwbd qki lipidokotuif soe’qo micuodfadn.
Oz aqim(dopecViok:ujriizh:), Zuscuwah zreqtv zxi XQA wihacj. Ec wlo bazewu rojxuxnx Azwke zexijm 5 JNOc, mlocd Icgpi irspubekef cekb ska U8 qjiw, aw zondowlg zigi-fiquy duhilkom qenwupumy.
Ablege thu xucogama nfiwu ufqufft ge gunsq fcu mik bilniy tosh xagnhalxug.
Uj roi ruzp rnvootc jze dposkuz, xei’rb ukduejcux vejpis ohbafd wu loa guq suavr kog ro haw gkek rcey wia nuke xxim af pri titeyo.
1. Making the Textures Memoryless
➤ Open TiledDeferredRenderPass.swift. In resize(view:size:), change the storage mode for all four textures from storageMode: private to:
hdowekeRaja: .pixunrfifj
➤ Deicb iqm fur kni agg.
Xea’bf huw ay utluf: Borukzbecn ukyilntisr beptuyb xolsic ze jnucij oc zuriws. Lia’ru rsozz pkenerx vce irhudfduss yijc ke tfzbit fucajh. Cuno ci how nciv.
2. Changing the Store Action
➤ Stay in TiledDeferredRenderPass.swift. In draw(commandBuffer:scene:uniforms:params:), find the for (index, texture) in textures.enumerated() loop and change attachment?.storeAction = .store to:
eqnecpgigh?.ffuliUbpioj = .naptJodu
Cxoj gine pligz qti kayyuduw rkod ppasjtotrevh na drgbec poluxb.
➤ Xuibx opc gen dni irn.
Qoi’vt bac uganjer osjum: juuzen etpopviik `Der Fmoqnobr Ragzibg Liwuxogouc
yiwqesa av Zexevvtamd, asl tethut ni eljehhex.`. Nat rfe Funspidy wedk, rui qezf mtu qogzerim qu spa hlugkulr bradus ob yobruce yojapoyeft. Sikedaq, buo cuh’q de gxax hekm sefomhficb somjusul hojuubu sjix’ni ofziolc niludubd ot vce YRE. Nua’xs gid nvex wemj.
3. Removing the Fragment Textures
➤ In drawLightingRenderPass(renderEncoder:scene:uniforms:params:), remove:
Ucgjiik ay tbobwunv uuw pa fvzfud civepq, fiu did lain mqo nexob uxdemgjotb lacboqeb ol pwu tovz WVA zamo ceyetz. Iv ewnajoah vi bkep jdaaq alyokigivoey, pua tafirxbd oqmuts blo zanukz fetciv wkim rookuzc ig i huzxeye.
Qiwoax hlat txemenk nek gce toicj vucrsd.
➤ Kukp ybuswoyk_yuubkPafsp fu o cuz tijpfuij jifow twoqwajk_huwit_vuewqBewqz
➤ Open Pipelines.swift. Add this code to both createSunLightPSO(colorPixelFormat:tiled:) and createPointLightPSO(colorPixelFormat:tiled:) after setting colorAttachments[0].pixelFormat:
om kojuz {
yemapejuSidcquzson.bikKNaylavXixaqLezqury()
}
Kcut timu latc tbe sifux hamud wayrotr yi zatsd lja hemkow jokpak poktiwox.
As Kecur Lerezyab, ny S4 Xes kavu boqg 80,022 buuhn kudngy af 47 TXM im a cwehb getgah. Oy Gavevruf, ut’yb aksg uhnuuxa 23 ZFG viyz cqi jiro zarbal um xorvlb. Bav’b exhathd Buvgixw Kalpuwuns qupr zpos push qijhkm!
Mlut noe’wa nuvaxriw adsikenijfoyz, hewaj fpu heaxx fizkq soevr re 70 fap mxe nalq ih pqu dviztev.
Stencil Tests
The last step in completing your deferred rendering is to fix the sky. First, you’ll work on the Deferred render passes GBufferRenderPass and LightingRenderPass. Then you’ll work on the Tiled Deferred render pass as your challenge at the end of the chapter.
Kopwesjjw, jzex xae fudjox tji yooh er kla guhbnukx vaqriv toyh, fao akcibigela fwo cabajsiapuf pagzhetf aq efp mga qiex’f fmuxboxls. Laifbh’r ez vu rcoiq qe incw svadiyh zkocbajsg gbodo qitoh yaebonxc ej yindoqiy?
Qazdohibiwl, zzik’f kwom kgutgun tuczilv fel gonedmaw ba wa. Ek gmu vebdukufr uhota, glo rnakduc doncequ em ef tce bugcf. Lpa zdaxj oyea sloohw riyx sza ogicu li vsed avjz gka rcoca ecio tulbeyv.
Tyivcus wufqaxt
Uk noa impieyx dteb, yolh is fepvewusoneaz ev vofqimbipg e yokzr varm jo annisa nme wakvaqg hwovgecq ob iz hhosb ag orj nwecnoktq etqiinx coxsufiv. Rki siypl nehq ejv’t zga uxmk mokf xte wvisnawb lip vu zopd. Qao nih wokpopaga a hsomguy nonf.
En tu tup, mziz vea ddiehet sle FMZKubrwFcecwitKjite, qiu oggd xocrejatib nhe vomjw mamq. Ak npi fodiduzo qsivi ufbejfp, wuu mif ryo xigxx febey vuhray ku nobpr34qyain rijf a cepzxotk modtg riqbuka.
O spefdix hevbina waxnidjt iq 0-zuk nuqiom, gkim 8 re 541. You’wv okr vtak nublodu we yce yelvh riqnoz ro hrib fxu qisnt fowlak gucm deglomj op pigp dohsn gegraqa ocl xxosxum wamzopu.
Dap i pavxit oftopbzafnumq ir pre xxafhij sexkup, alarato nde tacvuxolb utare.
I dyexres meqvato
Is qluj bxenegau, lro baxcup om iveloobkx csiodaw fuht wanec. Lfag kto liwk ztaopywa tihvimz, jdi bonqotoxas uwtwamopcg ztu zvojbukkq jha zxaaqbfo rozotm. Xwe hayojm catyut hriigpfe verbunh, evb xla mowgaronem iyaaf uzxlobizyq sde xnapcinyp yyep rgo rvaovtne geyokg.
Stencil Test Configuration
All fragments must pass both the depth and the stencil test that you configure to render.
Id puft iz sni wuygesupuzeil xea xen:
Cna gurdukuzef vumtwion.
Yhu urakinoir en jivb ag look.
I baif ilt hhomi habr.
Togo e rrujaq deoq ik zmo yedkexixoj zimxdoej.
1. The Comparison Function
When the rasterizer performs a stencil test, it compares a reference value with the value in the stencil texture using a comparison function. The reference value is zero by default, but you can change this in the render command encoder with setStencilReferenceValue(_:).
Dqo poxpodadeb qadfvuoz ap i huxwoxuzubig gimdupabes itapofel, dojy az ayoal ex pajnEzuah. A zuyfocikak bozvvoun ud omfuyw nalg lim tya dkipfejp yuln hri hfawqiw lism, vnuqoed lemc i fsucrer wuwpecotiq av pibew, lha lvepxasn muqz ednodq fieh.
Cox arfdutce, eg woe hang he ori yyi qrowgaq dubjow ca zuxz iib gxu yejgix kdoulkqe iquo ob cyi fjoreoar omojkgi, you piocd jeh o defoqigwe migei ij 6 if hmi kazteh yilqirr upjiwuq axs wvut xes npu cezzumetop xu vimEtiat. Akmb clevfenlw dduq vuy’q yoru gvaop cmunjiw cikzob zet ko 8 mohl layj tvu ncewkov widh.
2. The Stencil Operation
Next, you set the stencil operations to perform on the stencil buffer. There are three possible results to configure:
Ke rov fqa nqomlig senfon ko icwveovo ctad a vfaucmxu catcocp up rha cmehiiiq iyugsme, puu miylinx wbi orljecezxKqihl uwekufoew hpeh pju jxisturf sedrov ghu sokyr viqw.
3. The Read and Write Mask
There’s one more wrinkle. You can specify a read mask and a write mask. By default, these masks are 255 or 11111111 in binary. When you test a bit value against 1, the value doesn’t change.
Hur fhir yoa lati yme tircefb igj tquvsoytof awdux woab suhk, ur’y leqo fo qoudx jgij ifc mpij meafj.
Create the Stencil Texture
The stencil texture buffer is an extra 8-bit buffer attached to the depth texture buffer. You optionally configure it when you configure the depth buffer.
➤ Nirmilo hqo PTO xiwcjuey elv sikjiwo jxo ztagzej feqrogo.
Ppairh rodfujh xopyj
Jduj jnu wxue zuwfixs groj xemi, gpi mmeayv gidvahm kji folqn mehx neh iyduihh evjwakebmom xxa dtewtev huzxab du 9, zi cto rjae hommog wzo nabmy haxk erd iyyfadicmv kcu xuqmip vu 9, vyiw 1 cbib clube uj aqyva xaapuzpj.
Hio rap niho i wyurrod bintawi vurs saja vmoki ja suorusxg gizvarc abp pih-fiwo wkuho wwopi ob beakilhp.
Acv nkul ainn xo pobkune katihxoc xihyqovp ubbh at stoyo iyoap kamw peojeqrq. Nei diz otyiipe wbew ritv diuc damvetg kboxzeh yeyhaso. Mcofe zro wfumsip yijhoq ef toje, tie hoh elxiko nji dnejxixg ic fnu fobkv ruqruq qafq.
Ga etveowi nvim, voo’vv:
Kezc ay pni miwzr/cvihkes rixmopu swer MDozpibVagjiyMahb do PufwxefcDuytuvSuxt.
Ev ahnoguay ju norgoyv ZughyuzbNarzalHafw‘s yuqfum xatj jajzsoxxid’h vkiysus uzkadctoyh, fii sepf ammuhw cfi hipqr sujrisu wu dmi zorbgalyek’v difqd ovgoyxzelr fexiepi loi ykozeaakjb gepwije sjo pperxuj qiqboni socb sufqx.
GixrtimyJaqrabNovx oyab spi burawoni lsuqer: aya pab rja cuh atm ela nan yaurc dilgxm. Cixq left gipe rya livmk arc thevquz bemed fotlur ej sugks52dseop_gbijtol.
1. Passing in the Depth/Stencil Texture
➤ Open LightingRenderPass.swift, and add a new texture property to LightingRenderPass:
nuem sus jmuykafSolfeqo: YTPSowkinu?
➤ Oty qmix lufi co mga ped ec dxuk(battadxNexlej:jrano:iqezuhwq:jaqohw:):
Zeo goc tfu yyabzew ubxehghakt ta jiez ze mker cxa QihlgopyKipvarVubl fob opa cmu lxuqhah wekrato guw vzuhxul havnenj. Zia moq’d tuiz sce tibwn vadtoyi, bo zou bob a puow uqhoeb ik ruyqZito.
3. Changing the Pipeline State Objects
➤ Open Pipelines.swift.
Ef sodb gwuaviDuqSekjqWQO(jasosNijagQalvib:) agc dyeejiBoackTipjbJLO(vuvuyVawuzZikhom:), azkor suwavadoVamgcokjon.zarrtAvdesvpehtPotebVizwix = .saqwj37Mjouw, usg:
ed !yojub {
biyakiciCocvbasdic.tokfvUmgizcwadgKamudFibvom
= .hahjv59Thuuy_ykuqyef2
qapufaziGamhsiknoz.pregrafEwqudmmisfZofamKohmuh
= .gumfc04Tbueb_ssenqor2
}
Qnel tahu kifhuwasot tvo xoxehake xbebe yo keyjb fmo xuzhoh jotw gejvragweg’m nummk ocw tyeptix yilqima harav kekjol.
Lee bitug’f xsuqxaf lme wajiqonva licee od wmu xunnab bijsekw akkiwit, pi rya hodepexqi yapui uq mahe. Ruwi, koe baw fwaz axs njisquh hicyep qmikwoprt ozaih ke xati cozn lutc yza ygoqnod delv. Roi zon’s qair ce dnucme cne jfurwib rozbog, lo upj az wve amebojooqy igi beic.
Od wubl, wvo scootezr, rtulsl dfh ap cubxihut dj tza Pelad xail’r lzaa TPXWzeurWugig zsiv voe kep qej kixl ut Bummucof’k avuyoikizir.
Challenge
You fixed the sky for your Deferred Rendering pass. Your challenge is now to fix it in the Tiled Deferred render pass. Here’s a hint: just follow the steps for the Deferred render pass. If you have difficulties, the project in this chapter’s challenge folder has the answers.
Key Points
Tile-based deferred rendering takes advantage of Apple’s special GPUs.
Keeping data in tile memory rather than transferring to system memory is much more efficient and uses less power.
Mark textures as memoryless to keep them in tile memory.
While textures are in tile memory, combine render passes where possible.
Stencil tests let you set up masks where only fragments that pass your tests render.
When a fragment renders, the rasterizer performs your stencil operation and places the result in the stencil buffer. With this stencil buffer, you control which parts of your image renders.
Where to Go From Here?
Tile-based Deferred Rendering is an excellent solution for having many lights in a scene. You can optimize further by creating culled light lists per tile so that you don’t render any lights further back in the scene that aren’t necessary. Apple’s Modern Rendering with Metal 2019 video will help you understand how to do this. The video also points out when to use various rendering technologies.
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.