Simulating a Paintbrush in Code: How Procedural Brushstroke Painting Works and How to Build It

    Procedural brushstroke painting generates images as a sequence of explicit, replayable brushstroke instructions rather than a single denoised output. This article explains how to model brushes, paint, and canvas, how to structure paintings in layers, how to build an observe-and-correct feedback loop, and how to organize the engineering modules needed to make it work in practice.

    1. What Is Procedural Brushstroke Painting

    Procedural brushstroke painting is an approach in which a system does not generate a finished image in one shot. Instead, it outputs a series of brushstroke instructions, each containing path coordinates, pressure, color, brush width, and paint load. A painting engine then executes these instructions on a virtual canvas in sequence, and the final image is the accumulated result of those actions.

    This contrasts with how diffusion models typically work. A diffusion model starts from random noise and progressively denoises it until a complete image emerges, with an intermediate process that is hard to interpret. The stroke-based approach breaks creation down into a chain of readable, replayable, individually modifiable actions, where every step can be traced back to a specific stroke.

    This approach offers three main advantages: the process is interpretable, making it easy to locate errors; results are reproducible, since saving the instruction sequence is enough to redraw the image; and modification is cheap, because you only need to replace local strokes rather than recompute the entire image.

    2. Core Modeling: Brush, Paint, and Canvas

    To make strokes look like real painting, you need to model three types of objects separately.

    2.1 The Brush

    The brush determines the shape and texture of a stroke. Common parameters include:

    • Width: the diameter of the stroke on the canvas, usually measured in pixels.
    • Hardness: how abruptly the edges transition. A hard brush has crisp edges; a soft brush has edges that fade gradually.
    • Texture sampling: the bristle or grain shape of the brush, which produces detail by repeatedly stamping a pattern along the stroke path.

    In publicly reported cases, a single stroke used a 90-pixel-wide brush with roughly 7 pixels of random offset added along the path. This offset is intentional: a human hand cannot draw perfectly straight lines, and an ideally straight line actually looks mechanical.

    2.2 The Paint

    The paint model describes pigment load, wetness, and mixing behavior.

    • Load: the total pigment the brush carries. It decreases with each deposit, and once exhausted, strokes become faint or dry.
    • Wetness: wet paint spreads and blends with neighboring colors, while dry paint produces sharper boundaries.
    • Color mixing: color blending should be based on optical absorption and scattering rather than simple averaging. Simple averaging would mix blue and yellow into gray, which does not match how real pigments behave.

    2.3 The Canvas

    Canvas texture determines where paint settles. You can treat the canvas surface as a height map: recessed areas tend to hold more paint, while raised areas tend to show the underlying color. Only after the brush interacts with the canvas texture do you get broken, rough edges—the texture typical of real paintings.

    Here is illustrative pseudocode for stroke execution, showing the basic flow of deposition and blending:

    1. function paint_stroke(canvas, brush, path, paint):
    2. for segment in path:
    3. for sample in sample_along(segment, step = brush.spacing):
    4. tooth = canvas.texture_at(sample)
    5. deposit = brush.load * paint.density * (1 - tooth)
    6. canvas.blend(sample, paint.color, deposit, brush.width)
    7. paint.load = paint.load - deposit
    8. if paint.load <= 0:
    9. break

    Here, step controls sampling density. If the step is too large, strokes show gaps; if too small, computation grows quickly. In practice, the step is usually set to a small fraction of the brush width, such as one quarter.

    3. From a Single Stroke to a Full Painting: Layers and Planning

    Starting from the first stroke and painting stroke by stroke tends to produce a compositionally messy image. A safer approach is to plan first, then execute.

    3.1 Layered Painting

    A common layering order is:

    1. Base layer: lay in large background areas to establish the overall color tone.
    2. Blocking layer: paint the subject’s silhouette and major color masses to define the composition.
    3. Mid-shape layer: add structure, such as limbs, texture direction, and light-shadow boundaries.
    4. Detail layer: handle edges, small elements, and local contrast.
    5. Highlight layer: add the brightest points and reflections to enhance depth.

    The point of layering is error control. The first layers determine the big structure, and later layers only make local corrections, so even if a stroke turns out poorly, it will not overturn the whole composition.

    3.2 Composition and Stroke Sequences

    During planning, first determine the subject’s position, proportions, and focal point, then convert this information into a stroke sequence. For example, in a composition where the subject occupies one third of the canvas, you can start with a few wide strokes to establish the outer silhouette, then progressively tighten the details.

    3.3 The No-Undo Constraint

    One experimental setup requires that no stroke can be undone. This constraint forces the system to judge more carefully before each stroke, which is closer to real painting. In engineering terms, you can use overlay layers instead of undo: erroneous strokes remain in the lower layers and are corrected by subsequent strokes, while a complete history is recorded for later analysis.

    4. The Observe-and-Correct Loop

    Relying on one-shot planning rarely yields high-quality results. The key is to establish an “observe and correct” loop.

    4.1 Four Steps of the Loop

    1. Observe: render the canvas into an inspectable state, such as a thumbnail or region samples.
    2. Evaluate: compare against the target description or evaluation criteria and identify concrete problems, such as cluttered lines, unbalanced proportions, or colors that are too cool.
    3. Plan corrections: generate corrective strokes for each problem, specifying position, width, and color.
    4. Execute and record: apply the corrective strokes and save the instructions for replay and analysis.

    4.2 A Correction Example

    Suppose that in a bird painting, the lines along the bird’s back are too thin and look frail. A correction strategy would be to add a wider layer of covering strokes with reduced edge hardness, so the transition looks more natural. This step does not require repainting the entire bird—only the local region needs to change.

    4.3 The Control Loop

    1. while not satisfied(canvas, goal) and round < max_rounds:
    2. issues = critique(canvas, goal)
    3. for issue in issues[:3]:
    4. plan = plan_correction(issue)
    5. apply_strokes(canvas, plan.strokes)
    6. round = round + 1

    Limiting the number of issues processed per round and setting a maximum number of rounds prevents the loop from running indefinitely and keeps computation costs under control.

    5. Engineering Organization and Practical Advice

    A complete procedural painting system typically includes the following modules:

    • Canvas module: manages pixel buffers, texture height maps, and tiled rendering.
    • Brush module: defines brush shapes, textures, and parameter presets.
    • Paint module: handles load, wetness, and color mixing calculations.
    • Path module: generates stroke paths with controlled random perturbation.
    • Evaluation module: inspects the canvas state and outputs concrete problems.
    • Logging module: records every stroke’s parameters and execution order, supporting replay.

    In publicly reported cases, the drawing program for a single artwork was roughly 1,000 to 2,000 lines of code, with stroke counts ranging from 111 strokes to about 700,000 strokes. The program size mainly comes from parameter configuration and brush library organization rather than any single algorithm. The wide range in stroke counts shows that image complexity correlates directly with stroke density.

    A few practical recommendations:

    • Manage parameters centrally instead of hard-coding them, making batch tuning easier.
    • Use tiled rendering for large canvases and recompute only affected regions.
    • Save the complete instruction sequence for reproduction, comparison, and debugging.
    • Set quantifiable metrics for evaluation criteria to reduce reliance on subjective judgment.

    6. Use Cases and Limitations

    6.1 Suitable Use Cases

    • Teaching demos: showing how paint mixing and brush parameters affect the image.
    • Style experiments: exploring different visual styles by adjusting brush and paint parameters.
    • Digital painting assistance: providing stroke suggestions or automated underpainting for painting tools.
    • Interpretable generation: every image can be traced back to specific instructions, making review and modification easier.

    6.2 Limitations

    • The physical models are simplified approximations and cannot fully reproduce the behavior of real paint and paper.
    • Achieving photorealism requires extensive parameter tuning, which is costly.
    • Evaluating image quality partially depends on subjective judgment, making automated evaluation difficult.
    • Increasing stroke counts significantly raises computation, requiring a trade-off between quality and efficiency.

    If the system does not use external images as a base, the copyright risk from source material is reduced. However, you should still pay attention to the provenance of brush textures, color data, and reference material. When using public assets, verify the license terms and document them in your project.

    7. Suggested Adoption Path

    If you plan to introduce procedural brushstroke painting into your project, proceed in this order:

    1. Implement single-stroke execution and canvas deposition first, validating the basic behavior of brushes and paint.
    2. Add layered painting and confirm that the large structure can be generated reliably.
    3. Build observation and evaluation modules that output a quantifiable list of problems.
    4. Connect the correction loop, and limit the number of corrections per round and the total number of rounds.
    5. Polish logging and replay features to support later tuning and comparison.

    Validate each step on small-scale samples before scaling up to a full painting.