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.
Python agent-skillsanimechinese-paintingclaudeclaude-codeclaude-skillscolored-pencilcreative-codingcross-stitcheditorial-illustrationgenerative-artink-wash-paintingoil-paintingpaper-collagepixel-artprocedural-generationrisographshanshuiukiyo-ewatercolor
Claude Drawing (claude绘图): procedural ink-wash painting skill, no image model
cloveric8eadcf04c49f
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..78f6d80--- /dev/null+++ b/.gitignore@@ -0,0 +1,4 @@+__pycache__/+*.pyc+.DS_Store+/out*.pngdiff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..a68c2e0--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 cloveric++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..c917ac0--- /dev/null+++ b/README.md@@ -0,0 +1,178 @@+# Claude Drawing · Claude 绘图++**Claude paints with code — no image model.**+**不用生图模型,Claude 用代码一笔一笔作画。**++[English](#english) · [中文](#中文)++<p align="center">+ <img src="examples/drawing_bawansiqian.gif" width="720" alt="The painting being drawn stage by stage">+</p>++| 八万四千法门 · *Many paths, one summit* | 月印万川 · *One moon in ten thousand rivers* |+|---|---|+|  |  |++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.++---++## English++### 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:++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.++The first built-in style is **Chinese ink wash (水墨)**.++### Why paint with code instead of an image model?++- **Composition you can direct**: placement, empty space and colour 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.++### Install++```bash+git clone https://github.com/cloveric/claude-drawing-skill.git ~/.claude/skills/claude-drawing+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`.++### 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")+```++Or run the examples:++```bash+python3 examples/bawansiqian.py out.png --stages stages/ # also writes the draw-on stage snapshots+python3 examples/moon_river.py moon.png+```++### 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.++### 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.++---++## 中文++### 这是什么++一个 [Claude Code](https://claude.com/claude-code) skill,加上一个小巧的绘图库 `lib/inkpaint.py`,只依赖 numpy + Pillow。对 Claude 说「claude绘图」「你自己画」「用代码画」,它会:+1. **先定构图**:远中近层次、视觉焦点、大片留白、一处朱红点睛;+2. **写一段场景脚本**,调用绘图库;+3. **渲染并自己看图**,对照内置的毛病清单挑问题,一般改 2–4 轮。++目前内置并打磨过的画风是**中国水墨**。++### 为什么用代码画,而不用生图模型++- **构图可控**:位置、留白、朱红点在哪里都精确可控,不靠抽卡。+- **可复现**:同一个随机种子,画出同一幅画。+- **能做「作画过程」动画**:用 `stage()` 按「远山 → 主峰 → 小路 → 松石 → 朱日」存下每一步,视频里就能看到画被一步步画出来(见上面的动图)。生图模型只能给一整张画。+- **哪里都能跑**:离线、只用 CPU,不需要显卡、API Key 或额度;一张 1920×1080 只要 2–4 秒。++### 安装++```bash+git clone https://github.com/cloveric/claude-drawing-skill.git ~/.claude/skills/claude-drawing+pip install -r ~/.claude/skills/claude-drawing/requirements.txt # numpy、Pillow+```++题字和印章需要中文字体。macOS 的楷体/宋体、Linux 的 Noto CJK、Windows 的楷体/宋体都会自动找到,也可以用 `INKPAINT_FONT=字体路径` 指定。++### 快速上手++见上方英文部分的代码示例,或直接运行两个范例:++```bash+python3 examples/bawansiqian.py out.png --stages stages/ # 八万四千法门,同时输出分阶段快照+python3 examples/moon_river.py moon.png # 月印万川+```++### 工具箱++| 调用 | 画什么 |+|---|---|+| `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 交图前逐条自查)++- 后面的远山透过主峰 → 先远后近,每层墨染都遮挡身后的层+- 笔画像梯子、像串珠 → 落笔间距跟笔毛粗细挂钩+- 小路像头发丝 → 条数少一些,用样条曲线平滑,只画在山体上,从雾里伸出来+- 皴擦像撒了一片逗号 → 少而长,顺着坡向,集中在阴面+- 山脊像卡通描边 → 山脊线要淡而断续,边缘主要靠墨染的水痕+- 松针像海胆 → 扇形松针,下面垫一团淡墨+- 画面发闷 → 留白至少四成,朱红最多一两处++### 计划++- 在同一套笔刷、纸纹、墨染的底层上扩展更多画风:水彩、撕纸拼贴。+- 按笔画分层导出,方便在 Motion Canvas / Remotion 里做逐笔动画。++---++MIT License · Made by Claude (Opus 5.5) with [@cloveric](https://github.com/cloveric)diff --git a/SKILL.md b/SKILL.mdnew file mode 100644index 0000000..e7b7e36--- /dev/null+++ b/SKILL.md@@ -0,0 +1,89 @@+---+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。+---++# Claude 绘图++用 Python(只依赖 numpy + Pillow,系统自带的 `python3` 就能跑)按笔画和墨色的物理规律「画」图,不调用任何生图模型。+- **画面**:每一笔都是算出来的,可以精确控制构图、留白、朱红点缀的位置。+- **结果可复现**:固定随机种子后,同一段代码每次画出同一幅画。+- **适合做动画**:可以按「先远山、再主峰、再小路……」的顺序出分阶段快照,做成逐步画出的动画;生图模型只能给一整张画。++`examples/bawansiqian.jpg`(八万四千法门)和 `examples/moon_river.jpg`(月印万川)是水墨风的质量基准。++## 一、流程(每幅画都照做)++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`)++```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)+```++**顺序很重要**:先远后近(`wash` 会遮挡前面已画的层),雾要画在它该吞没的东西之后,题字和印章最后叠加。++## 三、毛病清单(都真实出现过,自查时逐条过)++| 看到的问题 | 原因 | 改法 |+|---|---|---|+| 后面的远山线条透过前面的主峰 | 层与层直接叠加,没有遮挡 | `wash(occlude=True)`(默认),并且先远后近 |+| 笔画像梯子或一串珠子 | 笔毛太细、落笔点间距太大 | 库里已经按笔毛大小自动算间距;自己写笔刷时也要这样 |+| 小路像头发丝、像根须 | 线太多、太弯、跑出山体 | 16 条左右,用样条平滑,起点在山脚雾里,只画在山体上 |+| 路是折线,像裂缝或图表 | 用直线段连接转折点 | 一律用 `spline()` 连接控制点 |+| 皴擦像撒了一片逗号 | 短笔太多、太匀、方向乱 | 减到约 150 笔,加长,顺着坡向,集中在阴面 |+| 山像卡通描边 | 山脊线太重太连续 | 山脊线用淡墨(0.3)加飞白,主要靠墨染的水痕边和苔点 |+| 松针像海胆 | 放射状的针太黑太满 | 扇形松针(上半圈)加底下一团淡墨晕 |+| 主峰像规整的锥子 | 左右对称、没有起伏 | 左右坡宽度不同,加山肩,加分形起伏 |+| 画面发闷 | 留白不够、朱红太多 | 留白至少四成,朱红最多一两处 |++## 四、做成动画++- **简单做法**:用 `p.stage()` 分阶段快照(远山 → 主峰 → 小路 → 松石 → 日与题字),在视频里依次淡入叠化,看起来就是一幅画被逐步画出来。+- **更细的做法**:把某一组笔画单独画到透明层上导出,在 Motion Canvas 里用遮罩按笔画顺序显现。这需要给笔画分组,还没做成现成接口,用到时再加。++## 五、扩展到别的画风++笔刷、纸纹、墨染这套底层可以改造成水彩(彩色墨染 + 水痕边 + 颗粒)或剪纸拼贴(撕纸毛边 = 噪声扰动多边形边缘 + 纸纹)。++**目前只有水墨风做过并经用户认可**,别的画风第一次做时先出一张给用户看。++## 六、文件++```+lib/inkpaint.py 绘图库(Painting 类 + 辅助函数,只依赖 numpy + Pillow)+examples/bawansiqian.py 范例「八万四千法门」:层层远山、主峰、小路汇顶、松石、朱日(约 3.6 秒)+examples/moon_river.py 范例「月印万川」:烘云托月、孤舟垂钓、芦苇、水面月影(约 2 秒)+examples/*.jpg / drawing_*.gif 成品与逐步画出的动图+中文字体:自动找 Kaiti/Songti(macOS)、Noto CJK(Linux)、KaiTi/SimSun(Windows),或设 INKPAINT_FONT+```diff --git a/examples/bawansiqian.jpg b/examples/bawansiqian.jpgnew file mode 100644index 0000000..8285aa2Binary files /dev/null and b/examples/bawansiqian.jpg differdiff --git a/examples/bawansiqian.py b/examples/bawansiqian.pynew file mode 100644index 0000000..47ee579--- /dev/null+++ b/examples/bawansiqian.py@@ -0,0 +1,52 @@+"""范例:「八万四千法门」— 很多条路,同一个山顶。纯代码水墨,约 3 秒出图。+python3 bawansiqian.py [out.png] [--stages DIR]+"""+import os, sys+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+from inkpaint import Painting++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'bawansiqian.png'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None++p = Painting(1920, 1080, seed=84000)+p.paper()+p.stage('宣纸')++# far -> near: each wash occludes what is behind it+far = p.ridge(560, peaks=[(420, 150, 330), (1650, 110, 260)], rough=26, rough_scale=220, seed=11)+p.wash(far, dens=0.16, decay=170, tex=140, edge=0.25, mist_y=700, mist_h=110, seed=21)+mid = p.ridge(690, peaks=[(700, 120, 260), (1580, 150, 300)], rough=30, rough_scale=160, seed=12)+p.wash(mid, dens=0.26, decay=150, tex=110, edge=0.3, mist_y=800, mist_h=90, seed=31)+p.stage('远山')++SX, SY = 1130, 252+main = p.peak(SX, SY, height=560, left_w=360, right_w=470, shoulders=[(SX + 250, 70, 90), (SX - 300, 45, 110)], seed=13)+p.wash(main, dens=0.46, decay=240, tex=90, edge=0.45, mist_y=920, mist_h=80, seed=41)+p.cun(main, SX - 600, SX + 600, n=150, shadow_x=SX, max_y=960)+p.moss(main, SX - 600, SX + 620, n=70)+p.ridge_line(main, SX - 680, SX + 640)+p.stage('主峰')++paths = p.trails(main, (SX, SY), n=16, red_index=7, seed=5)+p.mist(960, 70, 0.8)+p.mist(760, 45, 0.55)+for (i, t) in [(3, 0.45), (9, 0.35), (12, 0.6), (5, 0.3), (7, 0.62)]:+ q = paths[i][int(t * (len(paths[i]) - 1))]+ p.traveller(q[0], q[1])+p.pagoda(SX, SY)+p.stage('小路')++rock = 800 + 280 * ((p.xs / 640) ** 1.6) + 30 * __import__('inkpaint').fbm1d(1920, 70, 4, 91)+rock[p.xs > 640] = 2000+p.rock(rock)+p.pine((250, 1000), (330, 600), bend=70,+ branches=[((304, 760), (480, 705), -34), ((318, 690), (170, 648), 28), ((326, 640), (455, 588), -22), ((292, 830), (150, 808), 22)],+ extra_tufts=[(335, 590), (395, 612)])+p.stage('松石')++p.sun(1500, 190, 46)+p.birds([(1330, 300, 1.0), (1370, 322, 0.8), (1300, 334, 0.7)])+p.title_vertical('八万四千', 150, 150, 92)+p.seal('法门', 262, 176, 40)+p.save(out, stages_dir=stages)+print('saved', out)diff --git a/examples/drawing_bawansiqian.gif b/examples/drawing_bawansiqian.gifnew file mode 100644index 0000000..590e969Binary files /dev/null and b/examples/drawing_bawansiqian.gif differdiff --git a/examples/drawing_moon_river.gif b/examples/drawing_moon_river.gifnew file mode 100644index 0000000..473b4acBinary files /dev/null and b/examples/drawing_moon_river.gif differdiff --git a/examples/moon_river.jpg b/examples/moon_river.jpgnew file mode 100644index 0000000..659d473Binary files /dev/null and b/examples/moon_river.jpg differdiff --git a/examples/moon_river.py b/examples/moon_river.pynew file mode 100644index 0000000..f545b35--- /dev/null+++ b/examples/moon_river.py@@ -0,0 +1,94 @@+"""范例:「月印万川」— 烘云托月、孤舟、芦苇。纯代码水墨。+python3 moon_river.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 inkpaint import Painting, spline, curve, blur++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'moon_river.png'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None++p = Painting(1920, 1080, seed=2026)+p.paper()+p.stage('宣纸')+YY, XX, rng = p.YY, p.XX, p.rng++# ---- night sky wash that leaves the moon as bare paper (烘云托月)+MX, MY, MR = 1360, 250, 74+horizon = 610+dist = np.hypot(XX - MX, YY - MY)+sky = 0.30 * np.clip(1 - YY / horizon, 0, 1) ** 0.8 * (0.6 + 0.4 * p.noise2d(220, 4, 3))+sky *= np.clip((horizon - YY) / 140, 0, 1) ** 0.7 # fades out toward the water line+moon = np.clip((MR - dist) / 3, 0, 1)+halo = np.exp(-((dist - MR) / 60) ** 2) * (dist > MR)+sky = sky * (1 - moon) * (1 - 0.55 * np.exp(-(np.clip(dist - MR, 0, None) / 90))) # lighter glow near the moon+sky += 0.06 * halo * (0.6 + 0.4 * p.noise2d(40, 3, 4))+p.over(p.D, sky)+p.stage('夜空')++# ---- distant hills, very pale, sitting on the water line+# hills are bumps rising from below the water line, so the open water under the moon stays clean+far = p.ridge(horizon + 60, peaks=[(260, 150, 260), (640, 110, 200), (1760, 120, 230)], rough=12, rough_scale=200, seed=21)+p.wash(far, dens=0.2, decay=45, tex=90, edge=0.35, seed=22)+np.multiply(p.D, 1 - np.clip((YY - horizon) / 5, 0, 1), out=p.D) # everything stops at the water line+p.stage('远山')++# ---- water: moon reflection (broken pale strokes) and sparse ripples+for i in range(14):+ y = horizon + 30 + i * 22 + rng.normal(0, 3)+ half = 70 * (1 - i / 16) + rng.uniform(-10, 10)+ x0 = MX - half + rng.normal(0, 12)+ p.stroke(spline([(x0, y), (MX + rng.normal(0, 10), y + rng.normal(0, 1.5)), (MX + half, y)], 10), 1.6, 0.16, dry=0.55, taper=(0.3, 0.3))+for _ in range(40):+ x = rng.uniform(80, 1840); y = rng.uniform(horizon + 40, 1000)+ if abs(x - MX) < 150: continue+ ln = rng.uniform(40, 140) * (0.6 + (y - horizon) / 500)+ p.stroke(spline([(x, y), (x + ln / 2, y + rng.normal(0, 1.2)), (x + ln, y)], 8), 1.3, 0.13 + 0.1 * (y - horizon) / 470, dry=0.6, taper=(0.3, 0.3))+p.stage('江面')++# ---- lone boat with a fisherman+BX, BY = 760, 742+hull = spline([(BX - 120, BY - 8), (BX - 60, BY + 12), (BX + 40, BY + 14), (BX + 118, BY - 14)], 12)+p.stroke(hull, 7, 0.85, dry=0.25, taper=(0.1, 0.2))+p.stroke(spline([(BX - 108, BY - 4), (BX, BY + 6), (BX + 104, BY - 10)], 10), 2.2, 0.5, dry=0.4)+cover = spline([(BX + 10, BY - 4), (BX + 38, BY - 38), (BX + 78, BY - 36), (BX + 96, BY - 8)], 10) # woven canopy+p.stroke(cover, 4, 0.7, dry=0.35)+for k in range(5):+ x = BX + 22 + k * 15+ p.stroke([(x, BY - 34 + abs(k - 2) * 2), (x + 2, BY - 6)], 1.2, 0.45, dry=0.4)+FX, FY = BX - 58, BY - 10 # the fisherman+p.stroke(spline([(FX - 10, FY), (FX - 4, FY - 22), (FX + 4, FY - 32)], 8), 6, 0.8, dry=0.2, taper=(0.1, 0.3))+p.stroke(spline([(FX - 18, FY - 34), (FX + 3, FY - 50), (FX + 22, FY - 33)], 8), 3, 0.85, dry=0.15, taper=(0.1, 0.1)) # straw hat+p.stroke(spline([(FX + 2, FY - 22), (FX - 80, FY - 120), (FX - 210, FY - 170)], 14), 1.4, 0.7, dry=0.2, taper=(0.05, 0.6)) # rod+p.stroke(spline([(FX - 210, FY - 170), (FX - 214, FY - 60), (FX - 212, FY + 30)], 12), 0.8, 0.35, dry=0.3, taper=(0.05, 0.05)) # line+for r_ in (10, 20):+ p.stroke(spline([(FX - 212 - r_ * 2, FY + 34), (FX - 212, FY + 34 + r_ * 0.25), (FX - 212 + r_ * 2, FY + 34)], 8), 1.1, 0.25, dry=0.5)+p.stroke(spline([(BX - 150, BY + 22), (BX, BY + 30), (BX + 150, BY + 20)], 10), 1.4, 0.18, dry=0.6) # boat's shadow ripple+p.stage('孤舟')++# ---- reeds in the lower-right foreground+for i in range(22):+ back = i < 8 # paler reeds behind for depth+ x0 = rng.uniform(1500, 1900); y0 = 1085+ h = rng.uniform(220, 420)+ lean = rng.uniform(-70, 40)+ top = (x0 + lean, y0 - h)+ stem = spline([(x0, y0), (x0 + lean * 0.35 + rng.normal(0, 6), y0 - h * 0.5), top], 12)+ p.stroke(stem, rng.uniform(1.4, 2.4), rng.uniform(0.18, 0.3) if back else rng.uniform(0.45, 0.72), dry=0.4, taper=(0.02, 0.7))+ for _ in range(int(rng.integers(1, 3))): # blade leaves+ k = int(rng.integers(8, 20)); q = stem[k]+ side = rng.choice([-1, 1]); ln = rng.uniform(60, 130)+ p.stroke(spline([tuple(q), (q[0] + side * ln * 0.5, q[1] - ln * 0.35), (q[0] + side * ln, q[1] - ln * 0.1)], 8),+ rng.uniform(3, 5), rng.uniform(0.15, 0.25) if back else rng.uniform(0.4, 0.65), dry=0.45, taper=(0.05, 0.9))+ if rng.random() < 0.55: # plume+ for _ in range(7):+ p.stroke([top, (top[0] + rng.normal(-14, 8), top[1] + rng.uniform(18, 34))], 1.1, 0.35, dry=0.5, taper=(0.1, 0.8))+p.mist(1000, 60, 0.45)+p.stage('芦苇')++p.birds([(560, 330, 0.8), (600, 348, 0.6)])+p.title_vertical('月印万川', 150, 150, 92)+p.seal('禅心', 262, 176, 40)+p.save(out, stages_dir=stages)+print('saved', out)diff --git a/lib/inkpaint.py b/lib/inkpaint.pynew file mode 100644index 0000000..7fee22b--- /dev/null+++ b/lib/inkpaint.py@@ -0,0 +1,391 @@+"""inkpaint — procedural painting toolkit (numpy + Pillow only, no image model).++Everything is computed: rice paper, layered ink-wash mountains with mist, bristle brush strokes+with flying-white (飞白), texture strokes (皴), moss dots, pines, vermilion sun, birds, calligraphy.++ import sys; sys.path.insert(0, "<skill>/lib")+ from inkpaint import Painting, spline, curve, fbm1d+ p = Painting(1920, 1080, seed=7)+ p.paper()+ far = p.ridge(560, peaks=[(420, 150, 330), (1650, 110, 260)], rough=26)+ p.wash(far, dens=0.16, decay=170, mist_y=700)+ ...+ p.save("out.png")++Ink model: every mark adds density to a float buffer (ink `D` or vermilion `R`) with+over(): D = 1-(1-D)(1-a). Final colour = paper multiplied by ink, like pigment on paper.+Front wash layers occlude what is behind them (see wash()).+"""+import glob+import numpy as np+from PIL import Image, ImageDraw, ImageFont++INK = np.array([28, 26, 24], np.float32) / 255+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+++# ================================================================ the painting+class Painting:+ 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.xs = np.arange(W, dtype=np.float32)+ self.paper_rgb = np.ones((H, W, 3), np.float32) * PAPER+ self.D = np.zeros((H, W), np.float32) # ink density+ self.R = np.zeros((H, W), np.float32) # vermilion density+ self.texts = [] # (kind, args) drawn at save time+ self.stages = [] # snapshots for draw-on animation++ # ------------------------------------------------------------ noise / compositing+ def noise2d(self, scale, octaves=4, seed=0):+ r = np.random.default_rng(seed)+ out = np.zeros((self.H, self.W), np.float32); amp = 1.0; tot = 0.0+ for o in range(octaves):+ gh, gw = max(2, int(self.H / scale * 2 ** o) + 2), max(2, int(self.W / scale * 2 ** o) + 2)+ g = Image.fromarray(r.random((gh, gw)).astype(np.float32), mode='F')+ out += amp * np.asarray(g.resize((self.W, self.H), Image.BICUBIC), np.float32)+ tot += amp; amp *= 0.5+ out /= tot+ return (out - out.min()) / (out.max() - out.min() + 1e-6)++ @staticmethod+ def over(buf, a):+ np.copyto(buf, 1 - (1 - buf) * (1 - np.clip(a, 0, 1)))++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ------------------------------------------------------------ paper+ def paper(self, fibers=2600, tone=PAPER):+ H, W, rng = self.H, self.W, self.rng+ p = np.ones((H, W, 3), np.float32) * np.asarray(tone, np.float32)+ p *= (0.965 + 0.05 * self.noise2d(260, 5, 1))[..., None]+ p *= (1 + 0.012 * blur(rng.normal(0, 1, (H, W)).astype(np.float32), 0.6))[..., None]+ fib = Image.new('L', (W, H), 0); fd = ImageDraw.Draw(fib)+ for _ in range(fibers):+ x, y = rng.uniform(0, W), rng.uniform(0, H)+ ang, ln = rng.uniform(0, np.pi), rng.uniform(8, 40)+ fd.line([(x + np.cos(ang + 0.3 * np.sin(t)) * t, y + np.sin(ang + 0.3 * np.sin(t)) * t) for t in np.linspace(0, ln, 6)],+ fill=int(rng.uniform(10, 26)), width=1)+ p *= (1 - 0.35 * blur(np.asarray(fib, np.float32) / 255, 0.5))[..., None]+ self.paper_rgb = p++ # ------------------------------------------------------------ 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))++ def dot(self, x, y, r, ink=0.8, squash=1.4, red=False):+ """moss dot / head / seed: soft ellipse"""+ self.over(self.R if red else self.D, ink * np.exp(-((self.XX - x) ** 2 + ((self.YY - y) * squash) ** 2) / (2 * r * r)))++ # ------------------------------------------------------------ landscape+ def ridge(self, base, peaks=(), rough=24, rough_scale=180, seed=None):+ """ridgeline y(x): base minus gaussian peaks (x, height, width) plus fractal roughness"""+ y = np.full(self.W, float(base), np.float32)+ for (px, h, w) in peaks:+ y -= h * np.exp(-((self.xs - px) / w) ** 2)+ return y + rough * fbm1d(self.W, rough_scale, 5, seed if seed is not None else self._seed())++ def peak(self, sx, sy, height=560, left_w=360, right_w=470, power=1.15, shoulders=(), rough=26, seed=None):+ """a main mountain: cone-ish peak at (sx, sy) with asymmetric slopes and optional shoulders (x, h, w)"""+ xs = self.xs+ y = sy + height * (1 - np.exp(-np.abs(xs - sx) / np.where(xs < sx, left_w, right_w))) ** power+ for (x, h, w) in shoulders:+ y -= h * np.exp(-((xs - x) / w) ** 2)+ y += rough * fbm1d(self.W, 70, 5, seed if seed is not None else self._seed()) * np.clip(np.abs(xs - sx) / 120, 0, 1)+ return y++ def wash(self, ridge, dens=0.3, decay=180, tex=110, edge=0.35, mist_y=None, mist_h=100, occlude=True, seed=None):+ """ink-wash mass below `ridge`: dark at the top edge, fading downward, textured, with a wet rim.+ Front layers occlude what was painted behind (paint far -> near)."""+ seed = seed if seed is not None else self._seed()+ depth = self.YY - ridge[None, :]+ body = np.where(depth > 0, np.exp(-depth / decay), 0).astype(np.float32)+ tx = 0.55 + 0.45 * self.noise2d(tex, 4, seed)+ a = body * np.clip((depth + 2) / 5, 0, 1) * tx * (0.85 + 0.15 * self.noise2d(6, 2, seed + 1)) * dens+ m = (depth > 0).astype(np.float32)+ a += np.clip(blur(m, 2.2) - blur(m, 9), 0, None) * dens * edge * tx+ if mist_y is not None:+ a *= 1 - 0.92 * np.exp(-((self.YY - mist_y - 60 * (self.noise2d(400, 3, seed + 2) - 0.5)) / mist_h) ** 2)+ if occlude:+ np.multiply(self.D, 1 - 0.97 * np.clip((depth + 1) / 6, 0, 1), out=self.D)+ self.over(self.D, a)+ return a++ def mist(self, y, h=70, strength=0.8, patchy=True, seed=None):+ """horizontal mist band that lifts ink (paint it after the things it should swallow)"""+ seed = seed if seed is not None else self._seed()+ m = np.exp(-((self.YY - y - 50 * (self.noise2d(380, 3, seed) - 0.5)) / h) ** 2)+ if patchy: m *= 0.6 + 0.4 * self.noise2d(160, 3, seed + 1)+ np.multiply(self.D, 1 - strength * m, out=self.D)++ def cun(self, ridge, x0, x1, n=150, shadow_x=None, spread=70, max_y=None, ink=0.26):+ """dry texture strokes (皴) hanging from a ridge, denser/darker on the shadow side (x < shadow_x)"""+ rng = self.rng+ max_y = max_y if max_y is not None else self.H - 60+ sx = shadow_x if shadow_x is not None else (x0 + x1) / 2+ for _ in range(n):+ left = rng.random() < 0.72+ x = rng.uniform(x0, sx - 20) if left else rng.uniform(sx + 20, x1)+ top = ridge[int(np.clip(x, 0, self.W - 1))]+ dd = abs(rng.normal(0, spread)); y = top + 10 + dd+ if y > max_y: continue+ dirx = np.sign(sx - x)+ ln = rng.uniform(40, 120)+ ctrl = [(x, y), (x - dirx * ln * 0.25 + rng.normal(0, 6), y + ln * 0.5), (x - dirx * ln * 0.55 + rng.normal(0, 10), y + ln)]+ self.stroke(spline(ctrl, 8), rng.uniform(1.6, 3.6), (ink if left else ink * 0.55) * np.exp(-dd / 150), dry=0.65)++ def moss(self, ridge, x0, x1, n=70, depth=(2, 26)):+ """moss dots (苔点) along a ridge"""+ for _ in range(n):+ x = self.rng.uniform(x0, x1)+ self.dot(x, ridge[int(np.clip(x, 0, self.W - 1))] + self.rng.uniform(*depth), self.rng.uniform(1.6, 3.4), 0.75)++ def ridge_line(self, ridge, x0, x1, width=2.2, ink=0.3):+ """light, broken ridge accent — keep it light or it reads as a cartoon outline"""+ pts = np.stack([self.xs[::6], ridge[::6] + 2], 1)+ pts = pts[(pts[:, 0] > x0) & (pts[:, 0] < x1)]+ self.stroke(pts, width, ink, dry=0.6, taper=(0.1, 0.1))++ def trails(self, ridge, summit, n=16, x_range=None, start_y=(930, 990), red_index=None, seed=None):+ """winding switchback trails from the foot to one summit; returns the list of trail polylines"""+ rng = np.random.default_rng(seed if seed is not None else self._seed())+ SX, SY = summit+ lo, hi = x_range if x_range else (SX - 560, SX + 620)+ out = []+ for i in range(n):+ for _ in range(50):+ sx = rng.uniform(lo, hi)+ if ridge[int(np.clip(sx, 0, self.W - 1))] < start_y[0] - 30: break+ sy = rng.uniform(*start_y)+ zig = int(rng.integers(4, 8)); pts = []+ for k in range(zig + 1):+ t = k / zig+ amp = (1 - t) * rng.uniform(40, 110)+ pts.append((sx + (SX - sx) * t ** 0.9 + amp * (1 if k % 2 else -1), sy + (SY + 10 - sy) * t))+ pts[-1] = (SX + rng.normal(0, 2), SY + 10)+ c = spline(pts, 16)+ c[:, 1] = np.maximum(c[:, 1], ridge[np.clip(c[:, 0].astype(int), 0, self.W - 1)] + 5)+ out.append(c)+ for i, c in enumerate(out):+ if i == red_index:+ self.stroke(c, 2.0, 0.8, dry=0.3, jitter=0.2, red=True)+ else:+ self.stroke(c, rng.uniform(1.1, 1.5), rng.uniform(0.24, 0.34), dry=0.55, jitter=0.3)+ return out++ # ------------------------------------------------------------ motifs+ def pine(self, root, top, bend=70, branches=(), extra_tufts=(), trunk_w=16):+ """写意 pine: trunk + bark arcs + branches + fan-shaped needle tufts over a soft wash"""+ rng = self.rng+ trunk = curve(root, top, bend, 30, wig=12, seed=self._seed())+ self.stroke(trunk, trunk_w, 0.62, dry=0.35, taper=(0.02, 0.45), jitter=0.5)+ for _ in range(18):+ q = trunk[int(rng.integers(3, 26))]+ self.stroke(curve((q[0] - 7, q[1] + rng.uniform(-3, 3)), (q[0] + 5, q[1] + rng.uniform(4, 10)), rng.normal(-3, 2), 8), 1.4, 0.3, dry=0.5, taper=(0.3, 0.3))+ tips = list(extra_tufts)+ for (a0, b0, bnd) in branches:+ c = curve(a0, b0, bnd, 20, wig=7, seed=self._seed())+ self.stroke(c, trunk_w * 0.44, 0.62, dry=0.4, taper=(0.03, 0.55))+ tips += [tuple(b0), tuple(c[12])]+ for (bx, by) in tips:+ for _ in range(2):+ cx, cy = bx + rng.normal(0, 16), by + rng.normal(0, 8)+ self.over(self.D, 0.22 * np.exp(-(((self.XX - cx) / 46) ** 2 + ((self.YY - cy + 8) / 20) ** 2)))+ for a in np.linspace(-np.pi * 0.95, -np.pi * 0.05, 17):+ ln = rng.uniform(26, 42)+ self.stroke([(cx, cy + 4), (cx + np.cos(a) * ln, cy + np.sin(a) * ln * 0.5)], 1.2, 0.55, dry=0.25, taper=(0.05, 0.6))++ def rock(self, ridge, dens=0.7, texture=45):+ """dense foreground rock mass with dry texture"""+ self.wash(ridge, dens=dens, decay=260, tex=50, edge=0.6)+ rng = self.rng+ xs_ok = np.where(ridge < self.H)[0]+ if len(xs_ok) == 0: return+ for _ in range(texture):+ x = rng.uniform(xs_ok.min() + 10, xs_ok.max() - 10); top = ridge[int(x)]+ y = top + abs(rng.normal(0, 60)) + 6+ if y > self.H - 5: continue+ self.stroke(curve((x, y), (x + rng.normal(-12, 10), y + rng.uniform(20, 60)), rng.normal(0, 8), 10), rng.uniform(2.5, 5), 0.3, dry=0.7)++ def sun(self, x, y, r=46, red=True):+ dist = np.hypot(self.XX - x, self.YY - y)+ disc = (dist < r).astype(np.float32)+ s = np.clip((r - dist) / 2.5, 0, 1) * (0.78 + 0.22 * self.noise2d(12, 3, self._seed()))+ s += np.clip(blur(disc, 3) - blur(disc, 10), 0, None) * 0.35+ self.over(self.R if red else self.D, s * 0.9)++ def birds(self, items):+ """items: [(x, y, scale)] — two-stroke flying birds"""+ for (bx, by, s) in items:+ self.stroke(curve((bx - 14 * s, by), (bx, by + 2 * s), -6 * s, 8), 1.6, 0.7, dry=0.2)+ self.stroke(curve((bx, by + 2 * s), (bx + 14 * s, by - 2 * s), -6 * s, 8), 1.6, 0.7, dry=0.2)++ def pagoda(self, x, y):+ """tiny pagoda/pavilion sitting on (x, y)"""+ for (a, b) in [((x - 16, y - 6), (x + 16, y - 6)), ((x - 12, y - 16), (x + 12, y - 16)), ((x - 8, y - 25), (x + 8, y - 25))]:+ self.stroke(curve(a, b, -3, 10), 2.2, 0.8, dry=0.15, taper=(0.2, 0.2))+ self.stroke([(x, y - 36), (x, y - 25)], 1.6, 0.8, dry=0.1)+ for a in (-6, 6):+ self.stroke([(x + a, y - 6), (x + a, y + 6)], 1.6, 0.7, dry=0.1)++ def traveller(self, x, y):+ """a tiny walking figure standing at (x, y)"""+ self.stroke([(x, y - 7), (x + 0.5, y + 3)], 2.4, 0.75, dry=0.1, taper=(0.3, 0.3))+ self.dot(x, y - 11, 1.5, 0.8, squash=1.0)++ # ------------------------------------------------------------ text (rendered at save time, on top)+ def title_vertical(self, text, x, y, size=92, gap=1.17, color=(34, 31, 29)):+ self.texts.append(('vtext', (text, x, y, size, gap, color)))++ def seal(self, text, x, y, size=40, color=(172, 50, 40)):+ self.texts.append(('seal', (text, x, y, size, color)))++ # ------------------------------------------------------------ output+ def composite(self):+ img = self.paper_rgb * (1 - self.D[..., None] * (1 - INK))+ img = img * (1 - self.R[..., None] * (1 - VERMILION / np.maximum(self.paper_rgb, 1e-3)).clip(0, 1))+ out = Image.fromarray((np.clip(img, 0, 1) * 255).astype(np.uint8))+ font_path = kaiti_font()+ if self.texts and not font_path:+ print('inkpaint: no CJK font found (set INKPAINT_FONT); titles/seals skipped')+ if font_path and self.texts:+ 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)+ w, h = size * 1.4, size * 1.25 * len(text) + size * 0.3+ dr.rectangle((x, y, x + w, y + h), 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=(244, 238, 226))+ return out++ def stage(self, name):+ """snapshot the painting so far (for a stage-by-stage draw-on animation)"""+ 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 imgdiff --git a/requirements.txt b/requirements.txtnew file mode 100644index 0000000..220ee24--- /dev/null+++ b/requirements.txt@@ -0,0 +1,2 @@+numpy>=1.24+Pillow>=10.0