Code-Based Drawing with LLMs: Simulating a Paintbrush Instead of Generating Pixels
Most mainstream image generation treats the task as regression — recovering a target image from random noise. This article breaks down a different paradigm: the model outputs no pixels, but an executable drawing program that a deterministic renderer turns into lines and color patches. It covers how the two-stage planning/execution split works, how brush, pigment and canvas behavior get parameterized, how closed-loop feedback lets the model correct its own work, how stroke budgets keep the process convergent, and where this approach beats or loses to pixel-level diffusion — plus the engineering checklist for building it yourself.
Over the past two years, “model-generated images” has become the default entry point for generative AI. But while most mainstream approaches turn the problem into a regression task — recovering the target image from random noise — a different technical path is being validated: the model emits no pixels at all. Instead, it outputs an executable drawing program, and a rendering engine turns text descriptions, coordinate instructions and parameter settings into lines and color patches one stroke at a time. No image generation model is called, and no external reference image is needed. The model’s role shifts from painter to program author.
This article dissects that paradigm: how it works, which engineering problems must be solved, how its capability boundaries differ from traditional diffusion-based approaches, and what developers should watch for when evaluating and deploying it.
1. The paradigm shift: from emitting pixels to emitting programs
Traditional image generation rests on one core assumption: the final form of the image is determined by one (or several iterative) tensor transformations, and the model outputs a high-dimensional matrix the same size as the canvas. The advantage is high detail density and continuous color coverage. The drawbacks are that the process is opaque, the result is hard to edit, and it is difficult to control the exact position of any single line.
Code-based drawing splits the problem into two parts:
- Planning: the model decides what to draw, in what order, and the shape and color parameters of every stroke.
- Execution: a deterministic rendering program reads those parameters and lays down ink on a virtual canvas, stroke by stroke.
Decoupling these two stages yields a direct benefit: the output is explainable, intervenable and reproducible. The rendering stage is fully deterministic — the same stroke instructions executed repeatedly produce exactly the same image. If a stroke lands in the wrong place, you fix it at the instruction level instead of regenerating the whole image. This is also the fundamental reason the approach looks more like programming than generation.
The cost is equally clear: detail density is no longer free. A pixel-level approach fills the entire canvas in a single forward pass, whereas code-based drawing has to win on volume — decomposing a photorealistic image into tens of thousands, or even hundreds of thousands, of independent strokes. In one experiment referenced earlier, drawing a shopping cart in a virtual parking lot required roughly 700,000 simulated strokes in total, with the code running into the thousands of lines. Trading instruction count for realism effectively migrates compute from model parameters to execution count.
2. Modeling the stroke: parameterizing brush, pigment and canvas
To make code produce something that looks painted, the key is not color but the physical feel of the stroke. A reusable stroke model typically covers these parameter groups:
- Geometry: the path point sequence, brush width, tilt angle, terminal shape (flat / round / pointed), and the acceleration curve for stroke entry and exit.
- Medium: pigment viscosity, wetness, coverage opacity, whether colors are applied translucently, drying speed.
- Support surface: canvas texture (coarse linen, fine watercolor paper, smooth board), fiber absorption direction, pigment bleeding and buildup.
- Randomness: path jitter amplitude, pressure noise, edge roughness distribution.
There is a detail here that is easy to overlook but very valuable: perfectly straight lines actually look fake. In the experiment mentioned above, the model deliberately added a periodic oscillation of about seven pixels to a vertical line, on the grounds that a human arm cannot produce a perfectly straight trajectory. Injecting this kind of counterintuitive noise is the key step that takes code-based drawing from “usable” to “pleasant to look at” — it models physiological and physical imperfection explicitly as a feature of realism, instead of waiting for the renderer to add random noise.
Sketching the instruction structure of a single stroke in code looks roughly like this:
Stroke(points=[(x0, y0), (x1, y1), ..., (xn, yn)], # path control pointscolor="#30346a", # pigment colorbrush_width=90, # brush width (pixels)jitter_amplitude=7, # hand tremor / natural stroke jitterpressure_profile=[0.4, 0.6, 0.75, 0.5], # pressure from stroke entry to exitopacity=0.85, # pigment coveragewetness=0.6, # wetness, affects bleeding when overpaintingcanvas="rough_linen", # canvas texture type)
Once the parameter list grows long enough, the rendering engine is effectively a lightweight physical approximator: the contact area between the brush tip and the canvas determines the indentation, the remaining pigment determines color falloff, and the texture height field determines how pigment accumulates on raised areas. More parameters means a more expensive image, because compute and instruction length both grow.
3. Iterative correction: letting the model look at the canvas and revise
The real engineering difficulty is that the model writes instructions blind — it cannot predict the actual effect a stroke will have once it lands. Closed-loop feedback is therefore required, turning drawing from a single-pass generation task into a multi-round interaction:
- The model generates a batch of stroke instructions.
- The rendering engine executes them, producing an intermediate image.
- The model reads (or has described to it, in structured form) the current canvas state.
- It locates the deviation and outputs corrective strokes or adjusts the subsequent strategy.
The experiment mentioned earlier is a typical closed loop. After painting the bird’s back, the model found the lines too thin and the overall outline cluttered, so it added a number of strokes to deepen and tighten the structure. Three engineering points stand out:
- The no-undo constraint: once a stroke lands on the canvas it cannot be rolled back. This constraint is closer to real painting and forces stronger up-front planning from the model, but it also raises the quality bar for the first batch of strokes considerably.
- Asymmetric correction cost: adding a stroke is an additive, cheap operation; fixing a stroke usually means painting over and redrawing, which is expensive. The strategy should therefore lean toward “large shapes before small ones, structure before detail” — use low-precision, large strokes to establish composition and light/shadow relationships, then converge on detail with high-precision small strokes.
- The choice of feedback channel: feeding raw pixel images back to the model requires additional visual understanding capability. A cheaper option is to have the rendering engine emit a structured summary (current color block coverage, outline contrast, remaining stroke budget) and return it to the model as text. The latter is generally more controllable in both cost and stability.
The skeleton of a multi-step drawing loop can be written as:
canvas = Canvas(width=W, height=H, texture="fine_watercolor")engine = PaintEngine(canvas)for step in range(max_steps):strokes = model.plan(canvas.summary(), budget=strokes_left)if not strokes:breakfor s in strokes:engine.render(s) # stroke lands on the canvas, no undostrokes_left -= len(strokes)summary = canvas.summary() # observe the current canvas stateif quality_gate(summary):break
4. Stroke budgets and convergence control
Code-based drawing has no natural termination condition, so convergence must come from budgets plus a quality gate. Three resources are typically constrained at the same time:
- Stroke budget: an upper bound on total strokes, to prevent the model from falling into endless touch-ups.
- Code length budget: an upper bound on script lines, for maintainability (works from the experiment mostly ran to one or two thousand lines).
- Compute budget: a ceiling on rendering time, since total stroke volume directly determines render duration.
On top of these, a quality gate is layered in. Common evaluation dimensions include compositional completeness, whether the subject is recognizable, tonal layering, edge cleanliness, and an estimate of the marginal benefit of adding more strokes. A useful rule of thumb in practice: if the visual change from new strokes falls below the perceptual threshold, stop instead of continuing to pile on strokes. This controls cost and also prevents the image from becoming muddy through repeated overpainting.
5. Style and persona: stabilizing the stroke strategy
If realism is the only goal, the model easily slides toward an “average aesthetic.” A criticism raised in one public discussion was exactly this: some earlier drawing outputs stayed too close to existing artistic styles and lacked a recognizable identity. The fix is not to hard-code a list of painters into the model, but to externalize “style” as a set of stable creative constraints:
- Design a fictional artist persona, including training background, preferred media, favored color families and habitual brushwork.
- Express that persona as a stroke strategy (brush selection, pressure curves, jitter amplitude, color rules) rather than as adjectives.
- Tune it in small steps through natural-language feedback — for example “lower the saturation, add more dry side-brush strokes, reduce the level of detail” — and have the rendering engine map those descriptions onto concrete parameters.
The benefit is that style becomes controllable and reusable: the same persona should remain recognizably consistent across different subjects, and the tuning process is inherently auditable.
6. Capability boundaries and selection guidance
The applicability of this kind of approach has to be assessed objectively. It trades instruction volume for image precision, so in scenarios that need high-resolution texture, complex materials, natural lighting and human detail, cost and latency are clearly higher than for pixel-level generation. Conversely, in scenarios where the process must be explainable and the result needs fine-grained edits, it has a clear advantage.
A pragmatic rule of thumb:
- Favoring control and editability (diagrams, charts, geometric shapes, flat illustrations, engineering schematics, annotation images that need exact placement): prefer the code-based approach. Instructions are the version history, so modification cost is low.
- Favoring realism and material rendering (photographic images, skin and fabric detail): still hand this to pixel-level generation. Code-based drawing is only suitable here as a stylized supplement.
- Hybrid use: generate the structural layer and sketch with the code-based approach, then use pixel-level generation for detail rendering and material fill. This is the better cost-performance combination.
7. Engineering implementation checklist
To reproduce similar capability in your own system, several pieces need to be designed up front:
- Renderer first: build a deterministic renderer with complete parameter coverage and stable performance. The model side only produces parameters, which avoids coupling the two.
- Make stroke instructions a structured protocol: use fields rather than free text, so instructions can be validated, cached, replayed and diffed.
- Keep the feedback loop structured: compress canvas state into a readable summary to reduce uncertainty in the feedback channel.
- Long-running tasks and artifact management: stroke scripts and intermediate frames are classic batch artifacts; store them separately in object storage and version control. Let message queues and task schedulers handle task splitting and retries, and track render time and failure rates through logging and monitoring with alerting. Using generic cloud capabilities (object storage, message queues, container platforms, logging, monitoring and alerting) gives you stable elasticity and observability without locking into a specific implementation.
- Build an evaluation set: fix a set of prompts and stroke budgets, and periodically regress on image quality and render time, instead of relying on unverifiable conclusions like “it feels better.”
- Attribute cost to strokes: break each run into three metrics — planning tokens, render calls and correction rounds. Only then can you find the bottleneck actually worth optimizing.
Conclusion
Having the model write a drawing program instead of emitting pixels is fundamentally a redistribution of responsibilities: the model handles decisions and aesthetic judgment, the rendering engine handles physical realization, and the human handles feedback and tuning. It may never replace pixel-level generation, but in scenarios that require control, explainability and versionability, it offers a genuinely different engineering option. The key to understanding it is not asking “can it draw something photorealistic,” but “how do you decompose the act of drawing into a manageable instruction stream and a measurable quality loop.” That is the part of this methodology that is truly reusable.
