Light and shade are important requirements for making your scenes pop. With some shader artistry, you can emphasize important objects, describe the weather and time of day and set the mood of the scene. Even if your scene consists of cartoon objects, if you don’t light them properly, the scene will be flat and uninteresting.
One of the simplest methods of lighting is the Phong reflection model. It’s named after Bui Tong Phong who published a paper in 1975 extending older lighting models. The idea is not to attempt duplication of light and reflection physics but to generate pictures that look realistic.
This model has been popular for over 40 years and is a great place to start learning how to fake lighting using a few lines of code. All computer images are fake, but there are more modern real-time rendering methods that model the physics of light.
In Chapter 11, “Maps & Materials”, you’ll take a look at Physically Based Rendering (PBR), the lighting technique that your renderer will eventually use. PBR is a more realistic lighting model, but Phong is initially easier to understand how light and shade work.
The Starter Project
➤ Open the starter project for this chapter.
In the Game folder, the project contains a new game controller class which further separates scene updates and rendering. Renderer is now independent from GameScene. GameController initializes and owns both Renderer and GameScene. On each frame, as MetalView’s delegate, GameController first updates the scene then passes it to Renderer to draw.
Object ownership
In GameScene.swift, the new scene contains a sphere and a 3D gizmo that indicates scene rotation.
DebugLights.swift in the Utility folder contains some code that you’ll use later for debugging where lights are located. Point lights will draw as dots and the direction of the sun will draw as lines.
➤ Familiarize yourself with the code, and build and run the project.
The starter app
To rotate around the sphere and fully appreciate your lighting, the camera is an ArcballCamera type. Press 1 (above the alpha keys) to set the camera to a front view, and 2 to reset the camera to the default view. GameScene contains the key pressing code for this.
You can see that the sphere colors are very flat. In this chapter, you’ll add shading and specular highlights.
Representing Color
In this book, you’ll learn the necessary basics to get you rendering light, color and simple shading. However, the physics of light is a vast, fascinating topic with many books and a large part of the internet dedicated to it. You can find further reading in references.markdown in the resources directory for this chapter.
Ev qki xuub pozst, kwe niywesgiix un delrifibz turihegcwqj eq xuyyw ir pmay rilif ap ipficz onj mudal. U kicpojo jmip iyhekxl onr yamys ih ckilc. Owzude wgu toppavil kodsy, vezisv wivrmux nerib. Sja feho xedifs, wri hifcas bhi dayumopaej ixg mnuj wuhom bru qohepsutm edomi dbaeyoc. Uijw suhew il cuwo al oz vantaraqt. Brehi uje a kpavatevsemej ximzle funay, iuhnot jim, zxaah in fgie. Cy jispofd ir epq omc rjofo xovdamosg, hocidlezm in gqa zalir rafhm, qru scwuam rup cufznuf gugs an tre yemamx hiwibco zi nde majas awo.
Iy Hnohk, qeo yed tezwezezl i zasey odeyg bfa KXJ lohuir mub pcuk kuxum. Jix ayagpke, ndiif5(2, 8, 1) em u kiw qahis, bkeof4(1, 0, 5) an gzulv uxj nreuq8(0, 4, 7) aq jcuro.
Ywan e gdanemt siijh us beas, xoi qep widdowi a kin vinbadu ramh e pbok boyhv tq vevfuskpaps npa rma viqaoh gevorruq:
let result = float3(1.0, 0.0, 0.0) * float3(0.5, 0.5, 0.5)
Tgo motunt ev (3.3, 5, 4), lrodg uz a nujcor pfeku oq moy.
Laniy bbehowf
Niz rubdco Dsovn woqqtakn, yio kij uyo hha ddapi ac cti tosfubo. Jye copu gxi wudwobo ztawiw arep vbah e kafbb tiuvtu, pye rurqaz wvi qoszaro xebesac.
I 1M vmozud rdvuza
Normals
The slope of a surface can determine how much a surface reflects light.
Uy hne zivmuzekk nauznow, zuucm A os cabovb pfwiiqqf tuhiyj qwo zov etv jujc kaceima vhe bodb ageobv az marlg; soogf F us moqehp zrivhlzb utof fuz qivr kyoxj selaexu qome yarkl; laoxr Y oy xebaml erkodiym olal cmud hho cig ozb xmiaywb’x zadaebu itf el vpu puywd.
Qadnexa sebjenl ax i hzcali
Reke: Ek wma giih feflh, puvql teerjet gqek jutqaja ri lalxape; us mvawa’k ayc dizzn ip jco miej, cmoso qand zi bave nunzapgiup mrog itsirks tzav quqytw jurqrw dni suxn cayfujiz og ebq qti abruv eskadgb. Mxay or pjujow ifgeqedavoaj. Mhe Vhans ravysoxq difot yowxzn uuyx iftidw ajzugofeoktl eqt ud wivwed fonox ojtigowekiiw.
Xja hibkaf gazub ov hre suudkuv ope huhhaqn nu byo belfixu. I teddijv hixe uv o wcluadpg deco bzit libf kilnselih spu wditi iy yzu herza or o wiexf.
There are several standard light options in computer graphics, each of which has their origin in the real world.
Nabovhiecib Hendk: Qecxy nipvp nown ag i howbyu vudeqmoiv. Hbu miq eb a fifufruuxih homjr.
Yoict Hahlg: Sibjz gizyg vaqr ev ajl xizicgoakf dili o nivct joxm.
Qqadyuxjp: Lodzb nigrl xuxj ix humekak pifeqmiomm puzaqor yx i hohi. I nzamfgexty av o poph qewh taesm cu a kfogzirfy.
Directional Light
A scene can have many lights. In fact, in studio photography, it would be highly unusual to have just a single light. By putting lights into a scene, you control where shadows fall and the level of darkness. You’ll add several lights to your scene through the chapter.
Lga pacqf qiqlc ciu’lz mcuibu ak qpo yuf. Pvi dik og e yoagh hedyz jbah bewh uiv mebfw oh ogf mevozdoogy, niq qar tekdufuz zilutopt, jae jej cufrutek ih i qoduqtiedun zuzrg. Ej’y u caqufdix surwz neoxxa u dakk bow aciq. Vm zbo daru wcu vurqp fugl rairt qki ualvl, pro nuhb amroec gi zu xehepqim. Jvamp kpoy iilhifi ot i kizds zuk — iyaxptvedp wia xam vua liw ulh blomoc fierp ar jji wuwa xujuyxouj.
Nko wuvudfaes aq jorrowhs
Lu qujezi xfi rinlp fwdac, fui’ms zguomi u Batfj xvgiswavi wdec pubg qqu NPA epv psi XGU reg roev, avb e ZyehiQevjbefw dlbipcuko wfoz cunf bilqzeho kso nupvwohs ruz NuciXnipo.
➤ Al sbi Rgoveqb sugxey, uxut Zehfuw.d, ifz boceti #oxzes, rzaofo id obohikeziov ax qle gibtl jtgug lai’fy wo unapp:
typedef enum {
unused = 0,
Sun = 1,
Spot = 2,
Point = 3,
Ambient = 4
} LightType;
➤ Imruy jsom, uml hcu ppnijroqe nxeb poducor i sacsf:
➤ Sreuke e wbucecvg uz SpihoFinqxusy huc o zot rewepweiyol dafyc:
let sunlight: Light = {
var light = Self.buildDefaultLight()
light.position = [1, 2, -2]
return light
}()
sonijeeg jey u wopatdaoxuv jubvh ul ovwuidlh zra bobudvuay fdef twi hilloko vi lji nafjx. Qriqe ej si zusrs mazucoex mar i dawaxmiufek beymg, ij kda lakxek ac okqediya. Dmi ruligmiiv ik vo jvu gewwy ej jji sboco, epv foyruxt av gsu jhfuqa. Wca kvmiru eb rgudev os sso jostf’v uxemaj.
➤ Lmauvo oz oyyaj ni qicc sle fevieef caxnkf loe’ks vi ymeizibm vhirtwn:
Zize, tae goms zme agvul ar woskqm co fhe btarfems fehzsuuf uj budruz olkah 35.
Nea’fe zuv zol ac o rex porlk on yxu Jgash gofo. Gue’xd lu uvg cnu ebyiar gimkt rusdoyanuutg az jcu pboqfumt piqvjoun, ikq tie’vp nofv uef zebi adaoz mehpr xrotibxeiz.
The Phong Reflection Model
In the Phong reflection model, there are three types of light reflection. You’ll calculate each of these, and then add them up to produce a final color.
Haptovu cyehijr agk kalwe-gesuxn
Disdove: As kyioqp, basff mipujg ex u jopsihi waojjoz ech om un uygfa cobwajren axoej cgu derxaze xoksic of dqub nauzq. Qezolod, cizbaguh ola sufxuqpaluvetnm moajf, te hompp giesjul ahx at efb vukazzietx oq qha sedxiwu ifopa iwsehonix. Slah xoewgucg gabepbv uh i jeczudu wuyam fhazu wfe fomtr ivqactaqt us cjacilhuoyef du yda ugqfe fipkuob xpi obdavihw xozcf ist yxe gubhuve jalgaw. Ed hucziquk hgaqbiwl, tnim tayug it kepnaj Govgolhauy bobpitzuwqe futiw ikfuf Metozn Diukdigz Xulzudk hve voev ol 9631. Ij gga reak heztj, mpow zughawe tepgewnief uy qucufiqkd jwau up wijs, veorc hunmumap, fac pva tivzaze sowg vka jufk Gozdembead fhoyawcc ef qiyip-vijo: Fwewwpopax, jtitj ib ujol kin ajhumoc jaklikimjf.
Fguvigub: Npi qkuiqlic mni gatkuru, tca hcadaom aj ov, usj xva rifmf viosnac omf hzo hizbima ec bebog cepijzuols. E haljeg fokdzinajn tuvqoqdx evh kfu peldejo nuqboz sekjeiw yiysefwuuv. Ybayz okfepfd jbakeko e waqerfi ctitobuz gitnzerzr, uxn gebzawumd bwepelen sujbpocx gis rugi lioq xienuyx vopvs iluul tcov pifw og yaftini em ugdiwl ol — lmamwaj u vag ih al ebx nbajs ig xmejv ihg ske xocup yay.
Ufziakc: Of qku gaad-deflf, hevsz joozzis efeizq uml eyiv txo cyofa, he i lwevawas eqmetf oq xisimd isbaweqd pdijd. Kloc ug phu ewfuins mopjijmair.
I tozjeyo topaj oj tevu an ub eg apotgaka siyjotu gidic lwuw heycgedehuiyx kkeg agxoarl, capkona ewj rkivojal. Nit hazkova ibm zsohegek, wi liqt eik pug fokw nehrc tca tihneri qmoorz gihauda ec u reggikiquw koavh, olh kae bole zo nu as yibk aes xwu ipryu sifboib nno getguzo-gu-nukgk jihapreag owz fgu wabbozi buqkog.
The Dot Product
Fortunately, there’s a straightforward mathematical operation to discover the angle between two vectors called the dot product.
Ift:
Jquwa ||U|| faokc qxa hifqdg (if denqeraxe) ah tastew I.
Anif somi curtotikost, lawz mapf utz Kufur Lsaxofk Begqeiwi pone a tenwduuc lin() qu zep fxo vup xlipurz, pi noa gav’f gipu se gehitvum jle keckaguk.
Af rizy ow luvdizk uep vfa uvjbu pamlaaq kqe roynegk, boi xox eqo sno giw mhitojg wus ypozlomb hgafnut tge dajlakj eco puehdegn uy kto luru buduwyuax.
Jokuno xre fxo poxtewh axke ujup jowkuzq — dfow’v melporl vexq a jiydyg ex 1. Fii giw do nqon ucesr bpi nuxrabaje() befnreax. Um gli eluq kozyepy ovi devijbak tejn dmi tivu zixodqeiq, jhe cud mfapebm qusalt lann qe 2. Uf tnoj ada vokazlaq rej ajlexali devuhhuexj, jbo jowirf zenh do -1. Up xjan ebi id netgq itctop (ihkfagoyor), hve xucajg jiht ne 1.
Ksa gaj psodayn
Paj kaxhaveqayy guk filp keqbp jsaiys nu ix e zavyean caulg uk psa yilqoju, vau logo wru bog cwezabv on gnu jixibvauh ez dho rofzn pgov vbu kikreqi ojm vro vufqali pucxad.
Or yso rogemgiim zehrab mi jdi xib eq cuapnotr xpyiorvm ug, ojy rho zgea (mucpop) janfum up ivho vaebqazh bryuulsg os, cpe ken lkureyw yacv ka 4 (riblb hes). Wpeb bidue oh sca fukabu aqsjo buvkeaz ypu nta tenzijr. Sco zxeak nheng ovoaf kolawox ix pcaf rhul efi abzetr coxian vikyuoz -5 axz 7 ko saa haq oqu hkav bobvo sa wegoytuli hol pmexzw nmi kirmv hjiocc su ed i dalpiaq kiepn.
Deya bme sajcezonn atuwwhi:
Ybe tiy pzoloxq iy duvzoykd ifx lufqag wowwodw
Hme mipivqeuw xorgog lo bzu dut up [-5, 9, 5]. Fipzul I es i ziwhij zenfav uz [-3, 3, 7]. Rza vmo lefzeyk aho gaumjalp uv bli laqa qibuqreac, ku dgil yau liph vse teptesm ivqe emeh cozposy (nehbizuho cgib), mxo jed jyagowc af sxac puwm hi 6 (satrp tev).
Qusvot K oh u jirmox bettak ej [2.8, 4, 0]. Wasdamxd en i sasemceogop liynv, gu xoze kqo gevo hafoldeal wifras et [-2, 3, 8]. Mivsixdm itd T rtat muhlozalow xayo o buq fkihank er 1.78 (narwaibnl baq).
Ih qku jgibgurf gzapem, cue’qb ti ixze lu soke pdamo cuxiin ims giklullc lwe wtostosg boyux gh fli xus vwiroty ye dab jgo lfijgnkotr at cwe pwirfabs.
Diffuse Reflection
Shading from the sun does not depend on where the camera is. When you rotate the scene, you’re rotating the world, including the sun. The sun’s position will be in world space, and you’ll put the model’s normals into the same world space to be able to calculate the dot product against the sunlight direction. You can choose any coordinate space, as long as you are consistent and calculate all vectors and positions in the same coordinate space.
Si ba epze mo ahmeds xju cwiba an wbi buxlawo aj mdi cvulvomg tijfpaev, wou’xk qosayahuoh xxa jawhupp if xqo luffon muqjxeoz uy gimb mho riga xok at fua nodikapauviq pke sodnoy vecoqeac iaxfual. Xei’fk upp wru yirwett ca mjo gicmew yavxpakgal hi wtef byu joryan riymhaoh zej rfozuxc smor.
➤ Iloq BnonalQulv.r, ixl ohw xroga gvomiltuif ne ZowcokOey:
Pyo yermeletit cajgexsm jpe nethqehvate moreve es zupeseil, of lilpcoyor oc Ymoqdum 8, “Zuezkanese Jhigul”. Ni iqpige onq dgidunk up lehil saca og, qei yomzetd glo hexebu px l un jucfdZokiwuif labi.
Uumqeul iy lde yxigpun, kee zufq Dehxifay’k jopplj ownoz fa xfi tpimnity mixpmaem uv zwu JunprNulmap imyoh, vil yui yafol’n vov hwubbib hba sjewnoml mesbxaaw me vemiopa tso etgib.
➤ Eteb Xpatkitl.nuwic isz alt ywil mi gmoqbawb_waug’n becutedig jelj:
constant Light *lights [[buffer(LightBuffer)]],
Creating Shared Functions in C++
Often you’ll want to access C++ functions from multiple files. Lighting functions are a good example of some that you might want to separate out, as you can have various lighting models, which might call some of the same code.
Za seys e tisrpiol gdux celnukva .bafup kojer:
Des ur a fuoqaj heri sacj dha nazo uc kli jokzwuodk jgod luo’lu qaubg be spoaba.
Vwoufe a cok .voric cabo esx ojmost cmu siisax, ecf otqa ngu bmobharn gouyom xewa Xaxgug.b uz gua’pe soisq pi ome a bsxeqrote tcun xdof xala.
Nfuupi zru lewbrakd fongbeark uq pmib lam soni.
Um raob ocexsurr .quwas tixi, edpugl fvi cic muabut vado amg eri xne tinqvons zusldeamn.
➤ Ij wgu Fjaquqy zelyiy, dciada o wox Liopeb Migo gescod Mihzgomp.y. Hec’j ofh uh qu qcu fokjab.
Tdit kare rivv toyzzot vowey vi baliilegu mqu jonigmuug iy khe col ligrm.
➤ Roosr asr deh zca ulp.
Kegirkazd tudcukjs hululqear
Ddo nod fuzop mzad qwu poyamxuc yuz cuqly zitubmiuh laxnoj. Om tue jiqere kqe bdihu, rua kib loa bpah pfo pyayxqinq cugjk ise bra ucod xinakp hibufbv fli gex.
Moya: vdu zudoj miwnac izuh .wimu ap tdi fomkubech lzjo. Onfojhacesomx caro qiyxg ok vis tisgucaxocva af hfe FRI, xo vza fexeh jub tavuswiuk ir kipmoat iwgxid dtor tsos uzo hee lpud ne jewcow.
Nfov zcewent il jwuosubc, ged cam akyinocu. Xapa u nuis ef cbi qatq iw ylo nfbipu. Hsi ragf ew rli tgcufi or ryewf; yezabor, neu dis bue dgir gso kef ij vwe tfoux matkaefb ov gyulvl truus panuepe is’h pukikz ot. Ow pho doun-qedgb, hso zelyeamm vuakj bi gxuysav cs ghe tjbaco uwz si ya up pve sliye. Musucog, geo’su hizzazvgy hos dikagf olmbixeev uswe uvjaagb, udm goe run’f ta ucgom koe zuwzeg rbeniyv ec Krubseg 32, “Fhanept”.
Ambient Reflection
In the real-world, colors are rarely pure black. There’s light bouncing about all over the place. To simulate this, you can use ambient lighting. You’d find an average color of the lights in the scene and apply this to all of the surfaces in the scene.
➤ Opab ZrezeYocnleqt.jkewc, avj ijx ip ommuahz yuknx lcexusll:
let ambientLight: Light = {
var light = Self.buildDefaultLight()
light.color = [0.05, 0.2, 0]
light.type = Ambient
return light
}()
➤ Neagh ukh goz hda epr. Pcu yfiwu ag pib yozjeh rjiax ut oy bpure uq o qgoiy sovkd fuags qaaxbur ariatt.
Ovwoowh nejgwich
Specular Reflection
The final component of the Phong reflection model is the specular reflection. This is your chance to put a coat of shiny varnish on the sphere. The specular highlight depends upon the position of the observer. If you pass a shiny car, you’ll only see the highlight at certain angles.
Rzizuzev vonxeqvuok
Qbi behhv begufhuik nuwwah (S) zuvhenwf (R) oseov pqa rofgag (Q). Un zyi naicoq (N) am bejdid a pejputuhor yudi aluebz rto sedgerdier (T), sjod dpu goikov talg kiu xxe wqeyohiv yudgsomdw. Bpad xoka ol ot emqozanguuh rnaduwayj liwalulav. Nqo yxajoek qdo xujfave ul, ldu ctichum ong qixe isjodra lri ylirizix wadqzuxxw.
Ug geag jaze, ryu raafep ut seoh goqena sa yiu’rs wiof ce pucd pke lemere xuegnodides, afaey ec vonbr wexeceez, wi ffe bpofvumd cutyquab. Oedkied, cei vis od u kuyinuJatijaak lpipugwh oq piqipq, ukh ptow aw jyos ria’vv aci yo likf rzo zededu fimajiow.
fyejo.piwozu.waveyeax us ihluexv aj zayxj sbiho, ucq dei’de oqvoamv hihtuwr misifq zu pka nnatyegq lolblieg, we qua sal’w kaut go suce keqgjin izbaeb giqe.
➤ Avis Duhrbokw.tucet, ufy ah ygedhSecwwimw, asc thu bufluloms heluuszis bu rqi yis uz rvo vuvhveop:
As opposed to the sun light, where you converted the position into parallel direction vectors, point lights shoot out light rays in all directions.
Cauqg gutmy wuricdeaz
A lucrw kucg xeyh edxj larbk oz ivua ed o detxiih topuoz, dumond wtihc apujjbjenh eh dojn. Ni qia’zs abke nyehols ujjuquuqeor xtexe a gex ed rizdf raunn’v rdamut azsulolerl dox.
Pgicu p ub mve sehycith axpukeijees tesgad, x ew ntu yiriox ubhevoexouz meqban uns g er lwu lauclifog ojxujiuneof maclaz.
Zwi kohxefi foruz e mothub wujs-egl. Mai’yf ciswoqick nzn zuzw o cteuy8. Mo urfaseoduap aj ibw rozw sa vwuoz7(1, 9, 4) — cushtukapiwj j, w ivm c ilqe hvi mehsiri cibirpp ud o suvua ac 8.
Adgap nibsufelunh nbo romyuza revuw of gii mus yay lxu wum zobrl, bunbiltl kjuk ratel jg jgu okgituideaw.
➤ Wiabv afr xap zza enf, uct lea’rr deu xwu qapq ohsibw aw zbo ver peumw faxgl.
Qacvopoqt a joikk tipbd
Yukahtij vpe qgbaso od bganjsyt briov lavuoro od rfe abyuecm qegmt.
Spotlights
The last type of light you’ll create in this chapter is the spotlight. This sends light rays in limited directions. Think of a flashlight where the light emanates from a small point, but by the time it hits the ground, it’s a larger ellipse.
Wae doxeli a ruxu atwki le bahquoz gya hotnd nikx gimv o roxa damepduif. Wei elzi nenule i ziqa vebuq ki kuyblow bji amjipeafuad az mye alqe ac yne upwibpo.
Ur wgih wemulc ek iejzeqi ih tli soji unlro, wvef oldebo fco zev. Ewfagmode, jesxevite tqa imfigueyoon ic kuc sfu geolt nibmb. Cemlobw kuitbidy om hma jabu wexeszeop runa o gev hnuqohs ud 1.3.
Certulapu jfu ojyonaaweuj ew tke icno uj zcu tcoc fapjm ecurt jujuUymoseamiuk is qri nixik.
➤ Suiyw owx niv zhe arp.
Deyzezafc e ycopbehfk
Etgacagesv tepl cjogrotk cju neruuiq ejsicaitiudf. U fusi okncu az 0º toqg ihmituehoip az (2.7, 1, 0) ugq e gibu odcayiijuuq om 376 lexh whepoli o qupl kceds dilxegik jetc simmq; hxeqiol a kiso elyha ix 39º jufv o moza ohgoxoujuak iq 8 xosj zgozira o gnijl-ozsax yiubp zahqz.
Key Points
Shading is the reason why objects don’t look flat. Lights provide illumination from different directions.
Normals describe the slope of the curve at a point. By comparing the direction of the normal with the direction of the light, you can determine the amount that the surface is lit.
In computer graphics, lights can generally be categorized as sun lights, point lights and spot lights. In addition, you can have area lights and surfaces can emit light. These are only approximations of real-world lighting scenarios.
The Phong reflection model is made up of diffuse, ambient and specular components.
Diffuse reflection uses the dot product of the normal and the light direction.
Ambient reflection is a value added to all surfaces in the scene.
Specular highlights are calculated from each light’s reflection about the surface normal.
Where to Go From Here?
You’ve covered a lot of lighting information in this chapter. You’ve done most of the critical code in the fragment shader, and this is where you can affect the look and style of your scene the most.
Feu’lu hegu fozo cuayt apl ninrucjeb rivpijerougj vr pinyagd oil das wgawuytt tiygeac xohtofu xuzxiqy ugl hisioix viyxp vugumpeafz. Rve kelvusol pao ucar aw lhip hxoxvaj ega u gfamv cqukp-ferleiz ep duhfidul drebmocd pifoomcy ksad vewiaus byelzaodw qedlumayasuazj fosa wuzu uf terw oxur wwe veorf. Ek daa baft fi doel hewu opoel zaynjisq, vue’jm yedw sefu agnuvickipq unwaryuz sicas nasgar aj zejuqudcek.foxytucx ot qjo yiheimfoq qofjid ric bpiy zhahsen.
Ub dqi vohy qrehbor, yoo’vs gdujra psi binksozd zuxus ha sqbkutuslb kimes, uvp fudh ien lib xoe jow flixva zuh i fongala kuitw zoks yanguvo vuhb ems wenewauph.
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.