Procedural Painting with Code: Stroke Design, Rendering, and Engineering Practices

    Learn how to build a stroke-based painting system using serializable stroke data, controlled randomness, a rendering engine, and an observe-and-correct loop. This article compares procedural painting with diffusion models, explains the core Python structures, and covers reproducibility, stroke budgets, evaluation, and practical limitations.

    1. From Generating Images to Generating a Painting Process

    Most mainstream image generation systems focus on the final result: given a text description, a model produces a complete image. The process does not appear to the user as a sequence of deliberate painting actions.

    An alternative approach focuses on the painting process itself. It breaks an image into an ordered sequence of brushstroke instructions that a program executes on a canvas.

    The key difference is that the artwork becomes a readable, editable, and reproducible program rather than an opaque output. Each stroke has explicit coordinates, color, width, and wetness parameters. This makes the process easier to inspect and allows creators to adjust individual strokes.

    A publicly shared example illustrates this approach. Researchers at a large language model provider asked a model to create artwork entirely through code that simulated brush behavior, wet paint, and canvas texture. The process used no external image generation model and no prerendered or traced base image. One example depicted a bird at sunrise using 111 strokes, with a process video lasting about 21 seconds. The programs for individual artworks typically contained 1,000–2,000 lines of code.

    These figures highlight where much of the work lies: in the painting engine and stroke planning, rather than in a single rendering pass.

    2. Comparing Two Technical Approaches

    Procedural painting and diffusion-based generation differ in how they construct images, expose control, and support inspection.

    2.1 Diffusion Models

    Diffusion models begin with random noise and progressively produce an image through multiple denoising steps. Their strengths include modeling complex visual distributions, along with substantial engineering work on generation speed and visual richness.

    Their intermediate states, however, are difficult to interpret as deliberate drawing decisions. Local changes often require resampling or additional conditioning mechanisms.

    2.2 Procedural Brushstrokes

    A procedural painting system represents an image as an ordered set of drawing instructions. Each stroke records its path, color, brush parameters, and paint state.

    This approach offers several advantages:

    • Individual strokes can be inspected and adjusted.
    • The process can be reproduced under fixed rendering conditions.
    • Physical constraints can be explicit, such as making committed strokes irreversible.
    • The generated code serves as an auditable record of the creative process.

    The limitations are equally important. Visual quality depends heavily on the brush and paint models, while planning and rendering costs increase as the number of strokes grows.

    2.3 Choosing an Approach

    The two approaches are not mutually exclusive. Diffusion models are generally better suited to quickly generating visually rich images in different styles. Procedural brushstrokes are more useful when the priorities are process control, traceability, or the simulation of a particular physical medium.

    3. Designing the Stroke Data Structure

    A stroke is the basic unit of procedural painting. Its data structure should describe both geometry and material state.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Stroke:
    4. points: list # Path points, each represented as (x, y)
    5. color: tuple # RGB color tuple, with values from 0 to 255
    6. width: float # Brush width in pixels
    7. wetness: float # Range: 0–1; affects diffusion and edge softness
    8. opacity: float = 1.0 # Range: 0–1

    Three design choices matter here.

    First, the path uses discrete points rather than a continuous curve. These points are convenient to interpolate during rendering and adjust individually during planning.

    Second, wetness is an independent parameter. Wet strokes spread and develop softer edges, while dry strokes reveal more brush texture. Separating wetness from color allows the same color to behave differently under different material conditions.

    Third, every parameter should be serializable. This allows each stroke to be saved as a record for later inspection and replay.

    3.1 Adding Controlled Randomness

    Hand-drawn lines are rarely perfectly smooth. Small random perturbations can make a path feel less mechanically precise.

    1. import random
    2. def jitter_path(points, amplitude=2.0, seed=None):
    3. """Add Gaussian perturbations to simulate small hand movements."""
    4. rng = random.Random(seed)
    5. return [
    6. (x + rng.gauss(0, amplitude), y + rng.gauss(0, amplitude))
    7. for x, y in points
    8. ]

    The perturbation amplitude should match the brush size. Too much variation makes a line lose direction; too little has no visible effect. A fixed random seed makes the variation reproducible—a crucial distinction between controlled procedural variation and uncontrolled randomness.

    4. Core Modules of the Painting Engine

    The painting engine converts stroke instructions into pixels. A basic implementation has four main components.

    4.1 Canvas

    The canvas holds the current image state and maintains the list of committed strokes. Its central constraint is an append-only history: once a stroke is committed, it is not removed. Corrections must use additional strokes to cover or blend with existing paint.

    The following skeleton illustrates stroke-history management:

    1. class Canvas:
    2. def __init__(self, width, height, background=(245, 240, 230)):
    3. self.width = width
    4. self.height = height
    5. self.background = background
    6. self.strokes = [] # Append-only history
    7. def commit(self, stroke):
    8. """Record a committed stroke; do not modify or undo it afterward."""
    9. self.strokes.append(stroke)

    This constraint provides useful engineering properties. The history only grows, the rendered image can be reconstructed by replaying the stroke list, and debugging can identify exactly which stroke introduced a problem.

    4.2 Paint Mixing

    Paint mixing determines how overlapping colors interact. Basic alpha compositing works for opaque-paint approximations, while watercolor-like effects also need to account for wetness, spreading, and the visibility of underlying colors.

    Common practical rules include:

    • Use standard alpha compositing for opaque paint.
    • Blur edges and allow color bleeding for wetter strokes.
    • Use texture masks to simulate grain and broken coverage in dry strokes.

    These rules do not need to be physically exact, but they must remain consistent. Changing the mixing behavior across a painting can make the result look visually disjointed.

    4.3 Brush Texture

    Brush texture is implemented through masks. A mask determines which pixels receive paint, producing effects such as broken dry-brush marks or directional bristle patterns.

    Masks can come from noise functions or small, predefined procedural patterns. For a fully code-defined process, they should be generated from program parameters rather than external image assets.

    4.4 Rendering Loop

    The rendering loop processes the stroke list in order and composites each stroke onto the canvas. The loop itself is straightforward; most of the complexity lies in rendering individual strokes.

    At hundreds of thousands of strokes, consider tiled rendering or vectorized computation to manage the workload.

    5. The Observe, Evaluate, and Correct Loop

    A central benefit of procedural painting is its feedback loop. A planner applies strokes, observes the result, identifies problems, and decides what to paint next.

    1. def paint_loop(canvas, planner, evaluator, max_steps=500):
    2. for step in range(max_steps):
    3. snapshot = render(canvas) # Render the current canvas
    4. issues = evaluator(snapshot) # Identify the main issues
    5. if not issues:
    6. break
    7. strokes = planner(canvas, issues) # Plan corrective strokes
    8. for stroke in strokes:
    9. canvas.commit(stroke)
    10. return canvas

    This pseudocode separates three roles: rendering, evaluation, and planning. Evaluation guides the next correction by asking questions such as:

    • Are the contours clear and the proportions reasonable?
    • Do the color relationships support the overall palette?
    • Are local details too cluttered or too sparse?

    For example, a shape may have thin outlines that make the image look cluttered. Under an append-only constraint, the planner should add a thicker or darker stroke to clarify the contour rather than delete existing lines.

    5.1 Limits of Evaluation

    Evaluation is the hardest part of the loop to quantify. Goals such as near-photorealistic appearance depend on visual judgment and are difficult to automate completely.

    An engineering workflow can break evaluation into measurable signals, such as edge sharpness, statistical differences in color distributions, and local contrast, then supplement those signals with human review.

    6. Design Constraints and Engineering Practices

    The following practices apply to many procedural painting projects.

    6.1 Make Results Reproducible

    • Use fixed seeds for all random processes.
    • Save stroke sequences in a structured format such as JSON.
    • Record rendering parameters alongside the code version.

    Reproducibility is essential for debugging and auditing. If the same program produces different images across runs, problems become harder to isolate.

    6.2 Set a Stroke Budget

    Stroke count directly affects rendering time. Set a budget for each artwork and prioritize the regions with the greatest visual impact.

    Large background areas can be covered with a few broad strokes, while smaller brushes can add detail progressively.

    6.3 Organize the Image into Layers

    Separate the composition into layers such as background, subject, and detail. This helps isolate work on individual layers and makes the scope of corrections easier to manage.

    In an append-only workflow, layer organization should still respect the rule that committed strokes remain in the history.

    6.4 Define Quality Criteria Early

    Establish acceptance criteria before implementation begins.

    If the goal is a realistic appearance, agree on the evaluation method and human review process in advance. If the goal is stylistic consistency, define acceptable ranges for style parameters to prevent uncontrolled drift.

    7. Limitations and Risks

    Procedural painting is not a universal solution. Several trade-offs matter in practice.

    Development cost. Painting engines and brush models require dedicated design work. For a simple requirement, that investment may not be justified.

    Limited physical accuracy. Paint diffusion and texture are approximations, not substitutes for the full behavior of real materials.

    Stylistic convergence. Fixed brush parameters and planning rules can make different works look similar. Parameter variation and multiple style configurations can help reduce this effect.

    Subjective evaluation. Automated metrics cannot fully replace aesthetic judgment. Quality assessments should include human review.

    8. Conclusion

    Procedural painting shifts image generation from producing a final result to recording a creative process. Stroke data structures, rendering rules, and an observe-and-correct loop turn painting into a sequence of inspectable, reproducible steps.

    Compared with diffusion-based generation, this approach offers stronger control and interpretability, but it comes with significant development costs and limitations in visual realism.

    It is worth considering for projects that require transparent processes, controlled styles, or simulated physical media. Start by ensuring reproducibility, keeping stroke counts manageable, and defining quality criteria before building the full system.