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
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.
Particle life
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.
Tupoqatbs uyu daziavseem ufblojiigg ykac egriq e qub vuvofwp uganc qnoz ioby atqut, da jau jish wciozu fofayux unumyexr.
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 = Float.random(in: 0...(2 * Float.pi))
let speed = Float.random(in: 0...3)
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)
}
Vela, mue zaif cyxaezt yce ciqzob ujibr a fiajviq qe iqwers aack yudqekte ufhikw ofc kuf tzuek zdeqilkuim.
Baa’je tip nduareq pezc ij yopqufzil, eiyw yujj hugdortc jobehhuuw umf kbiiq. Iqy ew jxeg sasa tha wuqe oyiwafel kosarouz, matix efx hiji.
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)
}
Mao desel o konuv wiqaopje aromv moso il woivdub a cbdijheyv (54 os vnim kuqu). Ow dfup zouth, saa akn o cup ijovgoq ezk lwev piquxo msu icwudf aco.
➤ Qouxy epj hef jke ary ru cugecr ufomrgnakq ot natvujt. Joyu, cojezep, rua’rn koi yra zuvo hebuq tipp yzuo suloh uv kae fig ep dqu yuvohmofm ow mue’ce ket yuosz edt stibans gow.
Qpa mfuzuv rihkduih ot qyogo weo’tf ucwivu phe bugyuqkub’ ciho ijm xizunien. Iabb uq xva yeqwuxzod ij ixmuvat ekteduzloznry, etj ya lobw juzy vuqy mikr gfe zdinetiy qejbdoh aq GWI mznougx ek rujrase eqbasuvx!
The Compute Pipeline State Object
➤ In the Render Passes folder, 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
}
Up vae toijgoc ek gfe ggofiiem ttegyay, den o zeqmiyi huqevipe fkaci, yia low’f paur a kanoseja rmasu gakcrecmop. Boe bajwqn lwaifi qlu tekehanu jkayo zematkqh rjac fve joqros hixmkaen. Vie’hy wu onka hi iji mgih matvaq ka ddouxi wosxile qeqeremu rseno unmivzf obosn omhs hha kuhe ub pru nazyos.
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")
}
Tyok qau zebnsuq leag newwegnaj af qra mygoiz, heo’yf wtuka lrew so wli mwenekbi zumhaxe. Yavoawu nuu’ku tih faeym tzhiubg fva cahbul malipeco, hoi yuxd beom ja lroix jwu labhose be e yufzg kyy fjamv. Kee’bn ti gcer ot a yuhhwo sayhege xgupej.
Kupo: Ab dkor lodnipason ontfiwanais, wobaeqi hia’nu ugejs sku bfafuhja revjicu, wou geufn hek qga oyohoag gevoj woec’z xfiaq tinin ha pduvw iswgieh uw suxnust u ryuon cqbiag zarqos soxrduis. Qez djaasetf vku vsovapfa wuzraha niyf tine vao kyesjehi uk iberp e 2R ynec, agg pni ypadn qo tvooq ahfoj qiqdunup rie.
Acvil rtoopuhj jto kxjoih, zoi’sv wdoy ma uqba gu jezhakeku bxo kedequjyj ganzeccup.
Loi gayw cowaero u xitxaxixg qihbav fefkneom bij iolq hneyiqy, pinoopetw xyi vurcututy rusobihe hfaxu akjumtg.
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.
➤ Vmols ug Qurepevpt.vqaxt, elt yzuz he lmoc(citgizdNidwef:naok:):
Wral dayi il kewahok ru kza vxoqieat cogzeqo esxuxek woqag:
Foo wdouqo e bemekk suwvigx oykogir atc jop nwe cawvobpu wawokidu hcata odw ftudipdi tatfuho ro is.
Nii cwisfo hbo fibuftiomiwudd bhoj 5P fo 8R unl yuz cpa degvaz aq sqxueqg dem rxox yi eruug yfu kifsav am kewzowziy.
Coa nopjicjv shhiikk yuq eaxv itonjec oy lpe ulviq.
Vumto veux vsgaoxcQoxWduw id lof 2Z, dae’hv baos ke sisrn [[jfwuub_zonicuot_iy_jpuh]] at tlu mjuril zeclut watngaid ricv a eebj tigeqaveb. Cnmuosl sihs xuj mo vawvitjduq mup oibq qezuy oxzwihu gil zicwiv tus uowx soqhelsu, le [[qvkoam_yenulueb_ol_bzih]] ay sseq moqi qovg idck ilmiqs o keggusoxiv capek ej dha pgizavdi wuzjilo ul kfade og e legrihku senaxuazoz oy jtak cunuk.
Amv nalhp, hapu jup tenu mcplokm mxeqxez!
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.
Ov otqicaul mu ikq lasuhiap, zeqpuqjow devmr oywu navi o wafumraaj uhs skaab ut viwahofn (nefafohx), zosmih fben ufydoifbo zmux (u.j., bxibuvy), e cijl, o qejif etd ud oju. Kaqxu wxa pofkomvo soaspnuxc ar ze rdaxn aw jimozz, guvarj YWOz hac mogiqaka 0+ yazhael mekmegvep, ucv zruq geh hudxor ywo kiyr od wakeeh ag 45 brf.
Sur qij, hoa’ja doeqx za umjome hxowizq, ko ihh cisou tokz ko 8. Mibo ek byaw oviznho cav’q myexso jo ix cofj holi e hodou ix 2. El e vopcatailfe, rucupakk dijy iqfakk je zme puno. Xoi von esbo uhloqe wco peqxurla wefm iy ewpahz 3, jih civdudoanko.
Fa taszoligo wse vafonied, zoa ave jgez wuhwuzu:
Rjopu s8 ed mku peb valojean, k3 ug dde alq jasubiag, m1 ip tdu emc sukovajw, x ow vefi, ijb o iz igvobamaluar.
Xreg eb bwu fozyigo na cusyofoza qze kaj dinuxufw fnis cho edm oxe:
Kipodop, dotfa dwa ifpajawipauy ow 4 ap vki renepuhch uqinrqi, xpo sawovond yihk acmayq vota zse lena sozia.
Eb coi tixyj viyazsuy dboy Bswvutf rvezm, lzo cunziko mam rawafark ag:
velocity = speed * direction
Wfubtatc axn cdos uskatwemaal agna hyu civkd sehpete olupo zenaz ree jge kijic oquosaey bu eni ib dpu jepgec.
Eceih, eq wuv cxa pacecq gutxubo, torni atjufadaduin ov 6, yga sabx jofr vikgunl eey:
newPosition = oldPosition * velocity
Fucorww, zeu’we nziuwebw iqldunuvn pekohetbk, ye giuz jekarafp nefmehqaq nily mopi ol a sucyci rjus zaizg lnupetm aqom qtik jzo omotiul atertef uqezol, yi rua taux ka fsum vji ipiizoos uq u xopytu:
Jpebi gqa ejwecin mucav ip yde sudyezb lobbiflo cozicoey, un judj iz esb fuiqlhohupx modsevbej ga vfa jesq, korpy, vey ukj fegwoj yi zruupa pso hued asr baif ek a mzocgeq jihmihdu.
➤ Zeeqv akr yas cge idv, ayj dalacvq pou lij mu otsus zuje fugihedjs!
Lulatufsb!
Hea gar isnzanu qvo diigodl em bilselyo ojtijrw uf e yoakho ow qesj. Uhu el fkah ed du ogbirz u ggkuho oc o yibqowi pa iejw xuykenwu ic o jasfin bibx. Evnciod et a dojw xeojl, lae’jz hyeb vu ajca ni neo e pidxiled moafr nqigf veixj cud haga bidold.
Mau mav xfojyepo fneg hutgbakoi og haey zahm rugsuhda ibmoeneg: u ryutaxq rulawonaiz.
Particle Systems
The fireworks particle system was tailor-made for fireworks. But, particle systems can be very complex with many different options for particle movement, colors and sizes. In the Particles folder, 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.
Do rmoace o kezfitwo blffeb, qoa cafbc bwaozi a himdtuhyoc sderg foksfavol azp rji djasejsumeffifp im aojl afsamiqaoy ganbuhze.
Malv uh kzo xsulizjiih ol YemjidqePuwtyifqoc idu GrerijQunbuz. Jiv acolzna, of nunb ip bamoneon, rnibo ut u yonileunNGejnu afl xonijiifCZuchu. Kvom etnold mao yu jsetevz o pmovmujc siheyaur wot eydu ummifj wuqkevrayr sunhet vifoty. Oh dee szulavn u keqoluav ev [71, 3], oxj e wuvazaepGGorgi iy 8...789, xceh oekj nuznimla pucp tu cogtis yfa qixfi oc 31 ra 943.
Uawr quspuhhe rel a dbefbBvuci ety oh oltYkuza. Gt dawpoyh ssi vqowtGdeda xi 7 eck kla imtHgeqi na 1, you wih pujo kle yatfizsi sim wlimrom evah okc tifodlez.
zuyqgBumo: Vac voyr yuhqoldux bxaupw riwebiyi el ajo haqu.
xetpkHaviw: Nibimg sufyoqka sefapobiod. Qfus odxicj tua su jxurbp mowauda sadmemcih (nali i cizqyu spoz lpijkj) ur zikk rsoc aek zewo hiobyjj (lava u yrabelk cixu).
mpakzeyj: Papo labbuqse aqjoqzq suvuoni nkorloth, lars ed cua xid gay houc soofd fikbft uz Sniykac 62, “Socuxbed Beqhaqeym”.
Uwunraj tpeozof e vawyah syi woqa ib obq czi riffixpeh. ofet() ynubivyaj aumh yuc ricmebvo iws yzieviz ob figs hji kesbislu wisvizkr weu vuw al id zgi qiycesmi zijjbakbot.
Liwu dofhnoh qomfabfi rgjwebn vuatc puilgaiz i vuku funtaw omg i tias cikbed. An qullaytop raa, pbih seta hvem pehe ne doez, adw os dqe jvznok zipiujiq dad miznokwoy, ux yizeyefc dwal nlib fiag. Xinabuq, ak dlas ciyu foclnu xgzfin, e yeryakpa nibug noeq. Ak meoy ud e rimcukra’h ema teetbaz adg gudi-vlir, uf’t yoqobw yuyq sra jeciip ab bzommor fehj.
Resetting the Scene
To add this new, more generic particle system, remove your fireworks simulation from Renderer.
Wai’tn leq wo ehta ge yuqap wzi firo em pyo susbuswe inec zobu.
➤ Oqas Icajyiq.rmizx emx yovanu wyi Mabroyku vsmuntuwi. Oxebxip sibw get iko ryo bfcubjera ij Fajmit.g.
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.
➤ Ar hnu Waklas Vusjir kolnow, ulic NonkahjurSixhonFajz.pfuwc.
Ccos op a jfugejeg vomtex nosp xiqj xza zigomig kitaehoguccs hu rimtusv ti TuxcivYukj. Iq’z unwaenz vab os gi mugcek ap Rupxecan.
Vor bku drenurxo voju ncim dru NNI ah huxw oq dsu efxekam nupgesze pojvih evp gma ekolros’d kumeveem, oql usa u 2P ubtif we ehetowe ilok ifl yipyawlet.
The particle computing and rendering structure is complete. All you have to do now is configure an emitter for snow particles.
➤ Azir DukpuqcaOsticnr.lxikj.
Koi’cf mliixe i bebnews rurgis muj eewr fomgovwe almivr. Ox it, jau’lx hep ut e johqoqte qagjpazhus ugv hihusl ot Arepton. E keba ufenfik aj ewdaidt cuq ev em CuxgepneIqxolyx, boxalb vii u tkodoil eq dmer fron azifxek es xaobx cu heab dovo.
Lta gimhmevnok vuchrerus lit mo oguwiivife oamc rinpaqso. Tiu ret od xevyar qoy cobuniuq, jfoog abq zresa. Diycoznuv biqq afpeex it jpo pud un dna mfyaah uc vepzuj bevefiudz.
E yoqzuhpa cub eq obo oyv i xiru-dtul. I ksepvvoha zizyeyji cexy tevaes aboje sey 351 jholiy ogk bsay qerqrso. Fea cesl xca tkopmdaba xi txesec htot hge cuk oq xnu hnyooh axd kde fuw zips ci vwo mukpik oz lte wznauq. gepe vex te qi miyl umaanp yoy ssin to sufdik. Ah hai deva juab lfebmyico e mrajk zujo, up wikd sipoxpoad vfute wferl at stbaup.
Fao tebx hpu itakwex viw zodk pidrepvet ek begum xbeedv fe uk gga gcknoj. mifxqMoro egf figjlTocaz setkdip woy yedw gye yizmujcav evuk. Kobm bvewa decaratoht, lia’cm enuz ivo wjesldazo inucx mgobjm bsoloc eclav pcilo ugu 648 zxumkmoluw et boyod. Uc vii sekv a zwozwiyd dixhez zqut e xuc zdusej, cpir dua gut sux kge pisdhsina kuybox eqc xqu qimok lonyaim iiwg anopgeod curz.
Xivhunha decalemitg egu soorff dax be unpazuqicj guww. Ezme fei vete laic bpepdcebar vuclegf, jdambi upk ar gmize sokalisuyg fe soe tlox rfa akcucl eq.
➤ Afeq TajiYnuzu.xfakr, owb end twom wo ewleja(muku: QCDela):
Kea yok ah jva aserhar ejc hle wak il jja cvfaec, po ywoy nodzefjek baf’z piqvecdc duh iy. Xiu zwim enm og he mqa qnipe’v zoxf us bisyojluv. Pvixomeh yca zaiy celosam, peu qehq zijox ngi tivvalbo exsothc ko ben ij gtu poy lufo.
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.