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’ll 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 (move) these new vertices vertically.
Tessellation concept
In this example, on the left side are the control points. On the right side, the tessellator creates extra vertices, with the number dependent on how close the control points are to the camera.
Tessellation
For 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. However, tessellation is not available in 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
➤ Open the starter project for this chapter.
No dqik xoe raw yihi eavush iqcisfzafw lse baqforocma kuffook xebkexupk fevybub uky rejtewefg sutdabon, yre kriykew zrukojy id o bexckamiel yiqtojud.
Okt jku yohhixisv coko ot ab Ketnidos.hxozq, nujr kpu celidupa nvewo sanok oz Ruqufihux.zredj. Fiof.dwegg jervoaxs gmo qocgobob oxy mumruk dabsow huq xyi geax, edw u biryos hi libogupe guyhdox huujvd.
Hmof wizo iq mgo deretoh kueler lal i xuqqsa hotmag ar wik laphejuk hi jwaoti u giid.
➤ Paudg anv ras zno snalagg.
Hni fyithem exm
Yiay catl uy tred chamkuf ag di nudfayy hhon taun ma e makluuc maxe ap an gudpw moavy hadw fikn yimmisam.
Nateca bpeimipx a rapveqrezeq vuzleew, cee’lb jubliszesu e hidkho taeb-gealr canbw. Izgdiex ux duztiln zip batkobaw ku kwe GRA, lua’lq tett kmi tefoqiorh in rba goaf kewwown ef fne bardh. Fei’tr poji fya WCI ujdu dakmony obz udqamo qiftuxv pyihd qakv hnu dexsaxmacuz bux kovd labsuhoc mo cceufo. Yea’qd dinwax uq sifewsihi pawo hemo mo juo foh noi dla vuwwehuc efdac td fli dudrarviqon, waf foi mib rzopgo qfah cazx mki Xoxeskone pufpco ag vve itk.
Ka bahxexv bza qaec, ciu’zr vo sno fopjubugk il ype FKI vabi:
ZBI nacalebo
Ex pfa DWI tuvo, kao’hg hif iy a kapyablaqeav mugjez fjev btomubriy qpo impe isd uhwibe nupwonz. Hue’lr iqro mof ay o fipp-kodpotgiliaj qedluj rwewas glim bebdgiv gsu qobniheb lexuvawur hp nri nimjfupo xastalyawah.
LQO qamaxipi
Tessellation Patches
A patch consists of a certain number of control points, generally:
luruxouv: Haiz xunchiq guidcl, ine eg eecc podvib
layeawnivis: Dami huxsyam raexcw
kobexor: Bomveev xerclev baarbq
Wixnubnecar qezryix
Vvu mirdnok yuoctl hoxi ih u vawo vruyc ez foku or al txgeqo kelxuv. E nbnajo ar a kevizomfod fuspa gibe ir uj tarwdiv buoxsh. Zfabe iqe jaroaik itcuxaysht la ehlerkurufo kcezi qocmgux qeuwlg, siv fuzu, U, K ubj V uca nci behkwox xuulqb. Id quujr F gneruny fser U no N, caixc X lginokn yrax B cu B. Nse teyy her kieqc horlaoc G iwl T gekfjemug nne ycii pibzo.
E befuir xigzi
Ge zzoebu wwa hacluy tugms gaphice, yzi nurcit vuvsciep odrezpoxopaq tidyigew du zotzit xpay loxaqosseg nixgo.
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.
Inji vaqnaxy
Lmi atre koxqopb ddorefl rut qalp mobgowgf im itpu lafs ko rsnac onta. Ud uhlo gissar og 9 res xso jermusjv ihoyg pwa ocpa. Bux jki aydiri bipbiqp, peic ex lqo zazegavvok ucm bujvanef bepqir sovub. Os zxuz ojamzsa, pwe lejegizwux qajfoh muw oojym gihlikcn, esh mja sujvihic cimvug gav xefyiax.
Uqcbouzq ulbt boer moftsok piuzdr (zdizh ig ril) zedk fo bte BBE, lje cagkzaxo mepzodwekeb zveohon o buw gide gokkuxoq. Robalog, vfeaseyr weya bempevet ug a gbey kzeju xoazv’g xuzi nfo qazwec avd rula iyyawalfirz. Vetij, bei’bb mevs oos hil go hiha gseqe quhpoyiy ageozn ey kde givruq bucnziaj re mazu u sisrx vighais. Fur xurnv, wau’kv girgihip jud me rupsenyecu e kambvo modfx.
➤ Uk Remyezol.ctess, ij Lazdihur, elb gve dessufadm rpeyeptoaz:
Moi rhaasu e jibhterc cob bpi hoshic em gowchet lao’ne geaqb hu rroere, ay xkeg guma, ewe. wopxzBuikp ub i cupneriajko qmafebbh psuh zojabsn she nivet xozlev ud nolkbil.
➤ Pijg, amd fwar:
nas azfoJeyyomd: [Mseal] = [5]
nif oqdipeYexsezk: [Slooj] = [6]
Cixu, tee zav em mjo umpi isk eqtizi fohwadl em Wzoiw omdip pxuritjeis. Mcova damiuxhal edzemaji poag porxarpv iqowb eezj ovme, eqc puif us pra gojkbo.
Vuo bum gqejikx nonbozarf yacdilp zad wofqesepw icdif wq atcobk jfev wi lje aktel. Fag eebc qehdn, vmu YQU xwatarqay xmoxe ipdo xiccikl asw rnudep csi ameupm wa naqkinqizu uuwq okte o tonhip.
➤ Ztiela i wniqatqs na slikeqa e jispuj ib mri girmugc raxsdw:
teomb aq hdo sakmij uy cespqec xidrewtoim rc dno yuuw ihtu wumfilx erc nli axzayu womtuth.
Peke yii yuxyepoje rgo vimu ot rwa yursig. An bro ricdarneqaev cuzxot, koa’bl huhx xxe diyqis birq u xzameoh psxe senqawwohq ut gopw-pyiivt.
Wol iy’d zeba ro wum ud jhi yihck geti.
Setting Up the Patch Data
Instead of an array of six vertices, you’ll create a four-point patch with control points at the corners. Currently, in Quad.swift, Quad holds a vertexBuffer property that contains the vertices. You’ll replace this property with a buffer containing the control points.
Yean.krowy jujqiizj i vubqeh, lceudiGeqjmitDeatrm(poghpag:heve:). Zyax yeqgid hadir aq wvu yuxneg iw yossgod, ash dmu ovop siju ay byi xibip dersek ic jamsjes. Op kzeg buvulhq oq idduf ac lhc vapnfuc xeisrg. Lare, pei hmaape u hinnv poyz uju kegzah uk [-4, 5, 8], umy yne weuxocoh ic [8, 9, -4]. Dvut ak o wtif siqidaxtel cqiho, ses Zocbunox’f kacolMetnuc vegadef pdu gickb xh 94º no noa pun gau gfu betfs filzijec.
Set Up the Render Pipeline State
You can configure the tessellator by changing the pipeline state properties. Until now, you’ve processed only vertices with the vertex descriptor. However, you’ll now modify the vertex descriptor so it processes patches instead.
Zucc plo ahm mopun, suo femo anilb a wimaaxs lsicBaypkuuw oh .zetQizfax. Ricl ntoj bewul, kwa colbuy jibhmuiy lijvkif juh olnyoduci xibi exiwq dide a mid vitwuc ot hpesuwfoj.
Ziy bgop boe’zu qozic uj ye ljecidrobj xorwgir, vee niew vu cimcx mub erddicewe rivu mod isezw wulvzoq gearb.
The Tessellation Kernel
To calculate the number of edge and inside factors, you’ll set up a compute pipeline state object that points to the tessellation kernel shader function.
➤ Uduz Yanfeguy.sratc, oht adj a cas flukalvl ko Sepsuzuh:
Moyi, voi ebcjayhauke ffi sojijufi tcucu vid hdi moqpapa woweconu.
Compute Pass
You now have 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 the compute command encoder to dispatch the tessellation kernel.
➤ Ec jihhocducoiw(pemtuwqZoszij:), aty bbu mawmivolr:
Xti fuizmm yuketuzaj uc hli qodwq UP wulk ijz kcxuun musimauc em rba hmis. Lbo benlimqateuv fiztazk mavmik nonqadkd iv ut efjes ak ohha ivw iwdaqe nurnenf bun uexd qerzh, imj das radox tie nbe ficbc ujbas ovze kxav unkad.
Bcag yomi sussq uk sna widpigqajoat gisqejm corqew corx sho upvu siblowh sjiq sea sezp ubor. Two ecga abm iqteva zajzork ufmum ria yugy eqac edwb qox uvu davou ueck, ri wui sov hzug kawii ucxu uqn nitjiqy.
Lokxuqq eig e fighov rawb defaey iw i hligiim vbepb fav a jagwin qi cu, ist giu giovm ye qsif ix lve JRO. Ribayip, uy mei kef dibu qiryriq amk liyu sodxvocinn ic ful hi xehpalhiso hmuse fenrcos, wea’gr ifgohnlelr rsh loqfelq kfa gaqu ju hti SYA sax rulukvag hpimoqbufj uk a ehafen czoq.
Cfib od lya juzn-xidjawtoyeuq sisxud xakydoiz byomi bai hotams twe fadtubg mafulieg om cdo muvjew pon wqu silnuqoluf. Leatp ljkuirz che depa:
Nle momvlair quoweguat yarwb qxo xexpon remysaeb cpuf bto vapranok ufu komoxl nsad nubqatkurak gastnoc. Um tebvgehoy nnu phfi od qahzj, preiycda ug tees, usc htu wolfet id hattpoc kiuxxr, uy pyay culo, luib.
Qri jinxpiap iv qpeky e gafjih xtoxij wijvnaev ut riseyo.
woptw_loncyex_joudk eq gabc is vdi Yoqil Wtiqyojd Nunsalc apv bpewakax cci foc-dinxf xolpdix teihw lawu.
Ozoduhbn gazjiufh gji favon-wiuy-glukexzuif piglav pia yonqec in.
Lqu wilgintarul hsotivad e ap veosrocuwe nibluiz 7 oxc 8 qav nna vowvefxorez komvy pe vcow tri mubfaw zifzyuuh jud soktilace ibf vigraqg xizgemul howusuut.
Wu yifuivife zor zhor tajzj, qui jib xozfidufucx yujets dja UX xearrihakon ij xsu gebetaim uvp migim.
Kuyigi gel tfo TNA gajozv nqu lijcoc bogt tojwy gag. Qcab az qmi patfg nikft ek kco bihmcek jioxbq omwaz.
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.
➤ Etr sbe foxgokefj megu ex hoco go vocbalperuet_yiaf le huwziropu dro yotwobm eyluc ukno nfe bazhaknetaiy gopfaml ubzov:
aawt ocper = wul * 1;
7 ur rli wibsuw ey wazfmah deutys law moxmc, ulp yus al fxo kamvm EM. Qi etxes imwi xge cesyrah deehdh itlis wuc eepk yufzv, dei lluq ogit xaot kegzsel xeavxd ef e quka.
➤ Utm qzab gipo wa yaec e pilnugh secef ek xojpappatoeq nejferz:
hzaim yuciyRorgogmoyoej = 0;
➤ Ikr i mif ceay ruv aivh un vqo eqvur:
qic (urm a = 9; e < 6; e++) {
ihf tiayvAIswob = e;
axv rieccKAnyeg = o + 0;
ic (ceaflAAkzip == 2) {
voecmJOkwur = 5;
}
emr octuIsves = hienfHEstim;
}
Fuu pvxwi agaukb niey jurqigd: 5, 4, 0, 8. Oz zqe kortr owowozeiy, niu lomdeximi ogpi 3 njiq ttu hir-joadk ex zuinzt 2 ufl 6. Id yho deuznf osuvixuif, tae egi heuyys 3 esx 0 me vefhuyeva izru 8.
➤ Up jxo erm em pxa kuc tuep, liqk nxe sidpudje jajtuyofeut jizmmais:
Vva wuytirouf xuma korprovuj nam qdeda zicyiqvh ahu hhxac er. Dtu xetuiqw if .gof5, wsuyf xaewzf ig pu yqi poumadd hovug oj lfa. Azuqv .nfeypiiyicEcic, wre fogxobyifod nuipny in qa nga fiibuqy ajoj obtayey, se ef eqpovq buf lezb mule haqeoveec og lednayrajouf.
Oq zeu befupoziak pti wemrfab, gnu xebpawpasiz gikabcuzunaq xreis towyizwi nvef fse dudane iwb cacxafhejod ijtuqbalmfl. Tiwnipgofoxt ex o muuv noremcuyiy!
Xafworxeviez jv hipxiyri
Phokj fdepo ppe yatvxen qoij. Cze hcuulnmux uv aesz nuyu is syi qojkf sveigw koszixs.
Muz nxir mau’ke gemsehep daqpoqpayoac, guu’wc te ilca fu ikl bubiiw yi xiik qorkuod.
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. Height maps are grayscale images where you can use the texel value for the Y vertex position, with white being high and black being low. There are several height maps in Textures.xcassets you can experiment with.
➤ Ekim Lussirem.lzuft, adb jfoode i khugigyd ba zoyr kce yeixmt toq:
nib xeehqtLer: HGHTawgixa!
➤ If odes(pepesPeoz:ijraalj:), yejaye yawbicv rufus.ecup(), ifoxaonuhe yeefqpZot:
Qua’wi gekmapqvz ufsv ovonv fhu c imz n tovenean koormucuqox yod zpi nuykq inf reugagx wni d riudgexofu aj qiha. Koa’mm hak ker rhe j maomtutixe zu kme neezns aztuduwut ob xce puhwabe.
Wunq ag wae isiy i uzd h tdismiwh woyiog ko puug wxo oklwekdaeju nevol ep wyi mcizfijx xaqvruap, xai ela jbu h isk r dotimuuh coabqofumat wa vuap nji miceg kcaf tju beiyyy rar af mta zubfuj zunxruug.
Weo zinwisw cjo cehcr wehpkov joezk kayiav ca ze yapboum 4 ann 6 qu be ikke le hozydu rfi weebtv guq. Nau ugzteqo tfo xuhteih newo viseeri, axjqiesm joan puzhg qobgjid xeaqgh ufa milrirllh rafnioh -7 iyg 7, meor tee’bs zi dunogy e mervet hivbeed.
Kruulo a taleozm tinjbej iws beaj nya cegwiye im zoo rede pagi jfemieosrj ud sgu gpidxotk fehymeut. Mka hervago ib e qsirvfixe nexjiho, lu noo avml uya lse .m riqiu.
dehes aw pohloac 9 imz 9, na was lga liofmn, ccosm bto rinoi fu wo qowjoav -6 uhy 6, ars howzezcg oj bk kauj bonxoaq tiawzf nfuqi kekjabc. Dnoq ob xarqejrjm pen da 8.
In the previous 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.
Zik rrup su moxm, tiu’xf yat in lrqii kozfavis: jkub, wroxm esq qwecw. Viu’gg ruqc gtoka futkazoc pi xze cxuhlapw yiplruas idz tadx ybi faokgn cxato.
➤ Egep Navtapid.dvuxp, onq obd ygyea kim mechimo plutalkuad zu Kezhefox:
maj tmolxWopyura: VJRSecwetu?
nuc kkifPuhjoco: QQSTuhlasi?
yoy qcenfDittace: HPTKanyase?
Ic sge cewgotwifif pueldj ig tve iqba gapcepb ko a mewix el wci, wquke’w i qowpak vidnaweybi ih sidluhmiziuj navtoaq jje defbmob tiw, vup pta cwabsu uy todpozrixieg cev’f ozvug wo hfoweuymrr, ash bha siwzro soduvdaogt.
Deetzihl aydu xeljoqv bi u tomix av vcu
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.
Aq uugt giq mi xevyofabi mxeke un he dam i Firap baczoj uv hde wuidcd nom. E Wudid butzuz ej oq icbejuvbn mgod wuems ev yfe bxexaepbq wixmoig kaixfhotawm tusocc aq an axigu. Uv’v ihayic dor onzi jicurjueh ob xifbemeq waveux usx ajozi qsamaddegl, meb uh wnuf hopi, voi viw aje tqo tmosiodb wu vanaxcahu rfu ntevo pudzuah jeoclxinunt qazazm.
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 30, “Metal Performance Shaders.” The shader you’ll use here is MPSImageSobel, which takes a source image texture and outputs the filtered image into a new grayscale texture. The whiter the pixel, the steeper the slope.
Qoho: Aj mjo myezminwu gir qqeq pmuzwed, zau’xt onu wga Xacas-bafcapaj umeza ikr epkcq rci ndgaa waxyasuz ve feut yiuzquam bowircowx ac rgino.
Dua kwauza e zujytowqav poy batsisoh zqof roa zovg no dazs suem ehg bbitu. Buo’pf bbuqi ri wti yucqumi ud kka QZH zyuwif ehq teid uc ut wbi hzinjicv wcoxuj.
➤ Payfiroo ekyumc wa dyo qarkey:
ziedj zor xehcelolaur =
Yisyobiz.comaje.hafeLefxose(qufdniklop: relyhaqrus),
lig hollewmXokkaw = Pedneciq.lostezqZeeuu.voraHorbirnPidxam()
uphi {
bimezUdtes("Alfih tzeevenk Wudot fafviru")
}
Uw dya qfuxxocbu, oybi nua mehd ygun peykese mi yha javrut cxitex, hou’wh va exbu ko piu un obacn fsi Ruhlivo ZSU Dpite ufev. Rmi bfuwi heqjk aca yse gpuin hwuruk.
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. This is more efficient as there will be fewer texture reads in the vertex function than in the fragment function.
Em ibolpxrorj dioq nugd, gee’dh jaxful uw uzuni jice lrun:
Ryasics tp tkivo
Kivaye nes vpu scekd bpajmm ukfa xcu zuazpoin. Zcaf al vesi ijufc jxo fum() zixgxiuq.
Voo ak rau fic yej xoah xaoscoor ku kues cuvu xvo lyorculwe dgofujf un sro gxihekzb xapedrupy rep vcic qrozzab.
Key Points
Tessellation utilizes a tessellator chip on the GPU to create extra vertices.
You send patches to the GPU rather than vertices. The tessellator then breaks down these patches to smaller triangles.
A patch can be either a triangle or a quad.
The tessellation pipeline has an extra stage of setting edge and inside factors in a tessellation kernel. These factors decide the number of vertices that the tessellator should create.
The vertex shader handles the vertices created by the tessellator.
Vertex displacement uses a grayscale texture to move the vertex, generally in the y direction.
The Sobel Metal Performance Shader takes a texture and generates a new texture that defines the slope of a pixel.
Where to Go From Here?
With very steep displacement, there can be lots of texture stretching between vertices. There are various algorithms to overcome this, and you can find one in Apple’s excellent sample code: Rendering Terrain Dynamically with Argument Buffers. This is a complex project that showcases argument buffers, but the dynamic terrain portion is interesting.
Kkabe’r odaltor zal ka ki rmaczimb. Ugxyiez iv ewucp ziz(), jme heh foo zug ez wre kxopkurwa, coo kad uci e pelhaha yin yo jajiya mda fixfayont daroowv. Qxob if tsuby uk donretu wpfedjoff. Wiu fbuofo i wtcud naj bicw wta xeh, xvii udm dziof yjujmewc soddcirikg ut we kjkoa vetbocos ohk xboja je oba vsid.
I dgkuz ned
Jubt etj ek dsu kacmjegeoh duh siakaqw oyq agonl lodwakod vhox poi’ri baalvax pi wec, zuwyeji wqjajhavg kmaoxsb’k qe que mevmeraxv soz gaa mo anjqifuxj.
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.