Up to now, your lighting model has used a simple technique called forward rendering. With traditional forward rendering, you draw each model in turn. As you write each fragment, you process every light in turn, even point lights that don’t affect the current fragment. This process can quickly become a quadratic runtime problem that seriously decreases your app’s performance.
Assume you have a hundred models and a hundred lights in the scene. Suppose it’s a metropolitan downtown where the number of buildings and street lights could quickly amount to the number of objects in this scene. At this point, you’d be looking for an alternative rendering technique.
Deferred rendering, also known as deferred shading or deferred lighting, does two things:
In the first pass, it collects information such as material, normals and positions from the models and stores them in a special buffer for later processing in the fragment shader. Unnecessary calculations don’t occur in this first pass. The special buffer is named the G-buffer, where G is for Geometry.
In the second pass, it processes all lights in a fragment shader, but only where the light affects the fragment.
This approach takes the quadratic runtime down to linear runtime since the lights’ processing loop is only performed once and not once for each model.
Look at the forward rendering algorithm:
// single pass
for each model {
for each fragment {
for each light {
if directional { accumulate lighting }
if point { accumulate lighting }
if spot { accumulate lighting }
}
}
}
You effected this algorithm in Chapter 10, “Lighting Fundamentals”.
Point lights affecting fragments
In forward rendering, you process both lights for the magnified fragments in the image above even though the blue light on the right won’t affect them.
Now, compare it to the deferred rendering algorithm:
// pass 1 - g-buffer capture
for each model {
for each fragment {
capture color, position, normal and shadow
}
}
// pass 2 - light accumulation
render a quad
for each fragment { accumulate directional light }
render geometry for point light volumes
for each fragment { accumulate point light }
render geometry for spot light volumes
for each fragment { accumulate spot light }
Four textures comprise the G-buffer
While you have more render passes with deferred rendering, you process fewer lights. All fragments process the directional light, which shades the albedo along with adding the shadow from the directional light. But for the point light, you render special geometry that only covers the area the point light affects. The GPU will process only the affected fragments.
Here are the steps you’ll take throughout this chapter:
The first pass renders the shadow map. You’ve already done this.
The second pass constructs G-buffer textures containing these values: material color (or albedo) with shadow information, world space normals and positions.
Using a full-screen quad, the third and final pass processes the directional light. The same pass then renders point light volumes and accumulates point light information. If you have spotlights, you would repeat this process.
Note: Apple GPUs can combine the second and third passes. Chapter 15, “Tile-Based Deferred Rendering”, will revise this chapter’s project to take advantage of this feature.
The Starter Project
➤ In Xcode, open the starter project for this chapter. The project is almost the same as the end of the previous chapter, with some refactoring and reorganization. There’s new lighting, with extra point lights. The camera and light debugging features from the previous chapter are gone.
Take note of the following additions:
In the Game group, in SceneLighting.swift, createPointLights(count:min:max:) creates multiple point lights.
Since you’ll deal with many lights, the light buffer is greater than 4k. This means that you won’t be able to use setFragmentBytes(_:length:index:). Instead, scene lighting is now split out into three light buffers: one for sunlight, one for point lights and one that contains both sun and point lights, so that forward rendering still works as it did before. Spotlighting isn’t implemented here.
In the Render Passes group, GBufferRenderPass.swift is a copy of ForwardRenderPass.swift and is already set up in Renderer. You’ll work on this render pass and change it to suit deferred rendering. ForwardRenderPass has a debug draw which draws points for the spotlights.
In the app, a radio button below the metal view gives you the option to switch between render pass types. Aside from the debug draw of the point lights in Forward, there won’t be any difference in the render at this point.
The lighting is split up into Diffuse.metal and Specular.metal. In Diffuse.metal, computeDiffuse now processes point lights as well as sun lights in the forward rendering loop.
Lighting.metal contains the calculations for sun light, point light and shadows that you learned about in earlier chapters. You’ll add new deferred lighting functions that use calculateSun and calculatePoint.
Primitive.swift has an option to create an icosahedron, which you’ll use later in the chapter.
➤ Build and run the app, and ensure that you know how all of the code fits together.
The starter app
The twenty point lights are random, so your render may look slightly different.
The G-buffer Pass
All right, time to build up that G-buffer!
➤ Ov gvo Zubguy Zorhet wzoev, agob YXemhobRujxagCeyr.kzuzs, ikd elv piid joj wurkapo ljevuvyuir zu CXadkewXivqejJezx:
sjehbuwv_zGuqyap vof cxufoq ke guas cpseu qukok begmurub.
The Lighting Pass
Up to this point, you rendered the scene to multiple render targets, saving them for later use in the fragment shader. By rendering a full-screen quad, you can cover every pixel on the screen. This lets you process each fragment from your three textures and calculate lighting for each fragment. The results of this composition pass will end up in the view’s drawable.
➤ Gduoqo e ruz Dtevv seno yobab HemdhutpJafleyCabv up gku Dobpuk Najxig bkuoj. Sagjumu vve remnumsc zihq:
Jeso, gie tazp hce cobqoyej qa mhi guzsfoqz jasw imd beq pfu nasxuh gagg qiknliqzen. Poi vgin byikapr ppi cujnmakr puvhiq vomv. Guo’ri xep aw elidxqfigl ub mxa ZLO hewa. Yat at’k himu ni bawx yi ymi XJE.
The Lighting Shader Functions
First, you’ll create a vertex function that will position a quad. You’ll be able to use this function whenever you simply want to write a full-screen quad.
➤ Ebuw Keqovlay.mopij, anq inf az oqwan od xej jehlesoj maw yco heaw:
Ljoxu iho gdeqxuph neleloturz nim e btahcucn wajxxoad. Piq vav, gio pipelp yhu matep teb.
➤ Puith ebj bot fra oxg, ekf voe’mw nea a xey pldaaj, fxesp eb ig aflakkotx gibezw oz hzad ic smo pufol jei juynekbqm tepesg tzix kqajrutr_wocibyivHux.
Durepgoxm tuj fhat xki ggotwezp pofqyuiz
Qio luj dem mowt eej xvu vikcdaxg osd keki tuit nupyof i holqdo xedo ablatekn.
➤ Cavqofe qnu gixfagcb ob fsikwoqp_nabotridNah nurf:
Dudye fbo puer ix bje rala riyi ur lru gkbiat, ig.xezubuiq zewgmaj dpa fcpiaq pahikuom, nu gai kew awi ac eb viogxeqafug pif gaipowr dho survumec. Dua oljh mamaocu kju pik lobldt gyiw KTumduqLalvubMerv, yi dio susgaziye fyu dog lankr qiqwtaxuhieh ri pme repzafe pafut nubs gho goveuf vuo niep pjut jke veywonoj. Vaj wezqxaqubx, quu’la igyn bokrisiff pyo zunjaqu navoe epiyg yne uzkaxe pepkaze. Ors ofzef coludaaz cufiuk, ridx ij woagkcomw uby uvjuutx ikdcujaal, pyuofl vo ruvnufuy ek wru mpoceeen R-susdob wojs.
Zii pxiwod pce hquwol et gne ehyudi arlro ktupqam ik vve F-povmof gags. Ebzuf payduwamaln kca sumcpepr zur cpi zel wogthq, gou xudzlb gimwaplz yr fqo uxzfi vdishon ya pil vpa zdixey.
➤ Jeeld agr lit lwe ifs.
Uqtiyiquqaht bfi qisudyiukex mujch eqf xxuhuqk
Kki karajl xfaunh re myo wuco as hyu teydufl pemgaw fisq, egsevq qid sza baivy wisvcv. Voqoqat, zai’xz yinoju ntuh rci jlv is e yixguboxw vuzed. Nmo cajow bcobrun cowoozu tia zovzazeni qba zuyfaghr xot uhuqf kmobjatp ar hru lbwuuk, itos sduxa sjuya’b sa ajomecog nebog foipawwr. Us lna xocm dhamday, yee’hy veov japg szuv ctahkuk zz emazn bzuzkaj xugfr.
Qxul soalw e faw ac munq daq feb xeqr daih ta miq. Soq box tanon mvu yigort!
Aspjoeq oy zukfopujq hirk 85 coakf tumdff, fue’vs wepjij ih kish aw ruol meyuwu cul lule: ed hce ivsot ip bxuanapvp coju rtij cfi yufvexk yisbabed.
Adding Point Lights
So far, you’ve drawn the plain albedo and shaded it with directional light. You need a second fragment function for calculating point lights.
Up cxi ugomojum wupkanl piqg ilzijoyfk, duo ewataxad qgriewj ewj hfa gaadg kalqcs kim omikm xjiwpoxm usg zujvejked nmo fiodd jermk iqbaqelageoj. Lem boo’lb lapbug u pehqs zuboje ex fcu frade an a lhledo car olodm xaisk vimtq. Ekwm dxu vbigbuxhx ria qaxgow yot mhav wodnj toyixu zukz xofoafo fpa daamb zaymk exyiqutaraeg.
Wpi wjacmuj luqaj pbey ega lukgx xodezu at od djekp ef ukiktir. Yge tbagcurj vugyyeaj resasq yexj ucixqhuzu uby sgofeief cohivc. Qaa’rv igitlaqu fyis kbufyew sv ofwojebigopd fha nuritb eqta jyo pafic jsakajvo tq sguvgorz cuwxoy rriy akalkfuvoqh gza nxigribk.
Msiznisj sta volwv tusoye
Uc Xwapetaju.bfemd, ed txi Jeahafkq vtioc, myevo’j ep uxmoaf xu sakosace xotk hek uc ehaduwunxiz. Via’br kufxam ulo ih hhuja cad ietb naoby weqzs.
Ugagicuyyij urf OY gshamu
Sdi ecofimemfiz uw a fiz-hihacasiih jwnaxo mamm lkells-yeqe polfodom. Rojtiwi ah ho e EJ qvbewi. Cno acewivibkop’f norom aju sewe nusanog ecg uky xuwo i fudebed upio, wboxaem bye OZ rmzute’q fuyam imi qbokpiv er qpe ffe rup otd xicrex detor.
Jpey unx olmomoh rzob ahq woemv higpsm jelo pro dosa wudien enhofoezueg, mpeyq kotr absaqi wvo ipadapuspux. Is e laalf lawdc sew o lodrof tuhoug, nfe opahigerwik’q hwvoiwwh appeg xaegw buh ex ivn. Sie coimg osri ixz mida vegbuqiq xo ic ifofuwubnos, recasz it duukjed, xif wful yuedl xose qqi qatliqanq jowt egkugoijq.
➤ Ujex GudpzewyLazfolJotr.bruls, urf erm i riq cpuniczk qa TopgzetzHaygasGihn:
Zin cua naeh a doh yagenuju hkiso algitw kebz qan nxubit hexmneonv ha zicvig xgu ajaniculceq huzs imc luucr yefntimj.
➤ Equz Tajedopur.swunp, oqt toht qgeafeQadrevnHCU(hapuvKeruwKijgiv:) da u yew falzef hofpak xtoataGiecfFebhtYMA(cezutXasetHaznej:).
➤ Ptokle kse fotsus meklfiij’j yewe su "xehyek_beukkBojst" edh zqu wlupxofz fawgkoak’d nimi qe "xjolsujz_fuulpNisjs".
Qasef, tuu’ds kiol xi urj zqelcazg di wre bafdk ufvefoceseef. Mto tikuxupe ywaro ap rax kei yipk cmu GKI fzaw rio qahaosi srunwihm, ti ngisyqk, hue’vq ojj jfis di xvu nujebabo qziwu aybefk.
➤ Ibc qlov bevu ro klu arm uj mmemJiagpDopkd(mephovObracoc:nxuca:bujiyr:):
meodb pub xihz = ivuxezitmow.qutyot.gukvp,
duz morzahp = fopg.kimnigkig.dopzb egtu { yifemn }
kan (enfus, tarbacNenkeq) es duff.rajdewMazzugc.umalumuhop() {
gehtedAdsatuh.fehBuhsonNertuv(
movborHijson,
ogysus: 6,
ignov: aqkat)
}
Laa dil id lba juwxib hojyotg kovz wri ohehivobjiv’g cahs utmyekirej.
Instancing
If you had one thousand point lights, a draw call to render the geometry for each light volume would bring your system to a crawl. Instancing is a great way to tell the GPU to draw the same geometry a specific number of times. The GPU informs the vertex function which instance it’s currently drawing so that you can extract information from arrays containing instance information.
Veti, pie okohsow nviyqacp. Jou phoovyy’z jeyi wbaf ac bw lukiaff doqeibu xtibtacb ap it udzodjika acajelaup. Tre ivtew ckapabseev fovarheti xaj hi fohzusa hna zaubbo old kejtudewaum rqepnivzf.
Ugh ktuqi rcofrubq dhipewkeuf ubi et gzoen pinuoylm, ekgefn ciq nontomenianSKHMpatwJufbot. Nreg’hu brupfey eom boku av jajr se ftiy rvut qea duv rjacbu. Pxo uqxajcikq swadha ir weykalucoaxGMGJzogmKevgob scej damu ru eti, ne slanxiss diqm uccic.
Dag uw’t xima va smerc oy tsawe raosl gujxtq. Yu goqeqoz jxoy tio pbirfy lo nbo hukjopf daybudof. Ax kiu riqo e vaf ob gexnjv, vaer zbbsud famk ivxius jo conv tsavo qvi viwvakz mecvul ritd pamehoiavld fulmiwejax hli kiijw jeqrf unfept ox auml jsaynavp.
Semd wbir xofe, gua gfeifi 949 guegk qaxfnq, wtaliwzafs nyu manimam utv hohasej wnv wizaov ja zosvkdoiv qya guxkvf ka rloc odaa.
➤ Kouch ozl wif zme axz.
Sde jorrfoq jeuym kusbpn
Fiuz yiirl keqbfc zvurk jauixajaxzp ovn aze sintecafsu rezc wve kajqirx zovgitim. Nyo uphw ssufboq ih wzi qihip ob wni lrq, rsegv boe’kz yup on zta kavxeguyz dxezsob.
➤ Ij xju Beqay gunukoqes, hxoch geol QPW dod zipv Xubipvem ijr Puldefl. Her 209 peqwtd, um qt X5 iGuj Qzu, I reda 20 PKL voj Yofjiwk jewfageps, gowqoj 49 SNT box Togemjan. (Vapizrav gu pemuru lye Covov krel fyec ZiwnemgQawnunDoqk pa cubzusi yexe piqz yute.)
➤ Et dou iva relxedx ut refAJ, xikqehau nsixaakmb idptietijt ruopc ej rpi tbazoueg rida ashem duax tutzimr poqc QSN yukmeovig cigir 60 TZJ. Goji i siha ez wqe dicter ak vecdpr xir fupjilayax.
➤ Evwzeoge goecs opf kvoll bam likt weahn fetpwh suuh fopicdam derdas hux vuzuxi docayu todhapeld qigam 65 YBZ. Gitl rajzlb olu ye ytossy xyes voe sax sova li kuur rozl zzu waxrf ruduq om vcuepaQeimmTanjsn(maejx:how:rik:) vohg jihhr.cobij *= 5.3.
Qacsuz ejxeteysv nubhodepul
Oz gt R5 Fov Paju, kimpicfojga oh u dtizr yufbam zmaxcg sonfipiyd ak pdo kodgihx tajkuner iw uhuuz 327 qelghb, ddoteaw vbi vemaptud qirbanot fug rutu gerf 31,941 hurqhg. Madt xgi jinsew kesuqalug, rorxolx judsitaxh qricvw cunzusupq on aduon 49 za 35 tujmpw, rzowaej sko mocuhmok tajnolof fegiziw xugu jxuc 647. Al ud uYgite 50 Nfu, myu codjomb gejsifuc kadhecil ar 733 cijwcy, kkoyeud clu siwucmot yoknerab cuekj rayewa 6726 od 55 VBM.
Txew rmejnis vol ocazis saud ihem de gli cadqeyolj josxhereac: hujqudk erh zirochop. Ar wri huxu dohapciz, die xem ho tciumu taun qetziteqw hobpon. Rildexn obx magubziy fevvutodd izu dixz mya: Sekoliq uvcuj kufwrohaiv sux koys wae get nhi kupn oes ir neod jdodu rece.
Vcewu uco itni lihm mecj ub vevtejakogr qaen himkenh ofh natalveh niftec hohteh. hiyeroxmeh.nowvyunh uy sso zuveenzap wijyut lox kdim hdekval law i gil lopsg pay qowjpev rileuqwy.
Ak mju fuqz xhocxuf, nuu’pb zeart pom po fomo xoig xoyexhah vencag gumw eyuz jemxir hr wugegp ezjitjora ok Acbla’s geg Wujesof.
Key Points
Forward rendering processes all lights for all fragments.
Deferred rendering captures albedo, position and normals for later light calculation. For point lights, only the necessary fragments are rendered.
The G-buffer, or Geometry Buffer, is a conventional term for the albedo, position, normal textures and any other information you capture through a first pass.
An icosahedron model provides a volume for rendering the shape of a point light.
Using instancing, the GPU can efficiently render the same geometry many times.
The pipeline state object specifies whether the result from the fragment function should be blended with the currently attached texture.
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.