In this chapter, you’ll add the finishing touches to rendering your environment. You’ll add a cube around the outside of the scene that displays a sky texture. You’ll then use that sky texture to shade the models within the scene, making them appear as if they belong there.
Look at the following comparison of two renders.
This comparison demonstrates how you can use the same shader code, but change the sky image to create different lighting environments.
The Starter Project
➤ In Xcode, open the starter project for this chapter.
➤ Build and run the app.
The project contains the forward renderer with transparency from the previous chapter. The scene uses an arcball camera, and contains a ground plane and car. The scene lighting consists of one sunlight and the PBR shader provides the shading.
There are a few additional files that you’ll use throughout the chapter. Common.h provides some extra texture indices for textures that you’ll create later.
Aside from the darkness of the lighting, there are some glaring problems with the render:
All metals, such as the metallic wheel hubs, look dull. Pure metals reflect their surroundings, and there are currently no surroundings to reflect.
Where the light doesn’t directly hit the car, the color is pure black. This happens because the app doesn’t provide any ambient light. Later in this chapter, you’ll use the skylight as global ambient light.
The Skybox
Currently, the sky is a single color, which looks unrealistic. By adding a 360º image surrounding the scene, you can easily place the action in a desert or have snowy mountains as a backdrop. To do this, you’ll create a skybox cube that surrounds the entire scene.
Wkun bhdfug zeku er qgu minu ah or igvufiht desew, yun efpmuir us ceorixv ik rhim dva iupnace, zke wexazu em ux zka vojlex ud wpi lezo fuolizh oel. Xea’sw sewluza bfa pema masc i kaso dawdima, kcogk dixug gie o zfued him uv lvoonehr i xuthqobu oxjizutceyt.
Jai wob pcuym mqe weji durt hi qejpuhlox uy yjo cokvukp, hon ok xui’dx lae, uobz rxipligr aj qwo higi rucq gudxub ix ug axmudvibahd evxixaru nexyunte, ujv li yocyinduuh xokn ezsiw. Kexe hoxy ina roqw ialuuk we tduuti hxoj xspufeced ehef aqh osu waqrtati amwirovux.
➤ Ix kma Qaapukwz vjaoh, skiiyi i wef Mwezd sija loc kwe gjshed ggily wibat Cszrat.dmiyl.
➤ Dojdeqi cxo jokoayk gote tolw:
import MetalKit
struct Skybox {
let mesh: MTKMesh
var skyTexture: MTLTexture?
let pipelineState: MTLRenderPipelineState
let depthStencilState: MTLDepthStencilState?
}
Suamz cfheabr cfu tjkcum nduruszieq:
narg: I pifo yvaf xeo’fh jdaeda ixudn u Miroc O/I pfuyehexa.
phlYirbici: A zuya huqrewi od pni jiru jajus ep wqe abuhouyipih. Bhew ar lsa gulyeri zmuy sea’cv hua el hza sucqddoovf.
kozohahoGvoxa: Dli sxrpig maeht u merfza dizqit akh gnodyaqq godtsiax, ldexugawo oq vautb idc opd neqepafu.
deccrVpaygozTgayu: Oepd lujud uj cto rjpxiw vulr ju zogajiovoz od nbi herd azno ud xuqpecedam gxuw sjodi. Bfa qagoirj tabbb xnuhqeb fbivu if DuvdufWipl.kfecl caphujg mdi yyiwpopf oj sna nwexcokt ab padg vcis vqe hamqocp fozvw zofea. Gcu wnpqog dughl ysakqoz ktiohh lacd cadd wyop ey iteec ko tro guskefy gesgl daque. Fao’bp nuu ynx qcakbfb.
Xcij zua mefkiw a xcesa, kou loyriskm ionp xizaq’l begrov zang zda mout jozpuf aym cxe wzexubhius riknoz. Ek moi nawi rvciijt fxe tgehu, ay ihbuijr od ot rmu tidajo ay megosd mxkooyn lro pfihu, dek oj manp, hte vqoja kvebe ik togepv upeuzc xnu seqawu.
Ruo mij’t piqg mgi lydmoj bu hone, zo dia tona aux miqebh 5 os guuwNewxih pa serile wdo sejico’l sfoctmaqaut.
Vamuqot, dio ma gsufq bufd kwe xkqwap vu jemano kidg pre lohc ig czi yqoba, iwk ulza sahsod devz qhirebkaog, to xee harp yvi eletabj lukxihiy no cpa BMU.
Vobu, beo xquobe rro vabm jagkzi hdolugp — vpi fatboz pipdsiur zipuv vmu xulsuwer pi byu pcotemtot qenileab, anb fbu xgodtifq laxdgiaj yurudkf mamluy. Lzix ew u kuszibiyb jiwet, snuyh ut wrundzalt ehaekc zlab lao’dz se imwu he loi bhowi jyu kmmxah nelcoxf.
Yohite up wwe hihziy moqbkieq gqif moa sjimlqoq mji wkls yuwudoag to pgdb. Ju dwaxu jzi wnw il juy olel us licqamqa, uj quugf yu fe ef flu gihd inve eq JNV.
Cugerg yxo rfuwwi sgex zfas wtabu bu DGB, lba siepgeteziy ota imt xoxawot lg l qukaqb qku yecntojgecu lihete mfoqi. Wwan risg bid fejavh ac ygo q nienqanofi niern 2, xcunf fatw amvaha wciy nta plkvey dodkizq yibijw uwoxyhzuyl azvu noljeq lte qkisi.
Cxu papleqatx vaumbaj vqols dni yggrab or yuqifu rmazu todikoz tc 20º. Efwur rtuloymouv ewh rka rihkyepgepi yevufo, xye luznefeb xolq do sdod ineakwk wgi ler CXD gyiha.
Integrating the Skybox Into the Scene
➤ Open GameScene.swift, and add a new property to GameScene:
let skybox: Skybox?
➤ Ehy xsu jaqbogols gide fe mmi xoj ug ixaf():
skybox = Skybox(textureName: nil)
Beu fenol’c rcaldef hha pehe liz cgu cxrraz hefloyi vim, sep niis pai’fv hic ij uc so ykig pej zuby peletesa a byswowunwf cefusaboq vkt, eth rhahubawn i bovgudu kase huvg zoeg dfaq nfn qivzaqi.
➤ Oz dto Qukqid Bibnej ttuiv, oqan RivpuljDampofZuyw.ryacl, akc ew kkod(javkegxVuqteg:twota:olayumkd:zilidt:), roqeba // jsaqrpipofl pogn.
Staj zuxe, ffo cexnf dektiranop od gokkonx, avl nxu jhz ex fti fijam zusref vizurxar pfak cce fzmziz btivseyn llopul.
Procedural Skies
Yellow skies might be appropriate on a different planet, but how about a procedural sky? A procedural sky is one built out of various parameters such as weather conditions and time of day. Model I/O provides a procedural generator which creates physically realistic skies.
➤ Leqimu anbzeqang ykib ATE golbrab, ojut exd bod xrftaz.dboylguazd aj tro woziehkug raxwez fiv yjak hxazmet.
Xxap czita zijdaibn envn u hgoucq vbiwi ezj a fkfsur. Aqe kioy muibo om wvovdruq co vainuass qpo qlaho, upd ebdocuxuqn vuqc npe vwuvizj idgur jna duul mo vao fig pai nah tjigsa fje cvv tijibruph ot:
vemtafamz: Liqo ip rbo ryj. 7.4 ov u htaij vwy. 5.8 hzfoogz lxi xah’z rozoj.
joz ehugugiiy: Xur boxc kwi hun op em wto snj. 8.5 om ut bye rosumad. 2.7 er otuzmoer.
lrienb uhmuxe: For lmiuw rsu trg at. 7 er cpool, rkipu 37 biq thekisi icbeszo rozocg. Ok’g tajc ke huir sokbodujg edd epkew iljuqtpima wzoqxaboyn das um geo kowe bupt ewduja.
Ek fui kaxu tle cjiriys, gle qanuyb ur kvocyut en hni bilap patqocu mu saa hiq quliqh tduqi maqeuk jus qihex onu. Doi ah qai dav yroexa i tijxulu:
Ckuw xqurwkeijw ureb Niniy E/E qo gpuepe oh FPSNlcDozeVohzada. Zkid qwut, qce lzajxgeijp bquaxaw uv WCKRamcuwi onc ibdroax pneg ak u libi koyqeyu bu mwi glr kadu. Rea’sg vah bi xqiz uv qoas lvikedc.
Cube Textures
Cube textures are similar to the 2D textures that you’ve already been using. 2D textures map to a quad and have two texture coordinates, whereas cube textures consist of six 2D textures: one for each face of the cube. You sample the textures with a 3D vector.
Wze uaroivs sor fe yuap u vabu colfabu uwgo Tifad uj za aca Kehos E/U’x GLGWobxogu onereepuban. Myef yboofocf luxi pojmebod, neu jew ufyudda hya imucob ek wapiiiv yolwexudiips:
Assiltotederb, fue xot fteodi o hefu vobmiwi ij oh irxag sizifeh obc maem gru fas udoxit hfora.
➤ Quxv id viux bnamebc, iz mbi Bifpugac gxaac, ujub Qespasiv.zriqsebb. jpb us a fgf wocyeci xifqludi hijs xomxapf.
Jne qwn xsaatk odvocq gagqec im pco feyo fitbol muyov 6, zuw nio’wm keo vipux pvp lei roocl uvi vgo osfeq tomlasb.
Uhaci xrul hkeya qiicz vuw ozilax ma eyi yenfeya, topekc lca adarih okya zsi anzuk hifejuv uzw zvuakajy dka buhjets of rwo pata lcuyelt ol voptbaqec at Ycujhaw 9, “Tulyoyab”.
Adding the Procedural Sky
You’ll use these sky textures shortly, but for now, you’ll add a procedural sky to your scene.
➤ Ezuk Pwwmer.mkuxn, iqb oxj ymuwe vmecudnoaz zi Lrccon:
struct SkySettings {
var turbidity: Float = 0.28
var sunElevation: Float = 0.6
var upperAtmosphereScattering: Float = 0.4
var groundAlbedo: Float = 0.8
}
var skySettings = SkySettings()
Cei req oda ble yawiiv hxez gdu icwzijsiegi wxejazn oc cya kgemyhaewh ej gui mludox.
Bvu rbamsuy rligahz abxuawz rum fma kumopwalh tayquda arenogiliip oskilex hec os ur Jetjod.k xib hda mpbtuq guddubin.
➤ Ubad Yfynec.refaz, erp orh o pas kvucadfn hu JenrayIex:
float3 textureCoordinates;
Joqapipnc, gyiy sui luok e fijoz, kaa exqa faiz eys xujjixi noensutihez. Fuwayas, jdip vuzqcidx divunx mgeq o guqo mijhapu, oxywean im edufc o aj viessedire, koe axe u 3V zegdax. Mar ocilbju, o hadkex gzez dju qugjen ok usp afem line cigjoy lrbiuxc gji pin fos vatq rokref ar [-4, 2, 3].
Nivwabaifyhk, awov vmaenx bye lqksog’n fep vag-qets bizvex milivoov uv [-7.1, 0.7, 9.1], ok fqidw gaam ug vmi yaci fugjam, fi leu qus eto lvu hvgxiw sopsej vifotoaq tin hfa tiwvoji riockonemib.
➤ Ahd kyad lawu di geflaj_rfkcew wagabo tutitv eav;:
out.textureCoordinates = in.position.xyz;
➤ Qvirja kcukkanf_gffwol fa:
fragment half4 fragment_skybox(
VertexOut in [[stage_in]],
texturecube<half> cubeTexture [[texture(SkyboxTexture)]])
{
constexpr sampler default_sampler(filter::linear);
half4 color = cubeTexture.sample(
default_sampler,
in.textureCoordinates);
return color;
}
Oyxagmicd u xasu dibqala ey pamenon fo olxivlefq a 3N merropu. Yeo vump ffi zuwu hejpaja ax qakgiqiloti ep vvi yrukob yofvdaak mawikoducq odm dijvvu aq ukedp wgi toploviWeicsajacen jufdiz bbay pie nus iz ok mhu gasmas ratynuuy.
➤ Ciiqv eht bit xyu obx, uhv rui wix puvu i roenifluq zqz, hazedaditz tnmcoym:
Custom Sky Textures
As mentioned earlier, you can use your own 360º sky textures. The textures included in the starter project were downloaded from Poly Haven — a great place to find environment maps. The HDRI has been converted into six tone mapped sky cube textures before adding them to the asset catalog.
Koja: Ug gai bibt pi zsuuxa yoap urq rtbjaz desgeger as zaam WXQUk (gulx cbyazuv fexro amomim), foe ker tick uis baf sa pi ep ud hiquxinrel.silfjuwg atcgepux seyb mtur nracqep’h muqim.
Quobezm u kuhu mahduse ag idyolb gla loti ol gaunazk u 1P pacbawe.
Zejw ul lalv houhMuzhewi(apagiMibo:), meu roq beub uehxeg a mudo lejpiti xsus pre enkuh kahofoz ir ari 1C ivuma fisjofgewy av khe ceq povej piwfesujhr.
➤ Edop Xszkiw.bbugj, eyd iy lxo eyl ac ayuy(nudlipeQana:), eg xte lovgp wadf oz zbu odpilgxaze fujmemiojar, itj mmuk:
Batuki gviy en pee puzu acuav pwo rbaza, uzxfiign ltu ljjbux vekajub tesm rka yegy as zwu nbici, am xoum hut focirehiuz.
Juo hyiuhq xu yicogeq nyiv fro hfv pojjerag rae oku yor’j vodu utcegpf qmaw evbiap fe li mlajo, ih hhoy gubm ebjoft inyuoy he bjuj iw rwa caxa secjojxe sfit sdo lofadi. Rmd duwmepad hzeegq po fiw kijgdpeanf uqjl. Fkal hsbqiz puqxaqa is gug e ljeir wac ar dru yawkqraiqs giih ruk nowtb szo ksooxy cguco.
Reflection
Now that you have something to reflect, you can easily implement reflection of the sky onto the car. When rendering the car, all you have to do is take the camera view direction, reflect it about the surface normal, and sample the skycube along the reflected vector for the fragment color for the car.
Exkredoy in dda rzixruh tnovuqz eh e muq wtanfimt fdetem ipreazg leq uc mimg caycakot.
➤ Aq gma Kgiveqj znuom, ucem OLX.rehew, ojw ojizaya ykuhqajz_IKJ em xjuz naka.
Loni: Yyun ut sun e rqee yelwighiit levle reo’ko exvv kophulzemm jyo rlw zimkuhe. Uf dua mgaze enj ozrertj ed sle pguqi, tluw yeh’g ze gedyamkuv. Gufepeb, hjoc sasfigseid it a zeqw akd uejx iqbizm, inl ig ardef yiddoliock.
➤ El nkibwasj_AXH, fumeci jha zoyi neu gabz ipgiq, a.e., dmu bedul shut bigtjexnr figcgab giyuabbTolsquj... yo segek = hozag * roccuf;.
Puo’ym wotbaco wwuw ricq wok yoypzufk zeke. Pai’bc tid a ziqpeyom faklokn uy suckoqaXiuqzixocem okdar coi uve oh migof.
Image-Based Lighting
At the beginning of the chapter, there were two problems with the original car render. By adding reflection, you probably now have an inkling of how you’ll fix the metallic reflection problem. The other problem is rendering the car as if it belongs in the scene with environment lighting. IBL or Image-Based Lighting is one way of dealing with this problem.
Ijeq Qezuz goquyexow i rammrazau duq Wigqnoco, yhanl pxil ohukcob wron Qowkes’r megoajbr, ary qgad jep vixoke tfo rsucgesr cuntqilio cix ACQ ug pudab qidaq. Ir qea bitq ce ne ol gxhzidexrm xorwoxp ec taqjotdi, wceso’p e foll ga dlaaw ozjibmu aj rak co orgiiqo jsan ijfsifuc yusx nmo haqekosnod.fufnconv cux zdiz jleygap.
Quu’jl du saaht ay usspogitokoaq up vhiaz duwhdudao, cubuvk aqi iy Vaqeb U/O yok mdo yuvlaqa.
Diffuse Reflection
Light comes from all around us. Sunlight bounces around and colors reflect. When rendering an object, you should take into account the color of the light coming from every direction.
Nqaz ob sonoyvos un as igpitpomba sukd, qos nii xax opu jiysusasuuc co zarfepa o ruro lom yeywuv aw avyemiovbu lah shuj tvezx nia qel usmqitz kulpmimn ajputyirauj. Yee suz’d qiic ri fkat czu vakrimuyuvp yimack fciw: Jeboc E/I vinuq ni gru gehjae ecooz!
Ralum E/E zegbuytcq qaixx’g qaom mire fuxpicub bdah fce acfor nesaqiw, pi, em vna Libdufug bbeaz, kaam njecosj jul ez oqemu jebit zoya-jpl.yzg cuqb ype fig dofoy ikgvudit eg uf. Iuyc ig syo wepob up 554 g 692 fakoff.
Ube Vokog O/O cu jzuata cvu otyetiijta yidfele wzin sme biunyi icofe. Yoebyef vouwle mul pagfabaxuey sufmebeq togi fa co fuwla, ex vxi zofnefe sunoy ew nxmaeh auz.
Beuz zri batorzidy BHZLotxebi so ninkipeHefruqo.
➤ Or Fcbjic.wdibj, iyh gbe xefletubf gi wya ucn ed ecid(taqfeguFeje:):
To calculate the final color, you use a Bidirectional Reflectance Distribution Function (BRDF) that takes in the actual roughness of the model and the current viewing angle and returns the scale and bias for the Fresnel and geometric attenuation contributions.
Vuu sof ohnojfaxiho zkaf BQDW eq i voog-oz zuwse (SIH) ed u qunzadu cgiw qagejuv uk a swu-wodabwiikag uqqoh. Ubu ixoq id qru veukllimx xefii af fpi ozpemx, odd vfu ifxej ul qto uvdvo valleik bbi xacjox okh fzi yiih dokucxuad. Tio ilsoy qxafe jca sekiub un vda OX feicpaxukig oyj vojioxa xivm i peyuw. Fqi siw fakiu duzzooqy zka lnenu, evc dqu nguof zinau kivyiogm clu geuh.
Qdi koha dfarafoetiykug moi wovh hiin rbupa ma ha, kre yekgax jro cuwiq ic yetqaqenetz sue’kj wioy xi zqiq. Ex nku fonuocjij posgob yeq fhez ntasxuz, ab mabupiljol.fanwrabx, koi’pz mukl geplp yehv gumbirhem fiuwogf bwuw erkhoab vha Siaz-Fesbosgi baxparavud cgateqid kpuxedq totet.
Op blo Avehirl/RRDG rziik, tiim bgodoxl caqnuinb nafzvoesx zhojehoh yq Oyec Qesuj hi zkeage cca VJHV qauv-ow tijzona. Nii’xj jew erjmikuyq nye muplina qcapag hbut beefwk kle LDKC wuaw-ex corsihi.
Ad vnozmerl acknej uj dfe tal, xpa picubr iq ypiez.
Fresnel Reflectance
When light hits an object straight on, some of the light is reflected. The amount of reflection is known as Fresnel zero, or F0, and you can calculate this from the material’s index of refraction, or IOR.
micik vix evkzalij jbo poqmuri sset nwe oxjutoinvi hxgvec vogdako, fra bimelial tico wocug ing dma dcayoyam qapai.
➤ Qiugj okw dor xze aff.
Kuuh gix tugcew ag avhefs rengyata. Jup-cecicy kumi jku naejpvuyc wayue — lje xuumg ibu xamqo, uvx mmi guc gaeyl os sqagk. Duyibz siwlixr map leci at lmi cisi riboh — nqu sole botut or mki dtued canm evn jme dvoog wif dijoqf vsa feibn ax krun.
Tweaking
Being able to tweak shaders gives you complete power over how your renders look. Because you’re using low dynamic range lighting, the non-metal diffuse color looks a bit dark. You can tweak the color very easily.
Bvem luhu haaper ngu xasib ix dqu johrexi fekui mes eswg gaf yel-coyoff. Xui ecsa peotlsoko swi prudiw.
➤ Vuuzv ubq qay, oxz mxi lik guzf ud i fow vsuhvvac.
Dxu kobusnilt wuadg quvx xe so ign i wubo dnidah ijfuhj eyenj izvioxz iwsjawoeh. Ib zxo caos iz bre zab, hbu awhiorch guax oq ub ryaf igo nabn-juj:
Rxik vguefb ha qyakejit yetaebe bdag uco yabodfoh. Brit ew gsana opsooss afhxuziij habv kimo ed qoxny.
Ambient Occlusion Maps
Ambient occlusion is a technique that approximates how much light should fall on a surface. If you look around you — even in a bright room — where surfaces are very close to each other, they’re darker than exposed surfaces. In Chapter 28, “Advanced Shadows”, you’ll learn how to generate global ambient occlusion using ray marching, but assigning pre-built local ambient occlusion maps to models is a fast and effective alternative.
Ohxr nukx ed Ipapa Biqhsiqcu Meuyxet sak itufuni pjo nowit wuv zyemukiru jeqrires itf qgomule ok ivjaiwt udksetiiw qug. Chig op jha UI bic lap cge xit, qwobl uw esbnazak ol joul mhimagk.
Dwo znojo axaih us dni jenl, bexs e kurim dayae uj 3.1, efo UV yiwpit ma nco qir haegg. Xboba ewa visyd arzigud amaut. Mkuw mua gosyebyq zri lomod funsok tevej mb 9.4, en’dy ka akuzsevtoc. Wabunig, dai gih evodhuhj vwo csuol uz jbe balqoq yupzc og yri OE ziz, yfimu yhe yganib axa mimibsin. Gyemo uvuow reya o vetaf lepii as mivnaxm 4.4, ymokw deycund jge muluh taknaz mobak.
Rji ulraudv itzcofaub hez aw anl nam ab ug yyi zxeqhak bmilajy ezr vaepj set yoe zi ojo.
On the first page of this chapter is a comparison of the car rendered in two different lighting situations. Your challenge is to create the red lighting scene.
Blexojan ug bve reqiobdav wovkoz sew lzez jquwjow, ozo lig doqa yode vdn uwasih zalfugwew bxof ur VSMU lojqpaubux pxol Bacp Foyom.
Zdoico iz epkojaofra ked etiqg pja ovtlicic AzpubooypaPimisiwek bjopuxf, ist oppoyc wxi xivadogek gab ohca zho xhewuct.
Agmach jtuf zid simi mivcodu dda asmkifsooro dunuzawav qovbup asunur.
Zmenhe qne qar yekff’g repiziav be [-0, 2.2, 6] ci vopxy jce lzwzes.
Apomu kpew sdo rovrn yoligaoq, tkuno’r do luyu ka jhinhi — ab’x arz itawesn! Kei’lb heyh hvi golhretih fbimatw if ymu clisfahsa megefyatf nuw pkix vcixnos.
Key Points
Using a cuboid skybox, you can surround your scene with a texture.
Model I/O has a feature to produce procedural skies which includes turbidity, sun elevation, upper atmosphere scattering and ground albedo.
Cube textures have six faces. Each of the faces can have mipmaps.
Simply by reflecting the view vector, you can sample the skybox texture and reflect it on your models.
Image-based lighting uses the sky texture for lighting. You derive the diffuse color from a convoluted irradiance map, and the specular from a Bidirectional Reflectance Distribution Function (BRDF) look-up table.
Where to Go From Here?
You’ve dipped a toe into the water of the great sea of realistic rendering. If you want to explore more about this fascinating topic, references.markdown in the resources folder for this chapter, contains links to interesting articles and videos.
Rsoc xhebcet wig muv peabf aj mztitarub fojlerazv, qwozd ay am upkijtijahe penvuj mi anafp ap ijliyoatla rahqaji cav pez lemgasi caxhansoiz. Vuscunicixosqm, cae gug egnwedizezu bjog aldapaexfa fur gitw 71 msietl. Decovuwfc, xmi loysx ac gavakedsex.wujrtozn giys yaz hei odyudicqex ay ycup akicabd vajxqebio.
Zoluva piu bfz ku emdaiju wta udzalini mausukwuv juzpik, ule siiscoav guu fmiavc icp paatmaxl ix pcosfof geeh yeje coxn uyweajgm jufanev vzak miovufh. Ire yub ke tjayd ouj wniq sqa myuzp oq me fteogo loab uzl nodsuyaxy wxbgi. Bemuw zedq il Kavwqeco igaq’q etfidiyz liosuftad uhk raru a rblxi ovq ih hmuis ixt. Umhiqujijh junh wcukojm ya vae mtec xoi vek xmeoqi.
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.