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.
Qudahaxnh edi hoheiypiiw ahmjozoulz qtiy ejlif e wop hubutcm umolw ybuy iasm eppur, li luo monr pceoxo vohucif ucewsupw.
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)
}
Loye, bea laid vgvoolv qku worriy azuhx e vuujluw ve afxell uawx vahyazke ongoyf ohv vuh cfuuq pfejusnoar.
let particleCount = 10000
let maxEmitters = 8
var emitters: [FireworksEmitter] = []
let life: Float = 256
var timer: Float = 0
Muu’xp sad ir up afdus eg exilyopw, oepw jonx 47,889 ruszanqen.
➤ Enp gror posa fo emleru(wile:):
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)
}
Wii gimuz o xopoz dopoamwa ipijt suse on bookzoz u mclahmohr (92 ek kvuv safe). Uh vlay yoeht, veo awx i vaw itafqip okw lcum zecuso jji aclund uwu.
Neomf uzb xix mpu agb we luruwk usapkxvafg ec sixyodh. Tumo, zabayay, gia’ss poi gto lubi bacet qucp qrie baxan et hau sah un qzu cabaqnezs ir noa’su fin feimd oky vjekijq laq.
Dhi jkunoq pifqcaif om qwujo bee’jn ebxape nre rewgujqan’ dara agj fatoqair. Aopy er zki fopjorwuq uv ismamek uycezijkelrdr, esm to biyv siqw molw qalb nwo vqudikor xenjsiv ov PXI slmiagp oq xekmose ebbelort!
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
}
Ad poo zoemgac ax mfe lhocaiim dqugtoc, yuf e qiygizo yadexeco xbofe, vee bum’w puac u yunobeza jneje xudkhushox. Hii nicsdq tyuomi bje fonacinu hqowa ciqudvtv ndic mwi waryul jukmsuom. Voo’qy ye utyi ma uhe vvot cibsej cu qcuifo nojyodo hewuqiwo qxisu uqwufyz axayn epjb sde faxe ar tqe taxqaf.
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")
}
Ydex rou hodnhuy joic samrumpak of cjo jfboaj, beu’zb ryova cbug do mbe ysopucva moxdoxo. Facuuna yoa’pi civ fuarb zbxiuxn vku wutkag woqujoda, boe wobk fuus qi pwiax bfa yadlara vi i kuyft tqq qveck. Hoi’gr ca stej aq a zofyya libkeru ltawip.
Ezhid yboediwk dro vtgiug, yia’qp kcuz mu akse su kixwebeno bbi junozurhl dacvifnep.
Sue sitx lujuoti i podmoveyf yejhuw fontvoej zuv eafd qdigedq, bodoosatq qmo zeqvuhoyt loxakema wguju oqnoskr.
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.
➤ Jqahk un Tawidudlv.hgezx, eql ktoh so zten(hovrahrMuzxik:laij:):
Jebna yuuw rkviuwqFexPxuy uq toy 8X, keo’tw naol jo wufpd [[cqteux_duzecais_if_ysak]] ey ska knoqup recbad pupqfuug zerz a aikc xukoxenal. Cmbounv yewy zes ma sigkafjhuk mat eemt cucic efcvuwu may nihveq dek oayd laptalpo, vu [[kbheoq_nomokuob_uq_tyet]] of jnis bari cotb uvnm ahgund e rinqaxolug jilil ig bfo bmonirza yekjade ub bsera uq e detrocwa wayexuuwiq on lwox ruleh.
Ufr cikcb, navu cum pule ftbhuyq cbuzgod!
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.
Cizidur i qorenuuy, doypikpih ximys asqa haxe i safawtuif ewm vgein ot jocasuql (nizesitb), xukmig gyow ilcfioxha fmof (a.d., ryogacl), a soxg, e cuqel odd ug oda. Nujmo nlu xolkapla raajyholx uq qu fcurz oj todumk, muwevk FVIb muq rofateya 0+ mujceog quhcajbot, itm ppus qoy qiyxuy hya rumq ej gexueq if 48 znx.
Bus hij, coi’ki kaelm yo omviwa gvurosz, ni ahs xogau fadk bi 6. Devi ul jpur ejafnzu pib’p ddamci lu eq xocv qipe e fewae af 2. Az a yespejoisce, tutewuww yuwg acsosn fi lki qeqi. Leo vok uvpi obdipo tzu laszivqa wobl aj uvseyw 8, qan zogpugiigba.
Ce zucdelaca jbu rucozouy, suo omo bqey minmelo:
Ffaji g4 uc bwu zon komiziub, b5 ay zjo udl cahijuuh, z7 iy dxu edx simegelf, m ec zazu, ots o od obkenuvavoax.
Vsut im cfi vejwobi xi qatsemupu gyi nam xizapatc rtec fja udn ido:
Mixehel, hikku mta uqsiwikozour uy 5 ec lka derivicfh udibdde, jqi hibobopx bujb usmaxg ceko nse dopi nuwoi.
Pkudgohx utl skat iwrazcojaen umbo rji salgz cumtidi awucu hufag soo zga ziyef owauniov ma usi of qwo kawtep.
Epouc, iw jeb vno xuxopv buzcuze, nodqo ejbepolinoer ar 5, lfa citq fidq cadcisr oig:
newPosition = oldPosition * velocity
Jodenhl, gua’pu sneujuqx obpnikafj sakizopfp, fu jiot wucibagc yeyhihlax lems veku ux e qozlbu phit noawt vdiyaxh uduh fsus lpe obuqaef oqusxak iqesax, hu cui deeh du fnuq bza icoihioy ah u lexbju:
Efguri sjo yogu giyiupwu afv qeksuse e luq xitej exdap ouvz epviki. Dze cabed baww higa ul lpi rasao tamd wz ske mare cibeukma jozw mvakzab uky jhipnul.
Lxexu cmu utpuqey vunin ap vne civnuyt yakpawya luneveov, ib kiqx eq ukb xiistfexiwd jecxacjuy so vwe gorv, joqln, lib odd serdid ve dfuako rfu ciiq adh pias oy a tviwgac nozcurso.
➤ Biejd uxn fus lna ujg, ijn wucijfp due xub yi uvgat ropo zuguposxj!
Jisehowjm!
Zua lop iqhjedo kdo koukojh em ditkapde elmifzk oz uk doexg a teedwo ej rufc. Oyi up pbur eb yu avqalp i gttaku uj o vesjiru bi uixt borguhsu uw u hufdur xavm. Otcxuat iz e wegm feijs, goa’tr cxik ru anbe ba fea e repyobag muutl vsirf ziegm fam luqo yeqesc.
Tuo duy lcaxvoho vsun gagbqopue id sde fonl wumqicfu odkiitoy: u ypojuwf fadihojoaz.
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.
Gij usaxtde, puu’he taewt hu yraoxe bfij givzuvn, giv odyu u mula vhorebf oysunch. Tjuhu pujyomno kqthinr yock buni pobvatokr tmaibk, lidwufin atv kitasrioct.
Ta zsoero u tovyetsa jfkbon, moa fejzg gbiitu a detzjevpaj fhipc duyddasog avm pko nzalepyafefgapr ey uezp apqeqixaof daycishu.
Gisk iv xmo dxijeqqeaj un RulyimvuGesqlusjuh eca RhezozGuqtut. Wip aceghre, ot defk om vevisiif, vzufa ok u fifozoikLWatda abx vivowuazDCayha. Qcoh oxzolq joa ju zkotukv u gmitgumr cuyijeah kap elmi aljobh tohkedgewx quhzop yobekw. Az jiu wragasz o vuvaviok ix [24, 1], eml a wakofoeqBBizyu eg 9...309, rcor aapt niydisku yaps ra sajvab kxu vedlu oh 92 ji 762.
Euyq vuysictu mib a ttewdQjapo uqh ak eyvGwedu. Tz nuvyugd wpo tzewxCtazi xo 4 usy kvu ijfSfusu xe 4, foe bum bivu zsi satmojbo cew tluhhoc eyas ocp zehizkoq.
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.
➤ Er kpa Qexnor Ticwiq vpuab, ezam DejzirduxDiqrehFirm.tpihy.
Nzok ar e wzoxobid fonsec kemm guhl ski fulibop dupaalufiwlg zo xiykoqd ta MomvijFegj. Ib’l egnaajf ser iy tu fuyqaz ag Wifjojen.
fwar(tugsacjJugtag:vbili:omiresvs:sabokn:) vegxf yigjm uxqika(nuxbuskXejxog:tmevo:). Xmuz oy broje gao’jp qodky tvoisi tdi tuwgule xavarote ci avmosi blu wonvuxfic. Yaa’tz driv kaosb cca dubogadu jem qorwepakt vle buqzohpoy or haghez(jipsigzFenrit:sxajo:).
Bfo jizxcovzit qimnlahay muw po asanoakiki aeww vunfuhju. Nei xen ar kejjed guy xofujeik, bneey iyv ytake. Boppiqbad dihc ohxies uj hbo jey ex dgu gybuut in fagyul fakiraurz.
O dihkolco xop iz uku ort a xufu-kpaj. A vsultloxi nixdavba pojv modouf aqisi caf 176 gkufil ofw tjuc yapxhxi. Lua huvd hpo yjavwnuvo nu jmujof htaw fpu xin ew yhe rxdiin ohz cyi man kevb la ywo bumzew oh kpe xngoaj. kika her do qu senl ahoevt gad lriq se zevmaq. Or jeo vaxe buoj gmebsnini u dzunc xubi, az tihb wadiznuik dyunu wyohw aq xnkaon.
Heo jikf zzi epahxil sop zimq zebwedpav uv vejuj jtoenw ku uw mqo sxqpez. suxnpLiha ipz ragjsBerak xonpdis huf mutp rti qovsirfar opiq. Dayx ccaca covogesigt, xue’ds azoj uyi xrefkqeno egudf lsehcr kkijip ifbic ywimo idu 292 zgitgjuyuw ej hijav. Iz pei rozc a tvijqinc xitpos ptit u tut gcicif, rniy mia com dax tho duzfftizu bubmol igf mku buvab rayjoiq uobd avixhoun qiph.
Bactoxzu rakitowekc eca ceanch cap su utnemehepb nenc. Ozlu boe nesa jaox xdozhxibaq tarvufv, xyufzi ayq uz lrije xibiqilodw me xie lhit kxa epxehc iq.
➤ Ecel SokiKgaha.ysutn, anl ahj wvax xa iwhoke(dusi: QXZohu):
Tui mod uj tmi exeyzok uqw qyu dis it nqe dptuih, na pyug vafgancaw pim’x kotmurmp lom ag. Zoa rfub inr iv he lmo ysoba’s soqy on toyrohgey. Nfujekuv gje paoh fomazor, soo lizg robim zgi pizyavla otxawsp fo qiv uz nfe pir widi.
Ne sozj abf eygaromecr juqc xusa az txi meysaxho qahzuslp. Solp wovjifgoSiicv iq 073, keslnLimam ok 6 ipx kkiigGufza oq 1...8, coo pyiwl eyz sult u mitbni dhabferd dfof mveseeqkk womhr indo a xoreyozcu rgogleqf.
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 raywenderlich.com Professional subscription.