Skip to content

Claude paints with code: a Claude Code skill for procedural illustration in 83 styles, from ink wash (水墨), watercolour and ukiyo-e to stained glass, Roman mosaic, Art Deco, shadow puppets, pastel UI, sketchbook doodles, spot illustrations, grainy picture books, dreamy hills, sunlit greenery. No image model: numpy + Pillow on a CPU, draw-on GIFs.

Add watercolour and paper-collage styles; shared core

clovericcb19ec0216a0
diff --git a/README.md b/README.md
index c917ac0..bb8a923 100644
--- a/README.md
+++ b/README.md
@@ -1,19 +1,21 @@
# Claude Drawing · Claude 绘图
-**Claude paints with code — no image model.**
-**不用生图模型,Claude 用代码一笔一笔作画。**
+**Claude paints with code — no image model.** Ink wash · watercolour · torn-paper collage.
+**不用生图模型,Claude 用代码一笔一笔作画。** 水墨 · 水彩 · 剪纸拼贴。
[English](#english) · [中文](#中文)
-<p align="center">
- <img src="examples/drawing_bawansiqian.gif" width="720" alt="The painting being drawn stage by stage">
-</p>
+| Ink wash · 水墨 | Watercolour · 水彩 | Paper collage · 剪纸拼贴 |
+|---|---|---|
+| ![ink](examples/drawing_bawansiqian.gif) | ![watercolour](examples/drawing_watercolor_lotus.gif) | ![collage](examples/drawing_papercut_moon.gif) |
| 八万四千法门 · *Many paths, one summit* | 月印万川 · *One moon in ten thousand rivers* |
|---|---|
| ![bawansiqian](examples/bawansiqian.jpg) | ![moon_river](examples/moon_river.jpg) |
+| **一花一世界** · *A world in a flower* | **小沙弥看月亮** · *The little monk and the moon* |
+| ![lotus](examples/watercolor_lotus.jpg) | ![papercut](examples/papercut_moon.jpg) |
-Every mark above is computed: the rice-paper fibres, the layered mist mountains, the dry-brush strokes, the moss dots, the pine, the reeds and the vermilion sun. No diffusion model, no API, no stock art. Each 1920×1080 painting renders in **about 2–4 seconds on a CPU** from a few dozen lines of Python.
+Every mark above is computed: paper fibres, ink washes and mist, dry-brush strokes, pigment granulation and blooms, torn-paper edges, crayon wax and newsprint. No diffusion model, no API, no stock art. It is just Python with **numpy + Pillow** on a CPU: 2–4 s for an ink painting and about 20 s for watercolour or collage, at 1920×1080.
---
@@ -21,20 +23,26 @@ Every mark above is computed: the rice-paper fibres, the layered mist mountains,
### What it is
-A [Claude Code](https://claude.com/claude-code) skill plus a small painting library, `lib/inkpaint.py`, which needs only **numpy + Pillow**. Ask Claude to *"draw it yourself"*, *"paint this with code"* or *"claude绘图"*. Claude then does the following:
+A [Claude Code](https://claude.com/claude-code) skill and a small painting library with three styles:
-1. Plans a composition: far → near layers, a focal point, generous empty space, and one vermilion accent.
-2. Writes a short scene script using the library.
-3. Renders it, **looks at the result**, and fixes what is wrong using a built-in pitfall checklist, usually over 2–4 rounds.
+| Style | Module | What makes it read as the real medium |
+|---|---|---|
+| **Ink wash (水墨)** | `lib/inkpaint.py` · `Painting` | rice paper; occluding washes with wet rims and mist; bristle brush with flying-white; texture strokes (皴); moss dots; pines, boats, reeds; a moon reserved in white; calligraphy and seal |
+| **Watercolour** | `lib/watercolor.py` · `Watercolor` | cold-press paper tooth; *transparent glazes* that mix subtractively; wet-edge darkening; granulation; blooms (back-runs); wet-in-wet feathering; lifting; splatter |
+| **Paper collage** | `lib/papercut.py` · `Collage` | torn edges with a white fibrous core; paper depth shadows; coloured, kraft, crayon, newsprint and ruled-notebook papers; waxy crayon lines; cute faces with blush |
-The first built-in style is **Chinese ink wash (水墨)**.
+Ask Claude to *"draw it yourself"*, *"paint this with code"*, or *"claude绘图"*. It then works in three steps:
-### Why paint with code instead of an image model?
+1. **Plan the composition**: layers, a focal point, breathing space, one accent colour, and a subject that illustrates the idea rather than generic scenery.
+2. **Write a short scene script** using the library.
+3. **Render it, look at the result, and fix it** against a per-style checklist of real failure modes, usually over 2–4 rounds.
-- **Composition you can direct**: placement, empty space and colour accents are exact, not sampled.
+### Why code instead of an image model?
+
+- **Directed composition**: placement, empty space and accents are exact, not sampled.
- **Reproducible**: the same seed gives the same painting.
-- **Animatable**: `stage()` snapshots let a video show the painting *being painted* (distant hills → peak → paths → pine → sun), which a single generated bitmap can't do. See the GIFs.
-- **Runs anywhere**: offline, on a CPU, with no GPU, API key or quota.
+- **Animatable**: `stage()` snapshots let a video show the painting *being made*. The GIFs above are exactly that; a generated bitmap can't do it.
+- **Runs anywhere**: offline, on a CPU, with no GPU, key or quota.
### Install
@@ -43,66 +51,48 @@ git clone https://github.com/cloveric/claude-drawing-skill.git ~/.claude/skills/
pip install -r ~/.claude/skills/claude-drawing/requirements.txt # numpy, Pillow
```
-Titles and seals need a CJK font. macOS Kaiti/Songti, Linux Noto CJK and Windows KaiTi/SimSun are found automatically. You can also set `INKPAINT_FONT=/path/to/font.ttf`.
+Titles and notes need a CJK font. macOS Kaiti/Songti, Linux Noto CJK and Windows KaiTi/SimSun are found automatically; you can also set `INKPAINT_FONT=/path/to/font`.
### Quick start
```python
import sys; sys.path.insert(0, "lib")
-from inkpaint import Painting
-p = Painting(1920, 1080, seed=7)
-p.paper() # rice paper
-far = p.ridge(560, peaks=[(420, 150, 330), (1650, 110, 260)])
-p.wash(far, dens=0.16, decay=170, mist_y=700) # pale distant range
-main = p.peak(1130, 252, shoulders=[(1380, 70, 90)])
-p.wash(main, dens=0.46, decay=240, mist_y=920) # the main peak (occludes what's behind)
-p.cun(main, 530, 1730, shadow_x=1130) # dry texture strokes on the shadow side
-p.trails(main, (1130, 252), n=16, red_index=7) # winding paths to one summit
-p.mist(960, 70, 0.8)
-p.sun(1500, 190, 46)
-p.save("out.png")
+# ink wash
+from inkpaint import Painting
+p = Painting(1920, 1080, seed=7); p.paper()
+far = p.ridge(560, peaks=[(420, 150, 330), (1650, 110, 260)]); p.wash(far, dens=0.16, decay=170, mist_y=700)
+main = p.peak(1130, 252, shoulders=[(1380, 70, 90)]); p.wash(main, dens=0.46, decay=240, mist_y=920)
+p.cun(main, 530, 1730, shadow_x=1130); p.trails(main, (1130, 252), n=16, red_index=7)
+p.mist(960, 70, 0.8); p.sun(1500, 190, 46); p.save("ink.png")
+
+# watercolour
+from watercolor import Watercolor, hexc
+from core import blob_pts
+w = Watercolor(1920, 1080, seed=1); w.paper()
+w.gradient_wash(0, 540, top=hexc('#8fb0cf'), bottom=hexc('#f2cfae'))
+leaf = w.shape(blob_pts(900, 760, 260, 90, rough=0.1), soft=2.5)
+w.glaze(leaf, hexc('#a9c46b'), 0.75, edge=0.55, gran=0.35, bloom=1); w.save("watercolour.png")
+
+# paper collage
+from papercut import Collage
+c = Collage(1920, 1080, seed=2); c.background('#232d66', texture='kraft')
+c.piece(mask=c.circle_mask(1360, 300, 150), colour='#f6d77a', texture='crayon')
+c.face(1360, 310, 128, mood='sleep'); c.save("collage.png")
```
-Or run the examples:
+Full scenes: `python3 examples/<name>.py out.png --stages stages/`. `--stages` also writes the draw-on snapshots.
-```bash
-python3 examples/bawansiqian.py out.png --stages stages/ # also writes the draw-on stage snapshots
-python3 examples/moon_river.py moon.png
-```
+### Principles (the checklist Claude uses)
-### Toolkit
-
-| Call | What it paints |
-|---|---|
-| `paper()` | rice paper: mottled tone, grain, fibres |
-| `ridge()`, `peak()` | ridgelines: soft ranges, or an asymmetric main peak with shoulders |
-| `wash()` | an ink-wash mass under a ridge: dark edge fading down, texture, wet rim, mist, **occlusion** |
-| `stroke()` | the core brush: bristles, pressure taper, flying-white (飞白) dry breaks, wobble; ink or vermilion |
-| `cun()`, `moss()`, `ridge_line()` | texture strokes (皴), moss dots (苔点), a light broken ridge accent |
-| `trails()`, `mist()` | switchback paths to a summit; mist bands that swallow what's beneath |
-| `pine()`, `rock()`, `sun()`, `birds()`, `pagoda()`, `traveller()`, `dot()` | motifs |
-| `title_vertical()`, `seal()` | vertical calligraphy title and a vermilion seal |
-| `stage(name)`, `save(path, stages_dir)` | snapshots for draw-on animation, and the final output |
-
-Under the hood, every mark adds density to an ink buffer using pigment-style compositing, `D = 1 − (1−D)(1−a)`. The final image is the paper multiplied by the ink. Brushes are stamped bristle by bristle, with dab spacing tied to bristle size, so strokes never look beaded.
-
-### The pitfall checklist (what Claude checks before showing you)
-
-Things that went wrong while building this, and how they are fixed:
-
-- **Background ridges show through the peak** → paint far to near, and let each wash occlude what is behind it.
-- **Strokes look like ladders or beads** → dab spacing is tied to bristle size.
-- **Paths look like hair** → use fewer paths, smooth them with a Catmull-Rom spline, and keep them on the mountain so they emerge from the mist.
-- **Texture strokes look like scattered commas** → use fewer, longer strokes that follow the slope, mostly on the shadow side.
-- **The ridge reads as a cartoon outline** → keep the ridge line light and broken, and let the wash's wet rim carry the edge.
-- **Pine needles look like sea urchins** → use fan-shaped tufts over a soft wash.
-- **The image feels heavy** → keep at least 40% empty space and use vermilion only once or twice.
+- **Ink**: paint far to near, and each wash occludes what is behind it. Tie dab spacing to bristle size so strokes never look beaded. Paths should be few, smooth and emerge from mist. Texture strokes should be long, follow the slope and sit on the shadow side. Ridge lines stay light and broken.
+- **Watercolour**: keep the paper tooth subtle. Pool shadows wet-in-wet on one side (no bull's-eyes). Paint stems before leaves and keep them outside the leaf. Use at most three glazes in one place, and save lights or lift them out.
+- **Collage**: big areas use flat or kraft paper, and crayon texture is only for accents. Torn white rims are 5–8 px wide and appear on only part of an edge. Shadows use a zero-padded shift, never a wrap-around one. A moon gets a halo, not sun rays.
### Roadmap
-- More styles on the same brush/paper/wash core: watercolour, and torn-paper collage.
- Per-stroke layer export, for stroke-by-stroke animation in Motion Canvas or Remotion.
+- More styles on the same core, such as gouache, woodblock print and pencil sketch.
---
@@ -110,19 +100,25 @@ Things that went wrong while building this, and how they are fixed:
### 这是什么
-一个 [Claude Code](https://claude.com/claude-code) skill,加上一个小巧的绘图库 `lib/inkpaint.py`,只依赖 numpy + Pillow。对 Claude 说「claude绘图」「你自己画」「用代码画」,它会:
-1. **先定构图**:远中近层次、视觉焦点、大片留白、一处朱红点睛;
-2. **写一段场景脚本**,调用绘图库;
-3. **渲染并自己看图**,对照内置的毛病清单挑问题,一般改 2–4 轮。
+一个 [Claude Code](https://claude.com/claude-code) skill,加上一个小巧的绘图库,内置三种画风:
-目前内置并打磨过的画风是**中国水墨**。
+| 画风 | 模块 | 为什么看起来像真的 |
+|---|---|---|
+| **水墨** | `lib/inkpaint.py` · `Painting` | 宣纸纹理;会遮挡身后的墨染山体,带水痕边和雾;分笔毛的毛笔与飞白;皴擦、苔点;松、孤舟、芦苇;烘云托月的留白月亮;题字与印章 |
+| **水彩** | `lib/watercolor.py` · `Watercolor` | 冷压水彩纸纹理;**透明罩染**,叠色像真颜料一样变深、混色;水痕边;颜料颗粒;水渍花;湿画晕开;提白;甩点 |
+| **剪纸拼贴** | `lib/papercut.py` · `Collage` | 撕纸露出的白色纤维边;纸片层叠的阴影;彩纸、牛皮纸、蜡笔、报纸、笔记本横线纸;蜡笔线条;带腮红的可爱圆脸 |
+
+对 Claude 说「claude绘图」「你自己画」「用代码画」,它会:
+1. **先定构图**:层次、焦点、留白、一处点睛色,而且画面要图解内容本身,不是随便一幅风景;
+2. **写一段场景脚本**,调用绘图库;
+3. **渲染并自己看图**,对照该画风的毛病清单修改,一般改 2–4 轮。
### 为什么用代码画,而不用生图模型
-- **构图可控**:位置、留白、朱红点在哪里都精确可控,不靠抽卡。
+- **构图可控**:位置、留白、点睛色都精确可控,不靠抽卡。
- **可复现**:同一个随机种子,画出同一幅画。
-- **能做「作画过程」动画**:用 `stage()` 按「远山 → 主峰 → 小路 → 松石 → 朱日」存下每一步,视频里就能看到画被一步步画出来(见上面的动图)。生图模型只能给一整张画。
-- **哪里都能跑**:离线、只用 CPU,不需要显卡、API Key 或额度;一张 1920×1080 只要 2–4 秒。
+- **能做「作画过程」动画**:用 `stage()` 存下每一步,视频里就能看到画被一步步画出来。上面的动图就是这样做的,生图模型只能给一整张画。
+- **哪里都能跑**:离线、只用 CPU,不需要显卡、API Key 或额度。
### 安装
@@ -131,47 +127,29 @@ git clone https://github.com/cloveric/claude-drawing-skill.git ~/.claude/skills/
pip install -r ~/.claude/skills/claude-drawing/requirements.txt # numpy、Pillow
```
-题字和印章需要中文字体。macOS 的楷体/宋体、Linux 的 Noto CJK、Windows 的楷体/宋体都会自动找到,也可以用 `INKPAINT_FONT=字体路径` 指定。
+题字和纸条需要中文字体。macOS 的楷体/宋体、Linux 的 Noto CJK、Windows 的楷体/宋体都会自动找到,也可以用 `INKPAINT_FONT=字体路径` 指定。
### 快速上手
-见上方英文部分的代码示例,或直接运行两个范例:
+三种画风的最小示例见上方英文部分的代码。完整范例:
```bash
-python3 examples/bawansiqian.py out.png --stages stages/ # 八万四千法门,同时输出分阶段快照
-python3 examples/moon_river.py moon.png # 月印万川
+python3 examples/bawansiqian.py out.png --stages stages/ # 水墨:八万四千法门
+python3 examples/moon_river.py out.png # 水墨:月印万川
+python3 examples/watercolor_lotus.py out.png # 水彩:一花一世界
+python3 examples/papercut_moon.py out.png # 剪纸:小沙弥看月亮
```
-### 工具箱
+### 作画要点(Claude 交图前逐条自查)
-| 调用 | 画什么 |
-|---|---|
-| `paper()` | 宣纸:底色斑驳、颗粒、纤维 |
-| `ridge()` / `peak()` | 山脊线:远山起伏,或不对称、带山肩的主峰 |
-| `wash()` | 墨染山体:上浓下淡、纹理、水痕边、雾气,并**遮挡身后的层** |
-| `stroke()` | 核心毛笔:分笔毛、提按粗细、飞白、抖动;可用墨色或朱红 |
-| `cun()` / `moss()` / `ridge_line()` | 皴擦、苔点、淡而断续的山脊线 |
-| `trails()` / `mist()` | 汇向山顶的蜿蜒小路;雾带(会吞没下方已画的东西) |
-| `pine()` / `rock()` / `sun()` / `birds()` / `pagoda()` / `traveller()` / `dot()` | 松、石、日、飞鸟、小塔、行人、点 |
-| `title_vertical()` / `seal()` | 竖排题字、朱红印章 |
-| `stage(名字)` / `save(路径, stages_dir)` | 分阶段快照(做动画用)、输出成品 |
-
-原理:每一笔都往「墨量」缓冲里叠加,叠加方式模拟颜料,`D = 1 − (1−D)(1−a)`,最后用宣纸底色乘上墨色得到画面。毛笔按一根根笔毛盖章式落墨,落笔间距跟笔毛粗细挂钩,所以笔画不会一节一节的。
-
-### 毛病清单(Claude 交图前逐条自查)
-
-- 后面的远山透过主峰 → 先远后近,每层墨染都遮挡身后的层
-- 笔画像梯子、像串珠 → 落笔间距跟笔毛粗细挂钩
-- 小路像头发丝 → 条数少一些,用样条曲线平滑,只画在山体上,从雾里伸出来
-- 皴擦像撒了一片逗号 → 少而长,顺着坡向,集中在阴面
-- 山脊像卡通描边 → 山脊线要淡而断续,边缘主要靠墨染的水痕
-- 松针像海胆 → 扇形松针,下面垫一团淡墨
-- 画面发闷 → 留白至少四成,朱红最多一两处
+- **水墨**:先远后近,每层墨染遮挡身后;落笔间距跟笔毛挂钩,笔画不会一节一节;小路要少、平滑、从雾里伸出来;皴擦长而顺坡、集中在阴面;山脊线要淡而断续。
+- **水彩**:纸纹要细;阴影用湿画偏一侧积色,不要画成靶心;先画叶梗,并且只画在叶子外面;同一处罩染不超过三层,亮部留白或提白。
+- **剪纸**:大色块用平纸或牛皮纸,蜡笔只做点缀;撕口白边宽 5–8 像素,只出现在部分边缘;阴影偏移要补零,不能首尾相接;月亮用光圈,不画放射线。
### 计划
-- 在同一套笔刷、纸纹、墨染的底层上扩展更多画风:水彩、撕纸拼贴。
- 按笔画分层导出,方便在 Motion Canvas / Remotion 里做逐笔动画。
+- 在同一套底层上扩展更多画风:水粉、木刻版画、铅笔素描。
---
diff --git a/SKILL.md b/SKILL.md
index e7b7e36..3de3ef4 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -1,89 +1,122 @@
---
name: claude绘图
-description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。当前内置并验证过的画风是中国水墨:宣纸纹理、层层远山与雾气、飞白笔触、皴擦、苔点、松、芦苇、孤舟、烘云托月、朱红日、题字与印章。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」「代码水墨」,或 "draw it yourself", "paint with code", "procedural painting", "ink wash painting without an image model" 时使用;也用于需要可逐步画出(draw-on)动画的插画。几秒出一张 1920×1080。
+description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。内置三种画风:中国水墨(宣纸、层层远山与雾、飞白、皴擦、苔点、松、孤舟、烘云托月、题字印章)、水彩(湿画渐变、透明罩染、水痕边、颜料颗粒、水渍花、提白)、剪纸拼贴(撕纸白边、纸片阴影、彩纸/牛皮纸/报纸/笔记本纸、蜡笔、腮红圆脸的可爱小人)。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」「代码水墨/水彩/剪纸」,或 "draw it yourself", "paint with code", "procedural painting", "ink wash / watercolor / paper collage without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。
---
# Claude 绘图
-用 Python(只依赖 numpy + Pillow,系统自带的 `python3` 就能跑)按笔画和墨色的物理规律「画」图,不调用任何生图模型。
-- **画面**:每一笔都是算出来的,可以精确控制构图、留白、朱红点缀的位置。
-- **结果可复现**:固定随机种子后,同一段代码每次画出同一幅画。
-- **适合做动画**:可以按「先远山、再主峰、再小路……」的顺序出分阶段快照,做成逐步画出的动画;生图模型只能给一整张画。
+用 Python(只依赖 numpy + Pillow,系统自带的 `python3` 就能跑)按笔、墨、颜料、纸的物理规律「画」图,不调用任何生图模型。
+- **构图可控**:每一笔都是算出来的,构图、留白、点睛色的位置都精确可控。
+- **结果可复现**:固定随机种子,每次画出同一幅画。
+- **适合做动画**:可以输出分阶段快照,做成「一幅画被逐步画出来」的动画;生图模型只能给一整张画。
-`examples/bawansiqian.jpg`(八万四千法门)和 `examples/moon_river.jpg`(月印万川)是水墨风的质量基准。
+## 画风与范例(质量基准)
+
+| 画风 | 库 | 范例 | 耗时 |
+|---|---|---|---|
+| 水墨 | `lib/inkpaint.py` · `Painting` | `examples/bawansiqian.py` 八万四千法门、`examples/moon_river.py` 月印万川 | 2–4 秒 |
+| 水彩 | `lib/watercolor.py` · `Watercolor` | `examples/watercolor_lotus.py` 一花一世界(清晨荷塘) | 约 17 秒 |
+| 剪纸拼贴 | `lib/papercut.py` · `Collage` | `examples/papercut_moon.py` 小沙弥看月亮 | 约 20 秒 |
+
+三种画风共用 `lib/core.py` 里的底层工具:噪声、模糊、样条曲线、多边形遮罩、有机轮廓 `blob_pts`、毛笔 `bristle_stroke`、中文字体查找。
+
+**用户没有指定画风时怎么选**:禅意、古典、山水题材用水墨;清新、花卉、风景、带颜色的题材用水彩;童趣、温暖、故事感、角色类题材用剪纸拼贴。
## 一、流程(每幅画都照做)
1. **定构图**,动笔前先想清楚这几项:
- - 层次:远景 → 中景 → 主体 → 前景;
+ - 层次:远 → 中 → 主体 → 前景;
- 视觉焦点在哪里;
- - 留白至少四成;
- - 朱红只点一处或两处(日、印章、一条关键的路);
- - 题字位置(竖排,放在留白处)。
- - 画面必须图解内容本身。比如「八万四千法门」就画很多条路汇向同一个山顶,而不是随便一幅山水。
-2. **写场景脚本**:复制 `examples/bawansiqian.py` 改写,用 `lib/inkpaint.py` 的接口组合。
-3. **渲染并自己看图**:`python3 scene.py out.png`,大约 3–5 秒。
- - 用 Read 打开 PNG,**对照第三节的毛病清单逐条自查**;
- - 通常要改 2–4 轮,每轮只改最显眼的问题,把前一版存成 `_v1/_v2` 以便对比。
-4. **交付**:转成 JPG(quality 92,约 400KB),用当前对话渠道支持的方式发图。
- - 需要动画时加 `--stages DIR`,按 `p.stage('名字')` 输出每个阶段的快照。
-
-## 二、接口速查(`lib/inkpaint.py`)
+ - 留白够不够:水墨至少四成,水彩和剪纸也要有呼吸感;
+ - 点睛色只用一两处:水墨用朱红,剪纸用一个亮色主角;
+ - 题字或纸条放在哪里。
+ - **画面要图解内容本身**,而不是随便一幅风景。
+2. **写场景脚本**:复制最接近的范例改写。
+3. **渲染并自己看图**:`python3 scene.py out.png`。
+ - 用 Read 打开 PNG,对照第三节该画风的毛病清单逐条自查;
+ - 一般改 2–4 轮,每轮只改最显眼的问题,旧版存成 `_v1/_v2` 以便对比。
+4. **交付**:转成 JPG(quality 92),用当前对话渠道支持的方式发图。
+ - 要做动画时加 `--stages DIR`,按 `stage('名字')` 输出各阶段快照。
+
+## 二、接口速查
```python
import sys; sys.path.insert(0, "<本skill>/lib")
-from inkpaint import Painting, spline, curve, fbm1d, blur
-p = Painting(1920, 1080, seed=7) # 固定种子 = 可复现
-p.paper() # 宣纸:底色斑驳 + 颗粒 + 纤维
-ridge = p.ridge(base_y, peaks=[(x, 高, 宽), ...], rough=26) # 山脊线 y(x)
-main = p.peak(SX, SY, height=560, left_w=360, right_w=470, shoulders=[(x, h, w)]) # 主峰(不对称,带山肩)
-p.wash(ridge, dens, decay, tex, edge, mist_y, mist_h) # 墨染山体:上浓下淡、有水痕边、会遮挡后面的层
-p.cun(main, x0, x1, n=150, shadow_x=SX) # 皴擦:阴面多而深
-p.moss(main, x0, x1, n=70) # 苔点
-p.ridge_line(main, x0, x1) # 淡而断续的山脊线
-paths = p.trails(main, (SX, SY), n=16, red_index=7) # 蜿蜒小路汇向山顶,其中一条朱红
-p.mist(y, h, strength) # 雾带:盖住它之前画的东西
-p.rock(ridge); p.pine(root, top, bend, branches=[(起点, 终点, 弯度)], extra_tufts=[...])
-p.sun(x, y, r); p.birds([(x, y, s)]); p.pagoda(x, y); p.traveller(x, y); p.dot(x, y, r)
-p.stroke(points, width, ink, dry=0.35, taper=(0.25, 0.35), red=False) # 通用毛笔:飞白、按压粗细、抖动
-p.title_vertical('八万四千', x, y, 92); p.seal('法门', x, y, 40) # 楷体题字 + 朱印(最后叠加)
-p.stage('远山') # 动画用阶段快照
-p.save('out.png', stages_dir=None)
+from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask
```
-**顺序很重要**:先远后近(`wash` 会遮挡前面已画的层),雾要画在它该吞没的东西之后,题字和印章最后叠加。
-
-## 三、毛病清单(都真实出现过,自查时逐条过)
-
-| 看到的问题 | 原因 | 改法 |
-|---|---|---|
-| 后面的远山线条透过前面的主峰 | 层与层直接叠加,没有遮挡 | `wash(occlude=True)`(默认),并且先远后近 |
-| 笔画像梯子或一串珠子 | 笔毛太细、落笔点间距太大 | 库里已经按笔毛大小自动算间距;自己写笔刷时也要这样 |
-| 小路像头发丝、像根须 | 线太多、太弯、跑出山体 | 16 条左右,用样条平滑,起点在山脚雾里,只画在山体上 |
-| 路是折线,像裂缝或图表 | 用直线段连接转折点 | 一律用 `spline()` 连接控制点 |
-| 皴擦像撒了一片逗号 | 短笔太多、太匀、方向乱 | 减到约 150 笔,加长,顺着坡向,集中在阴面 |
-| 山像卡通描边 | 山脊线太重太连续 | 山脊线用淡墨(0.3)加飞白,主要靠墨染的水痕边和苔点 |
-| 松针像海胆 | 放射状的针太黑太满 | 扇形松针(上半圈)加底下一团淡墨晕 |
-| 主峰像规整的锥子 | 左右对称、没有起伏 | 左右坡宽度不同,加山肩,加分形起伏 |
-| 画面发闷 | 留白不够、朱红太多 | 留白至少四成,朱红最多一两处 |
+**水墨 `Painting`**:
+- `paper()`、`ridge(base, peaks=[(x,h,w)])`、`peak(SX, SY, shoulders=...)`
+- `wash(ridge, dens, decay, tex, edge, mist_y)`:墨染山体,上浓下淡、带水痕边,会遮挡后面的层
+- `cun()` 皴擦、`moss()` 苔点、`ridge_line()` 淡山脊线、`trails(ridge, summit, red_index)` 汇顶小路、`mist(y, h)` 雾带
+- 毛笔 `stroke(pts, width, ink, dry, taper, red)`
+- 物件:`pine()`、`rock()`、`sun()`、`birds()`、`pagoda()`、`traveller()`、`dot()`
+- 题字印章:`title_vertical()`、`seal()`
+
+**水彩 `Watercolor`**:
+- `paper()`:冷压水彩纸纹理
+- 遮罩:`shape(pts, soft, ragged)`,soft 取 1–4 是清晰的水痕边,15–40 是湿画晕开;`band(pts, width)` 是粗笔带状遮罩
+- `glaze(mask, 颜色, strength, edge, gran, bloom, variation)`:透明罩染,叠加会像真颜料一样变深、混色
+- `gradient_wash(y0, y1, top, bottom)`:湿画渐变天空
+- 笔触:`stroke()` 彩色干笔、`line()` 细线勾勒、`lift(mask)` 提白、`splatter()` 甩点
+- `Watercolor.petal_pts(x, y, 角度, 长, 宽)`:花瓣或叶片轮廓;`hexc('#rrggbb')` 转颜色
+
+**剪纸 `Collage`**:
+- `background(颜色, texture)`
+- `piece(pts 或 mask, 颜色, texture, torn, rim, shadow)`:贴一张纸。torn 是撕边程度,rim 是撕口白边,shadow 是纸片阴影;texture 可选 paper / kraft / crayon / newsprint / notebook
+- 形状遮罩:`circle_mask()`、`cloud_mask()`、`Collage.star_pts()`
+- 蜡笔和光:`crayon(pts, width, 颜色)` 蜡笔线、`dot()`、`glow()`
+- `face(cx, cy, r, mood='smile'|'sleep'|'dots')`:笑眼、嘴、腮红
+- `text(s, x, y, size, 颜色, vertical)`
+
+**顺序**:都是先远后近、先大后小,文字最后叠加。水墨的雾要画在它该吞没的东西之后;水彩的叶梗要先画,并且只画在叶子外面。
+
+## 三、毛病清单(都真实出现过)
+
+**水墨**
+
+| 问题 | 改法 |
+|---|---|
+| 后面的远山透过主峰 | 先远后近,`wash` 默认会遮挡身后 |
+| 笔画像梯子或串珠 | 落笔间距跟笔毛挂钩(`bristle_stroke` 已处理) |
+| 小路像头发丝,或是折线像裂缝 | 16 条左右,用 `spline` 平滑,只画在山体上,从雾里伸出来 |
+| 皴擦像撒逗号 | 约 150 笔,长而顺坡,集中在阴面 |
+| 山脊像卡通描边 | 山脊线用淡墨(0.3)加飞白,边缘靠水痕 |
+| 松针像海胆 | 扇形松针,下面垫一团淡墨晕 |
+| 主峰像锥子 | 左右坡宽度不同,加山肩和起伏 |
+| 远山被挖出方块、断边生硬 | 用「从水线以下升起的山包」来留出水面,不要直接挖空一段 |
+
+**水彩**
+
+| 问题 | 改法 |
+|---|---|
+| 纸纹像砂纸或拉毛墙 | 纸纹受光强度约 0.3,纸纹要细 |
+| 叶子中间一圈深色像靶心 | 第二层深色用湿画(soft 约 16)偏向一侧积色,不要同心 |
+| 叶梗画到了叶面上 | 先画梗,用 `*(1 - 叶遮罩)` 限制只在叶外 |
+| 颜色发脏 | 同一处罩染不超过三层;亮部留白或用 `lift` 提白 |
+
+**剪纸拼贴**
+
+| 问题 | 改法 |
+|---|---|
+| 大面积蜡笔纹像满屏刮痕 | 大色块用 paper / kraft,蜡笔只用在点缀或小物件上 |
+| 撕纸白边看不见 | 白边要宽出 5–8 像素(大半径模糊加低阈值),并且只出现在部分边缘上 |
+| 画面顶边或左边多出一条阴影 | 阴影偏移不能用会首尾相接的循环平移,要用补零平移(已修) |
+| 月亮画了光芒,像太阳 | 月亮用蜡笔光圈加几颗闪光,不要放射线 |
+| 脸的五官太粗太凶 | 线宽约 r×0.035,腮红用 `glow` |
## 四、做成动画
-- **简单做法**:用 `p.stage()` 分阶段快照(远山 → 主峰 → 小路 → 松石 → 日与题字),在视频里依次淡入叠化,看起来就是一幅画被逐步画出来。
-- **更细的做法**:把某一组笔画单独画到透明层上导出,在 Motion Canvas 里用遮罩按笔画顺序显现。这需要给笔画分组,还没做成现成接口,用到时再加。
-
-## 五、扩展到别的画风
-
-笔刷、纸纹、墨染这套底层可以改造成水彩(彩色墨染 + 水痕边 + 颗粒)或剪纸拼贴(撕纸毛边 = 噪声扰动多边形边缘 + 纸纹)。
-
-**目前只有水墨风做过并经用户认可**,别的画风第一次做时先出一张给用户看。
+- 各画风都有 `stage(name)` 和 `save(path, stages_dir)`,按阶段依次淡入叠化,就是「一幅画被逐步画出来」。README 里的四张动图就是这样做的。
+- 更细的逐笔动画:把一组笔画单独画到透明层上导出,再用 Motion Canvas 遮罩按顺序显现。这个还没做成现成接口。
-## 六、文件
+## 五、文件
```
-lib/inkpaint.py 绘图库(Painting 类 + 辅助函数,只依赖 numpy + Pillow)
-examples/bawansiqian.py 范例「八万四千法门」:层层远山、主峰、小路汇顶、松石、朱日(约 3.6 秒)
-examples/moon_river.py 范例「月印万川」:烘云托月、孤舟垂钓、芦苇、水面月影(约 2 秒)
-examples/*.jpg / drawing_*.gif 成品与逐步画出的动图
+lib/core.py 公共底层(噪声、模糊、样条、遮罩、毛笔、字体)
+lib/inkpaint.py 水墨
+lib/watercolor.py 水彩
+lib/papercut.py 剪纸拼贴
+examples/*.py 范例脚本;*.jpg 成品;drawing_*.gif 逐步画出的动图
中文字体:自动找 Kaiti/Songti(macOS)、Noto CJK(Linux)、KaiTi/SimSun(Windows),或设 INKPAINT_FONT
```
diff --git a/examples/drawing_papercut_moon.gif b/examples/drawing_papercut_moon.gif
new file mode 100644
index 0000000..36a2610
Binary files /dev/null and b/examples/drawing_papercut_moon.gif differ
diff --git a/examples/drawing_watercolor_lotus.gif b/examples/drawing_watercolor_lotus.gif
new file mode 100644
index 0000000..5cd80d5
Binary files /dev/null and b/examples/drawing_watercolor_lotus.gif differ
diff --git a/examples/papercut_moon.jpg b/examples/papercut_moon.jpg
new file mode 100644
index 0000000..01d3d0c
Binary files /dev/null and b/examples/papercut_moon.jpg differ
diff --git a/examples/papercut_moon.py b/examples/papercut_moon.py
new file mode 100644
index 0000000..0bcc8be
--- /dev/null
+++ b/examples/papercut_moon.py
@@ -0,0 +1,87 @@
+"""范例(剪纸拼贴):「小沙弥看月亮」— 撕纸毛边、纸片阴影、蜡笔质感、报纸云、笔记本纸条、可爱小人。
+python3 papercut_moon.py [out.png] [--stages DIR]
+"""
+import os, sys
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from papercut import Collage
+from core import blob_pts, spline, fbm1d
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'papercut_moon.png'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+
+c = Collage(1920, 1080, seed=15)
+rng = c.rng
+W, H = c.W, c.H
+
+# ---- night sky in navy crayon, stars
+c.background('#232d66', texture='kraft')
+for _ in range(40):
+ c.dot(rng.uniform(30, W - 30), rng.uniform(20, 560), rng.uniform(1.5, 3.2), '#f6e7a8')
+for (x, y, r) in [(260, 150, 22), (880, 110, 16), (1040, 360, 14), (1750, 140, 20), (150, 430, 14), (1650, 480, 12)]:
+ c.piece(Collage.star_pts(x, y, r), '#f4cf5e', texture='crayon', torn=0.15, rim=0.3, shadow=0.25)
+c.stage('夜空')
+
+# ---- the moon: soft glow, torn paper disc with a sleepy smile, crayon rays
+MX, MY, MR = 1360, 300, 150
+c.glow(MX, MY, 260, '#f7d98a', 0.18)
+c.piece(mask=c.circle_mask(MX, MY, MR), colour='#f6d77a', texture='crayon', torn=0.5, rim=0.9, shadow=0.35, angle=0.9)
+c.face(MX, MY + 10, MR * 0.85, mood='sleep')
+halo = [(MX + np.cos(a) * (MR + 38 + 6 * np.sin(5 * a)), MY + np.sin(a) * (MR + 38 + 6 * np.sin(5 * a))) for a in np.linspace(-2.2, 2.6, 40)]
+c.crayon(spline(halo, 4), 5, '#f2c94c', 0.75) # a hand-drawn crayon halo, not sun rays
+for a in (-2.6, -0.3, 0.6, 2.9):
+ x, y = MX + np.cos(a) * (MR + 90), MY + np.sin(a) * (MR + 90)
+ c.crayon([(x - 12, y), (x + 12, y)], 4, '#f6e7a8'); c.crayon([(x, y - 12), (x, y + 12)], 4, '#f6e7a8') # twinkles
+c.stage('月亮')
+
+# ---- a newspaper cloud drifting across
+c.piece(mask=c.cloud_mask(560, 250, 380, 170, puffs=5, seed=3), colour='#e9e3d6', texture='newsprint', torn=0.7, rim=0.9, shadow=0.35)
+c.stage('报纸云')
+
+# ---- torn-paper hills, far to near
+xs = np.linspace(-20, W + 20, 60)
+far = [(x, 640 - 70 * np.sin(x / 260 + 0.5) - 30 * fbm1d(60, 12, 3, 1)[i]) for i, x in enumerate(xs)]
+c.piece(far + [(W + 20, H + 20), (-20, H + 20)], '#3b3f86', texture='paper', torn=0.8, rim=0.9, shadow=0.4)
+mid = [(x, 760 - 90 * np.sin(x / 330 + 2.2) - 25 * fbm1d(60, 12, 3, 2)[i]) for i, x in enumerate(xs)]
+c.piece(mid + [(W + 20, H + 20), (-20, H + 20)], '#2e6275', texture='paper', torn=0.8, rim=0.9, shadow=0.4)
+# a little pagoda with a lit window on the middle hill
+PX, PY = 1560, 700
+for k, (wid, hgt) in enumerate([(120, 26), (96, 24), (72, 22)]):
+ y = PY - k * 58
+ c.piece([(PX - 30 + k * 4, y), (PX + 30 - k * 4, y), (PX + 30 - k * 4, y - 34), (PX - 30 + k * 4, y - 34)], '#6b3b36', torn=0.2, rim=0.3, shadow=0.3)
+ c.piece([(PX - wid / 2, y - 30), (PX + wid / 2, y - 30), (PX + wid * 0.28, y - 30 - hgt), (PX - wid * 0.28, y - 30 - hgt)], '#3a2433', torn=0.25, rim=0.4, shadow=0.3)
+c.dot(PX, PY - 16, 9, '#ffd66b'); c.glow(PX, PY - 16, 28, '#ffd66b', 0.35)
+c.crayon([(PX, PY - 180), (PX, PY - 206)], 5, '#3a2433')
+near = [(x, 880 - 120 * np.exp(-((x - 620) / 520) ** 2) - 20 * fbm1d(60, 10, 3, 3)[i]) for i, x in enumerate(xs)]
+c.piece(near + [(W + 20, H + 20), (-20, H + 20)], '#4f8a4f', texture='paper', torn=0.7, rim=0.9, shadow=0.45)
+for _ in range(60): # crayon grass tufts
+ x = rng.uniform(40, W - 40); y = 880 - 120 * np.exp(-((x - 620) / 520) ** 2) + rng.uniform(20, 170)
+ for k in range(3):
+ c.crayon([(x + k * 7, y), (x + k * 7 + rng.normal(0, 4), y - rng.uniform(14, 28))], 3.2, '#2f6a3a', 0.9)
+c.stage('山丘')
+
+# ---- a small monk sitting on the hill, looking up at the moon
+BX, BY = 640, 770
+robe = spline([(BX - 95, BY + 70), (BX - 80, BY - 10), (BX - 40, BY - 55), (BX + 40, BY - 55), (BX + 80, BY - 10), (BX + 95, BY + 70)], 10)
+c.piece(np.vstack([robe, [(BX + 95, BY + 78), (BX - 95, BY + 78)]]), '#e0873b', texture='paper', torn=0.35, rim=0.6, shadow=0.45)
+c.piece([(BX - 45, BY - 50), (BX - 10, BY - 50), (BX + 70, BY + 60), (BX + 35, BY + 66)], '#b8512e', texture='paper', torn=0.3, rim=0.5, shadow=0.3)
+c.piece(mask=c.circle_mask(BX + 30, BY + 20, 20), colour='#f3cda6', torn=0.2, rim=0.4, shadow=0.3) # hands in lap
+c.piece(mask=c.circle_mask(BX, BY - 110, 62), colour='#f3cda6', texture='paper', torn=0.3, rim=0.7, shadow=0.4)
+for sx in (-1, 1):
+ c.piece(mask=c.circle_mask(BX + sx * 60, BY - 106, 13), colour='#eebf95', torn=0.15, rim=0.3, shadow=0.2)
+c.face(BX + 6, BY - 118, 56, mood='smile')
+for (dx, dy) in [(-20, -150), (0, -156), (20, -150)]: # three dots on the shaved head
+ c.dot(BX + dx, BY + dy, 3.5, '#c98e6d')
+c.stage('小沙弥')
+
+# ---- a torn notebook scrap with a note, and fireflies
+note = [(1440, 820), (1780, 800), (1790, 960), (1452, 985)]
+c.piece(note, '#fbf8ef', texture='notebook', torn=0.6, rim=0.5, shadow=0.45)
+c.text('心中有月', 1490, 850, 64, '#3a5fa8')
+c.crayon(spline([(1500, 940), (1600, 952), (1720, 930)], 8), 4, '#d9534f', 0.85)
+for _ in range(14):
+ x, y = rng.uniform(200, 1400), rng.uniform(640, 1000)
+ c.glow(x, y, 16, '#fff0a0', 0.45); c.dot(x, y, 3, '#fff6c0')
+
+c.save(out, stages_dir=stages)
+print('saved', out)
diff --git a/examples/watercolor_lotus.jpg b/examples/watercolor_lotus.jpg
new file mode 100644
index 0000000..ab2dffd
Binary files /dev/null and b/examples/watercolor_lotus.jpg differ
diff --git a/examples/watercolor_lotus.py b/examples/watercolor_lotus.py
new file mode 100644
index 0000000..475c8f9
--- /dev/null
+++ b/examples/watercolor_lotus.py
@@ -0,0 +1,98 @@
+"""范例(水彩):「一花一世界」— 清晨荷塘。纯代码水彩:湿画天空、罩染荷叶、水痕边、颗粒、水渍花、提白叶脉。
+python3 watercolor_lotus.py [out.png] [--stages DIR]
+"""
+import os, sys
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from watercolor import Watercolor, hexc
+from core import blob_pts, spline, curve
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'watercolor_lotus.png'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+
+p = Watercolor(1920, 1080, seed=108)
+p.paper()
+p.stage('纸')
+rng = p.rng
+
+# ---- sky: wet-in-wet from cool blue to dawn peach
+p.gradient_wash(0, 520, top=hexc('#8fb0cf'), bottom=hexc('#f2cfae'), strength=0.55)
+# ---- far bank: soft blue-grey trees melting into the sky
+far = [(0, 560)] + [(x, 520 - 40 * np.sin(x / 190) - 25 * np.sin(x / 67 + 1) - rng.uniform(0, 18)) for x in np.linspace(0, 1920, 40)] + [(1920, 560)]
+p.glaze(p.shape(far, soft=14, ragged=0.35), hexc('#7d93a8'), 0.5, edge=0.25, gran=0.4)
+p.stage('天空')
+
+# ---- water: pale teal, darker toward the viewer, with horizontal dry-brush streaks
+water = [(0, 545), (1920, 545), (1920, 1080), (0, 1080)]
+wm = p.shape(water, soft=6, ragged=0.1) * np.clip((p.YY - 545) / 500, 0.35, 1)
+p.glaze(wm, hexc('#9cc3bf'), 0.55, edge=0.1, gran=0.45, variation=0.35)
+for _ in range(26):
+ y = rng.uniform(580, 1060); x = rng.uniform(-100, 1700); ln = rng.uniform(200, 520)
+ p.stroke(spline([(x, y), (x + ln / 2, y + rng.normal(0, 2)), (x + ln, y)], 10), rng.uniform(3, 7), hexc('#5f8f93'), 0.35, dry=0.7)
+p.stage('水面')
+
+# ---- lotus leaves (back to front): base glaze, darker second glaze, bloom, lifted veins, stem
+def leaf(cx, cy, rx, ry, rot, dark=0.55, hue='#a9c46b'):
+ pts = blob_pts(cx, cy, rx, ry, rough=0.11, n=140, seed=int(cx), rot=rot)
+ m = p.shape(pts, soft=2.5, ragged=0.22)
+ # stem first, visible only below the leaf
+ vx0, vy0 = cx + rx * 0.08, cy - ry * 0.05
+ p.glaze(p.band([(vx0, cy + ry * 0.6), (vx0 - 6, cy + ry + 60)], 7, soft=2) * (1 - m), hexc('#6f8a4a'), 0.4, edge=0.2)
+ p.glaze(m, hexc(hue), 0.75, edge=0.55, gran=0.35)
+ # shadow glaze pooled on one side (wet-in-wet, soft), not a centred ring
+ side = p.shape(blob_pts(cx - rx * 0.28, cy + ry * 0.18, rx * 0.72, ry * 0.7, rough=0.2, n=100, seed=int(cy), rot=rot), soft=16, ragged=0.45)
+ p.glaze(side * m, hexc('#4a7a45'), dark, edge=0.25, gran=0.45, bloom=1)
+ vx, vy = cx + rx * 0.08, cy - ry * 0.05
+ veins = np.zeros((p.H, p.W), np.float32)
+ for a in np.linspace(0, 2 * np.pi, 13, endpoint=False):
+ ex, ey = vx + np.cos(a + rot) * rx * 0.9, vy + np.sin(a + rot) * ry * 0.9
+ veins = np.maximum(veins, p.band(spline([(vx, vy), ((vx + ex) / 2 + rng.normal(0, 5), (vy + ey) / 2), (ex, ey)], 8), 3, soft=1.2))
+ p.lift(veins * m, 0.32)
+
+for (cx, cy, rx, ry, rot, dk, hue) in [(300, 640, 170, 55, -0.05, 0.45, '#b3c877'), (1560, 620, 150, 48, 0.08, 0.45, '#a3c27a'),
+ (980, 700, 200, 70, 0.04, 0.5, '#9fc06a'), (1750, 820, 230, 90, -0.1, 0.55, '#8fb873'),
+ (160, 900, 260, 110, 0.12, 0.6, '#a9c46b'), (620, 960, 240, 95, -0.06, 0.6, '#98bd6e')]:
+ leaf(cx, cy, rx, ry, rot, dk, hue)
+p.stage('荷叶')
+
+# ---- lotus flowers: stems, petals (pink with deeper tips), seed pod
+def flower(bx, by, scale=1.0, open_=True):
+ p.glaze(p.band(spline([(bx, by + 20), (bx + 8, by + 180), (bx + 2, by + 330)], 10), 9 * scale, soft=2), hexc('#7a9650'), 0.7, edge=0.4)
+ angles = np.linspace(-150, -30, 7) if open_ else np.linspace(-110, -70, 3)
+ for k, a in enumerate(angles):
+ ang = np.radians(a + rng.normal(0, 4))
+ L = (150 if open_ else 175) * scale * (0.85 + 0.3 * np.sin(np.pi * k / max(1, len(angles) - 1)))
+ Wd = (46 if open_ else 42) * scale
+ pts = Watercolor.petal_pts(bx, by, ang, L, Wd, curl=rng.normal(0, 0.05))
+ m = p.shape(pts, soft=2, ragged=0.15)
+ p.glaze(m, hexc('#f0a3b3'), 0.55, edge=0.6, gran=0.25)
+ tip = Watercolor.petal_pts(bx + np.cos(ang) * L * 0.45, by + np.sin(ang) * L * 0.45, ang, L * 0.55, Wd * 0.75)
+ p.glaze(p.shape(tip, soft=7, ragged=0.3) * m, hexc('#c94f73'), 0.55, edge=0.3)
+ p.line(spline([(bx, by), (bx + np.cos(ang) * L * 0.9, by + np.sin(ang) * L * 0.9)], 6), 1.0, hexc('#b0506a'), 0.25)
+ if open_:
+ pod = p.shape(blob_pts(bx, by - 30 * scale, 34 * scale, 18 * scale, rough=0.05, seed=int(bx)), soft=2)
+ p.glaze(pod, hexc('#e3bf4d'), 0.8, edge=0.6, gran=0.3)
+ for _ in range(7):
+ p.splatter(hexc('#9a7a2a'), 1, box=(bx - 22 * scale, by - 40 * scale, bx + 22 * scale, by - 24 * scale), size=(2, 3.5), strength=0.8)
+ # soft reflection in the water
+ ref = p.shape([(bx - 40 * scale, by + 340), (bx + 40 * scale, by + 340), (bx + 20, by + 470), (bx - 20, by + 470)], soft=20, ragged=0.4)
+ p.glaze(ref * (p.YY > 545), hexc('#e7a3b2'), 0.25, edge=0.1)
+
+flower(1150, 430, 1.05, True)
+flower(560, 470, 0.85, False)
+p.stage('荷花')
+
+# ---- a dragonfly and a few flicked droplets
+dx, dy = 1450, 300
+p.line(spline([(dx - 70, dy + 10), (dx, dy), (dx + 30, dy - 4)], 8), 3.2, hexc('#4b3b36'), 0.8)
+for (a, L) in [(-100, 95), (-70, 88), (100, 90), (70, 84)]:
+ ang = np.radians(a)
+ wp = Watercolor.petal_pts(dx - 8, dy, ang, L, 16)
+ p.glaze(p.shape(wp, soft=1.5, ragged=0.1), hexc('#b9d4e6'), 0.35, edge=0.7, gran=0.1)
+p.splatter(hexc('#6f9a5b'), 30, box=(0, 560, 1920, 1080), size=(1.5, 4.5), strength=0.5)
+p.splatter(hexc('#e38fa6'), 14, box=(900, 250, 1400, 700), size=(1.2, 3.5), strength=0.45)
+
+p.title_vertical('一花一世界', 150, 140, 80)
+p.seal('清净', 250, 160, 34)
+p.save(out, stages_dir=stages)
+print('saved', out)
diff --git a/lib/core.py b/lib/core.py
new file mode 100644
index 0000000..744e833
--- /dev/null
+++ b/lib/core.py
@@ -0,0 +1,150 @@
+"""core — shared helpers for every style (numpy + Pillow only)."""
+import glob
+import os
+import numpy as np
+from PIL import Image
+
+
+def blur(a, sigma):
+ """fast gaussian approximation: 3 separable box blurs via cumulative sums (numpy only)"""
+ if sigma <= 0: return a.copy()
+ out = a.astype(np.float32)
+ w = int(np.sqrt(12 * sigma * sigma / 3 + 1))
+ w += (w % 2 == 0)
+ r = w // 2
+ for _ in range(3):
+ for ax in (0, 1):
+ pad = [(0, 0), (0, 0)]; pad[ax] = (r + 1, r)
+ c = np.cumsum(np.pad(out, pad, mode='edge'), axis=ax, dtype=np.float64)
+ hi = np.take(c, np.arange(w, c.shape[ax]), axis=ax)
+ lo = np.take(c, np.arange(0, c.shape[ax] - w), axis=ax)
+ out = ((hi - lo) / w).astype(np.float32)
+ return out
+
+
+def fbm1d(n, scale, octaves=5, seed=0):
+ """1D fractal noise in [-1, 1] (ridgelines, wobble)"""
+ r = np.random.default_rng(seed)
+ x = np.arange(n, dtype=np.float32)
+ out = np.zeros(n, np.float32); amp = 1.0; tot = 0.0
+ for o in range(octaves):
+ k = max(2, int(n / scale * 2 ** o) + 2)
+ out += amp * np.interp(x, np.linspace(0, n - 1, k), r.random(k).astype(np.float32) * 2 - 1)
+ tot += amp; amp *= 0.5
+ return out / tot
+
+
+def curve(p0, p1, bend, n=24, wig=0.0, seed=0):
+ """curve from p0 to p1 bowing sideways by `bend` px, optional wiggle"""
+ p0, p1 = np.array(p0, np.float32), np.array(p1, np.float32)
+ t = np.linspace(0, 1, n)[:, None]
+ d = p1 - p0; nrm = np.array([-d[1], d[0]]) / (np.linalg.norm(d) + 1e-6)
+ off = (4 * t * (1 - t)) * bend
+ if wig: off = off + fbm1d(n, 6, 2, seed)[:, None] * wig
+ return p0 + d * t + nrm * off
+
+
+def spline(pts, per=14):
+ """Catmull-Rom through control points — always use this instead of straight zig-zags"""
+ P = np.asarray(pts, np.float32)
+ P = np.vstack([P[0] * 2 - P[1], P, P[-1] * 2 - P[-2]])
+ out = []
+ for i in range(1, len(P) - 2):
+ p0, p1, p2, p3 = P[i - 1], P[i], P[i + 1], P[i + 2]
+ for t in np.linspace(0, 1, per, endpoint=False):
+ t2, t3 = t * t, t * t * t
+ out.append(0.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 + (-p0 + 3 * p1 - 3 * p2 + p3) * t3))
+ out.append(P[-2])
+ return np.array(out, np.float32)
+
+
+
+def noise2d(h, w, scale, octaves=4, seed=0):
+ """2D value noise in [0, 1] (bicubic-upsampled random grids, fractal sum)"""
+ r = np.random.default_rng(seed)
+ out = np.zeros((h, w), np.float32); amp = 1.0; tot = 0.0
+ for o in range(octaves):
+ gh, gw = max(2, int(h / scale * 2 ** o) + 2), max(2, int(w / scale * 2 ** o) + 2)
+ g = Image.fromarray(r.random((gh, gw)).astype(np.float32), mode='F')
+ out += amp * np.asarray(g.resize((w, h), Image.BICUBIC), np.float32)
+ tot += amp; amp *= 0.5
+ out /= tot
+ return (out - out.min()) / (out.max() - out.min() + 1e-6)
+
+
+def smoothstep(e0, e1, x):
+ t = np.clip((x - e0) / (e1 - e0 + 1e-9), 0, 1)
+ return t * t * (3 - 2 * t)
+
+
+def polygon_mask(h, w, pts, ss=1):
+ """filled polygon -> float mask (optionally supersampled for smooth edges)"""
+ from PIL import ImageDraw
+ im = Image.new('L', (w * ss, h * ss), 0)
+ ImageDraw.Draw(im).polygon([(float(x) * ss, float(y) * ss) for x, y in pts], fill=255)
+ if ss > 1: im = im.resize((w, h), Image.BILINEAR)
+ return np.asarray(im, np.float32) / 255
+
+
+def blob_pts(cx, cy, rx, ry, rough=0.08, n=90, seed=0, rot=0.0):
+ """closed organic outline around (cx, cy): ellipse with fractal radius wobble"""
+ t = np.linspace(0, 2 * np.pi, n, endpoint=False)
+ wob = 1 + rough * fbm1d(n, n / 6, 4, seed)
+ x, y = np.cos(t) * rx * wob, np.sin(t) * ry * wob
+ c, s = np.cos(rot), np.sin(rot)
+ return np.stack([cx + x * c - y * s, cy + x * s + y * c], 1)
+
+
+def cjk_font():
+ """a brush-like CJK font: $INKPAINT_FONT, else Kaiti/Songti (macOS), Noto CJK (Linux), KaiTi/SimSun (Windows)"""
+ env = os.environ.get('INKPAINT_FONT')
+ if env and os.path.exists(env): return env
+ pats = ['/System/Library/AssetsV2/com_apple_MobileAsset_Font*/*/AssetData/Kaiti.ttc',
+ '/System/Library/Fonts/Supplemental/Songti.ttc', '/System/Library/Fonts/STHeiti Medium.ttc',
+ '/usr/share/fonts/**/NotoSerifCJK*.tt[cf]', '/usr/share/fonts/**/NotoSansCJK*.tt[cf]',
+ 'C:/Windows/Fonts/simkai.ttf', 'C:/Windows/Fonts/simsun.ttc']
+ for pat in pats:
+ fs = glob.glob(pat, recursive=True)
+ if fs: return fs[0]
+ return None
+
+
+def bristle_stroke(buf, pts, width, ink, dry=0.35, taper=(0.25, 0.35), jitter=0.6, seed=0):
+ """bristle brush along polyline `pts` into density buffer `buf` (in place).
+ width px; ink = peak opacity 0..1; dry = flying-white (0 wet .. 0.8 very dry); taper = (start, end)."""
+ H, W = buf.shape
+ r = np.random.default_rng(seed)
+ pts = np.asarray(pts, np.float32)
+ seg = np.linalg.norm(np.diff(pts, axis=0), axis=1)
+ L = float(seg.sum())
+ if L < 2: return
+ s = np.concatenate([[0], np.cumsum(seg)])
+ nb = max(3, int(width * 1.3))
+ br = max(0.6, width / nb * 1.7) # bristles overlap -> no stripes
+ step = max(0.5, min(width * 0.22, br * 0.7)) # dab spacing relative to bristle -> no beads
+ n = int(L / step) + 2
+ ss = np.linspace(0, L, n)
+ px = np.interp(ss, s, pts[:, 0]); py = np.interp(ss, s, pts[:, 1])
+ tx = np.gradient(px); ty = np.gradient(py)
+ tl = np.hypot(tx, ty) + 1e-6; tx /= tl; ty /= tl
+ nx, ny = -ty, tx
+ t = ss / L
+ press = 0.35 + 0.65 * np.clip(np.minimum(t / max(taper[0], 1e-3), (1 - t) / max(taper[1], 1e-3)), 0, 1) ** 0.6
+ offs = np.linspace(-0.5, 0.5, nb) + r.normal(0, 0.04, nb)
+ load0 = r.uniform(0.75, 1.0, nb)
+ wob = fbm1d(n, 40, 3, int(r.integers(1 << 30))) * jitter * width * 0.5
+ rad = int(br * 2 + 2)
+ ky, kx = np.mgrid[-rad:rad + 1, -rad:rad + 1].astype(np.float32)
+ for b in range(nb):
+ load = load0[b] * (1 - dry * t ** 1.2 * r.uniform(0.6, 1.4))
+ gate = fbm1d(n, 25, 3, int(r.integers(1 << 30)))
+ alive = (load * (0.75 + 0.5 * gate)) > (dry * 0.9)
+ for i in range(n):
+ if not alive[i]: continue
+ w = width * press[i]
+ cx = px[i] + nx[i] * (offs[b] * w + wob[i]); cy = py[i] + ny[i] * (offs[b] * w + wob[i])
+ ix, iy = int(cx), int(cy)
+ if ix < rad or iy < rad or ix >= W - rad - 1 or iy >= H - rad - 1: continue
+ k = np.exp(-((kx - (cx - ix)) ** 2 + (ky - (cy - iy)) ** 2) / (2 * (br * press[i]) ** 2 + 1e-3))
+ sl = buf[iy - rad:iy + rad + 1, ix - rad:ix + rad + 1]
+ np.copyto(sl, 1 - (1 - sl) * (1 - k * ink * load[i] * 0.55))
diff --git a/lib/inkpaint.py b/lib/inkpaint.py
index 7fee22b..0a55615 100644
--- a/lib/inkpaint.py
+++ b/lib/inkpaint.py
@@ -25,73 +25,7 @@ VERMILION = np.array([176, 52, 40], np.float32) / 255
PAPER = np.array([242, 236, 223], np.float32) / 255
-# ================================================================ generic helpers
-def blur(a, sigma):
- """fast gaussian approximation: 3 separable box blurs via cumulative sums (numpy only)"""
- if sigma <= 0: return a.copy()
- out = a.astype(np.float32)
- w = int(np.sqrt(12 * sigma * sigma / 3 + 1))
- w += (w % 2 == 0)
- r = w // 2
- for _ in range(3):
- for ax in (0, 1):
- pad = [(0, 0), (0, 0)]; pad[ax] = (r + 1, r)
- c = np.cumsum(np.pad(out, pad, mode='edge'), axis=ax, dtype=np.float64)
- hi = np.take(c, np.arange(w, c.shape[ax]), axis=ax)
- lo = np.take(c, np.arange(0, c.shape[ax] - w), axis=ax)
- out = ((hi - lo) / w).astype(np.float32)
- return out
-
-
-def fbm1d(n, scale, octaves=5, seed=0):
- """1D fractal noise in [-1, 1] (ridgelines, wobble)"""
- r = np.random.default_rng(seed)
- x = np.arange(n, dtype=np.float32)
- out = np.zeros(n, np.float32); amp = 1.0; tot = 0.0
- for o in range(octaves):
- k = max(2, int(n / scale * 2 ** o) + 2)
- out += amp * np.interp(x, np.linspace(0, n - 1, k), r.random(k).astype(np.float32) * 2 - 1)
- tot += amp; amp *= 0.5
- return out / tot
-
-
-def curve(p0, p1, bend, n=24, wig=0.0, seed=0):
- """curve from p0 to p1 bowing sideways by `bend` px, optional wiggle"""
- p0, p1 = np.array(p0, np.float32), np.array(p1, np.float32)
- t = np.linspace(0, 1, n)[:, None]
- d = p1 - p0; nrm = np.array([-d[1], d[0]]) / (np.linalg.norm(d) + 1e-6)
- off = (4 * t * (1 - t)) * bend
- if wig: off = off + fbm1d(n, 6, 2, seed)[:, None] * wig
- return p0 + d * t + nrm * off
-
-
-def spline(pts, per=14):
- """Catmull-Rom through control points — always use this instead of straight zig-zags"""
- P = np.asarray(pts, np.float32)
- P = np.vstack([P[0] * 2 - P[1], P, P[-1] * 2 - P[-2]])
- out = []
- for i in range(1, len(P) - 2):
- p0, p1, p2, p3 = P[i - 1], P[i], P[i + 1], P[i + 2]
- for t in np.linspace(0, 1, per, endpoint=False):
- t2, t3 = t * t, t * t * t
- out.append(0.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 + (-p0 + 3 * p1 - 3 * p2 + p3) * t3))
- out.append(P[-2])
- return np.array(out, np.float32)
-
-
-def kaiti_font():
- """a brush-like CJK font for titles/seals: $INKPAINT_FONT, else Kaiti/Songti (macOS), Noto CJK (Linux), KaiTi/SimSun (Windows)"""
- import os
- env = os.environ.get('INKPAINT_FONT')
- if env and os.path.exists(env): return env
- pats = ['/System/Library/AssetsV2/com_apple_MobileAsset_Font*/*/AssetData/Kaiti.ttc',
- '/System/Library/Fonts/Supplemental/Songti.ttc', '/System/Library/Fonts/STHeiti Medium.ttc',
- '/usr/share/fonts/**/NotoSerifCJK*.tt[cf]', '/usr/share/fonts/**/NotoSansCJK*.tt[cf]',
- 'C:/Windows/Fonts/simkai.ttf', 'C:/Windows/Fonts/simsun.ttc']
- for pat in pats:
- fs = glob.glob(pat, recursive=True)
- if fs: return fs[0]
- return None
+from core import blur, fbm1d, curve, spline, bristle_stroke, noise2d as _noise2d, cjk_font as kaiti_font # shared helpers
# ================================================================ the painting
@@ -143,45 +77,9 @@ class Painting:
# ------------------------------------------------------------ brush
def stroke(self, pts, width, ink, dry=0.35, taper=(0.25, 0.35), jitter=0.6, red=False, seed=None):
- """bristle brush along polyline `pts`. width px; ink = peak opacity 0..1;
- dry = flying-white amount (0 wet .. 0.8 very dry); taper = (start, end) fraction."""
- buf = self.R if red else self.D
- W, H = self.W, self.H
- r = np.random.default_rng(seed if seed is not None else self._seed())
- pts = np.asarray(pts, np.float32)
- seg = np.linalg.norm(np.diff(pts, axis=0), axis=1)
- L = float(seg.sum())
- if L < 2: return
- s = np.concatenate([[0], np.cumsum(seg)])
- nb = max(3, int(width * 1.3))
- br = max(0.6, width / nb * 1.7) # bristles overlap -> no stripes
- step = max(0.5, min(width * 0.22, br * 0.7)) # dab spacing relative to bristle -> no beads
- n = int(L / step) + 2
- ss = np.linspace(0, L, n)
- px = np.interp(ss, s, pts[:, 0]); py = np.interp(ss, s, pts[:, 1])
- tx = np.gradient(px); ty = np.gradient(py)
- tl = np.hypot(tx, ty) + 1e-6; tx /= tl; ty /= tl
- nx, ny = -ty, tx
- t = ss / L
- press = 0.35 + 0.65 * np.clip(np.minimum(t / max(taper[0], 1e-3), (1 - t) / max(taper[1], 1e-3)), 0, 1) ** 0.6
- offs = np.linspace(-0.5, 0.5, nb) + r.normal(0, 0.04, nb)
- load0 = r.uniform(0.75, 1.0, nb)
- wob = fbm1d(n, 40, 3, int(r.integers(1 << 30))) * jitter * width * 0.5
- rad = int(br * 2 + 2)
- ky, kx = np.mgrid[-rad:rad + 1, -rad:rad + 1].astype(np.float32)
- for b in range(nb):
- load = load0[b] * (1 - dry * t ** 1.2 * r.uniform(0.6, 1.4))
- gate = fbm1d(n, 25, 3, int(r.integers(1 << 30)))
- alive = (load * (0.75 + 0.5 * gate)) > (dry * 0.9)
- for i in range(n):
- if not alive[i]: continue
- w = width * press[i]
- cx = px[i] + nx[i] * (offs[b] * w + wob[i]); cy = py[i] + ny[i] * (offs[b] * w + wob[i])
- ix, iy = int(cx), int(cy)
- if ix < rad or iy < rad or ix >= W - rad - 1 or iy >= H - rad - 1: continue
- k = np.exp(-((kx - (cx - ix)) ** 2 + (ky - (cy - iy)) ** 2) / (2 * (br * press[i]) ** 2 + 1e-3))
- sl = buf[iy - rad:iy + rad + 1, ix - rad:ix + rad + 1]
- np.copyto(sl, 1 - (1 - sl) * (1 - k * ink * load[i] * 0.55))
+ """bristle brush along polyline `pts` (see core.bristle_stroke). red=True paints vermilion."""
+ bristle_stroke(self.R if red else self.D, pts, width, ink, dry, taper, jitter,
+ seed if seed is not None else self._seed())
def dot(self, x, y, r, ink=0.8, squash=1.4, red=False):
"""moss dot / head / seed: soft ellipse"""
diff --git a/lib/papercut.py b/lib/papercut.py
new file mode 100644
index 0000000..300ce60
--- /dev/null
+++ b/lib/papercut.py
@@ -0,0 +1,210 @@
+"""papercut — torn-paper collage with crayon texture (numpy + Pillow only).
+
+Each `piece` is a sheet of paper cut or torn to a shape and glued on:
+ - torn edges : the outline is broken up by fine + medium noise
+ - white rim : where paper tears, its pale core shows as a fibrous light edge
+ - shadow : every piece casts a small soft shadow onto what is below (paper depth)
+ - texture : plain coloured paper / kraft / crayon (waxy grain) / newsprint / ruled notebook
+Plus crayon strokes (waxy lines with paper showing through), stars, and simple cute faces.
+
+ from papercut import Collage, hexc
+ c = Collage(1920, 1080, seed=1)
+ c.background('#1f2a5c', texture='crayon')
+ c.piece(pts, '#f6d77a', texture='crayon')
+ c.save('out.png')
+"""
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+from core import blur, fbm1d, spline, noise2d, smoothstep, polygon_mask, blob_pts, bristle_stroke, cjk_font
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+PAPER_WHITE = hexc('#f7f1e4')
+
+
+class Collage:
+ def __init__(self, W=1920, H=1080, seed=0):
+ self.W, self.H = W, H
+ self.rng = np.random.default_rng(seed)
+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)
+ self.img = np.ones((H, W, 3), np.float32) * PAPER_WHITE
+ self.texts = []
+ self.stages = []
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ def noise(self, scale, octaves=3, seed=None):
+ return noise2d(self.H, self.W, scale, octaves, seed if seed is not None else self._seed())
+
+ # ------------------------------------------------------------ textures
+ def _crayon_grain(self, angle=0.6, density=0.62):
+ """waxy directional grain: 1 where wax sits on the tooth, 0 where paper shows"""
+ n = self.noise(1.6, 2)
+ k = 7
+ dx, dy = np.cos(angle), np.sin(angle)
+ acc = np.zeros_like(n)
+ for i in range(-k, k + 1): # smear along the stroke direction
+ acc += np.roll(np.roll(n, int(round(i * dy)), 0), int(round(i * dx)), 1)
+ acc /= (2 * k + 1)
+ acc = (acc - acc.mean()) / (acc.std() + 1e-6)
+ return smoothstep(-1.2 + 2.4 * (1 - density) - 0.6, -1.2 + 2.4 * (1 - density) + 0.6, acc)
+
+ def _texture(self, colour, texture, angle=0.6):
+ H, W = self.H, self.W
+ base = np.ones((H, W, 3), np.float32) * colour
+ mott = (0.95 + 0.08 * self.noise(50, 3))[..., None]
+ if texture == 'paper':
+ return base * mott
+ if texture == 'kraft':
+ fib = self.noise(2.5, 2)
+ return base * mott * (0.94 + 0.1 * fib)[..., None]
+ if texture == 'crayon':
+ # waxy coverage: gaps show a lighter tint of the same colour (not bare white) -> subtle, not scratchy
+ g = self._crayon_grain(angle, density=0.8)[..., None]
+ under = base * 0.6 + PAPER_WHITE * 0.4
+ return (base * mott) * g + under * (1 - g)
+ if texture == 'newsprint':
+ paper = np.ones((H, W, 3), np.float32) * hexc('#ebe6da') * mott
+ im = Image.new('L', (W, H), 0); d = ImageDraw.Draw(im)
+ y = 0
+ while y < H:
+ x = int(self.rng.integers(0, 14))
+ while x < W:
+ wl = int(self.rng.integers(8, 46))
+ d.rectangle((x, y, x + wl, y + 4), fill=int(self.rng.integers(120, 200)))
+ x += wl + int(self.rng.integers(5, 9))
+ y += 11 if self.rng.random() > 0.05 else 26
+ ink = blur(np.asarray(im, np.float32) / 255, 0.6)[..., None]
+ return paper * (1 - 0.6 * ink)
+ if texture == 'notebook':
+ paper = np.ones((H, W, 3), np.float32) * hexc('#fbf8ef') * mott
+ lines = ((self.YY % 36) < 2).astype(np.float32) * 0.55
+ paper = paper * (1 - lines[..., None] * (1 - hexc('#7fa3d8')))
+ return paper
+ raise ValueError(texture)
+
+ # ------------------------------------------------------------ pieces
+ def background(self, colour, texture='crayon', angle=0.5):
+ self.img = self._texture(hexc(colour) if isinstance(colour, str) else colour, texture, angle)
+
+ def mask_from(self, pts=None, mask=None):
+ return mask if mask is not None else polygon_mask(self.H, self.W, pts, ss=2)
+
+ def piece(self, pts=None, colour='#e07a5f', texture='paper', mask=None, torn=0.6, rim=0.8, shadow=0.35,
+ angle=0.6, cut_side=None):
+ """glue a sheet of paper: outline `pts` (or `mask`), colour, texture.
+ torn: 0 clean scissor cut .. 1 very ragged; rim: white torn edge strength; shadow: depth shadow strength."""
+ col = hexc(colour) if isinstance(colour, str) else colour
+ m0 = self.mask_from(pts, mask)
+ if torn > 0:
+ s1 = self._seed()
+ jag = (noise2d(self.H, self.W, 3, 2, s1) - 0.5) * 0.9 + (noise2d(self.H, self.W, 14, 3, s1 + 1) - 0.5) * 0.9
+ soft = blur(m0, 2.5)
+ m = smoothstep(0.47, 0.53, soft + jag * 0.35 * torn)
+ wide = blur(m0, 6.0) # the torn white core reaches ~5-8 px beyond the colour
+ outer = smoothstep(0.17, 0.23, wide + jag * 0.22 * torn)
+ gate = smoothstep(0.35, 0.6, noise2d(self.H, self.W, 60, 2, s1 + 2)) # tears only along parts of the edge
+ rim_m = np.clip(outer - m, 0, 1) * gate * rim
+ m_all = np.maximum(m, rim_m)
+ else:
+ m = smoothstep(0.4, 0.6, blur(m0, 0.8)); rim_m = np.zeros_like(m); m_all = m
+ if shadow > 0:
+ shifted = np.zeros_like(m_all); shifted[7:, 5:] = m_all[:-7, :-5] # no wrap-around
+ sh = blur(shifted, 6)
+ self.img *= (1 - shadow * sh * (1 - m_all))[..., None]
+ fill = self._texture(col, texture, angle)
+ self.img = self.img * (1 - m[..., None]) + fill * m[..., None]
+ self.img = self.img * (1 - rim_m[..., None]) + (PAPER_WHITE * (0.97 + 0.05 * self.noise(3, 1)[..., None])) * rim_m[..., None]
+ return m
+
+ def circle_mask(self, cx, cy, r):
+ return np.clip((r - np.hypot(self.XX - cx, self.YY - cy)) + 0.5, 0, 1)
+
+ def cloud_mask(self, cx, cy, w, h, puffs=5, seed=None):
+ rng = np.random.default_rng(seed if seed is not None else self._seed())
+ m = np.zeros((self.H, self.W), np.float32)
+ for i in range(puffs):
+ x = cx - w / 2 + w * (i + 0.5) / puffs + rng.normal(0, w * 0.03)
+ r = h * (0.45 + 0.4 * np.sin(np.pi * (i + 0.5) / puffs)) * rng.uniform(0.85, 1.1)
+ m = np.maximum(m, self.circle_mask(x, cy + h * 0.25 - r * 0.6, r))
+ m = np.maximum(m, polygon_mask(self.H, self.W, [(cx - w / 2, cy + h * 0.25), (cx + w / 2, cy + h * 0.25), (cx + w / 2 - 10, cy + h * 0.45), (cx - w / 2 + 10, cy + h * 0.45)]))
+ return m
+
+ @staticmethod
+ def star_pts(cx, cy, r, points=5, inner=0.45, rot=-np.pi / 2):
+ t = np.linspace(0, 2 * np.pi, points * 2, endpoint=False) + rot
+ rr = np.where(np.arange(points * 2) % 2 == 0, r, r * inner)
+ return np.stack([cx + np.cos(t) * rr, cy + np.sin(t) * rr], 1)
+
+ # ------------------------------------------------------------ crayon marks
+ def crayon(self, pts, width, colour, strength=0.9, angle=None):
+ """waxy crayon line: paper tooth breaks it up"""
+ col = hexc(colour) if isinstance(colour, str) else colour
+ buf = np.zeros((self.H, self.W), np.float32)
+ bristle_stroke(buf, pts, width, 1.0, 0.15, (0.1, 0.15), 0.3, self._seed())
+ P = np.asarray(pts, np.float32)
+ ang = angle if angle is not None else float(np.arctan2(P[-1, 1] - P[0, 1], P[-1, 0] - P[0, 0]))
+ g = self._crayon_grain(ang, density=0.7)
+ a = np.clip(buf * 1.4, 0, 1) * g * strength
+ self.img = self.img * (1 - a[..., None]) + col * a[..., None]
+
+ def dot(self, x, y, r, colour, soft=0.8):
+ col = hexc(colour) if isinstance(colour, str) else colour
+ a = np.clip((r - np.hypot(self.XX - x, self.YY - y)) / soft, 0, 1)
+ self.img = self.img * (1 - a[..., None]) + col * a[..., None]
+
+ def glow(self, x, y, r, colour, strength=0.35):
+ col = hexc(colour) if isinstance(colour, str) else colour
+ a = strength * np.exp(-((self.XX - x) ** 2 + (self.YY - y) ** 2) / (2 * r * r))
+ self.img = self.img * (1 - a[..., None]) + col * a[..., None]
+
+ def face(self, cx, cy, r, mood='smile', ink='#2b2430', blush='#f09aa0'):
+ """cute face: closed happy eyes (^ ^) or dot eyes, small smile, blush cheeks"""
+ e = r * 0.34; ey = cy - r * 0.05
+ lw = max(2.0, r * 0.035)
+ if mood in ('smile', 'sleep'):
+ for sx in (-1, 1):
+ x0 = cx + sx * e
+ self.crayon(spline([(x0 - r * 0.11, ey), (x0, ey - r * 0.08 * (1 if mood == 'smile' else -1)), (x0 + r * 0.11, ey)], 6), lw, ink, 1.0)
+ else:
+ for sx in (-1, 1):
+ self.dot(cx + sx * e, ey, max(3, r * 0.07), ink)
+ self.crayon(spline([(cx - r * 0.1, cy + r * 0.22), (cx, cy + r * 0.29), (cx + r * 0.1, cy + r * 0.22)], 6), lw, ink, 1.0)
+ for sx in (-1, 1):
+ self.glow(cx + sx * r * 0.52, cy + r * 0.2, r * 0.1, blush, 0.8)
+
+ # ------------------------------------------------------------ text / output
+ def text(self, s, x, y, size=48, colour='#3a5fa8', vertical=False):
+ self.texts.append((s, x, y, size, colour, vertical))
+
+ def composite(self):
+ out = Image.fromarray((np.clip(self.img, 0, 1) * 255).astype(np.uint8))
+ fp = cjk_font()
+ if self.texts and fp:
+ dr = ImageDraw.Draw(out)
+ for s, x, y, size, colour, vertical in self.texts:
+ f = ImageFont.truetype(fp, size, index=0)
+ c = tuple(int(v * 255) for v in hexc(colour))
+ if vertical:
+ for i, ch in enumerate(s): dr.text((x, y + i * size * 1.15), ch, font=f, fill=c)
+ else:
+ dr.text((x, y), s, font=f, fill=c)
+ return out
+
+ def stage(self, name):
+ self.stages.append((name, self.composite()))
+
+ def save(self, path, stages_dir=None):
+ img = self.composite(); img.save(path)
+ if stages_dir:
+ import os
+ os.makedirs(stages_dir, exist_ok=True)
+ for i, (name, im) in enumerate(self.stages):
+ im.save(f"{stages_dir}/{i:02d}_{name}.png")
+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")
+ return img
diff --git a/lib/watercolor.py b/lib/watercolor.py
new file mode 100644
index 0000000..b7b71fa
--- /dev/null
+++ b/lib/watercolor.py
@@ -0,0 +1,176 @@
+"""watercolor — transparent watercolour on cold-press paper (numpy + Pillow only).
+
+Model: the paper is white; every wash is a *glaze* that multiplies the image by the pigment's
+transmittance img *= 1 - d * (1 - colour) (subtractive, so overlaps darken and mix like real paint).
+Each glaze adds what makes watercolour read as watercolour:
+ - wet edges : pigment migrates to the rim of a wet shape -> darker outline
+ - granulation : pigment settles into the paper tooth -> speckled texture
+ - blooms : back-runs, pale cauliflower patches with dark rims
+ - soft edges : wet-in-wet feathering (mask blurred and noise-thresholded)
+ - lifting : dabbing paint off to recover light (veins, highlights)
+
+ from watercolor import Watercolor, hexc
+ p = Watercolor(1920, 1080, seed=1)
+ p.paper()
+ p.gradient_wash(0, 600, top=hexc('#9cb8d4'), bottom=hexc('#f4d3b4'))
+ p.glaze(p.shape(blob_pts(...), soft=3), hexc('#6f9a5b'), 0.8)
+ p.save('out.png')
+"""
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+from core import blur, fbm1d, curve, spline, noise2d, smoothstep, polygon_mask, blob_pts, bristle_stroke, cjk_font
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+class Watercolor:
+ def __init__(self, W=1920, H=1080, seed=0, paper_tone='#fbf8f1'):
+ self.W, self.H = W, H
+ self.rng = np.random.default_rng(seed)
+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)
+ self.base = np.ones((H, W, 3), np.float32) * hexc(paper_tone)
+ self.img = self.base.copy()
+ self.tooth = np.full((H, W), 0.5, np.float32)
+ self.texts = []
+ self.stages = []
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ def noise(self, scale, octaves=4, seed=None):
+ return noise2d(self.H, self.W, scale, octaves, seed if seed is not None else self._seed())
+
+ # ------------------------------------------------------------ paper
+ def paper(self):
+ """cold-press paper: tooth (height) texture with soft raking light"""
+ t = 0.55 * self.noise(2.5, 2) + 0.3 * self.noise(10, 3) + 0.15 * self.noise(60, 3)
+ self.tooth = t
+ shade = np.gradient(blur(t, 1.0), axis=1) + np.gradient(blur(t, 1.0), axis=0)
+ self.base = self.base * (1 - 0.3 * shade[..., None]) * (0.99 + 0.02 * self.noise(300, 3))[..., None]
+ self.img = self.base.copy()
+
+ # ------------------------------------------------------------ masks
+ def shape(self, pts, soft=2.0, ragged=0.18, seed=None):
+ """closed outline -> soft, slightly ragged mask (0..1). soft ~1-4 crisp wet edge; 15-40 wet-in-wet feather"""
+ m = polygon_mask(self.H, self.W, pts, ss=2)
+ if soft > 0:
+ m = blur(m, soft)
+ n = self.noise(max(6, soft * 3), 3, seed)
+ m = smoothstep(0.5 - 0.25, 0.5 + 0.25, m + (n - 0.5) * ragged)
+ return m
+
+ def band(self, pts, width, soft=2.0):
+ """a thick soft stroke (stems, reeds, rivers) as a mask"""
+ im = Image.new('L', (self.W, self.H), 0)
+ ImageDraw.Draw(im).line([tuple(map(float, p)) for p in pts], fill=255, width=int(width), joint='curve')
+ return blur(np.asarray(im, np.float32) / 255, soft)
+
+ # ------------------------------------------------------------ paint
+ def glaze(self, mask, colour, strength=0.8, edge=0.6, gran=0.35, bloom=0, variation=0.25, seed=None):
+ """transparent wash of `colour` over `mask`. edge: wet-edge darkening; gran: granulation;
+ bloom: number of back-run blooms; variation: patchy pigment density."""
+ seed = seed if seed is not None else self._seed()
+ d = mask * (1 - variation + variation * noise2d(self.H, self.W, 90, 4, seed))
+ ring = np.clip(mask - blur(mask, 5), 0, None)
+ d = d + edge * 2.2 * ring * (mask > 0.2)
+ d = d * (1 + gran * (self.tooth - 0.5) * 2.2)
+ for _ in range(bloom):
+ ys, xs = np.nonzero(mask > 0.6)
+ if len(xs) == 0: break
+ k = int(self.rng.integers(len(xs))); cx, cy = xs[k], ys[k]
+ r0 = self.rng.uniform(25, 70)
+ dist = np.hypot(self.XX - cx, self.YY - cy) / (r0 * (0.8 + 0.4 * noise2d(self.H, self.W, 20, 3, seed + 7)))
+ inner = np.clip(1 - dist, 0, 1)
+ rim = np.exp(-((dist - 1) / 0.08) ** 2)
+ d = d * (1 - 0.55 * inner * mask) + 0.35 * rim * mask
+ d = np.clip(d * strength, 0, 1.3)
+ self.img *= (1 - d[..., None] * (1 - colour))
+
+ def gradient_wash(self, y0, y1, top, bottom, strength=0.7, soft_bottom=60, gran=0.2):
+ """wet-in-wet sky: two colours blending vertically between y0 and y1"""
+ t = np.clip((self.YY - y0) / max(1, (y1 - y0)), 0, 1)
+ t = np.clip(t + (self.noise(260, 4) - 0.5) * 0.25, 0, 1)
+ mask = np.clip((y1 + soft_bottom - self.YY) / (2 * soft_bottom), 0, 1)
+ col = top[None, None, :] * (1 - t[..., None]) + bottom[None, None, :] * t[..., None]
+ d = mask * strength * (0.85 + 0.15 * self.noise(120, 3)) * (1 + gran * (self.tooth - 0.5) * 2)
+ self.img *= (1 - d[..., None] * (1 - col))
+
+ def stroke(self, pts, width, colour, strength=0.8, dry=0.3, taper=(0.2, 0.4), jitter=0.4):
+ """bristle brush stroke in colour (dry-brush texture comes from `dry` + paper tooth)"""
+ buf = np.zeros((self.H, self.W), np.float32)
+ bristle_stroke(buf, pts, width, 1.0, dry, taper, jitter, self._seed())
+ d = np.clip(buf * strength * (1 + 0.5 * (self.tooth - 0.5)), 0, 1)
+ self.img *= (1 - d[..., None] * (1 - colour))
+
+ def line(self, pts, width=1.4, colour=hexc('#5b4a3f'), strength=0.55):
+ """fine pen/pencil line for line-and-wash definition"""
+ self.stroke(pts, width, colour, strength, dry=0.15, taper=(0.1, 0.2), jitter=0.2)
+
+ def lift(self, mask, amount=0.6):
+ """lift paint back toward the paper (highlights, leaf veins)"""
+ a = np.clip(mask * amount, 0, 1)[..., None]
+ self.img = self.img + (self.base - self.img) * a
+
+ def splatter(self, colour, n=40, box=None, size=(1.5, 5), strength=0.7):
+ """flicked droplets"""
+ x0, y0, x1, y1 = box or (0, 0, self.W, self.H)
+ for _ in range(n):
+ x, y = self.rng.uniform(x0, x1), self.rng.uniform(y0, y1)
+ r = self.rng.uniform(*size)
+ m = np.clip((r - np.hypot(self.XX - x, self.YY - y)) / 1.2, 0, 1)
+ self.img *= (1 - (m * strength)[..., None] * (1 - colour))
+
+ # ------------------------------------------------------------ helpers for common subjects
+ @staticmethod
+ def petal_pts(x, y, angle, length, width, n=40, curl=0.0):
+ """a pointed petal/leaf outline from base (x, y) pointing at `angle` (radians)"""
+ t = np.linspace(0, 1, n)
+ half = width * np.sin(np.pi * t) ** 0.8 * (1 - 0.35 * t)
+ ax = t * length
+ off = curl * length * (t ** 2)
+ left = np.stack([ax, half + off], 1); right = np.stack([ax, -half + off], 1)[::-1]
+ P = np.vstack([left, right])
+ c, s = np.cos(angle), np.sin(angle)
+ return np.stack([x + P[:, 0] * c - P[:, 1] * s, y + P[:, 0] * s + P[:, 1] * c], 1)
+
+ # ------------------------------------------------------------ text / output
+ def title_vertical(self, text, x, y, size=84, gap=1.17, color=(70, 60, 55)):
+ self.texts.append(('vtext', (text, x, y, size, gap, color)))
+
+ def seal(self, text, x, y, size=36, color=(186, 58, 46)):
+ self.texts.append(('seal', (text, x, y, size, color)))
+
+ def composite(self):
+ out = Image.fromarray((np.clip(self.img, 0, 1) * 255).astype(np.uint8))
+ font_path = cjk_font()
+ if self.texts and font_path:
+ dr = ImageDraw.Draw(out)
+ for kind, args in self.texts:
+ if kind == 'vtext':
+ text, x, y, size, gap, color = args
+ f = ImageFont.truetype(font_path, size, index=0)
+ for i, ch in enumerate(text):
+ dr.text((x, y + i * size * gap), ch, font=f, fill=color)
+ else:
+ text, x, y, size, color = args
+ f = ImageFont.truetype(font_path, size, index=0)
+ dr.rectangle((x, y, x + size * 1.4, y + size * 1.25 * len(text) + size * 0.3), fill=color)
+ for i, ch in enumerate(text):
+ dr.text((x + size * 0.2, y + size * 0.2 + i * size * 1.25), ch, font=f, fill=(250, 244, 232))
+ return out
+
+ def stage(self, name):
+ self.stages.append((name, self.composite()))
+
+ def save(self, path, stages_dir=None):
+ img = self.composite(); img.save(path)
+ if stages_dir:
+ import os
+ os.makedirs(stages_dir, exist_ok=True)
+ for i, (name, im) in enumerate(self.stages):
+ im.save(f"{stages_dir}/{i:02d}_{name}.png")
+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")
+ return img