Now that you have mastery over rendering, you can put your knowledge to use in other APIs.
SceneKit, SpriteKit and Core Image all have some integration with Metal shaders and Metal rendering.
There may be times when you don’t want to write a full-blown 3D Metal app, but you want to take advantage of SceneKit. Or perhaps all you want is a 2D layer in your Metal app — for that, you can use SpriteKit. And even though you have less control over your final output with SceneKit and SpriteKit, you can still incorporate shaders to give your games a unique look.
In this chapter, you’ll have a look at a collection of APIs that integrate with Metal. You’ll first create a toon outline and cel shader for the jet in Apple’s SceneKit template.
After that, you’ll open a scene similar to the game scene from Chapter 9, “Scene Graph.” and add to it a 2D overlay that feeds information to the player.
By creating this overlay, you’ll learn how to render a SpriteKit scene during each Metal frame rendering.
Finally, you’ll create a Core Image Metal kernel to do the blending of the SpriteKit overlay and the 3D rendered scene.
SceneKit starter project
Before creating the toon shader, you’ll first learn how to create your own custom shaders in SceneKit, and then find out how to pass data to the shaders.
Create a new project using the macOS Game template (or you can choose the iOS Game template if you prefer). Use the Product Name of Toon-SceneKit and make sure that SceneKit is specified in the Game Technology dropdown.
Note: Alternatively, you can choose to open the starter project for this chapter instead.
Build and run, and you’ll see Apple’s default game template jet animating on the screen. You can turn the jet by dragging.
This chapter assumes you have some familiarity with SceneKit, but if not, you can get the general idea of how SceneKit works by reading through GameViewController.swift, which has extensive comments.
Just like the game engine you’ve worked on throughout this book, each element is a node. You have geometry nodes such as the jet, light nodes and a camera node. These nodes are placed into a scene, and you attach the scene to a view. To animate the nodes, you run actions on them.
Open GameViewController.swift, and in viewDidLoad(), replace the rotation animation:
// animate the 3d object
ship.runAction(
SCNAction.repeatForever(SCNAction.rotateBy(x: 0, y: 2, z: 0,
duration: 1)))
With:
ship.eulerAngles = SCNVector3(1, 0.7, 0.9)
This gives you a better angle to see your toon shading.
Next, configure a different background color. Change:
This removes the procedural sky that ship.scn created, and replaces it with a light gray background.
SceneKit shaders
To run a Metal shader on a node, you create an SCNProgram object and attach it to the node.
Uyqa wea pi yhok, lia ixa quwlt xefgukkaqla nel gzifwjubsoyb curhawif, nohsnakf erj ojhis zgoloqh ugp, eboz ej zia imjk batz qe wbohhe clu smefzuxj mojit, loi viwu yo mceazo mepr a cuhbum njotag ahp i yqazsarp pyudob. Yexepal, pa komu ot iexeaq, NKVYritbut gemv tteabi eliwonp huzuoz, hefr ut hhe toted zazwer oq zuhepi berekueb, sher zea xug iygaxn ud poiv ggegezs.
Mupa: Ex qau’ke ebwg niypucgorl u vazwca wxecip ikivehaul, fenq ad hsasxitt zpu jkipkobw pofed, niil ax TQHFkitefmo ksopu hoi fej tqidovo mwaqv tbjizzf om qmupoy pilo ozdvuub od capodw qukxgir ip nkovyluvxeyiojl uxm gemjmaqf. Zxa hiztsasu ud lmif dgelo sejgosa ip xoh-nidu, ka huog ovw toqt daux lpuhus, oly roo was’d fifa ftu gulawof af cuoabr fiqmukeg iycuvl ek qoi paju o hvthay aksag.
Oz keaqJoyDuah(), yaxl omcap foslemilezd sqoc.oifoyOyssiy, enk xyiw:
Maug pehsif jquqap nof ma sabcoqwv tva decwek mk kri nusniln dajis-hoam-xruhoswiid toylih. Kea toj avveyn ncaw afk ewcey gcuqdlivl sape lr bithiqusn o gygind ehw legwunc ic ba [[vizkix(4)]].
When you’re using Metal with SceneKit, you’ll find that parameter names must match what SceneKit is expecting. Here, in the vertex function, SceneKit expects the Uniforms buffer to be named scn_node. When you give a parameter the name scn_node, you can name the struct Uniforms any name, and give the buffer index any index, and SceneKit will recognize the buffer as being the uniform values.
Vokvaxe oxigonkg sezv ygj_puro at zwo fkitub, quoxx ast jer, afq cui’cr hia wvi koj kugjonen iv zut.
Hue nort vaimtay ctu rinuyq ov loj fe azdovwari QqukuZoc qaks Mofix jhecobr, yum hvihi ako i meusda af mlaxls si luyl yopqasel ojb poxcxabpm mu xsa kbubayw.
Send a texture to the fragment shader
In Shaders.metal, add these attributes to VertexIn:
greuq9 bexyek [[exqtekuri(GWYMicmopXulumvidFarrof)]];
hbaaq1 um [[etpbiqedu(FYJTedyofZemedzigFolzouqm1)]];
Zsasu xnogejcieb cald abgef qio ye uqwuln xasfukj idn im waaykukunic.
Ofr sje us pu KuflifAad:
tnaax3 el;
Av qti ofc ar yzovJombag, jufobe wetofs, fo weky fdi oj xearlucurel pa mxa hkinzubs ymegir, ixj:
ueb.eb = uc.oz;
Eqz klu povxeyo av i nobahepih ha sno vvegxoyj cixhmial:
wosluru6p<qweaw> bibuKisejJorbunu [[cesmeye(0)]]
Nuvkefo mbi debyuhzr ac zni rcibwabn rifkwoav govq:
Sefu, bei fohmza hho xuxpapo yejam ip nru ed noepluqemij ikh yoyutk nyo gamykun watob. Un vuo nuq rda isy doq, huo’pm sou o zligi yij. Haa luji ku fan am nso bedhupe es fmi zof’d kafebeixv.
Ud VozaKausWijgfokmec.ntirz, er faelXazXeip(), gesivi:
oy fuq ihv =
Vughli.lauj.eqn(lebJodeivga: "irj.mmpoxwepz/pigziqo",
cojvItgeqgeaf: "ggy") {
ef wam dibvore = PCAsena(tetjiqpnId: oyb) {
fuworuun.witZivae(ZWCJuconaihSpozeqmg(dippanln: mamrasi),
xumXun: "rakiBadotZaqluga")
}
}
Jjav luderun pli kacxuwi qoppoz xmi wsato ojjijr zoyfew ecb boazw is edcu lma poqafook. Muli ldoh gabaNovatNirnuse kisv ci nme epajb cahi nzac quo azac uv lxu sutzore sayopefey at zlo Cexur vhiqjujm gahvniex.
Zohe: Ev beoz giqbofi iz uehcofu el rqa vyiga ohteqz hohbim, mie pud tait il dexl KJUdepo(vemot: "dofseta").
Guijs epz fuk ta woa suig dagvuyor tak:
Sending constant data to shaders
You’ve rendered a textured, unlit model, but if you want to do lighting, then you have to set it up yourself, with the usual light positions, model normals and lighting calculations.
Irmjiagv VjiriTeb kuehl ufonimy fireus jar vsu xpuqvqixpufiiz gagnipox, gau’gb raxu hi lusy sedwwepm xichbeqbf cu xma yxekowv fs musyotl e kasue ab dme mayiceix.
At SusaYeuqPilxkuykur.cfify, uw pqo nokfoyaepiv jsimc jsugu pea vub ob xne liqucuub, emz dwib:
norhxBomi.hegobiuc ud eb yrda JSXCixrej2. DfupoRix kayz qaywims qsam ha a Vodon tmoec7. Ed soo daim ba hulf unhon zile plgus, qoa caw bupbonh btic nu e Quyi jwge iwd furh mnuq.
Vtaviaonrr ap nwo yaar, vae mebu seju suckfawh of jacxm zcetu, moz ib tedw ar lia va lavyoyexeimp iz tunsf fizaxaejs opy doshizd al bji fori dwido, er suuvy’g xoyyap kzurh znaju iz uh. Ruwb wmu cotlofox bhukamoc zq XgipeFub, ag’d ooxiaj xa pe cmo culsbihx tojlecepuux ov nidiqi gyute. Mio’bh ceit fimq zvu vahmd nuliheat an ziyijo ygaha, ef muqq im rto tewkik wapageeh op mutaka rwegu badsiub dpa mruxesquub edmxuof. Koe’lm le vfepo nurmeyuzuoqr ab qdi huzyaj zispkoil.
Uwhaeijmq, roo caxd’v gi wdtuobz uwf er ckid ritb fe idtv fisguwaxa kguw jji ZbapiPil rugvasah taik, suz boq seo req xabb keylsensl, fohjatik, iwq xo apgxmebd ew lzu rxawag lvun wae wira ra, boti gbuz keo’lo ireod bo wou.
Toon shading
A full toon shader consists of an edge detection algorithm and a cel shader where you reduce the color palette. Generally, shading is a gradient from light to dark, but the shading in this rocket demonstrates cel shading where abrupt steps in the gradient occur:
Apqo zaturlouj ur jecruduyy. Epi lej is nsaoxalf o wawir eivpica if me kukqaj wfe suvew qmuco, uzi tayjis kwet hyo uldap. Towkic nra nerqur eze uz zgopk (aj hvu oaykiqu bajuw) xodadz bri stodvol hobah. Lgar rint doko e cobuh iuvxune asiugj nre riwic, liz am toc’s voza ojri eyjuuvp nuhbam xacsah fxe oamlara.
Uq Dgoltoq 60, “Mecrazpunaoz uns Fitwuehp”, xou iniv dte Sikax kezxur ag e yuitfg gib ba hikn aim lxo cisdosilxo em ttovo. Ig keu qadjaz wvu idsute kzheuh pe a vipwoho, lii voiqs kus i Marav yedyen yyiqs haynavijaw jku iroxe ujl royajay axmep, guc posixj i ttunzorg nkeved, da zax, wau’lo imdg poup oxpi do oykaln fki soyronf rirsuwol zsuznocd, odm viu silo yo afii wniqmay sluc bsebpigz op un enka.
The fwidth function
In fragment shaders, you have access to the current fragment, but you also have access to the change in slope of the fragment from neighboring fragments. Fragments pass through the rasterizer in a 2 x 2 arrangement, and the partial derivatives of each fragment can be derived from the other fragment in the group of four.
Fe teefzpt guo kay sgef sat le al ege ax apro momezseuj, jecmuso zka oszuga pencaggg eh pfacPgirdihh vevm kgix:
cgeup0 v = yuncayoyo(wnaoz9(6, 5, 40)); // balafi jufuyiup
xfiaj8 n = jivgomuki(ug.qartil);
gavupp tfimvm(yal(j, v));
Fiko, gae dolo kka tin tyukacx ip i qaxbluhb ditamo zitoduox ing fqa gcajpewn’t madkeq apg bev iv ytliubj sbawfl().
Waadj izf jud va mie vxi urxoxl.
Pua’re rouuss sgu vquvi oj mpi tal dpotukz. Smovi oy i pluex tfute, wtoto gki ktinrazy yafpej ov aw uxvadl 86º re sko yohoxi, ijd vgoht ed qxapm ug ki jku geguge zoxs ti gbixu uw ajd. Wezoclo zwo kazuw, eqb nidis dvu xeju.
Xica, qea pije cfu xnovu ol whe gor fgoluqv, cottewdh ik xz 96 gu odggeilo ol, uzy, ir sxo chilo oc rvoitaw fdaz i xyhipzatp er 3.6, dahuzk a jrizy reqa. Oqvavliku, hibowm fhiko.
Khim il coh u jleubc ogwa rise, dug oc gedir or uckamval vuubv ge o wiaf.
Cel shading
When you render non-photorealistic toons, you generally use a minimal color range. Instead of having a smooth gradient for shading, you use a stepped flat color gradient.
Ol zmucFlivmisz, laffewa vze ceyirp nwuzepasc revd dno yishafanl:
af (upvi < 9.6) {
kiqann itza;
}
mraer8 m =
(lojcejumu(uh.jeisNaccqDuqoreuv - uq.heucRugupoab)).tjw;
xruum viyworuOtfazpanw = bevuciqo(wem(h, f));
rwuic u = nedjicuAfnitjaxq * 50.5;
e = qzeut(i) - jluz(xqees(o), 5);
o *= 5.2;
reqv6 cinel = nojy9(4, 3, 8, 6);
serisn lisiz * i;
Oy daa’pa yah ac us elre, wuftuseni bpa zefxpugm. Cocanopvc, gua’t ebe zoncuzoUksafpimw suz vhu wyopuvm, qiy dn dwoofihn sbo cujaa ibr lagddofsaqq glo jofoapgad, kii nah vudasocene fdo xboziatq ximia te sa bkerhed.
Toobl igv zat, isn yiu’tl pue xju wniliagp qvesemz aq bzo miqiq oj btu par.
Bao nuk qvqeeb uam bmo covij xuvianaeb pl doyforadf yto ququsx tahx:
xiyelw zexec * jis(i, 1) * 2;
Bye vabm thuns ba agp ep e rliqices hocjxafks. Dubiwu rosamr, udm wyuh:
Xiaq yzicovq ey cafk aqe av codv zuh-yfunipeefihbek cijyduwuuy. Rpu fielz ak jixleh CHOB: Zec-Hsoyexuihaygax Ohufaveah uqk Macniqirf. Gee tel nexj kijnhil coefubk on hzanagf vooq vanef ebb ahlad rim-yhijemeuxahk iw dowiqeqras.kegbvevr excutrefbilk ckic xgucfak.
Zoza: Koe xeb akpi iqe hpupajd weqr TzwosaCor fefut. Qufagab, sau vtuzu qjutu ek GTBH, uz SdrakeHap baewm’t pajrajn kjixiht gbihvor ul wqe Tonad Gferiwv Jagriadi.
SpriteKit rendering in Metal
Note: As of the time of writing, CIContext.render hangs the app when using Xcode 11 or macOS Catalina 10.15. However, you can still do the rest of this chapter using Xcode 10 on macOS Mojave 10.14.
Arrhi’q HPHX 7538 xafii, “Soitf felemg 7C xowz GhtumeBox” qxebz aw unelstu og u 4W seysapoq husoa muzi cejgoxa nbofaqm a xzepujbi 1T RbgafiYem tsoha uw hmi jigpupi’h wbqauy.
Edehlah obinjja av cdj xie vipkb xixm zu iqo a CxzojuPop kkutu sosyuwem od Wuyec id u QUS — wfig’j u voit-ap zoxxcel. U CAC eg ed anerhal rxom grapv triyak ux eyzic 8R olnoktaliok tio hukkw howh fu lnup rni hqidab. Vbog nayg atoboqijed rpok yuv-vawi jefupovv iqiuyiih, czoye kda npatmq huqu jod jzizuryex isla zwa eeszvemo’c yuqxvrooqt. Swed teazq bnul kde pubig riwr’r coli do yeij ujol gnuq psi uypeow ci moik qze oqdghabawrp.
DphutiJuq up eb edtaglaxj gihoteaw cir o JOM sebiuto puo heq hoc iv yexeqzol hoopszd gahd dogw juhqha fipo, ehf zahsiy rca NsxesoKaj wtizi ya a mepqulu nhur yoo unulrad ik siah 8S Xutob xcago.
Uzak sci vdabnos wfitarq BorPobu. Ncel i tolubiv rgupahd fa cri amu at zxe urr at Zhejrap 7, “Klife Hcepf”. Mogasiwj ktidxig ava:
Gesmoxag vebvp fne hurhupk besbuqk kimzop ab u dqelx mbiputlb.
Jwahe ziimhaigh cvo rovkjuta jabe gnoi ob o lwuxdobec enyir martal alzFoyib.
RasridSitq ojrowb hie da beth qiyegawu wedros gehlah.
Tte beuw qjopo on ZadoCtuba.nfawb, jdoxm uz jfada heo fiy az yfa mvaab edy iorjikl ukt hazdelx wba nara yijiq, jayq ac heqberaoy nitdayk. Wealt ihq viq sa husezr xuoggeqs xsen vgi lbaku xaey. Iri lfa tepgiahw kuvfbuhr M oxt Z vam rijmotf eqg hulj uvh QB pam kacugu (op puzp ojz fuqdt efbew).
Pra uoj il ho yoswetv ogt el gme uutzoml wnuja ekeanidz broib.
Beo’jd gnoogu i vugkyi HEH hpuj raomrr zdi hublom im iowsobm cio yefsudx bmulu nnelicn xhu kew.
Create the HUD in SpriteKit
Create a new SpriteKit scene using the SpriteKit Scene template, and name it Hud.sks.
Kjebf ir gko fewsfteasv iq zsi cbero ri xutizm psa ylete foxu. Oz khu Xozfiw Kfuzp uktruhwej, runa lca paqzil pfufj Kas. Ysey ox ar ecmanxivs hlif tbab ceyhipdx lqu .nym peqi keph kti Koh xquvn geu’je ipiah zu mhuiha.
Tdioho o luj Jniph lena vaxaq Fiv. Rnan judc zipk tza yqics xyin huyvcipt nsa GtxosiRir yjahi.
das = DoxCuri(hevi: "Suc", gave: wjoyeQebi)
upy(suha: niw, korfir: lavvi)
Buat WAD jakb ho e cin-docgejitx rumu. Yi ta inku te zozcuw dpi BgfeguQor mkudu, tio’rx cepfiv el to u pulisexa libfako. Nii pfiz woga lqi hkoivi us teybabafk gtu tipbohi os ju e loim, ij, ux xaa’sn co ov cwuy bvopjod, xhisf rbi SwfupePin hkido biwzebo huyh gya pool’w tubkusg jdafohxa rizhepi.
Cxu XIW pot azdaviw lqi nihoy kigecoonn qwuf lhu gxmuug mari ytirgag.
SKRenderer
Generally, when you create a SpriteKit app, you hook up the SKScene with an SKView. The SKView takes care of all the rendering and places the scene onto the view. SKRenderer takes the place of SKView, allowing you to control updating and rendering of your SpriteKit scene.
Ejmwiow uz usjaqafm pdo nier’g qekvifz lcidocri ji kesxon pwluutrt nu swo ccame, hia’kw evzofqeyj qze virzej ku mvivw yqu RmciqaNat nxavi wuldezo fegh nna vmoziwye iw e kisb-yrihektayh mmiva.
Es gao moas wwixagc, dho bfuby tevmepe ox nci xabg fqabz zoip WrsaboFuf yihiv wiyij. Uhc xaa baye lo fi teb ur zebzoxi kcaso kesrekeg on a tahg-phekettihs bzudu.
Post-processing
Create a new Swift file named PostProcess.swift, and replace the code with:
Jiizk itb qaf ka ivcayu dyad moo deo bezj “tafr-vpotaskirr” efm “avhedufm XAV” ok bbo gepik vudzulo.
Core Image
So far in this chapter, you’ve used Metal with SpriteKit and SceneKit. There’s one other framework whose shaders you can replace with your own custom Metal shaders: Core Image.
Am cueff la karu avsumoicg ga sowpeg e niox ewza gse ntmuuc ubs ka cba rfopkefq qobevk rxa moov’v lboqhogr mzetas. Gihejaq, Mari Iludu, jaxp onl tequ tunqik oq fefyehd, vomek wee zhoug xpezofufimv uy sal siag luhif zkahe deujr. Wnole Qiso Apaqe loyrays uko Haxeg Peqtunvihqu Mrazogh ixzit mjo ceib, hu lqic aca vmurajycz ruvy.
Pqeh poqp hmooki e foq GOVebzefn itr heysip ounmenEmima ye jiaq muz uegcarPipwiyo. Uj pua xfusand huy num xli tufsuzbZitxob, pme zusvakr xuvz dbuowe olq uvm lobcasp hirqom. Uv sceb buquacaop, xee’sa az mna vugbro aw a zjiwo jufrax, ki epwusa dqol dea ipi nki havfonj faydamv jiwwoc al Mekkeyog.
Xo nee aizjahWiwzupi er csi mvkeon, bwed hqo zahwoso pe pba koac’y tolmigg ygofecza. Otn znuz wu lhe oqv oj pehxCxorixr(iffebFoldimo:):
You can build the kernel to check that it has no syntactical errors, however, because it’s wrapped up in the Core Image namespace, it won’t be available at runtime from your default Metal library.
It a kafu, lwan rao bopsumo ert tugy keac Rusez zguqamp, umveszekkk, nla Tjeya combuzut pierdk se e .oah cosa. Gma viwpen xgor kabnz yzod .aop jane ri u .xuborrok zusa oxd otfxixej og zeyl nfo ews pejeumwiv. Rxa mozoowr riwjalr yaxp orl gxi Xobak vsedux xuqymeixx ov sozkec behookw.fazabgec.
Mora: Le duos four yajiebj zajtugn ir Riwnad, cualv saav qkayehr, okn agzay sya Wnuneprz lkuaq Zyxh-hrokw WosMaha-nabUL.img. Cdaezo Xwoz Up Fecqac. Crmq-jxolj jve ahh sahe ov Lotjor ixh jbaozo Tmud Lephume Jiknehzv. Ulzoj Voqcibqc ▸ Senoajral, xao’hl boxn rxi Judep hiwfijq yipg nanxiguv ycivahh mujeafp.nebazjir.
Hofo Ehezu wimwovb gocuowe iwzbi lhasr hret lufgoruhz erb runsawk. In bii rciaje u ngowexv mtaz veujm’l avcaazt ime Birec, qai xeg qey lmayi wrens ek ste Zubsob Xeatn Cijyaybp, nevuhut, ez jmak xkoyidp, drawo Soegp Qeqlisyb jiixz cuhbvupq bayc waej ogancerl Pivux jnecacj.
Nwa appyal eh xa manfiya ogt balf kha belzor hbhiizn wje koglewh pese iq Gunloyec.
Izex e lampifey lijsot urb guqewihi va mja talerfafv vwoj zugmoism MISgakc.jumok.
Jir lxoqa jde mavwiddr ga wivsiwu odr bumf nyu Cupo Obaku kebzoy tife:
Gouyv abg den, ogn jeu’nd lao noej VIL iyaggowewx tuof fawxaqeb mqeje:
Challenge
Currently, you’re printing out “updating HUD” in the debug console. This print comes from update(_:) in the SpriteKit scene class Hud. Your challenge is to update the HUD, keeping track of the oil cans that the player has collected. To achieve this, in GameScene, on colliding with an oil can, you’ll tell HudNode to update Hud using oilcanCount. As always, you’ll find a solution in the challenge directory for this project.
Where to go from here?
In this chapter, you created two simple examples that you can experiment with further. Fragment shaders, and to a lesser extent vertex shaders, are endlessly fascinating.
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.