Code as a Brush: How AI Draws Stroke by Stroke, and Why It Matters

    This article breaks down an emerging approach in which a model writes drawing code and renders an image stroke by stroke instead of generating pixels in one pass. It explains the core mechanics—formal stroke instructions, approximate paint and canvas simulation, layered global planning, and a visual feedback loop for self-correction—along with engineering pitfalls such as context growth, error accumulation, reproducibility, cost control, and evaluation. It also shows how the same execute–observe–correct pattern generalizes to long-horizon AI agent tasks.

    1. The Technical Shift: From One-Shot Images to Explainable Process

    A notable capability demo works like this: instead of outputting a finished image, the model writes a drawing program and advances across a virtual canvas one stroke at a time until a textured picture emerges. It relies on no existing image generation model, uses no pre-rendered or traced base image, and the final artifact is essentially runnable code.

    This contrasts sharply with the mainstream image generation path. Mainstream approaches are typically based on diffusion models: starting from random noise, they perform multi-step denoising in latent space to produce a pixel matrix. Their strengths are image quality and generation speed, but the process is a holistic numerical optimization whose intermediate states carry no human-interpretable semantics. “Code drawing” instead decomposes painting into a large number of discrete, independent stroke instructions, with the model planning the execution order, colors, brush widths, and landing coordinates itself. The process can be printed, replayed, and debugged step by step.

    For developers, the value of this difference is not “whether it can draw a closer likeness,” but controllability and verifiability: every step has a clear input and output, errors can be traced to a specific instruction, results can be reproduced, and they can be checked and constrained programmatically.

    2. Core Mechanics: Four System Problems to Solve

    Making stroke-by-stroke drawing an engineering capability requires solving at least four classes of problems.

    2.1 Formalizing the Stroke Instruction

    The minimal executable unit is not a pixel but a stroke instruction. An instruction typically includes color, brush type and width, a sequence of path points, paint wetness, and post-landing behavior constraints. A sketch of the data structure:

    1. @dataclass
    2. class Stroke:
    3. color: tuple[int, int, int] # RGB color value
    4. brush_width: int # Brush width (pixels)
    5. brush_type: str # Flat, round, scattered bristles, etc.
    6. wetness: float # Paint wetness, 0.0~1.0
    7. points: list[tuple[float, float]]# Path control points
    8. jitter: float = 0.0 # Deliberately introduced slight wobble
    9. undoable: bool = False # Whether undo is allowed after landing

    The “non-undoable” constraint is worth noting. It forces the model to bear the consequences of its decisions like a real painter, and it means every later correction must be done by “covering” rather than “rolling back,” which matches the causal structure of a real physical process.

    2.2 Approximating Virtual Canvas and Paint Physics

    Realism comes mainly from three quantifiable simulation dimensions: brush texture (edge burrs caused by bristle distribution), paint wetness (which determines color mixing and bleed range), and canvas texture (surface relief causing uneven coverage). In engineering, this is usually approximated with discrete stepping: sample along the path at a fixed interval, generate a brush kernel with alpha falloff at each sample point based on brush shape and wetness, then blend it with the canvas buffer.

    1. def render(canvas, s: Stroke):
    2. for a, b in zip(s.points, s.points[1:]):
    3. for t in sample_steps(a, b, step=max(1, s.brush_width // 4)):
    4. x, y = lerp(a, b, t)
    5. x += noise() * s.jitter # Slight wobble
    6. y += noise() * s.jitter
    7. kernel = brush_kernel(s.brush_type, s.brush_width, s.wetness)
    8. canvas.blend(x, y, s.color, kernel)

    2.3 Global Planning: Composition First, Then Locals

    High-quality results are almost impossible to obtain by “random landing.” A workable approach is layered planning: the first layer fixes the composition and subject placement (a low-resolution layout), the second fixes large color blocks and light–dark relationships, and only the third layer moves into detail strokes. Each layer outputs only the minimal instruction set that layer needs, avoiding context being drowned by a lengthy history.

    2.4 Visual Feedback Loop and Self-Correction

    This is the most critical part of the whole scheme. After a number of strokes, the model “observes” the canvas again (usually by downsampling the canvas into an interpretable summary or image input), compares the target with the current state, and then decides the next step. Typical correction strategies include: when the subject is too thin, cover it with a thicker brush while keeping edge brush marks to simulate a fluffy texture; when a later lighting layer causes local blurring, redraw the affected objects; when occlusion relationships are wrong in a multi-subject scene, redraw to adjust pose and contact relationships.

    An interesting practical detail: the model deliberately adds a wobble of roughly a few pixels to “straight” lines, on the grounds that a real human arm cannot draw an absolutely straight line, and absolute straightness actually breaks realism. This shows that the objective function of realism modeling is not geometric precision but perceptual plausibility.

    3. Engineering Implementation and Common Pitfalls

    • Context bloat: Hundreds to thousands of instructions fill the context quickly. History should be compressed into a “canvas state summary + to-do plan” rather than a full replay.
    • Error accumulation: In non-undoable mode, early deviations get amplified by later strokes. It is advisable to keep a read-only sequence of historical snapshots for post-hoc analysis and regression testing.
    • Reproducibility: Only fixed random seeds and fixed rendering parameters guarantee that the same code produces the same image, which is critical for automated testing.
    • Cost control: A single piece may contain thousands of strokes and multiple rounds of observation, so inference and rendering costs add up noticeably; step limits and budget circuit breakers are needed.
    • Difficult evaluation: Pixel-level metrics poorly reflect “process plausibility,” so it is advisable to evaluate structural consistency, instruction validity rate, and correction convergence speed as well.

    4. Capability Spillover: This Is Really an Agent Execution Paradigm

    What is truly noteworthy about stroke-by-stroke drawing is that it validates a general paradigm: decompose a complex task into atomic actions, execute–observe–correct, and keep advancing under constraints. The same mechanism transfers directly to engineering tasks that are long-horizon, multi-step, and strongly verified, such as repository-level refactoring, configuration inspection, data pipeline repair, and scenarios requiring many subtasks to be coordinated in parallel.

    In related practice at Baidu AI Cloud, such long-horizon agent tasks typically need a supporting engineering foundation: a container platform to host parallel execution environments, object storage to hold intermediate artifacts and snapshots, a message queue for subtask distribution, and logging plus monitoring and alerting for process observability and failure localization. Managing the “process” as a first-class citizen is the key to taking this kind of capability from demo to production.

    5. Conclusion

    Simulating a brush with code and drawing stroke by stroke looks like a difference in generation method; in essence, it replaces unexplainable holistic generation with an explainable, constrainable, correctable action sequence. The takeaway for developers is direct: when a task is complex enough, rather than pursuing a perfect one-shot result, design the atomic actions, state feedback, and correction strategy well—the ceiling of a capability often depends on the quality of the loop design.