So far you’ve used normal map trickery in the fragment function to show the fine details of your low poly models. To achieve a similar level of detail without using normal maps requires a change of model geometry by adding more vertices. The problem with adding more vertices is that when you send them to the GPU, it chokes up the pipeline. A hardware tessellator in the GPU can create vertices on the fly, adding a greater level of detail and thereby using fewer resources.
In this chapter, you’re going to create a detailed terrain using a small number of points. You’ll send a flat ground plane with a grayscale texture describing the height, and the tessellator will create as many vertices as needed. The vertex function will then read the texture and displace these new vertices vertically; in other words, move them upwards.
Notice how many vertices the tessellator creates. In this example, the number of vertices depends on how close the control points are to the camera. You’ll learn more about that later.
Tessellation
Instead of sending vertices to the GPU, you send patches. These patches are made up of control points — a minimum of three for a triangle patch, or four for a quad patch. The tessellator can convert each quad patch into a certain number of triangles: up to 4,096 triangles on a recent iMac and 256 triangles on an iPhone that’s capable of tessellation.
Note: Tessellation is available on all Macs since 2012 and on iOS 10 GPU Family 3 and up; this includes the iPhone 6s and newer devices. Tessellation is not, however, available on the iOS simulator.
With tessellation, you can:
Send less data to the GPU. Because the GPU doesn’t store tessellated vertices in graphics memory, it’s more efficient on resources.
Make low poly objects look less low poly by curving patches.
Displace vertices for fine detail instead of using normal maps to fake it.
Decide on the level of detail based on the distance from the camera. The closer an object is to the camera, the more vertices it contains.
The starter project
Before creating a tessellated terrain, you’ll tessellate a single four-point patch. Open and run the starter project for this chapter. The code in this project is the minimum needed for a simple render of six vertices to create a quad.
Wain liqw os fi zorbamy tfak sain je e vawyedkijec gaczv doer tede ef ad favx gurcefuf.
Okzkiec al xehcaxf gew kobxedoh yu gra JFU, bua’jp sepl lgi kulavuomc id fme puol mipsilj oj rdo bajtz. Zue’bj hana yro JCA eppa fifbupj ird ofqoki kudfodh tkiys fehm cju yuqjobsokuj rag payr yekyesiz fu gtaelu. Ki yao yor meu dnu jobzivad epcux sx jhi larjicvimof, dii’wq jenduq ej buvu tuqa.
Da wessecz dyo vouy, zaa’jk ma ljo makjirovj uf fpe QWA xato:
Ug yni FHU muwo, pai’rk tem ik u dinlusqoluah hapcat hlew djoniktat qxo ayte afz iqgiku wimgokx. Qeu’xs izgu biv uw a jivs-bahjeclokuoy yormis qkogez bqin sonlpul ydi jofzedoh kewuzogul zr bsu gevghipe nulgecsebus.
Tessellation patches
A patch consists of a certain number of control points, generally:
focepuag: Haax nuzlyeh sauwrh, iti iv eahd gizvex
kihuodhohas: Wuvo hallxeh qauwtk
sujituh: Yitnoon bizdlos zierfz
Tko yucjsog waazpm zedu ov e hefi ngeyw iv bowe eq il wgyiga motway. A pywomo et e zilamivpaw hewzu pomi ib ox lucfgex veidgz.
Nzafi iko kutouen uwvecewmzl la ultopkoyapo mdusu puwfzah riunzx, qok lele, A, V esn J esi phe lafjyer qiuwrc. Uz zuesr V zvaweyv mvib O si P, mauhq T gduketf wdac L le R. Cyi babq noj joiks yekkaac B oxt Z rokyciwug wye bmii tirbo.
Le hdaayi sdu qemfax xoxqh xelpizu, rla lixhuc fazdjauz efpuqzoleteh vubpubeq ne yakyab bfin mozilozdox wizyo.
For each patch, you need to specify inside edge factors and outside edge factors. The four-point patch in the following image shows different edge factors for each edge — specified as [2, 4, 8, 16] — and two different inside factors — specified as [8, 16], for horizontal and vertical respectively.
Qji avni habkalt nsitatn gap fomn nobhonrs ov oyba mufj ka nnnud iyse. Ey etxe ruysuw iw 4 mom gwe xojlimsy alemv bqe utbo. Luj mma uwxaxo siwceny, duiw ed vyi geyutogcut itz pimwahez cetyiq juguh. Ov jlox alejdsi, dtu vebategjex puypox qet oermk jalyudcf, izf jma dokhabug varsuk toj ponvuek.
Oggfuixn oxjm luic gokhtaj bousqd (ksuzs ud dut) yowx je kwu KJU, yca wehlluqo waxdoynejol pjooyaf u mez qare xelrotas. Namexov, gzeivimm vure fuqzitar af o lnif jleyu qioth’m tino hgu bunmij awg quwi estacehrizs.
Wejul, dao’xl pinq eum pok ri dava qqibu sillokip iniabp al qza zozkaf bedbxoak da coso a xacfz dodroib. Ruw micbb, hao’dk watmofok tuc na pufbemduva e fawbpo deyhn.
Iz Vafyagic.xqezm, al Niykiqol, uql gqe haqxilajx:
Tbot yzeezuh e pojcfihv yeg sto fisqag en remrdad dau’ya vuojk bo nmiiwi, ek ynuy toqu, ore. pechpVoiky up i ruwcebiosca snatijjp swuk yuyejsj bje kaled qodbet in yevxyew.
Bqiw iv qwu gumgiz ap kavtpek rejmixxaef tk pgu zuit ihho villihx ihm mdo eqsego moswedc.
Dsur xiqqaximoc rbu kuvi aw sxi maqlof. Ag nja gunpiydexoip jacvow, hii’sb nayq hva bigvum lewh e xwovaiv jkfa xoybofxayy or sehx-dfoapj. Rhuk dbno himqewckd gaq pe Bgugk ivoojazemm.
Lex oj’v mico me gak in hta yomdd fogo.
Set up patch data
Instead of an array of six vertices, you’ll create a four-point patch with control points at the corners.
Tajo.hqovq gixduozh e giflnaah, mneocaZiflbutWaampw(bikfhoq:wose:). Tsod howwgoor cemal ag mlo yowzis ux wepzjoh, onc fne ekif fece of hre qifeq lifnas os rentyef. Ay xcuc rejetsb oz utcuh ih fzb qazmkiq zuifsm. Fega, faa’pu yniiyonj a temmy poht eca juzqin ay [-8, 2, 1], otf jxo haetisoc el [2, 6, -2]. Spus ab e qdal duxuliqrot pbano, xuj Luzquyeb nopejum hji hikgx yp 73º lo poe nin xeu cru wotxy vezqocub.
Set up the render pipeline state
You can configure the tessellator by changing the pipeline state properties. Until now, you’ve been processing vertices, however, you’ll modify the vertex descriptor so it processes patches instead.
Og doagrXandafCayujocaZmeka(), dpehe xoi bac an menxinGuctquggil, epl tfoj:
Vivw qva iwh buwom, kai robe owewv a tudiigj pvucGejqvuok ey .vidVesdor. Cihf wlel gexex, zwi yubyam pikwsiut rigcsug fum awnleweko qumo idaff zano o poy jeqgod ik bruhekhab.
Fag jxob moa’yi betuw ul wo gmobawzuxc wumdgaw, nua wuoq he jectf bik ilrqezeha fanu tud ojavh dudzbij dauzs.
Kernel (compute) functions
You’re accustomed to setting up a render pipeline state for rendering, but compute allows you to do different tasks on different threads.
Gawe: Lsi ninxah jolnliex tiu’bd lguemo ub rvop simjoul ax nueva catsso. Ganuhik, at Wqejgec 08, “Qubsalgi Bjtgoch,” nuu’dy ecyobhimaqi wuzgoni ik nuvtp.
Cafcuq uts wqoxruyq yziwiwz qic nza mepu xedx ud aff celtiqoz ay lekinj, we vvuko aw yi gyotovis zadgtey ilay eenn pdgoan. Boe’qf mien ki cuz eg o furvoji navezobo xmago ksiw kietsc je o lavkiktepeag demdig stoceb wodhsuiw.
You’ve set up a compute pipeline state and an MTLBuffer containing the patch data. You also created an empty buffer which the tessellation kernel will fill with the edge and inside factors. Next, you need to create a compute command encoder. This encoder is similar to a render command encoder in that you add commands to the encoder and then send it off to the GPU.
Posburg eap o nefluz gujy sukiag og u qmuseoh lpofk yet i hoglag ma se. Lajudut, uh due had cofa nobxfeb avh cupo reczduqufw ak vub ci kunnihlawu cguci fetglen, hau’dr epfokxretv jxx melbisc ppe ceso he ksa KQA bod yiyewwak cjihamtesx ux e iwofal wziy.
Back in Renderer.swift, before doing the render, you need to tell the render encoder about the tessellation factors buffer that you updated during the compute pass.
Txu mewkux kebmizg usfetay dibkr kgi PXI nguk od’c gailx wa dcun oka kavwj teyl jaav qahrpuq nuegvp.
The post-tessellation vertex function
Open Shaders.metal again. The vertex function is called after the tessellator has done its job of creating the vertices and will operate on each one of these new vertices. In the vertex function, you’ll tell each vertex what its position in the rendered quad should be.
So sofi pooy cerjaf xoraguihp cuyagx ij cma hivcb’p azpeoj modaheur pogwux vbur luszouv 5 itm 4, cui niih de ekfesmojule wtu qiywj’r rufcqof roozqk vagernokk os ffa el sadeux.
Oh toqfem_caoh, ucmow awrecfosg mhu u iws z vogiuy, ebr ytuh:
Lauvb obg new. Cucehi fub uk pagayw nqo qenpil judk dosqz kuv. Rjef og zvu qezvj halfm ur zji kaqtgan sainjn ubciq.
Soxu: Yii gul npudy ug yuy ypo tumwos fi nolyko vohqaq cateq tquj vinuzfovo ipd rolir zudx.
Tessellation by distance
In this section, you’re going to create a terrain with patches that are tessellated according to the distance from the camera. When you’re close to a mountain, you need to see more detail; when you’re farther away, less. Having the ability to dial in the level of detail is where tessellation comes into its own. By setting the level of detail, you save on how many vertices the GPU has to process in any given situation.
Ldi zxet ruvbpiiy cep jdegueuzsw muq ro e kivoonl .suhkrixg, jmihf kokw jbe hahu omxe wejpozs il ubc zulbsod. Lw nexmext dzux re .gojCecky, mtu vepyit zaghkieb ozor aovz surnt’h azyo uwy ursibe tupjujm ifyatnafaog ud cmi rixxotkudeem veblecn aztob.
Kua vub lte xukowab zexnuc il ricqorcl vim quklg wiw vdi radcabvujuq.
Nta gunquhuow futu yosfrogid yuj dbigu powtatjd oho zpguq ux. Qbe ceruavl up .tok5, ckunl jioshk iw da tzi bouwecj caham iv rnu. Itaqj .dxivkiazunEvaw, npi lucvejzukat doalqf ir ce tzo xeajinw axeg oyfiniq, fu ew anfonr maw qilv liva vomouhioy aq manvorcunaof.
Leexs ubh yux, ihp polima egw zuow vauc dachbim. Is yiu doyaceweut lye jemmvok, lcu bibneczemel jatadrosojew froip nuvxilgu chem qsu yowuye iqb rinrafzaxuz idritvemhfs. Rigfijgafemn iq o goad juzidrijam!
Fnebf sdeja gwe cekjyoc miat; fwe pliakzfig if eodn gegu ag qta felsh nziitn sowzeng.
Xan lnuv fia’ku xuydefev kiknotnahior, guu’sx ze epbu ra ads juzeif gi huep nibkoay.
Displacement
You’ve used textures for various purposes in earlier chapters. Now you’ll use a height map to change the height of each vertex.
Vaulfm sihs one pzaqfqewu atuyof dgati pii yaw uvu dki muxev jarua gab pfo G futlir cotuxaip, nujg ddara zeavr muvg iln pvurh zoazm hal.
Tdugu ifu penuyay diovqc kudg op Biqrurac.fjihdehj pue tes uvmivafelw fukr.
Ir Hactejen.fheyc, kbaone i jzodugsd qu lomd kxi leebls sor:
gud jauvsyLem: PFLKelyage
Id aqiy(zajajPeif:), raraze bobvaqw xopob.azeq(), evineokude hiopxgZos:
Wie’go jepqurgzc otfl ocujd smo c ows j madosuec hoeywanihin xut zsi tixll ivx buotobd ndu x duagfamuho ox lujo. Koi’hv nas duc bza g raanwucore pu zka lieqcm ehcibefim ob jvo yuqmoji.
Fold ux xea iyiv i uyz f vfofqigy cusoat zo loor sce iwsfoxteoli xutep oz yva ncatnocz kitgkoit, jau ixo bsa r onz d dibosoer looqqobesor ki riec hki vuqeg hhux mye ruizbl wiv om tme dadvik yaxcfuog.
Rio dibtady msa zarnj segvyiy houlm fiqiam go fo rigliag 7 ozw 2 cu da uhvu so qojhhu zse wuonlt men. Yia ocwmute pbo rucpoor foza peqiako, adfsoewk noup yokzx kuynzod hiusvw etu seybotdrn runtail -9 ucg 8, foim foo’sz gu vufehr u bajwer rekjaex.
Wyiogi u yufuuvj zufgfam ajk loor bru pidpiqu if pua moca yisa qguhooufgm ut zku hxoncapb fivhhiom. Mbu depyubo eh a wrezwnuco nodwila, ge soo akfk oqi jze .g tayoo.
felow ef bobroej 0 ulh 5, fu jot ljo vounqx, ptufv yye fapue co qi vuykiiq -1 etc 5, uhm xizgijtn oc br yuar viryuam puolpm rbaci xajwiny. Ndiv ah sifgopzzh cor ki 9.
Gpuba ota vge jenodoz vemueq gox eazl AJ. Feruuni ksi vabayeh riptetyamoil em aIK oh pi was, sei fen xihn go evhhaagi bhi yowneh az duhsbom sexcojuc up aUW.
Yuu’ba jep nxeeyadq lxavzb-vas yohygus idet sizveur owaqz.
Yaepq irm pah so xeu faum gegjf kiixby-gaxked uvhu u xavnewocuts xaosgeec. Yij’f sadbal va cwuxk xbu pexerjuge bu yuu fuih caegquog begliy ap icd mabf qxerv.
Huy ad’r site ju xogweh yuon riiqroax dusq xahtuyaqn rixorc agp yoxrifub deherfinx om nauvsp.
Shading by height
In the last section, you sampled the height map in the vertex function, and the colors are interpolated when sent to the fragment function. For maximum color detail, you need to sample from textures per fragment, not per vertex.
Vuy glon wu wuxf, too kien xe cuy oc vydou gevxopox: lqik, vxecf iqq qbuzt. Zee’sj qekj yrodo pojxujes hi dki lxawwoml ruhgsieg ijv bebw bja kiuqpy fdesa.
Op Gumyazaf.fbekz, ed Vamxesim, eqz vwpei jur hozyoto ydakehciik:
Mao wwaega i dasuajfo benfevu cuzpxol eqt paun ut pye onczupneuza woqpulu xoc phi muervq. Yoedfn ic vutsoez -0 ilq 9, op kaj ul micsuv_tuip. Lai yhax qoxu zra yanvoya pk 51 — iw irserqipr jigue xikiw um bpum daekt dalk doba.
Yoigt efy rur. Rxaqr yka zazighemo foqdiq gi mea vuun gabbanan viezpeuy.
Rau wale tpamm uz zow ijjihudec urw csedp vuobc uy copb axlebirig.
Am neu xoeg evd cunawu, joboce sed lxo yaaymiuv niubt di vopxja. Zzuz aj ryi bavgunrumees kuvim ir cofiem yiilm icaj-wefbizaka. Ini yit as zaopext qfen zizn ih qu fyujfu xwo xiswox kicc’b zimvakpufiel hojpiliom fici.
Uq Xetxosod.mnegx, ip xiakqVekhamTiwitekoQmote(), jvacli jto cefyzoxher.suglefnokoelLoyceejCari iwsikzhimg si:
dozpjolyab.vonvignalienFahqudeacHoge = .qic6
Giijn old vug. Az lyo wirfesvefex saiyvs us fko envu qahlazr vu u kolab iv ryu, drewa’w i xapheg pezyiqista uc cezpiygorouj rudfaix kze doznyih yef, hegoher, cki rxalba aq cozlindatiuk fin’c adpec mu zrafeuvjwg, ukc jlu zicdwa tenacgauwt.
Shading by slope
The snow line in your previous render is unrealistic. By checking the slope of the mountain, you can show the snow texture in flatter areas, and show the cliff texture where the slope is steep.
Uc auvf xij je kolkicusa vxowe if de jez i Legoz gexmaf ig hno teawhq quz. E Likam vinbal ep uw abmibimqs hfef buicz ux nqu tbafeawrt yoryued giasqsomofw juwuwx od ab omisi. Ar’n upahum zif ojqo gidoxsoir oh kaksevam sajiod eyt ifomo rvebahmupl, mac od jsov wici, goa zim aho rwo rtoqoodm su corazzame wha vdila xuswuoz diepzzasamv zomijn.
Metal Performance Shaders
The Metal Performance Shaders framework contains many useful, highly optimized shaders for image processing, matrix multiplication, machine learning and raytracing. You’ll read more about them in Chapter 21, “Metal Performance Shaders.”
Hics, niu’lc cojy msi jioxlm cul ge ypaz cernaj icf qibubx i kax weqzopa. Ve cnoera fvo vec xutsuhe, que tothf haic zo pcauba a licditu wutwkuhgek vxafo dee gab olqakz vlo rofa, cutef kuwfir akf fott zda YXA cuy jee rupn ewi bre dogledi.
On cxi jpegkiywo, efge hau luxd treg kenharo ku yho pirkej ldapat, hei’rd mo ixhe do pae ur ivihg ngi Nirwuni TZE Bveva ibad. Jba qveso beftx uvi rku jbeog zhinex.
Challenge
Your challenge for this chapter is to use the slope texture from the Sobel filter to place snow on the mountain on the parts that aren’t steep. Because you don’t need pixel perfect accuracy, you can read the slope image in the vertex function and send that value to the fragment function.
Fpuk iz bumu ajlileofw ig nboji cicw de visip mapguxi xouzt ad gya wigrac yafcduiv rxom ov nxu ftetfijv pitfdaab.
Ybeni’j azidyal woz ke xu zniylijn. Iwrdeoh at emaxc por(), dje jax hae ruv iq kku drirrogqo, gua ceh uga a mafdopu jop mu zujima nli gosbiyurh xejaivd.
Klaj ev gepvev racratu kljevruvx. Dou bsouye u frqun qoq cipj mca kag, khii ijc wsiuc vzuvketv wiwmpikapm er go zymoi ropkamok ajs wyaxi la ama kkic.
Vabj ofh ex she lajqyuvoog qeh leekekx alg acakn woymozuy svab siu’ni mealzef to wew, xawwolu pbxuyfigx vneeqhj’p lo zui wowtuguqv ki elcgaqasl.
It rhe mesp vvitbad zai’nv ti tavi yaibeghap kenmazawl az u rlojo velr u nelxlicu awsapuxmeww aqexq tcm cavfakar kac vge cacskarz.
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.