Probabilistic Cellular Automata for Granular Media in Video Games
PProbabilistic Cellular Automata for Granular Media in Video Games
Jonathan Devlin ∗ and Micah D. Schuster † Wentworth Insititue of Technology, 550 Huntington Ave, Boston, MA 02115, USA
Granular materials are very common in the everyday world. Media such as sand, soil, gravel, foodstuffs, pharmaceuticals, etc. all have similar irregular flow since they are composed of numeroussmall solid particles. In video games, simulating these materials increases immersion and can beused for various game mechanics. Computationally, full scale simulation is not typically feasibleexcept on the most powerful hardware and tends to be reduced in priority to favor other, moreintegral, gameplay features. Here we study the computational and qualitative aspects of side profileflow of sand-like particles using cellular automata (CA). Our CA uses a standard square latticethat updates via a custom, modified Margolus neighborhood. Each update occurs using a set ofprobabilistic transitions that can be tuned to simulate friction between particles. We focus on thelook of the sandpile structure created from an hourglass shape over time using different transitionprobabilities and the computational impact of such a simulation.
I. INTRODUCTION
There are many computational methods that can beused to compute physical phenomena. Modeling a com-plex system first from principles is ideal in many scientificfields, where physical accuracy is paramount. However,for video games and computer graphics, performance of-ten trumps accuracy. Provided that the result looks real-istic enough, a simple physical simulation can be enoughto create the illusion of a more complex interaction with-out the computational cost. This work looks to simu-late physical phenomena in a realistic manner using cel-lular automata (CA), as done in games such as Noita [1],Rimworld [2], and Oxygen Not Included [3]. Our modeluses probabilistic transitions and a modified Margolusneighborhood [4] to simulate the flow of granular mediathrough an hourglass.The most common two-dimensional sandpile simula-tion is the Abelian model [5]. It is simulated from atop-down perspective following sand topping rules basedon height. From a mathematical perspective, this simula-tion is often used to study concepts such as self-organizedcriticality, as an examination of how complexity arisesin nature [6], rather than for video games or computergraphics. Side profile sandpile simulations [7–9], however,are more relevant for video games. Noitas primary gamemechanics, for example, use a side profile sandpile modelas the basis for their fluid, gas, and solid simulations[10]. This leads to interesting interactions between thegame world and the player, where it is possible to directlymanipulate the environment in response to a player’s ac-tions.At a fundamental level, CA are simplified simulationsof physical phenomena where time and space have beendiscretized and physical quantities are represented by afinite set of values. The problem domain is defined as acollection of cells whose properties are updated over time ∗ E-mail: [email protected] † E-mail: [email protected] via a predetermined set of rules. The rules for updatingthe cell typically consider local information only, i.e. onlynearby cells are considered, known as a neighborhood.The concept was originally developed by StanislawUlam and John von Neumann in the 1940s at Los AlamosNational Laboratory for work on crystal growth and self-replicating robots [11]. Further work was done by sci-entists and mathematicians throughout the rest of thecentury. Stephen Wolfram, in the 1980s, explored CA inthe context of mathematics, physics, biology, and chem-istry [12–17]. His book on this research, A New Kind ofScience [18], is an important starting point for learningabout physical modeling using CA.A common example of CA is Conways Game of Life(GOL) [19]. GOL uses a two-dimensional square latticewhere each cell can be alive (1) or dead (0). Updatingthe cells is defined by five rules that represent conceptssuch as overpopulation or birth. Although the simula-tion is simple, it displays surprisingly complex behavior.The typical structures that emerge from a purely randomstarting grid consist of groups of static cells, groups thatoscillate between two or more states, and groups that tra-verse the grid. The GOL model shows that when dealingwith CA, simple starting rules can lead to complex be-havioral results.CA modeling of physical systems provides an excellentcomputational framework for modeling the macroscopicbehaviors of various phenomena provided that the updaterules can approximate the microscopic properties. There-fore, CA preserves features such as simultaneous motion,local interactions, and time reversal symmetry for non-probabilistic rules. In addition, the lattice structure ofthe simulation is ideal for modern parallel computers,where one can perform large simulations with minimalhardware.Common applications of CA to model complex systemsrange from fluid dynamics to traffic congestion. NotableCA such as lattice gas automata for fluid dynamics [20–22], as well as chemical reactions, such as the Belousov-Zhabotinsky reaction [23] using the Greenberg-HastingsModel [24], are examples of CA applied to real worldapplications. a r X i v : . [ n li n . C G ] A ug The flexibility that CA offers in video game environ-ments, while keeping calculation time to a minimum, pro-vides a simple way to represent complex interactions. Inthis context, otherwise prohibitively expensive compu-tations, such as interactions between gases, liquids, andsolids, can be implemented following simple rules thatproduce the desired complex behavior. This allows gamesto feel more realistic without the need to solve the com-plex equations that govern these processes.This work aims to examine the computational andqualitative features of a modification to the standardside-profile sandpile simulation. We start by describ-ing our sandpile model and how we approached simulat-ing sand particles falling in an hourglass. Then we willpresent the results and computational performance of oursimulations using probabilistic transitions. Finally, weconclude with our perspective on future work and modi-fications to the model.
II. SANDPILE MODEL
Our sand pile model uses a modified Margolus neigh-borhood, shown in Fig. 1. The standard version of thisneighborhood is first partitioned into 2x2 blocks of cellson the lattice. On successive iterations, the 2x2 blockis shifted one cell in each dimenion before evaluation.Although any block CA that uses a Margolus neighbor-hood can be computed using a larger neighborhood, theamount of states to consider during each iteration in-creases rapidly. Our change to the standard Margolusneighborhood adds an additional shift to the 2x2 block.This creates a cyclical pattern over four iterations. Thefirst two are the standard Margolus update, the secondtwo shift the neighborhood as shown in Fig. 1b.As an example of this update process, consider ( x, y ) tobe upper-left corer of the 2x2 block on the first iteration.The upper-left corner in successive iterations would be: • Iteration 2: ( x + 1 , y + 1) • Iteration 3: ( x, y + 1) • Iteration 4: ( x + 1 , y )Note there may be cells on the domain boundary thatare updated on every other iteration. This is typicallynot an issue for our simulations since the interior cells,where the dynamics occur, will be updated properly.The motivation for this change stems from the topplingbehavior of the particles when interacting with staticboundary cells, whether the finite boundary of the simu-lation or lattice features for the particles to interact with.The standard neighborhood causes sand particles to top-ple in one direction only until they can no longer fall inthat specific direction. When forming a pile, one sidebuilds to the top before the toppling behavior switchesto the other slope. When interacting with static featureswithin on the lattice, this can cause particles to stickto left hand slopes. Our modified neighborhood forces FIG. 1. Standard alternating 2x2 block Margolus neighbor-hood, panel ( a ), and our addition to the neighborhood, panel( b ). The standard neighborhood alternates between the darkand light 2x2 blocks on successive iterations. With our addi-tion, the simulation alternates between four 2x2 blocks, twoin panel ( a ) and two in panel ( b ). partiles to alternate topple direction, yielding a more in-teresting simulation.When modeling a physical system, it is important toconsider the real world properties of the media being sim-ulated. Accounting, in some way, for the microscopicmotion of our particles will lead to a more realistic andinsightful result. As sand pours through an hourglass,the grains contact each other which, due to nonuniformparticle shapes, prevents a smooth and consistent flow.Using a regular square grid, it is impossible to directlysimulate nonuniform particles and their interactions. In-stead, we use a set of probabilistic transitions to approxi-mate the effect of friction and other particle interactions.Fig. 2 shows all of the transitions that change state.Most of the transitions, Fig. 2(a) - 2(h), will always tran-sition in a natural way, falling or toppling down. The fi-nal two transitions, Fig. 2(i) and 2(j), where the particlesare stacked vertically, will only topple with probability p .This represents the effect of irregular shape and frictionas the particles move past each other.These transitions prevent a smooth flow of particles asthey begin to stack, which, as shown in the results, ulti-mately changes the overall piling behavior of the particlesas they come to rest. While we chose two of the tran-sitions to exhibit the probabilistic behavior, for analysispurposes, transitions (c)-(h) could also have associtaedprobablities. This would give seven parameters to adjustto achieve the desired toppling and stacking behavior.One can even bias the tople direction by choosing dif-ferent probabilities for the left and right version of thetransition. FIG. 2. All transitions that change the particle configuration within the Margolus neighborhood. The two probabilistictransitions (i) and (j) will transition to a new state with probability p . III. RESULTS
We obtained all our results using an hourglass shapedcontainer inside of a 61x61 cell grid. The edges of thehourglass are fixed to the occupied state and do notchange their state over the course of the simulation. Foreach iteration, we use the modified Margolus neighbor-hood, as described above, and the transitions shown inFig. 2.We start our investigation by examining the determin-istic simulation, where the probability, p , for all transi-tions in Fig. 2, is set to 1. Thus, using the same initialcondition will always result in the same evolution of thesimulation. We then adjust the probability of the transi-tions and investigate the differences in the piling behav-ior. Computationally, each iteration of the domain tooka few milliseconds to calculate, with our visualizationdominating the execution time. For time sensitive appli-cations, such as computer graphics and video games, thisstyle of simulation can easily be translated to productionapplications. A. Deterministic Simulation
The deterministic approach fixes every transition with p = 1. Without a probability governing toppling behav-ior, any given starting condition of sand will result in thesame sand position for any given number of generationsregardless of how many runs of the simulation are per-formed. The deterministic simulation gives us a baselinefor which to compare, which is especially can be usefulwhen adding additional interactions between particles.Fig. 3 shows the formation of the sandpile over time.Despite its moderate accuracy representing granularflow, there is a noticeable bias in how the sand fills thehourglass. The particles alternate filling one slope com-pletely before falling down the other slope. This patternalternates as the pile is formed, breaking any attemptedimmersion as sand falls in an abnormal but constant way.The unusual way the particles interacted prompted us toadd a probabilistic system that reproduced friction-likeinteractions. B. Probabilistic Simulation
For this approach we adjust the probabilities of twotransitions, shown in Fig. 2(i) and (j). The piling be-havior of the deterministic simulations can then be usedas a baseline for comparison when adjusting these proba-bilities. Our goal for these simulations is to examine thechanges in the structure of the sandpile.Fig. 4 shows how the sand piled on the bottom of thehourglass after 200 iterations in response to four differentvalues of p : 0 .
25, 0 .
50, 0 .
75, and 1 .
00. Each simulationwas executed 10000 times and the average probabilityfor a particle to exsist in any given cell is shown by thecolorbar. The p = 1 .
00 simulation is equivalent to thedeterministic simulation and is shown for reference.The simulations where p < .
00 show areas around thepile where sand particles may be present after the 200iterations. As the value of p decreases, the sandpile be-comes thinner and taller as a result of particles resistingtopple. In effect, this can be interpreted as a friction-likeforce that keeps the individual grains from sliding pasteach other. Over time, the grains will settle as they willeventually come to a stable configuration.From a qualitative perspective, when p ≤ .
50, the pileappears more like a viscous fluid rather than a discreteset of grains. This leads to an upstable looking pile thatsettles over many iterations. Values larger than p = 0 . C. Computational Performance
To use this simulation in production computer graph-ics or video games, it must be performant at the desiredresolution for the application. To see the toppling be-havior in detail, we used a low-resolution hourglass forour results. However, in practice, we expect the neces-sary resolution to be much higher. Modern video games,for example, typically use resolutions of 1080p to 4k toenhance visual fidelity.By their nature, the speed of any CA simulation willbe dependent on the specifics of the computing hardware.
FIG. 3. Deterministic sandpile hourglass simulation time progression from t = 50 to t = 500, (a)-(d). When there are noprobabilistic transitions the result of the simulation is completely determined by the starting condition. This deterministicsimulation acts as the baseline for comparison.FIG. 4. Sandpile hourglass simulation after 200 iterations using different transition probabilities (see text for details). Thecolorbar represents the probability that a particle exsists in the associated cell. Lower probability transitions create long, skinnypiles compared to higher probabilities. Thus, a direct comparison of the compute times is lessrelevant than the scaling behavior as we increase the res-olution of the simulation. Since CA are compute heavy,the only relevant piece of hardware is the CPU. For all ofour calculations we used a 4 . Resolution Time (ms) Cells Scaling640x480 3.08 307,200 1.00800x600 4.57 480,000 1.451920x1080 21.51 2,073,600 6.982560x1440 38.84 3,686,400 12.613840x2160 85.88 8,294,400 27.88TABLE I. Compute times, number of cells, and time scalingfor different simulation resolutions. All times represent com-puting one iteration of the simulation and are the average of100 individual runs. 640x480 is the baseline used to computescaling as the resolution increases.
The time scaling follows the increase in cells nearlyidentically. This is because the time per iteration issolely dependent on performing the Margolus neighbor-hood calculations, which itself depends on the total num-ber of cells in the domain. The memory footprint is neg-ligible for this style of simulation because we can use asingle byte to represent the occupation of each cell.For a typical video game, where a simulation like thismay take place, one has approximately 16 millisecondsfor all calculations in one frame. Thus, when using asmaller grid, more time can be allocated to other compu-tations, such as physics, input, animation, etc. Typically,these types of physical simulations do not associate onecell with one screen pixel. Rather, lower resolutions areused to approximate liquids, gases, and granular mediathat are relevant to the specific game. For example, Ter-raria [25] uses 16x16 pixel tiles to represent the gameworld. When computing its CA fluid simulations, thisgreatly reduces the number of cells to calculate on eachframe. Overall, the highest resolution possible for thegiven context is desirable.
IV. CONCLUSIONS
We have shown the characteristics of sandpiles usinga probabilistic CA model. The toppling behavior andfinal structure are largely dependent on the chosen prob-abilities and can be adjusted to create a friction-like in-teraction between particles. This causes elongated pilesand longer settling times as the probability to topple de-creases. Using our modified Margolus neighborhood, weget a complex and interesting flow of particles that re-flect real world motion. Computationally, our methodprovides a balance between fast computation and realis-tic flow, even at high resolution.In game development, where framerate is paramount,using CA for physical simulations allows for fast calcu-lations while maintaining a high framerate. In addition,simulating multiple types of materials and their inter-actions adds very little computational overhead whilegenerating complex behaviors. The system we modeledcould handle up to 4k resolution while maintaining a rea-sonable execution time per iteration. Most games, how-ever, do not simulate each pixel. Instead, small regionsof pixels represent one cell of data. Thus, a 4k screenregion can be simulated with less cells than our 640x480calculation. When implementing new rules for new materials, thereare possibilities for refining the calculations. Breaking upthe domain into large groups of cells and preventing up-dates on groups that are unlikely to change value, suchas at the domain boundary, can significantly speed upthe calculations. For our simulations, the domain wassmall enough that this type of optimization was not nec-essary. However, for high resolution production applica-tions, this represents an efficient way to reduce the calcu-lation time per iteration. For the future, we intend to addadditional materials that interact probabilistically usingour modified neighborhood. This leads to increased im-plementation complexity while, at the same time, givesour simulation more interesting behaviors. In addition,we intend to design a fully configurable toy simulationthat can be used and expanded upon in modern gameengines.
ACKNOWLEDGMENTS
This work was performed with the support of the De-partment of Computer Science and Networking at Went-worth of Technology. [1] Nolla Games, “Noita,” Nolla Games, Helsinki (2019).[2] Ludeon Studios, “Rimworld,” Ludeon Studios, Montreal(2018).[3] Klei Entertainment, “Oxygen Not Included,” Klei Enter-tainment, Vancouver (2017).[4] T. Toffoli and N. Margolus,
Cellular Automata Machines:A New Environment For Modeling (The MIT Press,1987).[5] P. Bak, C. Tang, and K. Wiesenfeld, Physical ReviewLetters (1987).[6] P. Bak and M. Paczuski, Proceedings of the NationalAcademy of Sciences (1995).[7] J. Cervelle, E. Formenti, and B. Masson, TheoreticalComputer Science (2007).[8] A. Dennunzio, P. Guillon, and B. Masson, TheoreticalComputer Science (2009).[9] E. Goles and M. Kiwi, Theoretical Computer Science (1993).[10] P. Purho, “Noita: A game based on falling sandsimulation,” https://80.lv/articles/noita-a-game-based-on-falling-sand-simulation/ (2019).[11] J. von Neumann, Theory Of Self-Reproducing Automata (University of Illinois Press, 1966). [12] S. Wolfram, Nature (1984).[13] S. Wolfram, Physica D: Nonlinear Phenomena (1984).[14] S. Wolfram, Physical Review Letters (1985).[15] S. Wolfram, Physical Review Letters (1985).[16] S. Wolfram, Journal of Statistical Physics (1986).[17] S. Wolfram, Cellular Automata And Complexity (WorldScientific Publishing, 1986).[18] S. Wolfram,
A New Kind Of Science (Wolfram Media,2002).[19] M. Gardner, Scientific American (1970).[20] J. Hardy, O. de Pazzis, and Y. Pomeau, SIAM Journalon Applied Mathematics (1976).[21] U. Frisch, B. Hasslacher, and Y. Pomeau, Physical Re-view Letters (1986).[22] D. Wolf-Gladrow, A. Dold, F. Takens, and B. Teissier, Lattice-Gas Cellular Automata And Lattice BoltzmannModels (Springer Berlin / Heidelbe, 2004).[23] A. M. Zhabotinskii, Biofizika (1964).[24] J. Greenberg and S. Hastings, Physical Review A13