How Code-Based Painting Works: Technical Principles and Engineering Practices Behind Stroke-by-Stroke Generation

    This article explains how code-based painting differs from diffusion-based image generation, and why the distinction matters for engineers building stateful AI systems. Instead of denoising a pixel tensor in latent space, the model writes a program that defines the canvas, brushes, pigments, and blending rules, then emits structured stroke instructions one at a time. The article breaks down stroke modeling, the rendering engine that composites pigment into canvas texture, and how the model plans stroke sequences. It then covers the observe-verify-correct loop, including single-stroke quality checks, region-level error correction through overpainting rather than undo, and multi-round global consistency. Engineering challenges and mitigations are discussed for long-sequence stability, rendering throughput, and visual feedback precision. Finally, the article maps these techniques to long-horizon agent tasks and offers practical recommendations for developers adopting a generate-execute-observe-correct paradigm.

    1. From Pixel-Level Generation to Stroke-Level Execution: Two Fundamentally Different Routes

    Nearly all mainstream image generation approaches rest on the same underlying assumption: an image is a continuous pixel tensor, and the target distribution is recovered step by step from random noise through denoising, diffusion, flow matching, or similar mechanisms. The advantage is that the pipeline is end-to-end and requires no intermediate representation. The drawbacks are equally clear. The model itself has no notion of what it means to “make a stroke”: it has no brush, no pigment, no wrist trajectory, and no concept of covering a mistake with a new stroke. Everything happens in latent space, and all humans ever see is the final result.

    Code-based painting takes a completely different path. It reduces painting to a physical process. The model writes a program (typically one to two thousand lines) that defines the canvas dimensions, coordinate system, brush types, pigment properties, and blending rules, then outputs stroke instructions one by one. Each instruction is essentially a structured output containing coordinates, path control points, color values, brush width, pressure curves, wetness parameters, and more. A rendering engine receives these instructions, actually “lays down” each stroke on a virtual canvas, produces visible pixel changes, and feeds the result back as visual input for the next round of decisions.

    The difference between the two paradigms can be summarized as follows:

    Dimension Diffusion-Based Generation Code-Based Painting
    Output unit Pixels / latent variables Stroke instructions
    Intermediate representation None (end-to-end) Structured stroke sequence
    Reversibility Implicit (resampling) Explicit (a laid stroke cannot be undone)
    Error correction Regenerate Overpaint with new strokes
    Interpretability Low High (every step is readable)
    Compute cost Single forward pass Multi-round iteration, state-aware

    Understanding this split is the prerequisite for understanding every engineering detail that follows.

    2. Core Architecture: From Stroke Modeling to the Rendering Engine

    2.1 Stroke Modeling: Reproducing the Physics of a Real Brush

    The first layer of code-based painting is making strokes physical. The model cannot simply output “draw a line”; it must describe how that line was drawn. A complete stroke description typically includes:

    • Path information: start point, end point, and a sequence of control points. Slight offsets in the control points are deliberate. A human arm cannot draw a perfectly straight line, and a perfectly straight path actually looks mechanical. In practice, micro-jitter on the order of a few percent of a pixel is introduced into the control point coordinates so the line reads as naturally hand-drawn.
    • Brush type and width: round-tip, flat-tip, fan, and dry brushes produce very different textures. Width is declared in pixels and directly determines how much of the canvas the stroke covers.
    • Pigment properties: color value (such as a hexadecimal color), opacity, and wetness. Wet pigment produces softer edge diffusion on the canvas, while dry pigment preserves sharper bristle marks.
    • Pressure and speed curves: real brush pressure varies along a stroke, producing uneven thickness, and speed variation affects how much pigment is deposited. High-quality simulation defines, for each stroke, a function of pressure over the path parameter.

    2.2 The Rendering Engine: Canvas, Pigment, and Texture Interaction

    Stroke instructions need an engine to execute them. That engine is responsible for:

    1. Coordinate transformation: interpolating the model’s path control points into a continuous pixel trajectory.
    2. Pigment deposition simulation: computing the pigment coverage and blending mode at each pixel position based on brush type, pressure, and speed.
    3. Canvas texture overlay: a canvas is not a smooth plane; it has fiber texture and varying absorbency. The engine convolves or alpha-blends the stroke with the canvas texture so the pigment looks like it has soaked into the canvas rather than been pasted on top.
    4. History state maintenance: after each stroke lands, the canvas state updates and the new stroke blends against the current state. Strokes are therefore not independent; there is a strict temporal ordering dependency between them.

    A simplified stroke execution flow can be described with pseudocode:

    1. class Canvas:
    2. def __init__(self, width, height, texture):
    3. self.pixels = np.zeros((height, width, 3)) # RGB
    4. self.texture = texture # canvas texture map
    5. def apply_stroke(self, stroke):
    6. path_points = self._interpolate_path(
    7. stroke.start, stroke.control_points, stroke.end
    8. )
    9. for point in path_points:
    10. brush = self._build_brush_tip(
    11. brush_type=stroke.brush_type,
    12. width=stroke.width,
    13. pressure=stroke.pressure_at(point),
    14. color=stroke.color,
    15. wetness=stroke.wetness
    16. )
    17. self._composite(brush, point)
    18. def _composite(self, brush_tip, position):
    19. """Core: blend pigment within the brush footprint with existing canvas pixels"""
    20. region = self._extract_region(position, brush_tip.size)
    21. blended = mix_pigment(
    22. base=region,
    23. pigment=brush_tip,
    24. canvas_texture=self.texture,
    25. alpha=brush_tip.opacity
    26. )
    27. self._write_region(position, blended)

    The core idea here is that a stroke is not a block of color painted on top; it is a physical mixing event between pigment and canvas, and between pigment and existing pigment.

    2.3 Planning the Stroke Sequence: The Model’s Painting Strategy

    Once stroke modeling and the rendering engine are in place, the real difficulty shifts to how the model decides where the next stroke goes and with what parameters. This is a sequential decision problem, fundamentally different from conventional image generation:

    • Global composition planning: the model must first settle the overall layout, subject placement, and light direction, then decompose them into an executable stroke sequence.
    • Local-to-global progression: typically, large areas of base color go down first, local detail is refined step by step, and highlights and shadows are added last. This matches the human logic of working from major relationships to minor ones.
    • State awareness: after each stroke executes, the model needs to “see” the current canvas state and judge whether later strokes need adjustment. This requires visual understanding, with the rendered canvas image serving as input.

    3. The Key Capability: Observation, Verification, and Self-Correction

    The most striking property of code-based painting is that the model can look back at its work mid-process and correct it. This capability decomposes into three levels.

    3.1 Single-Stroke Quality Checks

    After executing a stroke, the model can observe its actual effect on the canvas and compare it against what was intended. If a smooth curve was expected but the render came out broken or excessively aliased, the model can judge whether the brush wetness was too low or the path control points were too sparse, and adjust parameters in subsequent strokes.

    3.2 Region-Level Error Identification and Overpainting

    When the result in some region deviates from the target, the model does not “undo” (a laid stroke cannot be undone) but plans new strokes to cover it. For example:

    • If the lines on a bird’s back are too thin and look messy, the model switches to a wider dry brush and covers the existing area at a slightly different angle. The edges of the covering stroke retain some of the old bristle marks, and this incomplete coverage actually produces a texture closer to fluffy feathers.
    • If lighting added later accidentally blurs the outlines of objects on a table, the model replans strokes and re-traces those edges with higher opacity and a narrower brush.

    This “cover rather than undo” correction mechanism forces the model to think like a real painter: how to fix an error with a limited budget of strokes without destroying work already done.

    3.3 Multi-Round Iteration for Global Consistency

    In more complex scenes, the model has to maintain global consistency across multiple rounds. In a dusk scene depicting two people interacting, for instance, the model must ensure their inner shoulders touch as the composition requires, while each figure paints with the hand on their outer side. Planning each stroke therefore means accounting not only for its local effect but also for its contribution to the overall compositional relationships.

    A simplified iterative painting loop looks like this:

    1. def paint_iteratively(model, canvas, prompt, max_strokes=500):
    2. stroke_history = []
    3. for step in range(max_strokes):
    4. # The model observes the current canvas + stroke history
    5. observation = canvas.render()
    6. next_strokes = model.plan_strokes(
    7. observation=observation,
    8. prompt=prompt,
    9. history=stroke_history
    10. )
    11. for stroke in next_strokes:
    12. canvas.apply_stroke(stroke) # cannot be undone
    13. stroke_history.append(stroke)
    14. # Decide whether to stop
    15. if model.should_stop(observation=canvas.render(), prompt=prompt):
    16. break
    17. return canvas.render()

    4. Engineering Challenges and How to Address Them

    4.1 Stability of Long- Sequence Output

    A high-complexity piece may require hundreds of thousands of stroke calls. Over long sequences, models tend to drift in their parameters, fall into repetitive patterns, or forget the semantics of the task. Common mitigations include:

    • Hierarchical planning: split the stroke sequence into coarse (composition layer), medium (object layer), and fine (texture layer) levels, each with its own context window, reducing the sequence length of any single generation.
    • Structured constraints: use a schema to constrain the range of stroke parameters (brush width must stay within a sensible interval, color values must conform to the color space), cutting down invalid output.
    • Checkpointing: take a global snapshot every so many strokes so the model can refer back to the early compositional intent in later steps.

    4.2 Rendering Performance and Stroke Throughput

    Rendering hundreds of thousands of strokes in real time puts heavy demands on the engine. Optimization directions include:

    • Batch rendering: merge strokes along a continuous path whose parameters barely change into a single render call.
    • GPU acceleration: stroke blending and texture overlay are highly parallel pixel operations, well suited to running on a GPU.
    • Incremental rendering: update only the region a stroke covers instead of repainting the whole canvas.

    4.3 Precision of Visual Feedback

    The model’s ability to observe depends on accurately understanding the render. If it cannot distinguish subtle texture differences at stroke edges, its correction decisions will be off. Practical improvements include:

    • Multi-scale observation: supply both a downscaled full-image view and high-resolution local crops, so the model can grasp the whole and inspect details at the same time.
    • Difference-map feedback: compute a pixel-level diff between the current canvas and a target reference (if one exists) or the expected stroke effect, exposing deviant regions directly.
    • Semantic annotation: overlay auxiliary layers on the canvas (outline strokes, region labels) to help the model locate exactly where correction is needed.

    5. Technical Kinship with Long-Horizon Agent Tasks

    Code-based painting may look like a creative task, but its underlying technical stack is largely isomorphic to long-horizon agent tasks. The core loop in both is: plan → execute → observe → verify → correct. The kinship shows up in several ways:

    1. Multi-step state management: whether painting a picture or completing a software project, an agent must maintain a state that evolves over time (canvas / codebase) and decide each step based on the current state.
    2. Handling irreversible actions: a laid stroke cannot be undone, just as some code commits, deployments, or physical actions cannot be rolled back. The agent has to learn to decide under constraints rather than assume free trial and error.
    3. Multi-agent coordination: a complex task can be decomposed into sub-goals handled by different sub-agents in parallel or in sequence. In a painting, sky, figures, and ground can be assigned to different sub-agents, with a main agent unifying style and lighting at the end.
    4. Repeated verification and convergence: much like the run-check-fix loop in software testing, the render-observe-overpaint loop in painting is a convergence process. The agent needs well-designed termination conditions to avoid endless correction or stopping too early.

    These are exactly the capabilities that carry large models from single-turn question answering toward long-horizon autonomous task execution. Models that can reliably execute hundreds of steps, correct themselves, and coordinate multiple agents have broad application space in software engineering, research assistance, physical simulation, and other fields.

    6. Practical Advice: Bringing This Approach into Your Own Project

    For developers who want to borrow this “code generation + state awareness + iterative correction” paradigm, the following suggestions may help:

    • Build observable intermediate state first: do not rely only on the final output. Design clear intermediate artifacts for every step (rendered images, logs, structured state snapshots) so the agent has something to look at.
    • Make constraints explicit: write the physical constraints of strokes (color ranges, brush widths, irreversibility rules) into code or a schema instead of hoping the model remembers them. Explicit constraints noticeably improve long-sequence stability.
    • Design a layered context strategy: for long-sequence tasks, manage context in layers by granularity to avoid overloading a single window.
    • Prefer differential feedback over absolute judgment: have the agent compare the current state against the target state rather than re-evaluating “how good is this” from scratch every time. Diff signals are usually more reliable and easier to optimize than absolute scores.
    • Accept the engineering reality of overpainting: in many real systems (database migrations, production configuration, physical device operation), undo is extremely costly or impossible. Rather than designing undo mechanisms, train agents to work under overpaint-style correction constraints.

    What code-based painting demonstrates is not just a new use of large models in creative work, but a technical paradigm worth taking seriously: turning a generation problem into an execution problem, and turning one-shot output into an observable, verifiable, correctable iterative process. When a model starts to work like an engineer, doing one step, looking once, and fixing one thing, its interface to the real world is no longer just text and pixels, but a complete loop of actions, state, and feedback.