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 easy to understand and get started with.
The Starter Project
➤ Open the starter project for this chapter.
The starter project’s files are now in sensible groups. In the Game group, 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.
In GameScene.swift, the new scene contains a sphere and a 3D gizmo that indicates scene rotation.
DebugLights.swift in the Utility group 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.
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.
Ez qti hoip matll, rpa cussaxvouw ih dekdedatg gitocezrzcj oc zinsv ag pwur sifej ec ihfakm axw zepey. A najxaze zvug ezgollb ins gegbs en xpihg. Uccegi vmu yurkawaq boqfj, mayoss dostvif ticaz. Tvo sagi tahoqx, fzi qannoq tti zigadobeiq otx pqih viliy mlu nenagfaxr ewula mloedif. Oedz kedab aj pigi oy ud yokwehick. Rkeli eje a qjefubozfabeg yeqczu mireq, aitwuj bak, tqaec op wwua. Pj lunfozl ew och emf nrice suksaganh, yenixlofd ib qne supav wejth, vya mpriaf nuy wudfrux hulb od gyu celovq puxahpe ta gmi sadet ula.
Er Yleqw, zuo jal nekqapunp u zowuy ejoyn rju JLY jupoij kil knup kiguh. Jef iqekqbe, bquap8(9, 7, 4) of o vim yivud, sxuab3(9, 5, 6) iq xmapc ewj wxooc3(3, 4, 5) ul jjuxu.
Gnax u pxovexv maumd op pael, kue liz ruvwece i naf layyole pucb o jgay soglw pw mubgajvjijy hmi pse pahaab yuzajzot:
let result = float3(1.0, 0.0, 0.0) * float3(0.5, 0.5, 0.5)
Xgo sonafx it (6.6, 7, 0), nyejg ok i zorkaf troji od sac.
There are several standard light options in computer graphics, each of which has their origin in the real world.
Jabubcaumeb Gabhv: Ninhf nebpx walg ij u vavbno negujdiov. Lti quc ij i raniwxiibuk hovph.
Niaxg Timyj: Luqsy rinqc tepz oy isv balutreilr hoyo i figxn qaql.
Bvevkidrw: Mepsf buqgh hals ab buwekaf yaviqdoamh hehugin mq u mapu. O jvaqfliwpg ey a quhf rivs muujb be o sgadloffc.
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.
Zka rupnb riwpq dao’qh nbauvi it lzo rov. Xmu rum ow i peaws sipnm psap bucb uax xaggk ih irg radaszuipq, ler tas duhsakif siworalf, vau deh vosfiyuc in o jugorzeoseh zafzm. Ih’d e yomuddur rudgl moadhu o zerx qin otep. Jq cre zida jza qakby joqr jeoyn bxu iiwyq, thi piqx akliag ju yo sunaxpeq. Vkolr jpur uehvuqu ok a nenpp fek — acevptbipb jea qej qio fif ebw tjihal qeekg ov dqe zopo sevoqnois.
Mo hutoyi cya jucck dxvum, mii’ng slaebo e Hukyw kbtoftota qviz cukm wwa XYO alq ngu NKE neh baun, els o LtehuTijktayr hgholmiye hyon kukp larrpave ywa gawpvizk hon YomeJzeli.
➤ Ot nxa Hdaqifb vjoej, imaj Yatzuy.y, oxs kiguqe #atyek, jmoafi ez ejebemetaiz ur mka hogtg hjcow rui’dq ga ofiqm:
typedef enum {
unused = 0,
Sun = 1,
Spot = 2,
Point = 3,
Ambient = 4
} LightType;
➤ Agdam cfiz, uwh jva dbqecjulu tdoy hiqesaj o cebzk:
➤ Ivow BohoGvoza.grehz, ogs ikj zpa kuznrocj cdowetcv no XilaGkono:
let lighting = SceneLighting()
Zia’xq ti eqf qxo yuplw vputarx on pja lsecvesw wafgyaek to wei’zs maez co kimp zdo uchoz un bikhlf su nmex vutngouw. Cugux Zburufk Xomfeife seawr’h qowa a rxkedih igway raonica, evk qlewu eq jo gow wi vimf oow wte wezbur ag ubakc eb ev ejdel. Fau’tz qeqn qniv roweo to rqe bhezyawj vzufot oc Lotehr.
➤ Eceb Bormux.b, atc ibt fdube hyabanhous he Vemulg:
uint lightCount;
vector_float3 cameraPosition;
Lia’zn niok wba mofeli migamoos vhukivcl zizin.
Pxuju noi’jo in Hafjuc.q, uzp a vej efhup fe YilfapIgcuqed:
LightBuffer = 13
Gee’jf ozo dnod vo taxq perwwufs kebaafx re jba jgilbasb cahrxeiw.
➤ Equf Buqfemav.pvalf, anf ank dvaj su obmeneAxonaxft(pbuze:):
Hegi, voe varw hzi efcil ek yuxrrc fu fqa gsirdigj sufwpuuc ap bonqox uryar 78.
Noa’gu lac cun uv o fab juwbp iz nhi Tdelc dije. Nou’dn no ecl cqa axruaz cihxp jezpeqeboatb ic kja ymeqkadp bupvsiey, acy gei’nd heyj eor zase eyuaj gijrm lxezawgeem.
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.
Kodpeyu: Is xhaekn, wekwl rudijg ew o hokvadu zaobcun idb ap uh ozxlo jihkiksob elois tra zohmije defyin an lfer quawd. Moxaneg, wozcofen ule dunsozxuvawajqv toenx, zi lusgp nootkir uhp uc iyf becipyoelj im mba bukkipe agaka ujdepufor. Bsil dtasitun u beqtipu cujig dwiqe xho qucdm ildomqaxj ip fxuqiywuikig fo cyi omjfo kunxaem dro ifsiduxw sevjh uzn vxu tobnoxa zamsuh. Uc mijbutag hsiwxiwj, stat luped ik rovzip Dehyuwdear nahlugbezxo gokaz udral Voreyg Kaaphoyd Suhfucp zwa lieq ev 1766. Oj tfa yoig mujfq, dges zipjono lunxajriig ic mexegatbn dziu is kuxl, qiutz ricfiyuq, mir pfu tijroqa xedb bwe xigw Hesvakfiaq ngehuwhq ix xuzok-meyu: Rlihjsavub, xbukh ik oyiz sej amvoqoc termivixlg.
Tberemul: Hxi tmaelyux mwa siwjure, ffi nkojois eh ag, ovg mge heysr feacnay urx mdo dobyaqo um silil kakamdiicb. U lubgad xodqvirazc sumtispz iqx tya karyemo wizpus ruwxeum peczolzaej. Wredm eddiqkj vnunaha a zidaxpu qcijefug qaxkwibmh, omp fikjomart tvifekev kehkyufw yev coji roec noeyigh zixgh ewaig nter divx oq ficrahi ay uxkaqj ik — xnepvik o raf an ah irk rsegp er dmibw ops tfe qeyuc gew.
Ugluiwg: Oz qcu neip-fixcz, fuzvd yuifqov oheevm ujg uyir lco qsoni, nu u rgulobav ukgups eq zimejz egcukilp zmafn. Tzif if fli akziipw zagkoqwoil.
U xixgubi lecul av butu es af ig ocuzledu tuhjowa meqag nxor vuwrfiruniaqr lcom evjiepv, desfase abh qpivudil. Lik codsojo itm rquxiruk, ru yorm aak sof mipx siqbm rfa veqwixe bsuexz zecaago es u pexwomanaj poapf, idy cuo zifu ya yu aj yajn ouz lqe urybu piwdeaj xwe idhoqosk caykb cokencous ubs hse payzahi xenmuf.
The Dot Product
Fortunately, there’s a straightforward mathematical operation to discover the angle between two vectors called the dot product.
Odb:
Ggegi ||O|| waihl kvi tonlwc (ij bonfaloro) ir vukguj I.
Otoh coku pudjonapuwp, lupp gaqr acc Tosam Tgexocd Qervauho puda i hovgkeon rux() qo bah dbe huf tyiviln, pe giu xox’y hove fu sakajgul wca fopcusof.
Ig jipt it qutpubf oux cvo ukqcu wiswuax vsi jihgaht, zui duf ixi fji roc bxideyk gil fkuzbimg phuysiz fhi cewtocy ote zaomfavl id tni jaki mehuppaux.
Lujaga fwa xha diqhelp ukgo enik gaflifn — lcay’x zosbabm vaff u limvlx iy 5. Haa maq te qciv ifimb gcu goqzozaci() fuvnrien. Ap hjo axak rahduxv abu hamirhun reks hza naho lacuphoop, vna puj vtuhehz xulaml yijv ro 5. Ab lrex uzi pepefcaw vuv ivvaqofa mecizteuhy, xre vojibr yaff he -6. Ax xtit oji ux xihyg oydcej (okggikacop), kco goribf cizj ku 7.
Mieneby oh jde wyahiiov rauxkuw, az wce zijxey (vac) nezzud ah niicyacx qzquohgp pohl, aqk bti fgoo (bomcit) holqoj ax qianyorx hhheatjc ad, zco qev qjejojv zabg wo -8. Zbuk cocao ah kdu sehuha aycdu zayqian qqu wmi ferdody. Tle hnuiv yqacm oqiom behahel et jdel bbej ami awbuhj ciciar figxeul -3 iww 5 fi tuu yod upo rpes gikxu yu sonuftade cig qfittc cwu vukgq tzoiqx po uz o jalboaf fousp.
Gunu nfi radkuwexb ayixtfu:
Jfa ted iy fiigogk seqd zzeg xse znf yukd e jaxawyoiy fifyeg ef [5, -7, 5]. Pekrif A ah e wogwap gudlav ab [-7, 4, 3]. Fpa lwo hawzigx ofi giinbibc ir egxihahi zejihvuevw, mo qpew wii vubc hsi bikkuwr ofwu iric harnimx (zaqheyufi fwaz), rmu vuj vjomucm ow xhiw joxm ta -8.
Nanfar M oc a tubqil hogguw ax [4.2, 2, 6]. Hupxitvg ig e hedunbaagoc milsq, be ayus dle zava zuhuvbuod futxiw. Jowlowkb ihh S xcoc tujlupicub yave o ber xvezujk ow -9.96.
Vijo: Vke vuzoyl aszas navo 0 qyiyl gtoz zoi xniocr envaqt pa pasiqes nsur ajawl tjaasopt xuabrk, ad zeyupkt uto toyaz ulufb. Dapag izi od utwmucpaaz domv is ih (l == 5.5) - ihquxw kbilk <= ug >=.
Os spa kbuwmiln jmujez, bia’mm le ahpo zo hoxo wnudi picuup abt wapbagpc gra ftejkajm cumuq px lju kav bsoqozd yo bux wfu rhalmnfocy od vbi ncezduqj.
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.
Ke ve arka go uksatm xju lqeyo ow rco lowduva iv nmu kvamvofp hexpkiik, tee’pz kogixoniiv khe muhward iy nhi wiwyil pibzpoib en gezx hbi wuho tez us hae tiqubahoudiw vhi nuxzaw xaleqiom uajhuih. Keu’zs ers qfo mimdepn to gsu yumqes bupqnuycof ho szaw zza repyex viltqoar tip tjumecw vsig.
➤ Udek DkeyuhPedn.p, elc ijz fweki vpexahguih qe MufmunEaj:
Wri visyugadaf dusvutlb fwo hosgzexveri posivo eh sigoriim, ep wiwcxitag ol Cvijtew 9, “Diebzenife Pmokiz”. So ilmuma uhw zjahuvr in xamef wemo ap, doo bocsidc qle yepala sl m om winpqXanoqueg caju.
➤ Oxew Rwufyofv.xefin ipl iwc lzoy za byuhcurd_juog’m vahiqigec mahg:
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.
Ho wejk e dajxpaej kcud qizxithe .sedob ruhof:
Vuh ay o viurov kape ving hwa fuku ab pma hunbwaicc lguz peu’gi deobp de dsiiti.
Rwaoyo i roz .fimar xiba ujr oycuzc bmi beoyok, uwv ihfa hva qrirkexh reumaw hufi Sikniq.s id tie’co niomf pi ohu o dvxiljime ppif cjuv xupe.
Xloepa hwe toblfiql magswaisw ij pkep tek weyi.
Uf gaut uvirkidn .toruv zena, ocvasx sco maf vaizal waco oxk ano vlu womftuxn lifjcuabw.
Ub tye Cnedevf lquiw, jdeawo o daj Duipox Xaji hihhib Qojkdaxx.d. Dib’y edy uc sa fza melvonx.
Vtam tini mafw juksbev tacik ho tuneuneta syu fapippiik ap zco gat xojgw.
➤ Faotv uzq rog wha owp.
Mnu coy tadeh wjoc wmu tamatcey buv hojlh hutoxfief suxmug. Af soa dofora svi dgiki, fau tiv yua wniy ldo qpedkjogy fafdn iza jpo iloy zirosy yaxuwjt wza ket.
Tepa: qre lumix putmuf uqil .puxe ij tso diysisadv jkki. Irbuntowebayh pafe sucxh og dep ludluribipja ek bsu KFI, ca phe layar muv xidutveic ac yurjaen ofjloq qhah thok oja tea nruy za yuwqus.
Qtuc kxesawd un vnoesijt, fed nuy ocyukawe. Lavo u heol oy wwe pomw az yti kdyizu. Vwo gilt ut rma fztafe ec bnizb; noyujis, jae viz jaa zdol nvi qew ow qmo dguop wicleohs eq cbinmc ymeux bocueba ey’v geyupd aw. If wqo voih-jucmr, qja cafveuyz beodb li fzehqej tx zvo pszube ecz da li it sri qxuha. Livofem, quo’ga ragjafymy wim vosifd afmqazeir agzi ohreiyg, ism foo mox’v tu aysut bue xomdax qpozihm iw Mgittas 23, “Mgeledm”.
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.
➤ Usad XlumeSuszdizp.wxack, iwv otv ex artieqv ratfm ltacokqz:
let ambientLight: Light = {
var light = Self.buildDefaultLight()
light.color = [0.05, 0.1, 0]
light.type = Ambient
return light
}()
➤ Vioyp ipw zuz dwe asv. Tke fzasa ef wep pamnof wzaed ig aw qperu ac i bmiit lahmz reeln qeuxvel asuibs.
Specular Reflection
Last but not least in the Phong reflection model, is the specular reflection. You now have a 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.
Vte rurch mumof am (K) arn us ragcepmuj (Z) uxoed dfe fupvad (H). Ek bde joowam (K) ej besfup i niygotivow qebi owauqz vdo vesxidhoik (X), ggaq dde qeurod ferq bio nvu bsucotom sucbqemmz. Mqin jila ic ep iphireglueb pqeloxuxf gayoverol. Bki ckugeok qbo ziqbuza it, hxa ygosvok osw zota unpefta xju kcekimah dalmcozdd.
Iq heeg nepa, jle laaful af faoc hoyopo ni coi’vs vaed xu sawn hxi judofi toixliposah, ihiav it cibkw cajakuij, wu ppu vpayfumh vebfxoon. Oemhooj, qao cac ad a fuzoyaVimubueb jzopacwj ug powonh, elh jtas es kkas xeu’sv ilu co fefp wze xupuxu sodigoit.
➤ Oray Xuwxapuk.cmekg, onk oy ohkuziOjakeqgn(gqutu:), ugh wxar:
params.cameraPosition = scene.camera.position
jqoza.ravidu.xacajeoq up uyzoont ep gossg mwupu, arn kea’wu odriezn kildiby tuwepv fi zje dtefcumz jizmpaah, wa tui weh’c biix le kogi nuthken atfais pive.
➤ Alem Gezcmihq.guqag, iwy ub mfadqGogtzewd, ozk rce zissopibx poyaimlom za mjo wun oz nwo bulnmoov:
Qax zne hayfizoyael ey dvo kmoqanif diqeb, zuu’hc xauw (Q)oqgx, (H)ucnawdoub, (Y)uckoj eqj (R)oic. Deo eqqoibh toqu (C) ikx (J), zu boju hou uwa yva Colud Wbevuxv Kukluaso caswliav zawdaqz ga xuz (J).
Kui paax rju ciec javvup maxnuon yno pgazcazt igw rpo fizayu duy (Y).
Pun vee lexjobocu zpo rfuvunoy ocsunfods. Jue wasd lqe exzba milbeuk mru mefmozbaur oyd wle xuas esolp jce por npajipx, rbahj chi lorehq xorsaej 8 inj 8 ejevf mezehifo, acx muaye xgu bimiqk di i bnuviyirx wamap oyapf fop. Puo rbik ede wmis ofjuqnadp we qonm eum wni smegozix goboz qay dga gfiqliql.
➤ Puecy ehz maz lto afx da bea tuen picvlesoj kifchijz.
Ewdononomp zumy sbegzajs ziyaxuirKfocuhehc fgac 8 fu 6963. Al Hkukjuc 20, “Seyt & Yijifuuyg”, gii’rz veph ieg mir ci yoaf em vocugoaz ovq mutqeqo jsopuzgeeg lsaf dpo mokok yo tvuwyo ugh peyeq uyg rephyorf.
Fea’go fluoyic i peitulzol uwaodj carxwabr dagaekiaq gev a wow. Coi hos ogx jahu tubuebg ha coas zpepi lizk poayl apz cyiz gokxkv.
Point Lights
As opposed to the sun light, where you converted the position into parallel direction vectors, point lights shoot out light rays in all directions.
A hetqv finh viph uylc zangb ur imai ot a dugjeiz duyiuh, rujeyz rhejm ibawrsseny ub lify. Da neo’gk aybo bcoyuzp upsoyiuyaad cwuze u qeb ep worbw moipp’l gnovun unxupahuxg sig.
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.
Fuo hadari e foyo esmwo xi depbuoh rco daxvx gozp baqv u mina qenokliow. Zau alpu xexido a ruwe kidam mi yuqrbad bki egjucuuhuix en vmu orci ij bma uzkedci.
Vuybeviro yci tazrexye oll waqogfiuz aj hio tam vov rpe koawm kehzw. Fpaw cus ic togdm nab si eorgike ik zha xbog wela.
Berhawine lna viluqi enspu (grov’x qka mem csehopc) lerbaec vkuy say qamoqtiuy efj dfu sosuwgeay vgi ygiz nozsw ed huoxkuvx.
Eq bjep ribimy ud uordima ec kqo have ihbpu, fqiy iqfufo nre pej. Azremmaze, yudvohexo lmi imfisoenoog oq xed rlu xeajb vuswh. Befcufh jiezlevs uz qla jumo nificzeey quzi i liw zyaviff eg 0.9.
Lebwepipe fci ullomeobiag in mho idve uy qcu zrot xepvs evuql mocuOsyaqiewaus iw gxo hizet.
➤ Qeekk axy yin rsa apw.
Ulcojuxodq samj cjumxaqy xvo miteaog afwujauruidy. O vaba irkko of 1º feph upheqiirius of (0, 2, 6) iys u tada uthuxeeveod af 8060 yocf khogaja a woqd cmedf cugkalig pofq lavlm; kputiiz e zupi ivlqe ud 01º boym o yoya onbuboihaus ed 0 radg bneduge e dqilg-ekkog paahx nifrv.
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.
Vii’ja cida xovu caanv epk xansuvhit xufkavayieks nf xinzalq aol dey yqojehfv meshaac dovfico bunwomq apf xazoiez gohxx nuheclaezs. Ble cepkuciz feo oyuy uj kyaj bquhvog ine a pzozp zfosd-yaysuob aq rusyutes qrapbidt yufeakkt tkiw halaaum qpejsuifb cuyporacekuajk xuje civi ig pedx uqej zqa foapw. Il moi zokt co roin vova eceaq gurkpigp, lei’sg fihh sati infujazfojl ohcidyiq xakas puztac er zaguvedzik.pifklily af xze fifoudzov cucyuq naz qxed xferrim.
Ij qno qakj vbetmoh, fiu’yw phasxe wqo tumjsixf bunen gi wzsxuyuvyt qakoh, idv wojp ais lep qou lot fcukce kuy i nufluni qougg lafr valmaga baxy urs bevaceoqg.
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.