Simulating Realistic Brushstrokes in Code: AI Painting Without Image Generation Models
This article explores an alternative approach to AI-driven image creation: instead of calling image generation models, a system plans painting actions and executes them programmatically on a virtual canvas. It covers how this approach differs from diffusion-based generation, a practical five-layer system architecture, how to represent strokes as executable data, the simulation mechanisms behind visual realism, visual feedback loops for error correction, engineering concerns such as performance, security, and reproducibility, and evaluation metrics that go beyond simply counting strokes.
1. From “Generating Pixels” to “Planning Painting Actions”
It is possible to produce an image programmatically without directly calling an image generation model: the model first converts the creative goal into a composition plan, then writes or generates painting instructions, which a program finally executes on a virtual canvas.
The key to this approach is not using code as a wrapper around an image file, but using code to describe the actual painting process. Where the brush starts, the path it follows, how stroke width varies, which colors are used, and how new paint blends with existing paint can all become explicit control targets.
As a result, the system’s output is no longer limited to the final image—it can also include the complete stroke sequence, canvas state changes, and execution logs. For developers, this means the painting process can be inspected, replayed, and modified. For enterprise applications, it offers a new implementation path for process auditing, interactive editing, and teaching demonstrations.
It is worth emphasizing that “not calling an image model” does not mean “using no image processing at all.” A painting program still needs rasterization, color blending, and image export. If the system is expected to automatically observe its work and adjust the next action, it also needs visual understanding capabilities, or auxiliary algorithms that can analyze image structure.
2. How Does It Differ from Common Image Generation Methods?
Common diffusion-based image generation starts from a noise state and gradually forms an image that matches the given conditions through multiple computation steps. The intermediate states primarily serve image synthesis and do not naturally correspond to the act of placing a brushstroke in human painting.
Code-driven painting, by contrast, treats “actions” as the primary unit of expression. Every stroke can carry information about its path, color, pressure, and order, and the image is the accumulated result of these actions.
The differences fall into three main areas:
2.1 Different Control Targets
Direct image generation mainly controls image content and its distribution; code-based painting can explicitly control stroke parameters and local operations. When adjusting a specific region, developers can modify the relevant strokes rather than regenerating the entire image.
However, explicit control does not automatically imply better semantic understanding. The model still needs to correctly understand object shapes, perspective, materials, and lighting—otherwise it simply executes a flawed composition with greater precision.
2.2 Different Traceability
In a code-based painting system, you can trace which strokes formed a particular colored region, or which operations were added by a specific correction.
This traceability is limited to the execution process; it cannot fully explain why the model chose a particular composition. In engineering terms, “auditable action logs” should be distinguished from “fully interpretable model decisions.”
2.3 Different Quality Bottlenecks
The quality of direct image generation depends on training data, model architecture, and inference settings. Code-based painting is additionally constrained by the expressive capacity of the painting engine.
Even with correct planning, if the engine can only draw uniform solid lines, it is difficult to express dry brush effects, paint impasto, or rough surfaces. Final quality therefore comes from the combined effect of planning capability, the execution engine, and feedback mechanisms—it cannot be attributed to the language model alone.
3. A Practical System Architecture
A system that is easy to develop and debug can be divided into five layers:
Creative Goal → Composition Planning → Stroke Instructions → Painting Engine → Image Evaluation
Evaluation results are fed back to the planning layer, forming an iterative loop.
3.1 Creative Goal Layer
Organize natural-language requirements into explicit constraints: subject, viewpoint, canvas size, lighting direction, color palette, and style.
“Make it realistic” is too vague. It is better to break it down into observable requirements: reasonable subject proportions, consistent perspective, unified shadow directions, and recognizable material features. This makes planning easier for the model and acceptance testing easier afterward.
3.2 Composition Planning Layer
First determine the subject’s position, background regions, and major light-dark blocks; then arrange the details.
A robust strategy is to work from the global to the local: lay down the background and large color blocks first, establish outlines, then add structure and materials, and finally paint highlights and fine textures. Investing in local details too early may cause the system to keep spending effort on an incorrect overall composition.
3.3 Stroke Instruction Layer
Represent painting actions with a constrained data structure rather than letting the model manipulate the runtime environment arbitrarily. This makes it easier to validate parameters, limit resource consumption, and locate errors.
3.4 Painting Execution Layer
The executor converts paths into color changes on the canvas, handling edge coverage, brush textures, opacity, and color blending.
3.5 Evaluation and Correction Layer
After completing a batch of strokes, the system generates a preview, checks composition, proportions, and color relationships, and then decides whether to continue refining. Check frequency requires a trade-off: checking too often increases feedback overhead, while intervals that are too long allow errors to accumulate.
4. Representing a Stroke as Executable Data
A stroke typically includes path points, width, color, opacity, brush type, and execution order. For richer expression, it can also include pressure variation, tilt direction, speed, or paint load.
The following is an illustrative data structure, not the interface of any existing service:
stroke:path_points = [(x1, y1), (x2, y2), ...]width = initial_widthcolor = three-channel color valueopacity = value within valid rangepressure_sequence = pressure values matching path sample positionsbrush_type = round, flat, or textured brush
During execution, the engine interpolates along the path and places a series of brush dabs at fixed distances. Adjacent dabs overlap to form a continuous stroke. Sampling that is too sparse produces gaps; sampling that is too dense increases the number of blends, making the result heavier than intended.
Paths do not have to be perfectly straight either. Bounded perturbation can break the mechanical feel, but its amplitude should relate to brush size and image scale. Adding random jitter unconditionally tends to produce noise rather than natural-looking strokes.
In addition, the coordinate system, color representation, and parameter ranges must be clearly defined. Illegal coordinates, excessive widths, or abnormal opacity values produced by the model should be rejected or normalized before execution—the painting engine should not be left to guess their meaning.
5. Where Does Realism Come From?
5.1 Brush Contact Shape
The simplest brush can be represented as a circular coverage area with edge falloff. More advanced options include directional dabs, sparse bristle distributions, or shapes that change with pressure.
The orientation of a flat brush affects edge morphology; dry brush effects require discontinuous coverage; fine pens focus on path smoothness and width variation. Different effects should come from corresponding mechanisms, not merely from switching colors.
5.2 Paint Coverage and Blending
A basic implementation can use alpha compositing, but this only approximates some painting effects and is not equivalent to real paint mixing.
To express wet-on-wet effects, the system can maintain simplified wetness and paint states: a new stroke blends to a limited extent when it meets a wet region, wetness decreases over time, and drier areas reduce diffusion. This is a visual approximation and should not be claimed as a full reproduction of the complex physics of real materials.
5.3 Canvas Texture
Canvas texture can do more than serve as a background—it can also influence paint deposition. The bumps and recesses of a rough surface change coverage, causing local discontinuities within the same stroke.
However, texture intensity must be moderate. If every region receives equally strong grain, the subject structure may be disturbed and materials will look uniform.
5.4 Lighting and Spatial Structure
Photorealistic appearance does not primarily depend on stroke count. Perspective, occlusion, contact shadows, reflections, and tonal layering usually matter more.
For example, when depicting a metal grid structure, if the perspective convergence of parallel lines is inconsistent, adding large numbers of fine lines will not produce a credible sense of space. Realism should therefore be established through geometry and lighting relationships first, and then enhanced with texture.
6. How Visual Feedback Helps the System Correct Errors
Code-based painting can iterate in an “execute a batch, check once” manner rather than outputting all actions at once.
Checks should focus on concrete questions:
- Has the subject drifted from its intended position?
- Are local proportions out of balance?
- Do the light-dark partitions support a sense of volume?
- Are outlines being swallowed by the background?
- Does the detail exceed what the current canvas resolution can express?
If the system supports undo, it can return to a checkpoint and re-execute a local plan. If the experiment requires that strokes cannot be undone once placed, corrections can only be made by appending strokes—covering over, thickening outlines, or reorganizing light and shadow.
These two modes should be clearly distinguished. An irrevocable constraint is closer to certain real painting situations, but it also raises the cost of correction. It does not automatically prove the model is better at painting; it only changes the decision conditions.
To avoid repeatedly correcting the same region, set a local modification budget and require each modification to state its goal. For example, “increase the brightness difference between the subject and the background” is easier to implement and verify than “make it look better.”
7. Performance, Security, and Reproducibility in Engineering
7.1 Don’t Make the Model Output Every Sample Point
A single stroke may require a large number of interpolated points. If all of these are generated by the model one by one, both text length and error probability increase.
A better approach is to have the model output a small number of control points and parameters, and let the executor handle interpolation, sampling, and brush-dab expansion. For regular textures, constrained procedural rules can also be used, but the rules and random seeds must be recorded.
7.2 Prefer Declarative Instructions
Having the model generate complete programs offers flexibility, but it can also introduce risks such as file access, network access, and resource abuse. Production environments should prefer a fixed executor plus declarative painting instructions.
When executing generated code is truly necessary, use an isolated environment that limits file permissions, network capability, memory, and runtime, and validate the dimensions and type of output files.
7.3 Build Reproducible State Management
The same stroke sequence does not necessarily produce pixel-identical results across all environments. Color blending methods, random numbers, engine versions, and numerical computation differences can all affect output.
Therefore, save the canvas configuration, stroke sequence, random seeds, engine version, and key checkpoints. When strict reproducibility is required, the execution environment and relevant computation rules should also be pinned.
7.4 Limit Local Computation Scope
When executing a new stroke, only its affected region needs to be updated, avoiding a full-canvas recompute each time. However, if the simulation includes paint diffusion or cross-region interactions, the update range must cover the corresponding effects—state consistency must not be broken for the sake of speed.
8. How to Evaluate Results—Not Just Count Strokes
Stroke count, code length, and demo video duration do not directly represent painting quality. Videos may be sped up, programs may unroll large numbers of actions through loops, and many tiny strokes may simply be redundant coverage.
More reasonable evaluation dimensions include:
- Content fidelity: Does the result accurately express the subject, scene, and composition requirements?
- Structural accuracy: Are proportions, perspective, and occlusion relationships reasonable?
- Visual expressiveness: Are materials, lighting, and brushwork coherent?
- Execution reliability: Are invalid instruction rates, failure rates, and state anomalies under control?
- Editing and reproducibility: Can local operations be located, the process replayed, and results stably reconstructed?
- Resource efficiency: Under comparable quality targets, how many planning rounds, execution time, and storage space are required?
Practical testing should also cover a variety of subjects, rather than judging system capability from a handful of successful cases. A single subject against a simple background places very different demands on planning and execution than complex perspective with multiple occluding objects.
9. Applicable Scenarios and Technical Boundaries
Code-driven painting suits tasks that emphasize the creative process, stroke control, and interactive modification—for example, painting instruction, process animation, procedural art, and auditable visual creation experiments.
If the goal is to quickly obtain a high-quality finished image of a complex scene, it may not be more efficient than direct image generation. The model may need multiple rounds of planning and checking, and the painting engine may be unable to fully express complex materials. The trade-offs among cost, latency, and realism should be determined through testing on actual tasks.
The core value of this technical route is transforming image creation from a finished product that cannot be directly edited into a set of actions that can be executed, recorded, and adjusted. A reliable solution should not stop at “the model can write painting code”—it should establish clear instruction specifications, a stable simulation engine, effective feedback mechanisms, and a verifiable evaluation system. Only when all of these elements come together can code-simulated brushwork move from demos to maintainable engineering practice.
