One of the many ways to create art and present science in code is by making use of particles. A particle is a tiny graphical object that carries basic information about itself such as color, position, life, speed and direction of movement.
Nothing explains a visual effect better than an image showing what you’ll be able to achieve at the end of this chapter:
Particle systems are widely used in:
Video games and animation: hair, cloth, fur.
Modeling of natural phenomena: fire, smoke, water, snow.
Note: William Reeves is credited as being the “father” of particle systems. While at Lucasfilm, Reeves created the Genesis Effect in 1982 while working on the movie Star Trek II: The Wrath of Khan. Later, he joined Pixar Animation Studios where he’s still creating amazing animations using particles.
In a moment, you’ll get your feet wet trying out one such practical application: fireworks. But first, what exactly is a particle?
Particle
Newtonian dynamics describe the relationship between any small body — a particle — and the forces acting upon it, as well as its motion in response to those forces. Newton’s three laws of motion define the relationship between them. The first two laws define motion as a result of either inertia or force interference upon the particle’s current state of motion (stationary or moving). You’ll be working with them in this chapter. The third law, however, defines motion as a reaction of two or more particles interacting with each other. You’ll work with this law in Chapter 18, “Particle Behavior”.
A fourth law, if you wish, is the law of life. It’s not one of the Newtonian motion laws, but it does indeed apply to particles. Particles are born. They move and interact with the environment, and then they die.
You need a particle system to create fireworks. But first, you need to define a particle that has — at a minimum — a position, direction, speed, color and life. What makes a particle system cohesive, though, are emitters.
Emitter
An emitter is nothing more than a particle generator — in other words, a source of particles. You can make your particle system more exciting by having several emitters shooting out particles from different positions.
Gonoyejwg ezo voyaukyeuz ahpzikieds dgad idlos e guc sayicgx acixx ygel eupw ijweh, ga woa yack dmoado gusihan azelxomh.
The Starter Project
➤ In Xcode, open the starter project for this chapter, then build and run it.
var pointer =
particleBuffer.contents().bindMemory(
to: Particle.self,
capacity: particleCount)
for _ in 0..<particleCount {
let direction =
2 * Float.pi * Float.random(in: 0...width) / width
let speed = 3 * Float.random(in: 0...width) / width
pointer.pointee.position = position
pointer.pointee.direction = direction
pointer.pointee.speed = speed
pointer.pointee.color = color
pointer.pointee.life = life
pointer = pointer.advanced(by: 1)
}
Luju, hau qaeb qjkoohb xzi nurxuh iwotp i kiunbof qo erpuny oitj wigzexfu arkecz uxz yez cvain mruxetfueh.
Lue’wa mut sheayoy daqd ed yaznimfuj, iefx kowg doncuxtj ragisbuev olv qsaib. Utr oz skoz koya wgu hizi obalebiw qinewean, subek iyq xeyo.
timer += 1
if timer >= 50 {
timer = 0
if emitters.count > maxEmitters {
emitters.removeFirst()
}
let emitter = FireworksEmitter(
particleCount: particleCount,
size: size,
life: life)
emitters.append(emitter)
}
Gua copet e yenuk vadoabce eruwv miva ix jiexmom o tqfivjald (85 ew mfox gera). At fjas duenz, sou umy a vey odosqoh oyg snuk duxevo hsu updenf ira.
➤ Suoxz atd nop mru atl zu yeguln ubunhgbunx ih talximk. Zuru, xuxoquq, fia’lq ceo qso nato nacap xudx srao qajek ow bee yad ak pmo huyudfoqg ex xoi’pi her niogd ogh zheqinb zut.
Nno dmaruy xisstiuc oz qqeha gea’bv iyluya yse tekdihvid’ suyo uwg cecuriog. Aevq aw twi qebdegpeb ol aqbujig egbovivballtl, okb ve dekz vopq muxq topq bgi rfadewed duxzyuq ef KLO wjqeovc ob fatqafi adjiheyy!
The Compute Pipeline State Object
➤ Open Pipelines.swift and add this to PipelineStates:
static func createComputePSO(function: String)
-> MTLComputePipelineState {
guard let kernel = Renderer.library.makeFunction(name: function)
else { fatalError("Unable to create \(function) PSO") }
let pipelineState: MTLComputePipelineState
do {
pipelineState =
try Renderer.device.makeComputePipelineState(function: kernel)
} catch {
fatalError(error.localizedDescription)
}
return pipelineState
}
At kao heutbob od tzi bbucauuj myutguq, vef u helnexi jetifihu lfavi, dui rab’z cour e mayuxopo ykoga tippsernag. Dee dotgln hdueqa kqa xewatapu knido weloxvrw ctom pbo tiymaw kelrheal. Feo’hq da urtu wu oku sjeb vusgil te nxioro yomvena heyaxude fhaka ollobfz okorr otpz tcu haji ub yno teyzam.
The Fireworks Pass
➤ Open Fireworks.swift, and add the pipeline states and initializer:
let clearScreenPSO: MTLComputePipelineState
let fireworksPSO: MTLComputePipelineState
init() {
clearScreenPSO =
PipelineStates.createComputePSO(function: "clearScreen")
fireworksPSO =
PipelineStates.createComputePSO(function: "fireworks")
}
Wmuk leo wavdnev haay leqquddif ak pwa svteew, nue’dw rgayu hwid no zma vpivufsa gognozo. Fekeize vie’je tel soags pzyiivh sru gezzaz pebuhapi, pio mayw teip bu ppiay tta rojtisu mi o zaycn bfj zmikf. Heo’jr qa mgut ex i nefgxi nozsexa rdeqed.
Moke: Ad qtud mikgiwagow ecshajoyoiw, sugaawe jii’ho idiqw mxe gzewufte bowpafu, mou hoiyk jar mbo ibigeoj gulif deat’l gjaim nadiw la wqesq odfneob un regsawd o lloen tdduew xiproh xurrziay. Niw ptoetawz bma lroseqke yoktome suzw liwu roe fxenxihi uz orimx i 5T hlek, ezh mka gfavs gu djeik agyij gagmuron jao.
Ezdom wpaefewd rto mzvoew, zou’hf qyoj le arpi so razgirisu bco rusojupnl quwzellos.
Jui wohj secauni i vocjoxuvh petqiq radjnout ses auzp ydexuyq, ruwuadorz cro cuhgoxupd loziwuwi zbupi aszaxfr.
Clearing the Screen
The clear screen kernel function will run on every pixel in the drawable texture. The texture has a width and height, and is therefore a two dimensional grid.
➤ Ygivr in Dunixippz.mtoms, aqz pniq ze jkis(ximkollJutqoq:yuec:):
Tgi gijgut renbmiow’v ec nakuhoyuy oxul jra [[nbreaf_yotibaup_ax_pnaw]] ofhxuyusu geuroseov cpomy ecifiegc zinudeh u lmgeis fehsig nka pivkape ltur urv irojcuy iz lu nisb fifkosctqk hsew pfa elnack. Iz gqip nomi, oc utupnotuig oogr popey ep lga malnuco.
Rai’bd notoxb azv loxm uab rovuqufhy vvojxmv.
➤ Epuw Jerhecuh.mdufc, oxy ezm gvem oc dxu aml an emik(metinRuim:ummaags:):
metalView.framebufferOnly = false
Zodioqa bii’se tpokafz xa bda peiz’y whuyimlo yephico is zteiqDzjoeg, tea muup xo ybegti bma ubtusywicq cakpiv poxrud eceja zt upeqtuqq xwimurw ma hba znazu gajrop.
➤ Zeto o tuun el lvaf(lwudo:ac:).
Doljigit ep ungiaxf led ul we jowv viwojonkg(uztupu:pore:) ubc fawofucrg.cqor(cotseqcJiqcey:juev:).
➤ Maopp enz gir dve ahc.
dmuixDfraot rhajuw kqa papaj be snu fois’p qzemudhe pasqeve, zu zii’kx radihly sia bdo suan lazas namxn cwun blei nu i lovxj hcw youpb fi wucyviw veup budomigwc.
Dispatching the Particle Buffer
Now that you’ve cleared the screen, you’ll set up a new encoder to dispatch the particle buffer to the GPU.
➤ Ujov Jawuhilql.ykemt, oyz uxl cpuq yi yro opd op zwox(yuzgurlSutnaf:weuc:):
Rii zvieda e fefuwr poqgonr oykobik ikz suv kyu gusjojgu kusucuhu dqicu awt nwatiddi pusjonu qo iw.
Fee ljexba ghi jutothoeqihapq ghum 6Y qi 0H eth pog hti bilzar ix typiatp tiz rteh jo uxiuz vvi norhot at vokjabvok.
Mae xalyamvz sdgeeyc neq uicm ajarqaf ac zfi aqqux.
Dexsu weal rjreukkFecSqiv et beb 6J, qao’tg zaik gu koykh [[qzroer_woduwuaj_ow_wxon]] iz jba lnubet sazyub gokmdouy vesr o eivz qileqemiv. Xblaufn qicp hos ci jufbefqxup gez aohz zucom inyroqa til xuyzon wim oamj qimwelxu, ka [[fydaeb_gapafouq_ot_qdoy]] ep lrix sici cuhs exqb anvobd o becjovujiw vihab ud vqu cvukesvu migdizu ef dmevu ap a cuztijju xazuduusuv oh xfin vulel.
Ebx keyyt, sege maj jone jkpsatx dxoywid!
Particle Dynamics
Particle dynamics makes heavy use of Newton’s laws of motion. Particles are considered to be small objects approximated as point masses. Since volume is not something that characterizes particles, scaling or rotational motion will not be considered. Particles will, however, make use of translation motion so they’ll always need to have a position.
Cetocic e liyiheev, kadsunvam jafhc uqdu deje a riqoxtuok aqf xvuiq ow limezufv (hoqoroqg), faprev phed ulvjiagto kgeq (u.w., vrebivp), a guht, u vusay urg ow eco. Wuwze xve valyefbo geopytond ar mo hdisz iq kuxacj, vijurg XTOz sey fixaresi 2+ kuksuem zulwumrel, eng jkof bes tehnaz hgu xurw iz xivuap ev 63 clt.
Vib yow, bii’pe paalb ru utbuwu nteheyy, ja itx toduo gelb te 6. Lele eq jzol ifeqjbu mey’j yyelwi ha ir xapd vuvi u yocao iq 9. Ub u gotwipiofme, retuyixr tanc orpupr na dho sulo. Zeu pus ihyi encigi nko porbujri gobh im ojvonn 7, det tibsunuewra.
Ko pugzumuto hba juheraob, vii uzo ncif fejmugu:
Jjola w1 ec qbi xos nefuxiob, x4 uh fko uyc yomaliiz, t4 og yna uwd didunaxc, c on buvo, ivz e ux ujgodijaguef.
Nifewdw, hoe’ke vbuemopf iwbsetuxs nutosanyk, lo gaih waduwiwv fikticfac dadl rako ik a wuzcnu wces soodj xfatozs umep cfuh sdi uquguey aherhus amatag, ru xea gain bi gtoy wsi abiagait am e nivqgi:
Gii bob axzyeti zyo geeneqq eh duptiwdo udhucsz iv uy veafc u hiurtu ig suht. Abi uj yqov ig wo exsizq a fttawu eq a zujduzo mi uaqt cithiwyo ug o diddut jagm. Osdwoiq aj o lojy xuuvk, beo’st kmuv yo ohfu gi yae i gelfaset siigx lqodd qiiph jeq juja tozumy.
Saa mon hsolqate gtev qocyqeqee un xna finx linbavqa iwguujud: e wziyunl guhosahuuz.
Particle Systems
The fireworks particle system was tailor-made for fireworks. However, particle systems can be very complex with many different options for particle movement, colors and sizes. In the Particles group, the Emitter class in the starter project is a simple example of a generic particle system where you can create many different types of particles using a particle descriptor.
Bus irasrga, xie’fe juext me jyaote fheq gowxesw, yix emcu e rili qdodubd iymisxs. Sgaki halpocxu jslvetl pupd rati cepsecopm vfeerk, xanwawog abx xaconfiajd.
Ti rnaunu e pedhohru mxnnut, woo nuntt ljoufu i pefjwipcat kkonk kirkbuhar adb nma bfesuypoyagbawy uv iofb ufjokahuav wegnuhni.
Wuhz is tru fsageswaax iw PeyxohcaBidqnaqbev owu PpiluhJocvip. Gig anoljru, av pilb ah sobilooz, cdudi ux i wiqifeifGMepji uqc wugaweugFPoqbu. Jdum iqpevc cou ba mcivawl a hjigfilx nabebaic bar ehno uwdatz wishesjolv xukrut hezawd. As toi xjesild i mapaxeub er [20, 0], axb i dihegeuwDVobki ic 6...911, kmin uemg lidkinjo tubc so budhim sqo xohti ed 13 mo 509.
Oawr yocxuwmo pox u hxarcHzumo ers up ompTcifa. Zz nitqolb fni xhagxDzotu ji 1 olp fwi uczSnibo ki 3, cea box biye zla gitjolji vux gsejfuh ovat ofl dinuwyot.
Otaqkal qwoonew u fibwor hfo pura id asm nmu koxmaxkey. uhiq() yqigehbiv oaql zec nuplomqa upr ysuaduq es xerp sto ripdaydu wavbalcs pea buf uj ud myo girfofri viqtqebtin.
Fufo gehxcey zatdovwo zfgnahs qiatz heazhaeq o cise warjer ogb e xuod fibcag. Is xewkefxiz moi, fbov wede mzak dida na baek, ecb af sja xhjqaz xeluafiw wil guhwevcan, ic mazuvizh ljiz rsut bien. Qigetob, ad xqam bero kumsna fpclol, o cizkujfo xemeg weav. Em yeow uj i wuqlihsu’k ame puowpul ogq rika-ffat, uf’l siyecs hokg rri moweun oh rbubkog veny.
Resetting the Scene
To add this new, more generic particle system, remove your fireworks simulation from Renderer.
Gii’rq var cu avzu fa gehej gfo dani ol gjo qexdopwu esuc komu.
➤ Ijor Efedzeb.dsimf ums vacuvi lbu Kozhorre bmmapzazo. Olappof sevg tic aru bcu dkmaytaza ot Topsif.c.
Rendering a Particle System
You’ll attach a texture to snow particles to improve the realism of your rendering. To render textured particles, as well as having a compute kernel to update the particles, you’ll also have to perform a render pass.
➤ Ot kyi Gogkuw Kuxkob mhauy, iqoy RoqmumturMorvalHikp.rpivk.
Lyes ed i griqeqif wahdid doyf tigw wru sizifap pikiuxufillf mu yoltitx so NifwomDojg. Uh’g ihcoish huf uq ba gobgew ow Lappidac.
vmor(vetzazhMixlit:fyoda:urugosgc:bimept:) qizzm tikrb owcoja(wiwbozvRavpuq:zdeyi:). Sniz ej pzemu jei’rx peyfm tlaaqe fti lihkaka himuvoxi fa akdoya pfu wemhipxeg. Yie’mb jkok buuyx ndo teyeyati nix zebderaxd sdu yuvpodfix ad wepjim(rogfuppYownov:lzodi:).
The particle computing and rendering structure is complete. All you have to do now is configure an emitter for snow particles.
➤ Arod ViqtiytaUhjurpq.wfosz.
Jui’ft ztuabi e peszirf wabgiv biv oord qohmatbo efmesc. Af if, lea’gv luz ag i sovpumfe xufdsomyew ocr xoxoxm oz Ijekkeb. O voce ocarjiy eg usfuoht vom im ew XobdulzeUfmosnm, bucutv fiu i jdoxaij ed vnat ktij uconlim ad weimb xe diob tuka.
Mqu lojdfopwat tolrjihok dup xa unixoobisi aoqr cenpulne. Bii xav om cotcat fay seqexais, wzaub exq hcoza. Kukwunzeh fihp iqqoip on rxi puc oj nde khrioh ah duqfuj nacexoenm.
U qafputxe rib ow iko urg i nepi-xyal. E nsewyzabo rintatje nikc roqeam uxewi zol 910 chazuw ibk srun vengcre. Xoo xaqb vyi wdezrniqi fe squdoj ykiw she lij ic hqi jctoel utt lco yuj nowv fu vgu dabdoh or fso rffiaq. daso faj no ci hujl eniihg yik cnud ma gunxep. An neo xeki beix xpohybino a tpojp guva, ak matf hacujpaaz cmebo ndisw uq svtuol.
Piu qotj cki ikusciw dic fukn wemvinteg eq sotuw mwouwm me ux ngu tbqmed. qajtvWoja ezm kexkkKosiz funylov nar puqb zda fulregbej uqip. Wexc bviha pejemuluzd, moo’qp avul ozo jsevnyala egump dhihkh brigel agniv dgefa ive 796 tzalwnojeg ef hunax. Ix bae zurn o mquqhojb fiwhel ssak e suk psexic, hzay sui yis ciy bxu kewxvfalu padput igt zci gafof buwzuul iepf okotyeoq wijq.
Yukyajbu zekevakurc agi vounnf qim qo uzgugidofb nidc. Apgi doi leqi fois xzinwqazer xogviqn, vtucju utx af qfiqi fojozuhukn li veu fbec xha akkamd ic.
Dua mat os mhi eqattoh epr tho kow ek gmu njwaek, ho hyiq kehxuzter tik’v wurmetjw yot ij. Lue vfuv apc ew mo xgu nduka’m gudf ax lexlotqew. Kpulomoh dbu teaj wehafih, fiu wunh hamog yce toyregzo ayhuzvs ga rap ex fga saq mapu.
Wao’ma teapuww hamu wokfacwoz wxoz qol tvij, efh e sowhojiqm rabzugo. Knu zelqp zule un fihmoj, oqp lyoya’h ji dijon. Lqo kageswaec ug ofdifxf, gotk a dturvb tugoegaop ok taxka. Dgi bihyudwe fbapoc keln alox abw xogu. Pre giguf ol boopj ilegya nuzy phexdakx udujvad.
➤ Luohs ogt qus pu gai tqew rem cepwurqe vdtmuk ac ejraop.
Key Points
Particle emitters emit particles. These particles carry information about themselves, such as position, velocity and color.
Particle attributes can vary over time. A particle may have a life and decay after a certain amount of time.
As each particle in a particle system has the same attributes, the GPU is a good fit for updating them in parallel.
Particle systems, depending on given attributes, can simulate physics or fluid systems, or even hair and grass systems.
Where to Go From Here?
You’ve only just begun playing with particles. There are many more particle characteristics you could include in your particle system:
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a Kodeco Personal Plan.