
1 месяц назад
WaveFunctionCollapse
This program generates bitmaps that are locally similar to the input bitmap.
Local similarity means that
 (C1) The output should contain only those NxN patterns of pixels that are present in the input.
 (Weak C2) Distribution of NxN patterns in the input should be similar to the distribution of NxN patterns over a sufficiently large number of outputs. In other words, probability to meet a particular pattern in the output should be close to the density of such patterns in the input.
In the examples a typical value of N is 3.
WFC initializes output bitmap in a completely unobserved state, where each pixel value is in superposition of colors of the input bitmap (so if the input was black & white then the unobserved states are shown in different shades of grey). The coefficients in these superpositions are real numbers, not complex numbers, so it doesn't do the actual quantum mechanics, but it was inspired by QM. Then the program goes into the observationpropagation cycle:
 On each observation step an NxN region is chosen among the unobserved which has the lowest Shannon entropy. This region's state then collapses into a definite state according to its coefficients and the distribution of NxN patterns in the input.
 On each propagation step new information gained from the collapse on the previous step propagates through the output.
On each step the number of nonzero coefficients decreases and in the end we have a completely observed state, the wave function has collapsed.
It may happen that during propagation all the coefficients for a certain pixel become zero. That means that the algorithm has run into a contradiction and can not continue. The problem of determining whether a certain bitmap allows other nontrivial bitmaps satisfying condition (C1) is NPhard, so it's impossible to create a fast solution that always finishes. In practice, however, the algorithm runs into contradictions surprisingly rarely.
Wave Function Collapse algorithm has been implemented in C++, Python, Kotlin, Rust, Julia, Go, Haxe, Java, Clojure, JavaScript and adapted to Unity and Houdini. You can download official executables from itch.io or run it in the browser. WFC generates levels in Bad North, Caves of Qud, Dead Static Drive, Townscaper, several smaller games and many prototypes. It led to new research. For more related work, explanations, interactive demos, guides, tutorials and examples see the ports, forks and spinoffs section.
Watch a video demonstration of WFC algorithm on YouTube: https://youtu.be/DOQTr2Xmlz0
Algorithm
 Read the input bitmap and count NxN patterns.
 (optional) Augment pattern data with rotations and reflections.
 Create an array with the dimensions of the output (called "wave" in the source). Each element of this array represents a state of an NxN region in the output. A state of an NxN region is a superposition of NxN patterns of the input with boolean coefficients (so a state of a pixel in the output is a superposition of input colors with real coefficients). False coefficient means that the corresponding pattern is forbidden, true coefficient means that the corresponding pattern is not yet forbidden.
 Initialize the wave in the completely unobserved state, i.e. with all the boolean coefficients being true.
 Repeat the following steps:
 Observation:
 Find a wave element with the minimal nonzero entropy. If there is no such elements (if all elements have zero or undefined entropy) then break the cycle (4) and go to step (5).
 Collapse this element into a definite state according to its coefficients and the distribution of NxN patterns in the input.
 Propagation: propagate information gained on the previous observation step.
 Observation:
 By now all the wave elements are either in a completely observed state (all the coefficients except one being zero) or in the contradictory state (all the coefficients being zero). In the first case return the output. In the second case finish the work without returning anything.
