Catalog · How the catalog works
wfc
wave function collapse algorithm
- ★ 12 on GitHub
Anyone may press Interesting, signed in or not. It helps others find this project.
README
WFC
Constraint-driven generation in Pascal, for Free Pascal Compiler (FPC) and pas2js. Describe values, their allowed relationships, and the layers that depend on them. Generate terrain, then roads, housing, and foliage—or apply the same principle to structures, music, text, and other discrete designs.
The original fluent API remains the center of the project. The portable implementation uses project-owned Pascal and the applicable compiler RTL; browser demos run compiled Pascal using standard browser APIs. The included FPC server hosts them locally.
Status: an expanding 0.x ecosystem, not a finished 1.0 release. The core supports deterministic propagation, weighted observation, backtracking, transactional pass DAGs, selective regeneration, and bounded pass negotiation. Count-range clauses, rooted port connectivity, and opt-in deterministic restarts extend those contracts without changing existing replay behavior. Domain libraries, learners, portable artifacts, native tools, and interactive browser demos have executable conformance fixtures. The roadmap records the remaining work and explicit exit gates.
Start here
| What you want | Where to start |
|---|---|
| Understand and author passes | Pass basics, dependency DAGs |
| Compose coarse and fine spatial layers | Mapped passes, Mapped World workbench |
| Require connected roads or circulation | Rooted port connectivity, training-source authoring |
| Require exact or bounded output quantities | Whole-pass value quotas, portable quota recipes |
| Build and run locally | Build guide, FPC development tools |
| Try an interactive demo | Demo table below, complete examples index |
| Learn models from examples | Learning, training documents and CLI |
| Learn cyclic text, rhythms or event patterns | Circular sequence training, Training Studio |
| Save and replay a pipeline | Portable recipes, runs, and results |
| Assemble independently authored or learned pipelines | Immutable fragment composition |
| Edit a bound pipeline and authorize repair | Preparation and input replacement, prepared sessions |
| Save edit history and restore a live workspace | Workspace journals, exact replay, atomic authoring and CLI |
| Edit arbitrary supported pipelines interactively | Pipeline Workspace, native artifact-generating host |
| Check or inspect saved work | Artifact-family validation, inspection, and exact replay |
| Check source-distribution assets and review status | Asset inventory and native checker |
| Extend or evaluate the system | Roadmap, research records |
A small pass-based program
This program generates land/water, then chooses a compatible foliage value at every coordinate. Each pass owns its own values and rules; foliage reads terrain through an explicit named requirement.
program TwoPasses;
{$mode delphi}{$H+}
uses SysUtils, wfc;
var
Graph: TGraph;
Options: TGraphSolveOptions;
Report: TGraphSolveReport;
begin
Graph := TGraph.Create;
try
Graph.Seed := 42;
Graph.Reshape(16, 12, 1);
Graph.WrapNeighbors := False;
Graph.CurrentPass := 'terrain';
Graph.PassMode := gpmOverlay;
Graph.AddValue('land');
Graph.AddValue('water');
Graph.SwitchToPass('foliage');
Graph.PassMode := gpmOverlay;
Graph.AddValue('grass').RequireFromPass('terrain', 'land');
Graph.AddValue('reeds').RequireFromPass('terrain', 'water');
Options := DefaultGraphSolveOptions;
if not Graph.TrySolve(Options, Report) then
raise Exception.CreateFmt('WFC failed in pass %d',
[Report.FailedPassIndex]);
WriteLn(Graph.PassGraph[0].Entry[0, 0, 0].Value);
WriteLn(Graph.PassGraph[1].Entry[0, 0, 0].Value);
finally
Graph.Free;
end;
end.Save this as TwoPasses.lpr. Once the native build below has created its
output directories, compile it with
fpc -Mdelphi -Fusrc -FUbuild/native/units -FEbuild/native/bin TwoPasses.lpr.
The build guide also covers isolated builds, FPM, and the
runtime-only Lazarus package.
Directional rules express same-layer adjacency. Named requirements can read the same coordinate, a signed offset, any matching declared neighbor, or an inclusive count range. Explicit modes distinguish matching offsets from distinct provider cells when wrapped offsets alias. Opt-in mapped passes give each layer its own integer world layout: coarse terrain, fine foliage, and larger building footprints can read exact points or every intersecting provider cell, including unique-cell count ranges. The Mapped World workbench lets you edit domains, locks, housing demands, and sampling on three fixed showcase grids. Its reproducible footprint study contrasts a clear corner with an interior blocker and demonstrates explicitly authorized upstream repair. The additive portable mapped pipeline extension keeps these concerns separate: recipes own per-pass topology and mapped policies, runs own independent extents, and results retain each layer's actual layout. The workbench's general layout editing and portable import/export UI remain open.
Pipeline composition combines complete authored or learned recipes with explicit names, preserving projection bridges, aliases, policies, topology, and resource provenance. It produces an immutable recipe; the caller supplies run extents and executes it through the existing runtime. The prepared-session API now adds immediate input edits, revision-bound explicit repair plans, cumulative pending requirements and complete detached solver/state evidence for one bound recipe. It keeps caller ownership and scoped reuse distinct from fresh invocation results. The workspace layer adds complete ordered journals, explicit epochs, exact replay and atomic edit/repair publication through shared Pascal APIs and an included FPC CLI. Imported journals remain unverified claims until their complete actual evidence replays. The separate Pipeline Workspace editor uses those APIs for complete recipe/run import, cell inputs, explicit scoped repair, journal restore/save and caller-defined mapped epochs. Its shared native host starts from real mixed-resolution or learned-sequence presets and exports canonical artifacts plus an exact selected-pass SVG. View windows do not limit composition size; format capacities, resources and solver feasibility still apply. The fixed Mapped World study and Ensemble Studio interfaces have not been migrated or replaced.
Ordinary solving follows prepare → solve → validate → commit. A failed
reference transaction restores its previous entries and random streams.
Selective regeneration reopens an explicit descendant
closure; negotiation may revisit complete upstream
assignments within a separate budget. Restarts retry local
backtrack exhaustion with versioned effective seeds. None implies a global
optimum, minimal edit, or a proof that every budget-limited model is impossible.
Demos
Standard demos use project-owned implementations and the applicable compiler RTL. The native and browser hosts share Pascal generation and validation code. The nine retained historical assets are not inputs to standard demo execution; their origin and redistribution documentation remains unresolved.
| Domain | Native presentation | Interactive pas2js demo |
|---|---|---|
| 2D worlds | Typed terrain, biome, foliage; settlement and repair examples | 2D Pass Workbench |
| Mixed-resolution worlds | Coarse terrain, fine foliage, inset housing; footprint inspection, scoped repair, shared SVG | Mapped World |
| Generic pipeline editing | Native preset/import host: user layouts, canonical recipe/run/journal, exact slice SVG; existing CLI continues history | Pipeline Workspace: drafts, cell inputs, scoped repair, epochs and verified restore |
| Learned 3D terrain | Learned volume → socket/support structure → spatial foliage; exact SVG | Learned Terraces |
| 3D buildings | Validated multi-floor geometry and deterministic SVG | Building 3D |
| Text | Structure → lexical → punctuation composition | Text Pass Workbench |
| Music | Score, MIDI, WAV, streamed arrangements, import/training tools | Music Studio |
| Polyphonic music | Synchronized chord-capable voices, training, repair, streamed audio and MIDI | Ensemble Studio |
| Independent musical roles | Learned role vocabularies, novel vertical combinations, collective harmony, streamed WAV/MIDI | Voice Studio |
| Training | Editable 1D/2D/3D corpora → models → recipes → validated results | Training Studio |
| Overlapping volumes | Joint XYZ learning, saved public constraints/replay, native cutaway SVG | Training Studio lattice preset |
| Pass counts | Lower/upper bounds, wrapped aliases, scoped repair | Neighborhood Counts |
| Connected routes | Solver-propagated roads and multi-floor circulation, independent BFS, SVG, scoped repair | Connected Routes |
Music Studio accepts user-defined composition duration and streams newly solved sections with bounded memory. There is no fixed minute cap; numeric capacity, storage, and local search constraints still apply. Its current streamed arranger remains monophonic. The separate ensemble libraries generate synchronized polyphonic scores and stream continued polyphonic segments and audio, with two-pass streamed MIDI, without retaining the whole composition. Finite preview and score adapters still have their own resource bounds. The musical-form planner adds bar-level form, harmonic-intent, and gesture passes. Ensemble Studio's developed profile uses them for question/answer/contrast/return phrases, with exact acoustic masks and an independently checked realization instead of extending one repeated bar. The optional native Ensemble download host streams user-selected-duration WAVE to ordinary browser downloads, including trusted-LAN clients without the direct browser file-system picker. The separate independent-voice libraries learn one chord-capable vocabulary per role and generate new vertical combinations under collective harmony, shared rhythm, ranges, and optional pair gaps. Their research record distinguishes the exact coverage proof from musical breadth and search-performance claims. See arrangements and MIDI import and selected-excerpt training.
The examples index includes exact commands, fixtures, additional console experiments, and the status of isolated legacy demos.
Build, test, and host
Run the checked native build and conformance suite:
.\build.ps1bash ./build.shBoth scripts preserve nonzero failure exits and place build output under
build/. The maintained gate covers the core, domain validators, learners,
artifact codecs, native tools, and console demonstrations. Portable
conformance sources also compile and execute in real browsers.
For example, build and host Music Studio using the included FPC server:
.\build-browser-music.ps1 -Compiler 'C:/path/to/pas2js.exe'
.\build\native\bin\wfc_serve.exe --root build/browser/music/www --port 4177The shell equivalents are bash ./build-browser-music.sh and
build/native/bin/wfc_serve --root build/browser/music/www --port 4177.
Set PAS2JS to your compiler path when it is not on PATH.
Open http://127.0.0.1:4177/; stop the foreground server with Ctrl+C.
The build guide covers the browser staging scripts, compiler versions and overrides, package builds, and CI. The development-tool guide covers the FPC server, browser completion capture, evidence checker, and browser conformance runner. Generated browser code is build output, not a second hand-maintained implementation.
Framework guides
| Area | Contracts and APIs |
|---|---|
| Solver and replay | Reference solver, determinism, restarts and timing |
| Pass composition and diagnosis | DAGs, counts, negotiation, selective negotiation, causal traces, streaming and bounded inspection |
| Learned representations | Cardinal models, 2D overlapping patterns, 3D overlapping volumes, sequences, training |
| Spatial domains | 2D worlds, mapped passes, voxels, learned terraces, Building 3D |
| Music and text | Exact music model, polyphonic ensembles, independent voices, audio, arrangements, import, text completion |
| Portable workflow | Pipeline artifacts, editable workspaces and exact history replay, validation and inspection tools, dependency policy |
The remaining work includes richer harmonic models, general voice-leading constraints, independently learned rhythm roles, larger spatial topologies, interactive domain/trace inspection, stronger repair strategies, more importers, and complete release/provenance tooling. Research claims must have reproducible fixtures and counterexamples; the current pass-negotiation baseline does not claim greater efficiency than an equivalent flattened model.
License
Project-authored source is under the MIT license. The standard runtime and demos use project-owned implementations and the applicable compiler RTL. The former external-engine and media-library demo integrations have been removed; see the dependency policy and examples index. The separate asset manifest and review guide records nine retained historical files without assigning them invented provenance or terms. Its byte check is not a legal-permission or release-readiness verdict.

