Code as a Brush: How Generative AI Drawing Programs Work and How to Engineer Them

    This article explores an alternative to end-to-end AI image generation: having a large language model write and execute drawing programs that place strokes on a virtual canvas. It explains the five-layer architecture (planner, stroke DSL, brush and paint simulation, renderer, and critic feedback), why stroke-level generation is harder but more controllable, and the key techniques for realistic brushes, color mixing, canvas texture, and observe-evaluate-revise loops. It also covers production concerns such as asynchronous task pipelines, cost and performance optimization, DSL validation and sandboxing, observability, evaluation metrics, common failure modes, and how this approach complements diffusion models rather than replacing them.

    Code as a Brush: How Generative AI Drawing Programs Work and How to Engineer Them

    1. The Problem: Turning “Generate an Image” into “Write a Drawing Program”

    Most recent discussions of “AI image generation” assume a single paradigm: you input a text description, and an end-to-end image generation model directly outputs a pixel matrix, leaving the user with a finished image. In engineering practice, however, a “dumber” but more controllable route is gaining renewed attention: instead of painting pixels directly, a coding assistant or large model writes and executes a drawing program that lays down strokes one by one on a virtual canvas, completing the work like a real painter.

    The core idea can be summarized in one sentence: the model outputs “actions,” not “results.” It breaks a painting into a large number of independent stroke instructions (starting position, control points, pressure, brush type, paint color and wetness, how the stroke ends, and so on), which a rendering engine executes one by one and composites onto the canvas. During the process, the model can “look back” at the canvas state, spot problems such as incorrect proportions, messy lines, or color drift, and then use new strokes to cover, deepen, or correct them.

    Compared with end-to-end image generation, this route has several notable differences:

    • Stronger explainability: every step can be traced to a specific instruction and rendering parameter, making debugging, replay, and auditing easier.
    • Stronger controllability: you can cap the total number of strokes, restrict brush types, and enforce “no undo,” approximating the physical constraints of real painting.
    • Iterative correction: it supports an “observe-evaluate-paint again” loop instead of a single forward pass that decides everything.
    • Style control: persona settings, constraint rules, and feedback mechanisms produce more stable creative output.
    • Different engineering cost: you need to build rendering and simulation capabilities (brushes, paint, canvas), but you do not depend on a large-scale image generation inference cluster.

    Of course, there are clear tradeoffs: longer generation time, potentially enormous stroke counts, greater sensitivity to prompts and feedback strategies, and a need for stronger process monitoring. The rest of this article focuses on how to turn this into a practical engineering capability.


    2. Overall Architecture: From “Model Generates Text” to “Engine Renders Images”

    A practical “code drawing” pipeline typically has five layers:

    1. Planner: the model understands the subject, composition, style, and constraints, and produces a drawing plan (for example, lay down large color blocks first, then outline, then add details).
    2. Instruction layer (Stroke DSL / API): the model outputs a structured sequence of stroke instructions. There are two common forms:
      • Calling a drawing library’s API (for example, combinations of paths, Bézier curves, layers, and filters);
      • A custom “stroke DSL” that is easier to constrain and validate (for example, allowing only a limited set of actions such as stroke, fill_region, blend, and texture_overlay).
    3. Simulation layer (Brush & Paint Simulation): simulates brush shape, bristle distribution, pressure and speed, paint viscosity/wetness, paper or canvas texture, drying, and color mixing.
    4. Renderer: rasterizes instructions onto the canvas, maintains layers, opacity, and blend modes, and outputs PNGs or frame sequences for video replay.
    5. Critic & Feedback layer: inspects the current image (composition, edges, color distribution, detail density), generates textual or structured feedback, and drives the next round of stroke planning.

    An illustrative instruction structure (pseudocode, emphasizing controllability):

    1. stroke = {
    2. "tool": "flat_brush", # Flat brush; an enumerated type to avoid uncontrolled model improvisation
    3. "color": "#30346a", # Color
    4. "width_px": 90, # Brush width
    5. "opacity": 0.85,
    6. "pressure": [0.2, 0.6, 0.4], # Pressure sequence (affects width and paint deposition)
    7. "points": [ # Path points (slight jitter can simulate a real hand)
    8. {"x": 120, "y": 80},
    9. {"x": 126, "y": 84},
    10. {"x": 131, "y": 89},
    11. ],
    12. "wetness": 0.55, # Paint wetness, affecting edge diffusion and mixing
    13. "blend_mode": "multiply", # Layer blend mode
    14. "layer": "bird_body",
    15. "undoable": False, # Real-painting constraint: a stroke cannot be undone
    16. }

    From an engineering standpoint, it is strongly recommended not to let the model output arbitrary executable code (both security and stability risks are significant). A safer approach is to have the model output only a constrained DSL/JSON, which the server parses, validates, and hands to a deterministic rendering engine; if you truly need to “write a program,” it should run in an isolated sandbox with limits on libraries, filesystem, network, and CPU/memory resources.


    3. Why Is “Stroke-Level Generation” Harder but More Controllable?

    1. Planning difficulty rises from “pixels” to “action sequences”

    An end-to-end model only needs to output an image once; stroke-level generation requires the model to have something like “motion planning” ability: what to draw first, what to draw later, how to layer, how to avoid muddy colors, and how to reach the target effect with a limited number of strokes. The stroke count can range from a few dozen to hundreds of thousands, and the model must maintain global consistency (proportion, perspective, light direction, uniform color temperature) across a large span of steps.

    2. Local errors are harder to “disappear automatically”

    Pixel models can “smooth out” many flaws in latent space; once a stroke model lays down a wrong stroke, if undo is not allowed, it must correct through covering, deepening, mixing, or repainting a region. This is closer to real painting, but it also demands stronger “diagnose-and-repair” ability: knowing where the problem is, which brush and color to use, and how to avoid over-layering that leads to muddiness.

    3. Controllability brings reproducibility and auditability

    Stroke instructions are naturally logs: every step can be replayed, compared, and located. This is especially important for enterprise scenarios, for example:

    • Design and asset production: requires traceable edit history and version management;
    • Education and training: requires breaking “how to draw” into explainable steps;
    • Content safety: policy checks can be done at the instruction layer (prohibiting specific symbols, color combinations, layer names, etc.);
    • Quality evaluation: metrics such as stroke count, coverage, color gamut distribution, and repeated-stroke ratio can be quantitatively monitored.

    4. Key Techniques: Making “Strokes” Actually Look Like Strokes

    1. Brush modeling: from “a line” to “a set of physical parameters”

    The visual characteristics of a real brush come from multiple coupled factors: number and distribution of bristles, paint held in the brush belly, splitting of the brush tip, deformation under pressure, and speed and pauses while moving. In engineering, this is usually abstracted as:

    • Shape core (stamp): periodically “stamps” along the path, forming a line through rotation, scaling, and opacity changes;
    • Bristle model: multiple bristles each with offset and stiffness, producing streaks and dry-brush effects;
    • Pressure curve: maps pressure to width, paint deposition, and edge sharpness;
    • Paint model: viscosity, wetness, and covering power determine diffusion, mixing, and drying speed.

    A simplified “jittered path” example (simulating that a real person cannot draw a perfectly straight line):

    1. def jitter_path(points, amplitude=7, seed=42):
    2. # amplitude ~= 7 pixels makes lines feel more human and avoids the "plastic" look of mechanical straight lines
    3. import random
    4. random.seed(seed)
    5. return [(x + random.uniform(-amplitude, amplitude),
    6. y + random.uniform(-amplitude, amplitude)) for x, y in points]

    2. Paint and color mixing: avoiding “getting dirtier the more you paint”

    When layers stack, the color mixing strategy determines whether the image stays clear. Common approaches include:

    • Linear interpolation/alpha blending: suitable for translucent glazing;
    • Multiply blending: suitable for shadows and stacking transparent colors;
    • Kubelka-Munk-based paint models: closer to real paint, but computationally heavier;
    • Wet edges and diffusion: local blur/anisotropic diffusion to simulate paint migration on a wet canvas.

    Engineering advice: make “mixing rules” a configurable policy set, and limit each layer’s opacity and number of overpaints to prevent the model from repeatedly stacking into dullness.

    3. Canvas texture: texture determines “whether it looks painted on paper or cloth”

    Canvas texture affects stroke edges, paint adhesion, and highlight reflection. Common implementations:

    • Height map plus a lighting model to produce bumps and texture;
    • Texture-modulated brush deposition: less paint on high spots, more in low spots, forming natural “hanging color”;
    • Paper/cloth noise: multi-scale noise overlay to avoid regular repetition.

    4. Observation and correction: building a “look-evaluate-fix” loop

    Having the model “observe the canvas” is typically implemented in engineering as follows:

    • Downsample the current canvas and crop key regions as multimodal input;
    • Combine deterministic image metrics (edge density, color histogram, local contrast) to generate auxiliary prompts;
    • Have the evaluator output a structured problem list (such as “the bird’s back is too thin,” “the outline is messy,” “the light source is inconsistent”), and the model plans corrective strokes accordingly.

    Note: do not rely on the model “feeling good about itself.” A more reliable approach is a three-layer mechanism of “rule checks + metric thresholds + model review” to reduce ineffective repeated strokes.


    5. Engineering Implementation: Stability, Cost, and Observability

    1. Productize the generation process

    It is recommended to package the capability as asynchronous tasks:

    1. The user submits subject, style, canvas size, stroke limit, and time limit;
    2. The task enters a queue and renders by stage (draft-block in-details-polish);
    3. Each stage produces thumbnails and metrics, and the user can abort or adjust parameters;
    4. On completion, output the final image, stroke log, replay video, and version records.

    2. Cost and performance

    The cost of stroke-level generation comes mainly from two parts:

    • Model side: multiple rounds of planning and review bring many inference calls;
    • Rendering side: compositing and texture simulation of hundreds of thousands of strokes can be very time-consuming.

    Optimization directions include: layered resolution (low-resolution draft first, then high-resolution details), stroke batching and vectorized rendering, hot-brush caching, GPU compositing, keeping only necessary snapshots for “no-undo” parts, and deduplicating and merging repeated strokes.

    3. Stability and security

    • DSL validation: field enumeration, range checks, prohibition of arbitrary code;
    • Sandboxed execution: if code generation is allowed, run isolated with resource and network limits;
    • Content policy: filter violating elements at the instruction layer and perform a safety review before rendering;
    • Observability: record each round’s plan, review conclusions, stroke statistics (count, coverage, average length, repetition rate), and failure reason categories.

    4. Evaluation system

    It is recommended to establish three categories of metrics:

    • Visual quality: structural reasonableness, edge sharpness, color gamut coverage, local contrast, noise/artifacts;
    • Process quality: total stroke count, average step length, rollback/overpaint ratio, repeated-stroke ratio, correction convergence speed;
    • Business metrics: generation time, failure rate, manual rework rate, cost per image.

    6. Common Failure Modes and Countermeasures

    • Composition drift: multiple rounds of detail stacking cause proportion imbalance. Countermeasure: lock key anchors (outline/perspective reference lines) and only allow refinement within the anchor neighborhood.
    • Messy lines: brush too small and jitter too large. Countermeasure: limit minimum brush width, reduce jitter amplitude, introduce smoothing constraints.
    • Muddy colors: repeated stacking and wrong mixing. Countermeasure: limit layer count and opacity, prefer glazing over impasto, introduce color gamut monitoring.
    • Excessive detail: strokes increase without bound with diminishing returns. Countermeasure: set a marginal-benefit threshold and stop and move to finishing once reached.
    • No-undo causing collapse: wrong strokes cannot be rolled back. Countermeasure: keep a “snapshot + local repaint” mechanism, or allow limited undo at the business level.

    7. Relationship with Diffusion-Based Image Generation: Not Replacement, but Complement

    Diffusion models excel at quickly producing visually appealing, atmospheric assets; stroke-level code drawing excels at controllable, traceable, editable processes and style consistency. In a real system, the two can be combined:

    • Use a diffusion model to produce composition sketches or color schemes (as “references” rather than tracing a base image);
    • Use the code drawing engine to complete an editable stroke layer, making later modification, layered delivery, and copyright auditing easier;
    • Use an evaluator to gate output uniformly, ensuring it meets business standards.

    8. Conclusion

    “Having a large model simulate a real brush with code” is essentially a paradigm shift from “result generation” to “process generation.” It translates invisible model inference into a visible, verifiable, replayable sequence of actions. For enterprises, the value of this route lies not only in “drawing realistically,” but also in being controllable, explainable, and integrable: it can plug into content production pipelines, support versioning and auditing, and enable fine-grained governance for different business constraints.

    If you want to build similar capabilities in your own business, you can rely on general cloud fundamentals such as “model serving + task queue + object storage + containerized rendering + logging and monitoring” to build an end-to-end pipeline, and turn the stroke DSL, rendering engine, and evaluation strategies into reusable assets. This keeps the technology neutral and portable while achieving a more robust balance among quality, cost, and compliance.