Code-Driven Stroke-by-Stroke Painting: Technical Paths and Engineering Practice

    This article examines the technical architecture and implementation challenges of code-driven, stroke-by-stroke painting engines—a generative approach that outputs executable brushstroke programs rather than pixel tensors. It covers system architecture, brush modeling, irreversible stroke planning, the observe-diagnose-correct loop, multi-agent coordination, and engineering best practices for building explainable and reproducible visual generation pipelines.

    From “Generating Pixels” to “Planning Actions”: A Shift in Problem Definition

    Common image generation approaches rely on diffusion models that progressively denoise random noise to produce a final image in one pass. The core output is a pixel tensor, and the generation process is effectively “implicit” in relation to the final image: the model never explicitly determines how each stroke is drawn, nor does it guarantee that the output is composed of interpretable painting actions.

    Procedural stroke-based painting redefines the problem as “action sequence planning.” Instead of outputting an image directly, the system produces an executable program or instruction stream that drives a virtual painting engine to simulate brush movements on a canvas. Each brushstroke includes parameters such as color, width, path points, wetness, and texture. Once applied, a stroke cannot be undone—it can only be corrected by subsequent strokes painted over it. This pipeline closely resembles human painting: plan the composition, apply strokes, observe the result, diagnose deviations, and keep refining.

    The value of this approach is not in replacing diffusion models, but in providing a visual generation method that is explainable, replayable, and auditable. Each artwork corresponds to a program; the sequence of strokes can be reproduced, and the correction process is observable. This makes it particularly suited for applications such as education, simulation, and robot action planning where process visibility matters.

    System Architecture: Virtual Canvas, Brush Models, and the Instruction Layer

    A usable procedural painting system typically consists of four layers:

    1. Canvas State Layer: Maintains pixel data, texture, wetness, and layers; supports stroke compositing and rendering feedback.
    2. Brush Model Layer: Abstracts physical brush properties such as width, color, path point jitter, bristle edge traces, and pigment spread.
    3. Instruction Planning Layer: Generates structured stroke instructions through a model, determining what to draw, in what order, with which brush, and where.
    4. Observation and Correction Layer: Renders the current canvas, diagnoses deviations from the target semantics, and generates corrective or supplementary strokes.

    A simplified pseudocode illustration:

    1. class Brush:
    2. width, color, wetness, texture
    3. path_points: list[Point]
    4. class Canvas:
    5. state
    6. def apply(stroke: Brush):
    7. # Composite the stroke and update canvas state
    8. pass
    9. def paint(goal, canvas):
    10. plan = planner.initial_plan(goal)
    11. for step in plan:
    12. obs = render(canvas)
    13. diag = diagnose(obs, goal)
    14. strokes = generator.generate_instructions(diag, step)
    15. for s in strokes:
    16. canvas.apply(s) # Strokes cannot be undone once applied
    17. return canvas, instruction_log

    The critical point lies in the “instruction layer” rather than the “pixel layer.” In documented cases, a high-fidelity artwork uses approximately 700,000 simulated strokes, with the generated program comprising roughly 1,000 to 2,000 lines. Another small scene was completed with only 111 strokes; the first stroke included a color value, a width of 90 pixels, and five slightly jittered path points. The approximately 7-pixel wobble was intentionally preserved because human arms cannot draw perfectly straight lines either. These details highlight that brush models must account for both geometric paths and hand-introduced uncertainty.

    Stroke-by-Stroke Planning Under the Irreversibility Constraint

    In real painting, paint cannot be deleted once applied—it can only be covered. If a procedural system strictly simulates this constraint, planning difficulty increases significantly: early stroke errors accumulate, and later corrections must be made through overpainting, thickening, or edge adjustments rather than simple rollbacks.

    The planner therefore requires a layered capability:

    • Composition Layer: Determines the subject’s position, proportions, occlusion relationships, and lighting direction.
    • Stroke Layer: Decomposes regions into executable stroke sequences, controlling width, direction, and wetness.
    • Correction Layer: Generates covering strokes based on rendered results, addressing edges, texture, and semantic deviations.

    Overpainting strategies must also avoid making things worse. For example, when an area is too thin or lines are chaotic, wider brushstrokes can be used to cover it, while retaining bristle traces at the edges to create a softer texture. If later lighting effects accidentally blur a desktop object, the local object needs to be redrawn rather than repainting the entire scene. This requires the system to maintain a mapping between local semantics and stroke history.

    The Observe–Diagnose–Correct Loop

    The core strength of procedural painting is not one-shot generation but closed-loop correction. After each batch of strokes, the system renders the canvas, compares the current result against the target description and spatial constraints, diagnoses deviations, and generates new instructions.

    This loop closely resembles robot control: perceive the current state, plan actions, execute, observe results, and correct. The difference is that the actions here are virtual brushstrokes, while robotic actions are physical end-effector movements. Both face similar challenges: irreversible actions, noisy state observation, and error accumulation over long tasks.

    Semantic constraints are especially critical. For instance, when the target requires two characters’ inner shoulders to touch while each uses the hand on the outer side of their body to paint, the system must first plan poses and occlusion relationships, then allocate stroke regions, and finally verify that the contact constraint is satisfied. If an arm occlusion error is detected, corrective strokes must be applied; pixels cannot be moved once painted. Such constraints push the system beyond visual similarity toward structural satisfiability.

    Long-Horizon Tasks and Multi-Agent Coordination

    Stroke-by-stroke painting is inherently a long-horizon task: stroke counts can reach hundreds of thousands, execution cycles are long, and local errors are frequent. To manage complexity, multi-agent coordination can be introduced: a planning sub-agent handles composition and stroke decomposition, an execution sub-agent generates instructions, a validation sub-agent checks rendered results against semantic constraints, and a coordinator merges outputs and resolves conflicts.

    This pattern generalizes to broader complex technical tasks: decomposing long-horizon objectives into verifiable subtasks, iteratively improving results through validation, and coordinating multiple sub-agents during execution. The engineering difficulties lie in state consistency, task boundaries, and conflict resolution. If sub-agents modify different parts of the canvas independently, versioned canvas states and instruction logs are required to ensure reproducibility and avoid overpainting conflicts.

    Engineering Challenges and Best Practices

    When building a procedural painting engine, the following points deserve attention:

    • Instruction Serialization: Record each stroke’s color, width, path points, wetness, and timestamp to guarantee replayability and auditability.
    • State Versioning: Snapshot canvas states by batch for diagnosis and comparison; provide “overpainting” rather than “undo” as the correction mechanism.
    • Rendering Feedback Frequency: Too high incurs overhead; too low accumulates errors. Adjust dynamically based on task complexity.
    • Quality Assessment: Beyond pixel similarity, incorporate structure constraints, stroke plausibility, and semantic satisfaction metrics.
    • Safety and Control: Restrict executable program permissions, isolate the rendering environment, and prevent loss of control in long-running tasks.
    • Explainable Output: Maintain stroke logs and diagnostic records so the creation process remains teachable and debuggable.

    Conclusion

    Code-driven stroke-by-stroke painting fundamentally transforms visual generation into an executable action-planning problem. Rather than relying on one-shot pixel output, it builds a “plan–execute–observe–correct” long-horizon pipeline through virtual canvases, brush physics, irreversible instructions, and closed-loop correction. For developers, this path offers an explainable and reproducible paradigm for visual generation. For enterprise users, it holds general reference value in simulation, education, robot demonstration, and complex task orchestration. Understanding the architecture and constraints matters more than chasing single-pass generation quality.