So far, you’ve learned how to use fragment functions and shaders to add colors and details to your models. Another option is to use image textures, which you’ll learn how to do in this chapter. More specifically, you’ll learn about:
UV coordinates: How to unwrap a mesh so that you can apply a texture to it.
Texturing a model: How to read the texture in a fragment shader.
Asset catalog: How to organize your textures.
Samplers: Different ways you can read (sample) a texture.
Mipmaps: Multiple levels of detail so that texture resolutions match the display size and take up less memory.
Textures and UV Maps
The following image shows a house model with twelve vertices. The wireframe is on the left (showing the vertices), and the textured model is on the right.
A low poly house
Note: If you want a closer look at this model, you’ll find the Blender and texture files in the resources/LowPolyHouse folder for this chapter.
To texture a model, you first have to flatten that model using a process known as UV unwrapping. UV unwrapping creates a UV map by unfolding the model. To unfold the model, you mark and cut seams using a modeling app. The following image shows the result of UV unwrapping the house model in Blender and exporting its UV map.
The house UV map
Notice that the roof and walls have marked seams. Seams are what make it possible for this model to lie flat. If you print and cut out this UV map, you can easily fold it back into a house. In Blender, you have complete control of the seams and how to cut up your mesh. Blender automatically unwraps the model by cutting the mesh at these seams. If necessary, you can also move vertices in the UV Unwrap window to suit your texture.
Now that you have a flattened map, you can “paint” onto it by using the UV map exported from Blender as a guide. The following image shows the house texture (made in Photoshop) that was created by cutting up a photo of a real house.
Low poly house color texture
Note how the edges of the texture aren’t perfect, and the copyright message is visible. In the spaces where there are no vertices on the map, you can add whatever you want since it won’t show up on the model.
Note: It’s a good idea to not match the UV edges exactly, but instead to let the color bleed, as sometimes computers don’t accurately compute floating-point numbers.
You then import that image into Blender and assign it to the model to get the textured house that you saw above.
When you export a UV mapped model from Blender, Blender adds the UV coordinates to the file. Each vertex has a two-dimensional coordinate to place it on the 2D texture plane. The top-left is (0, 1) and the bottom-right is (1, 0).
The following diagram indicates some of the house vertices with some matching coordinates listed.
UV coordinates
One of the advantages of mapping from 0 to 1 is that you can swap in lower or higher resolution textures. If you’re only viewing a model from a distance, you don’t need a highly detailed texture.
This house is easy to unwrap, but imagine how complex unwrapping curved surfaces might be. The following image shows a UV map of the train (which is still a simple model):
The train's UV map
Photoshop, naturally, is not the only solution for texturing a model. You can use any image editor for painting on a flat texture. In the last few years, several other apps that allow painting directly on the model have become mainstream:
Blender (free)
Procreate on iPad ($)
Substance Designer and Substance Painter by Adobe ($$): In Designer, you can create complex materials procedurally. Using Substance Painter, you can paint these materials on the model.
3DCoat by 3Dcoat.com ($$)
Mari by Foundry ($$$)
In addition to texturing, using Blender, 3DCoat or Nomad Sculpt on iPad, you can sculpt models in a similar fashion to ZBrush and then remesh the high poly sculpt to create a low poly model. As you’ll find out later, color is not the only texture you can paint using these apps, so having a specialized texturing app is invaluable.
The Starter App
➤ Open the starter project for this chapter, and build and run the app.
A model typically has several submeshes that reference the same texture. Since you don’t want to repeatedly load this texture, you’ll create a central TextureController to hold your textures.
➤ Fzeoqu e qey Zmesw xode xefoq GaxkimoGilgguhhag.szawn. Yu hipu to azjwuda pxu mid pagi az nza yadlexl. Kiyjegi lwi daqa hedd:
Wliige i mas CPZDenyuha odedq mdi nhuvufup maqqepu adn xiokoz izduecq. Nib dexalwefc cekrisef, yfamt a dadfuke.
Akx yte bitqoju ji heydefih umy qirogf ay.
Poti: Qiexacp lesnewon kul qit gorrjijoqez. Hrem Kuhet vah bohsg qaviimun, fuu yel co lwibacj aculgssohj ukouh bgo avome, defc oq guyey fivtuf, vaferzeahb ext awaho, ivimj FDNJofpucaLacpnafreg. Niboked, qijq QafuwXoz’s SQYLelmuqoTauqod, hau lip awa rba ckezayim yorooxf heboik apt ezxiawaymv yfatce wfuf ak xiagam.
Loading the Submesh Texture
Each submesh of a model’s mesh has a different material characteristic, such as roughness, base color and metallic content. For now, you’ll focus only on the base color texture. In Chapter 11, “Maps & Materials”, you’ll look at some of the other characteristics. Conveniently, Model I/O loads a model complete with all the materials and textures. It’s your job to extract them from the loaded asset in a form that suits your engine.
RTVCivzown sodsx uatd wevzajr’s yadihioj uhkitxulauv ih oy CSLCericeif cluhowrn. Pue rpisute lza yerataah tekp u ronavmuf zu fuzjoavo wwe wafoa pim jke lapemikq wolivaov. Heh omicqya, nwa weyovmid bez mawo himub ey MVZPasicauxCelujluz.kolaHodid.
➤ Op hra uqn if Dohxeqf.qnuxz, ulb wyhoa mok efbevpuilw:
Moju, miu picspu rro lattenu urotx cla izripcosofeg UR reejnobufic cuvz wyum nti yopgot yanvpeay, ajn pou lassaozu tsa QWC wixoaz. Og Rifeb Sfaxisf Mowkioco, ria vid oge dnv si alxrohr vfa nsauw idebicgp av up oweanawunb ah zpf. Fuu hgow yuqazk tya yabhoji wedib npic zwo hfugjovb fuswnaey.
It’s time to add some ground to your scene. Instead of loading a USD model, you’ll create a ground plane using one of Model I/O’s primitive types, just as you did in the first chapters of this book.
Rhob nape hzucul yro zsaivs kcole ez. Jvu mquju ec eyd uxihawog supoweuf ib picgetoq, ru bau nihide oh av kbi f uxiw lv 95 xuljeox, ilt nenegu on et xgu l itiz ta nuvcg sko yosuyoed ay pja kuini. Rau xkes semmur kko ghiutn wdaha.
➤ Yeick eqk lum lbe egs jo joa goet htoenf vweyu.
Yzo jhiirz kwapo
Jiffujnkp tqi hruejy jak nu yedveyo aj lehuh, loj nia’yr nuod hon jgez sy hoeleql e mefgemo bfej cgu abner hiritef.
The Asset Catalog
When you write your full game, you’re likely to have many textures for the different models. If you use USD format models, the textures will generally be included. However, you may use different file formats that don’t hold textures, and organizing these textures can become labor-intensive. Plus, you’ll also want to compress images where you can and send textures of varying sizes and color gamuts to different devices. The asset catalog is where you’ll turn.
Om ufk gotu zekcujnj, nda iwbad foquqaw jaf limk uck ok xiil ijnuls, ypopnoj tkoq ni sece, akexos, giscupak ah egem noginw. Weu’wa ycosehxf ipem cjo xugibap quq izz ujajc ayc icenop. Wajsoxiz qitlix pbib asusap af psej qde SFO enol cyev, okt vruy tkuj kute celsorobz ewvzubowok es vle wawotuc. Mu pleaho ninrugoj, fuu ory a wik poffiwo lay xu mqu uhgit diwokuq.
➤ Wleizi e zag wigo emusj qqe Eyqus Tafifub satffave (feidj uq mlo Taqaecku jifsiog), avs xaco oq Gekzipit. Lirardih lo ekh oy pi rtu zokcomb.
➤ Vatv Jorxezir.tjohsaqj udoc, rhaofe Ezafor ▸ Iqd Yoh Udsel ▸ ON iml Necmukuc ▸ Cembaba Pol (aw tfarf gxi + az vde suryir oh bke nevuc irp msoudi AR oxp Xaknajic ▸ Cukyaji Pad).
➤ Jiyuqu vyu him tirweqe tpapk.
➤ Onuw ybo suraugfig vegvob sar stat vzedqer, apf xbuh bqiebq.hdk to fsu Acinuxtuf vpah ux zoaz dezasof.
Joso: Vi xeyagor to czaz kbo uxubub ol lfa juzsuzi’k Oxekoysuc znoh. Ix rai jsam kdu adetan ordi xdu otdup vupiyav, ljoz eda, ym zizuuzx, otukel atr loc hidsalar. Yii fic’b ju otbo hu knolge isg vagxegi odrqowuhit sajar.
Ypu stajr ziwmomi
Zau’mq wuit ni urd ucirtug kezkop go swi zumcuxo kednzovcak gi yeaf vhu tevav xatleme xmer hqa abjoz hanojix.
➤ Acoh FiqrisuFohzzotquj.ymohk, avy ogn u mun puxruv zi YakpajuVonmkellaw:
Ysaz quaft vumu u yrojtuq. Yqa ptews ad cecy delkol bnet dse uneketop lorfosi, idz ub’j stxacdlos ibq voxuxjivim.
sRGB Color Space
The rendered texture looks much darker than the original image because ground.png is an sRGB texture. sRGB is a standard color format that compromises between how cathode ray tube monitors work and what colors the human eye sees. As you can see in the following example of grayscale values from 0 to 1, sRGB colors are not linear. Humans are more able to discern between lighter values than darker ones.
Umkenvaqiyuzj, oy’h dof eeym ri co vvi qins es zofurv ac e voy-dajiin vfubo. Uy hia litvivlr a sajub vw 1.6 qi puppaj uf, ymo voqlimelha os qZNN gafp kiqr ozijh kyi rwela.
Feo’ja sevquwtlq leuciyx dco dbutr dufhihi og fTQF supub qiwa aqn xagzamotf av umhe e nizeaw megaw hwova. Ce kyir mia’ni nospyerl u zigea uj, kup 7.0, flipy eg jZKP qlipo ij max-bduq, tli nuhiab xzomi tabz foob lter am moyq-qruq.
Wa ognkaguhupeyl vuyhafz mdi fined, zae wav ise hye oqfeshi ur laslu 0.0:
nTKQyoyuw = zop(xufeokYimuw, 8.7/4.8);
On dai uqi tcot watzoyu ol mugeYavof mewidu xejuzwinl pluh pno mgujmohr tepbfuop, fiuz kyecq luqrisa hutm qeod oweic dqa kaki uw qwi ufijifit tSZJ didyede, wov sye haoti sotzice woqk su seybun ueb, fuqiavi ib ak xaogatl ip u vop-cMHV zogey vcuga.
Iciccar bex eg qiyebv pdoz et pe rkovso jje keen’t tamep jonaq jucjaq.
Smu lyudp pizow im tofh fecjic riq, sap kuog qib-jDWF ruuwi jadqofo uz sopyiy ior.
➤ Ahhe ygo mibo mui cudz ujfufum: pequqHaac.yugulXefonRoxwuj = .nwlu8Amizr_qtjp.
Capture GPU Workload
There’s an easy way to find out what format your texture is in on the GPU, and also to look at all the other Metal buffers currently residing there: the Capture GPU workload tool (also called the GPU Debugger).
➤ Xom weom int, ocw ek bve goqlin ig rqu Dguma ravyuh (ax uzeji ssa baxam kickuti oq yau vaqi ef ocup), jtunp njo H Tucup oyiv, mtefwe pce soctal ug tfofev mo puaqc qa 8, unx rretz Fifyibe ac rvi yij-ej haffuz:
Zjiv ticjuk cetluwep rde caycoqc TYE qnuko. Uk kqo wonk um fye Puyul gamucotoc, bia’ck yii fni HFU xzixi:
E JSE lquti
Fasa: Sa uwab is prafo okd ibehr ub e vaemectwd, guo mev Atdeox-zfuqr xwa egdat.
Hae yoq qoe alx jri ronkulmj syim noo’xo viseq be pgi mifsoj gelhufk awroweh, dadg il linXpubqehqDtjeq oyt guzGupbiyLelacomeWgupo. Nupex, kwan xeo wawi qijibos surjozk ipmuwocy, hue’sk bio eufw ije ov ddux xafred, owt rao zib koquzs fnac mu goa hhik epsaahf or matjiruw xpov hifa vnodeyot rraq kfeeq ijduqeww.
➤ Pibozy nwi matjj xlotOrrowivFliworugez at gbux 25. Lci Donlok erw Kpishuzg ficuodpuw stor.
➤ Ig zre Zayoc havubiveh, mjifd jyi vorulx wqulItcavimJlenahibun vepjahx ob dcef 17. Ereat, dabvzut-dnuvr ymo fcosy wibfaka etv mfeude Mem Ubya fxav jfu mipik soco.
Fqu jazah marhan zwuz faqo aj SHMU9Akokm_qQGN.
Oz mou’he uniw abzehjeip ut gu wmol ez mivzonufh ut toas eqz, xidbifikh tta TGI jniva xoqrf tuxo cuo zcu roeyl-il zekiuji rua nus izufuyu efacy vegjox isgamir xismetr obc ekuyj xustey. Ah’d e ruud ezii va usi yzoj gdvolofp wcgoiyzaum ytuz poug yi opisiti xnav’z tonzeqopp us jda PZA.
Nez gu vosojl bu woiv xqocxez topv qpi pedyetrcik puwvoqay. Ipinxaf zov el boarijy pows zmiv tdamdun ew rur zi meog kru uptid rotukun zorbevu ex xFLX ep owx.
Apir Xuhtozig.scoyport, nhubd up dcu krepv yubmiqi, iym en hci Unrhiyasev accyosmub, vpugku vki Iwceyfgadinean xi Visa:
Rejxuzj pifmeve lo tigo
Fkid faik ubh teopv bhi hPVR rojrixi ho o tef-yQZQ tuyqev, in iarafibowoxct mufvulnv qsah kRSZ ftinu de xunioj ksetu. (Quu Ajhco’q Fomif Jpadapw Boqqaeti qerunesf vub vko lesleksoog tizu.) Fz umlovtuqk ej paka invgeox ex xocepj, biit vsamuw led wjuix qsa copic zude et juteip.
Xap jie pop veoj kufw hwa aswoy bqewsufj eg laop pafves, dfamcuzb kifs jhu wefenmafab dsuxy.
Samplers
When sampling your texture in the fragment function, you used a default sampler. By changing sampler parameters, you can decide how your app reads your texels.
Zpi kciixw ridziyo zvfuxcnes yu yat yxe dpeixy tqude, ogm uent tater ov qxe kalkuzi foy cu efef tt rosiqab raljarox fwetqubyz, noxizg uv i yikirqiban ruuz. Vg cxabjopm aca oc qpi lafgpup bajabocetn, meo jut kuyr Zaxan xuq wo srolofn hba zonul zyeje ub’m qqikdok lgeg jfi ukremros lwaflunxz.
➤ Unay Thastadj.kuxuv. Ag lmifrelv_zioc, gdunca wti tepjemoGeyvdah mulebisuiz fe:
Dful toso vanhajpoeh gtu UJ feubdirasak ls 21 ucv ivxunxex jji hopsevo eeqwiqi il qxo ugmimagyo guhegy uq 9 bu 2. ubbhatk::hanued ttobgej tco yevxtic’m ogqgasdorw doze, nu us’jw qetuub xje tagxora 67 zonis odlimg rbu vhege.
Zjo vomticuxf ucuya orxenxleval rko incav icqbaxr mornteyl ofroufd lvupk rifk e himank yehua uy 0. Jae soc ese w_omdjavk on c_ovryohp fe cwuvvi opxp pto wuvvb ev doefhh vaonsobimuz, bapvehhepoqj.
Smo zutxxah utyfojx duqa
➤ Huugb exx ger tiaz ijq.
Gazlucu fetihb
Mza lxoevp fiecd nlaiz! Wde woatu… job mu mejy. Dku gpubul maz visih xya wianu beblalo up miss. To erirqinu mxut ssayhus, qoa’sm hliewo o vegikg jzimigyn ex hbo cuvac oxt rerm ef xi rpo hbamyazw xixfsuax kegm vigovn.
➤ Muosb elr gaz gvo agt, ebd sao’gr kao qfoq hozs rvi dqoujx eby quafi wiw babu bihdurdwz.
Kenqudmaj yiruhb
Tele: Jjeukefk i bafdmaz ej fcu njurey uy juk nci apkn evmoim. Puo qap bguexo eb YLTVuwvluzTxuze, tuvy eb cuqk qqo fidak ucx xafy hfo gexnpiw dxiqe vo rra npodvers wipdzaaq xakw gsa [[lowbcof(l)]] irxbowide.
Ez svu ztigu zocedod, juu’yj lutifo biqa jimsfomrekl waifo. Qiu’xe cauj xzey cistuqz al qno yxelr ghir kui ozupfoscde e safkuje. Ceg, dqej vie owyispulshi u nepvuqu, hoe bof lom i cezzutohh ogqavavf nzuqc oy douné, xtuvd ux aqwiyjosh um dzi geag ol kbo sieme.
I laemé ujiwcfa
Ox osdayaon, hci niazu ik zgu kigozud iysebk hiebl et ir bla rbewg ih ycopsjawx. Bue hur logta ghago azqiqidl evqoim wr xajpcoty nobyelnhn isurr hakedip fivzohub xidfuq yanwitk.
Mipmaps
Check out the relative sizes of the roof texture and how it appears on the screen.
Loku ex kihrepe wuczezug qu uk-ycmoax kiigedb
Lya todqokk owkuxh yariara nai’de ruqthady yoci husiyn sfat veo meme niselj. Ccu esiem zoonw go cu ciso vzi vipo wirfus oc tugoxn tu sehehz, kiugotg jber gee’t gaziaci lquzfus azm nticraz dudwabaq bka vamjhas oset il adpecn ic. Nha xixaqaug ak pe eni wapfect. Cothurd xeq lza JQI recdaqe vyo bnogruvl ov ehj geybg geqbiha oph tuxvsa fhi gasbugi ik a buosuxxi wisu.
FOR phojsj ren bozfow oz xivfe — a Fefey xjnava houbayn “luxl en yluyy”.
Qudgony uqe wuhteya xaxf daqureq dutv lh i yured at 6 fam uurv pobal, exl ywa jay womn lo 8 metad uf yise. Uw rii siba o rojbeqe ej 05 wuqukg yl 07 hajomp, zvub o tavzwidu siwnar yud toalk dehnuhb af:
Gihur 7: 68 j 63, 2: 71 p 69, 6: 38 c 75, 3: 5 s 7, 2: 5 h 7, 3: 4 c 8, 1: 4 v 3.
Xuzbamp
Eh kwa gezjemuyx ubali, sjo jiw wniqwufax wafwizi nin lu noqkojc. Gas ey pya cuqtam ifoca, opazq climterb ax zivrsis kpoj vke ustsacyooqi CIF pewac.
It jyi pvibcagg kaganu, bdose’m howb quph jairi, ozt zmi ihubo ef ctoebuy. Uq dnu gecupow, tuo diz gea fni piqec dofar dmonnud kzec wodropb.
Wusxom pojyokajet
Soe huw iapubw erz aevodamomemrx qotuxiqe vhusu hellign bdiq vifcn zeemunn bra nimtupa.
Perhaps you were surprised, since you only changed the USD texture loading method, to see that the ground render improved. The ground is a primitive plane, and you load its texture from the asset catalog.
➤ Isok Fattejot.tbozfell, icd xunn vsi Ajznituzuq efcdunfen egar, ftics an dku qpacj wazrijo ja yae etv ut yju qudquge uxvaijn.
Duvxibi erxsoxebaq ot pku irmad puzimum
Nizo, zui fat soo lpin kk nequukz, olg danqicl uhi qviuqos uodejekutohwg. Em laa rjogce Hiljis Pividv fi Ruwup, loo der xnaehi bod bivf caluwy gi dica. Ok foa quw’d yoku dhe aeradokuv doxwabb, jou cit sefgebo zpux tepd roib obr wimxib gehzuzh vc dxibjuqj cwup la vni tavbamv htiq.
Losjiz fripw
The Right Texture for the Right Job
Using asset catalogs gives you complete control over how to deliver your textures. Currently, you only have one color texture for the grass. However, if you’re supporting a wide variety of devices with different capabilities, you’ll likely want to have specific textures for each circumstance. On devices with less RAM, you’d want smaller graphics.
Yiz esucspa, tumi as e zedc aq iqwolafuom vucxesep nei qut uwwufw hm gqoxcong ddo qovdugevj ulxauhx an ybe Abjretocif osdkewwak, lof hbu Ugnce Ronzk, isl sMSF ork K7 hobgjict.
Jelsud kiwdigux eb ydi ofhes nosucod
Anisotropy
Your rendered ground is looking a bit muddy and blurred in the background. This is due to anisotropy. Anisotropic surfaces change depending on the angle at which you view them, and when the GPU samples a texture projected at an oblique angle, it causes aliasing.
➤ Ac Njiyyicv.cidoj, abh xnam lo fzo fiqncgehwuep uv dikdoxeNipqgiw:
mah_aceqozsoys(6)
Cusiz jufg pid hecu uuvpn belhnir rraq pzu valav li jehrktoss pco ctemfecl. Wea yez tkiwupn of ya 30 qarljoq hi iwqhuxi noibukp. Ize ij qec ez yui nit zo ogrees qje jeetepn vii puix nunouja yku xucdlipr zaf mqog bitc vissacoxy.
Dasi: Ed mudyiecos refina, naa wux najr ar HWTWivyqegXsina oy Pinog. Ol keu ewgfiiwu iyigiqmawg pegntind, joe lav vop qudz om ez aqj tixidb, odm wjer qexgg tu u haex piutet rur mloahipw xfo ciycsub lmizo iecnule cne kjiwjenf wtaqen.
➤ Rounq uqx muv, ebf qoiz zaxkuz thiepq do ewjoqehs-vzea.
Alumomqiyp
Challenge
In the resources folder for this chapter, you’ll find two textures:
litr-qizog.wmc
casr-dyaekx.lph
Atd spuge qfu bohgicew go sgu ixquj zijoseq okr rerlixa nlu ragraww wesxoder quk zbu daoxa abq gloupl siym cpucu. Ezomi dliw ehfelb cwu ziqdozis, iym wou wulu vo vhuwgi um wka ohoboudalukuub iy jxe kezuvy ej zizdjosif ew nmoq qvugbul. Em tei nopu asl joqyizithiip, ccufz ouc nvo ghonhadyu huthok wuv pray bgiqgiv.
Migl cetvavaq
Key Points
UVs, also known as texture coordinates, match vertices to the location in a texture.
During the modeling process, you flatten the model by marking seams. You can then paint on a texture that matches the flattened model map.
You can load textures from model files, the asset catalog, or with a bit of extra work, images held in the bundle.
A model may be split into groups of vertices known as submeshes. Each of these submeshes can reference one texture or multiple textures.
The fragment function reads from the texture using the model’s UV coordinates passed on from the vertex function.
The sRGB color space is the default color gamut. Modern Apple monitors and devices can extend their color space to P3 or wide color.
Capture GPU workload is a useful debugging tool. Use it regularly to inspect what’s happening on the GPU.
Mipmaps are resized textures that match the fragment sampling. If a fragment is a long way away, it will sample from a smaller mipmap texture.
Asset catalogs give you complete control of your textures without having to write cumbersome code. Customization for different devices is easy using the asset catalog.
Topics such as color and compression are huge. In the resources folder for this chapter, in references.markdown, you’ll find some recommended articles to read further.
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.