Code-Based Brush Simulation: A Technical Guide to Programmatic Painting Without Image Models
This article explores an alternative to diffusion-based image generation: writing runnable code that paints on a virtual canvas stroke by stroke instead of calling an image model. It breaks down a four-layer architecture, a Stroke data structure for physical brush properties, a minimal rendering engine, and a draw-observe-correct feedback loop. It also covers artist-persona style constraints, engineering challenges at scale, a comparison with diffusion models, and practical steps for building your own code-driven painting system.
1. Background: Why “Letting a Model Write Code to Paint” Matters
In the public mind, AI image generation is almost synonymous with “call an image generation model, enter a prompt, and wait for the result.” Most mainstream approaches rely on diffusion models: the model gradually removes random noise in a latent space and finally decodes pixels. These methods are fast and produce strong textures, but the generation process is close to a black box for developers—it is hard to precisely specify “the 37th stroke should land at which coordinate, with how much pressure, and at what angle it should end.”
A recently discussed technical route offers a completely different idea: without calling any image model, have an AI coding tool (or a large model) write a runnable program that paints stroke by stroke on a virtual canvas. According to reports, Anthropic employee Jake Eaton demonstrated on X that Claude Fable 5.2, aiming to get “as close to photorealism as possible,” drew a shopping cart in a parking lot using roughly 700,000 simulated brush strokes; each image is essentially a 1000–2000 line Python program that controls different brush types through a simulated painting engine. In another experiment, the model drew a “bird at sunrise,” using 111 strokes from a blank canvas to completion. The first stroke used color #30346a, a 90-pixel width, and a path with 5 slightly jittering control points; the model explained that this roughly 7-pixel wobble was deliberate—“a human arm cannot draw an absolutely straight line either.”
The real value of this route is not “replacing diffusion models” but turning painting into a programmable, explainable, step-by-step debuggable engineering process. This article abstracts it into a general technical approach, discussing how to build a “stroke-level” drawing engine with code and let an AI coding tool handle planning and execution within it.
2. Core Idea: Rewriting “Pixel Generation” as “Instruction Sequence Generation”
Traditional image models output a final pixel matrix; programmatic drawing instead outputs a reproducible drawing program. The model does not produce the image directly but generates a large number of independent stroke commands, which the engine interprets and executes to render the image.
This paradigm brings three structural changes:
- Explainable process: every stroke has explicit geometry and material parameters, so errors can be traced to a specific instruction;
- Reproducible results: the same code with the same engine and random seed yields consistent output;
- Iterable style: changing stroke strategies, brush types, or color rules changes the overall style without retraining a model.
The whole system can be abstracted into four layers:
| Layer | Responsibility | Key Content |
|---|---|---|
| Intent planning layer | Decides “what to draw, in how many steps” | Scene decomposition, layer order, light and shadow strategy |
| Stroke generation layer | Produces coordinate-level instructions | Path points, speed, angle, pressure |
| Physical simulation layer | Computes realistic paint behavior | Brush deformation, wet diffusion, canvas texture |
| Rendering output layer | Composites the final image | Anti-aliasing, blend modes, color gamut mapping |
3. Stroke Modeling: Giving “One Stroke” Physical Properties
The core difficulty of programmatic drawing is defining “one stroke.” In real painting, a stroke contains multiple variables: direction, length, width, pressure, bristle distribution, water content, and pressing angle. In engineering, a structured object is usually used to describe it:
from dataclasses import dataclass, field@dataclassclass Stroke:color: str = "#30346a" # Color (hex)width: float = 90.0 # Base brush width (pixels)points: list = field(default_factory=list) # Path control points (x, y, t)pressure: list = field(default_factory=list) # Pressure sequence aligned with pointsjitter: float = 7.0 # Intentional jitter amplitude (pixels)brush_type: str = "flat" # Brush type: flat / round / fanwetness: float = 0.6 # Water content 0~1, affects edge diffusion
3.1 Path and Jitter
Absolutely straight lines barely exist in the real world. Adding small random perturbations to path points can significantly improve the “hand-drawn feel.” For example, the first stroke uses 5 slightly wobbling path points with an amplitude of about 7 pixels—this is not noise but a deliberate “humanizing parameter.”
3.2 Brush Texture
- Flat brush: suitable for large-area color fills and hard-edged structures;
- Round brush: suitable for soft transitions and volume shaping;
- Fan brush: suitable for hair, grass, and texture details.
Brush texture can be generated procedurally: overlay multiple thin bristle bundles along the brush width, each with an independent offset and opacity.
3.3 Paint Wetness
Wetness determines edge behavior:
def render_stroke(canvas, stroke, engine):wet = stroke.wetness# Higher wetness means more visible edge diffusion and slightly lower saturationradius = stroke.width * (1.0 + 0.25 * wet)alpha = 0.85 - 0.25 * wetfor p in stroke.points:engine.stamp(canvas, x=p[0], y=p[1],radius=radius, color=stroke.color, alpha=alpha)
3.4 Canvas Texture
A canvas is not an ideal plane. Low-frequency noise can simulate fabric or paper grain, slightly modulating colors during rendering so that strokes “bite into” the canvas rather than float above it.
4. A Minimal Drawing Engine Implementation
A minimal usable simulated painting engine needs only three steps: receive strokes → interpolate along the path → “stamp” or do vector fill on the canvas.
from PIL import Image, ImageDrawclass Canvas:def __init__(self, w=1024, h=1024, bg="#ffffff"):self.img = Image.new("RGB", (w, h), bg)self.draw = ImageDraw.Draw(self.img, "RGBA")def stamp_line(self, stroke):if len(stroke.points) < 2:returnpts = [(p[0], p[1]) for p in stroke.points]# Draw a semi-transparent polyline with width and color to simulate a strokeself.draw.line(pts, fill=stroke.color, width=int(stroke.width))def save(self, path):self.img.save(path)
A real system is far more complex: it needs to handle pressure curves, paint mixing (such as subtractive color approximation), layer blend modes, anti-aliasing, and supersampling. But the skeleton is always “instruction → interpretation → rasterization.”
5. Multi-Round Observation and Correction Loop
Another advantage of programmatic drawing over diffusion models is that it is iterable. The model does not output all instructions at once but uses a “draw—observe—correct” loop:
- Drawing phase: generate a batch of strokes and execute them;
- Observation phase: read a low-resolution version of the current canvas or statistical features (such as regional brightness and edge density);
- Diagnosis phase: determine what does not match expectations—the bird’s back is too thin, lines are messy, light and shadow relationships are wrong;
- Correction phase: add new strokes to cover or reinforce, rather than “undoing” old strokes (real painting cannot undo either).
def draw_with_feedback(model, engine, max_rounds=5):canvas = engine.new_canvas()for round_i in range(max_rounds):strokes = model.plan_next_strokes(canvas, round_i)for s in strokes:canvas.apply(s)critique = model.evaluate(canvas) # Observe the current imageif critique["done"]:break# Adjust the next round's stroke strategy based on critiquemodel.adjust_strategy(critique)return canvas
This mechanism lets the model “step back and look at the whole” like a painter, then return to local fixes. The reported experiment worked exactly this way: when the model found the bird’s back lines too thin and messy, it reshaped them with new strokes instead of repainting the whole image.
6. Style and “Artist Persona”: From Imitation to Self-Consistency
Some early AI artworks were criticized for over-imitating existing artistic styles. The programmatic route offers a new handle for style control: instead of imitating a reference image, define a self-consistent set of creative rules.
One approach is to have the model build an “artist persona”—setting fictional experiences, preferences, and constraints, and then deciding:
- A habitual palette (such as cool, low-saturation blue-greens);
- Stroke habits (long arcs, broken dots, dry-brush sweeps);
- Composition preferences (lots of negative space, low horizon line);
- Correction strategy (prefer layering over starting over).
Artist persona example:- Background: lived in a port city for many years- Color: prefers gray-blue and dark gold in morning mist- Strokes: mainly long arcs, shadows swept lightly with a dry brush- Taboos: no high-saturation primaries, avoid fully symmetrical composition
This “persona constraint” is essentially a set of executable heuristic rules that keep the output stable and recognizable in style across multiple creations.
7. Performance and Engineering Challenges
700,000 simulated strokes mean enormous computation and scheduling overhead. Engineering needs to focus on:
- Stroke scheduling: large numbers of small strokes need batching and parallel rendering to avoid blocking on each stroke synchronously;
- Intermediate state management: canvas snapshots, layer caches, and incremental rendering reduce repeated computation;
- Context length: the model cannot remember the entire stroke history at once and needs hierarchical summaries (global composition + local details);
- Determinism: fix the random seed to ensure reproducibility;
- Failure recovery: roll back to the latest snapshot when a stroke execution exception occurs.
When deployed in the cloud, such tasks typically combine container platforms (running the drawing engine and batch tasks), object storage (saving canvas snapshots and final works), message queues (decoupling stroke generation from rendering execution), and logging services with monitoring and alerting (tracking the progress and exceptions of long tasks). These are all general cloud capability categories, not tied to any specific vendor implementation.
8. Comparison with Traditional Image Generation Routes
| Dimension | Diffusion-based image generation | Code-simulated strokes |
|---|---|---|
| Output | Final pixels | Runnable drawing program + image |
| Process controllability | Weak (prompt level) | Strong (coordinate and parameter level) |
| Reproducibility | Depends on seed, details hard to control | Fixed code means fixed result |
| Iterative correction | Regenerate or locally repaint | Add strokes, natural continuation |
| Style stability | Affected by prompt and model drift | Locked by rule set and artist persona |
| Computational profile | GPU-intensive, single inference | Long pipeline, multi-round, state-intensive |
| Typical scenarios | Concept art, quick drafts | Controllable illustration, programmatic art, teaching demos |
It should be emphasized that the two routes are not replacements. Diffusion models excel at rapid “from-scratch” exploration; programmatic strokes excel at “precise control” and “process transparency.” In production, the former can be used for composition exploration first, then the latter for detailed painting.
9. Practical Advice: How to Build Your Own “Code Brush” System
If you want to reproduce or draw on this idea, proceed in the following order:
- Build the engine first, then talk about the model: implement a basic canvas, path interpolation, and brush stamping in 200–300 lines of code, ensuring stable rendering of simple shapes;
- Define a stroke protocol: unify the Stroke data structure so all generation logic only produces instructions and never manipulates pixels directly;
- Add physical details: prioritize jitter, pressure, and wet edges—these three improve the “hand-drawn feel” the most;
- Build a feedback loop: let the planner read canvas statistics (brightness histogram, edge density, regional color difference) and adjust strategy accordingly;
- Introduce style constraints: use rules or an “artist persona” to fix the palette and stroke habits, avoiding style drift between outputs;
- Ensure observability: log stroke counts, per-round timing, and correction reasons for easier debugging and optimization.
A typical execution skeleton is as follows:
def programmatic_paint(scene_desc, engine, planner):canvas = engine.new_canvas(width=1024, height=1024)strokes_log = []for round_i in range(MAX_ROUNDS):plan = planner.plan(canvas, scene_desc, round_i) # Produce stroke instructionsfor stroke in plan.strokes:canvas.apply(stroke)strokes_log.append(stroke)feedback = planner.review(canvas) # Observe and diagnoseif feedback.finished:breakreturn canvas, strokes_log
10. Conclusion: Painting Moves from “Generation” to “Orchestration”
The route of “not calling an image model, simulating a brush with code” reveals an important trend: when AI coding tools have sufficient planning and self-correction ability, visual creation can be viewed as an orchestration problem—orchestrating strokes, orchestrating materials, and orchestrating correction strategies. It turns the tacit experience of art creation into explicit parameters, making the process explainable, the style reproducible, and the result debuggable.
For developers, this is both a technical exercise and a product idea: any scenario requiring “precise, controllable visual output”—teaching demos, parametric illustration, artistic expression of data visualization, and schematic generation in industrial workflows—can borrow this “instruction sequence + physical simulation + feedback loop” architecture. More mature future systems are likely to be hybrid: use generative models to explore possibilities and a programmatic engine to lock in determinism and style.
