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 chalkboard and cyberpunk styles (17 styles); GIF grid 4×4, gallery 9×2

clovericcc7b04867b91
diff --git a/README.md b/README.md
index 93cdd03..f2102a5 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,7 @@
# Claude Drawing · Claude 绘图
-**Claude paints with code — no image model.** Fifteen styles, from ink wash and impasto oil to clay, cyanotype, cross-stitch, sticker collage and a lab notebook.
-**不用生图模型,Claude 用代码一笔一笔作画。** 十五种画风,从水墨、油画到黏土、蓝晒、十字绣、贴纸小票和实验笔记本。
+**Claude paints with code — no image model.** Seventeen styles, from ink wash and impasto oil to clay, cyanotype, cross-stitch, sticker collage, a lab notebook, a chalkboard and a cyberpunk street.
+**不用生图模型,Claude 用代码一笔一笔作画。** 十七种画风,从水墨、油画到黏土、蓝晒、十字绣、贴纸小票、实验笔记本、黑板板书和赛博朋克。
[English](#english) · [中文](#中文)
@@ -14,10 +14,8 @@
| ![editorial](examples/drawing_editorial_ideas.gif) | ![oil](examples/drawing_oil_wheatfield.gif) | ![ukiyoe](examples/drawing_ukiyoe_fuji.gif) | ![pixel](examples/drawing_pixel_rainy_cafe.gif) |
| **Stop-motion clay · 黏土定格** | **Cyanotype · 蓝晒** | **Cross-stitch · 十字绣** | **Retro panel · 复古仪器面板** |
| ![clay](examples/drawing_clay_lighthouse.gif) | ![cyanotype](examples/drawing_cyanotype_botanicals.gif) | ![stitch](examples/drawing_stitch_sampler.gif) | ![panel](examples/drawing_panel_radio.gif) |
-
-| Sticker collage × receipt · 贴纸拼贴 · 小票 | Lab notebook × stickers · 实验笔记本 · 贴纸 |
-|---|---|
-| ![sticker](examples/drawing_sticker_market.gif) | ![notebook](examples/drawing_notebook_brewing.gif) |
+| **Sticker collage × receipt · 贴纸拼贴 · 小票** | **Lab notebook × stickers · 实验笔记本 · 贴纸** | **Chalkboard · 黑板板书** | **Cyberpunk · 赛博朋克** |
+| ![sticker](examples/drawing_sticker_market.gif) | ![notebook](examples/drawing_notebook_brewing.gif) | ![chalk](examples/drawing_chalk_lesson.gif) | ![cyberpunk](examples/drawing_cyberpunk_neon_street.gif) |
### Gallery · 画廊
@@ -39,8 +37,10 @@
| <img src="examples/stitch_sampler.jpg" width="100%"> | <img src="examples/panel_radio.jpg" width="100%"> |
| **周末市集** · *Weekend Market*<br><sub>Sticker collage × receipt · 贴纸拼贴 · 小票</sub> | **咖啡萃取实验** · *Coffee Brewing Experiment*<br><sub>Lab notebook × stickers · 实验笔记本 · 贴纸</sub> |
| <img src="examples/sticker_market.jpg" width="100%"> | <img src="examples/notebook_brewing.jpg" width="100%"> |
+| **为什么天空是蓝的** · *Why Is the Sky Blue?*<br><sub>Chalkboard · 黑板板书</sub> | **霓虹不夜城** · *Neon District*<br><sub>Cyberpunk · 赛博朋克</sub> |
+| <img src="examples/chalk_lesson.jpg" width="100%"> | <img src="examples/cyberpunk_neon_street.jpg" width="100%"> |
-Every mark above is computed: paper fibres, ink washes and mist, dry-brush strokes, pigment granulation and blooms, torn-paper edges, pencil wax on paper tooth, cel-shaded clouds, risograph grain and halftones, lit impasto relief, woodblock grain and bokashi, dithered pixels, plasticine lit like a film set, sunlight through leaves on Prussian blue, twisted thread on Aida cloth, machined knobs behind a backlit dial, die-cut vinyl with a laminate gloss, streaky thermal print, graphite catching the tooth of graph paper, highlighter pooling at the start of a swipe. No diffusion model, no API, no stock art. It is just Python with **numpy + Pillow** on a CPU: from 0.1 s (pixel art) to about 30 s per 1920×1080 image.
+Every mark above is computed: paper fibres, ink washes and mist, dry-brush strokes, pigment granulation and blooms, torn-paper edges, pencil wax on paper tooth, cel-shaded clouds, risograph grain and halftones, lit impasto relief, woodblock grain and bokashi, dithered pixels, plasticine lit like a film set, sunlight through leaves on Prussian blue, twisted thread on Aida cloth, machined knobs behind a backlit dial, die-cut vinyl with a laminate gloss, streaky thermal print, graphite catching the tooth of graph paper, highlighter pooling at the start of a swipe, chalk dust settling under half-erased lessons, rain-lit neon glass mirrored in a wet street. No diffusion model, no API, no stock art. It is just Python with **numpy + Pillow** on a CPU: from 0.1 s (pixel art) to about 30 s per 1920×1080 image.
---
@@ -48,7 +48,7 @@ Every mark above is computed: paper fibres, ink washes and mist, dry-brush strok
### What it is
-A [Claude Code](https://claude.com/claude-code) skill and a small painting library with fifteen styles:
+A [Claude Code](https://claude.com/claude-code) skill and a small painting library with seventeen styles:
| Style | Module | What makes it read as the real medium |
|---|---|---|
@@ -67,6 +67,8 @@ A [Claude Code](https://claude.com/claude-code) skill and a small painting libra
| **Vintage instrument panel** | `lib/panel.py` · `Panel` | teak veneer, brushed aluminium, moulded plastic, grille cloth with lurex floats, perforated metal; bevels, wells and drop shadows from one key light; machined knobs, piano keys, toggle switch, jewel lamp, magic-eye tube, meter; silkscreened scales and a backlit dial behind glass |
| **Sticker collage × receipt** | `lib/sticker.py` · `Sticker` | cream card board with grain, mottling and fibres; flat-vector art die-cut into *vinyl stickers* (rounded white border, cut-edge thickness, laminate gloss rim and sheen, contact + drop shadow, peeled corners showing the pale backing); a thermal receipt with serrated tear edges, grey streaky thermal print, dotted leaders, a printed strike-through, a fold crease and curl; translucent washi tape with torn ends; price tags with grommets on baker's twine; a round rubber stamp in translucent, unevenly pressed ink; red ballpoint ticks |
| **Lab notebook × stickers** | `lib/notebook.py` · `Notebook` | a wire-o graph-paper notebook on a graphite desk (hard back cover, stepped page stack, divider tabs, dog-ear, wire loops lit as metal tubes); graphite that only catches the paper tooth, with pressure, taper and hand wobble; ruled lines, hatching, pencil charts and check boxes; multiply highlighter swipes with pooled starts, felt streaks and dry tails; red felt-pen loops that overshoot instead of closing; curling sticky notes, die-cut vinyl stickers, embossed label-maker tape, a coffee ring; a hexagonal pencil with a scalloped sharpened edge |
+| **Chalkboard** | `lib/chalk.py` · `Chalkboard` | cloudy green slate paint; chalk that only catches the board's tooth, with pressure, grain and broken edges; side-of-the-stick shading; a felt eraser that really removes chalk, drags a smear along the wipe and leaves ghosts of the last lesson; dust settling thicker toward the tray; hand-set text where each character sits a little differently; hand-drawn ∝, waves, arrows and open loops; a mitred wooden frame with chalk sticks and an eraser on the ledge |
+| **Cyberpunk** | `lib/cyberpunk.py` · `Cyberpunk` | a pinhole camera down a rain-soaked street canyon, rendered in HDR with a z-buffer: glass-tube neon with over-exposed cores, dead and flickering tubes; backlit light boxes; a translucent hologram ad with scan lines, tear slices and colour fringing; each object mirrored from its own ground line into the wet asphalt and puddles; depth fog lit by the city; steam lit by the signs; three layers of rain lit only near the neon; flying-car light trails; bloom, halation, grain and one glitch line |
Ask Claude to *"draw it yourself"*, *"paint this with code"*, or *"claude绘图"*, and name a style if you like. Claude then:
@@ -135,6 +137,8 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages
- **Cyanotype**: think in UV transmission, not paint. Thin leaves ~0.85 opacity with fully blocking veins; lift fluff off the paper for a soft penumbra. A fern pinna is one lobed blade, not a row of separate leaflets. Dry-brush stroke ends are crisp broken streaks, not a blur.
- **Cross-stitch**: everything lives on the hole grid. Never lay half stitches over cross stitches (switch floss colour instead). A short diagonal back-stitch is one stitch from hole to hole, or it snaps into L-shaped steps.
- **Panel**: one key light for every part: lit upper-left edges, shadows to the lower right. Grille-cloth lurex needs long floats (short ones read as a perforated dot grid). Keep legends off busy textures and away from scale ends.
+- **Chalkboard**: even full-pressure chalk keeps ~15% pits and soft, broken edges, or it reads as vector lines. Draw ∝ by hand (a bold font's ∝ closes up into ∞). Shade large areas lightly with a pressure gradient. Ghosts of the last lesson stay faint and sit in empty space.
+- **Cyberpunk**: mirror each object from its own ground row, not one horizon line. Keep shop interiors dim (0.2–0.45) or the street turns into over-exposed walls. Light rain streaks only near the neon. Light trails cross the street instead of all flying into the vanishing point.
### Roadmap
@@ -146,7 +150,7 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages
### 这是什么
-一个 [Claude Code](https://claude.com/claude-code) skill,加上一个小巧的绘图库,内置十五种画风:
+一个 [Claude Code](https://claude.com/claude-code) skill,加上一个小巧的绘图库,内置十七种画风:
| 画风 | 模块 | 为什么看起来像真的 |
|---|---|---|
@@ -165,6 +169,8 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages
| **复古仪器面板** | `lib/panel.py` · `Panel` | 柚木贴皮、拉丝铝、注塑塑料、带金丝的喇叭布、冲孔网;同一盏主光照出倒角、凹槽和投影;车削旋钮、琴键、拨杆开关、宝石指示灯、绿色魔眼管、指针表;丝印刻度、玻璃后面的背光刻度窗 |
| **贴纸拼贴 · 小票** | `lib/sticker.py` · `Sticker` | 奶油卡纸底板,带纸纹、斑驳和纤维;平面矢量图模切成**乙烯贴纸**:圆角白边、切口厚度、覆膜光泽和斜向反光、贴地阴影加投影,翻起一角露出浅色背面;热敏小票:锯齿撕边、灰色断针热敏字、点线引导、删除线、折痕和卷翘;半透明和纸胶带;麻绳吊牌;油墨不匀的圆形橡皮章;红色圆珠笔勾选 |
| **实验笔记本 · 贴纸** | `lib/notebook.py` · `Notebook` | 石墨蓝灰桌面上的线圈方格本:硬封底、错开的页边、分隔标签、折角,线圈按金属管打光;石墨只挂在纸纹凸起上,有压力、收笔和手抖;靠尺直线、排线、铅笔折线图、勾选框;荧光笔正片叠底,起笔积墨、纤维条纹、尾部干涩;红笔圈故意不闭合;翘角便利贴、模切贴纸、标签机压印胶带、咖啡杯印;六棱铅笔 |
+| **黑板板书** | `lib/chalk.py` · `Chalkboard` | 云状不匀的墨绿石板漆;粉笔只挂在板面「齿」的凸起上,有压力、颗粒和断口;粉笔横躺的侧锋铺色;板擦真的能擦掉粉笔,顺着擦的方向拖出残迹,留下上节课的残影;越往下越厚的粉笔灰;每个字微转、错位、轻重不一;手写 ∝、波浪线、箭头和不闭合的圈;斜接木框,粉笔槽里放着粉笔和板擦 |
+| **赛博朋克** | `lib/cyberpunk.py` · `Cyberpunk` | 一台针孔相机看向雨夜街道深处,HDR 缓冲加深度遮挡:玻璃管霓虹中心过曝、边缘彩色光晕,还有坏管和闪烁管;背光灯箱;半透明全息广告,带扫描线、撕裂切片和色边;每样东西按自己的着地行翻出湿路面和水洼里的倒影;被城市灯光照亮的深度雾;被招牌照亮的井盖蒸汽;三层雨,只在霓虹附近看得见;飞车光轨;泛光、胶片红晕、颗粒和一道故障扫描线 |
对 Claude 说「claude绘图」「你自己画」「用代码画」,也可以指定画风。它会:
1. **先定构图**:层次、焦点、留白,而且画面要图解内容本身;
@@ -209,6 +215,8 @@ python3 examples/stitch_sampler.py out.png # 十字绣
python3 examples/panel_radio.py out.png # 复古仪器面板:Aurora 64 收音机
python3 examples/sticker_market.py out.png # 贴纸拼贴 · 小票:周末市集
python3 examples/notebook_brewing.py out.png # 实验笔记本 · 贴纸:咖啡萃取实验
+python3 examples/chalk_lesson.py out.png # 黑板板书:为什么天空是蓝的
+python3 examples/cyberpunk_neon_street.py out.png # 赛博朋克:霓虹不夜城
```
### 作画要点(Claude 交图前逐条自查)
@@ -226,6 +234,8 @@ python3 examples/notebook_brewing.py out.png # 实验笔
- **蓝晒**:想的是挡紫外线,不是上颜料:薄叶不透明度约 0.85、叶脉完全挡光;绒毛要离纸,边缘才柔;蕨类羽片是一整片带圆齿的叶子,不是一排分开的小叶;干刷的笔尾是利落的断续刷丝,不是一片模糊。
- **十字绣**:一切都在布孔的格子上;半针不要叠在十字绣上(亮部换浅色线);短的斜向回针一针从孔到孔,否则会被吸附成 L 形台阶。
- **复古面板**:所有部件同一盏主光:左上边亮、向右下投影;喇叭布的金丝要长浮,短了像冲孔板;丝印字别压在花纹上,也别挤到刻度末端。
+- **黑板**:满压的粉笔也要留约 15% 的坑点和毛边,否则像矢量线;∝ 要手写一笔(粗体字形会糊成 ∞);大面积用轻压力加渐变铺色;上节课的残影要淡,放在空白处。
+- **赛博朋克**:倒影按每样东西自己的着地行翻转,不能按一条地平线整体翻;店内亮度压在 0.2–0.45,否则街面成了过曝的墙;雨丝只在霓虹附近被照亮;飞车光轨横穿街道,不要全都飞向灭点。
### 计划
diff --git a/SKILL.md b/SKILL.md
index b304e64..a661115 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -1,6 +1,6 @@
---
name: claude绘图
-description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。内置十五种画风:中国水墨、水彩、剪纸拼贴、韩国彩铅、日本动漫、编辑风手绘(Riso)、油画厚涂(梵高式流向笔触+颜料浮雕打光)、浮世绘木版画(晕色、木纹、墨线主版、青海波)、像素风(低分辨率+Bayer 抖动+像素字体)、黏土定格(高度图捏出的彩泥+影棚打光)、蓝晒(普鲁士蓝日光晒图,植物剪影透光)、十字绣(Aida 布十字绣+回针绣+缎面绣+法式结)、复古仪器面板(60 年代收音机/仪器正面:柚木、拉丝铝、旋钮、刻度窗、指示灯)、贴纸拼贴·小票(模切乙烯贴纸、热敏小票、和纸胶带、吊牌、橡皮章)、实验笔记本·贴纸(线圈方格本、铅笔图表、荧光笔、红笔圈、便利贴)。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」,或点名以上任一画风(含黏土、彩泥、定格动画、蓝晒、晒图、十字绣、刺绣、复古面板、老式收音机、贴纸、小票、收据、手帐拼贴、实验笔记本、方格本、荧光笔、便利贴),或 "draw it yourself", "paint with code", "procedural painting", "watercolor / collage / colored pencil / anime / editorial / impasto oil / ukiyo-e / pixel art / clay / claymation / cyanotype / sun print / cross-stitch / embroidery / retro instrument panel / vintage radio / sticker collage / receipt / lab notebook / graph paper without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。
+description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。内置十七种画风:中国水墨、水彩、剪纸拼贴、韩国彩铅、日本动漫、编辑风手绘(Riso)、油画厚涂(梵高式流向笔触+颜料浮雕打光)、浮世绘木版画(晕色、木纹、墨线主版、青海波)、像素风(低分辨率+Bayer 抖动+像素字体)、黏土定格(高度图捏出的彩泥+影棚打光)、蓝晒(普鲁士蓝日光晒图,植物剪影透光)、十字绣(Aida 布十字绣+回针绣+缎面绣+法式结)、复古仪器面板(60 年代收音机/仪器正面:柚木、拉丝铝、旋钮、刻度窗、指示灯)、贴纸拼贴·小票(模切乙烯贴纸、热敏小票、和纸胶带、吊牌、橡皮章)、实验笔记本·贴纸(线圈方格本、铅笔图表、荧光笔、红笔圈、便利贴)、黑板板书(墨绿石板、粉笔颗粒、板擦残影、示意图与公式)、赛博朋克(雨夜霓虹街道、玻璃管霓虹招牌、全息广告、湿路面倒影)。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」,或点名以上任一画风(含黏土、彩泥、定格动画、蓝晒、晒图、十字绣、刺绣、复古面板、老式收音机、贴纸、小票、收据、手帐拼贴、实验笔记本、方格本、荧光笔、便利贴、黑板、板书、粉笔、赛博朋克、霓虹、雨夜街道),或 "draw it yourself", "paint with code", "procedural painting", "watercolor / collage / colored pencil / anime / editorial / impasto oil / ukiyo-e / pixel art / clay / claymation / cyanotype / sun print / cross-stitch / embroidery / retro instrument panel / vintage radio / sticker collage / receipt / lab notebook / graph paper / chalkboard / blackboard / cyberpunk / neon city without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。
---
# Claude 绘图
@@ -29,6 +29,8 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型
| 复古仪器面板 | `lib/panel.py` · `Panel` | `examples/panel_radio.py` Aurora 64 收音机(柚木机壳、喇叭布、背光刻度窗、琴键、魔眼管、拨杆、旋钮) | 约 7 秒 |
| 贴纸拼贴 · 小票 | `lib/sticker.py` · `Sticker` | `examples/sticker_market.py` 周末市集(热敏小票、模切贴纸:酸种面包/传家番茄/郁金香花束/咖啡豆、贴纸大字、波浪边促销贴、麻绳吊牌、和纸胶带、「已付」橡皮章) | 约 3 秒 |
| 实验笔记本 · 贴纸 | `lib/notebook.py` · `Notebook` | `examples/notebook_brewing.py` 咖啡萃取实验(线圈方格笔记本、铅笔表格与折线图、排线标出最佳区间、荧光笔、没闭合的红笔圈、便利贴结论、模切贴纸、标签机日期、桌上的六棱铅笔) | 约 3 秒 |
+| 黑板板书 | `lib/chalk.py` · `Chalkboard` | `examples/chalk_lesson.py` 为什么天空是蓝的(墨绿石板、半擦掉的上节课残影与板擦痕、越往下越厚的粉笔灰;白黄粉蓝粉笔写的标题、太阳→大气层→眼睛示意图、长短波浪线、手写 ∝ 与圈出的 1/λ⁴、光谱条与散射曲线、带缺口的「小结」框;木框和粉笔槽里的粉笔、板擦) | 约 5 秒 |
+| 赛博朋克 | `lib/cyberpunk.py` · `Cyberpunk` | `examples/cyberpunk_neon_street.py` 霓虹不夜城 · Neon District(雨夜街道峡谷、真玻璃管霓虹竖招牌(坏管与闪烁管)、背光灯箱、过街天桥「不夜城」、全息海月水母广告、电线、飞车光轨、井盖蒸汽、透明伞背影、湿路面与水洼倒影、胶片颗粒与一道撕裂扫描线) | 约 10 秒 |
各画风共用 `lib/core.py` 里的底层工具:噪声、模糊、样条曲线、多边形遮罩、有机轮廓 `blob_pts`、毛笔 `bristle_stroke`、中文字体查找;新四种还用到补零平移 `shift`、文字遮罩 `text_mask`、西文字体查找 `latin_font`/`load_font`,以及高度图打光 `height_normals`、`height_shadow`(沿光线步进的投影)、`ambient_occlusion`。
@@ -47,7 +49,9 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型
- 家、温馨、手作礼物、贺卡、名字和字母 → 十字绣;
- 设备、仪表、音响收音机、复古科技与产品感 → 复古仪器面板;
- 清单、账单、价格、购物、市集、活动海报、轻松但成熟的讲解片封面 → 贴纸拼贴 · 小票;
-- 实验记录、数据对比、复盘笔记、讲解片里的「算账 / 结论」页 → 实验笔记本 · 贴纸。
+- 实验记录、数据对比、复盘笔记、讲解片里的「算账 / 结论」页 → 实验笔记本 · 贴纸;
+- 讲课、知识点、公式推导、原理示意图、讲解片里的「板书 / 课堂」页 → 黑板板书;
+- 夜景、城市、雨、霓虹、电影感氛围、讲解片的「未来 / 科技 / 城市」封面 → 赛博朋克(要复古小尺寸或像素动画仍用像素风)。
每种画风一幅范例作为质量基准(范例都不用禅意主题);水墨另加一幅「月印万川」(留白托月、水面倒影)。
@@ -193,6 +197,29 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask
- 道具:`pencil_prop(x, y, angle, length, width, label, end='eraser'|'plain')` 六棱铅笔
- 角度:`rot` 逆时针为正(同 PIL);`angle`(铅笔、箭头方向)是屏幕角度,顺时针为正。常用色:`INK SOFT LEAD RED HI MINT MINTD`
+**黑板板书 `Chalkboard`**:
+- 分层:石板漆 → 粉笔层(预乘颜色 + 透明度,板擦能擦掉)→ 板前物件(木框、粉笔槽、粉笔、板擦及其投影)→ 室内光与暗角
+- 板面:`slate()` 云状不匀的墨绿石板漆;`dust(amount, specks, haze)` 沉降的粉笔灰,越往下越厚;`frame(rail, top, ledge)` 斜接木框加粉笔槽,会设置写字区 `area` 和槽面高度 `tray_y`。默认尺寸构造时就已知,dust 和擦痕可以先于画框画
+- 板擦:`swipe(pts, width, strength, haze, smear, keep)` 沿路径擦一遍:带走粉笔、顺擦向拖出残迹、毡面梳出细纹、毡面两端积灰;`smudge(cx, cy, w, h, rot)` 短擦一下;`with cb.erased(keep, angle, smear):` 块里画的一切都变成擦过没洗的旧课残影
+- 笔尖:`stroke(pts, colour, width, pressure, jitter)` / `strokes([...])`;`line()` 徒手直线、`rule()` 靠尺直线;`box(x0, y0, x1, y1, gap=(xa, xb))` 四边出头,上边可留缺口写标签;`loop(cx, cy, rx, ry, rot, turns)` 不闭合的圈、`circle()`;`arrow(pts, head)` 两笔箭头在尖端叠厚;`underline(x0, x1, y, double)`;`wave(p0, p1, wavelength, amplitude)` 光波曲线带箭头;`dashed()` 一段段画的虚线;`dot()`;`hatch(mask, angle, spacing)` 排线;`propto(x, y, size)` 手写 ∝,返回宽度
+- 侧锋:`side(p0, p1, stick, pressure)` 粉笔横躺拖一笔;`shade(mask, colour, angle, stick, pressure, overlap, weight)` 侧锋铺色,weight 是全画布 0–1 的压力图,可做渐变
+- 粉笔只挂在板面「齿」的凸起上:pressure 0.2–0.4 颗粒稀疏(铺色),0.8–0.95 写字画线
+- 文字 `text(s, x, y, size, colour, font, anchor, pressure, weight, rot, spacing, hand, grain)`:font 用 sans / sans_bold / cjk_sans,某套字体缺字自动换另一套;每个字各自微转、错位、轻重不一(hand=0 为排版体);`text_width()` 量宽度
+- 道具:`chalk_stick(x, cb.tray_y, length, colour, rot, worn='right'|'left'|None)` 粉笔,一端磨斜;`eraser(x, cb.tray_y + 2)` 板擦;`crumbs(x0, x1, n)` 碎粉笔
+- 颜色:`WHITE YELLOW PINK BLUE` 为主,`RED ORANGE GREEN VIOLET` 用于光谱和彩色粉笔,另有 `DUST`;所有 angle 和 rot 都是逆时针为正
+
+**赛博朋克 `Cyberpunk`**:
+- 思路:一台水平的针孔相机看向街道深处,世界坐标 X 右、Y 上、Z 向前,单位是米。所有东西写进 HDR 缓冲(反照率、自发光、z-buffer 深度、倒影镜像行),调用顺序不影响遮挡;`render` 时统一算光:环境光 + 光源外溢照明、深度雾(雾色是城市光的散射)、地面倒影、蒸汽、雨、胶片
+- 构造:`Cyberpunk(W, H, seed, focal=1150, vp=(x, y), eye=1.7, fog=125, wall=9.5, road=6, record=True)`;`record=False` 时 `stage()` 不出快照,渲染更快。相机工具:`project(X, Y, Z)`、`ground_row(Z)`、`near_z(side)`
+- 远景:`sky()` 被街灯从下面照亮的低云;`skyline(z, x_range, heights, widths)` 远处塔楼剪影、针点窗光、红色航空灯;`light(x, y, r, 颜色, z)` 小点光源
+- 楼:`building(side, z0, z1, height, wall, colour, lit, shops=(亮店, 卷帘门, 暗店, 自动售货机))` 透视楼块,正面加沿街立面贴图(窗格、空调外机、雨痕、底商、招牌字,右侧立面的字会自动镜像)
+- 霓虹:`blade_sign(side, z, Y0, Y1, '字', 颜色, reach, border=颜色, latin='BAR', dead=[序号], flicker=[序号], kind='neon'|'box', text_colour, level)` 伸向街心、面向镜头的竖招牌;`sign(z, X0, X1, Y0, Y1, ..., vertical=False)` 横招牌或立式灯箱;`neon_text(s, x, y, size, 颜色, z, vertical, dead, flicker)`、`neon_path(点列, 颜色, z)` 任意灯管
+- 全息:`hologram(z, X0, X1, Y0, Y1, '海月', 'SEA MOON', level, jelly=(x, y), sub_y)` 半透明投影广告(海月水母、竖排明朝标题、扫描线、撕裂切片、色边、投影边框),只加光,还会照亮雾和墙
+- 街道:`street(crossing=(z, 宽), puddles)` 湿沥青、路缘、铺砖、斑马线、积水;`puddle(X, Z, rx, rz)` 指定水洼(放在近处招牌的倒影位置上,能倒映出整块招牌);`grate(X, Z)` 井盖格栅
+- 空中:`walkway(z, Y, thick, deep, windows=None)` 过街天桥(正面可再挂 `neon_text`);`cables(n, z=(近, 远), Y=(低, 高))` 电线;`light_trail(三维控制点, 颜色, pair, strobe, fade)` 飞车光轨(左行交通:尾灯红、头灯暖白)
+- 氛围:`steam(X, Z, height, width, drift, density)` 井盖蒸汽;`mist()` 只躺在远处街面的薄雾;`figure(X, Z, umbrella='clear'|'dark'|None)` 打伞背影(两侧霓虹轮廓光,无脸);`rain(far, mid, near, slant, rings)` 三层雨和溅落圈;`glitch(y, h, shift, split)` 一道撕裂扫描线,只在成片里出现,用一次就够
+- 颜色常量 `MAGENTA CYAN AMBER RED WHITE`;`save('x.jpg')` 默认 quality 88、4:4:4 色度,霓虹边缘不糊
+
**顺序**:都是先远后近、先大后小,文字最后叠加。水墨的雾要画在它该吞没的东西之后;水彩的叶梗要先画,并且只画在叶子外面。
## 三、毛病清单(都真实出现过)
@@ -346,10 +373,33 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask
| 红笔箭头被后贴的便利贴盖住 | 箭头停在便利贴边缘外,或先贴便利贴再画箭头 |
| 标题上的荧光笔起笔压到了前一个字 | 起点按字宽算,落在目标字的左边缘 |
+**黑板板书**
+
+| 问题 | 改法 |
+|---|---|
+| 粉笔线像干净的矢量线:满压几乎实心、边缘光滑 | 满压也要留约 15% 的坑点(阈值 0.98 − 0.86 × 压力);笔尖接触面按线宽的 0.26 倍模糊,边缘才会毛、才会断 |
+| 中文(黑体)比 Helvetica Bold 细一截;加粗后 30 px 的复杂字糊成一团 | 中文按字号加粗,小字加粗减弱;40 px 以下自动加压、减轻颗粒和边缘扭曲(已处理) |
+| 字体的粗体 ∝ 被粉笔加粗后闭合,看着像 ∞ | 用 `propto()` 手写一笔:双纽线的左瓣加两条向右的尾巴 |
+| 大气层用侧锋铺色,成了一整块发闷的矩形,压住上面的波浪和标注 | 压力约 0.3、strength 约 0.6,用 `weight` 做渐变(近地面浓、往上淡),左右两端长距离渐隐 |
+| 上节课的残影被后来的大擦痕又擦没了,或者压在新板书下面影响阅读 | 残影 keep 取 0.26–0.34,大擦痕 strength 不超过 0.6;残影放在空白处(上沿、角落、标题和图之间) |
+| 动图调色板只取最后一帧,满屏绿色吃掉色位,粉彩粉笔、光谱条发灰 | 调色板用加权像素样本做中值切分(彩色像素 ×5、亮色 ×2),所有帧仍共用这一张 |
+
+**赛博朋克**
+
+| 问题 | 改法 |
+|---|---|
+| 倒影按一条地平线整体翻转,位置全错;被近处天桥挡住的远景在倒影里成了黑洞 | 每个物体按自己的着地行(mirror row)翻转,最近者优先;被挡住的空洞用对应行的雾色填 |
+| 一楼店面发光太亮太大,近处成了过曝的纯色墙,货物画成色块像霉斑或柱状图 | 店内亮度 0.2–0.45,从天花板往下衰减、两侧变暗,加货架侧影和人影;最近的街区多放卷帘门和自动售货机 |
+| 雨丝统一提亮成满屏灰帘,溅落圈太大像气泡 | 每根雨丝按周围光照上色,只在霓虹附近看得见;溅落圈半径 3–11 厘米,只在水洼里亮 |
+| 蒸汽用背后的暗画面照亮,完全看不见 | 蒸汽按光源外溢光照明(像一块浅色表面),再加前向散射 |
+| 光轨沿街飞,全都汇向灭点,像激光或钢丝 | 让飞车横穿街道:从一侧墙后出现,拱形掠过,消失在另一侧墙后;加频闪点 |
+| 全息水母的 1 像素线被雾和扫描线吃掉;C 形生殖腺像数字「93」,后排两个像一双眼睛(成了脸) | 线宽至少 2 像素;生殖腺放在伞内的水平面上,侧视压成一条柔和的粉带;副标用 Light 字重,撕裂切片别落在字上 |
+
## 四、做成动画
- 各画风都有 `stage(name)` 和 `save(path, stages_dir)`,按阶段依次淡入叠化,就是「一幅画被逐步画出来」。README 里的动图就是这样做的。
- 动图规格(多数现有动图和新增四幅一致):720×405;每个阶段停 900 毫秒,再用 5 帧(每帧 90 毫秒)叠化到下一阶段,最后一帧停 2600 毫秒,无限循环。新增四幅的所有帧共用一张 256 色调色板,文件小、不闪烁。
+- 调色板别只取最后一帧:满屏单色(黑板的墨绿、赛博朋克的夜色)会吃掉色位,彩色部分被量化成灰。黑板按加权像素样本做中值切分(彩色像素 ×5、亮色 ×2);赛博朋克从全部关键帧的拼图取 255 色,留 1 个透明色标记「和上一帧相同」的像素,并去掉 Pillow 每帧重复写入的局部调色板(3.8 MB → 1.8 MB)。
- 更细的逐笔动画:把一组笔画单独画到透明层上导出,再用 Motion Canvas 遮罩按顺序显现。这个还没做成现成接口。
## 五、文件
@@ -371,6 +421,8 @@ lib/stitch.py 十字绣
lib/panel.py 复古仪器面板
lib/sticker.py 贴纸拼贴 · 小票
lib/notebook.py 实验笔记本 · 贴纸
+lib/chalk.py 黑板板书
+lib/cyberpunk.py 赛博朋克
examples/*.py 范例脚本;*.jpg 成品;drawing_*.gif 逐步画出的动图
中文字体:自动找 Kaiti/Songti(macOS)、Noto CJK(Linux)、KaiTi/SimSun(Windows),或设 INKPAINT_FONT
西文字体(新四种用):core.latin_font(style) 按 sans / sans_bold / rounded / script / hand / typewriter 等找系统字体,可用 INKPAINT_FONT_<STYLE> 指定;字体文件不要放进仓库
diff --git a/examples/chalk_lesson.jpg b/examples/chalk_lesson.jpg
new file mode 100644
index 0000000..4af19f9
Binary files /dev/null and b/examples/chalk_lesson.jpg differ
diff --git a/examples/chalk_lesson.py b/examples/chalk_lesson.py
new file mode 100644
index 0000000..8cebbae
--- /dev/null
+++ b/examples/chalk_lesson.py
@@ -0,0 +1,184 @@
+"""Example (chalkboard): 为什么天空是蓝的 · Why is the sky blue? — a physics lesson on a classroom chalkboard: the
+title with 蓝 written in blue chalk, a diagram (the sun's white light entering the atmosphere, an air molecule
+sending short blue waves off in every direction while the long red wave carries straight on, an eye on the ground
+seeing blue), Rayleigh's law 散射 ∝ 1/λ⁴ with the key term looped, a worked comparison of blue and red, a small
+spectrum bar with the 1/λ⁴ curve drawn over it, a boxed 小结, and a question for next time. Behind it all, the
+half-erased ghosts of the previous lesson (a prism and Snell's law), eraser swipes and chalk dust; a wooden frame
+and a ledge with chalk and a felt eraser. No image model.
+python3 chalk_lesson.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 chalk import Chalkboard, WHITE, YELLOW, PINK, BLUE, RED, ORANGE, GREEN, VIOLET
+from core import polygon_mask
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'chalk_lesson.png'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+
+cb = Chalkboard(1920, 1080, seed=11)
+W, H = cb.W, cb.H
+
+# ---- the board as the class found it: last lesson's prism, wiped off but not washed; eraser swipes; dust
+cb.slate()
+with cb.erased(keep=0.34, angle=2):
+ cb.text('光的色散 Dispersion', 1296, 250, 46)
+ cb.stroke([(1000, 322), (1060, 212), (1120, 322), (1000, 322)], smooth=False, width=4)
+ cb.line(930, 300, 1036, 272)
+ for k, c in enumerate((RED, ORANGE, YELLOW, GREEN, BLUE, VIOLET)):
+ cb.line(1092, 272 + k * 3, 1236, 268 + k * 15, c, width=3.6)
+ cb.text('棱镜', 1138, 226, 36)
+with cb.erased(keep=0.3, angle=-3):
+ cb.text('n₁ sin θ₁ = n₂ sin θ₂', 44, 700, 36)
+ cb.text('作业 P.42 第 1–6 题', 1060, 64, 36)
+with cb.erased(keep=0.26, angle=4):
+ cb.text('v = λ f', 60, 782, 48)
+ cb.text('c = 3 × 10⁸ m/s', 936, 1002, 36)
+ cb.text('红 橙 黄 绿 蓝 靛 紫', 560, 300, 36)
+for pts, w, st in [([(40, 330), (700, 300), (1300, 322), (1880, 290)], 150, 0.5),
+ ([(40, 560), (800, 540), (1880, 590)], 140, 0.45),
+ ([(60, 790), (900, 810), (1880, 760)], 150, 0.5),
+ ([(1160, 140), (1500, 160), (1880, 130)], 110, 0.6)]:
+ cb.swipe(pts, w, st, haze=0.05)
+cb.smudge(1640, 860, 220, 90, rot=12, strength=0.5)
+cb.smudge(300, 640, 180, 80, rot=-8, strength=0.5)
+cb.dust()
+cb.stage('slate')
+
+# ---- frame, ledge, chalk and the eraser
+cb.frame()
+TY = cb.tray_y
+cb.crumbs(160, 1820, 16)
+cb.chalk_stick(262, TY, 94, WHITE, rot=-1.2)
+cb.chalk_stick(372, TY, 58, YELLOW, rot=1.6, worn='left')
+cb.chalk_stick(462, TY, 78, PINK, rot=-0.5)
+cb.chalk_stick(545, TY, 34, BLUE, rot=4, worn=None)
+cb.eraser(1670, TY + 2)
+cb.stage('frame')
+
+# ---- title
+x = 104
+for seg, col in [('为什么天空是', WHITE), ('蓝', BLUE), ('的?', WHITE)]:
+ cb.text(seg, x, 164, 90, col)
+ x += cb.text_width(seg, 90)
+cb.text('Why is the sky blue?', 938, 160, 42, BLUE)
+cb.underline(106, 858, 192, YELLOW, width=5.5, double=True)
+cb.text('9月30日 星期三', 1846, 94, 32, WHITE, anchor='rs', pressure=0.9)
+cb.text('物理 · 光学', 1770, 158, 28, PINK, anchor='ms')
+cb.box(1690, 124, 1850, 174, PINK, width=3.0, pressure=0.8)
+cb.stage('title')
+
+# ---- the sun and its white light
+SX, SY, SR = 196, 432, 58
+yy, xx = np.mgrid[0:H, 0:W]
+cb.shade(((xx - SX) ** 2 + (yy - SY) ** 2 < (SR - 4) ** 2).astype(np.float32), YELLOW, angle=12, stick=30, pressure=0.5)
+cb.circle(SX, SY, SR, YELLOW, width=4.4)
+rays = []
+for k in range(12):
+ a = np.deg2rad(k * 30 + 8)
+ r0, r1 = SR + 14, SR + (38 if k % 2 == 0 else 26)
+ rays.append([(SX + np.cos(a) * r0, SY + np.sin(a) * r0), (SX + np.cos(a) * r1, SY + np.sin(a) * r1)])
+cb.strokes(rays, YELLOW, 4.2, 0.85, 0.3, smooth=False)
+cb.text('太阳', SX, 562, 32, YELLOW, anchor='ms')
+cb.text('Sun', SX, 596, 24, WHITE, anchor='ms', pressure=0.8)
+cb.arrow([(300, 452), (470, 460), (628, 470)], WHITE, width=5.0, head=20)
+cb.text('白光(七色混合)', 318, 432, 26, WHITE, pressure=0.85)
+cb.stage('sun')
+
+# ---- the atmosphere over the curved ground; air molecules
+GX, RG = 820, 2600.0 # Earth: centre far below, radius RG
+ground = lambda x: 716 + RG - np.sqrt(RG ** 2 - (x - GX) ** 2)
+top = lambda x: 716 - 372 + (RG + 372) - np.sqrt((RG + 372) ** 2 - (x - GX) ** 2)
+xs = np.linspace(440, 1210, 40)
+air = polygon_mask(H, W, [(x, top(x) + 10) for x in xs] + [(x, ground(x) - 8) for x in xs[::-1]], 2)
+thick = (0.25 + 0.75 * np.clip((yy - 380) / 330.0, 0, 1) ** 1.4) * np.clip((xx - 436) / 190, 0, 1) ** 1.5 * np.clip((1214 - xx) / 120, 0, 1) ** 1.5
+cb.shade(air, BLUE, angle=3, stick=44, pressure=0.34, overlap=0.1, strength=0.62, weight=thick) # denser air near the ground
+cb.stroke([(x, ground(x)) for x in np.linspace(430, 1216, 9)], WHITE, 4.6, 0.9)
+cb.strokes([[(x, ground(x) + 4), (x - 13, ground(x) + 21)] for x in np.arange(452, 1212, 17)], WHITE, 2.6, 0.62, 0.2, smooth=False)
+cb.dashed([(x, top(x)) for x in np.linspace(436, 1214, 9)], WHITE, 20, 13, 3.4, 0.78)
+cb.text('大气层', 1070, top(1070) + 46, 28, WHITE, pressure=0.9)
+cb.text('atmosphere', 1070, top(1070) + 74, 22, BLUE, pressure=0.85)
+MOL = [(548, 392), (498, 548), (724, 636), (884, 436), (1016, 608), (1150, 630), (792, 688)]
+for mx, my in MOL:
+ cb.circle(mx, my, 7.5, WHITE, width=3.0, pressure=0.8)
+MX, MY = 646, 474
+cb.circle(MX, MY, 11, WHITE, width=3.6)
+cb.dot(MX, MY, 4.2)
+cb.circle(466, 694, 7.5, WHITE, width=3.0, pressure=0.8)
+cb.text('= 空气分子 N₂, O₂', 482, 703, 25, WHITE, pressure=0.9)
+cb.stage('atmosphere')
+
+# ---- the waves: long red carries straight on, short blue scatters every way; the eye on the ground
+cb.wave((666, 476), (1196, 500), 58, 12, RED, width=4.4, head=18)
+cb.text('红光 λ 长 → 几乎直穿', 944, 552, 26, RED)
+for p1 in [(604, 382), (770, 386), (530, 618), (846, 640)]:
+ cb.wave((MX + (p1[0] - MX) * 0.1, MY + (p1[1] - MY) * 0.1), p1, 17, 6.5, BLUE, width=3.8, head=14)
+cb.text('蓝光 λ 短 → 四处散射', 784, 394, 26, BLUE)
+EX, EY = 904, 668 # the eye, looking up to the left
+cb.stroke([(EX - 58, EY + 3), (EX - 22, EY - 26), (EX + 26, EY - 24), (EX + 58, EY + 1)], WHITE, 4.2, 0.92)
+cb.stroke([(EX - 58, EY + 3), (EX - 16, EY + 24), (EX + 28, EY + 20), (EX + 58, EY + 1)], WHITE, 3.8, 0.88)
+ring = (((xx - (EX - 8)) ** 2 + (yy - (EY - 3)) ** 2 < 17 ** 2) & ((xx - (EX - 10)) ** 2 + (yy - (EY - 5)) ** 2 > 7 ** 2)).astype(np.float32)
+cb.shade(ring, BLUE, angle=35, stick=20, pressure=0.8, overlap=0.2, ragged=0.4)
+cb.circle(EX - 8, EY - 3, 17, BLUE, width=3.2)
+cb.dot(EX - 14, EY - 10, 3.0, WHITE)
+lash = [[(EX + dx, EY + dy), (EX + dx * 1.18, EY + dy - 13)] for dx, dy in ((-40, -16), (-20, -24), (2, -26), (24, -23))]
+cb.strokes(lash, WHITE, 2.8, 0.8, 0.2, smooth=False)
+cb.text('眼睛:满天都是蓝光', 978, 700, 25, WHITE, pressure=0.92)
+cb.stage('waves')
+
+# ---- Rayleigh's law
+cb.line(1252, 262, 1256, 800, WHITE, width=2.6, pressure=0.45)
+cb.text('瑞利散射', 1296, 312, 44, YELLOW)
+cb.text('Rayleigh scattering', 1296 + cb.text_width('瑞利散射', 44) + 18, 310, 26, BLUE)
+cb.text('散射', 1300, 448, 76)
+pw = cb.propto(1300 + cb.text_width('散射', 76) + 22, 448, 76)
+FX = 1300 + cb.text_width('散射', 76) + 22 + pw + 72
+cb.text('1', FX, 410, 58, anchor='ms')
+cb.rule(FX - 50, 428, FX + 54, 430, WHITE, width=4.6, pressure=0.9)
+cb.text('λ', FX - 10, 500, 62, anchor='ms')
+cb.text('4', FX + 22, 472, 36, anchor='ms')
+cb.stage('formula')
+
+# ---- the key point, looped; a worked comparison
+cb.loop(FX + 2, 452, 84, 76, YELLOW, width=4.6, rot=-4)
+cb.arrow([(FX + 88, 488), (FX + 112, 506), (FX + 132, 510)], YELLOW, width=3.8, head=13)
+cb.text('波长越短', FX + 140, 500, 26, YELLOW)
+cb.text('散得越多', FX + 140, 532, 26, YELLOW)
+cb.text('蓝 450 nm vs 红 700 nm', 1300, 590, 28, WHITE, pressure=0.9)
+cb.text('(700 ÷ 450)⁴ ≈ 5.9', 1300, 646, 36, WHITE)
+cb.text('蓝光多散射约 6 倍', 1636, 644, 26, BLUE)
+cb.stage('key')
+
+# ---- spectrum bar with the 1/λ⁴ curve over it
+BX0, BX1, BY0, BY1 = 1322, 1800, 892, 930
+px_of = lambda l: BX0 + (l - 400) / 300 * (BX1 - BX0)
+cols = [(400, 435, VIOLET), (435, 485, BLUE), (485, 520, '#a6e3dc'), (520, 565, GREEN), (565, 590, YELLOW), (590, 625, ORANGE), (625, 700, RED)]
+for l0, l1, c in cols:
+ m = polygon_mask(H, W, [(px_of(l0) - 5, BY0), (px_of(l1) + 5, BY0), (px_of(l1) + 5, BY1), (px_of(l0) - 5, BY1)], 1)
+ cb.shade(m, c, angle=0, stick=42, pressure=0.95, overlap=0.0, overshoot=3, ragged=0.5, strength=1.0)
+cb.rule(BX0 - 16, 878, BX0 - 16, 700, WHITE, width=3.2, pressure=0.8)
+cb.arrow([(BX0 - 16, 706), (BX0 - 16, 682)], WHITE, width=3.2, head=12)
+cb.text('散射强度', BX0 + 2, 704, 22, WHITE, pressure=0.85)
+ls = np.linspace(400, 700, 30)
+cb.stroke([(px_of(l), 878 - 164 * (400 / l) ** 4) for l in ls], WHITE, 4.0, 0.9)
+for l, c, s in ((450, BLUE, '蓝'), (700, RED, '红')):
+ cb.dot(px_of(l), 878 - 164 * (400 / l) ** 4, 8.0, c)
+ cb.text(s, px_of(l) + (12 if l < 700 else -2), 878 - 164 * (400 / l) ** 4 - 16, 24, c, anchor='ls' if l < 700 else 'rs')
+cb.strokes([[(px_of(l), BY1 + 3), (px_of(l), BY1 + 17)] for l in (400, 500, 600, 700)], WHITE, 3.2, 0.95, 0.1, smooth=False)
+for l in (400, 500, 600, 700):
+ cb.text(str(l), px_of(l), BY1 + 40, 22, WHITE, anchor='ms', pressure=0.9)
+cb.text('λ / nm', BX1 + 16, BY1 - 10, 20, WHITE, pressure=0.9)
+cb.stage('spectrum')
+
+# ---- 小结 box and a question for next time
+cb.box(92, 806, 880, 994, WHITE, width=3.8, gap=(128, 232))
+cb.text('小结', 180, 818, 36, YELLOW, anchor='ms')
+for i, s in enumerate(['① 阳光是七色光的混合(白光)', '② 空气分子散射短波长光最强:散射 ∝ 1/λ⁴',
+ '③ 蓝光被散向四面八方 → 满天都是蓝色']):
+ cb.text(s, 124, 872 + i * 50, 29, WHITE)
+cb.text('想一想:', 930, 874, 30, PINK)
+cb.text('夕阳为什么是红的?', 930, 924, 30, PINK)
+cb.underline(930, 1196, 940, PINK, width=3.4, sag=1.5)
+
+cb.save(out, stages_dir=stages)
+print('saved', out)
diff --git a/examples/cyberpunk_neon_street.jpg b/examples/cyberpunk_neon_street.jpg
new file mode 100644
index 0000000..234414e
Binary files /dev/null and b/examples/cyberpunk_neon_street.jpg differ
diff --git a/examples/cyberpunk_neon_street.py b/examples/cyberpunk_neon_street.py
new file mode 100644
index 0000000..d9a27ee
--- /dev/null
+++ b/examples/cyberpunk_neon_street.py
@@ -0,0 +1,93 @@
+"""Example (cyberpunk): 霓虹不夜城 · Neon District — a rain-soaked street canyon at night seen from the kerb:
+perspective towers with window grids, blade signs of real neon tubes (a dead tube, a flickering one), backlit
+lightboxes, a footbridge gate over the street, a holographic jellyfish ad glowing through the haze, cables,
+flying-car light trails, steam from the grates, a lone figure under a clear umbrella, and the whole street
+mirrored in wet asphalt and puddles; finished with bloom, halation, grain and a single torn scanline.
+No image model.
+python3 cyberpunk_neon_street.py [out.jpg] [--stages DIR]
+"""
+import os, sys, time
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+from cyberpunk import Cyberpunk, MAGENTA, CYAN, AMBER, RED
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'cyberpunk_neon_street.jpg'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+t0 = time.time()
+
+c = Cyberpunk(1920, 1080, seed=2077, focal=1150, vp=(940, 560), eye=1.7, fog=125, wall=9.5, road=6.0,
+ record=stages is not None)
+
+# ---- sky and the far city beyond the end of the street
+c.sky()
+c.skyline(z=900, x_range=(-760, 760), heights=(140, 460), widths=(30, 90), colour='#1b1d36')
+c.skyline(z=460, x_range=(-320, 320), heights=(70, 250), widths=(18, 50), colour='#151830')
+c.stage('sky')
+
+# ---- the canyon: blocks on both sides, near to far (z0, z1, height, wall, colour, lit)
+left = [(6, 22, 42, 9.5, '#2b2f3c', 0.30), (22, 34, 30, 9.8, '#30303a', 0.35), (34, 52, 58, 9.3, '#272c38', 0.28),
+ (52, 70, 34, 9.6, '#2e2c36', 0.35), (70, 95, 64, 9.4, '#282d3a', 0.3), (95, 130, 46, 9.7, '#2c2e38', 0.35),
+ (130, 185, 82, 9.5, '#272b36', 0.3), (185, 270, 56, 9.5, '#2a2d38', 0.3)]
+right = [(6, 18, 36, 9.5, '#2e2f3a', 0.3), (18, 36, 72, 9.3, '#282c38', 0.3), (36, 50, 26, 9.6, '#302f38', 0.35),
+ (50, 72, 60, 9.4, '#2a2e3a', 0.3), (72, 100, 42, 9.8, '#2d2f39', 0.35), (100, 140, 74, 9.5, '#282c37', 0.3),
+ (140, 200, 58, 9.6, '#2b2e38', 0.3), (200, 290, 92, 9.5, '#272a35', 0.3)]
+for i, (z0, z1, h, w, col, lit) in enumerate(left): # the nearest block: shutters and vending machines
+ c.building(-1, z0, z1, h, wall=w, colour=col, lit=lit, shops=(0.2, 0.35, 0.15, 0.3) if i == 0 else (0.45, 0.35, 0.2, 0.0))
+for z0, z1, h, w, col, lit in right:
+ c.building(+1, z0, z1, h, wall=w, colour=col, lit=lit)
+c.stage('canyon')
+
+# ---- the wet street
+c.street(crossing=(12.5, 4.0), puddles=0.55)
+for X, Z in [(2.8, 11.5), (-3.6, 23.0), (4.4, 37.0)]:
+ c.grate(X, Z)
+c.puddle(-2.6, 4.6, 2.2, 1.6) # mirrors the near signs
+c.puddle(2.4, 5.2, 1.2, 1.1)
+c.puddle(-0.6, 19.5, 2.0, 2.5)
+c.stage('street')
+
+# ---- blade signs (neon tubes and lightboxes), near to far
+c.blade_sign(-1, 14, 2.9, 8.3, '夜市', MAGENTA, reach=2.6, border=CYAN, latin='NIGHT MARKET')
+c.blade_sign(-1, 23, 3.3, 10.4, '拉麺', '#fff1e2', reach=2.0, kind='box', latin='RAMEN', text_colour=RED, level=0.8)
+c.blade_sign(-1, 32, 4.2, 12.2, '旅館', CYAN, reach=2.3, latin='HOTEL', flicker=[1]) # caught mid-flicker
+c.blade_sign(-1, 45, 3.6, 8.6, '酒', MAGENTA, reach=1.8, border=AMBER)
+c.blade_sign(-1, 60, 4.5, 14.5, '質屋', AMBER, reach=2.2, dead=[0]) # a dead tube
+c.blade_sign(-1, 80, 4.0, 12.0, '時計', MAGENTA, reach=2.0, kind='box', text_colour='#1a0610', level=0.8)
+c.blade_sign(-1, 110, 5.0, 16.0, '薬', CYAN, reach=2.0)
+c.blade_sign(+1, 17, 3.0, 9.8, '雨宿', CYAN, reach=2.6, border=MAGENTA, latin='BAR', dead=[1])
+c.blade_sign(+1, 27, 3.5, 11.6, '喫茶', AMBER, reach=2.1, kind='box', latin='COFFEE', text_colour='#2a1406', level=0.75)
+c.blade_sign(+1, 39, 4.0, 13.0, '電器', CYAN, reach=2.2, border=AMBER)
+c.blade_sign(+1, 54, 3.8, 10.0, '麻雀', MAGENTA, reach=1.9, flicker=[0])
+c.blade_sign(+1, 72, 4.5, 15.0, '書店', '#eaf6ff', reach=2.0, kind='box', text_colour='#1478ff', level=0.8)
+c.blade_sign(+1, 100, 5.0, 17.0, '湯', MAGENTA, reach=2.0)
+c.sign(19.5, 4.2, 7.4, 3.0, 3.9, 'NOODLES', MAGENTA, vertical=False, box=0.2)
+c.sign(15.5, -8.9, -8.2, 0.25, 1.95, '営業中', '#fff4e6', kind='box', text_colour='#e0303a', level=0.7, box=0.25) # a standing sidewalk sign
+c.stage('neon')
+
+# ---- the gate over the street and the hologram glowing beyond it
+c.walkway(50, 8.2, thick=2.6, deep=4.0, windows=None)
+gx, gy = c.project(0, 9.5, 49.9)
+c.neon_text('不夜城', gx, gy - 4, 36, MAGENTA, 49.9, spacing=0.3)
+c.neon_text('NEON DISTRICT', gx, gy + 24, 12, CYAN, 49.9, spacing=0.35, flicker=[5])
+c.hologram(74, -8.3, 9.2, 9.0, 34.5, '海月', 'SEA MOON', level=2.2, jelly=(0.4, 0.3), sub_y=0.7)
+c.stage('hologram')
+
+# ---- cables and light trails
+c.cables(22, z=(12, 40), Y=(11, 22))
+c.light_trail([(-16, 20.5, 42), (-6, 22.8, 45.5), (4, 23.2, 49), (16, 21.0, 53)], '#ffe6c0', level=2.0, pair=1.2, strobe=7,
+ fade=(0.12, 0.25)) # a car crossing the street overhead
+c.light_trail([(16, 25.5, 66), (5, 27.2, 62), (-5, 26.8, 59.5), (-16, 25.0, 57)], RED, level=1.7, pair=1.4, fade=(0.12, 0.3))
+c.stage('wires')
+
+# ---- steam, mist and the lone figure
+c.steam(2.8, 11.5, height=6.5, width=0.55, drift=1.8, density=1.5)
+c.steam(-3.6, 23.0, height=7.0, width=0.8, drift=2.2, density=1.3)
+c.steam(4.4, 37.0, height=8.0, width=1.0, drift=2.5, density=1.1)
+c.mist()
+c.figure(-1.0, 19.5)
+c.stage('figure')
+
+# ---- rain, and one torn scanline in the finished frame
+c.rain()
+c.glitch(236, 7, 9, 2)
+c.save(out, stages_dir=stages)
+print('saved', out, f'{time.time() - t0:.1f}s')
diff --git a/examples/drawing_chalk_lesson.gif b/examples/drawing_chalk_lesson.gif
new file mode 100644
index 0000000..688a576
Binary files /dev/null and b/examples/drawing_chalk_lesson.gif differ
diff --git a/examples/drawing_cyberpunk_neon_street.gif b/examples/drawing_cyberpunk_neon_street.gif
new file mode 100644
index 0000000..68181c6
Binary files /dev/null and b/examples/drawing_cyberpunk_neon_street.gif differ
diff --git a/lib/chalk.py b/lib/chalk.py
new file mode 100644
index 0000000..b56166d
--- /dev/null
+++ b/lib/chalk.py
@@ -0,0 +1,911 @@
+"""chalk — a classroom chalkboard: green slate, chalk lettering and diagrams, eraser swipes and the ghosts of old
+lessons, a wooden frame and a chalk ledge with sticks of chalk and a felt eraser (numpy + Pillow only).
+
+Model: the board is seen straight on under the classroom lights (from above, a little to the left).
+ slate matt green board paint: an uneven, cloudy tone (years of washing and wiping), a darker fall-off toward
+ the frame, a very fine paint grain, and a per-pixel "tooth" field -- the microscopic peaks and pits of
+ the paint that chalk catches on. The same tooth is used by every mark, so crossing strokes share grain.
+ chalk a stick of soft calcium carbonate. A mark is a deposit, not a paint fill: where the stick touches, chalk
+ is scraped off onto the tooth peaks. Pressure decides how deep into the tooth it reaches, so a light
+ stroke skips the pits and comes out broken and grainy, a heavy one is nearly solid but still keeps a
+ few pits. The worn tip's contact patch is rounded, so a stroke is densest down its centre and ragged at
+ its edges. Along a stroke the hand's pressure drifts, the stick lands with a slightly heavier dab and
+ lifts off with a taper. Loose powder makes a faint halo round every mark, and some of it falls: a few
+ specks always drift below fresh writing.
+ side the stick laid on its side and dragged broadside (shading, fills): a wide band whose long edges are the
+ stick's two ends, very light pressure (only the highest tooth takes chalk) and long streaks in the
+ direction of motion, because the stick's surface touches unevenly along its length. Overlapping
+ passes build up, so a shaded area is streaky, never flat.
+ letters a font mask (CJK / Latin sans, never a handwriting font) written the way a teacher writes on a board:
+ each character a little rotated, lifted or dropped, a touch bigger or smaller, pressed harder or softer,
+ the line drifting slightly off level. The mask is then warped by a pixel or so (broken edges), given a
+ patchy pressure field and pushed through the same tooth deposit as the strokes.
+ drawing freehand lines with a slow bow, ruler lines (straight, pressure still uneven), boxes whose sides
+ overshoot the corners, loops that run past a full turn and drift so they never close, arrows whose two
+ head flicks meet (and pile up chalk) at the tip, underlines, hatching, pressed dots, dashed lines drawn
+ dash by dash, and wave squiggles for light.
+ eraser a felt block pushed along a path: it lifts most of the chalk in its footprint, drags the rest along the
+ motion (a smear), leaves a thin film of dust combed into streaks by the felt, and a slightly heavier line
+ of dust at the two ends of the felt. `erased()` turns anything drawn inside it into the ghost of an old
+ lesson: wiped, not washed.
+ dust specks of settled powder everywhere, thicker toward the bottom where it falls, and a haze just above
+ the ledge.
+ frame mitred wooden rails (grain along each rail, a rounded outer edge, a bevel down to the board) casting a
+ shadow onto the board, and a chalk ledge: a dusty tray floor and a rounded front lip, holding sticks of
+ chalk (matt cylinders, one end worn to a slant) and a felt eraser (wooden back, layered felt caked with
+ chalk), each with its own shadow.
+Layers: slate -> chalk (premultiplied colour + alpha, so the eraser can take chalk away again) -> things in front
+of the board (frame, ledge, props, the shadows they cast) -> room light and vignette.
+Lettering uses sans / sans_bold / cjk_sans (a glyph missing in one falls back to the other), never handwriting fonts.
+Angles and rotations are degrees counter-clockwise, like PIL.
+
+ from chalk import Chalkboard, WHITE, YELLOW, PINK, BLUE
+ cb = Chalkboard(1920, 1080, seed=1)
+ cb.slate()
+ with cb.erased(keep=0.15): # an old lesson, wiped off
+ cb.text('v = λ f', 1300, 300, 60)
+ cb.swipe([(80, 400), (900, 380), (1800, 420)], width=130)
+ cb.dust()
+ cb.frame()
+ cb.chalk_stick(300, cb.tray_y, 90, WHITE); cb.eraser(1650, cb.tray_y + 7)
+ cb.text('为什么天空是蓝的?', 110, 160, 88)
+ cb.underline(110, 900, 186, YELLOW)
+ cb.loop(600, 500, 160, 60, YELLOW) # a loop that doesn't quite close
+ cb.arrow([(300, 700), (500, 660), (700, 700)])
+ cb.save('out.png')
+"""
+import numpy as np
+from contextlib import contextmanager
+from PIL import Image, ImageDraw, ImageChops
+from core import blur, fbm1d, spline, noise2d, smoothstep, shift, load_font
+
+WHITE, YELLOW, PINK, BLUE = '#f4f2e9', '#f4e18c', '#f4b5c4', '#acd4ef'
+RED, ORANGE, GREEN, VIOLET = '#f4a19b', '#f6c58f', '#bfe2ab', '#cdb9ec'
+DUST = '#e1e8e1'
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+def _c(c):
+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)
+
+
+# ---------------------------------------------------------------- small helpers (kept inside this module)
+_FONTS, _HAS = {}, {}
+
+
+def _font(style, size):
+ k = (style, int(round(size)))
+ if k not in _FONTS:
+ _FONTS[k] = load_font(style, max(4, int(round(size))))
+ return _FONTS[k]
+
+
+def _is_cjk(ch):
+ o = ord(ch)
+ return 0x2E80 <= o <= 0x9FFF or 0xF900 <= o <= 0xFAFF or 0xFF00 <= o <= 0xFFEF or 0x3000 <= o <= 0x303F
+
+
+def _has(style, ch):
+ """does the font for `style` have a real glyph for ch (not the .notdef box)?"""
+ k = (style, ch)
+ if k not in _HAS:
+ f = _font(style, 48)
+ a, b = f.getmask(ch), f.getmask('\ue000')
+ _HAS[k] = ch.isspace() or not (a.size == b.size and bytes(a) == bytes(b))
+ return _HAS[k]
+
+
+def _pick(ch, style):
+ """font style for one character: CJK uses the CJK sans; a glyph missing in one font falls back to the other"""
+ first = 'cjk_sans' if (_is_cjk(ch) or style in ('cjk', 'cjk_sans')) else style
+ if _has(first, ch): return first
+ other = 'sans_bold' if first == 'cjk_sans' else 'cjk_sans'
+ return other if _has(other, ch) else first
+
+
+def _resample(P, step):
+ P = np.asarray(P, np.float32)
+ seg = np.hypot(*np.diff(P, axis=0).T)
+ s = np.concatenate([[0], np.cumsum(seg)])
+ if s[-1] < 1e-3: return P[:1]
+ n = max(2, int(s[-1] / step) + 1)
+ ss = np.linspace(0, s[-1], n)
+ return np.stack([np.interp(ss, s, P[:, 0]), np.interp(ss, s, P[:, 1])], 1).astype(np.float32)
+
+
+def _bilinear(a, x, y):
+ h, w = a.shape
+ x = np.clip(x, 0, w - 1.001); y = np.clip(y, 0, h - 1.001)
+ x0 = x.astype(np.int32); y0 = y.astype(np.int32)
+ fx, fy = x - x0, y - y0
+ return (a[y0, x0] * (1 - fx) * (1 - fy) + a[y0, x0 + 1] * fx * (1 - fy)
+ + a[y0 + 1, x0] * (1 - fx) * fy + a[y0 + 1, x0 + 1] * fx * fy)
+
+
+def _dirblur(a, angle, length, taps=11):
+ """average of shifted copies along a direction (degrees ccw): the smear of a wiped mark"""
+ if length < 1: return a.copy()
+ t = np.deg2rad(angle)
+ out = np.zeros_like(a)
+ for k in np.linspace(-length / 2, length / 2, taps):
+ out += shift(a, k * np.cos(t), -k * np.sin(t))
+ return out / taps
+
+
+def _sdf_rrect(u, v, hw, hh, r):
+ qx, qy = np.abs(u) - (hw - r), np.abs(v) - (hh - r)
+ return np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) + np.minimum(np.maximum(qx, qy), 0) - r
+
+
+class Chalkboard:
+ def __init__(self, W=1920, H=1080, seed=0, light=(-0.3, -0.8, 0.52)):
+ 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)
+ L = np.asarray(light, np.float32)
+ self.L = L / np.linalg.norm(L)
+ self.paint = np.zeros((H, W, 3), np.float32) + hexc('#2b4538')
+ self.ca = np.zeros((H, W), np.float32) # chalk: alpha
+ self.cc = np.zeros((H, W, 3), np.float32) # chalk: colour, premultiplied
+ self.ta = np.zeros((H, W), np.float32) # in front of the board: alpha
+ self.tc = np.zeros((H, W, 3), np.float32) # in front of the board: colour, premultiplied
+ self.dims = (22, 20, 58) # frame: side rails, top rail, ledge (px)
+ self.area = (22, 20, W - 22, H - 58) # the writing area inside the frame
+ self.tray_y = H - 58 + int(58 * 0.4) - 3
+ g = blur(self.rng.random((H, W)).astype(np.float32), 0.55) # paint tooth: ~1 px peaks and pits ...
+ m = noise2d(H, W, 3.2, 2, self._seed()) # ... a little clumpy
+ z = (0.85 * (g - g.mean()) / (g.std() + 1e-6) + 0.4 * (m - m.mean()) / (m.std() + 1e-6)) / np.hypot(0.85, 0.4)
+ self.tooth = (0.5 + 0.5 * np.tanh(0.95 * z)).astype(np.float32) # roughly uniform in 0..1
+ self.stages = []
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ # ------------------------------------------------------------ low-level compositing
+ def _box(self, x0, y0, x1, y1):
+ x0, y0 = max(0, int(np.floor(x0))), max(0, int(np.floor(y0)))
+ x1, y1 = min(self.W, int(np.ceil(x1))), min(self.H, int(np.ceil(y1)))
+ if x1 <= x0 or y1 <= y0: return None
+ return (slice(y0, y1), slice(x0, x1))
+
+ def _lay(self, sl, a, colour):
+ """chalk onto the board (premultiplied over): it covers the slate, and more chalk covers chalk"""
+ a = np.clip(a, 0, 1)
+ col = colour if (isinstance(colour, np.ndarray) and colour.ndim == 3) else _c(colour)
+ self.cc[sl] = self.cc[sl] * (1 - a[..., None]) + col * a[..., None]
+ self.ca[sl] = self.ca[sl] + a * (1 - self.ca[sl])
+
+ def _front(self, sl, a, colour):
+ """something in front of the board (frame, ledge, props, their shadows); colour may be (h, w, 3)"""
+ a = np.clip(a, 0, 1)
+ col = colour if (isinstance(colour, np.ndarray) and colour.ndim == 3) else _c(colour)
+ self.tc[sl] = self.tc[sl] * (1 - a[..., None]) + col * a[..., None]
+ self.ta[sl] = self.ta[sl] + a * (1 - self.ta[sl])
+
+ def _shadow(self, sl, mask, dx, dy, soft, strength, tint='#070a08'):
+ sh = shift(mask, dx, dy)
+ if soft > 0: sh = blur(sh, soft)
+ self._front(sl, sh * strength, tint)
+
+ def _specks(self, x, y, alpha, colour=DUST, size=0.55):
+ """scattered grains of chalk powder"""
+ x, y, alpha = np.asarray(x), np.asarray(y), np.asarray(alpha, np.float32)
+ ok = (x >= 1) & (y >= 1) & (x < self.W - 1) & (y < self.H - 1)
+ if not ok.any(): return
+ x, y, alpha = x[ok], y[ok], alpha[ok]
+ sl = self._box(x.min() - 6, y.min() - 6, x.max() + 7, y.max() + 7)
+ m = np.zeros((sl[0].stop - sl[0].start, sl[1].stop - sl[1].start), np.float32)
+ np.add.at(m, (np.round(y).astype(int) - sl[0].start, np.round(x).astype(int) - sl[1].start), alpha)
+ m = blur(m, size) * (1.0 / (2 * np.pi * size * size)) * 0.9
+ self._lay(sl, np.clip(m, 0, 0.9), colour)
+
+ # ------------------------------------------------------------ the chalk deposit
+ def _deposit(self, v, sl, grain=1.0, halo=0.15, powder=0.0):
+ """contact map v (coverage x pressure, 0..1) -> chalk alpha. The tooth decides where chalk sticks:
+ low contact only reaches the highest peaks (broken, grainy), high contact fills all but the deepest pits."""
+ t = 0.5 + (self.tooth[sl] - 0.5) * grain
+ v = np.clip(v, 0, 1)
+ thr = 0.98 - 0.86 * v # full pressure still leaves ~15 % pits
+ a = smoothstep(thr - 0.12, thr + 0.12, t) * (0.5 + 0.5 * v) * smoothstep(0.03, 0.18, v)
+ if powder:
+ a = a + powder * v * (1 - a)
+ if halo: # loose powder round the mark, some falling
+ h = blur(a, 1.8) * halo + blur(shift(a, 0, 3), 4.5) * halo * 0.45
+ a = 1 - (1 - a) * (1 - np.clip(h, 0, 1))
+ return a
+
+ def _fall(self, a, sl, colour, amount):
+ """a few grains drop off fresh chalk and stick to the board below it"""
+ if amount <= 0: return
+ ys, xs = np.nonzero(a > 0.45)
+ n = int(len(xs) * 0.0035 * amount)
+ if n == 0: return
+ r = self.rng
+ i = r.integers(0, len(xs), n)
+ self._specks(xs[i] + sl[1].start + r.normal(0, 1.3, n), ys[i] + sl[0].start + 1 + r.exponential(10, n),
+ r.uniform(0.1, 0.42, n), colour)
+
+ # ------------------------------------------------------------ stroke rasteriser
+ def _raster(self, strokes, pad=16, ss=3):
+ """strokes: [(P (n,2), width (n,), value (n,) 0..1)] -> (mask, slices), drawn at ss x then box-filtered"""
+ allp = np.concatenate([s[0] for s in strokes])
+ p = max(float(s[1].max()) for s in strokes) / 2 + pad
+ sl = self._box(allp[:, 0].min() - p, allp[:, 1].min() - p, allp[:, 0].max() + p, allp[:, 1].max() + p)
+ if sl is None: return None, None
+ x0, y0 = sl[1].start, sl[0].start
+ bw, bh = sl[1].stop - x0, sl[0].stop - y0
+ im = Image.new('L', (bw * ss, bh * ss), 0)
+ d = ImageDraw.Draw(im)
+ for P, w, v in strokes:
+ Q = (P - np.array([x0, y0], np.float32)) * ss
+ n = len(Q)
+ if n == 1:
+ r = w[0] * ss / 2
+ d.ellipse([Q[0, 0] - r, Q[0, 1] - r, Q[0, 0] + r, Q[0, 1] + r], fill=int(255 * np.clip(v[0], 0, 1)))
+ continue
+ for i in range(0, n - 1, 2):
+ j = min(n - 1, i + 2)
+ ww = float(w[i:j + 1].mean()) * ss
+ vv = int(round(255 * float(np.clip(v[i:j + 1].mean(), 0, 1))))
+ r = ww / 2
+ d.ellipse([Q[i, 0] - r, Q[i, 1] - r, Q[i, 0] + r, Q[i, 1] + r], fill=vv)
+ d.line([(float(q[0]), float(q[1])) for q in Q[i:j + 1]], fill=vv, width=max(1, int(round(ww))))
+ r = w[-1] * ss / 2
+ d.ellipse([Q[-1, 0] - r, Q[-1, 1] - r, Q[-1, 0] + r, Q[-1, 1] + r], fill=int(255 * np.clip(v[-1], 0, 1)))
+ return np.asarray(im.resize((bw, bh), Image.BOX), np.float32) / 255, sl
+
+ def _prep(self, pts, width, pressure, jitter, smooth=True, step=1.2):
+ """resample a hand stroke, add the hand's slow wobble and a pressure profile -> (P, widths, pressures)"""
+ P = np.asarray(pts, np.float32)
+ if smooth and len(P) > 2: P = spline(P, 10)
+ P = _resample(P, step)
+ n = len(P)
+ if n < 2: return P, np.array([width], np.float32), np.array([pressure], np.float32)
+ tg = np.gradient(P, axis=0)
+ tg /= np.linalg.norm(tg, axis=1, keepdims=True) + 1e-6
+ nrm = np.stack([-tg[:, 1], tg[:, 0]], 1)
+ s = self._seed()
+ P = P + nrm * (fbm1d(n, max(4, 150 / step), 3, s) * jitter + fbm1d(n, max(2, 10 / step), 2, s + 1) * jitter * 0.15)[:, None]
+ L = n * step
+ d = np.linspace(0, L, n)
+ land = 1 + 0.16 * np.exp(-(d / 4.0) ** 2) # the stick lands with a heavier dab
+ lift = 0.35 + 0.65 * smoothstep(0, min(18.0, L * 0.35), L - d) # ... and lifts off with a taper
+ flow = 1 + 0.2 * fbm1d(n, max(4, 110 / step), 2, s + 2) + 0.07 * fbm1d(n, max(2, 7 / step), 1, s + 3)
+ press = np.clip(pressure * land * lift * flow, 0.02, 1).astype(np.float32)
+ w = (width * (0.78 + 0.22 * press / max(pressure, 1e-3))).astype(np.float32)
+ return P, w, press
+
+ # ------------------------------------------------------------ tip strokes
+ def strokes(self, paths, colour=WHITE, width=4.0, pressure=0.85, jitter=0.7, smooth=True, grain=1.0, halo=0.15,
+ fall=1.0, strength=0.96):
+ """many chalk strokes in one pass (a list of point lists); where they cross they don't pile up"""
+ prepared = [self._prep(p, width, pressure, jitter, smooth) for p in paths if len(p) >= 1]
+ prepared = [p for p in prepared if len(p[0])]
+ if not prepared: return
+ m, sl = self._raster(prepared)
+ if sl is None: return
+ v = np.clip(blur(m, max(0.6, 0.26 * width)) * 1.22, 0, 1) # the worn tip's rounded contact patch
+ a = self._deposit(v, sl, grain, halo) * strength
+ self._lay(sl, a, colour)
+ self._fall(a, sl, colour, fall)
+
+ def stroke(self, pts, colour=WHITE, width=4.0, pressure=0.85, jitter=0.7, smooth=True, **kw):
+ """one freehand chalk stroke through pts (Catmull-Rom smoothed unless smooth=False)"""
+ self.strokes([pts], colour, width, pressure, jitter, smooth, **kw)
+
+ def line(self, x0, y0, x1, y1, colour=WHITE, width=4.0, pressure=0.85, bow=None, jitter=0.6, overshoot=3.0,
+ ruler=False, **kw):
+ """a freehand straight line (a slow bow, ends over/under-shooting) or, ruler=True, one drawn along a ruler"""
+ r = self.rng
+ p0, p1 = np.array([x0, y0], np.float32), np.array([x1, y1], np.float32)
+ d = p1 - p0; L = float(np.linalg.norm(d)) + 1e-6; u = d / L
+ a = p0 - u * r.uniform(-overshoot * 0.4, overshoot)
+ b = p1 + u * r.uniform(-overshoot * 0.4, overshoot)
+ if ruler:
+ self.stroke([a, b], colour, width, pressure, 0.15, smooth=False, **kw)
+ else:
+ bow = r.uniform(-1, 1) * L * 0.006 if bow is None else bow
+ mid = (a + b) / 2 + np.array([-u[1], u[0]]) * bow
+ self.stroke([a, mid, b], colour, width, pressure, jitter, smooth=True, **kw)
+
+ def rule(self, x0, y0, x1, y1, colour=WHITE, width=4.0, pressure=0.85, **kw):
+ """a line drawn against the board ruler: dead straight, pressure still uneven"""
+ self.line(x0, y0, x1, y1, colour, width, pressure, ruler=True, **kw)
+
+ def box(self, x0, y0, x1, y1, colour=WHITE, width=3.6, pressure=0.85, overshoot=8.0, gap=None, jitter=0.5, **kw):
+ """four separate strokes whose ends run past the corners; gap=(xa, xb) leaves the top side open for a label"""
+ r = self.rng
+ j = lambda: r.uniform(-1.4, 1.4)
+ ov = lambda: r.uniform(1.5, overshoot)
+ ya, yb = y0 + j(), y0 + j()
+ top = [(x0 - ov(), ya, x1 + ov(), yb)]
+ if gap:
+ top = [(x0 - ov(), ya, gap[0], ya + (yb - ya) * 0.3), (gap[1], ya + (yb - ya) * 0.7, x1 + ov(), yb)]
+ sides = top + [(x1 + j(), y0 - ov(), x1 + j(), y1 + ov()), (x1 + ov(), y1 + j(), x0 - ov(), y1 + j()),
+ (x0 + j(), y1 + ov(), x0 + j(), y0 - ov())]
+ for (a, b, c, d) in sides:
+ self.line(a, b, c, d, colour, width * r.uniform(0.9, 1.08), pressure * r.uniform(0.9, 1.05), jitter=jitter,
+ overshoot=0.5, **kw)
+
+ def underline(self, x0, x1, y, colour=YELLOW, width=5.0, pressure=0.9, double=False, sag=2.5, **kw):
+ r = self.rng
+ self.stroke([(x0, y + r.uniform(-1, 1)), ((x0 + x1) / 2, y + sag), (x1, y - r.uniform(0.5, 3))], colour, width,
+ pressure, 0.6, **kw)
+ if double:
+ self.stroke([(x0 + 26, y + 15), ((x0 + x1) / 2, y + 15 + sag), (x1 - 70, y + 13)], colour, width * 0.62,
+ pressure * 0.9, 0.6, **kw)
+
+ def loop(self, cx, cy, rx, ry, colour=YELLOW, width=4.4, pressure=0.88, rot=0.0, turns=1.13, a0=None, drift=0.08, **kw):
+ """a hand-drawn loop around something: a bit more than one turn, drifting outward so it never closes"""
+ r = self.rng
+ N = int(max(90, 2 * np.pi * max(rx, ry) * turns / 3))
+ t = np.linspace(0, 1, N)
+ a0 = r.uniform(150, 215) if a0 is None else a0
+ ang = np.deg2rad(a0) + t * 2 * np.pi * turns
+ k = 1 + fbm1d(N, 30, 2, self._seed()) * 0.018 + (t - 0.5) * drift
+ x, y = rx * k * np.cos(ang), ry * (k + (t - 0.5) * drift * 0.5) * np.sin(ang)
+ q = np.deg2rad(-rot)
+ P = np.stack([cx + x * np.cos(q) - y * np.sin(q), cy + x * np.sin(q) + y * np.cos(q)], 1)
+ self.stroke(P, colour, width, pressure, 0.5, smooth=False, **kw)
+
+ def circle(self, cx, cy, r, colour=WHITE, width=4.0, pressure=0.85, **kw):
+ """a freehand circle: the ends just meet and overlap a little"""
+ self.loop(cx, cy, r, r * self.rng.uniform(0.97, 1.02), colour, width, pressure, rot=0, turns=1.04, drift=0.025, **kw)
+
+ def dot(self, x, y, r=3.5, colour=WHITE, pressure=1.0):
+ """a dot pressed in with a little twist of the stick"""
+ n = 14
+ a = np.linspace(0, 3 * np.pi, n); rr = np.linspace(r * 0.45, 0.2, n)
+ self.stroke(np.stack([x + rr * np.cos(a), y + rr * np.sin(a)], 1), colour, r * 1.5, pressure, 0.1, smooth=False, fall=0.3)
+
+ def arrow(self, pts, colour=WHITE, width=4.0, pressure=0.85, head=18, spread=27, smooth=True, **kw):
+ """a stroke through pts ending in two head flicks that meet (and pile up chalk) at the tip"""
+ P = np.asarray(pts, np.float32)
+ P = spline(P, 12) if (smooth and len(P) > 2) else _resample(P, 2.0)
+ self.stroke(P, colour, width, pressure, 0.45, smooth=False, **kw)
+ self._head(P, colour, width, pressure, head, spread, **kw)
+
+ def _head(self, P, colour, width, pressure, head, spread, **kw):
+ tip = P[-1]
+ d = np.hypot(*(P - tip).T)
+ k = int(np.argmax(d > head * 0.8)) if (d > head * 0.8).any() else 0
+ a = np.arctan2(tip[1] - P[k][1], tip[0] - P[k][0])
+ r = self.rng
+ wings = []
+ for side in (1, -1):
+ b = a + np.pi + side * np.deg2rad(spread * r.uniform(0.9, 1.1))
+ wings.append([tip + np.array([np.cos(b), np.sin(b)]) * head * r.uniform(0.9, 1.08), tip + (tip - P[k]) / (d[k] + 1e-6) * 1.5])
+ self.strokes(wings, colour, width * 0.95, pressure, 0.2, smooth=False, **kw)
+
+ def wave(self, p0, p1, wavelength=40, amplitude=10, colour=BLUE, width=3.6, pressure=0.85, head=15, **kw):
+ """light as a squiggle from p0 to p1: a sine along the line, easing in, settling onto the axis at the arrow tip"""
+ p0, p1 = np.array(p0, np.float32), np.array(p1, np.float32)
+ d = p1 - p0; L = float(np.linalg.norm(d)); u = d / L; nrm = np.array([-u[1], u[0]], np.float32)
+ s = np.arange(0, L, 1.0)
+ env = smoothstep(0, wavelength * 0.5, s) * smoothstep(head * 0.6, head * 0.6 + wavelength * 0.6, L - s)
+ ph = self.rng.uniform(0, 0.2)
+ P = p0 + u * s[:, None] + nrm * (amplitude * env * np.sin(2 * np.pi * (s / wavelength + ph)))[:, None]
+ P = np.vstack([P, p1])
+ self.stroke(P, colour, width, pressure, 0.3, smooth=False, **kw)
+ if head: self._head(P, colour, width, pressure, head, 28, **kw)
+
+ def propto(self, x, y, size, colour=WHITE, width=None, pressure=0.9):
+ """the proportional sign written by hand (a font's bold ∝ thickens into ∞): one stroke, the left loop of a
+ lemniscate with both tails running on to the right. (x, y) = left end on the baseline, size = letter size"""
+ a = size * 0.46
+ t = np.linspace(np.pi / 2 - 0.55, 3 * np.pi / 2 + 0.55, 90)
+ den = 1 + np.sin(t) ** 2
+ px, py = np.cos(t) / den, np.sin(t) * np.cos(t) / den # the left lobe, crossing at the origin
+ P = np.stack([x + a * 1.05 + px * a * 1.05, y - size * 0.32 + py * a * 1.3], 1)
+ self.stroke(P[::-1], colour, width or max(3.0, size * 0.075), pressure, 0.3, smooth=False)
+ return a * 2.1
+
+ def dashed(self, pts, colour=WHITE, dash=18, gap=13, width=3.4, pressure=0.8, smooth=True, **kw):
+ """a dashed line drawn dash by dash (every dash lands and lifts on its own)"""
+ P = np.asarray(pts, np.float32)
+ P = spline(P, 12) if (smooth and len(P) > 2) else P
+ P = _resample(P, 1.0)
+ r = self.rng
+ out, i = [], int(r.uniform(0, gap))
+ while i < len(P) - 3:
+ ln = int(dash * r.uniform(0.8, 1.2))
+ out.append(P[i:min(len(P), i + ln)])
+ i += ln + int(gap * r.uniform(0.8, 1.25))
+ self.strokes([o for o in out if len(o) > 2], colour, width, pressure, 0.2, smooth=False, **kw)
+
+ def hatch(self, mask, colour=WHITE, angle=45, spacing=9, width=2.6, pressure=0.7, jitter=0.4, overshoot=3, **kw):
+ """tip hatching inside a mask: parallel strokes, each slightly bowed, ends over/under-shooting"""
+ ys, xs = np.nonzero(mask > 0.5)
+ if len(xs) == 0: return
+ a = np.deg2rad(angle)
+ d = np.array([np.cos(a), -np.sin(a)], np.float32)
+ nv = np.array([np.sin(a), np.cos(a)], np.float32)
+ cx, cy = xs.mean(), ys.mean()
+ corners = np.array([[xs.min(), ys.min()], [xs.max(), ys.min()], [xs.min(), ys.max()], [xs.max(), ys.max()]], np.float32) - [cx, cy]
+ on, od = corners @ nv, corners @ d
+ r = self.rng
+ paths = []
+ o = on.min()
+ while o < on.max():
+ ts = np.arange(od.min() - 2, od.max() + 2, 1.0)
+ px = cx + nv[0] * o + d[0] * ts; py = cy + nv[1] * o + d[1] * ts
+ ix, iy = np.round(px).astype(int), np.round(py).astype(int)
+ ok = (ix >= 0) & (iy >= 0) & (ix < self.W) & (iy < self.H)
+ inside = np.zeros(len(ts), bool)
+ inside[ok] = mask[iy[ok], ix[ok]] > 0.5
+ edges = np.diff(np.concatenate([[0], inside.astype(int), [0]]))
+ for s0, s1 in zip(np.nonzero(edges == 1)[0], np.nonzero(edges == -1)[0]):
+ if s1 - s0 < 4: continue
+ t0 = ts[s0] - r.uniform(-overshoot * 0.6, overshoot)
+ t1 = ts[s1 - 1] + r.uniform(-overshoot * 0.8, overshoot * 1.2)
+ p0 = np.array([cx, cy]) + nv * o + d * t0
+ p1 = np.array([cx, cy]) + nv * o + d * t1
+ mid = (p0 + p1) / 2 + nv * r.uniform(-1, 1) * (t1 - t0) * 0.015
+ paths.append([p0, mid, p1])
+ o += spacing * r.uniform(0.85, 1.15)
+ self.strokes(paths, colour, width, pressure, jitter, smooth=True, **kw)
+
+ # ------------------------------------------------------------ side of the stick
+ def side(self, p0, p1, colour=WHITE, stick=36, pressure=0.45, clip=None, grain=1.0, strength=0.92, halo=0.06):
+ """the stick laid on its side and dragged broadside from p0 to p1: a band `stick` px wide with streaks along
+ the motion (the stick touches unevenly along its length); `clip` is a full-canvas mask it is confined to"""
+ p0, p1 = np.array(p0, np.float32), np.array(p1, np.float32)
+ d = p1 - p0; L = float(np.linalg.norm(d)) + 1e-6; tx, ty = d / L
+ pad = stick / 2 + 10
+ sl = self._box(min(p0[0], p1[0]) - pad, min(p0[1], p1[1]) - pad, max(p0[0], p1[0]) + pad, max(p0[1], p1[1]) + pad)
+ if sl is None: return
+ X, Y = self.XX[sl] - p0[0], self.YY[sl] - p0[1]
+ u = X * tx + Y * ty
+ v = -X * ty + Y * tx
+ s = self._seed()
+ nv = int(stick + 24); vi = np.clip(v + stick / 2 + 12, 0, nv - 1)
+ nu = int(L + 48); ui = np.clip(u + 24, 0, nu - 1)
+ prof = np.interp(vi, np.arange(nv), 0.66 + 0.22 * fbm1d(nv, 2.5, 2, s) + 0.2 * fbm1d(nv, 11, 2, s + 1))
+ e0 = np.interp(ui, np.arange(nu), fbm1d(nu, 40, 2, s + 2) * 2.2)
+ e1 = np.interp(ui, np.arange(nu), fbm1d(nu, 40, 2, s + 3) * 2.2)
+ band = smoothstep(-stick / 2 - 1.5, -stick / 2 + 2.0, v + e0) * smoothstep(-stick / 2 - 1.5, -stick / 2 + 2.0, -v + e1)
+ rag = np.interp(vi, np.arange(nv), fbm1d(nv, 4, 2, s + 4) * 5)
+ ends = smoothstep(-2, 5, u - rag) * smoothstep(-2, 6, L - u + rag)
+ press = pressure * (1 + 0.28 * np.interp(ui, np.arange(nu), fbm1d(nu, 90, 2, s + 5)))
+ vc = band * ends * prof * press
+ if clip is not None: vc = vc * clip[sl]
+ a = self._deposit(vc, sl, grain, halo, powder=0.22) * strength
+ self._lay(sl, a, colour)
+
+ def shade(self, mask, colour=WHITE, angle=0.0, stick=36, pressure=0.42, overlap=0.3, overshoot=6, ragged=1.0,
+ strength=0.92, weight=None):
+ """fill a mask with the side of the stick: parallel broadside passes (angle = direction of motion, degrees
+ ccw) that overlap and build up; the fill stops a little short of / runs a little past the outline.
+ weight: optional full-canvas 0..1 map of how hard the hand presses (e.g. a gradient)"""
+ ys, xs = np.nonzero(mask > 0.5)
+ if len(xs) == 0: return
+ s = self._seed()
+ bm = blur(mask.astype(np.float32), 2.0)
+ clip = smoothstep(0.3, 0.7, bm + ragged * 0.35 * (noise2d(self.H, self.W, 9, 2, s) - 0.5)) if ragged else mask
+ if weight is not None: clip = clip * weight
+ a = np.deg2rad(angle)
+ d = np.array([np.cos(a), -np.sin(a)], np.float32)
+ nv = np.array([np.sin(a), np.cos(a)], np.float32)
+ cx, cy = xs.mean(), ys.mean()
+ on = (xs - cx) * nv[0] + (ys - cy) * nv[1]
+ od = (xs - cx) * d[0] + (ys - cy) * d[1]
+ r = self.rng
+ o = on.min() + stick * 0.3
+ while o < on.max() + stick * 0.2:
+ sel = np.abs(on - o) < stick / 2
+ if sel.any():
+ t0, t1 = od[sel].min() - overshoot, od[sel].max() + overshoot
+ c = np.array([cx, cy]) + nv * o
+ self.side(c + d * t0, c + d * t1, colour, stick * r.uniform(0.9, 1.1), pressure * r.uniform(0.85, 1.15),
+ clip, strength=strength)
+ o += stick * (1 - overlap) * r.uniform(0.85, 1.1)
+
+ # ------------------------------------------------------------ lettering
+ def _tmask(self, s, x, y, size, style='sans_bold', anchor='ls', spacing=0.0, rot=0.0, weight=0.0, hand=1.0, ss=2):
+ """lettering -> (mask, slices). Characters are placed one by one like handwriting: each gets its own small
+ rotation, baseline shift, scale and pressure (the mask value); the line drifts slightly off level."""
+ r = self.rng
+ chars = [(ch, _pick(ch, style)) for ch in s]
+ advs = [_font(st, size).getlength(ch) + spacing for ch, st in chars]
+ total = sum(advs) - (spacing if chars else 0)
+ if any(_is_cjk(ch) for ch, _ in chars):
+ capH = -_font('cjk_sans', size).getbbox('中', anchor='ls')[1]
+ else:
+ capH = -_font(_pick('H', style), size).getbbox('H', anchor='ls')[1]
+ desc = size * 0.22
+ dyb = {'s': 0, 'm': capH / 2, 'a': capH, 't': capH, 'd': -desc, 'b': -desc}.get(anchor[1], 0)
+ xs0 = x - total * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor[0]]
+ m = size * 0.6 + weight + 8
+ corners = np.array([[xs0 - m, y + dyb - capH - m], [xs0 + total + m, y + dyb - capH - m],
+ [xs0 - m, y + dyb + desc + m], [xs0 + total + m, y + dyb + desc + m]], np.float32)
+ if rot:
+ q = np.deg2rad(rot)
+ dx, dy = corners[:, 0] - x, corners[:, 1] - y
+ rc = np.stack([x + dx * np.cos(q) + dy * np.sin(q), y - dx * np.sin(q) + dy * np.cos(q)], 1)
+ corners = np.vstack([corners, rc])
+ ox, oy = int(np.floor(corners[:, 0].min())), int(np.floor(corners[:, 1].min()))
+ bw, bh = int(np.ceil(corners[:, 0].max())) - ox + 1, int(np.ceil(corners[:, 1].max())) - oy + 1
+ sl = self._box(ox, oy, ox + bw, oy + bh)
+ if sl is None: return None, None
+ im = Image.new('L', (bw * ss, bh * ss), 0)
+ cx = (xs0 - ox) * ss
+ by = (y + dyb - oy) * ss
+ slope = r.normal(0, 0.006) * hand
+ for (ch, st), adv in zip(chars, advs):
+ if not ch.isspace():
+ sc = 1 + r.normal(0, 0.03) * hand
+ f = _font(st, size * ss * sc)
+ fill = int(255 * np.clip(r.normal(0.93, 0.045 * hand + 0.01), 0.72, 1.0))
+ wc = weight + (size * 0.028 * float(np.clip((size - 10) / 30, 0.3, 1)) if st == 'cjk_sans' else 0)
+ # ^ the CJK sans is lighter than Latin bold; boost it, but less when small (dense characters clog up)
+ gs = int(size * ss * sc * 1.8 + wc * ss * 2 + 8)
+ g = Image.new('L', (gs, gs), 0)
+ gx, gy = gs * 0.2, gs * 0.75
+ ImageDraw.Draw(g).text((gx, gy), ch, font=f, fill=fill, anchor='ls', stroke_width=int(round(wc * ss)), stroke_fill=fill)
+ rc = r.normal(0, 1.3) * hand
+ if abs(rc) > 0.05:
+ g = g.rotate(rc, resample=Image.BICUBIC, center=(gx + adv * ss * sc / 2, gy - capH * ss * sc / 2))
+ jx = r.normal(0, 0.012 * size) * hand * ss
+ jy = r.normal(0, 0.02 * size) * hand * ss + slope * (cx - (xs0 - ox) * ss)
+ px, py = int(round(cx + jx - gx)), int(round(by + jy - gy))
+ box = (px, py, px + gs, py + gs)
+ im.paste(ImageChops.lighter(im.crop(box), g), box)
+ cx += adv * ss
+ if rot:
+ im = im.rotate(rot, resample=Image.BICUBIC, center=((x - ox) * ss, (y - oy) * ss))
+ a = np.asarray(im.resize((bw, bh), Image.BOX), np.float32) / 255
+ ys0, xs1 = sl[0].start - oy, sl[1].start - ox
+ return a[ys0:ys0 + (sl[0].stop - sl[0].start), xs1:xs1 + (sl[1].stop - sl[1].start)], sl
+
+ def text_width(self, s, size, font='sans_bold', spacing=0.0):
+ return sum(_font(_pick(ch, font), size).getlength(ch) + spacing for ch in s) - (spacing if s else 0)
+
+ def text(self, s, x, y, size, colour=WHITE, font='sans_bold', anchor='ls', pressure=0.93, weight=0.0, rot=0.0,
+ spacing=0.0, hand=1.0, grain=None, halo=0.14, fall=0.6, strength=0.97):
+ """chalk lettering. anchor: first letter l/m/r, second s (baseline), m (middle of the capitals), t (top).
+ hand: how much every character wanders (0 = typeset). grain: how much the tooth breaks the letters
+ (default: less for small text, so it stays legible)."""
+ m, sl = self._tmask(s, x, y, size, font, anchor, spacing, rot, weight, hand)
+ if sl is None: return
+ h, w = m.shape
+ s0 = self._seed()
+ m = self._warp(m, 0.2 + size * 0.0095, max(4.0, size * 0.1), s0) # broken edges (gentler when small)
+ prs = 0.84 + 0.3 * noise2d(h, w, max(6.0, size * 0.55), 2, s0 + 1) # patchy pressure
+ v = np.clip(m * 1.06, 0, 1) * pressure * prs
+ g = float(np.clip(0.3 + size / 95, 0.52, 1.0)) if grain is None else grain
+ if size < 40: v = np.clip(v * (1.12 - size * 0.003), 0, 1) # small writing is pressed firmer
+ a = self._deposit(v, sl, g, halo) * strength
+ self._lay(sl, a, colour)
+ self._fall(a, sl, colour, fall)
+
+ def _warp(self, m, amp, scale, seed):
+ h, w = m.shape
+ dx = (noise2d(h, w, scale, 2, seed) - 0.5) * 2 * amp
+ dy = (noise2d(h, w, scale, 2, seed + 7) - 0.5) * 2 * amp
+ Y, X = np.mgrid[0:h, 0:w].astype(np.float32)
+ return _bilinear(m, X + dx, Y + dy)
+
+ # ------------------------------------------------------------ board
+ def slate(self, colour='#2c473a', edge='#18271f', worn='#3a5146', mottle=1.0):
+ """matt green board paint: darker toward the frame, cloudy where it has been washed and wiped for years"""
+ H, W = self.H, self.W
+ s = self._seed()
+ r = np.hypot((self.XX - 0.48 * W) / (0.66 * W), (self.YY - 0.42 * H) / (0.7 * H))
+ t = smoothstep(0.2, 1.2, r)[..., None]
+ base = _c(colour) * (1 - t) + _c(edge) * t
+ cloud = noise2d(H, W, 480, 4, s)
+ mid = noise2d(H, W, 110, 3, s + 1)
+ wear = smoothstep(0.52, 0.85, noise2d(H, W, 700, 3, s + 2))[..., None] * 0.35 * mottle
+ base = base * (1 - wear) + _c(worn) * wear
+ fine = noise2d(H, W, 1.3, 2, s + 3)
+ tone = 1 + mottle * (0.11 * (cloud - 0.5) + 0.05 * (mid - 0.5)) + 0.03 * (self.tooth - 0.5) + 0.02 * (fine - 0.5)
+ self.paint = base * tone[..., None]
+
+ @contextmanager
+ def erased(self, keep=0.15, angle=0.0, smear=34, streaks=1.0):
+ """everything drawn inside this block becomes the ghost of an old lesson: wiped with a felt eraser
+ (angle = direction of the wiping, degrees ccw), smeared along the wipe, `keep` of it left behind"""
+ ca0, cc0 = self.ca, self.cc
+ self.ca = np.zeros_like(ca0); self.cc = np.zeros_like(cc0)
+ try:
+ yield self
+ finally:
+ a, c = self.ca, self.cc
+ self.ca, self.cc = ca0, cc0
+ ys, xs = np.nonzero(a > 0.002)
+ if len(xs):
+ pad = smear + 12
+ sl = self._box(xs.min() - pad, ys.min() - pad, xs.max() + pad, ys.max() + pad)
+ a, c = a[sl], c[sl]
+ sa, sc = _dirblur(a, angle, smear), _dirblur(c, angle, smear)
+ h, w = a.shape
+ q = np.deg2rad(angle)
+ Y, X = np.mgrid[0:h, 0:w].astype(np.float32)
+ u = X * np.cos(q) - Y * np.sin(q); v = X * np.sin(q) + Y * np.cos(q)
+ s = self._seed()
+ vmin = float(v.min()); nvv = int(v.max() - vmin) + 4
+ fib = np.interp(v - vmin, np.arange(nvv), (fbm1d(nvv, 2.2, 2, s) + 1) / 2)
+ slow = noise2d(h, w, 60, 2, s + 1)
+ wipe = keep * np.clip(0.15 + 2.0 * slow ** 1.3 * ((1 - streaks) + streaks * 1.4 * fib ** 1.6), 0, 2.4)
+ ga = blur(sa * 0.7 + a * 0.3, 0.7) * wipe
+ gc = np.stack([blur(sc[..., k] * 0.7 + c[..., k] * 0.3, 0.7) for k in range(3)], -1) * wipe[..., None]
+ self.cc[sl] = self.cc[sl] * (1 - ga[..., None]) + gc
+ self.ca[sl] = self.ca[sl] + ga * (1 - self.ca[sl])
+
+ def swipe(self, pts, width=120, strength=0.9, haze=0.05, smear=30, keep=0.12, colour=DUST):
+ """a felt eraser pushed along pts: lifts chalk in its footprint (strength), drags `keep` of it along the
+ motion, leaves a thin streaky film of dust (haze) and a heavier line of dust at the felt's two ends"""
+ P = np.asarray(pts, np.float32)
+ P = spline(P, 8) if len(P) > 2 else P
+ P = _resample(P, 8.0)
+ hw = width / 2
+ pad = hw + smear + 10
+ sl = self._box(P[:, 0].min() - pad, P[:, 1].min() - pad, P[:, 0].max() + pad, P[:, 1].max() + pad)
+ if sl is None: return
+ X, Y = self.XX[sl], self.YY[sl]
+ best = np.full(X.shape, 1e12, np.float32); uu = np.zeros_like(X); vv = np.zeros_like(X)
+ seg = np.hypot(*np.diff(P, axis=0).T); acc = np.concatenate([[0], np.cumsum(seg)])
+ for i in range(len(P) - 1):
+ a, b = P[i], P[i + 1]
+ ab = b - a; l2 = float(ab @ ab) + 1e-6
+ t = np.clip(((X - a[0]) * ab[0] + (Y - a[1]) * ab[1]) / l2, 0, 1)
+ qx, qy = X - (a[0] + t * ab[0]), Y - (a[1] + t * ab[1])
+ dd = qx * qx + qy * qy
+ k = dd < best
+ best = np.where(k, dd, best)
+ uu = np.where(k, acc[i] + t * np.sqrt(l2), uu)
+ vv = np.where(k, np.sign(ab[0] * qy - ab[1] * qx) * np.sqrt(dd), vv)
+ Lp = float(acc[-1])
+ s = self._seed()
+ nu = int(Lp + 2); nv = int(width + 2 * pad)
+ ui = np.clip(uu, 0, nu - 1); vi = np.clip(vv + nv / 2, 0, nv - 1)
+ wav = np.interp(ui, np.arange(nu), fbm1d(nu, 60, 2, s) * 4)
+ band = smoothstep(hw + 3, hw - 4, np.abs(vv) + wav) # round caps where the eraser lands and lifts
+ press = 0.78 + 0.22 * np.interp(ui, np.arange(nu), fbm1d(nu, 140, 2, s + 1))
+ fib = (np.interp(vi, np.arange(nv), fbm1d(nv, 1.8, 2, s + 2)) + 1) / 2
+ fib2 = (np.interp(vi, np.arange(nv), fbm1d(nv, 9, 2, s + 3)) + 1) / 2
+ e = np.clip(band * strength * press * (0.82 + 0.18 * fib), 0, 1)
+ ang = np.rad2deg(np.arctan2(-(P[-1, 1] - P[0, 1]), P[-1, 0] - P[0, 0]))
+ sa = _dirblur(self.ca[sl] * band, ang, smear); sc = _dirblur(self.cc[sl] * band[..., None], ang, smear)
+ self.ca[sl] = self.ca[sl] * (1 - e) + sa * e * keep
+ self.cc[sl] = self.cc[sl] * (1 - e[..., None]) + sc * (e * keep)[..., None]
+ rim = np.exp(-((np.abs(vv) - hw + 3) / 3.0) ** 2) * smoothstep(0, 20, uu) * smoothstep(0, 20, Lp - uu)
+ film = haze * press * (band * (0.3 + 0.55 * fib * fib2 + 0.35 * fib2) + 0.45 * rim * (0.4 + 0.6 * fib2))
+ self._lay(sl, np.clip(film, 0, 1), colour)
+
+ def smudge(self, cx, cy, w=160, h=60, rot=0.0, strength=0.7, haze=0.06):
+ """a short dab of the eraser (a few centimetres of wiping)"""
+ q = np.deg2rad(rot)
+ d = np.array([np.cos(q), -np.sin(q)]) * w / 2
+ self.swipe([(cx - d[0], cy - d[1]), (cx + d[0], cy + d[1])], h, strength, haze, smear=w * 0.25)
+
+ def dust(self, amount=1.0, specks=4200, haze=0.2):
+ """settled chalk powder: specks everywhere, thicker toward the bottom; a streaky haze above the ledge"""
+ x0, y0, x1, y1 = self.area
+ r = self.rng
+ n = int(specks * amount)
+ ys = y1 - (r.random(n) ** 2.3) * (y1 - y0)
+ xs = r.uniform(x0, x1, n)
+ self._specks(xs, ys, r.uniform(0.04, 0.26, n) * amount, DUST, 0.55)
+ m = n // 6
+ self._specks(r.uniform(x0, x1, m), y1 - (r.random(m) ** 3) * 200, r.uniform(0.05, 0.2, m) * amount, DUST, 1.0)
+ sl = self._box(x0, y1 - 240, x1, y1)
+ if sl is None: return
+ Y = self.YY[sl]; hh, ww = Y.shape
+ s = self._seed()
+ streak = np.asarray(Image.fromarray(r.random((max(2, hh // 3), max(2, ww // 150))).astype(np.float32)).resize((ww, hh), Image.BICUBIC))
+ cloud = noise2d(hh, ww, 90, 3, s)
+ k = smoothstep(y1 - 240, y1, Y) ** 2.4
+ self._lay(sl, np.clip(haze * amount * k * (0.35 + 0.45 * streak + 0.6 * cloud), 0, 1), DUST)
+
+ # ------------------------------------------------------------ frame, ledge and props
+ def _wood(self, h, w, colour, dark, seed, vertical=False):
+ if vertical: h, w = w, h
+ r = np.random.default_rng(seed)
+ rs = lambda gh, gw, res=Image.BICUBIC: np.asarray(Image.fromarray(r.random((max(2, gh), max(2, gw))).astype(np.float32)).resize((w, h), res))
+ g1 = rs(h // 2, w // 90); g2 = rs(h, w // 24); pores = rs(h, w // 5, Image.BILINEAR)
+ fig = noise2d(h, w, 80, 3, seed + 1)
+ rings = 0.5 + 0.5 * np.sin((fig * 7 + np.linspace(0, 3, h)[:, None]) * 2 * np.pi)
+ grain = np.clip(0.5 * g1 + 0.3 * g2 + 0.2 * rings, 0, 1)
+ col = _c(dark) + (_c(colour) - _c(dark)) * (0.35 + 0.8 * grain)[..., None]
+ col = col * (1 - 0.3 * smoothstep(0.86, 0.97, pores))[..., None]
+ return np.transpose(col, (1, 0, 2)) if vertical else col
+
+ def _lit(self, nx, ny, nz, spec=0.12, shine=30):
+ dif = np.clip(nx * self.L[0] + ny * self.L[1] + nz * self.L[2], 0, 1)
+ Hh = self.L + np.array([0, 0, 1], np.float32); Hh /= np.linalg.norm(Hh)
+ sp = np.clip(nx * Hh[0] + ny * Hh[1] + nz * Hh[2], 0, 1) ** shine * spec
+ return dif, sp
+
+ def frame(self, rail=None, top=None, ledge=None, wood='#77502f', dark='#2e1d10'):
+ """mitred wooden rails round the board and a chalk ledge along the bottom; sets self.area (the writing area)
+ and self.tray_y (where things lying on the ledge rest). Default sizes are known from the start (self.dims),
+ so dust() and swipes can be laid down before the frame is drawn."""
+ W, H = self.W, self.H
+ rail, top, ledge = rail or self.dims[0], top or self.dims[1], ledge or self.dims[2]
+ self.dims = (rail, top, ledge)
+ BB = H - ledge
+ fl = int(ledge * 0.4)
+ self.area = (rail, top, W - rail, BB)
+ self.tray_y = BB + fl - 3
+ s = self._seed()
+ full = (slice(0, H), slice(0, W))
+ X, Y = self.XX, self.YY
+ # shadows of the frame on the board (the rails stand proud of it; the light comes from above)
+ dt, dl, dr = Y - top, X - rail, (W - rail) - X
+ ins = ((dt > 0) & (dl > 0) & (dr > 0) & (Y < BB)).astype(np.float32)
+ sh = (0.5 * np.exp(-np.clip(dt, 0, None) / 6) + 0.2 * np.exp(-np.clip(dt, 0, None) / 30) + 0.34 * np.exp(-np.clip(dl, 0, None) / 5)
+ + 0.12 * np.exp(-np.clip(dl, 0, None) / 24) + 0.14 * np.exp(-np.clip(dr, 0, None) / 4) + 0.3 * np.exp(-np.clip(BB - Y, 0, None) / 3))
+ self._front(full, np.clip(sh, 0, 0.85) * ins, '#050806')
+ # rails: grain along each rail; profile = rounded outer edge, flat face, bevel down to the board
+ def profile(sa):
+ slope = 1.3 * (1 - smoothstep(0, 0.3, sa)) - 1.0 * smoothstep(0.62, 1.0, sa) # dh/ds
+ n = 1 / np.sqrt(1 + slope ** 2)
+ return -slope * n, n
+ wt = self._wood(top, W, wood, dark, s + 1)
+ sa = (Y[:top] + 0.5) / top
+ na, nz = profile(sa)
+ dif, sp = self._lit(np.zeros_like(na), na, nz)
+ col = wt * (0.32 + 0.95 * dif)[..., None] + sp[..., None]
+ mt = ((Y[:top] <= X[:top] * top / rail) & (Y[:top] <= (W - 1 - X[:top]) * top / rail)).astype(np.float32)
+ self._front((slice(0, top), slice(0, W)), mt, col)
+ for side in (0, 1):
+ x0 = 0 if side == 0 else W - rail
+ sl = (slice(0, H), slice(x0, x0 + rail))
+ wv = self._wood(H, rail, wood, dark, s + 2 + side, vertical=True)
+ xx = X[sl] - x0
+ sa = (xx + 0.5) / rail if side == 0 else (rail - xx - 0.5) / rail
+ na, nz = profile(sa)
+ nx = na if side == 0 else -na
+ dif, sp = self._lit(nx, np.zeros_like(na), nz)
+ col = wv * (0.32 + 0.95 * dif)[..., None] + sp[..., None]
+ xl = xx if side == 0 else rail - 1 - xx
+ mv = (Y[sl] > xl * top / rail).astype(np.float32)
+ self._front(sl, mv, col)
+ j = np.exp(-((Y[sl] - xl * top / rail) / 0.8) ** 2) * (Y[sl] < top + 2) # the mitre joint
+ self._front(sl, j * 0.45, '#140c06')
+ # the ledge: tray floor (seen from above, dusty) and a rounded front lip
+ sl = (slice(BB, H), slice(0, W))
+ wl = self._wood(H - BB, W, wood, dark, s + 5)
+ yy = Y[sl] - BB
+ floor = (yy < fl).astype(np.float32)
+ fcol = wl * (0.34 + 0.18 * (yy / fl))[..., None]
+ fcol = fcol * (1 - 0.5 * np.exp(-yy / 2.5))[..., None] # the gap under the board
+ la = yy - fl
+ nose = smoothstep(0, 7, la)
+ ny = -(1 - nose) * 0.85 + 0.45 * smoothstep(H - BB - fl - 8, H - BB - fl, la)
+ nz = np.sqrt(np.clip(1 - ny ** 2, 0, 1))
+ dif, sp = self._lit(np.zeros_like(ny), ny, nz, 0.18, 24)
+ lcol = wl * (0.3 + 0.85 * dif)[..., None] * (1 - 0.35 * smoothstep(0, H - BB - fl, la))[..., None] + sp[..., None]
+ col = np.where(floor[..., None] > 0, fcol, lcol)
+ self._front(sl, np.ones_like(yy), col)
+ self._front(sl, np.exp(-((la - 0.5) / 1.2) ** 2) * 0.5, '#120a05') # floor meets lip
+ # chalk dust in the tray: heavier toward the back where it falls from the board
+ fsl = (slice(BB, BB + fl), slice(rail // 2, W - rail // 2))
+ hh, ww = fl, W - 2 * (rail // 2)
+ r = self.rng
+ streak = np.asarray(Image.fromarray(r.random((max(2, hh // 2), max(2, ww // 40))).astype(np.float32)).resize((ww, hh), Image.BICUBIC))
+ cl = noise2d(hh, ww, 50, 3, s + 6)
+ k = 1 - smoothstep(0, fl, self.YY[fsl] - BB) * 0.6
+ self._front(fsl, np.clip((0.12 + 0.35 * cl * streak) * k, 0, 0.7), DUST)
+ n = int(W * 0.5)
+ px = r.uniform(rail, W - rail, n); py = BB + 2 + r.random(n) ** 1.5 * (fl - 4)
+ self._front_specks(px, py, r.uniform(0.2, 0.7, n), r.uniform(0.5, 1.6, n))
+
+ def _front_specks(self, x, y, alpha, rad, colour=DUST):
+ sl = self._box(x.min() - 4, y.min() - 4, x.max() + 5, y.max() + 5)
+ m = np.zeros((sl[0].stop - sl[0].start, sl[1].stop - sl[1].start), np.float32)
+ for big in (False, True):
+ k = rad > 1.0 if big else rad <= 1.0
+ mm = np.zeros_like(m)
+ np.add.at(mm, (np.round(y[k]).astype(int) - sl[0].start, np.round(x[k]).astype(int) - sl[1].start), alpha[k])
+ sz = 1.1 if big else 0.55
+ m += blur(mm, sz) / (2 * np.pi * sz * sz) * 0.9
+ self._front(sl, np.clip(m, 0, 0.85), colour)
+
+ def chalk_stick(self, x, y, length=86, colour=WHITE, rot=0.0, r=7.5, worn='right'):
+ """a stick of chalk lying on the ledge, centred at (x, y - r) so it rests on y: a matt cylinder, one end cut
+ square, the other (worn='right'|'left'|None) worn to a slant; fine lengthwise striations; its shadow"""
+ cy = y - r
+ q = np.deg2rad(rot); ca, sa = np.cos(q), np.sin(q)
+ R = length / 2 + r + 12
+ sl = self._box(x - R, cy - R * abs(sa) - r - 12, x + R, cy + R * abs(sa) + r + 12)
+ X, Y = self.XX[sl] - x, self.YY[sl] - cy
+ u = X * ca - Y * sa
+ v = X * sa + Y * ca
+ hl = length / 2
+ d = _sdf_rrect(u, v, hl, r, r * 0.4)
+ facet = np.zeros_like(u)
+ if worn:
+ sg = 1 if worn == 'right' else -1
+ cut = (sg * u - hl + 0.55 * (r + v)) / np.hypot(1, 0.55) # a slanted flat worn into the used end
+ d = (d + cut + np.sqrt((d - cut) ** 2 + 2.5 ** 2)) / 2 # smooth intersection: rounded edges
+ facet = smoothstep(-4.0, -1.0, cut) # the worn flat catches more light
+ m = np.clip(0.5 - d, 0, 1)
+ self._shadow(sl, m, 2.5, 4.5, 2.4, 0.55)
+ self._shadow(sl, m, 0.5, 1.5, 0.8, 0.45)
+ nv = np.clip(v / r, -1, 1); nz = np.sqrt(np.clip(1 - nv ** 2, 0, 1))
+ dif, _ = self._lit(sa * nv, ca * nv, nz)
+ s = self._seed()
+ nn = int(2 * r + 6)
+ stri = np.interp(np.clip(v + r + 3, 0, nn - 1), np.arange(nn), fbm1d(nn, 1.5, 2, s)) * 0.05
+ col = _c(colour) * (0.5 + 0.62 * dif - stri + 0.06 * (self.tooth[sl] - 0.5))[..., None]
+ fcol = _c(colour) * (0.98 + 0.08 * (self.tooth[sl] - 0.5))[..., None]
+ col = col * (1 - facet[..., None]) + fcol * facet[..., None]
+ self._front(sl, m, np.clip(col, 0, 1))
+
+ def eraser(self, x, y, w=196, h=50, wood='#7c5433', felt='#4a4b48'):
+ """a felt board eraser standing on the ledge, bottom centre at (x, y): wooden back on top, layered felt below,
+ caked with chalk (thickest near the working face), with its shadow on the tray"""
+ x0, y0 = x - w / 2, y - h
+ sl = self._box(x0 - 30, y0 - 20, x0 + w + 30, y + 16)
+ X, Y = self.XX[sl], self.YY[sl]
+ u, v = X - x, Y - (y0 + h / 2)
+ m = np.clip(0.5 - _sdf_rrect(u, v, w / 2, h / 2, 3.5), 0, 1)
+ self._shadow(sl, m, 5, 5, 4, 0.5)
+ self._shadow(sl, m, 1, 2, 1.2, 0.5)
+ yy = Y - y0
+ split = h * 0.46
+ # wooden back: rounded top edge, grain along its length
+ wt = self._wood(sl[0].stop - sl[0].start, sl[1].stop - sl[1].start, wood, '#3a2414', self._seed())
+ ny = -(1 - smoothstep(0, 7, yy)) * 0.9 + 0.5 * smoothstep(split - 5, split, yy)
+ nx = -(1 - smoothstep(0, 5, X - x0)) * 0.6 + 0.6 * smoothstep(w - 5, w, X - x0)
+ nz = np.sqrt(np.clip(1 - ny ** 2 - nx ** 2, 0.05, 1))
+ dif, sp = self._lit(nx, ny, nz, 0.14, 26)
+ wd = wt * (0.3 + 0.9 * dif)[..., None] + sp[..., None]
+ # felt: stacked layers, chalk caked in horizontal streaks, heavier toward the bottom
+ s = self._seed()
+ hh, ww = X.shape
+ fib = blur(self.rng.random((hh, ww)).astype(np.float32), 0.7) # matt felt: fine, non-directional
+ fib = (fib - fib.mean()) / (fib.std() + 1e-6)
+ blot = noise2d(hh, ww, 11, 3, s + 1)
+ seams = 1 - 0.22 * (np.exp(-((yy - split - (h - split) * 0.36) / 0.8) ** 2) + np.exp(-((yy - split - (h - split) * 0.7) / 0.8) ** 2))
+ caked = smoothstep(0.35, 0.75, blot * 0.8 + 0.45 * smoothstep(split + 2, h, yy)) # chalk worked into the felt
+ dust = np.clip(0.12 + 0.62 * caked + 0.05 * fib, 0, 0.82)
+ fc = _c(felt) * (1 + 0.1 * fib)[..., None] * seams[..., None] * (1 - 0.3 * smoothstep(h - 5, h, yy))[..., None]
+ fc = fc * (1 - dust[..., None]) + _c(DUST) * (0.74 + 0.06 * fib)[..., None] * dust[..., None]
+ col = np.where((yy < split)[..., None], wd, fc)
+ col = col * (1 - 0.4 * np.exp(-((yy - split) / 1.1) ** 2))[..., None]
+ self._front(sl, m, np.clip(col, 0, 1))
+
+ def crumbs(self, x0, x1, n=18, colours=(WHITE, WHITE, YELLOW, PINK, BLUE)):
+ """little broken bits of chalk lying in the tray"""
+ r = self.rng
+ for i in range(n):
+ x = r.uniform(x0, x1); rr = r.uniform(1.4, 3.6)
+ y = self.tray_y - rr * 0.6 + r.uniform(-4, 2)
+ sl = self._box(x - 8, y - 8, x + 9, y + 9)
+ X, Y = self.XX[sl] - x, self.YY[sl] - y
+ th = np.arctan2(Y, X)
+ rad = rr * (1 + 0.14 * np.sin(2 * th + r.uniform(0, 6)) + 0.09 * np.sin(3 * th + r.uniform(0, 6)))
+ m = np.clip(rad - np.hypot(X, Y * 1.35) + 0.5, 0, 1)
+ self._shadow(sl, m, 1.2, 1.6, 1.0, 0.45)
+ lit = np.clip(0.8 - 0.3 * Y / rr - 0.1 * X / rr, 0.45, 1.05)
+ self._front(sl, m, np.clip(_c(r.choice(colours)) * lit[..., None], 0, 1))
+
+ # ------------------------------------------------------------ output
+ def composite(self, vignette=0.26):
+ W, H = self.W, self.H
+ lamp = 1 + 0.08 * np.exp(-(((self.XX - 0.34 * W) / (0.6 * W)) ** 2 + ((self.YY - 0.18 * H) / (0.65 * H)) ** 2))
+ img = (self.paint * (1 - self.ca[..., None]) + self.cc) * lamp[..., None]
+ img = img * (1 - self.ta[..., None]) + self.tc
+ r = np.hypot((self.XX - W * 0.5) / W, (self.YY - H * 0.45) / H)
+ img = img * (1 - vignette * r ** 2 * 2.2)[..., None]
+ return Image.fromarray((np.clip(img, 0, 1) * 255).astype(np.uint8))
+
+ 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/cyberpunk.py b/lib/cyberpunk.py
new file mode 100644
index 0000000..9aab160
--- /dev/null
+++ b/lib/cyberpunk.py
@@ -0,0 +1,1348 @@
+"""cyberpunk — a rain-soaked neon street canyon at night, lit like a film still (numpy + Pillow only).
+
+Model: one physically-lit HDR scene seen through one camera, then finished like a frame of film.
+ camera a level pinhole camera `eye` metres above the street, looking straight down it (X right, Y up,
+ Z into the scene). A point lands at (vx + f*X/Z, vy + f*(eye - Y)/Z): verticals stay vertical,
+ every line along the street runs to the vanishing point, sizes fall off as 1/Z.
+ buffers painting fills screen-space buffers — albedo (surface colour), emission (light given off, HDR:
+ a neon core is 5-10x paper white), depth in metres (a z-buffer, so draw order does not matter
+ for solid things, and fog), and a mirror row (the screen row where that object's foot meets
+ the ground, for reflections). Things made only of light (hologram, light trails, tube halos)
+ go to an additive buffer, already faded by the fog in front of them.
+ light every surface is lit by a dim blue ambient plus the *spill* of the light sources near it on
+ screen (emission blurred at three radii): a wall glows magenta beside a magenta sign, a sign's
+ dark backing picks up its own colour. No light is painted by hand.
+ buildings perspective boxes: the street-side facade is an X = const plane, the front face a Z = const
+ plane. Each is painted as a texture in metres — concrete with rain streaks, floor slabs, a
+ window grid (lit / dark / blinds / TV-blue), air-conditioner boxes, a ground floor of lit
+ shopfronts and roller shutters with light leaking underneath — and warped onto the screen by
+ the exact inverse camera map, pre-filtered along the foreshortened axis so far windows melt
+ into a glow instead of shimmering.
+ neon real glass tubes. A hairline skeleton (a W0 font glyph or a path) is widened into a tube of
+ radius r; brightness follows the chord length through the glowing gas (hot centre line, dark
+ rim), the core over-exposes toward white the way film does, a short coloured halo hugs the
+ glass. A tube can `flicker` (caught mid-dip: dim and patchy along its length) or be `dead`
+ (pale unlit glass with one specular line). Blade signs stick out over the street and face the
+ camera: steel brackets, a box with depth, a dark backing, a border tube, letters. Lightboxes
+ are backlit acrylic with the fluorescent tubes showing through as soft bands.
+ hologram a translucent projected panel, light only: the motif (a drifting jellyfish) and lettering in
+ cyan with magenta fringes, scanlines at a fixed pitch on the panel, a slow brightness band,
+ a few slices torn sideways, a dust of sparkle, soft edges. It lights the fog and the walls.
+ street wet asphalt evaluated per pixel in ground coordinates (aggregate, paint, puddles all
+ foreshorten correctly and fade out below a pixel): kerbs, paving joints, worn lane paint, a
+ zebra crossing, grates.
+ reflection every upright thing is mirrored in the ground about its *own* contact row (a far wall about its
+ far base, a hanging sign about the ground under it); pixels are splatted and the nearest
+ object wins, so a figure's reflection covers the wall's. The mirror image is torn by ripples,
+ kept sharp only in puddles, smeared into long vertical streaks on damp asphalt (the brightest
+ lights smear farthest), and Fresnel makes the far street a better mirror than the near one.
+ atmosphere depth fog whose colour is the city's light scattered in it (the end of the street glows);
+ steam from grates (domain-warped noise, widening, bent by wind, lit by what is around it);
+ rain in three depths (fine far rain, mid streaks, a few big defocused near streaks), each
+ streak lit by the light around it, so rain only shows where it falls past neon; splash rings.
+ lens/film bloom at four radii, red film halation around hot lights, ACES filmic tone curve, cool shadows /
+ warm highlights, radial chromatic aberration growing toward the corners, mid-tone film grain,
+ one thin torn scanline band, vignette.
+
+ from cyberpunk import Cyberpunk, MAGENTA, CYAN, AMBER
+ c = Cyberpunk(1920, 1080, seed=7)
+ c.sky(); c.street()
+ c.building(-1, 12, 40, 45); c.building(+1, 12, 36, 60)
+ c.blade_sign(-1, 20, 3.5, 9.5, '拉麺', AMBER, dead=[1])
+ c.hologram(80, -6, 8, 10, 30, '海月', 'SEA MOON')
+ c.steam(2.0, 16); c.rain()
+ c.save('out.png')
+"""
+import glob
+import os
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+from core import blur, fbm1d, spline, noise2d, smoothstep, load_font
+
+MAGENTA, CYAN, AMBER = '#ff2a8c', '#2ed8ff', '#ffa93a'
+RED, WHITE = '#ff3b3b', '#fff4e8'
+LUMA = np.array([0.2126, 0.7152, 0.0722], np.float32)
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+def _lin(c):
+ """'#rrggbb' or an RGB triple (display values) -> linear light"""
+ c = hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)
+ return c ** 2.2
+
+
+def _gblur(a, s):
+ """gaussian blur of (H, W) or (H, W, C); large radii run at reduced resolution (same look, much faster)"""
+ if s <= 0: return a.astype(np.float32).copy()
+ if a.ndim == 3: return np.stack([_gblur(a[..., i], s) for i in range(a.shape[2])], -1)
+ k = int(min(8, max(1, s // 4)))
+ if k == 1: return blur(a, s)
+ H, W = a.shape
+ sm = np.asarray(Image.fromarray(a.astype(np.float32), 'F').resize((max(2, W // k), max(2, H // k)), Image.BOX))
+ sm = blur(sm, s / k)
+ return np.asarray(Image.fromarray(sm, 'F').resize((W, H), Image.BILINEAR))
+
+
+def _blur_axis(a, s, axis):
+ """gaussian (three box passes) along one axis only — for streaks and anisotropic texture filtering"""
+ if s < 0.3: return a.astype(np.float32).copy()
+ out = a.astype(np.float32)
+ w = int(np.sqrt(12 * s * s / 3 + 1)); w += (w % 2 == 0); r = w // 2
+ for _ in range(3):
+ pad = [(0, 0)] * out.ndim; pad[axis] = (r + 1, r)
+ c = np.cumsum(np.pad(out, pad, mode='edge'), axis=axis, dtype=np.float64)
+ n = c.shape[axis]
+ out = ((np.take(c, np.arange(w, n), axis=axis) - np.take(c, np.arange(0, n - w), axis=axis)) / w).astype(np.float32)
+ return out
+
+
+def _sample(img, x, y):
+ """bilinear sample of an (H, W) or (H, W, C) array at float pixel coordinates (clamped to the edge)"""
+ H, W = img.shape[:2]
+ x = np.clip(x, 0, W - 1.001); y = np.clip(y, 0, H - 1.001)
+ x0 = x.astype(np.int32); y0 = y.astype(np.int32)
+ fx = (x - x0).astype(np.float32); fy = (y - y0).astype(np.float32)
+ if img.ndim == 3: fx = fx[..., None]; fy = fy[..., None]
+ return ((img[y0, x0] * (1 - fx) + img[y0, x0 + 1] * fx) * (1 - fy)
+ + (img[y0 + 1, x0] * (1 - fx) + img[y0 + 1, x0 + 1] * fx) * fy)
+
+
+def _vnoise(x, y, seed=0):
+ """smooth value noise at arbitrary float coordinates (lattice spacing 1), in [0, 1]"""
+ xi = np.floor(x); yi = np.floor(y)
+ fx = x - xi; fy = y - yi
+ fx = fx * fx * (3 - 2 * fx); fy = fy * fy * (3 - 2 * fy)
+ xi = xi.astype(np.int64); yi = yi.astype(np.int64)
+
+ def h(a, b):
+ n = (a * 374761393 + b * 668265263 + seed * 144269477) & 0xffffffff
+ n = ((n ^ (n >> 13)) * 1274126177) & 0xffffffff
+ return ((n ^ (n >> 16)) & 0xffff).astype(np.float32) / 65535.0
+ return ((h(xi, yi) * (1 - fx) + h(xi + 1, yi) * fx) * (1 - fy)
+ + (h(xi, yi + 1) * (1 - fx) + h(xi + 1, yi + 1) * fx) * fy).astype(np.float32)
+
+
+def _fbm(x, y, octaves=4, seed=0, foot=None):
+ """fractal value noise in [0, 1]; `foot` (lattice cells per pixel) fades octaves finer than a pixel"""
+ out = 0.0; amp = 1.0; tot = 0.0; fr = 1.0
+ for o in range(octaves):
+ n = _vnoise(x * fr, y * fr, seed + o * 7919)
+ if foot is not None:
+ n = 0.5 + (n - 0.5) * np.clip(1.4 - foot * fr, 0, 1)
+ out = out + amp * n; tot += amp; amp *= 0.5; fr *= 2.0
+ return (out / tot).astype(np.float32)
+
+
+def _aces(x):
+ return np.clip((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0, 1)
+
+
+# ---------------------------------------------------------------- sign fonts (never committed to the repo)
+_FONTS = {
+ 'neon': [('/System/Library/Fonts/ヒラギノ角ゴシック W0.ttc', 0), ('/System/Library/Fonts/ヒラギノ角ゴシック W1.ttc', 0),
+ ('/usr/share/fonts/**/NotoSansCJK*Thin*.tt[cf]', 0), ('/usr/share/fonts/**/NotoSansCJK*Light*.tt[cf]', 0),
+ ('C:/Windows/Fonts/msyhl.ttc', 0), ('/System/Library/Fonts/Hiragino Sans GB.ttc', 0),
+ ('/usr/share/fonts/**/NotoSansCJK*.tt[cf]', 0), ('C:/Windows/Fonts/msyh.ttc', 0)],
+ 'bold': [('/System/Library/Fonts/ヒラギノ角ゴシック W6.ttc', 0), ('/System/Library/Fonts/STHeiti Medium.ttc', 0),
+ ('/usr/share/fonts/**/NotoSansCJK*Bold*.tt[cf]', 0), ('C:/Windows/Fonts/msyhbd.ttc', 0)],
+ 'mincho': [('/System/Library/Fonts/ヒラギノ明朝 ProN.ttc', 0), ('/System/Library/Fonts/Supplemental/Songti.ttc', 0),
+ ('/usr/share/fonts/**/NotoSerifCJK*.tt[cf]', 0), ('C:/Windows/Fonts/simsun.ttc', 0)],
+ 'thin': [('/System/Library/Fonts/HelveticaNeue.ttc', 12), ('/System/Library/Fonts/Avenir Next.ttc', 10),
+ ('/usr/share/fonts/**/DejaVuSans-ExtraLight.ttf', 0), ('C:/Windows/Fonts/segoeuil.ttf', 0)],
+ 'light': [('/System/Library/Fonts/HelveticaNeue.ttc', 7), ('/System/Library/Fonts/Avenir Next.ttc', 7),
+ ('/usr/share/fonts/**/DejaVuSans.ttf', 0), ('C:/Windows/Fonts/segoeuil.ttf', 0)],
+}
+_FCACHE = {}
+
+
+def sign_font(kind, size):
+ """PIL font for signs. kind: neon (hairline CJK+Latin, the tube skeleton), bold, mincho, thin / light (Latin).
+ Override with $INKPAINT_FONT_NEON / _BOLD / _MINCHO / _THIN / _LIGHT."""
+ key = (kind, int(size))
+ if key in _FCACHE: return _FCACHE[key]
+ env = os.environ.get('INKPAINT_FONT_' + kind.upper())
+ font = None
+ for pat, idx in ([(env, 0)] if env else []) + _FONTS.get(kind, []):
+ for p in glob.glob(pat, recursive=True):
+ try:
+ font = ImageFont.truetype(p, max(4, int(size)), index=idx); break
+ except OSError:
+ pass
+ if font: break
+ if font is None: font = load_font('cjk_sans', size)
+ _FCACHE[key] = font
+ return font
+
+
+def _glyph(ch, size, kind='neon'):
+ """one character as a float mask centred in a square of side ~1.5*size"""
+ f = sign_font(kind, size)
+ n = int(size * 1.5) + 4
+ im = Image.new('L', (n, n), 0)
+ ImageDraw.Draw(im).text((n / 2, n / 2), ch, font=f, fill=255, anchor='mm')
+ return np.asarray(im, np.float32) / 255
+
+
+class Cyberpunk:
+ def __init__(self, W=1920, H=1080, seed=0, focal=1150.0, vp=None, eye=1.7, fog=150.0, wall=9.5, road=6.0,
+ ambient='#3a4266', fog_colour='#1c2140', record=True):
+ self.W, self.H = W, H
+ self.rng = np.random.default_rng(seed)
+ self.f = float(focal)
+ self.vx, self.vy = (W * 0.5, H * 0.52) if vp is None else (float(vp[0]), float(vp[1]))
+ self.eye, self.fog_m, self.wall, self.road = float(eye), float(fog), float(wall), float(road)
+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)
+ z3 = lambda: np.zeros((H, W, 3), np.float32)
+ self.alb, self.emi, self.add, self.lsrc = z3(), z3(), z3(), z3()
+ self.dep = np.full((H, W), np.inf, np.float32)
+ self.base = np.full((H, W), -1.0, np.float32)
+ self.ground = np.zeros((H, W), np.float32)
+ self.pools = np.zeros((H, W), np.float32)
+ self.damp = np.zeros((H, W), np.float32)
+ self.steam_d = np.zeros((H, W), np.float32)
+ self.amb = _lin(ambient) * 0.3
+ self.fogc = _lin(fog_colour)
+ self.sky_t = 0.5 # how much of the painted sky survives the haze
+ self.fog_floor = 0.1 # far haze saturates: distant towers keep a trace of themselves
+ self.spill_k, self.scatter_k = 0.55, 0.6
+ self.exposure = 1.1
+ self.rain_layers, self.rings = [], None
+ self.glitch_bands = []
+ self.street_on = False
+ self.record = record
+ self.stages = []
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ # ------------------------------------------------------------ camera
+ def project(self, X, Y, Z):
+ """world metres -> screen pixels"""
+ Z = np.maximum(Z, 1e-3)
+ return self.vx + self.f * np.asarray(X) / Z, self.vy + self.f * (self.eye - np.asarray(Y)) / Z
+
+ def ground_row(self, Z):
+ """screen row where the ground at depth Z is seen (the mirror line of anything standing there)"""
+ return self.vy + self.f * self.eye / np.maximum(Z, 1e-3)
+
+ def fog_t(self, Z):
+ """fraction of light that survives the haze over Z metres"""
+ return float(np.exp(-Z / self.fog_m))
+
+ def near_z(self, side, wall=None):
+ """nearest depth of a facade at |X| = wall that is still on screen"""
+ wall = self.wall if wall is None else wall
+ edge = self.vx if side < 0 else self.W - self.vx
+ return self.f * wall / edge
+
+ # ------------------------------------------------------------ low-level compositing
+ def _box(self, x0, y0, x1, y1):
+ x0, y0 = max(0, int(np.floor(x0))), max(0, int(np.floor(y0)))
+ x1, y1 = min(self.W, int(np.ceil(x1)) + 1), min(self.H, int(np.ceil(y1)) + 1)
+ if x1 <= x0 or y1 <= y0: return None
+ return (slice(y0, y1), slice(x0, x1))
+
+ def _put(self, sl, a, alb=0.0, emi=0.0, depth=1.0, base=None, ztest=True):
+ """paint an opaque surface: coverage `a` (cropped to sl), colours as linear RGB (3,) or (h, w, 3),
+ depth scalar or (h, w). Z-tested, so nearer things always win whatever the order of the calls."""
+ a = np.clip(a, 0, 1).astype(np.float32)
+ D = self.dep[sl]
+ if ztest: a = a * (depth < D)
+ a3 = a[..., None]
+ alb = np.asarray(alb, np.float32); emi = np.asarray(emi, np.float32)
+ self.alb[sl] = self.alb[sl] * (1 - a3) + alb * a3
+ self.emi[sl] = self.emi[sl] * (1 - a3) + emi * a3
+ self.add[sl] *= 1 - a3
+ hard = a > 0.5
+ D[hard] = depth[hard] if np.ndim(depth) else depth
+ if base is not None:
+ B = self.base[sl]; B[hard] = base[hard] if np.ndim(base) else base
+ G = self.ground[sl]; G *= 1 - a
+ return a
+
+ def _glow(self, sl, rgb, depth, light=0.0):
+ """additive light in the air (halo, hologram, trail): faded by its own fog, hidden behind nearer solids"""
+ vis = (depth < self.dep[sl]).astype(np.float32)[..., None]
+ T = np.exp(-np.asarray(depth, np.float32) / self.fog_m)
+ T = T[..., None] if np.ndim(T) else T
+ self.add[sl] += rgb * vis * T
+ if light: self.lsrc[sl] += rgb * vis * light
+
+ def _poly(self, pts, ss=2):
+ """antialiased polygon -> (slice, mask) cropped to its bounding box"""
+ P = np.asarray(pts, np.float32)
+ sl = self._box(P[:, 0].min() - 1, P[:, 1].min() - 1, P[:, 0].max() + 1, P[:, 1].max() + 1)
+ if sl is None: return None, None
+ y0, x0 = sl[0].start, sl[1].start
+ h, w = sl[0].stop - y0, sl[1].stop - x0
+ im = Image.new('L', (w * ss, h * ss), 0)
+ ImageDraw.Draw(im).polygon([((x - x0) * ss, (y - y0) * ss) for x, y in P], fill=255)
+ return sl, np.asarray(im.resize((w, h), Image.BOX), np.float32) / 255
+
+ def _lines(self, sl, segs, ss=2):
+ """antialiased strokes in a box: segs = [(points, width_px, value)], returns (coverage, value-weighted)"""
+ y0, x0 = sl[0].start, sl[1].start
+ h, w = sl[0].stop - y0, sl[1].stop - x0
+ cov = Image.new('F', (w * ss, h * ss), 0.0); val = Image.new('F', (w * ss, h * ss), 0.0)
+ dc, dv = ImageDraw.Draw(cov), ImageDraw.Draw(val)
+ for pts, width, v in segs:
+ q = [((x - x0) * ss, (y - y0) * ss) for x, y in pts]
+ wd = max(1, int(round(width * ss)))
+ dc.line(q, fill=1.0, width=wd, joint='curve'); dv.line(q, fill=float(v), width=wd, joint='curve')
+ c = np.asarray(cov.resize((w, h), Image.BOX)); v = np.asarray(val.resize((w, h), Image.BOX))
+ return np.clip(c, 0, 1), v
+
+ # ------------------------------------------------------------ sky and the far city
+ def sky(self, zenith='#04050c', mid='#0d0f26', horizon='#462660', glow='#ff4d8f', clouds=1.0, seed=None):
+ """night sky over the city: near-black zenith, a low smog deck lit from underneath by the streets
+ (magenta-amber near the horizon, fading upward), all of it emission (the sky has no albedo)"""
+ seed = self._seed() if seed is None else seed
+ H, W = self.H, self.W
+ t = np.clip(self.YY / max(1.0, self.vy), 0, 1.2)[..., None]
+ z, m, h = _lin(zenith), _lin(mid), _lin(horizon)
+ col = np.where(t < 0.55, z + (m - z) * (t / 0.55), m + (h - m) * np.clip((t - 0.55) / 0.45, 0, 1) ** 1.6)
+ n = np.asarray(Image.fromarray(noise2d(H // 3, W // 9, 18, 5, seed)).resize((W, H), Image.BICUBIC))
+ n2 = np.asarray(Image.fromarray(noise2d(H // 2, W // 4, 14, 4, seed + 1)).resize((W, H), Image.BICUBIC))
+ billow = smoothstep(0.38, 0.78, 0.65 * n + 0.35 * n2)
+ under = np.clip(t[..., 0], 0, 1) ** 2.2
+ col = col * (0.55 + 0.9 * billow[..., None])
+ col = col + _lin(glow) * (billow * under * 0.16 * clouds)[..., None] + _lin(AMBER) * (billow ** 3 * under * 0.03 * clouds)[..., None]
+ below = np.clip((self.YY - self.vy) / (H - self.vy + 1), 0, 1)[..., None] # under the horizon: unlit haze
+ col = np.where(below > 0, h * 0.35 * (1 - below) ** 3 + z * 0.4, col)
+ self.alb[:] = 0; self.emi[:] = col.astype(np.float32)
+ self.dep[:] = np.inf; self.base[:] = self.vy
+
+ def skyline(self, z=420.0, x_range=(-420, 420), heights=(60, 300), widths=(18, 60), colour='#12152a',
+ lights=0.5, beacons=0.5, seed=None):
+ """a row of far towers at depth z: flat silhouettes with setback tops, pin-prick windows, red beacons"""
+ r = np.random.default_rng(self._seed() if seed is None else seed)
+ X = x_range[0]
+ while X < x_range[1]:
+ w = r.uniform(*widths); h = r.uniform(*heights) * (1.2 - 0.5 * min(1, abs(X) / max(abs(x_range[0]), 1)))
+ if r.random() < 0.6: # a setback crown
+ i = w * r.uniform(0.12, 0.3)
+ pts = [(X, 0), (X + w, 0), (X + w, h * 0.72), (X + w - i, h * 0.72), (X + w - i, h), (X + i, h), (X + i, h * 0.72), (X, h * 0.72)]
+ else:
+ pts = [(X, 0), (X + w, 0), (X + w, h), (X, h)]
+ scr = [self.project(px, py, z) for px, py in pts]
+ sl, m = self._poly(scr)
+ if sl is not None:
+ yy = self.YY[sl]
+ shade = _lin(colour) * (0.8 + 0.4 * r.random())
+ em = np.zeros(m.shape + (3,), np.float32)
+ if lights:
+ dots = (r.random(m.shape) < 0.012 * lights) & (((yy.astype(int)) % 3) == 0)
+ tint = np.where(r.random(m.shape)[..., None] < 0.7, _lin('#ffc27a'), _lin('#9fd8ff'))
+ em = dots[..., None] * tint * r.uniform(0.3, 1.2, m.shape)[..., None]
+ self._put(sl, m, shade, em, z, self.ground_row(z))
+ if r.random() < beacons:
+ bx, by = self.project(X + w / 2, h + 2, z)
+ self.light(bx, by, 1.2, RED, z, 3.0)
+ X += w + r.uniform(-4, 14)
+
+ def light(self, x, y, r, colour, z, level=2.0, halo=4.0):
+ """a small point light (beacon, lamp): a hot dot plus a soft halo in the air"""
+ sl = self._box(x - r * halo * 3, y - r * halo * 3, x + r * halo * 3, y + r * halo * 3)
+ if sl is None: return
+ d = np.hypot(self.XX[sl] - x, self.YY[sl] - y)
+ core = np.clip(1.2 - d / max(r, 0.6), 0, 1)
+ col = _lin(colour)
+ self._put(sl, core, 0.0, col * level * 2.5, z, self.ground_row(z))
+ self._glow(sl, col * (np.exp(-(d / (r * halo)) ** 2) * level * 0.6)[..., None], z, 0.5)
+
+ # ------------------------------------------------------------ buildings
+ def _facade(self, wm, hm, ppu, ppv, colour, floor, bay, lit, shop, seed, signs=True, flip=False, mix=(0.45, 0.35, 0.2, 0.0)):
+ """paint one wall as a texture in metres: returns albedo, emission (th, tw, 3); row 0 is the top (Y = hm)"""
+ r = np.random.default_rng(seed)
+ tw, th = max(4, int(np.ceil(wm * ppu))), max(4, int(np.ceil(hm * ppv)))
+ u = (np.arange(tw, dtype=np.float32) + 0.5) / ppu
+ v = hm - (np.arange(th, dtype=np.float32) + 0.5) / ppv
+ U, V = np.meshgrid(u, v)
+ n1 = _fbm(U / 3.0, V / 3.0, 3, seed)
+ streak = _fbm(U / 0.35, V / 6.0, 3, seed + 1)
+ shade = (0.7 + 0.55 * n1) * (0.72 + 0.5 * streak)
+ alb = (_lin(colour)[None, None, :] * shade[..., None]).astype(np.float32)
+ emi = np.zeros_like(alb)
+ gf = 4.4 if shop else 0.0
+ fv = V - gf
+ k = np.floor(fv / floor).astype(np.int32); vv = fv - k * floor
+ j = np.floor(U / bay).astype(np.int32); uu = U - j * bay
+ up = (fv > 0) & (V < hm - 0.6)
+ alb[up & (vv < 0.3)] *= 0.55 # floor slab
+ alb[up & (vv >= 0.3) & (vv < 0.38)] *= 1.5 # its lit lip
+ nk, nj = int(hm / floor) + 3, int(wm / bay) + 3
+ kk, jj = np.clip(k, 0, nk - 1), np.clip(j, 0, nj - 1)
+ t_lit = r.random((nk, nj)) < lit
+ pal = np.array([_lin(c) for c in ('#ffb46e', '#ffe0b8', '#d6e8ff', '#7fa6ff', '#ff9ccc', '#9ff0e2')], np.float32)
+ t_col = r.choice(len(pal), (nk, nj), p=[0.5, 0.2, 0.17, 0.08, 0.03, 0.02])
+ t_int = r.uniform(0.15, 1.0, (nk, nj)) ** 2.0 * 0.75
+ t_bl = r.random((nk, nj)) < 0.4
+ t_ac = r.random((nk, nj)) < 0.35
+ t_acx = r.uniform(0.15, max(0.2, bay - 1.0), (nk, nj))
+ win = up & (uu > 0.32) & (uu < bay - 0.32) & (vv > 0.95) & (vv < floor - 0.42)
+ alb[win] = _lin('#0d1119') * (0.8 + 0.4 * n1[win])[..., None]
+ Lw = win & t_lit[kk, jj]
+ grad = 0.55 + 0.6 * np.clip((vv - 0.95) / (floor - 1.37), 0, 1)
+ blind = np.where(t_bl[kk, jj], 0.35 + 0.65 * (np.sin(vv * 2 * np.pi / 0.09) > -0.1), 1.0)
+ t_cur = r.uniform(-0.2, 1.0, (nk, nj)) # a half-drawn curtain
+ cur = np.where((uu - 0.32) / (bay - 0.64) < t_cur[kk, jj], 0.18, 1.0)
+ e = pal[t_col[kk, jj]] * (t_int[kk, jj] * grad * blind * cur)[..., None]
+ emi[Lw] = e[Lw]
+ mull = win & (np.abs(uu - bay / 2) < 0.045)
+ alb[mull] = _lin('#1a1d24'); emi[mull] = 0
+ ac = up & t_ac[kk, jj] & (uu > t_acx[kk, jj]) & (uu < t_acx[kk, jj] + 0.85) & (vv > 0.36) & (vv < 0.88)
+ grille = 0.75 + 0.25 * (np.sin((uu - t_acx[kk, jj]) * 2 * np.pi / 0.07) > 0)
+ alb[ac] = (_lin('#6b7078') * 0.55 * grille[..., None])[ac]; emi[ac] = 0
+ drip = up & t_ac[kk, jj] & (np.abs(uu - t_acx[kk, jj] - 0.42) < 0.05) & (vv < 0.36)
+ alb[drip] *= 0.6
+ if shop:
+ sw = r.uniform(4.5, 7.0)
+ si = np.floor(U / sw).astype(np.int32); su = U - si * sw
+ ns = int(wm / sw) + 2
+ ci = np.clip(si, 0, ns - 1)
+ mix = np.asarray(mix, np.float64); kind = r.choice(4, ns, p=mix / mix.sum())[ci] # lit shop, shutter, dark, vending
+ spal = np.array([_lin(c) for c in ('#ffc98c', '#cfe6ff', '#ffab5c', '#b8ffd8', '#ffb8d8')], np.float32)
+ inner = spal[r.choice(5, ns, p=[0.35, 0.25, 0.2, 0.1, 0.1])][ci] * r.uniform(0.2, 0.45, ns)[ci][..., None]
+ g = V < gf
+ glass = g & (V > 0.45) & (V < 3.0) & (su > 0.3) & (su < sw - 0.3)
+ lit_s = glass & (kind == 0)
+ ceil = 0.12 + 0.88 * np.clip((V - 0.45) / 2.3, 0, 1) ** 2.2 # lit from the ceiling down
+ fix = (V > 2.78) & (V < 2.84) & (((su - 0.3) % 1.1) < 0.7) # the tube fittings themselves
+ shelf = (((su - 0.3 + 0.3 * _vnoise(si * 7.0, V * 0.0, seed)) % 0.9) < 0.08) & (V < 2.2) # shelf ends, edge-on
+ clutter = smoothstep(0.5, 0.75, _fbm(U / 0.3, V / 0.35, 3, seed + 7)) * (V < 1.9)
+ counter = (V > 0.45) & (V < 1.05) & (_vnoise(U / 1.3, si * 3.0, seed + 5) > 0.55)
+ pu = r.uniform(0.8, max(1.0, sw - 0.8), ns)[ci]; ph = r.random(ns)[ci] < 0.5
+ person = ph & (np.hypot((su - pu) / 0.22, (V - 1.2) / 0.62) < 1) | ph & (np.hypot((su - pu) / 0.12, (V - 1.95) / 0.14) < 1)
+ mull = (np.abs(((su - 0.3) % 1.7) - 0.85) > 0.8)
+ side = np.clip(np.minimum(su - 0.3, sw - 0.3 - su) / 1.2, 0.3, 1.0)
+ e_in = inner * (ceil * side * np.where(shelf, 0.45, 1.0) * np.where(counter, 0.35, 1.0) * (1 - 0.6 * clutter))[..., None]
+ e_in = np.where(fix[..., None], inner * 2.2, e_in)
+ e_in = np.where((person | mull)[..., None], e_in * 0.08, e_in)
+ emi[lit_s] = e_in[lit_s]; alb[lit_s] = 0.015
+ shut = glass & (kind == 1)
+ rib = 0.65 + 0.35 * (np.sin(V * 2 * np.pi / 0.085) > 0)
+ alb[shut] = (_lin('#5a6068') * 0.4 * rib[..., None])[shut]; emi[shut] = 0
+ gap = r.random(ns)[ci] < 0.4
+ leak = shut & gap & (V < 0.62) # light leaking under a half-shut shutter
+ emi[leak] = (spal[0] * 0.22 * np.clip((0.62 - V) / 0.17, 0, 1)[..., None])[leak]
+ dark = glass & (kind == 2)
+ alb[dark] = 0.01; emi[dark] = 0
+ vend = g & (kind == 3) # vending machines against a shutter
+ alb[vend & (V < 3.0)] = (_lin('#5a6068') * 0.4 * rib[..., None])[vend & (V < 3.0)]; emi[vend] = 0
+ mu = su - 0.6; mi = np.floor(mu / 1.0); mx = mu - mi
+ box = vend & (mi >= 0) & (mi < 3) & (mx > 0.04) & (mx < 0.96) & (V < 1.85)
+ face = box & (mx > 0.1) & (mx < 0.9) & (V > 0.95) & (V < 1.75)
+ row = np.floor((V - 1.0) / 0.25); rx = (mx - 0.1) / 0.8 * 6
+ can = face & ((rx % 1) > 0.2) & ((rx % 1) < 0.8) & (((V - 1.0) % 0.25) > 0.07) & (((V - 1.0) % 0.25) < 0.19)
+ ccol = np.array([_lin(c) for c in ('#ff4b5c', '#38c6ff', '#ffd23f', '#7dff9a', '#ffffff')], np.float32)
+ cidx = (np.abs(np.sin(np.floor(rx) * 7.1 + row * 3.7 + mi * 1.3)) * 5).astype(int) % 5
+ emi[box] = _lin('#1b2230') * 0.3
+ emi[face] = _lin('#eaf4ff') * 0.75
+ emi[can] = (ccol[cidx] * 0.9)[can]
+ emi[box & (V > 1.76) & (V < 1.83)] = _lin(CYAN) * 0.6
+ alb[box] = 0.05
+ alb[g & ~glass & (V < 3.2)] *= 0.55
+ if signs: # a fascia sign over each shop
+ words = ['薬局', '食堂', '理髪', '酒場', '珈琲', '精肉', '鮮魚', '古書', '時計', '骨董', '写真', '洋服',
+ '餃子', '茶房', '花屋', '雑貨', 'DELI', 'REPAIR', 'PHOTO', 'LAUNDRY', 'NOODLE', 'PARTS', '24H']
+ fcs = [MAGENTA, CYAN, AMBER, '#f4efe6', '#f4efe6']
+ for i in range(ns):
+ if r.random() > 0.75: continue
+ u0, u1 = i * sw + 0.5, (i + 1) * sw - 0.5
+ c0, c1 = int(u0 * ppu), min(tw, int(u1 * ppu))
+ r0, r1 = int((hm - 4.05) * ppv), int((hm - 3.35) * ppv)
+ if c1 - c0 < 3 or r1 - r0 < 2 or c0 >= tw: continue
+ fc = _lin(fcs[r.integers(len(fcs))]) * r.uniform(0.3, 0.55)
+ ink = r.random() < 0.6 # dark letters on a lit face, or lit letters on dark
+ wd = words[r.integers(len(words))]
+ ht = 64; wt = max(8, int(ht * (u1 - u0) / 0.7))
+ im = Image.new('L', (wt, ht), 0)
+ fnt = sign_font('bold', ht * 0.66)
+ ImageDraw.Draw(im).text((wt * 0.5, ht * 0.52), wd, font=fnt, fill=255, anchor='mm')
+ if flip: im = im.transpose(Image.FLIP_LEFT_RIGHT)
+ m = np.asarray(im.resize((c1 - c0, r1 - r0), Image.BOX), np.float32) / 255
+ if ink: e = fc[None, None] * (1 - 0.9 * m)[..., None]
+ else: e = fc[None, None] * (0.06 + 1.6 * m)[..., None]
+ emi[r0:r1, c0:c1] = e; alb[r0:r1, c0:c1] = 0.04
+ return alb, emi
+
+ def _levels(self, tex, lo, hi):
+ """anisotropic pre-filtering: level k blurs along u by 0.5*2^k texels (v gets the square root of that)"""
+ out = {}
+ for k in range(lo, hi + 1):
+ if k == 0: out[k] = tex
+ else: out[k] = _blur_axis(_blur_axis(tex, 0.5 * 2 ** k, 1), 0.5 * 2 ** (k / 2), 0)
+ return out
+
+ def _draw_side(self, side, wall, z0, z1, Y0, Y1, alb_t, emi_t, ppu, ppv, u0):
+ """warp a facade texture (u = Z metres from u0, v from the top Y1) onto the plane X = side*wall"""
+ Xp = side * wall
+ xa, _ = self.project(Xp, 0, z0); xb, _ = self.project(Xp, 0, z1)
+ ya = min(self.project(0, Y1, z0)[1], self.project(0, Y1, z1)[1])
+ yb = max(self.project(0, Y0, z0)[1], self.project(0, Y0, z1)[1])
+ sl = self._box(min(xa, xb) - 1, ya - 1, max(xa, xb) + 1, yb + 1)
+ if sl is None: return
+ X = self.XX[sl]; Y = self.YY[sl]
+ dx = X - self.vx
+ Z = np.where(dx * side > 0.5, self.f * Xp / np.where(np.abs(dx) < 0.5, 0.5, dx), 1e9)
+ ax = np.clip(np.minimum(X - min(xa, xb), max(xa, xb) - X) + 0.5, 0, 1)
+ Zc = np.clip(Z, z0, z1)
+ yt = self.vy + self.f * (self.eye - Y1) / Zc; ybt = self.vy + self.f * (self.eye - Y0) / Zc
+ ay = np.clip(np.minimum(Y - yt, ybt - Y) + 0.5, 0, 1)
+ a = ax * ay * (Z <= z1 + 0.5) * (Z >= z0 - 0.5)
+ idx = np.nonzero(a > 0)
+ if len(idx[0]) == 0: return
+ Zi = Zc[idx]; Yw = self.eye - (Y[idx] - self.vy) * Zi / self.f
+ uu = (Zi - u0) * ppu - 0.5; vv = (Y1 - Yw) * ppv - 0.5
+ fu = ppu * Zi * Zi / (self.f * wall)
+ L = np.clip(np.log2(np.maximum(fu, 1.0)), 0, 6)
+ k0 = np.floor(L).astype(int); t = (L - k0).astype(np.float32)
+ tex = np.concatenate([alb_t, emi_t], -1)
+ lv = self._levels(tex, int(k0.min()), int(min(6, k0.max() + 1)))
+ acc = np.zeros((len(Zi), 6), np.float32)
+ for k, tk in lv.items():
+ w = np.where(k0 == k, 1 - t, 0) + np.where(k0 + 1 == k, t, 0)
+ sel = w > 0
+ if sel.any(): acc[sel] += w[sel, None] * _sample(tk, uu[sel], vv[sel])
+ A = np.zeros(a.shape + (3,), np.float32); E = np.zeros_like(A)
+ A[idx] = acc[:, :3]; E[idx] = acc[:, 3:]
+ Zf = np.where(a > 0, Zc, np.inf).astype(np.float32)
+ self._put(sl, a, A, E, Zf, self.ground_row(Zf))
+
+ def _draw_front(self, side, wall, z, w0, w1, Y0, Y1, alb_t, emi_t, ppm):
+ """warp a texture onto the plane Z = z; u runs outward from |X| = w0 to w1 on the given side"""
+ xa, _ = self.project(side * w0, 0, z); xb, _ = self.project(side * w1, 0, z)
+ _, ya = self.project(0, Y1, z); _, yb = self.project(0, Y0, z)
+ sl = self._box(min(xa, xb) - 1, ya - 1, max(xa, xb) + 1, yb + 1)
+ if sl is None: return
+ X = self.XX[sl]; Y = self.YY[sl]
+ ax = np.clip(np.minimum(X - min(xa, xb), max(xa, xb) - X) + 0.5, 0, 1)
+ ay = np.clip(np.minimum(Y - ya, yb - Y) + 0.5, 0, 1)
+ a = ax * ay
+ Xw = (X - self.vx) * z / self.f; Yw = self.eye - (Y - self.vy) * z / self.f
+ uu = (side * Xw - w0) * ppm - 0.5; vv = (Y1 - Yw) * ppm - 0.5
+ A = _sample(alb_t, uu, vv); E = _sample(emi_t, uu, vv)
+ self._put(sl, a, A, E, z, self.ground_row(z))
+
+ def building(self, side, z0, z1, height, wall=None, depth=40.0, colour='#2a2f3d', floor=3.3, bay=2.6, lit=0.3,
+ shop=True, roof=True, shops=(0.45, 0.35, 0.2, 0.0), seed=None):
+ """a block on one side of the street (side -1 left, +1 right) from depth z0 to z1, `height` metres tall,
+ its street wall at |X| = wall: front face (Z = z0) plus the long street facade, textured and lit.
+ shops = probabilities of (lit shop, roller shutter, dark shop, vending machines) along the ground floor"""
+ seed = self._seed() if seed is None else seed
+ wall = self.wall if wall is None else wall
+ zv = max(z0, self.near_z(side, wall) * 0.98)
+ if zv >= z1: return
+ top = lambda z: min(height, self.eye + (self.vy + 4) * z / self.f + 1.0)
+ # front face (only if it starts on screen)
+ if z0 >= self.near_z(side, wall):
+ Yt = top(z0); ppm = self.f / z0
+ wm = min(depth, max(1.0, (self.vx if side < 0 else self.W - self.vx) * z0 / self.f - wall + 1))
+ A, E = self._facade(wm, Yt, ppm, ppm, colour, floor, bay, lit, shop, seed + 3, flip=side < 0, mix=shops)
+ A *= 0.8
+ self._draw_front(side, wall, z0, wall, wall + wm, 0, Yt, A, E, ppm)
+ # street facade
+ Yt = top(z1)
+ ppv = min(64.0, self.f / zv); ppu = min(64.0, max(6.0, self.f * wall / zv ** 2))
+ A, E = self._facade(z1 - zv, Yt, ppu, ppv, colour, floor, bay, lit, shop, seed, flip=side > 0, mix=shops)
+ self._draw_side(side, wall, zv, z1, 0, Yt, A, E, ppu, ppv, zv)
+ if roof and height < top(z1) - 0.5:
+ self._roof(side, wall, z0, z1, height, depth, seed + 5)
+
+ def _roof(self, side, wall, z0, z1, height, depth, seed):
+ """rooftop clutter seen against the sky: water tanks, masts with red beacons, a billboard frame"""
+ r = np.random.default_rng(seed)
+ for _ in range(r.integers(2, 5)):
+ Z = r.uniform(z0 + 2, z1 - 2); X = side * (wall + r.uniform(0.5, 8))
+ if r.random() < 0.5:
+ w, h = r.uniform(1.5, 3.0), r.uniform(1.8, 3.2)
+ pts = [self.project(X - w / 2, height, Z), self.project(X + w / 2, height, Z),
+ self.project(X + w / 2, height + h, Z), self.project(X - w / 2, height + h, Z)]
+ sl, m = self._poly(pts)
+ if sl is not None: self._put(sl, m, _lin('#20242e') * 0.6, 0.0, Z, self.ground_row(Z))
+ else:
+ h = r.uniform(4, 11)
+ x0, y0 = self.project(X, height, Z); _, y1 = self.project(X, height + h, Z)
+ wpx = max(1.0, 0.18 * self.f / Z)
+ sl = self._box(x0 - wpx - 2, y1 - 2, x0 + wpx + 2, y0 + 2)
+ if sl is None: continue
+ c, _ = self._lines(sl, [([(x0, y0), (x0, y1)], wpx, 1.0)])
+ self._put(sl, c, _lin('#1a1d26') * 0.6, 0.0, Z, self.ground_row(Z))
+ if r.random() < 0.7: self.light(x0, y1, max(0.8, 0.12 * self.f / Z), RED, Z, 2.0)
+
+ # ------------------------------------------------------------ neon
+ def _tube(self, sl, skel, r, colour, depth, base=None, level=1.0, state='on', seed=None):
+ """a glass tube along a thin skeleton mask (cropped to sl, with a margin of ~4r):
+ light ~ chord length through the gas, near-white over-exposed core, halo in the air"""
+ r = max(0.9, float(r)); s = r / 1.4
+ g = blur(skel, s)
+ on = skel > 0.5
+ pk = np.percentile(g[on], 75) if on.sum() > 6 else g.max()
+ n = np.clip(g / (pk + 1e-6), 1e-4, 2.0)
+ chord = np.sqrt(np.clip(1 + 2 * (s / r) ** 2 * np.log(n), 0, 1)).astype(np.float32)
+ body = smoothstep(0.0, 0.3, chord)
+ col = _lin(colour)
+ if state == 'dead': # unlit glass: pale, one glint
+ glass = col * 0.12 + 0.07
+ a = body * (depth < self.dep[sl])
+ self.alb[sl] = self.alb[sl] * (1 - a[..., None]) + glass * a[..., None]
+ self.emi[sl] += (chord ** 10 * 0.05)[..., None] * a[..., None]
+ return
+ lv = np.full(skel.shape, level, np.float32)
+ if state == 'flicker': # caught mid-dip, patchy
+ sd = self._seed() if seed is None else seed
+ h, w = skel.shape
+ nz = noise2d(h, w, max(3.0, 5 * r), 2, sd)
+ lv = level * (0.08 + 0.42 * smoothstep(0.4, 0.7, nz))
+ core = chord ** 5
+ white = col * 0.3 + 0.7
+ E = (col * (2.6 * chord)[..., None] + white * (5.5 * core)[..., None]) * lv[..., None]
+ a = body * (depth < self.dep[sl])
+ self.emi[sl] = self.emi[sl] * (1 - a[..., None]) + E * a[..., None]
+ self.alb[sl] = self.alb[sl] * (1 - a[..., None]) + 0.2 * a[..., None]
+ D = self.dep[sl]; D[a > 0.5] = depth
+ if base is not None:
+ B = self.base[sl]; B[a > 0.5] = base
+ src = chord * lv
+ halo = blur(src, 1.8 * r) * 0.9 + blur(src, 5.0 * r) * 0.45
+ self._glow(sl, col * halo[..., None], depth + 0.02)
+
+ def neon_path(self, pts, colour, z, r=None, level=1.0, state='on', closed=False, base=None, seed=None):
+ """a tube bent along screen points `pts` (at depth z); r = tube radius in px"""
+ P = np.asarray(pts, np.float32)
+ if closed: P = np.vstack([P, P[:1]])
+ r = r if r is not None else max(1.0, 0.016 * self.f / z)
+ m = 5 * r + 3
+ sl = self._box(P[:, 0].min() - m, P[:, 1].min() - m, P[:, 0].max() + m, P[:, 1].max() + m)
+ if sl is None: return
+ skel, _ = self._lines(sl, [(P.tolist(), 1.4, 1.0)], ss=3)
+ self._tube(sl, skel, r, colour, z - 0.03, self.ground_row(z) if base is None else base, level, state, seed)
+
+ def neon_text(self, s, x, y, size, colour, z, vertical=False, spacing=0.0, dead=(), flicker=(), level=1.0,
+ r=None, base=None, kind='neon'):
+ """neon lettering centred on screen point (x, y): one tube per character (so single characters can be
+ `dead` or `flicker` by index); vertical stacks the characters top to bottom"""
+ r = r if r is not None else max(0.9, size * 0.018)
+ chars = list(s)
+ if vertical:
+ pitch = size * (1.0 + spacing)
+ pos = [(x, y + (i - (len(chars) - 1) / 2) * pitch) for i in range(len(chars))]
+ else:
+ f = sign_font(kind, size)
+ adv = [f.getlength(c) + spacing * size for c in chars]
+ tot = sum(adv) - spacing * size
+ cx = x - tot / 2; pos = []
+ for c, a in zip(chars, adv):
+ pos.append((cx + f.getlength(c) / 2, y)); cx += a
+ for i, (c, (px, py)) in enumerate(zip(chars, pos)):
+ if c == ' ': continue
+ g = _glyph(c, size, kind)
+ n = g.shape[0]
+ m = int(5 * r + 3)
+ sl = self._box(px - n / 2 - m, py - n / 2 - m, px + n / 2 + m, py + n / 2 + m)
+ if sl is None: continue
+ y0, x0 = sl[0].start, sl[1].start
+ hh, ww = sl[0].stop - y0, sl[1].stop - x0
+ canvas = np.zeros((hh, ww), np.float32)
+ gy, gx = int(round(py - n / 2)) - y0, int(round(px - n / 2)) - x0
+ ys0, xs0 = max(0, gy), max(0, gx)
+ ys1, xs1 = min(hh, gy + n), min(ww, gx + n)
+ if ys1 <= ys0 or xs1 <= xs0: continue
+ canvas[ys0:ys1, xs0:xs1] = g[ys0 - gy:ys1 - gy, xs0 - gx:xs1 - gx]
+ state = 'dead' if i in dead else 'flicker' if i in flicker else 'on'
+ self._tube(sl, canvas, r, colour, z - 0.03, self.ground_row(z) if base is None else base, level, state)
+
+ def sign(self, z, X0, X1, Y0, Y1, text='', colour=MAGENTA, kind='neon', vertical=True, face='#150f1a',
+ border=None, latin=None, latin_colour=None, dead=(), flicker=(), level=1.0, char=0.74, box=0.35,
+ text_colour=None, frame='#2a2c33'):
+ """a sign board facing the camera at depth z (X0..X1, Y0..Y1 metres).
+ kind='neon': dark backing, border tube (`border` colour, None = same as text) and tube lettering;
+ kind='box': a backlit lightbox — the acrylic glows `colour`, lettering in `text_colour` (dark = paint).
+ `box` metres of depth show as a side panel toward the street centre."""
+ s = self.f / z
+ xa, ya = self.project(X0, Y1, z); xb, yb = self.project(X1, Y0, z)
+ x0, x1 = min(xa, xb), max(xa, xb)
+ base = self.ground_row(z)
+ # side of the box, visible toward the vanishing point
+ Xi = X1 if abs(X1) < abs(X0) else X0
+ if box > 0:
+ p = [self.project(Xi, Y1, z), self.project(Xi, Y1, z + box), self.project(Xi, Y0, z + box), self.project(Xi, Y0, z)]
+ sl, m = self._poly(p)
+ if sl is not None: self._put(sl, m, _lin(frame) * 0.5, 0.0, z + box / 2, base)
+ # frame and face
+ fr = max(1.0, 0.07 * s)
+ sl = self._box(x0, ya, x1, yb)
+ if sl is None: return
+ X = self.XX[sl]; Y = self.YY[sl]
+ a = np.clip(np.minimum(X - x0, x1 - X) + 0.5, 0, 1) * np.clip(np.minimum(Y - ya, yb - Y) + 0.5, 0, 1)
+ inner = np.clip(np.minimum(np.minimum(X - x0, x1 - X), np.minimum(Y - ya, yb - Y)) - fr + 0.5, 0, 1)
+ if kind == 'box':
+ u = (X - x0) / max(1, x1 - x0); v = (Y - ya) / max(1, yb - ya)
+ bands = 0.78 + 0.22 * (np.cos((u if vertical else v) * 2 * np.pi * 2) * 0.5 + 0.5) # tubes behind the acrylic
+ edge = smoothstep(0.0, 0.12, np.minimum(np.minimum(u, 1 - u), np.minimum(v, 1 - v)))
+ E = _lin(colour) * (level * 1.2 * bands * (0.55 + 0.45 * edge) * inner)[..., None]
+ self._put(sl, a, _lin(frame) * (1 - inner[..., None]) * 0.5 + 0.3 * inner[..., None], E, z, base)
+ else:
+ self._put(sl, a, _lin(frame) * 0.5 * (1 - inner[..., None]) + _lin(face) * inner[..., None], 0.0, z, base)
+ ins = 0.14 * s
+ bcol = colour if border is None else border
+ if border is not False:
+ rr = min(0.22 * s, (x1 - x0) * 0.2)
+ P = self._rrect_path(x0 + ins, ya + ins, x1 - ins, yb - ins, rr)
+ self.neon_path(P, bcol, z, r=max(0.9, 0.022 * s), level=level * 0.85, base=base)
+ if not text: return
+ w, h = x1 - x0, yb - ya
+ pad = min(0.3 * s, 0.14 * w)
+ lat_h = 0
+ if latin:
+ lat_h = min(0.2 * w, 0.42 * s)
+ fl = sign_font('thin' if kind == 'box' else 'neon', lat_h)
+ tw = sum(fl.getlength(ch) for ch in latin) + 0.1 * lat_h * (len(latin) - 1)
+ if tw > 0.8 * w: lat_h *= 0.8 * w / tw
+ n = len(text)
+ if vertical:
+ size = min((w - 2 * pad) * char, (h - 2 * pad - lat_h * 1.6) / n * 0.86)
+ cx, cy = (x0 + x1) / 2, ya + pad + (h - 2 * pad - lat_h * 1.6) / 2
+ else:
+ size = min((h - 2 * pad - lat_h * 1.6) * char, (w - 2 * pad) / max(1, n) * 0.95)
+ cx, cy = (x0 + x1) / 2, ya + pad + (h - 2 * pad - lat_h * 1.6) / 2
+ if kind == 'box':
+ self._painted_text(text, cx, cy, size, text_colour or '#1a0d10', z, vertical, level=level)
+ else:
+ self.neon_text(text, cx, cy, size, colour, z, vertical, 0.12 if vertical else 0.06, dead, flicker, level, base=base)
+ if latin:
+ ly = yb - pad - lat_h * 0.55
+ if kind == 'box':
+ self._painted_text(latin, cx, ly, lat_h, text_colour or '#1a0d10', z, False, level=level, kind='thin')
+ else:
+ self.neon_text(latin, cx, ly, lat_h, latin_colour or colour, z, False, 0.1, level=level, base=base,
+ r=max(0.8, lat_h * 0.03))
+
+ def blade_sign(self, side, z, Y0, Y1, text='', colour=MAGENTA, reach=2.4, gap=0.3, wall=None, **kw):
+ """a vertical sign sticking out over the street from the wall on `side`, facing the camera, on two
+ steel brackets"""
+ wall = self.wall if wall is None else wall
+ Xo = side * (wall - gap); Xi = side * (wall - gap - reach)
+ s = self.f / z
+ for Yb in (Y1 - 0.25, Y0 + 0.25): # brackets back to the wall
+ xw, yw = self.project(side * wall, Yb, z); xs, ys = self.project(Xo, Yb, z)
+ sl = self._box(min(xw, xs) - 3, yw - 3, max(xw, xs) + 3, yw + 3 + 0.08 * s)
+ if sl is not None:
+ c, _ = self._lines(sl, [([(xw, yw), (xs, ys)], max(1.0, 0.06 * s), 1.0)])
+ self._put(sl, c, _lin('#2b2d33') * 0.5, 0.0, z + 0.05, self.ground_row(z))
+ self.sign(z, Xo, Xi, Y0, Y1, text, colour, **kw)
+
+ def _rrect_path(self, x0, y0, x1, y1, r, n=6):
+ pts = []
+ for cx, cy, a0 in ((x1 - r, y0 + r, -90), (x1 - r, y1 - r, 0), (x0 + r, y1 - r, 90), (x0 + r, y0 + r, 180)):
+ for t in np.linspace(a0, a0 + 90, n):
+ pts.append((cx + r * np.cos(np.radians(t)), cy + r * np.sin(np.radians(t))))
+ pts.append(pts[0])
+ return pts
+
+ def _painted_text(self, s, x, y, size, colour, z, vertical, level=1.0, kind='bold'):
+ """lettering painted on a lightbox face: dark paint blocks the light, a colour glows as that colour"""
+ f = sign_font(kind, size)
+ n = int(size * 1.5) + 4
+ chars = list(s) if vertical else [s]
+ for i, c in enumerate(chars):
+ if vertical:
+ py = y + (i - (len(chars) - 1) / 2) * size * 1.08; px = x
+ wbox = n
+ else:
+ py, px = y, x
+ wbox = int(f.getlength(c)) + n
+ sl2 = self._box(px - wbox / 2, py - n / 2, px + wbox / 2, py + n / 2)
+ if sl2 is None: continue
+ y0, x0 = sl2[0].start, sl2[1].start
+ im = Image.new('L', (sl2[1].stop - x0, sl2[0].stop - y0), 0)
+ ImageDraw.Draw(im).text((px - x0, py - y0), c, font=f, fill=255, anchor='mm')
+ m = np.asarray(im, np.float32) / 255 * (z - 0.05 < self.dep[sl2] + 0.2)
+ col = _lin(colour)
+ lum = float(col @ LUMA)
+ if lum < 0.02: # opaque paint
+ self.emi[sl2] *= 1 - m[..., None] * 0.92
+ else:
+ self.emi[sl2] = self.emi[sl2] * (1 - m[..., None]) + col * (2.2 * level) * m[..., None]
+
+ # ------------------------------------------------------------ hologram
+ def hologram(self, z, X0, X1, Y0, Y1, title='海月', sub='SEA MOON', colour=CYAN, accent=MAGENTA, level=1.0,
+ scan=0.09, jelly=(0.4, 0.28), sub_y=0.9, seed=None):
+ """a translucent projected ad panel at depth z (X0..X1, Y0..Y1 metres), light only: a moon jellyfish,
+ a vertical mincho title on the right, a spaced Latin sub-line; scanlines at `scan` metres pitch on the
+ panel, a slow brightness band, torn slices, colour fringes, soft edges and a faint projection edge.
+ jelly = (x, y) of the bell as fractions of the panel; sub_y = baseline of the sub-line (fraction).
+ It is additive light: walls behind it stay visible, and it lights the fog and the walls around it."""
+ r = np.random.default_rng(self._seed() if seed is None else seed)
+ xa, ya = self.project(X0, Y1, z); xb, yb = self.project(X1, Y0, z)
+ sl = self._box(xa, ya, xb, yb)
+ if sl is None: return
+ y0, x0 = sl[0].start, sl[1].start
+ h, w = sl[0].stop - y0, sl[1].stop - x0
+ A = np.zeros((h, w), np.float32); B = np.zeros((h, w), np.float32)
+ ox, oy = xa - x0, ya - y0 # panel origin inside the box
+ pw, ph = xb - xa, yb - ya
+ jx, jy, R = ox + pw * jelly[0], oy + ph * jelly[1], pw * 0.3
+ self._jellyfish(A, B, jx, jy, R, r)
+ # title: big vertical mincho on the right, filled light; sub-line in spaced Latin at the bottom
+ tsize = pw * 0.2
+ f = sign_font('mincho', tsize)
+ im = Image.new('L', (w, h), 0); d = ImageDraw.Draw(im)
+ for i, c in enumerate(title):
+ d.text((ox + pw * 0.83, oy + ph * 0.2 + i * tsize * 1.12), c, font=f, fill=255, anchor='mm')
+ T = np.asarray(im, np.float32) / 255
+ A += blur(T, 0.6) * 1.3
+ im = Image.new('L', (w, h), 0); d = ImageDraw.Draw(im)
+ fs = sign_font('light', max(9, pw * 0.062))
+ x = ox + pw * 0.08
+ for c in sub:
+ d.text((x, oy + ph * sub_y), c, font=fs, fill=255, anchor='ls'); x += fs.getlength(c) + pw * 0.022
+ d.line([(ox + pw * 0.08, oy + ph * (sub_y + 0.02)), (ox + pw * 0.38, oy + ph * (sub_y + 0.02))], fill=160, width=1)
+ B += np.asarray(im, np.float32) / 255 * 1.2
+ # the panel itself: faint sheet with soft edges
+ X = self.XX[sl] - x0; Y = self.YY[sl] - y0
+ u = (X - ox) / pw; v = (Y - oy) / ph
+ edge = smoothstep(0.0, 0.06, np.minimum(np.minimum(u, 1 - u), np.minimum(v, 1 - v)))
+ rim_ = np.clip(1 - np.abs(np.minimum(np.minimum(u, 1 - u) * pw, np.minimum(v, 1 - v) * ph) - 1.5) / 1.2, 0, 1)
+ A = A * edge + 0.014 * edge + 0.16 * rim_ * (0.6 + 0.4 * np.cos(v * 40))
+ # scanlines at a fixed pitch on the panel, a slow bright band, torn slices
+ p = max(3.2, scan * self.f / z)
+ sc = 0.5 + 0.5 * (np.cos(Y * 2 * np.pi / p) * 0.5 + 0.5)
+ band = 1 + 0.5 * np.exp(-((v - r.uniform(0.55, 0.75)) / 0.05) ** 2)
+ flick = 1 + 0.12 * (fbm1d(h, 30, 3, int(r.integers(1 << 30)))[:, None])
+ rgbA = A * sc * band * flick; rgbB = B * sc * band * flick
+ img = rgbA[..., None] * _lin(colour) * 2.0 + rgbB[..., None] * _lin(accent) * 2.0
+ for _ in range(3): # torn slices (kept off the lettering)
+ yy = int(oy + r.uniform(0.4, 0.6) * ph); hh = int(r.uniform(2, 7))
+ img[yy:yy + hh] = np.roll(img[yy:yy + hh], int(r.choice([-1, 1]) * r.uniform(5, 16)), axis=1)
+ img[..., 0] = np.roll(img[..., 0], 2, axis=1); img[..., 2] = np.roll(img[..., 2], -2, axis=1) # fringes
+ dust = (r.random((h, w)) < 0.0025) * edge * r.uniform(0.5, 2.0, (h, w))
+ img += dust[..., None] * _lin(colour)
+ img = img * level * 2.4
+ self._glow(sl, img + blur(img.mean(-1), 3)[..., None] * _lin(colour) * 0.4, z, light=0.6)
+
+ def _jellyfish(self, A, B, cx, cy, R, r):
+ """a moon jellyfish (海月) drawn in light, seen from the side and a little below: a translucent dome
+ built as a 3-D surface (canals run over it, the front of the margin is bright and the back faint),
+ four soft gonad rings glowing through it in the accent colour, a fringe of fine marginal tentacles and
+ four frilly oral-arm ribbons trailing beneath"""
+ h, w = A.shape
+ dh, mh = R * 0.58, R * 0.13 # dome height, margin tilt
+ P3 = lambda th, ph: (cx + R * np.sin(th) * np.cos(ph), cy - dh * np.cos(th) + mh * np.sin(th) * np.sin(ph))
+ la = [] # (points, width, value, fade-to-tip)
+ la.append(([P3(th, 0.0) for th in np.linspace(np.pi / 2, 0, 40)] + [P3(th, np.pi) for th in np.linspace(0, np.pi / 2, 40)],
+ max(2.0, R * 0.026), 1.1, False)) # silhouette of the dome
+ la.append(([P3(np.pi / 2, ph) for ph in np.linspace(0, np.pi, 70)], max(2.0, R * 0.024), 1.0, False)) # margin, front
+ la.append(([P3(np.pi / 2, ph) for ph in np.linspace(np.pi, 2 * np.pi, 70)], max(1.2, R * 0.012), 0.35, False)) # margin, back
+ for k in range(16): # canals over the dome
+ ph = 2 * np.pi * (k + 0.5) / 16
+ v = 0.45 if np.sin(ph) > 0 else 0.18
+ la.append(([P3(th, ph) for th in np.linspace(0.08, np.pi / 2, 16)], max(1.0, R * 0.01), v, False))
+ yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
+ gon = np.zeros((h, w), np.float32)
+ yg = cy - dh * 0.32 # gonads lie on a plane inside the bell:
+ for k in range(4): # seen nearly edge-on they flatten into a
+ ph = np.pi / 4 + k * np.pi / 2 # soft cluster (never a pair of 'eyes')
+ gx, gy = cx + R * 0.24 * np.cos(ph), yg + mh * 1.6 * 0.24 * np.sin(ph)
+ d = np.hypot((xx - gx) / (R * 0.16), (yy - gy) / (R * 0.16 * mh * 1.6 / R + R * 0.03))
+ gon += np.exp(-((d - 0.75) / 0.35) ** 2) * (0.8 if np.sin(ph) > 0 else 0.5)
+ B += gon
+ for k in range(64): # marginal tentacles
+ ph = 2 * np.pi * k / 64
+ x0, y0 = P3(np.pi / 2, ph)
+ L = R * r.uniform(0.4, 0.95); sw = r.uniform(0, 6)
+ v = 0.75 if np.sin(ph) > 0 else 0.35
+ la.append(([(x0 + R * 0.05 * np.sin(q * 5 + sw) + R * 0.1 * q * q, y0 + q * L) for q in np.linspace(0, 1, 14)],
+ max(1.0, R * 0.011), v, True))
+ arms = Image.new('F', (w * 2, h * 2), 0.0); da = ImageDraw.Draw(arms)
+ for k in range(4): # oral arms: frilly ribbons
+ x0 = cx + (k - 1.5) * R * 0.12
+ L = R * r.uniform(1.4, 1.9); sw = r.uniform(0, 6)
+ q = np.linspace(0, 1, 70)
+ mid = x0 + R * 0.12 * np.sin(q * 5 + sw) * q + R * 0.08 * q * q
+ half = R * (0.02 + 0.07 * np.sin(np.pi * np.clip(q * 1.1, 0, 1))) * (1 + 0.35 * np.sin(q * 38 + k * 2))
+ ys = cy + mh + q * L
+ left = list(zip(mid - half, ys)); right = list(zip(mid + half, ys))
+ da.polygon([(x * 2, y * 2) for x, y in left + right[::-1]], fill=0.22)
+ for edge in (left, right):
+ la.append((edge, max(1.0, R * 0.012), 0.85, True))
+ A += np.asarray(arms.resize((w, h), Image.BOX))
+ im = Image.new('F', (w * 2, h * 2), 0.0); d = ImageDraw.Draw(im)
+ for pts, wd, v, tip in la:
+ q = [(x * 2, y * 2) for x, y in pts]
+ n = len(q)
+ for i in range(n - 1):
+ fade = v * (1 - i / n) ** 0.9 if tip else v
+ d.line([q[i], q[i + 1]], fill=float(fade), width=max(1, int(round(wd * 2))))
+ A += np.asarray(im.resize((w, h), Image.BOX))
+ dome = (((xx - cx) / R) ** 2 + ((yy - cy) / dh) ** 2 < 1) & (yy < cy + mh * 0.5)
+ A += dome * (0.05 + 0.08 * np.clip((cy - yy) / dh, 0, 1))
+ A += blur(A, R * 0.04) * 0.45
+ B += blur(B, R * 0.05) * 0.5
+
+ # ------------------------------------------------------------ bridges, cables, trails
+ def walkway(self, z, Y, thick=2.4, deep=3.5, X0=None, X1=None, colour='#1b1e28', windows=AMBER, lamps=AMBER, seed=None):
+ """a covered footbridge across the street at depth z, underside Y metres up: facing wall with a strip of
+ lit windows, the underside (seen from below) with a row of lamps"""
+ r = np.random.default_rng(self._seed() if seed is None else seed)
+ X0 = -self.wall - 2 if X0 is None else X0; X1 = self.wall + 2 if X1 is None else X1
+ # underside
+ p = [self.project(X0, Y, z), self.project(X1, Y, z), self.project(X1, Y, z + deep), self.project(X0, Y, z + deep)]
+ sl, m = self._poly(p)
+ if sl is not None:
+ self._put(sl, m, _lin(colour) * 0.7, 0.0, z + deep / 2, self.ground_row(z + deep / 2))
+ zc = z + deep / 2
+ for X in np.arange(X0 + 1.5, X1, 3.0):
+ lx, ly = self.project(X, Y, zc)
+ self.light(lx, ly, max(0.8, 0.07 * self.f / zc), lamps, zc, 1.6, 3.0)
+ # face
+ xa, ya = self.project(X0, Y + thick, z); xb, yb = self.project(X1, Y, z)
+ sl = self._box(xa, ya, xb, yb)
+ if sl is None: return
+ X = self.XX[sl]; Yp = self.YY[sl]
+ a = np.clip(np.minimum(X - xa, xb - X) + 0.5, 0, 1) * np.clip(np.minimum(Yp - ya, yb - Yp) + 0.5, 0, 1)
+ s = self.f / z
+ v = (yb - Yp) / s # metres above the underside
+ Xw = (X - self.vx) / s
+ n = _fbm(Xw / 1.5, v / 0.8, 3, int(r.integers(1 << 30)))
+ alb = _lin(colour)[None, None] * (0.7 + 0.5 * n)[..., None]
+ strip = (v > 0.75) & (v < 1.75)
+ pane = strip & ((Xw % 1.6) > 0.1)
+ wl = r.random(int((X1 - X0) / 1.6) + 4) < 0.7
+ idx = np.clip(((Xw - X0) / 1.6).astype(int), 0, len(wl) - 1)
+ E = np.zeros(a.shape + (3,), np.float32)
+ if windows:
+ E[pane & wl[idx]] = _lin(windows) * 0.6
+ E *= (0.7 + 0.5 * (v - 0.75))[..., None]
+ if windows: alb[strip] = 0.02
+ self._put(sl, a, alb, E, z, self.ground_row(z))
+
+ def cables(self, n=20, z=(12, 90), Y=(6, 16), sag=(0.3, 1.6), width=0.04, colour='#0b0c10', seed=None):
+ """power and data lines strung across the street between the walls, sagging, thin, lit by the neon"""
+ r = np.random.default_rng(self._seed() if seed is None else seed)
+ segs = []
+ for _ in range(n):
+ za = r.uniform(*z); zb = za + r.uniform(-3, 3)
+ ya = r.uniform(*Y); yb = ya + r.uniform(-1.5, 1.5)
+ sg = r.uniform(*sag)
+ t = np.linspace(0, 1, 60)
+ Xs = -self.wall + 2 * self.wall * t; Zs = za + (zb - za) * t
+ Ys = ya + (yb - ya) * t - sg * 4 * t * (1 - t)
+ xs, ys = self.project(Xs, Ys, Zs)
+ segs.append((np.stack([xs, ys], 1), Zs))
+ if r.random() < 0.35: # a second line in the same bundle
+ xs2, ys2 = self.project(Xs, Ys - 0.25, Zs + 0.1)
+ segs.append((np.stack([xs2, ys2], 1), Zs + 0.1))
+ for P, Zs in segs:
+ zm = float(Zs.mean())
+ sl = self._box(P[:, 0].min() - 4, P[:, 1].min() - 4, P[:, 0].max() + 4, P[:, 1].max() + 4)
+ if sl is None: continue
+ wpx = width * self.f / zm
+ c, _ = self._lines(sl, [(P.tolist(), max(1.1, wpx), 1.0)])
+ self._put(sl, c * min(1.0, 0.4 + wpx), _lin(colour) * 0.8, 0.0, zm, self.ground_row(zm))
+
+ def light_trail(self, pts, colour, level=1.4, width=0.06, pair=1.5, fade=(0.2, 0.3), strobe=0, head=True, seed=None):
+ """a long-exposure trail of a flying car along 3-D control points (metres): two parallel lamps
+ `pair` metres apart, fading in and out; `strobe` adds blinking nav-light dashes"""
+ P = spline(np.asarray(pts, np.float32), 24)
+ N = len(P)
+ t = np.linspace(0, 1, N)
+ env = np.clip(np.minimum(t / fade[0], (1 - t) / fade[1]), 0, 1) ** 1.5
+ xs, ys = self.project(P[:, 0], P[:, 1], P[:, 2])
+ m = 30
+ sl = self._box(xs.min() - m, ys.min() - m, xs.max() + m, ys.max() + m)
+ if sl is None: return
+ y0, x0 = sl[0].start, sl[1].start
+ h, w = sl[0].stop - y0, sl[1].stop - x0
+ lay = Image.new('F', (w * 2, h * 2), 0.0); dep = Image.new('F', (w * 2, h * 2), 1e6)
+ dl, dd = ImageDraw.Draw(lay), ImageDraw.Draw(dep)
+ offs = (-pair / 2, pair / 2) if pair else (0.0,)
+ for o in offs:
+ xo, yo = self.project(P[:, 0] + o, P[:, 1], P[:, 2])
+ for i in range(N - 1):
+ Z = P[i, 2]
+ wd = max(1, int(round(max(0.7, width * self.f / Z) * 2)))
+ v = level * env[i] * self.fog_t(Z)
+ if strobe and (i // max(1, N // strobe)) % 2: v *= 0.35
+ seg = [((xo[i] - x0) * 2, (yo[i] - y0) * 2), ((xo[i + 1] - x0) * 2, (yo[i + 1] - y0) * 2)]
+ dl.line(seg, fill=float(v), width=wd); dd.line(seg, fill=float(Z), width=wd + 2)
+ L = np.asarray(lay.resize((w, h), Image.BOX))
+ Dz = np.asarray(dep.resize((w, h), Image.NEAREST))
+ vis = (Dz < self.dep[sl]).astype(np.float32)
+ L = L * vis
+ col = _lin(colour)
+ g = L * 1.6 + blur(L, 1.5) * 1.0 + blur(L, 6) * 0.5
+ self.add[sl] += g[..., None] * (col * 0.8 + 0.2)
+ self.lsrc[sl] += (blur(L, 4) * 0.8)[..., None] * col
+ if head: # the car itself, at the bright end
+ for o in offs:
+ hx, hy = self.project(P[-1, 0] + o, P[-1, 1], P[-1, 2])
+ self.light(hx, hy, max(0.9, 0.12 * self.f / P[-1, 2]), colour, P[-1, 2], 2.2, 5.0)
+
+ # ------------------------------------------------------------ street
+ def street(self, asphalt='#1d2027', paving='#2c2f36', kerb='#555558', paint='#cfcabb', crossing=(15.0, 4.2),
+ centre=True, puddles=0.5, seed=None):
+ """the wet street, evaluated per pixel in ground coordinates: asphalt with aggregate and tar patches,
+ kerbs, paving joints, worn lane paint, a zebra crossing, puddles (more along the gutters)"""
+ seed = self._seed() if seed is None else seed
+ y0 = int(np.floor(self.vy)) + 1
+ sl = (slice(y0, self.H), slice(0, self.W))
+ Y = self.YY[sl]; X = self.XX[sl]
+ Z = (self.f * self.eye / np.maximum(Y - self.vy, 0.4)).astype(np.float32)
+ Xg = ((X - self.vx) * Z / self.f).astype(np.float32)
+ fx = Z / self.f; fz = Z * Z / (self.f * self.eye)
+ foot = np.maximum(fx, fz)
+ ax = np.abs(Xg); road = self.road
+
+ def stripe(d, half, fw): # antialiased band |d| < half
+ return np.clip((half - np.abs(d)) / np.maximum(fw, 1e-4) + 0.5, 0, 1)
+
+ agg = _fbm(Xg * 7, Z * 7, 3, seed, foot * 7)
+ blot = _fbm(Xg * 0.35, Z * 0.2, 4, seed + 1, foot * 0.35)
+ alb = _lin(asphalt)[None, None] * (0.8 + 0.35 * (agg - 0.5) + 0.5 * (blot - 0.5))[..., None]
+ tar = _fbm(Xg * 0.9, Z * 0.5, 3, seed + 2, foot * 0.9)
+ alb *= (1 - 0.35 * smoothstep(0.62, 0.66, tar))[..., None]
+ walk = np.clip((ax - road - 0.22) / np.maximum(fx, 1e-3) + 0.5, 0, 1)
+ kb = stripe(ax - road - 0.11, 0.11, fx)
+ joints = np.maximum(stripe(((Xg + 0.3) % 0.6) - 0.3, 0.015, fx), stripe(((Z + 0.3) % 0.6) - 0.3, 0.015, fz))
+ joints *= np.clip(0.03 / np.maximum(foot, 1e-3), 0, 1)
+ pv = _lin(paving)[None, None] * (0.8 + 0.4 * (agg - 0.5) + 0.3 * (blot - 0.5))[..., None] * (1 - 0.55 * joints)[..., None]
+ alb = alb * (1 - walk[..., None]) + pv * walk[..., None]
+ alb = alb * (1 - kb[..., None]) + _lin(kerb) * (0.85 + 0.3 * agg)[..., None] * kb[..., None]
+ gut = stripe(ax - road + 0.12, 0.1, fx)
+ alb *= (1 - 0.5 * gut)[..., None]
+ pm = np.zeros_like(Z)
+ if centre:
+ pm = np.maximum(pm, stripe(Xg, 0.07, fx) * stripe((Z % 9.0) - 2.0, 1.6, fz))
+ pm = np.maximum(pm, stripe(ax - (road - 0.45), 0.06, fx))
+ if crossing:
+ zc, zw = crossing
+ inz = stripe(Z - (zc + zw / 2), zw / 2, fz) * (ax < road - 0.2)
+ pm = np.maximum(pm, inz * stripe(((Xg + 0.275) % 1.1) - 0.55, 0.26, fx))
+ wear = smoothstep(0.3, 0.6, _fbm(Xg * 2.5, Z * 2.5, 3, seed + 5, foot * 2.5))
+ pm = pm * (0.35 + 0.65 * wear) * (1 - walk)
+ alb = alb * (1 - pm[..., None] * 0.85) + _lin(paint) * 0.55 * pm[..., None] * 0.85
+ p = _fbm(Xg * 0.28, Z * 0.14, 4, seed + 7, foot * 0.28)
+ edge = np.clip((ax - road + 1.4) / 1.4, 0, 1) * (1 - walk) # water collects in the gutters
+ pud = smoothstep(0.6 - 0.12 * puddles - 0.16 * edge, 0.66 - 0.12 * puddles - 0.16 * edge, p)
+ pud *= 1 - 0.75 * walk
+ damp = 0.45 + 0.55 * _fbm(Xg * 1.3, Z * 0.7, 3, seed + 9, foot * 1.3)
+ glint = _fbm(Xg * 3.2, Z * 1.4, 3, seed + 11, foot * 3.2) # wet film broken by the aggregate
+ damp = damp * (0.2 + 0.8 * smoothstep(0.38, 0.7, glint)) * (1 - 0.5 * pm)
+ a = np.ones_like(Z)
+ self._put(sl, a, alb.astype(np.float32), 0.0, Z, None)
+ vis = (np.abs(self.dep[sl] - Z) < 1e-3).astype(np.float32)
+ self.ground[sl] = np.maximum(self.ground[sl], vis)
+ self.pools[sl] = pud * vis; self.damp[sl] = damp * vis
+ self.street_on = True
+
+ def puddle(self, X, Z, rx, rz, seed=None):
+ """a puddle on the street centred at ground point (X, Z), radii in metres, ragged edge"""
+ sd = self._seed() if seed is None else seed
+ pts = [self.project(X + sx * rx, 0, Z + sz * rz) for sx, sz in ((-1.3, -1.3), (1.3, -1.3), (1.3, 1.3), (-1.3, 1.3))]
+ P = np.asarray(pts)
+ sl = self._box(P[:, 0].min(), P[:, 1].min(), P[:, 0].max(), P[:, 1].max())
+ if sl is None: return
+ Zg = self.f * self.eye / np.maximum(self.YY[sl] - self.vy, 0.4)
+ Xg = (self.XX[sl] - self.vx) * Zg / self.f
+ d = np.hypot((Xg - X) / rx, (Zg - Z) / rz) + 0.35 * (_fbm(Xg * 1.2, Zg * 1.2, 3, sd) - 0.5)
+ fw = np.maximum(Zg / self.f / rx, Zg * Zg / (self.f * self.eye) / rz)
+ m = np.clip((1 - d) / np.maximum(fw * 4.0, 0.08), 0, 1) * self.ground[sl]
+ self.pools[sl] = np.maximum(self.pools[sl], m)
+ self.damp[sl] = np.maximum(self.damp[sl], np.clip((1.35 - d) / 0.35, 0, 1) * 0.9 * self.ground[sl])
+
+ def grate(self, X, Z, w=1.0, d=0.6, glow='#ff9a4a', level=0.25):
+ """a steel grate in the street (dry, dark slats, a faint warm glow from below)"""
+ xs = [self.project(X + sx * w / 2, 0, Z + sz * d / 2) for sx, sz in ((-1, -1), (1, -1), (1, 1), (-1, 1))]
+ sl, m = self._poly(xs)
+ if sl is None: return
+ Y = self.YY[sl]; Xp = self.XX[sl]
+ Zg = self.f * self.eye / np.maximum(Y - self.vy, 0.4)
+ Xg = (Xp - self.vx) * Zg / self.f
+ slat = (np.sin((Xg - X) * 2 * np.pi / 0.07) > 0.1).astype(np.float32)
+ slat = 0.5 + 0.5 * slat * np.clip(0.035 / (Zg / self.f), 0, 1)
+ m = m * (np.abs(self.dep[sl] - Zg) < 0.5)
+ self.alb[sl] = self.alb[sl] * (1 - m[..., None]) + _lin('#15171b') * slat[..., None] * m[..., None]
+ self.emi[sl] += _lin(glow) * (level * (1 - slat) * m)[..., None]
+ self.pools[sl] *= 1 - m
+
+ # ------------------------------------------------------------ figure
+ def figure(self, X, Z, height=1.74, umbrella='clear', coat='#07080c', rim=(MAGENTA, CYAN), stride=0.16):
+ """a lone figure walking away (seen from behind, no face) in a long coat, holding an umbrella; a thin rim
+ of the two sides' neon on the silhouette. umbrella: 'clear' (see-through canopy: bright rim, faint ribs,
+ beads of rain), 'dark', or None"""
+ k = self.f / Z * height / 1.74
+ xf, yf = self.project(X, 0, Z)
+ sl = self._box(xf - 0.8 * k, yf - 2.35 * k, xf + 0.8 * k, yf + 3)
+ if sl is None: return
+ y0, x0 = sl[0].start, sl[1].start
+ h, w = sl[0].stop - y0, sl[1].stop - x0
+ S = 4
+ T = lambda px, py: ((xf + px * k - x0) * S, (yf - py * k - y0) * S)
+ im = Image.new('L', (w * S, h * S), 0); d = ImageDraw.Draw(im)
+ coat_pts = spline([(-0.245, 0.56), (-0.24, 0.95), (-0.225, 1.3), (-0.17, 1.42), (-0.06, 1.465), (0.06, 1.465),
+ (0.17, 1.42), (0.225, 1.3), (0.235, 0.95), (0.26, 0.58)], 8)
+ d.polygon([T(*p) for p in coat_pts] + [T(0.0, 0.6)], fill=255)
+ d.polygon([T(-0.14, 0.0), T(-0.05, 0.0), T(-0.04, 0.7), T(-0.15, 0.7)], fill=255) # legs
+ d.polygon([T(0.045, 0.02 + stride * 0.35), T(0.13, 0.03 + stride * 0.3), T(0.14, 0.7), T(0.03, 0.7)], fill=255)
+ d.polygon([T(-0.05, 1.44), T(0.05, 1.44), T(0.045, 1.55), T(-0.045, 1.55)], fill=255) # neck
+ hx, hy = T(0.0, 1.625); d.ellipse([hx - 0.093 * k * S, hy - 0.113 * k * S, hx + 0.093 * k * S, hy + 0.113 * k * S], fill=255)
+ wa = max(2, int(0.085 * k * S))
+ d.line([T(0.19, 1.38), T(0.27, 1.13), T(0.12, 1.2)], fill=255, width=wa, joint='curve') # raised arm
+ d.line([T(-0.2, 1.36), T(-0.265, 0.92)], fill=255, width=wa, joint='curve') # hanging arm
+ body = np.asarray(im.resize((w, h), Image.BOX), np.float32) / 255
+ shaft = Image.new('L', (w * S, h * S), 0)
+ ImageDraw.Draw(shaft).line([T(0.1, 1.2), T(0.03, 2.13)], fill=255, width=max(1, int(0.022 * k * S)))
+ shaft = np.asarray(shaft.resize((w, h), Image.BOX), np.float32) / 255
+ can = Image.new('L', (w * S, h * S), 0); dc = ImageDraw.Draw(can)
+ cx, apex, rimy, R = 0.03, 2.14, 1.86, 0.56
+ top = [T(cx + R * np.cos(t), rimy + (apex - rimy) * np.sin(t)) for t in np.linspace(0, np.pi, 40)]
+ tips = [cx - R + 2 * R * i / 8 for i in range(9)]
+ scal = []
+ for i in range(8): # the rim sags between rib tips
+ for t in np.linspace(0, 1, 6):
+ scal.append(T(tips[i] + (tips[i + 1] - tips[i]) * t, rimy + 0.035 * np.sin(np.pi * t)))
+ dc.polygon(top + scal, fill=255)
+ canopy = np.asarray(can.resize((w, h), Image.BOX), np.float32) / 255
+ ribs = Image.new('L', (w * S, h * S), 0); dr = ImageDraw.Draw(ribs)
+ for tx in tips[1:-1]:
+ u = (tx - cx) / R
+ dr.line([T(cx + R * u * q, apex - (apex - rimy) * q ** 2) for q in np.linspace(0, 1, 8)], fill=255, width=max(1, S // 2))
+ ribs = np.asarray(ribs.resize((w, h), Image.BOX), np.float32) / 255 * canopy
+ self._put(sl, np.maximum(body, shaft), _lin(coat), 0.0, Z, yf)
+ for c, dx in zip(rim, (-1, 1)): # rim light from each side of the street
+ e = np.clip(body - np.roll(body, -dx * max(1, int(0.025 * k)), axis=1), 0, 1) * body
+ self.emi[sl] += _lin(c) * (e * 0.55)[..., None]
+ if umbrella == 'clear':
+ a = canopy * 0.38
+ self.alb[sl] = self.alb[sl] * (1 - a[..., None]) + 0.22 * a[..., None]
+ edge = np.clip(canopy - blur(canopy, max(1.0, 0.03 * k)), 0, 1) * 2.5
+ self.emi[sl] += (_lin('#dfe8ff') * 0.3 + _lin(rim[0]) * 0.45) * edge[..., None] + _lin('#dfe8ff') * (ribs * 0.18)[..., None]
+ drops = (np.random.default_rng(3).random((h, w)) < 0.025) * canopy
+ self.emi[sl] += drops[..., None] * 0.5
+ D = self.dep[sl]; D[canopy > 0.5] = Z
+ B = self.base[sl]; B[canopy > 0.5] = yf
+ G = self.ground[sl]; G *= 1 - canopy
+ elif umbrella:
+ self._put(sl, canopy, _lin('#0b0c12'), 0.0, Z, yf)
+
+ # ------------------------------------------------------------ atmosphere
+ def steam(self, X, Z, height=5.0, width=0.6, drift=1.4, density=1.0, seed=None):
+ """a plume rising from a grate at ground point (X, Z): widens, thins, curls and bends with the wind"""
+ sd = self._seed() if seed is None else seed
+ s = self.f / Z
+ x0, y0 = self.project(X, 0, Z)
+ hp = height * s
+ m = (width * 2.2 + abs(drift)) * s
+ sl = self._box(x0 - m, y0 - hp, x0 + m, y0 + 0.3 * s)
+ if sl is None: return
+ Yl = self.YY[sl]; Xl = self.XX[sl]
+ v = np.clip((y0 - Yl) / hp, 0, 1)
+ h, w = Yl.shape
+ n1 = noise2d(h, w, max(4.0, 0.9 * s), 4, sd)
+ n2 = noise2d(h, w, max(4.0, 1.4 * s), 3, sd + 1)
+ wob = fbm1d(h, 20, 3, sd + 2)[:, None] * 0.35 * s * v
+ cen = x0 + drift * s * v ** 1.7 + wob + (n2 - 0.5) * 0.6 * s * v
+ wid = width * s * (0.35 + 1.5 * v)
+ q = (Xl - cen) / wid
+ warp = _sample(n1, np.clip(Xl - Xl.min() + (n2 - 0.5) * 0.8 * s, 0, w - 1), np.clip(Yl - Yl.min() + (n1 - 0.5) * 0.8 * s, 0, h - 1))
+ d = np.exp(-q * q) * (0.25 + 1.1 * smoothstep(0.3, 0.8, warp)) * smoothstep(0.0, 0.06, v) * (1 - v) ** 1.4
+ d = d * density * (Z < self.dep[sl] + 1.0)
+ self.steam_d[sl] = np.maximum(self.steam_d[sl], 0) + d.astype(np.float32)
+
+ def mist(self, y=None, h=70, density=0.35, seed=None):
+ """a low drift of mist lying along the street toward the vanishing point"""
+ sd = self._seed() if seed is None else seed
+ y = self.vy + 8 if y is None else y
+ n = np.asarray(Image.fromarray(noise2d(self.H // 2, self.W // 8, 10, 4, sd)).resize((self.W, self.H), Image.BICUBIC))
+ band = np.exp(-((self.YY - y) / h) ** 2)
+ far = smoothstep(25.0, 90.0, np.where(np.isfinite(self.dep), self.dep, 1e4)) # it lies down the street, not on you
+ self.steam_d += (band * far * smoothstep(0.3, 0.8, n) * density).astype(np.float32)
+
+ def rain(self, far=6000, mid=1500, near=90, slant=0.1, rings=380, seed=None):
+ """rain in three depths (streak masks, lit later by the light around each streak) and splash rings"""
+ r = np.random.default_rng(self._seed() if seed is None else seed)
+ H, W = self.H, self.W
+ self.rain_layers = []
+ for n, L, wd, a, bl, gain in ((far, (8, 20), 1, (0.2, 0.55), 0.0, 0.22), (mid, (24, 55), 1, (0.3, 0.8), 0.35, 0.42),
+ (near, (150, 330), 3, (0.25, 0.55), 2.6, 0.7)):
+ im = Image.new('F', (W, H), 0.0); d = ImageDraw.Draw(im)
+ xs = r.uniform(-60, W + 60, n); ys = r.uniform(-300, H, n)
+ ls = r.uniform(*L, n); al = r.uniform(*a, n); sk = slant + r.normal(0, 0.012, n)
+ for x, y, l, v, k in zip(xs, ys, ls, al, sk):
+ d.line([(x, y), (x + k * l, y + l)], fill=float(v), width=wd)
+ m = np.asarray(im)
+ if bl: m = blur(m, bl)
+ self.rain_layers.append((m.astype(np.float32), gain))
+ # splash rings on the wet ground (ellipses flattened by perspective)
+ im = Image.new('F', (W, H), 0.0); d = ImageDraw.Draw(im)
+ for _ in range(rings):
+ Z = 1.0 / r.uniform(1 / 60.0, 1 / 3.0); X = r.uniform(-self.wall, self.wall)
+ x, y = self.project(X, 0, Z)
+ if not (0 <= x < W and self.vy < y < H): continue
+ rad = r.uniform(0.03, 0.11)
+ rx = rad * self.f / Z; ry = rx * self.eye / Z
+ if rx < 0.8: continue
+ d.ellipse([x - rx, y - ry, x + rx, y + ry], outline=float(r.uniform(0.3, 0.8)), width=1)
+ if r.random() < 0.4:
+ d.line([(x, y - ry - 0.6 * rx), (x, y - ry)], fill=0.8, width=1) # the crown
+ self.rings = np.asarray(im, np.float32)
+
+ def glitch(self, y, h=16, shift=14, split=4):
+ """one torn scanline band across the finished frame (used sparingly: one or two per picture)"""
+ self.glitch_bands.append((int(y), int(h), int(shift), int(split)))
+
+ # ------------------------------------------------------------ rendering passes
+ def _reflect(self, img, haze):
+ H, W = self.H, self.W
+ src = (self.base > self.vy) & (self.YY < self.base) & (self.ground < 0.5)
+ src |= np.isinf(self.dep) & (self.YY < self.vy)
+ ys, xs = np.nonzero(src)
+ b = self.base[ys, xs]
+ yr = np.rint(2 * b - ys).astype(np.int64)
+ ok = (yr < H) & (yr > self.vy)
+ ys, xs, yr = ys[ok], xs[ok], yr[ok]
+ d = self.dep[ys, xs]
+ o = np.argsort(d, kind='stable') # nearest first ...
+ tgt = (yr * W + xs)[o]
+ _, first = np.unique(tgt, return_index=True) # ... and the nearest wins
+ sel = o[first]
+ R = np.zeros((H, W, 3), np.float32); C = np.zeros((H, W), np.float32)
+ R[yr[sel], xs[sel]] = img[ys[sel], xs[sel]]
+ C[yr[sel], xs[sel]] = 1
+ Rs = _blur_axis(R * C[..., None], 5, 0); Cs = _blur_axis(C, 5, 0)
+ ym = np.clip(2 * (self.vy + 6) - self.YY, 0, H - 1).astype(np.int32) # what hides behind near things: haze
+ fill = haze[ym, self.XX.astype(np.int32)]
+ R = np.where(C[..., None] > 0, R, np.where((Cs > 0.3)[..., None], Rs / np.maximum(Cs, 1e-3)[..., None], fill))
+ # ripples: displacement noise in ground coordinates
+ g = self.ground
+ Yr = np.maximum(self.YY - self.vy, 0.4)
+ Z = self.f * self.eye / Yr; Xg = (self.XX - self.vx) * Z / self.f
+ near = np.clip(Yr / (H - self.vy), 0, 1)
+ amp = 1.0 + 7.0 * near
+ n1 = _vnoise(Xg * 2.2, Z * 5.0, 11) - 0.5; n2 = _vnoise(Xg * 1.1, Z * 2.3, 12) - 0.5
+ dx = (n1 * 0.7 + n2 * 0.6) * amp * 2.0
+ dy = (_vnoise(Xg * 3.0, Z * 6.0, 13) - 0.5) * amp * 0.8
+ n3 = _vnoise(Xg * 9.0, Z * 14.0, 14) - 0.5 # rain-drop chop, strongest near
+ dx = dx + n3 * amp * 0.9 * self.pools; dy = dy + (_vnoise(Xg * 8.0, Z * 12.0, 15) - 0.5) * amp * 0.5 * self.pools
+ Rd = _sample(R, self.XX + dx, self.YY + dy)
+ sharp = _blur_axis(_blur_axis(Rd, 0.8, 1), 2.0, 0)
+ soft = _blur_axis(_blur_axis(Rd, 2.4, 1), 14, 0)
+ hot = np.clip(Rd - 0.6, 0, None)
+ streak = _blur_axis(_blur_axis(hot, 3.0, 1), 46, 0) # the brightest lights smear farthest
+ cos = Yr / np.sqrt(self.f ** 2 + Yr ** 2)
+ fres = 0.02 + 0.98 * (1 - cos) ** 5
+ Fp = (0.45 + 0.55 * fres ** 0.5) * g
+ Fd = (0.07 + 0.5 * fres ** 0.7) * g * self.damp
+ pud = self.pools
+ refl = sharp * (pud * Fp)[..., None] + (soft * 0.8 + streak * 0.9) * ((1 - pud) * Fd)[..., None]
+ out = img * (1 - 0.55 * pud * g)[..., None] + refl
+ if self.rings is not None:
+ env = _gblur(Rd, 3) * 0.9
+ out += env * (self.rings * g * (0.1 + 0.9 * pud))[..., None]
+ return out
+
+ def _steam(self, img, spill):
+ d = self.steam_d
+ if d.max() <= 0: return img
+ a = (1 - np.exp(-d * 1.3))[..., None]
+ light = (self.amb + spill * self.spill_k) * 0.35 + _gblur(img, 30) * 0.6 + _gblur(img, 120) * 0.5
+ return img * (1 - a) + light * a
+
+ def _rain(self, img):
+ if not self.rain_layers: return img
+ Lr = _gblur(img, 6) * 0.9 + _gblur(img, 24) * 0.8 + _gblur(img, 80) * 0.25
+ out = img.copy()
+ for m, gain in self.rain_layers:
+ out += Lr * (m * gain)[..., None]
+ return out
+
+ def _film(self, hdr, final):
+ H, W = self.H, self.W
+ lum = hdr @ LUMA
+ bright = np.clip(hdr - 0.8, 0, None)
+ bloom = _gblur(bright, 3) * 0.28 + _gblur(bright, 11) * 0.26 + _gblur(bright, 34) * 0.22 + _gblur(bright, 110) * 0.2
+ hdr = hdr + bloom * 0.55
+ hal = _gblur(np.clip(lum - 1.4, 0, None), 5)
+ hdr = hdr + hal[..., None] * np.array([1.0, 0.2, 0.08], np.float32) * 0.22
+ x = _aces(hdr * self.exposure)
+ out = x ** (1 / 2.2)
+ L = out @ LUMA
+ out = out + ((1 - L) ** 3)[..., None] * np.array([-0.006, 0.004, 0.018], np.float32) + (L ** 2)[..., None] * np.array([0.02, 0.0, -0.015], np.float32)
+ out = out * 0.975 + 0.012 * np.array([0.35, 0.45, 1.0], np.float32)
+ if final:
+ out = self._aberrate(out)
+ gr = np.random.default_rng(len(self.glitch_bands) + 99)
+ for (y, h, sh, sp) in self.glitch_bands:
+ xa = int(gr.uniform(0.05, 0.3) * W)
+ while xa < W * 0.95: # torn segments of different lengths
+ xb = min(W, xa + int(gr.uniform(0.12, 0.3) * W))
+ yy = y + int(gr.integers(-2, 3)); hh = max(2, h + int(gr.integers(-3, 3)))
+ y0, y1 = max(0, yy), min(H, yy + hh)
+ k = int(sh * gr.uniform(0.4, 1.3) * gr.choice([-1, 1]))
+ band = out[y0:y1].copy()
+ for c, o in ((0, k + sp), (1, k), (2, k - sp)):
+ band[..., c] = np.roll(band[..., c], o, axis=1)
+ band[1::2] *= 0.9
+ ramp = np.clip(np.minimum(np.arange(W) - xa, xb - np.arange(W)) / 20.0, 0, 1)[None, :, None]
+ out[y0:y1] = out[y0:y1] * (1 - 0.7 * ramp) + band * 0.7 * ramp
+ xa = xb + int(gr.uniform(0.04, 0.2) * W)
+ g = self.rng.normal(0, 1, (H, W)).astype(np.float32)
+ g = blur(g, 0.6); g /= g.std() + 1e-6
+ L = out @ LUMA
+ amp = 0.022 * (0.35 + 2.4 * L * (1 - L))
+ out = out + (g * amp)[..., None] + self.rng.normal(0, 0.004, (H, W, 3)).astype(np.float32)
+ r = np.hypot((self.XX - W / 2) / (W / 2), (self.YY - H / 2) / (H / 2)) / np.sqrt(2)
+ out = out * (1 - 0.42 * r ** 2.2)[..., None]
+ return np.clip(out, 0, 1)
+
+ def _aberrate(self, out, k=0.0016):
+ """radial chromatic aberration: red magnified a little, blue not at all -> fringes grow toward the edges"""
+ H, W = self.H, self.W
+ ch = []
+ for i, sc in enumerate((1 + 2 * k, 1 + k, 1.0)):
+ if sc == 1.0: ch.append(out[..., i]); continue
+ a = 1 / sc
+ im = Image.fromarray(out[..., i].astype(np.float32), 'F').transform(
+ (W, H), Image.AFFINE, (a, 0, W / 2 * (1 - a), 0, a, H / 2 * (1 - a)), resample=Image.BILINEAR)
+ ch.append(np.asarray(im))
+ return np.stack(ch, -1)
+
+ # ------------------------------------------------------------ output
+ def render(self, final=True):
+ src = self.emi + self.lsrc
+ spill = _gblur(src, 14) * 0.8 + _gblur(src, 55) * 1.1 + _gblur(src, 200) * 1.0
+ down = np.zeros_like(src); dy = int(0.12 * self.H); down[dy:] = src[:-dy]
+ spill = spill + (_gblur(down, 60) * 1.2 + _gblur(down, 180) * 1.2) * self.ground[..., None]
+ lit = self.alb * (self.amb + spill * self.spill_k) + self.emi
+ fin = np.isfinite(self.dep)
+ T = np.where(fin, np.maximum(np.exp(-np.where(fin, self.dep, 0) / self.fog_m), self.fog_floor), self.sky_t).astype(np.float32)
+ scat = _gblur(src, 40) * 0.45 + _gblur(src, 130) * 0.8 + _gblur(src, 320) * 0.6
+ rowg = (0.55 + 0.9 * np.exp(-((self.YY - self.vy) / (0.22 * self.H)) ** 2))[..., None]
+ fogc = self.fogc * rowg * 0.5 + scat * self.scatter_k
+ img = lit * T[..., None] + fogc * (1 - T)[..., None] + self.add
+ if self.street_on: img = self._reflect(img, fogc * (1 - np.exp(-300 / self.fog_m)))
+ img = self._steam(img, spill)
+ img = self._rain(img)
+ return self._film(img, final)
+
+ def composite(self, final=True):
+ return Image.fromarray((self.render(final) * 255 + 0.5).astype(np.uint8))
+
+ def stage(self, name):
+ if self.record: self.stages.append((name, self.composite(final=False)))
+
+ def save(self, path, stages_dir=None, quality=88):
+ img = self.composite(final=True)
+ if path.lower().endswith(('.jpg', '.jpeg')): img.save(path, quality=quality, subsampling=0)
+ else: img.save(path)
+ if stages_dir:
+ 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