Tilemap generation
The simplest nontrivial case of the algorithm is when NxN=1x2 (well, NxM). If we simplify it even further by storing not the probabilities of pairs of colors but the probabilities of colors themselves, we get what we call a "simple tiled model". The propagation phase in this model is just adjacency constraint propagation. It's convenient to initialize the simple tiled model with a list of tiles and their adjacency data (adjacency data can be viewed as a large set of very small samples) rather than a sample bitmap.
Lists of all the possible pairs of adjacent tiles in practical tilesets can be quite long, so I implemented a symmetry system for tiles to shorten the enumeration. In this system each tile should be assigned with its symmetry type.
Note that the tiles have the same symmetry type as their assigned letters (or, in other words, actions of the
dihedral group D4 are isomorphic for tiles and their corresponding letters). With this system it's enough to enumerate pairs of adjacent tiles only up to symmetry, which makes lists of adjacencies for tilesets with many symmetrical tiles (even the summer tileset, despite drawings not being symmetrical the system considers such tiles to be symmetrical) several times shorter.
Note that the unrestrained knot tileset (with all 5 tiles being allowed) is not interesting for WFC, because you can't run into a situation where you can't place a tile. We call tilesets with this property "easy". Without special heuristics easy tilesets don't produce interesting global arrangements, because correlations of tiles in easy tilesets quickly fall off with a distance. Many easy tilesets can be found on Guy Walker's website. Consider the "Dual" 2edge tileset there. How can it generate knots (without tjunctions, not easy) while being easy? The answer is, it can only generate a narrow class of knots, it can't produce an arbitrary knot.
Note also that Circuit, Summer and Rooms tilesets are nonWang. That is, their adjacency data cannot be induced from edge coloring. For example, in Circuit two Corners cannot be adjacent, yet they can be connected with a Connection tile, and diagonal tracks cannot change direction.
Higher dimensions
WFC algorithm in higher dimensions works completely the same way as in dimension 2, though performance becomes an issue. These voxel models were generated with N=2 overlapping tiled model using 5x5x5 and 5x5x2 blocks and additional heuristics (height, density, curvature, ...).
Higher resolution screenshots: 1, 2, 3.
Voxel models generated with WFC and other algorithms will be in a separate repo.
Constrained synthesis
WFC algorithm supports constraints. Therefore, it can be easily combined with other generative algorithms or with manual creation.
Here is WFC autocompleting a level started by a human:
ConvChain algorithm satisfies the strong version of the condition (C2): the limit distribution of NxN patterns in the outputs it is producing is exactly the same as the distributions of patterns in the input. However, ConvChain doesn't satisfy (C1): it often produces noticeable defects. It makes sense to run ConvChain first to get a wellsampled configuration and then run WFC to correct local defects. This is similar to a common strategy in optimization: first run a MonteCarlo method to find a point close to a global optimum and then run a gradient descent from that point for greater accuracy.
P. F. Harrison's texture synthesis algorithm is significantly faster than WFC, but it has trouble with long correlations (for example, it's difficult for this algorithm to synthesize brick wall textures with correctly aligned bricks). But this is exactly where WFC shines, and Harrison's algorithm supports constraints. It makes sense first to generate a perfect brick wall blueprint with WFC and then run a constrained texture synthesis algorithm on that blueprint.
Comments
Why the minimal entropy heuristic? I noticed that when humans draw something they often follow the minimal entropy heuristic themselves. That's why the algorithm is so enjoyable to watch.
The overlapping model relates to the simple tiled model the same way higher order Markov chains relate to order one Markov chains.
WFC's propagation phase is very similar to the loopy belief propagation algorithm. In fact, I first programmed belief propagation, but then switched to constraint propagation with a saved stationary distribution, because BP is significantly slower without a massive parallelization (on a CPU) and didn't produce significantly better results in my problems.
Note that the "Simple Knot" and "Trick Knot" samples have 3 colors, not 2.
One of the dimensions can be time. In particular, ddimensional WFC captures the behaviour of any (d1)dimensional cellular automata.
Used work
 Alexei A. Efros and Thomas K. Leung, Texture Synthesis by Nonparametric Sampling, 1999. WaveFunctionCollapse is a texture synthesis algorithm. Compared to the earlier texture synthesis algorithms, WFC guarantees that the output contains only those NxN patterns that are present in the input. This makes WFC perfect for level generation in games and pixel art, and less suited for large fullcolor textures.
 Paul C. Merrell, Model Synthesis, 2009. Merrell derives adjacency constraints between tiles from an example model and generates a new larger model with the AC3 algorithm. We generalize his approach to work with NxN patterns of tiles instead of individual tiles. This allows to use a single image as the input to the algorithm. By varying N, we can make the output look more like the input or less. We introduce the lowest entropy heuristic that removes the directional bias in generated results, is defined for irregular grids and is better suited for preconstrained problems. We implement a tile symmetry system to reduce the sizes of inputs. We visualize partially observed states, either with color averaging or pervoxel voting. Merrell also introduced a method of incrementally modifying the model in parts to reduce the failure rate (which we don't use here). Recently the author created a page for model synthesis and published code.
 Alan K. Mackworth, Consistency in Networks of Relations, 1977. WFC translates a texture synthesis problem into a constraint satisfaction problem. Currently it uses the AC4 algorithm by Roger Mohr and Thomas C. Henderson, 1986.
 Paul F. Harrison, Image Texture Tools, 2005. WFC was also influenced by the declarative texture synthesis chapter of Paul Harrison's dissertation. The author defines adjacency data of tiles by labeling their borders and uses backtracking search to fill the tilemap.
How to build
WFC is a console application that depends only on the standard library. Get .NET Core for Windows, Linux or macOS and run
dotnet run configuration Release WaveFunctionCollapse.csproj
Alternatively, use build instructions from the community for various platforms from the relevant issue. Casey Marshall made a pull request that makes using the program with the command line more convenient and includes snap packaging.
Notable ports, forks and spinoffs
 Emil Ernerfeldt made a C++ port.
 Max Aller made a Kotlin (JVM) library, Kollapse. Joseph Roskopf made a line by line Kotlin port of the optimized 2018 version. Edwin Jakobs made a Kotlin library that supports 3d examples.
 Kevin Chapelier made a JavaScript port.
 Oskar Stålberg programmed a 3d tiled model, a 2d tiled model for irregular grids on a sphere and is building beautiful 3d tilesets for them: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15.
 Joseph Parker adapted WFC to Unity and used it generate skateparks in the Proc Skater 2016 game, fantastic plateaus in the 2017 game Swapland and platform levels in the 2018 game Bug with a Gun.
 Martin O'Leary applied a WFClike algorithm to poetry generation: 1, 2, 3, 4.
 Nick Nenov made a 3d voxel tileset based on my Castle tileset. Nick uses text output option in the tiled model to reconstruct 3d models in Cinema 4D.
 Sean Leffler implemented the overlapping model in Rust.
 rid5x is making an OCaml version of WFC.
 I published a very basic 3d tiled model so people could make their own 3d tilesets without waiting for the full 3d repository.
 I made an interactive version of the overlapping model, you can download the GUI executable from the WFC itch.io page.
 Brian Bucklew built a level generation pipeline that applies WFC in multiple passes for the Caves of Qud game: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22.
 Danny Wynne implemented a 3d tiled model.
 Arvi Teikari programmed a texture synthesis algorithm with the entropy heuristic in Lua. Headchant ported it to work with LÖVE.
 Isaac Karth made a Python port of the overlapping model.
 Oskar Stålberg made an interactive version of the tiled model that runs in the browser.
 Matt Rix implemented a 3d tiled model (1, 2, 3, 4) and made a 3dimensional tiled model where one of the dimensions is time (1, 2, 3, 4, 5).
 Nick Nenov made a visual guide to the tile symmetry system.
 Isaac Karth and Adam M. Smith wrote a paper (open access link) in which they examine the role of backtracking and different possible heuristics in WFC, experiment with global constraints and combine WFC with VQVAE. Earlier in 2017, the authors wrote a workshop paper where they formulate WFC as an ASP problem, use general constraint solver clingo to generate bitmaps, trace WFC's history and give a detailed explanation of the algorithm.
 Sylvain Lefebvre made a C++ implementation of 3d model synthesis, described the thought process of designing a sample and provided an example where adjacency constraints ensure that the output is connected (walkable).
 I generalized 3d WFC to work with cube symmetry group and made a tileset that generates Escheresque scenes.
 There are many ways to visualize partially observed wave states. In the code, color values of possible options are averaged to produce the resulting color. Oskar Stålberg shows partially observed states as semitransparent boxes, where the box is bigger for a state with more options. In the voxel setting I visualize wave states with pervoxel voting.
 Remy Devaux implemented the tiled model in PICO8 and wrote an article about generation of coherent data with an explanation of WFC.
 For the upcoming game Bad North Oskar Stålberg uses a heuristic that tries to select such tiles
that the resulting observed zone is navigable at each step.  William Manning implemented the overlapping model in C# with the primary goal of making code readable, and provided it with WPF GUI.
 Joseph Parker wrote a WFC tutorial for Procjam 2017.
 Aman Tiwari formulated the connectivity constraint as an ASP problem for clingo.
 Matvey Khokhlov programmed a 3d overlapping model.
 Sylvain Lefebvre, LiYi Wei and Connelly Barnes are investigating the possibility of hiding information inside textures. They made a tool that can encode text messages as WFC tilings and decode them back. This technique allows to use WFC tilings as QR codes.
 Mathieu Fehr and Nathanael Courant significantly improved the running time of WFC, by an order of magnitude for the overlapping model. I integrated their improvements into the code.
 Vasu Mahesh ported 3d tiled model to TypeScript, made a new tileset and visualised the generation process in WebGL.
 Hwanhee Kim experimented with 3d WFC and created/adapted many voxel tilesets: 1, 2, 3, 4, 5, 6, 7, 8.
 Oskar Stålberg gave a talk about level generation in Bad North at the Everything Procedural Conference 2018.
 I wrote about how to generate (approximately) unbiased paths between 2 points with WFC and other algorithms.
 Isaac Karth and Adam M. Smith published a preprint where they describe a system based on WFC that learns from both positive and negative examples, and discuss it in a general context of dialogs with exampledriven generators.
 Brendan Anthony uses WFC to generate wall decorations in the game Rodina.
 Tim Kong implemented the overlapping model in Haxe.
 In order to generate connected structures, Boris the Brave applied the chiseling method to WFC. He published a library that supports hex grids, additional constraints and backtracking.
 Marian Kleineberg created a city generator based on the tiled model for Procjam 2018. He wrote an article describing his approaches to setting adjacencies, backtracking and the online variation of WFC.
 Sol Bekic programmed the tiled model that runs on GPU using PyOpenCL. Instead of keeping a queue of nodes to propagate from, it propagates from every node on the grid in parallel.
 Wouter van Oortmerssen implemented the tiled model in a single C++ function, with a structure similar to a priority queue for faster observation.
 Robert Hoenig implemented the overlapping model in Julia, with an option to propagate constraints only locally.
 Edwin Jakobs applied WFC to style transfer and dithering.
 Breanna BaltaxeAdmony applied WFC to music generation.
 Shawn Ridgeway made a Go port.
 For the Global Game Jam 2019, Andy Wallace made a game in which the player can interact with WFCbased level generator by resetting portions of the level with various weapons.
 Stephen Sherratt wrote a detailed explanation of the overlapping model and made a Rust library. For the 7DRL Challenge 2019 he made a roguelike Get Well Soon that uses WFC to generate levels.
 Florian Drux created a generalization that works on graphs with arbitrary local structure and implemented it in Python.
 Bob Burrough discovered a percolationlike phase transition in one of the tilesets that manifests in spiking contradiction rate.
 Oskar Stålberg combined WFC with marching cubes on irregular grids and made a town building toy Townscaper based on it: 1, 2, 3, 4, 5, 6. Oskar gave a Q&A session about mixed initiative town generation in Townscaper at the Everything Procedural Conference 2021.
 In his Rust roguelike tutorial, Herbert Wolverson wrote a chapter about implementing the WFC algorithm from scratch.
 At the Roguelike Celebration 2019, Brian Bucklew gave a talk about WFC and how Freehold Games uses it to generate levels in Caves of Qud. The talk discusses problems with overfitting and homogeny, level connectedness and combining WFC with constructive procgen methods.
 Boris the Brave published a commercial Unity asset based on the tiled model.
 Steven Casey ported WFC to Java and Clojure.
 Nuño de la Serna implemented the 3d tiled model in an openFrameworks addon that supports tiles with no symmetries.
 Paul Ambrosiussen integrated the overlapping model into Houdini and gave a talk about the algorithm and his implementation at Houdini HIVE 2020.
 Keijiro Takahashi implemented a 3d tiled model and generated Escheresque scenes with it: 1, 2, 3, 4, 5.
 Simon Verstraete published a tutorial about generating game levels for Unreal Engine 4 using the Houdini WFC tool: 0, 1, 2, 3, 4.
 Élie Michel posted a twitter thread that explains the relationship between the overlapping and the tiled models.
 Lionel Radisson published an interactive Observable notebook that generates Mario and Zeldalike levels with the overlapping model: 1, 2, 3, 4.
 Łukasz Jakubowski, Maciej Kaszlewicz, Paweł Kroll and Stefan Radziuk implemented the tiled model in C.
 Ivan Donchevskii published a commercial Unreal Engine plugin based on the tiled model.
 Ján Pernecký and Ján Tóth published a Grasshopper plugin that extends the tiled model.
 Krystian Samp made a singlefile overlapping WFC library in C.
 Gerald Krystian made an interactive tool that explores the tiled model where tile adjacencies are induced from edge colorings.
 DeepMind openended learning team used WFC to generate arenas for reinforcement learning agents.
 Oskar Stålberg made an island generator that combines triangle and quad tiles and uses a custom observation heuristic that doesn't produce local minimums.
Credits
Circles tileset is taken from Mario Klingemann. FloorPlan tileset is taken from Lingdong Huang. Summer tiles were drawn by Hermann Hillmann. Cat overlapping sample is taken from the Nyan Cat video, Water + Forest + Mountains samples are taken from Ultima IV, 3Bricks sample is taken from Dungeon Crawl Stone Soup, Qud sample was made by Brian Bucklew, MagicOffice + Spirals samples  by rid5x, ColoredCity + Link + Link 2 + Mazelike + RedDot + SmileCity samples  by Arvi Teikari, Wall sample  by Arcaniax, NotKnot + Sand + Wrinkles samples  by Krystian Samp, Circle sample  by Noah Buddy. The rest of the examples and tilesets were made by me. Idea of generating integrated circuits was suggested to me by Moonasaur and their style was taken from Zachtronics' Ruckingenur II. Voxel models were rendered in MagicaVoxel.
Описание
Bitmap & tilemap generation from a single example with the help of ideas from quantum mechanics