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 perler-bead style (27 styles)

clovericc406404f72b9
diff --git a/README.md b/README.md
index b1edcc4..40ff61e 100644
--- a/README.md
+++ b/README.md
@@ -1,12 +1,16 @@
# Claude Drawing · Claude 绘图
-**Claude paints with code — no image model.** Twenty-six styles, from ink wash and impasto oil to clay, cyanotype, cross-stitch, a chalkboard, a cyberpunk street, an isometric island, a ray-traced ball pit and a synthwave sunset.
-**不用生图模型,Claude 用代码一笔一笔作画。** 二十六种画风,从水墨、油画到黏土、蓝晒、十字绣、黑板板书、赛博朋克、等轴小岛、光线追踪的小球海和 Synthwave 落日。
+**Claude paints with code — no image model.** Twenty-seven styles, from ink wash and impasto oil to clay, cyanotype, cross-stitch, a chalkboard, a cyberpunk street, an isometric island, a ray-traced ball pit, perler beads and a synthwave sunset.
+**不用生图模型,Claude 用代码一笔一笔作画。** 二十七种画风,从水墨、油画到黏土、蓝晒、十字绣、黑板板书、赛博朋克、等轴小岛、光线追踪的小球海、拼豆和 Synthwave 落日。
[English](#english) · [中文](#中文)
<p align="center"><img src="examples/drawing_bawansiqian.gif" width="100%"><br><sub><b>Ink wash · 水墨</b> — every style below is drawn stage by stage like this · 下面每种画风都是这样一步步画出来的</sub></p>
+| Isometric 2.5D · 等轴 2.5D | Perler beads · 拼豆 |
+|---|---|
+| ![isometric](examples/drawing_isometric_weather_island.gif) | ![perler](examples/drawing_perler_strawberry_coaster.gif) |
+
| Watercolour · 水彩 | Paper collage · 剪纸拼贴 | Coloured pencil · 韩国彩铅 | Anime · 日本动漫 |
|---|---|---|---|
| ![watercolour](examples/drawing_watercolor_autumn.gif) | ![collage](examples/drawing_papercut_balloons.gif) | ![pencil](examples/drawing_colorpencil_dessert.gif) | ![anime](examples/drawing_anime_summer.gif) |
@@ -16,14 +20,10 @@
| ![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 · 实验笔记本 · 贴纸** | **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) |
-
-| Hand-drawn cartoon · 卡通手绘 | Isometric 2.5D · 等轴 2.5D | Continuous line art · 单线画 |
-|---|---|---|
-| ![cartoon](examples/drawing_cartoon_toaster.gif) | ![isometric](examples/drawing_isometric_weather_island.gif) | ![lineart](examples/drawing_lineart_paper_plane.gif) |
-| **Soft 3D · 柔光 3D** | **Shape morph · 形变动画** | **Newspaper collage · 报刊拼贴** |
-| ![soft3d](examples/drawing_soft3d_rise.gif) | ![morph](examples/drawing_morph_water_cycle.gif) | ![newscollage](examples/drawing_newscollage_curiosity.gif) |
-| **Aurora glass · 弥散玻璃** | **Bauhaus geometric · 包豪斯几何** | **Retro synthwave · 复古 Synthwave** |
-| ![aurora](examples/drawing_aurora_morning.gif) | ![bauhaus](examples/drawing_bauhaus_form_colour.gif) | ![synthwave](examples/drawing_synthwave_coastline.gif) |
+| **Hand-drawn cartoon · 卡通手绘** | **Continuous line art · 单线画** | **Soft 3D · 柔光 3D** | **Shape morph · 形变动画** |
+| ![cartoon](examples/drawing_cartoon_toaster.gif) | ![lineart](examples/drawing_lineart_paper_plane.gif) | ![soft3d](examples/drawing_soft3d_rise.gif) | ![morph](examples/drawing_morph_water_cycle.gif) |
+| **Newspaper collage · 报刊拼贴** | **Aurora glass · 弥散玻璃** | **Bauhaus geometric · 包豪斯几何** | **Retro synthwave · 复古 Synthwave** |
+| ![newscollage](examples/drawing_newscollage_curiosity.gif) | ![aurora](examples/drawing_aurora_morning.gif) | ![bauhaus](examples/drawing_bauhaus_form_colour.gif) | ![synthwave](examples/drawing_synthwave_coastline.gif) |
### Gallery · 画廊
@@ -31,34 +31,34 @@
|---|---|
| **八万四千法门** · *Many Paths, One Summit*<br><sub>Ink wash · 水墨</sub> | **月印万川** · *One Moon in Ten Thousand Rivers*<br><sub>Ink wash · 水墨</sub> |
| <img src="examples/bawansiqian.jpg" width="100%"> | <img src="examples/moon_river.jpg" width="100%"> |
-| **秋日湖畔** · *Autumn Lake*<br><sub>Watercolour · 水彩</sub> | **水彩底纹** · *Watercolour Washes*<br><sub>Watercolour · 水彩 — a background for explainer videos · 讲解视频的背景</sub> |
-| <img src="examples/watercolor_autumn.jpg" width="100%"> | <img src="examples/watercolor_washes.jpg" width="100%"> |
-| **热气球小镇** · *Balloon Day*<br><sub>Paper collage · 剪纸拼贴</sub> | **午后甜点** · *Afternoon Dessert*<br><sub>Coloured pencil · 韩国彩铅</sub> |
-| <img src="examples/papercut_balloons.jpg" width="100%"> | <img src="examples/colorpencil_dessert.jpg" width="100%"> |
-| **夏空** · *Summer Sky*<br><sub>Anime · 日本动漫</sub> | **灵感生长** · *Growing Ideas*<br><sub>Editorial · 编辑风手绘</sub> |
-| <img src="examples/anime_summer.jpg" width="100%"> | <img src="examples/editorial_ideas.jpg" width="100%"> |
-| **麦田星空** · *Swirling Sky over the Wheat Field*<br><sub>Impasto oil · 油画厚涂</sub> | **富士曙** · *Fuji at Dawn*<br><sub>Ukiyo-e · 浮世绘</sub> |
-| <img src="examples/oil_wheatfield.jpg" width="100%"> | <img src="examples/ukiyoe_fuji.jpg" width="100%"> |
-| **雨夜咖啡店** · *Rainy Night Cafe*<br><sub>Pixel art · 像素风</sub> | **灯塔岛** · *Lighthouse Island*<br><sub>Stop-motion clay · 黏土定格</sub> |
-| <img src="examples/pixel_rainy_cafe.png" width="100%"> | <img src="examples/clay_lighthouse.jpg" width="100%"> |
-| **蓝晒植物** · *Sun-Print Botanicals*<br><sub>Cyanotype · 蓝晒</sub> | **家** · *Home Sampler*<br><sub>Cross-stitch · 十字绣</sub> |
-| <img src="examples/cyanotype_botanicals.jpg" width="100%"> | <img src="examples/stitch_sampler.jpg" width="100%"> |
-| **Aurora 64 收音机** · *Aurora 64 Radio*<br><sub>Vintage instrument panel · 复古仪器面板</sub> | **周末市集** · *Weekend Market*<br><sub>Sticker collage × receipt · 贴纸拼贴 · 小票</sub> |
-| <img src="examples/panel_radio.jpg" width="100%"> | <img src="examples/sticker_market.jpg" width="100%"> |
-| **咖啡萃取实验** · *Coffee Brewing Experiment*<br><sub>Lab notebook × stickers · 实验笔记本 · 贴纸</sub> | **为什么天空是蓝的** · *Why Is the Sky Blue?*<br><sub>Chalkboard · 黑板板书</sub> |
-| <img src="examples/notebook_brewing.jpg" width="100%"> | <img src="examples/chalk_lesson.jpg" width="100%"> |
-| **霓虹不夜城** · *Neon District*<br><sub>Cyberpunk · 赛博朋克</sub> | **早安吐司** · *Good Morning, Toast*<br><sub>Hand-drawn cartoon · 卡通手绘</sub> |
-| <img src="examples/cyberpunk_neon_street.jpg" width="100%"> | <img src="examples/cartoon_toaster.jpg" width="100%"> |
-| **岛上的气象站** · *Island Weather Station*<br><sub>Isometric 2.5D · 等轴 2.5D</sub> | **从这扇窗到那扇窗** · *From Window to Window*<br><sub>Continuous line art · 单线画</sub> |
-| <img src="examples/isometric_weather_island.jpg" width="100%"> | <img src="examples/lineart_paper_plane.jpg" width="100%"> |
-| **浮出** · *Rise*<br><sub>Soft 3D · 柔光 3D</sub> | **一滴水的旅程** · *A Drop's Round Trip*<br><sub>Shape morph · 形变动画</sub> |
-| <img src="examples/soft3d_rise.jpg" width="100%"> | <img src="examples/morph_water_cycle.jpg" width="100%"> |
-| **好奇心周刊 · 拆开看看** · *Curiosity Weekly · Take It Apart*<br><sub>Newspaper collage · 报刊拼贴</sub> | **晨间计划** · *Morning Plan*<br><sub>Aurora glassmorphism · 弥散玻璃</sub> |
-| <img src="examples/newscollage_curiosity.jpg" width="100%"> | <img src="examples/aurora_morning.jpg" width="100%"> |
-| **形与色** · *Form & Colour*<br><sub>Bauhaus geometric · 包豪斯几何</sub> | **海岸线 1987** · *Coastline 1987*<br><sub>Retro synthwave · 复古 Synthwave</sub> |
-| <img src="examples/bauhaus_form_colour.jpg" width="100%"> | <img src="examples/synthwave_coastline.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, chalk dust settling under half-erased lessons, rain-lit neon glass mirrored in a wet street, a blue-pencil rough under boiling brush ink, an island ray-traced under one soft sun, a single unbroken gold line, candy balls with softbox glints, one outline morphing through six shapes, halftone photos cut out with scissors, frosted glass blurring the real pixels behind it, screen-printed primaries out of register, a slit sun sinking behind a neon grid played off tape. 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 45 s (the soft 3D ray tracer) per 1920×1080 image.
+| **秋日湖畔** · *Autumn Lake*<br><sub>Watercolour · 水彩</sub> | **热气球小镇** · *Balloon Day*<br><sub>Paper collage · 剪纸拼贴</sub> |
+| <img src="examples/watercolor_autumn.jpg" width="100%"> | <img src="examples/papercut_balloons.jpg" width="100%"> |
+| **午后甜点** · *Afternoon Dessert*<br><sub>Coloured pencil · 韩国彩铅</sub> | **夏空** · *Summer Sky*<br><sub>Anime · 日本动漫</sub> |
+| <img src="examples/colorpencil_dessert.jpg" width="100%"> | <img src="examples/anime_summer.jpg" width="100%"> |
+| **灵感生长** · *Growing Ideas*<br><sub>Editorial · 编辑风手绘</sub> | **麦田星空** · *Swirling Sky over the Wheat Field*<br><sub>Impasto oil · 油画厚涂</sub> |
+| <img src="examples/editorial_ideas.jpg" width="100%"> | <img src="examples/oil_wheatfield.jpg" width="100%"> |
+| **富士曙** · *Fuji at Dawn*<br><sub>Ukiyo-e · 浮世绘</sub> | **雨夜咖啡店** · *Rainy Night Cafe*<br><sub>Pixel art · 像素风</sub> |
+| <img src="examples/ukiyoe_fuji.jpg" width="100%"> | <img src="examples/pixel_rainy_cafe.png" width="100%"> |
+| **灯塔岛** · *Lighthouse Island*<br><sub>Stop-motion clay · 黏土定格</sub> | **蓝晒植物** · *Sun-Print Botanicals*<br><sub>Cyanotype · 蓝晒</sub> |
+| <img src="examples/clay_lighthouse.jpg" width="100%"> | <img src="examples/cyanotype_botanicals.jpg" width="100%"> |
+| **家** · *Home Sampler*<br><sub>Cross-stitch · 十字绣</sub> | **Aurora 64 收音机** · *Aurora 64 Radio*<br><sub>Vintage instrument panel · 复古仪器面板</sub> |
+| <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%"> |
+| **早安吐司** · *Good Morning, Toast*<br><sub>Hand-drawn cartoon · 卡通手绘</sub> | **岛上的气象站** · *Island Weather Station*<br><sub>Isometric 2.5D · 等轴 2.5D</sub> |
+| <img src="examples/cartoon_toaster.jpg" width="100%"> | <img src="examples/isometric_weather_island.jpg" width="100%"> |
+| **从这扇窗到那扇窗** · *From Window to Window*<br><sub>Continuous line art · 单线画</sub> | **浮出** · *Rise*<br><sub>Soft 3D · 柔光 3D</sub> |
+| <img src="examples/lineart_paper_plane.jpg" width="100%"> | <img src="examples/soft3d_rise.jpg" width="100%"> |
+| **一滴水的旅程** · *A Drop's Round Trip*<br><sub>Shape morph · 形变动画</sub> | **好奇心周刊 · 拆开看看** · *Curiosity Weekly · Take It Apart*<br><sub>Newspaper collage · 报刊拼贴</sub> |
+| <img src="examples/morph_water_cycle.jpg" width="100%"> | <img src="examples/newscollage_curiosity.jpg" width="100%"> |
+| **晨间计划** · *Morning Plan*<br><sub>Aurora glassmorphism · 弥散玻璃</sub> | **形与色** · *Form & Colour*<br><sub>Bauhaus geometric · 包豪斯几何</sub> |
+| <img src="examples/aurora_morning.jpg" width="100%"> | <img src="examples/bauhaus_form_colour.jpg" width="100%"> |
+| **海岸线 1987** · *Coastline 1987*<br><sub>Retro synthwave · 复古 Synthwave</sub> | **草莓杯垫** · *Strawberry Coaster*<br><sub>Perler beads · 拼豆</sub> |
+| <img src="examples/synthwave_coastline.jpg" width="100%"> | <img src="examples/perler_strawberry_coaster.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, chalk dust settling under half-erased lessons, rain-lit neon glass mirrored in a wet street, a blue-pencil rough under boiling brush ink, an island ray-traced under one soft sun, a single unbroken gold line, candy balls with softbox glints, one outline morphing through six shapes, halftone photos cut out with scissors, frosted glass blurring the real pixels behind it, screen-printed primaries out of register, a slit sun sinking behind a neon grid played off tape, hollow fuse beads on a pegboard melting together under an iron. 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 45 s (the soft 3D ray tracer) per 1920×1080 image.
---
@@ -66,7 +66,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 twenty-six styles:
+A [Claude Code](https://claude.com/claude-code) skill and a small painting library with twenty-seven styles:
| Style | Module | What makes it read as the real medium |
|---|---|---|
@@ -96,6 +96,7 @@ A [Claude Code](https://claude.com/claude-code) skill and a small painting libra
| **Aurora glassmorphism** | `lib/aurora.py` · `Aurora` | a mesh gradient of colour pools mixed in OKLab on a domain-warped grid, with aurora ribbons and fine grain; glossy iridescent orbs; frosted panes that blur the *actual* pixels beneath them (backdrop, orbs, the cards and text behind), boost saturation and add a milky veil that is thicker toward the light; a bevelled rim that bends the view outward with faint dispersion, a light-facing 1 px edge highlight, frost grain and a soft shadow tinted by what it falls on; crisp SDF controls: gradient toggles, sliders, conic progress rings, pill bars, sparklines, glass chips, a glossy sun behind a glass cloud; SF + PingFang lettering |
| **Bauhaus geometric** | `lib/bauhaus.py` · `Bauhaus` | a press sheet printed screen by screen, light to dark, on cream uncoated stock (cloudy pulp, fibres, flecks, tooth, a slight cockle); each screen has its own registration error, so colour meets black with a sliver of paper or a dark overlap and the register targets print as a stack of offset crosshairs; an ink film streaked along the squeegee pull and thinning toward the end of the stroke, with bare tooth pits and pinholes where it is thin and a mesh-ragged stencil edge; semi-opaque inks that darken where they overprint; circles, sectors, triangles and heavy bars on a strict module grid; Futura-style caps and heavy Hei, knocked out of solids; crop marks, a colour bar and a pencilled edition number |
| **Retro synthwave** | `lib/synthwave.py` · `Synthwave` | an 80s retro-future dusk through a pinhole camera: a gradient sun cut by slits that thicken toward the horizon; an analytic neon grid with honest line widths that fades to its average instead of moiré; wireframe mountains glowing magenta to cyan; a sea whose reflection is torn into bars stretched about the sun's column; palm silhouettes with sunset rims; chrome caps mirroring sky over ground with a sharp horizon, extrusion and glints; neon script; then played back off tape: chroma bleed, a tracking band, head-switching noise, on-screen display and scanlines |
+| **Perler beads** | `lib/perler.py` · `Perler` | a height field of real tubes seen by a camera leaning back a little (each pixel walks its column to the first surface), so every bead shows a sliver of side wall, its hole shows the inner wall and the peg inside tinted by light through the plastic, and the gaps show the pegboard; a translucent pegboard (square, round, hexagonal) with empty pegs; per-bead dye-lot shade and wobble; opaque, pearl, clear and glow plastics; ironing as melt: tubes slump and spread, holes close from the rim, neighbours flow together through a smooth union until the gaps shrink to diamonds and the top becomes one flat waxy sheet with paper grain; translucent ironing paper that drapes over the beads and peels back with a curl; a soft box seen in reflection (crisp arcs on glossy rims, a drifting sheen on melted plastic); sorting-tray heaps, spilled beads, tweezers held in the air with their own shadow, a printed chart with pencil ticks |
Ask Claude to *"draw it yourself"*, *"paint this with code"*, or *"claude绘图"*, and name a style if you like. Claude then:
@@ -175,6 +176,7 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages
- **Aurora glass**: blur what is really under the pane, then veil it lightly (tint ~0.24, saturate ~1.5), or it turns into milky plastic. Let orbs pass a third or more behind the glass and never touch an edge tangentially. Overlap cards only inside each other's padding. Give each gradient one meaning. For the GIF, weight saturated pixels in the palette sample and add one static Bayer pattern.
- **Bauhaus**: print light to dark, one ink per screen, and keep everything of one colour on its screen so misregistration moves it together. Keep bare-paper pits to ~2% and only in thin-film streaks, or solids turn to sandpaper and type to a worn rubber stamp. Use a light 3×3 edge blur (a big blur rounds the corners). Knock labels out of dark solids instead of printing black on blue, and keep margin text clear of the crop marks.
- **Synthwave**: keep the sun's base colour low and let the bloom lift it, or it burns to white and the slits fill in. Break the sea's reflection into bands stretched about the sun's column, and let light sources reflect more strongly than the sky. Measure grid lines in screen pixels and swap dense cells for their average. Keep tape damage mild: one tracking band, sub-pixel jitter.
+- **Perler beads**: build real tubes and let the light make the bead: the hole, the peg inside it and a sliver of side wall are what separate it from pixel art. Iron with melt, not paint: 0.4 is the half-melt (holes open, beads stuck, diamond gaps), 0.7 a finished piece; drop seam grooves and fine grain once it is flat, or it turns into hex nuts and frosting. Shade walls from smoothed maps sampled at their foot, never from the anti-aliased edge row. Keep heaps about one bead deep. Gloss comes from a soft box seen in reflection (an arc on the upper-left rim), not a Fresnel ring around every hole.
### Roadmap
@@ -186,7 +188,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,加上一个小巧的绘图库,内置二十七种画风:
| 画风 | 模块 | 为什么看起来像真的 |
|---|---|---|
@@ -216,6 +218,7 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages
| **弥散玻璃** | `lib/aurora.py` · `Aurora` | 网格渐变:几团色光在 OKLab 里混色,坐标扭曲成流动的形状,加极光光带和细颗粒;虹彩光泽小球;磨砂玻璃模糊的是它下面**真实的像素**(背景、小球、后面的卡片和字),提高饱和度,蒙一层近光源更厚的白纱;边缘斜面向外折射并带一点色散,朝光的边有 1 px 高光,玻璃上有磨砂颗粒,投影颜色取自下面的背景;界面用距离场画,边缘干净:渐变开关、滑块、锥形渐变进度环、胶囊柱状图、折线图、玻璃小胶囊、躲在玻璃云后的光泽太阳;SF + 苹方字体 |
| **包豪斯几何** | `lib/bauhaus.py` · `Bauhaus` | 在奶油色未涂布纸(云状纸浆、纤维、纸屑、纸齿、微微不平)上按色版先浅后深逐版刮印;每块网版有自己的套准误差,色块和黑线相接处露出一丝纸白或压出一道深边,套准十字叠成几色错开的样子;墨膜顺刮板方向有条纹、行程末端变薄,薄处露出纸齿坑点和针孔,版边有网目锯齿;墨半透明,叠印变深;圆、扇形、三角、粗黑条都落在严格的模数网格上;Futura 式几何无衬线大写和粗黑体,可从色块里挖空;裁切线、色标条和铅笔版号 |
| **复古 Synthwave** | `lib/synthwave.py` · `Synthwave` | 针孔相机看 80 年代复古未来的黄昏:横条切口越往下越厚的渐变落日;逐像素解析的霓虹网格,线宽准确,远处换成平均值不出摩尔纹;从品红渐变到青色的线框山脉;倒影按横带拉伸、碎成一条条光带的海面;带落日轮廓光的棕榈剪影;上映天空、下映地面、中间一道锐利地平线的镀铬大字,带挤出和星闪;霓虹手写字;最后「过一遍录像带」:色度渗色、跟踪噪带、磁头噪声、屏显字和扫描线 |
+| **拼豆** | `lib/perler.py` · `Perler` | 整张桌面是高度图,豆子是真的短管,相机略向后仰、逐列找最近的表面:每颗豆露一条侧壁,孔里看得到内壁和被塑料透光染色的钉子,珠间缝里露出钉板;半透明钉板(方、圆、六边形)上的空钉;每颗豆色号深浅略有不同、在钉上略有歪斜;不透明、珠光、透明、夜光几种塑料;熨烫是真的熔化:管子塌低变宽、孔从边缘收小、相邻的豆通过平滑并集流到一起,缝缩成小菱形直到合拢,顶面变成一片带纸纹的蜡质平面;半透明熨烫纸顺着豆子盖下去,可以卷边揭开;镜面里看得到灯箱(亮面豆沿上一道锐利高光弧,熔化后变成一片蜡光);分色收纳盒里的豆堆、散落的豆、悬空带投影的镊子、带铅笔勾的图纸 |
对 Claude 说「claude绘图」「你自己画」「用代码画」,也可以指定画风。它会:
1. **先定构图**:层次、焦点、留白,而且画面要图解内容本身;
@@ -271,6 +274,7 @@ python3 examples/newscollage_curiosity.py out.png # 报刊拼
python3 examples/aurora_morning.py out.png # 弥散玻璃:晨间计划
python3 examples/bauhaus_form_colour.py out.png # 包豪斯几何:形与色
python3 examples/synthwave_coastline.py out.png # 复古 Synthwave:海岸线 1987
+python3 examples/perler_strawberry_coaster.py out.png # 拼豆:草莓杯垫
```
### 作画要点(Claude 交图前逐条自查)
@@ -299,6 +303,7 @@ python3 examples/synthwave_coastline.py out.png # 复古 Synt
- **弥散玻璃**:玻璃要模糊它下面真实的东西,白纱要薄(约 0.24,饱和度约 1.5),否则像奶白塑料;小球要有三四成压在玻璃后面,别和卡片边相切;卡片只在对方的内边距里重叠;一种渐变只代表一件事;动图调色板给饱和像素加权,再叠同一张 Bayer 抖动。
- **包豪斯**:先浅后深,一种颜色一块版,同色的东西放在同一块版上,错位才会整体一起动;露纸坑点约 2%、只在墨膜薄的条纹里,否则色块像砂纸、字像旧橡皮章;版边只做 3×3 轻模糊(大模糊会把直角磨圆);深色块上的标注用挖空,不要黑字压蓝;页边小字让开裁切线。
- **复古 Synthwave**:太阳底色压低、靠泛光提亮,否则冲成白团、切口被填平;海面倒影按横带以太阳所在列为中心拉伸打碎,光源的倒影比天空更强;网格线按屏幕像素算宽度,格子太密就换成平均值;录像带损伤要轻:一条跟踪噪带、不到一像素的逐行抖动。
+- **拼豆**:先搭出真的管子,让光把豆子「画」出来:孔、孔里的钉子和那一条侧壁,才是它和像素风的区别。熨烫用 melt 控制,不要手涂:0.4 是半熔(孔在、珠粘、留菱形缝),0.7 是成品;熨平后去掉接缝沟和细纹,否则像六角螺母、像糖霜。侧壁从平滑后的图、在墙脚取样着色,别用抗锯齿的边缘行。豆堆只堆一层左右。光泽靠镜面里的灯箱(左上沿一道弧),不要每个孔一圈菲涅尔白环。
### 计划
diff --git a/SKILL.md b/SKILL.md
index af6ad4c..378505b 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -1,6 +1,6 @@
---
name: claude绘图
-description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。内置二十六种画风:中国水墨、水彩、剪纸拼贴、韩国彩铅、日本动漫、编辑风手绘(Riso)、油画厚涂(梵高式流向笔触+颜料浮雕打光)、浮世绘木版画(晕色、木纹、墨线主版、青海波)、像素风(低分辨率+Bayer 抖动+像素字体)、黏土定格(高度图捏出的彩泥+影棚打光)、蓝晒(普鲁士蓝日光晒图,植物剪影透光)、十字绣(Aida 布十字绣+回针绣+缎面绣+法式结)、复古仪器面板(60 年代收音机/仪器正面:柚木、拉丝铝、旋钮、刻度窗、指示灯)、贴纸拼贴·小票(模切乙烯贴纸、热敏小票、和纸胶带、吊牌、橡皮章)、实验笔记本·贴纸(线圈方格本、铅笔图表、荧光笔、红笔圈、便利贴)、黑板板书(墨绿石板、粉笔颗粒、板擦残影、示意图与公式)、赛博朋克(雨夜霓虹街道、玻璃管霓虹招牌、全息广告、湿路面倒影)、卡通手绘(蓝铅笔稿、毛笔线、错位平涂、赛璐璐阴影、逐帧抖线)、等轴 2.5D(正等轴微缩模型、一个太阳照出三面明暗、悬浮数据卡)、单线画(一根不断开的线一笔画完、唯一点睛色)、柔光 3D(光线追踪的糖果色小球海和鼓鼓的软字、景深)、形变动画(一条轮廓依次变形、洋葱皮残影、缓动曲线)、报刊拼贴(牛皮纸、手撕旧报纸、网点老照片、勒索信拼贴字)、弥散玻璃(弥散渐变、磨砂玻璃卡片界面)、包豪斯几何(三原色几何、丝网印刷海报)、复古 Synthwave(切口落日、霓虹网格、镀铬字、录像带质感)。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」,或点名以上任一画风(含黏土、彩泥、定格动画、蓝晒、晒图、十字绣、刺绣、复古面板、老式收音机、贴纸、小票、收据、手帐拼贴、实验笔记本、方格本、荧光笔、便利贴、黑板、板书、粉笔、赛博朋克、霓虹、雨夜街道、卡通、手绘卡通、逐帧手绘、抖线、等轴、2.5D、微缩模型、单线画、一笔画、线条动画、柔光 3D、3D 渲染、C4D 风、软糖字、小球海、形变、变形动画、报刊拼贴、剪报、达达、勒索信字、网点印刷、弥散渐变、玻璃拟态、毛玻璃、包豪斯、几何构成、丝网印刷、Synthwave、蒸汽波、合成器浪潮、80 年代复古),或 "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 / cartoon / hand-drawn animation / isometric / 2.5D / continuous line / one-line drawing / soft 3D / 3D render / puffy letters / ball pit / shape morph / morphing / newspaper collage / Dada / ransom note / halftone / glassmorphism / aurora gradient / Bauhaus / geometric poster / screen print / synthwave / retrowave / outrun without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。
+description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。内置二十七种画风:中国水墨、水彩、剪纸拼贴、韩国彩铅、日本动漫、编辑风手绘(Riso)、油画厚涂(梵高式流向笔触+颜料浮雕打光)、浮世绘木版画(晕色、木纹、墨线主版、青海波)、像素风(低分辨率+Bayer 抖动+像素字体)、黏土定格(高度图捏出的彩泥+影棚打光)、蓝晒(普鲁士蓝日光晒图,植物剪影透光)、十字绣(Aida 布十字绣+回针绣+缎面绣+法式结)、复古仪器面板(60 年代收音机/仪器正面:柚木、拉丝铝、旋钮、刻度窗、指示灯)、贴纸拼贴·小票(模切乙烯贴纸、热敏小票、和纸胶带、吊牌、橡皮章)、实验笔记本·贴纸(线圈方格本、铅笔图表、荧光笔、红笔圈、便利贴)、黑板板书(墨绿石板、粉笔颗粒、板擦残影、示意图与公式)、赛博朋克(雨夜霓虹街道、玻璃管霓虹招牌、全息广告、湿路面倒影)、卡通手绘(蓝铅笔稿、毛笔线、错位平涂、赛璐璐阴影、逐帧抖线)、等轴 2.5D(正等轴微缩模型、一个太阳照出三面明暗、悬浮数据卡)、单线画(一根不断开的线一笔画完、唯一点睛色)、柔光 3D(光线追踪的糖果色小球海和鼓鼓的软字、景深)、形变动画(一条轮廓依次变形、洋葱皮残影、缓动曲线)、报刊拼贴(牛皮纸、手撕旧报纸、网点老照片、勒索信拼贴字)、弥散玻璃(弥散渐变、磨砂玻璃卡片界面)、包豪斯几何(三原色几何、丝网印刷海报)、复古 Synthwave(切口落日、霓虹网格、镀铬字、录像带质感)、拼豆(钉板上的熔珠小管、熨烫熔合)。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」,或点名以上任一画风(含黏土、彩泥、定格动画、蓝晒、晒图、十字绣、刺绣、复古面板、老式收音机、贴纸、小票、收据、手帐拼贴、实验笔记本、方格本、荧光笔、便利贴、黑板、板书、粉笔、赛博朋克、霓虹、雨夜街道、卡通、手绘卡通、逐帧手绘、抖线、等轴、2.5D、微缩模型、单线画、一笔画、线条动画、柔光 3D、3D 渲染、C4D 风、软糖字、小球海、形变、变形动画、报刊拼贴、剪报、达达、勒索信字、网点印刷、弥散渐变、玻璃拟态、毛玻璃、包豪斯、几何构成、丝网印刷、Synthwave、蒸汽波、合成器浪潮、80 年代复古、拼豆、拼拼豆、熔珠、熨豆、豆豆画、钉板、烫豆),或 "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 / cartoon / hand-drawn animation / isometric / 2.5D / continuous line / one-line drawing / soft 3D / 3D render / puffy letters / ball pit / shape morph / morphing / newspaper collage / Dada / ransom note / halftone / glassmorphism / aurora gradient / Bauhaus / geometric poster / screen print / synthwave / retrowave / outrun / perler beads / hama beads / artkal / fuse beads / melty beads / pegboard beads without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。
---
# Claude 绘图
@@ -40,6 +40,7 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型
| 弥散玻璃 | `lib/aurora.py` · `Aurora` | `examples/aurora_morning.py` 晨间计划(日出色弥散渐变与极光光带、光泽小球;磨砂玻璃卡片层叠:晨间计划时间线(3/5 完成,进行中那一行是玻璃叠玻璃)、专注倒计时圆环、光泽太阳躲在玻璃云后的天气卡、勿扰开关与白噪音滑块、近 7 天专注柱状图、9:00 站会提醒胶囊) | 约 2 秒 |
| 包豪斯几何 | `lib/bauhaus.py` · `Bauhaus` | `examples/bauhaus_form_colour.py` 形与色 · Form & Colour(奶油色纸上的丝网印刷讲座海报:黄三角、红方、蓝圆站在粗黑地线上,60° 弧、直角框、挖空的圆心和半径,下面大字角数 3 / 4 / 0;「形与色」大标题、挖空字的黑条论点「角越尖,色越亮」;构成网格、套准十字、裁切线、色标条、铅笔版号) | 约 2 秒 |
| 复古 Synthwave | `lib/synthwave.py` · `Synthwave` | `examples/synthwave_coastline.py` 海岸线 1987(横条切口的渐变落日沉入海面、倒影碎成一条条光带、线框小岛与线框山脉、霓虹网格地面、霓虹边线的海岸公路、灭点处亮灯的小城、带落日轮廓光的棕榈剪影、驶向城市的尾灯、镀铬大字 COASTLINE 与霓虹手写 Last Sunset、录像机 PLAY 与日期屏显、色度渗色、跟踪噪带和扫描线) | 约 4 秒 |
+| 拼豆 | `lib/perler.py` · `Perler` | `examples/perler_strawberry_coaster.py` 草莓杯垫(方格图纸上的草莓图样与图例,铅笔勾掉已摆的颜色;透明方钉板上摆到一半:草莓摆完、天蓝底色一行行往下铺,镊子夹着下一颗悬在空钉上,旁边散豆;九格分色收纳盒;熨平的圆杯垫:豆子熔成一片蜡质平面、孔缩小、外沿扇贝形,压着揭下的熨烫纸) | 约 9 秒 |
各画风共用 `lib/core.py` 里的底层工具:噪声、模糊、样条曲线、多边形遮罩、有机轮廓 `blob_pts`、毛笔 `bristle_stroke`、中文字体查找;新四种还用到补零平移 `shift`、文字遮罩 `text_mask`、西文字体查找 `latin_font`/`load_font`,以及高度图打光 `height_normals`、`height_shadow`(沿光线步进的投影)、`ambient_occlusion`。
@@ -69,7 +70,8 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型
- 杂志封面、观点海报、达达 / 复古拼贴、「拆开看看 / 里面有什么」类讲解页、需要老照片质感又不能用真人照片 → 报刊拼贴(要童趣温暖的彩纸拼贴仍用剪纸拼贴);
- 产品界面、App / 小组件展示、效率工具与数据面板、明亮通透的科技感、讲解片的「功能 / 界面」页 → 弥散玻璃(要暗夜霓虹氛围仍用赛博朋克);
- 设计感海报、讲座 / 展览 / 活动海报、概念图解(形状、比例、对比、原则)、讲解片里的「定义 / 原理」页 → 包豪斯几何;
-- 80 年代复古未来、怀旧、夏夜公路与海边、音乐和歌单封面、讲解片的「复古科技 / 回到过去」封面 → 复古 Synthwave(要雨夜城市用赛博朋克,要低分辨率游戏感用像素风)。
+- 80 年代复古未来、怀旧、夏夜公路与海边、音乐和歌单封面、讲解片的「复古科技 / 回到过去」封面 → 复古 Synthwave(要雨夜城市用赛博朋克,要低分辨率游戏感用像素风);
+- 手作、DIY 教程、「从图纸到成品」的步骤图、把像素图案做成可爱实物(杯垫、挂件、冰箱贴)、讲解片里的「动手做」页 → 拼豆(要屏幕上的像素游戏感用像素风,要布上的针线用十字绣)。
每种画风一幅范例作为质量基准(范例都不用禅意主题);水墨另加一幅「月印万川」(留白托月、水面倒影)。
@@ -356,6 +358,16 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask
- `vhs(bleed, shift_px, jitter, noise, scan, tracking, head)`:只作用于成片,包括 YIQ 色度模糊右移、重影振铃、逐行抖动、一条跟踪噪带、底部磁头噪声、掉磁白线、扫描线、黑位抬升;阶段快照保持干净
- 颜色常量 `MAGENTA CYAN VIOLET ORANGE YELLOW PINK RED WHITE`;字体用 `synth_font('chrome'|'script'|'caption', size)` 找系统字体(Avenir Next Heavy Italic / Brush Script / 冬青黑体),可用 `INKPAINT_FONT_CHROME` 等指定;`save('x.jpg')` 默认 quality 88、4:4:4 色度
+**拼豆 `Perler`**:
+- 思路:整张桌面是高度图,每样东西都是实体(豆是带孔短管、钉板带钉子、纸有厚度),相机略向后仰:每个屏幕像素沿自己那一列找最近的表面,所以豆子露一条侧壁、缝里露出后排侧面、孔里看得到内壁和钉子。光是左上一个大灯箱:局部点光、沿高度图步进的软阴影、天光 AO,镜面反射里看得到灯箱(亮面上是锐利的弧,熔化后变成蜡质光泽);线性空间着色,`ss` 倍超采样
+- 构造:`Perler(W, H, seed, pitch=22, tilt=0.32, ss=2, light=(x, y, z))`;pitch 是珠距(像素),tilt 是后仰量
+- 桌面与纸:`desk(颜色, kind='wood'|'mat')`;`chart(rows, key, cx, cy, cell, angle, title, subtitle, number, names, done)` 印好的图纸(格子、符号、行列号、每 5 格粗线、图例带颗数),返回对象的 `.done.update('RD')` 用铅笔勾掉已摆的颜色;`tape(字, cx, cy, angle, size, sub, badge='1')` 美纹纸标签;`sheet(draw, cx, cy, angle, thick, translucency, drape, cut, curl, bump)` 任意薄片
+- 钉板与豆:`pegboard(cx, cy, cols, rows, shape='square'|'circle'|'hexagon', colour='clear'|'white'|颜色, angle)` 返回 `Board`(钉子都在方格点上,`xy(row, col)` 取钉子位置);`place(board, rows, key, at=(行, 列), only='RDP', keep=lambda r, c: ...)` 按文字图样插豆,可按颜色、按区域分批;key 的值用 `BEADS` 色名(含 `pearl` 珠光、`clear` 透明、`glow` 夜光)或 '#rrggbb'
+- 熨烫:`ironing_paper(cx, cy, w, h, angle, cut=((x, y), (nx, ny)), curl, wrinkle)` 盖在豆上的半透明熨烫纸,cut 表示揭开一半(卷边),wrinkle 是热皱;`iron(board, melt, where)`:0.4 半熔,0.7 成品,0.8 全平;`lift_off(board)` 取下成品
+- 道具:`tray(cx, cy, [[色, ...], ...], cell, angle, fill)` 分色收纳盒(每格一堆豆);`spill(cx, cy, colours, n, spread, standing)` 散豆;`bead(x, y, 颜色, pose='stand'|'side', angle, tilt)`;`tweezers(tip, angle, length, lift, rise, holding='sky', grip)` 悬空的镊子,尖端夹一颗豆,自带投影
+- 层次与动画:`on_top(*objs)` 提到最上层,`remove(obj)` 拿走;`stage(name)` 只存快照,`save(path, stages_dir)` 时才按 1× 渲染各阶段
+- 颜色常量 `BEADS`;角度逆时针为正;`save('x.jpg')` 默认 quality 88、4:4:4 色度
+
**顺序**:都是先远后近、先大后小,文字最后叠加。水墨的雾要画在它该吞没的东西之后;水彩的叶梗要先画,并且只画在叶子外面。
## 三、毛病清单(都真实出现过)
@@ -660,6 +672,21 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask
| 小岛挡住太阳正下方,吃掉最亮的一段倒影 | 小岛只和太阳左缘略微相交 |
| 阶段快照里地平线下是整块橘色,太阳下半截露在地上 | `sky()` 先铺一层没点亮的暗色地面;太阳在地平线处截断 |
+**拼豆**
+
+| 问题 | 改法 |
+|---|---|
+| 钉板四周出现一整块深灰方框 | 豆子高度只写在豆子覆盖处(其余设 -1e3),别把整个窗口抬到板面高度 |
+| 熨过的豆还是一颗颗分开的甜甜圈,和没熨的差不多 | melt 同时控制:外半径 +22%、smooth-min 融合宽度增到 0.55 倍珠距、孔缩 74%、高度降 40%,外沿和孔口分开倒圆;0.4 是半熔(孔在、珠粘、留菱形缝),0.7 是成品 |
+| 熨平的杯垫像一块块六角螺母,表面像糖霜 | 接缝沟只在半熔时有(×(1 − m/0.7)²),顶面只留 5% 的枕形起伏,熨烫纸细纹 0.08 px |
+| 收纳盒里的豆堆成一根根塔 | 散豆落在下面的东西上,但限高约一层豆(`cap`);每格约 20 颗,按抖动网格铺开 |
+| 镊子像两根筷子、像白纸条 | 两腿成 V 形,尾部合拢、尖端张开一颗豆宽,腿宽 1.5→4.9 px;钢色偏暗,靠拉丝纹和窄的灯箱反射显出金属;悬空层单独投影 |
+| 白豆侧壁出现竖条纹、钟乳石状锯齿 | 侧壁的 AO 和阴影改从平滑图上、在墙脚和墙顶内侧取样;墙顶取最近几行的最大高度;太陡的抗锯齿斜坡按侧壁着色 |
+| 熨烫纸(缓坡)上出现发丝状细线 | 朝镜头的缓坡会把一行拉成约 1.1 屏幕行,超过 1.5 行才算侧壁 |
+| 高光要么看不见,要么每颗豆一圈白光环 | 用灯箱反射:镜面方向落在主光方向 8° 内(越粗糙越宽)才亮,得到左上沿和孔内远侧唇口两道弧;菲涅尔权重压到 0.08 |
+| 熨烫纸盖住标签,字变半透明 | 后放的会盖住先放的,用 `on_top()` 把标签、杯垫提到最上层 |
+| 图例铅笔勾挤到前一栏数量上;深绿、叶绿都印成 G | 勾直接打在豆子图标上;符号原样印,不转大写 |
+
## 四、做成动画
- 各画风都有 `stage(name)` 和 `save(path, stages_dir)`,按阶段依次淡入叠化,就是「一幅画被逐步画出来」。README 里的动图就是这样做的。
@@ -704,6 +731,7 @@ lib/newscollage.py 报刊拼贴
lib/aurora.py 弥散玻璃(弥散渐变 · 玻璃拟态)
lib/bauhaus.py 包豪斯几何(丝网印刷海报)
lib/synthwave.py 复古 Synthwave
+lib/perler.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/drawing_perler_strawberry_coaster.gif b/examples/drawing_perler_strawberry_coaster.gif
new file mode 100644
index 0000000..912b975
Binary files /dev/null and b/examples/drawing_perler_strawberry_coaster.gif differ
diff --git a/examples/perler_strawberry_coaster.jpg b/examples/perler_strawberry_coaster.jpg
new file mode 100644
index 0000000..2e1333d
Binary files /dev/null and b/examples/perler_strawberry_coaster.jpg differ
diff --git a/examples/perler_strawberry_coaster.py b/examples/perler_strawberry_coaster.py
new file mode 100644
index 0000000..fd2358c
--- /dev/null
+++ b/examples/perler_strawberry_coaster.py
@@ -0,0 +1,118 @@
+"""Example (fuse beads / 拼豆): 草莓杯垫 · Strawberry Coaster — how a bead coaster is made, left to right on a
+craft table: ① the printed pattern chart on graph paper (a strawberry in a 21-bead circle, legend with counts,
+pencil ticks on the colours already placed); ② a clear square pegboard with the same pattern half done -- the
+strawberry colours are in, the sky-blue background is going in row by row, tweezers hold the next bead above
+its peg, loose beads spilled beside; a sorting tray with a heap of every colour; ③ the finished coaster, ironed:
+the beads have flowed into one flat, waxy piece, holes shrunk, the ironing paper peeled off beside it.
+Draw-on stages: empty pegboards -> reds -> seeds and leaves -> background -> border -> ironing paper -> peeled
+-> the coaster off its board. No image model.
+python3 perler_strawberry_coaster.py [out.jpg] [--stages DIR]
+"""
+import os, sys, time
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from perler import Perler
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'perler_strawberry_coaster.jpg'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+t0 = time.time()
+
+# ---- the pattern: a strawberry on a sky-blue 21-bead circle with a white rim and a few pearl sparkles
+N = 21
+STRAWBERRY = ['......gg.....',
+ '......g......',
+ '..GGG.g.GGG..',
+ '.GGGGGgGGGGG.',
+ '..DGGGgGGGD..',
+ '.DRRGGDGGRRD.',
+ 'DRPRRDRDRRRRD',
+ 'DRPPRRRRYRRRD',
+ 'DRPRRYRRRRYRD',
+ 'DRRRRRRRRRRRD',
+ '.DRYRRRYRRRD.',
+ '.DRRRRRRRYRD.',
+ '..DRYRRRRRD..',
+ '...DRRRYRD...',
+ '....DRRRD....',
+ '.....DDD.....']
+grid = [['.'] * N for _ in range(N)]
+inside = lambda r, c: 0 <= r < N and 0 <= c < N and (r - 10) ** 2 + (c - 10) ** 2 <= 10.45 ** 2
+for r in range(N):
+ for c in range(N):
+ if inside(r, c):
+ rim = not all(inside(r + dr, c + dc) for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)))
+ grid[r][c] = 'W' if rim else 'B'
+for i, line in enumerate(STRAWBERRY):
+ for j, ch in enumerate(line):
+ if ch != '.': grid[3 + i][4 + j] = ch
+for r, c in [(2, 7), (3, 14), (6, 2), (5, 17), (11, 1), (14, 18), (17, 4), (18, 14), (9, 19)]:
+ if grid[r][c] == 'B': grid[r][c] = 'o'
+PATTERN = [''.join(row) for row in grid]
+KEY = {'R': 'red', 'D': 'dark_red', 'P': 'pink', 'Y': 'yellow', 'G': 'green', 'g': 'dark_green',
+ 'B': 'sky', 'o': 'pearl', 'W': 'white'}
+NAMES = {'R': '草莓红', 'D': '深红', 'P': '浅粉', 'Y': '柠檬黄', 'G': '叶绿', 'g': '墨绿', 'B': '天蓝',
+ 'o': '珠光白', 'W': '白'}
+
+p = Perler(1920, 1080, seed=11, pitch=22, ss=2)
+p.desk('#e0caa6')
+
+# ---- ① the chart, taped to the table
+chart = p.chart(PATTERN, KEY, 282, 338, cell=15, angle=-2.5, title='草莓杯垫', number='PATTERN No.07',
+ subtitle='STRAWBERRY COASTER · 21 x 21 · %d BEADS' % sum(len(l) - l.count('.') for l in PATTERN),
+ names=NAMES)
+t1 = p.tape('看图纸', 206, 74, angle=-4, size=24, sub='PATTERN', badge='1')
+
+# ---- sorting tray: a heap of each colour
+p.tray(292, 858, [['red', 'dark_red', 'pink'], ['yellow', 'green', 'dark_green'], ['sky', 'pearl', 'white']],
+ cell=86, angle=4, fill=20)
+
+# ---- ② the square pegboard (the one being made) and ③ the round one (the one that gets ironed)
+sq = p.pegboard(905, 468, 29, colour='clear', angle=1.2)
+rd = p.pegboard(1582, 420, 23, shape='circle', colour='#f3dfe4', angle=-6)
+t2 = p.tape('按颜色摆豆', 706, 846, angle=2, size=24, sub='PLACE', badge='2')
+t3 = p.tape('熨平 成杯垫', 1478, 738, angle=-3, size=24, sub='IRON', badge='3')
+p.stage('empty_pegboards')
+
+AT_SQ, AT_RD = (4, 4), (1, 1)
+p.place(sq, PATTERN, KEY, at=AT_SQ, only='RDP'); p.place(rd, PATTERN, KEY, at=AT_RD, only='RDP')
+chart.done.update('RDP')
+p.stage('reds')
+p.place(sq, PATTERN, KEY, at=AT_SQ, only='YGg'); p.place(rd, PATTERN, KEY, at=AT_RD, only='YGg')
+chart.done.update('YGg')
+p.stage('seeds_leaves')
+
+# the square board stops half way through the background: placed row by row from the top, row 13 half done
+front = lambda r, c: (r - AT_SQ[0]) < 13 or ((r - AT_SQ[0]) == 13 and (c - AT_SQ[1]) < 9)
+p.place(sq, PATTERN, KEY, at=AT_SQ, only='Bo', keep=front)
+p.place(rd, PATTERN, KEY, at=AT_RD, only='Bo')
+# the next bead goes on the first empty background peg along the front, lower right of the strawberry
+todo = [(r, c) for r in range(N) for c in range(N) if PATTERN[r][c] in 'Bo' and not front(r + AT_SQ[0], c + AT_SQ[1])
+ and c > 12]
+tr_, tc_ = min(todo, key=lambda rc: (rc[0], rc[1]))
+target = sq.xy(AT_SQ[0] + tr_, AT_SQ[1] + tc_)
+p.tweezers(target, angle=-38, length=330, lift=24, holding='sky')
+p.spill(1268, 912, ['sky', 'sky', 'sky', 'pearl', 'white', 'clear'], n=18, spread=62, standing=0.45)
+p.spill(560, 985, ['red', 'yellow', 'green'], n=7, spread=30, standing=0.3)
+p.stage('background')
+
+p.place(rd, PATTERN, KEY, at=AT_RD, only='W')
+p.stage('border_done')
+
+paper = p.ironing_paper(1590, 425, 600, 590, angle=4)
+p.on_top(t3)
+p.stage('ironing_paper')
+
+p.iron(rd, 0.70)
+p.remove(paper)
+paper = p.ironing_paper(1590, 425, 600, 590, angle=4, cut=((1640, 425), (np.cos(0.3), np.sin(0.3))), curl=7)
+p.on_top(t3)
+p.stage('peeled')
+
+# ---- the coaster comes off its board; the used ironing paper lies beside it
+p.remove(paper)
+p.lift_off(rd)
+p.ironing_paper(1790, 700, 330, 300, angle=14, cut=((1640, 700), (0.97, -0.24)), curl=9, wrinkle=1.8)
+p.on_top(rd, t1, t2, t3) # the coaster lies on the paper; labels stay on top
+
+p.save(out, stages)
+print(out, f'{time.time() - t0:.1f}s')
diff --git a/lib/perler.py b/lib/perler.py
new file mode 100644
index 0000000..0928ba7
--- /dev/null
+++ b/lib/perler.py
@@ -0,0 +1,1105 @@
+"""perler — fuse beads (Perler / Hama / Artkal): little plastic tubes pushed one by one onto a pegboard to make a
+pixel picture, then ironed so they melt together into one piece. Photographed from just above a craft table
+(numpy + Pillow only).
+
+Model: the table top is a *height field* (every object is solid geometry measured in output pixels) seen by a
+camera that looks almost straight down but leans back a little, so the side of anything tall shows as a sliver
+under its top. Nothing is painted as a picture of a bead; every bead is a tube and the light does the rest.
+ camera oblique projection: a point (x, y, z) lands on screen at (x, y - tilt * z). Each screen pixel walks
+ its column of the height field from the front and takes the first surface it hits, so near beads hide
+ far ones, the gap between two beads shows a sliver of the far bead's side wall, and holes show their
+ inside walls (a reverse running minimum + one searchsorted per column; no draw order involved).
+ bead a short tube: outer radius 0.47 pitch, hole radius 0.235, height 0.88, with rounded top edges. On a
+ pegboard the peg stands inside the hole, so looking down the hole you see the peg tip in the dark,
+ tinted by light that came through the bead wall. Each bead sits a little off-centre on its peg, is a
+ hair taller or shorter, and has its own shade of the colour (dye lots are never identical).
+ plastics opaque (glossy, translucent enough that shadows are coloured), pearl (iridescent sheen), clear (you
+ see the board through it; edges refract dark), glow (milky pale green).
+ pegboard a translucent plastic plate (square, circle or hexagon outline; the pegs always stand on a square
+ lattice) with a peg at every lattice point inside it; the table shows through it faintly. Empty pegs
+ stay visible wherever no bead has been placed yet.
+ ironing `melt` 0..1 per bead: the tube slumps (lower), spreads (wider), its hole closes from the rim, the
+ edges roll over and neighbours flow together (a smooth union of their outlines that grows with
+ melt), so the dark gaps shrink to little diamonds and then close, and the joined top turns into a
+ flat, pillowy, waxy sheet with the grain of the ironing paper pressed into it. `iron(board, 0.4)` is
+ the classic half-melt (holes still open, beads stuck together); 0.8 is a flat, smooth piece.
+ paper pattern charts, ironing paper and tape are thin sheets. Ironing paper drapes over the beads (a max
+ filter + blur of what is under it), is translucent, and can be peeled back with a curled edge.
+ light one big soft box up and to the left: a local point light (so a flat piece gets a sheen that drifts
+ across it), a directional march through the height field for soft cast shadows, and the box itself
+ seen in reflection -- every surface whose mirror direction points into it shows a bright patch, which
+ on a glossy tube is a crisp arc on the upper-left shoulder of the rim and on the far lip of the hole,
+ and on melted (rougher) plastic spreads into a broad waxy sheen. Sky light with ambient occlusion from
+ the height field, a little Fresnel on edges, coloured light through translucent plastic in the shade;
+ shaded in linear light with a soft highlight shoulder, rendered at `ss` x supersampling.
+ props a sorting tray with a heap of beads in every compartment, spilled beads standing on end or lying on
+ their side, tweezers held above the board with a bead in their tips (drawn as a lifted layer that
+ casts its own shadow), masking tape labels.
+
+ from perler import Perler
+ p = Perler(1920, 1080, seed=1, pitch=22)
+ p.desk('#d8c3a0')
+ b = p.pegboard(960, 540, 29, colour='clear') # 29 x 29 square board
+ p.place(b, ['.RR.', 'RRRR', '.RR.'], {'R': 'red'}, at=(10, 10)) # beads from a text pattern
+ p.stage('placed')
+ p.iron(b, 0.7) # fuse them
+ p.lift_off(b) # piece off the board
+ p.save('out.jpg')
+Coordinates are output pixels, y down; angles in degrees, counter-clockwise; heights in output pixels.
+"""
+import copy
+import os
+import numpy as np
+from PIL import Image, ImageDraw
+from core import blur, noise2d, smoothstep, load_font, height_shadow, ambient_occlusion
+
+# ---------------------------------------------------------------- colours
+BEADS = {
+ 'red': '#d3272f', 'dark_red': '#8c1726', 'pink': '#f6a0ae', 'yellow': '#f7c62b', 'orange': '#f27a24',
+ 'green': '#3a9d48', 'dark_green': '#1c6334', 'light_green': '#9ccc54', 'sky': '#7cc3e8', 'blue': '#2f63b5',
+ 'purple': '#8759b8', 'brown': '#7b4a2c', 'tan': '#d9a86c', 'cream': '#f2e3bd', 'white': '#f5f4f0',
+ 'grey': '#a3a6ab', 'black': '#26242b', 'pearl': '#efe9e3', 'clear': '#e4edf0', 'glow': '#e0f1c6',
+}
+_KIND = {'pearl': 1, 'clear': 2, 'glow': 3} # every other colour is opaque plastic
+DESK, PLASTIC, BOARD, PAPER, METAL, PEARL, CLEAR = range(7)
+
+BEAD_R, BEAD_RH, BEAD_H, BEAD_C = 0.47, 0.235, 0.88, 0.10 # outer radius, hole radius, height, edge round (x pitch)
+PEG_R, PEG_H, PLATE_T = 0.17, 0.50, 0.34 # peg radius, peg height, plate thickness (x pitch)
+
+
+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):
+ if isinstance(c, str): return hexc(BEADS.get(c, c))
+ return np.asarray(c, np.float32)
+
+
+def _lin(c):
+ return np.power(np.clip(c, 0, 1), 2.2).astype(np.float32)
+
+
+def _shoulder(e, h, c, aa):
+ """height of a flat-topped wall at distance e inside its edge: a vertical side, top corner rounded with radius c"""
+ c = np.maximum(c, 1e-3)
+ ec = np.clip(e, 0, c)
+ top = h - c + np.sqrt(np.maximum(c * c - (c - ec) ** 2, 0))
+ return np.maximum(top, 0) * np.clip(e / aa + 0.5, 0, 1)
+
+
+def _smin(a, b, k):
+ """polynomial smooth minimum: outlines closer than k flow into each other"""
+ k = np.maximum(k, 1e-4)
+ h = np.clip(0.5 + 0.5 * (b - a) / k, 0, 1)
+ return b * (1 - h) + a * h - k * h * (1 - h)
+
+
+def _maxf(a, r):
+ """box max filter (radius r px) via shifted maxima"""
+ r = int(r)
+ if r < 1: return a
+ o = a.copy()
+ for d in range(1, r + 1):
+ o[:, d:] = np.maximum(o[:, d:], a[:, :-d]); o[:, :-d] = np.maximum(o[:, :-d], a[:, d:])
+ a = o; o = a.copy()
+ for d in range(1, r + 1):
+ o[d:] = np.maximum(o[d:], a[:-d]); o[:-d] = np.maximum(o[:-d], a[d:])
+ return o
+
+
+def _blur3(a, sigma):
+ """core.blur on each channel of an (h, w, 3) array"""
+ return np.stack([blur(a[..., i], sigma) for i in range(a.shape[-1])], -1)
+
+
+def _font(style, size):
+ return load_font(style, max(6, int(round(size))))
+
+
+# ---------------------------------------------------------------- the canvas that objects are rasterised into
+class _Canvas:
+ """height field + material maps at `S` x supersampling. z is in output px; x, y indices are internal px."""
+
+ def __init__(self, W, H, S, tilt, zmax):
+ self.S, self.k = S, tilt
+ self.W, self.H = W * S, H * S
+ self.Hm = self.H + int(np.ceil(tilt * zmax * S)) + 4 * S # world rows below the frame still show up
+ Hm, Wm = self.Hm, self.W
+ self.z = np.zeros((Hm, Wm), np.float32)
+ self.alb = np.zeros((Hm, Wm, 3), np.float32) # linear albedo
+ self.spec = np.zeros((Hm, Wm), np.float32)
+ self.rough = np.ones((Hm, Wm), np.float32)
+ self.trans = np.zeros((Hm, Wm), np.float32) # how much light the stuff lets through
+ self.mat = np.zeros((Hm, Wm), np.uint8)
+ self.over = [] # lifted layers (tweezers)
+
+ def win(self, x0, y0, x1, y1):
+ """window in output px -> (slices, X, Y) with X, Y the pixel centres in output px"""
+ S = self.S
+ a0, a1 = max(0, int(np.floor(x0 * S))), min(self.W, int(np.ceil(x1 * S)))
+ b0, b1 = max(0, int(np.floor(y0 * S))), min(self.Hm, int(np.ceil(y1 * S)))
+ if a1 <= a0 or b1 <= b0: return None
+ X = ((np.arange(a0, a1, dtype=np.float32) + 0.5) / S)[None, :]
+ Y = ((np.arange(b0, b1, dtype=np.float32) + 0.5) / S)[:, None]
+ return (slice(b0, b1), slice(a0, a1)), X, Y
+
+ def put(self, sl, znew, alb, spec, rough, mat, trans=0.0):
+ """lay a surface down wherever it rises above what is already there (soft over ~0.7 internal px)"""
+ zo = self.z[sl]
+ a = np.clip((znew - zo) * self.S / 0.7, 0, 1)
+ self.z[sl] = np.maximum(zo, znew)
+ a3 = a[..., None]
+ self.alb[sl] = self.alb[sl] * (1 - a3) + np.asarray(alb, np.float32) * a3
+ self.spec[sl] = self.spec[sl] * (1 - a) + spec * a
+ self.rough[sl] = self.rough[sl] * (1 - a) + rough * a
+ self.trans[sl] = self.trans[sl] * (1 - a) + trans * a
+ self.mat[sl] = np.where(a > 0.5, mat, self.mat[sl]).astype(np.uint8)
+ return a
+
+ def paste(self, im, cx, cy, angle):
+ """rotate an RGBA image about its centre and place it at (cx, cy) output px -> (slices, rgba array) or None"""
+ if angle: im = im.rotate(angle, resample=Image.BICUBIC, expand=True)
+ w, h = im.size
+ x0, y0 = int(round(cx * self.S - w / 2)), int(round(cy * self.S - h / 2))
+ a0, b0 = max(0, x0), max(0, y0)
+ a1, b1 = min(self.W, x0 + w), min(self.Hm, y0 + h)
+ if a1 <= a0 or b1 <= b0: return None
+ arr = np.asarray(im, np.float32)[b0 - y0:b1 - y0, a0 - x0:a1 - x0] / 255
+ return (slice(b0, b1), slice(a0, a1)), arr
+
+
+# ---------------------------------------------------------------- beads on a lattice (the heart of the style)
+def _lattice(cv, sl, u, v, p, occ, col, kind, melt, jit, base):
+ """beads whose centres sit on integer (u, v); melt fuses neighbours. Writes into the canvas window `sl`."""
+ R_, C_ = occ.shape
+ S = cv.S
+ aa = 1.0 / S
+ i0, j0 = np.floor(u).astype(np.int32), np.floor(v).astype(np.int32)
+ occf, meltf = occ.ravel(), melt.ravel()
+ SD, RR, ID = [], [], []
+ for a in (0, 1):
+ for b in (0, 1):
+ ci, rj = i0 + a, j0 + b
+ ok = (ci >= 0) & (ci < C_) & (rj >= 0) & (rj < R_)
+ idx = np.clip(rj, 0, R_ - 1) * C_ + np.clip(ci, 0, C_ - 1)
+ ok &= occf[idx]
+ m = meltf[idx]
+ r = np.hypot(u - ci - jit[..., 0].ravel()[idx], v - rj - jit[..., 1].ravel()[idx]) * p
+ sd = np.where(ok, r - BEAD_R * p * (1 + 0.22 * m), 1e4)
+ SD.append(sd.astype(np.float32)); RR.append(r.astype(np.float32)); ID.append(np.where(ok, idx, -1))
+ SD, RR, ID = np.stack(SD), np.stack(RR), np.stack(ID)
+ if not (ID >= 0).any(): return
+ own = np.argmin(SD, 0)[None]
+ sd1 = np.take_along_axis(SD, own, 0)[0]
+ r_own = np.take_along_axis(RR, own, 0)[0]
+ i_own = np.take_along_axis(ID, own, 0)[0]
+ have = i_own >= 0
+ io = np.maximum(i_own, 0)
+ m = meltf[io] * have
+ mm = np.max(np.where(ID >= 0, meltf[np.maximum(ID, 0)], 0), 0)
+ kk = (0.012 + 0.55 * mm) * p # outlines flow together as they melt
+ order = np.argsort(SD, 0)
+ Ss = np.take_along_axis(SD, order, 0)
+ sdu = Ss[0]
+ for q in (1, 2, 3): sdu = _smin(sdu, Ss[q], kk)
+ sdu = np.where(have, sdu, 1e4)
+ rh = BEAD_RH * p * (1 - 0.74 * m)
+ hb = BEAD_H * p * (1 - 0.40 * m) * (1 + jit[..., 2].ravel()[io])
+ e_in = r_own - rh
+ e = np.minimum(-sdu, e_in)
+ c_out = BEAD_C * p * (1 + 0.6 * m) # the piece's outer edge rolls over
+ c_in = BEAD_C * p * (1 + 1.3 * m) # molten plastic slumps into the hole
+ prof = np.minimum(_shoulder(-sdu, hb, c_out, aa), _shoulder(e_in, hb, c_in, aa))
+ if mm.max() > 0:
+ # melted top: each bead slumps into a low pillow around its closing hole; seams stay as faint grooves;
+ # the grain of the ironing paper is pressed into the plastic
+ pil = 1 - 0.05 * m * np.clip(r_own / (0.55 * p), 0, 1.4) ** 2
+ seam = np.exp(-((Ss[1] - Ss[0]) / (0.05 * p)) ** 2) * (Ss[1] < 0.2 * p)
+ groove = 0.06 * BEAD_H * p * seam * np.clip(1 - m / 0.7, 0, 1) ** 2 * (m > 0)
+ hh, ww = prof.shape
+ grain = (noise2d(hh, ww, 2.2 * S, 2, int(p * 1000) % 9973) - 0.5) * 0.08 + \
+ (noise2d(hh, ww, 30 * S, 3, 77) - 0.5) * 0.7
+ prof = np.where(prof > 0, prof * pil - groove + grain * m * (prof > 0.5 * hb), prof)
+ # colours: soft blend across seams, per-bead dye-lot shade
+ wq = np.exp(-np.clip(SD - sd1[None], 0, 30) / (0.6 / S)) * (ID >= 0)
+ colf = col.reshape(-1, 3)
+ albb = (wq[..., None] * colf[np.maximum(ID, 0)]).sum(0) / np.maximum(wq.sum(0), 1e-6)[..., None]
+ kd = kind.ravel()[io]
+ under = cv.alb[sl].copy()
+ # looking down a hole: the peg / table in there is lit through the coloured wall
+ hole_w = (np.clip(-e_in * S, 0, 1) * have * (r_own < BEAD_R * p))[..., None]
+ cv.alb[sl] = under * (1 - hole_w) + under * (0.22 + 0.78 * albb) * 0.8 * hole_w
+ alb = albb.copy()
+ clear = (kd == 2)[..., None]
+ if clear.any():
+ wall = BEAD_R * p - BEAD_RH * p
+ rim = np.exp(-(np.clip(e, 0, None) / (0.18 * wall)) ** 2)[..., None]
+ alb = np.where(clear, (0.35 * albb + 0.65 * under * 1.08) * (1 - 0.45 * rim), alb)
+ glow = (kd == 3)[..., None]
+ if glow.any(): alb = np.where(glow, 0.8 * albb + 0.2 * under, alb)
+ mat = np.select([kd == 1, kd == 2], [PEARL, CLEAR], PLASTIC).astype(np.uint8)
+ spec = np.select([kd == 1, kd == 2], [0.45, 0.85], 0.55) * (1 - 0.25 * m)
+ rough = np.select([kd == 1, kd == 2], [0.30, 0.06], 0.16) + 0.30 * m
+ trans = np.select([kd == 2, kd == 3], [0.0, 0.9], 0.55)
+ cv.put(sl, np.where(prof > 0, base + prof, -1e3), alb, spec, rough, mat, trans)
+
+
+def _stamp_bead(cv, x, y, col, pose, ang, tilt, p, sink=0.3, base=None, layer=None, floor=None, cap=1.3):
+ """one loose bead: standing on end (a ring, maybe tipped) or lying on its side. Lands on whatever is under it."""
+ tgt = layer if layer is not None else cv
+ w = cv.win(x - p, y - p, x + p, y + p) if layer is None else layer.win(x - p, y - p, x + p, y + p)
+ if w is None: return
+ sl, X, Y = w
+ S = cv.S
+ aa = 1.0 / S
+ zo = tgt.z[sl]
+ if base is None:
+ rr = np.hypot(X - x, Y - y)
+ near = rr < BEAD_R * p * 0.9
+ base = (zo[near].max() if near.any() else 0.0) - sink * BEAD_R * p
+ base = max(base, float(zo[near].min()) if near.any() else 0.0)
+ if floor is not None: base = min(base, floor + cap * BEAD_H * p * 0.62)
+ ca, sa = np.cos(np.radians(ang)), np.sin(np.radians(ang))
+ dx, dy = X - x, Y - y
+ t = dx * ca - dy * sa # along the tilt / lying axis (screen, ccw angle)
+ s = dx * sa + dy * ca
+ c = _c(col)
+ R = BEAD_R * p
+ if pose == 'side':
+ L = BEAD_H * p
+ et = L / 2 - np.abs(t)
+ ce = 0.16 * p
+ fe = np.sqrt(np.clip(1 - (1 - np.clip(et / ce, 0, 1)) ** 2, 0, 1))
+ top = np.sqrt(np.maximum(R * R - s * s, 0))
+ cov = np.clip((R - np.abs(s)) / aa + 0.5, 0, 1) * np.clip(et / aa + 0.5, 0, 1)
+ prof = (R * 0.9 + top) * fe * cov
+ # a tube lying down shows its hole at the ends as a dark ring on the end face
+ endh = np.clip(1 - np.hypot(s / (BEAD_RH * p), (np.abs(t) - L / 2 + 0.02 * p) / (0.13 * p)), 0, 1)
+ shade = 1 - 0.55 * np.clip(endh * 3, 0, 1)
+ alb = _lin(c)[None, None] * shade[..., None]
+ else:
+ ct = np.cos(tilt)
+ r = np.hypot(t / ct, s)
+ e = np.minimum(R - r, r - BEAD_RH * p)
+ prof = _shoulder(e, BEAD_H * p * ct, BEAD_C * p, aa)
+ prof = np.where(prof > 0, prof + t * np.sin(tilt) * 0.9, 0)
+ alb = np.broadcast_to(_lin(c)[None, None], prof.shape + (3,)).copy()
+ inh = ((r < BEAD_RH * p) & (r < R))[..., None]
+ tgt.alb[sl] = np.where(inh, tgt.alb[sl] * (0.22 + 0.78 * _lin(c)) * 0.75, tgt.alb[sl])
+ kd = _KIND.get(col, 0) if isinstance(col, str) else 0
+ if kd == 2 and pose != 'side':
+ rim = np.exp(-(np.clip(np.minimum(R - r, r - BEAD_RH * p), 0, None) / (0.05 * p)) ** 2)[..., None]
+ alb = (0.22 * alb + 0.78 * tgt.alb[sl] * 1.05) * (1 - 0.5 * rim)
+ elif kd == 2: alb = 0.3 * alb + 0.7 * tgt.alb[sl] * 1.08
+ mat = {1: PEARL, 2: CLEAR}.get(kd, PLASTIC)
+ spec = {1: 0.45, 2: 0.85}.get(kd, 0.55)
+ rough = {1: 0.3, 2: 0.06}.get(kd, 0.16)
+ zn = np.where(prof > 0, base + prof, -1e3)
+ if layer is not None:
+ layer.put(sl, zn, alb, spec, rough, mat, thick=np.where(prof > 0, prof + 2, 0))
+ else:
+ cv.put(sl, zn, alb, spec, rough, mat, 0.9 if kd == 3 else (0.0 if kd == 2 else 0.55))
+
+
+# ---------------------------------------------------------------- scene objects
+class _Desk:
+ def __init__(self, colour, kind, seed):
+ self.c, self.kind, self.seed = _c(colour), kind, seed
+
+ def raster(self, cv):
+ Hm, Wm, S = cv.Hm, cv.W, cv.S
+ base = _lin(self.c)
+ if self.kind == 'wood':
+ lo = noise2d(Hm, max(16, Wm // 14), 40 * S, 4, self.seed)
+ lo = np.asarray(Image.fromarray(lo).resize((Wm, Hm), Image.BICUBIC), np.float32)
+ y = np.arange(Hm, dtype=np.float32)[:, None] / S
+ ring = 0.5 + 0.5 * np.sin(2 * np.pi * (y / 11.0 + 5.5 * lo))
+ fine = noise2d(Hm, max(16, Wm // 40), 3 * S, 2, self.seed + 1)
+ fine = np.asarray(Image.fromarray(fine).resize((Wm, Hm), Image.BILINEAR), np.float32)
+ blot = noise2d(Hm, Wm, 220 * S, 3, self.seed + 2)
+ v = 1 - 0.07 * ring ** 3 - 0.05 * (fine - 0.5) - 0.07 * (blot - 0.5)
+ cv.alb[:] = base[None, None] * v[..., None]
+ cv.alb[..., 0] *= 1 + 0.04 * ring ** 3
+ cv.spec[:], cv.rough[:] = 0.06, 0.55
+ else: # a plain craft mat
+ n = noise2d(Hm, Wm, 3 * S, 2, self.seed) - 0.5
+ blot = noise2d(Hm, Wm, 260 * S, 3, self.seed + 2) - 0.5
+ cv.alb[:] = base[None, None] * (1 + 0.035 * n + 0.05 * blot)[..., None]
+ cv.spec[:], cv.rough[:] = 0.03, 0.8
+ cv.z[:] = 0
+ cv.mat[:] = DESK
+
+
+class _Sheet:
+ """any thin flat thing drawn with PIL: a chart, a card, a strip of tape, ironing paper"""
+
+ def __init__(self, draw, cx, cy, angle, thick=0.9, translucency=0.0, drape=0.0, spec=0.03, rough=0.85,
+ cut=None, curl=0.0, bump=0.0, seed=0):
+ self.draw, self.cx, self.cy, self.angle = draw, cx, cy, angle
+ self.thick, self.tr, self.drape, self.spec, self.rough = thick, translucency, drape, spec, rough
+ self.cut, self.curl, self.bump, self.seed = cut, curl, bump, seed
+ self.data = {}
+ self.hidden = False
+
+ def raster(self, cv):
+ if self.hidden: return
+ code = self.draw.__code__
+ im = self.draw(cv.S, data=self.data) if 'data' in code.co_varnames[:code.co_argcount] else self.draw(cv.S)
+ got = cv.paste(im, self.cx, self.cy, self.angle)
+ if got is None: return
+ sl, arr = got
+ a = arr[..., 3]
+ if self.cut is not None: # peeled back: only the part past a line stays
+ (px, py), (nx, ny) = self.cut
+ yy, xx = np.mgrid[sl[0], sl[1]].astype(np.float32) / cv.S
+ d = (xx - px) * nx + (yy - py) * ny # > 0 keeps
+ a = a * np.clip(d * cv.S + 0.5, 0, 1)
+ zo = cv.z[sl]
+ if self.drape:
+ r = int(self.drape * cv.S)
+ base = blur(_maxf(zo, r), 0.8 * r)
+ else:
+ base = zo
+ lift = 0
+ if self.cut is not None and self.curl:
+ lift = self.curl * np.exp(-np.clip(d, 0, None) / 9.0) * (d > -1)
+ if self.bump: # heat-wrinkled: a low, soft cockle
+ hh, ww = a.shape
+ lift = lift + self.bump * (noise2d(hh, ww, 32 * cv.S, 3, self.seed % 9973) - 0.5) * 2 + self.bump
+ rgb = _lin(arr[..., :3])
+ if self.tr: rgb = rgb * (1 - self.tr) + cv.alb[sl] * self.tr * 1.05
+ cv.put(sl, np.where(a > 0.02, base + (self.thick + lift) * a, -1), rgb, self.spec, self.rough, PAPER,
+ 0.25 if self.tr else 0.0)
+
+
+class Board:
+ """a pegboard and the beads on it. Returned by Perler.pegboard(); cells are (row, col)."""
+
+ def __init__(self, cx, cy, cols, rows, shape, colour, angle, pitch, translucency, seed):
+ self.cx, self.cy, self.cols, self.rows = cx, cy, cols, rows
+ self.shape, self.colour, self.angle, self.pitch, self.tr = shape, _c(colour), angle, pitch, translucency
+ r = np.random.default_rng(seed)
+ self.seed = seed
+ self.occ = np.zeros((rows, cols), bool)
+ self.col = np.zeros((rows, cols, 3), np.float32)
+ self.kind = np.zeros((rows, cols), np.int32)
+ self.melt = np.zeros((rows, cols), np.float32)
+ self.jit = np.stack([r.normal(0, 0.022, (rows, cols)), r.normal(0, 0.022, (rows, cols)),
+ r.normal(0, 0.018, (rows, cols))], -1).astype(np.float32)
+ self.shade = r.normal(0, 1, (rows, cols, 2)).astype(np.float32)
+ self.plate = True
+ vv, uu = np.mgrid[0:rows, 0:cols].astype(np.float32)
+ cu, cr = (cols - 1) / 2, (rows - 1) / 2
+ if shape == 'circle':
+ self.pegs = np.hypot(uu - cu, vv - cr) <= min(cols, rows) / 2 - 0.3
+ elif shape == 'hexagon': # flat-topped hexagon
+ q, w = np.abs(uu - cu), np.abs(vv - cr)
+ self.pegs = np.maximum(w, q * 0.866 + w * 0.5) <= (min(cols, rows) / 2 - 0.3) * 0.866
+ else:
+ self.pegs = np.ones((rows, cols), bool)
+
+ def xy(self, row, col):
+ """output-px position of the peg at (row, col) (its foot on the board)"""
+ a = np.radians(self.angle)
+ lx, ly = (col - (self.cols - 1) / 2) * self.pitch, (row - (self.rows - 1) / 2) * self.pitch
+ return (self.cx + lx * np.cos(a) + ly * np.sin(a), self.cy - lx * np.sin(a) + ly * np.cos(a))
+
+ def top(self):
+ return PLATE_T * self.pitch if self.plate else 0.0
+
+ def raster(self, cv):
+ p, S = self.pitch, cv.S
+ a = np.radians(self.angle)
+ ca, sa = np.cos(a), np.sin(a)
+ margin = 0.42 * p
+ half = 0.5 * np.hypot(self.cols, self.rows) * p + margin + 4
+ w = cv.win(self.cx - half, self.cy - half, self.cx + half, self.cy + half)
+ if w is None: return
+ sl, X, Y = w
+ dx, dy = X - self.cx, Y - self.cy
+ lx, ly = dx * ca - dy * sa, dx * sa + dy * ca # board-local px
+ u = lx / p + (self.cols - 1) / 2
+ v = ly / p + (self.rows - 1) / 2
+ zo = cv.z[sl]
+ base = float(np.median(zo))
+ aa = 1.0 / S
+ if self.plate:
+ hx, hy = self.cols * p / 2 + margin, self.rows * p / 2 + margin
+ if self.shape == 'circle':
+ sd = np.hypot(lx, ly) - (min(self.cols, self.rows) / 2 * p + margin * 0.6)
+ elif self.shape == 'hexagon':
+ rr = min(self.cols, self.rows) / 2 * p + margin * 0.6
+ q, w_ = np.abs(lx), np.abs(ly)
+ sd = np.maximum(w_, q * 0.866 + w_ * 0.5) - rr * 0.866
+ else:
+ rc = 0.9 * p
+ qx, qy = np.abs(lx) - hx + rc, np.abs(ly) - hy + rc
+ sd = np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) + np.minimum(np.maximum(qx, qy), 0) - rc
+ tb = PLATE_T * p
+ plate = _shoulder(-sd, tb, 0.45 * tb, aa)
+ iu, iv = np.rint(u).astype(np.int32), np.rint(v).astype(np.int32)
+ ok = (iu >= 0) & (iu < self.cols) & (iv >= 0) & (iv < self.rows)
+ ok &= self.pegs[np.clip(iv, 0, self.rows - 1), np.clip(iu, 0, self.cols - 1)]
+ rp = np.hypot(u - iu, v - iv) * p
+ peg = _shoulder(PEG_R * p - rp, PEG_H * p, 0.8 * PEG_R * p, aa) * ok * (plate > 0.9 * tb)
+ under = _blur3(cv.alb[sl], 3 * S)
+ bc = _lin(self.colour)[None, None]
+ n = noise2d(zo.shape[0], zo.shape[1], 5 * S, 2, self.seed % 9973)[..., None]
+ alb = bc * (1 - self.tr) + under * self.tr * 1.15
+ alb = alb * (0.985 + 0.03 * n)
+ alb = np.where((peg > 0.3)[..., None], alb * 0.9 + bc * 0.12, alb)
+ cv.put(sl, np.where(plate > 0, base + plate + peg, -1), alb, 0.30, 0.30, BOARD, 0.6)
+ zb = base + tb
+ else:
+ zb = np.maximum(blur(zo, 2 * S), zo) # off the board: sits on the table
+ if self.occ.any():
+ _lattice(cv, sl, u, v, p, self.occ, _lin(self.col), self.kind, self.melt, self.jit, zb)
+
+
+class _Tray:
+ def __init__(self, cx, cy, cols, rows, cell, angle, colour, seed):
+ self.cx, self.cy, self.cols, self.rows, self.cell = cx, cy, cols, rows, cell
+ self.angle, self.colour, self.seed = angle, _c(colour), seed
+ self.wall, self.h = 0.12 * cell, 0.26 * cell
+
+ def local_to_xy(self, lx, ly):
+ a = np.radians(self.angle)
+ return self.cx + lx * np.cos(a) + ly * np.sin(a), self.cy - lx * np.sin(a) + ly * np.cos(a)
+
+ def raster(self, cv):
+ S, a = cv.S, np.radians(self.angle)
+ W2, H2 = self.cols * self.cell / 2 + self.wall, self.rows * self.cell / 2 + self.wall
+ half = np.hypot(W2, H2) + 6
+ w = cv.win(self.cx - half, self.cy - half, self.cx + half, self.cy + half)
+ if w is None: return
+ sl, X, Y = w
+ dx, dy = X - self.cx, Y - self.cy
+ lx, ly = dx * np.cos(a) - dy * np.sin(a), dx * np.sin(a) + dy * np.cos(a)
+ rc = 0.18 * self.cell
+ qx, qy = np.abs(lx) - W2 + rc, np.abs(ly) - H2 + rc
+ sd = np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) + np.minimum(np.maximum(qx, qy), 0) - rc
+ aa = 1.0 / S
+ e_out = np.minimum(-sd, self.wall + sd)
+ e = e_out
+ for i in range(1, self.cols):
+ e = np.maximum(e, np.minimum(self.wall / 2 - np.abs(lx - (-W2 + self.wall + i * self.cell)), -sd))
+ for j in range(1, self.rows):
+ e = np.maximum(e, np.minimum(self.wall / 2 - np.abs(ly - (-H2 + self.wall + j * self.cell)), -sd))
+ walls = _shoulder(e, self.h, 0.4 * self.wall, aa)
+ floor = _shoulder(-sd, 1.6, 0.8, aa)
+ zo = cv.z[sl]
+ under = _blur3(cv.alb[sl], 3 * S)
+ bc = _lin(self.colour)[None, None]
+ wallish = (walls > 0.5)[..., None]
+ alb = np.where(wallish, bc * 0.8 + under * 0.25, bc * 0.45 + under * 0.62)
+ cv.put(sl, np.where(np.maximum(walls, floor) > 0, zo + np.maximum(walls, floor), -1), alb, 0.35, 0.25,
+ BOARD, 0.7)
+
+
+class _Beads:
+ """a set of loose beads (a spill, a heap in a tray compartment, one bead) rastered in order, so they stack;
+ floor: the surface they were poured onto (heaps stay low: at most `cap` bead layers)"""
+
+ def __init__(self, items, pitch, floor=None, cap=1.3):
+ self.items, self.p, self.floor, self.cap = items, pitch, floor, cap
+
+ def raster(self, cv):
+ for (x, y, col, pose, ang, tilt) in self.items:
+ _stamp_bead(cv, x, y, col, pose, ang, tilt, self.p, floor=self.floor, cap=self.cap)
+
+
+class _Layer:
+ """something held in the air: its own little height field, drawn after the scene with its own cast shadow"""
+
+ def __init__(self, cv, x0, y0, x1, y1):
+ self.cv = cv
+ w = cv.win(x0, y0, x1, y1)
+ self.sl, self.X, self.Y = w
+ h, ww = self.Y.shape[0], self.X.shape[1]
+ self.z = np.full((h, ww), -1e3, np.float32)
+ self.alb = np.zeros((h, ww, 3), np.float32)
+ self.spec = np.zeros((h, ww), np.float32)
+ self.rough = np.ones((h, ww), np.float32)
+ self.mat = np.zeros((h, ww), np.uint8)
+ self.thick = np.zeros((h, ww), np.float32)
+
+ def win(self, x0, y0, x1, y1):
+ S = self.cv.S
+ b0, a0 = self.sl[0].start, self.sl[1].start
+ c0, c1 = max(0, int(np.floor(x0 * S)) - a0), min(self.z.shape[1], int(np.ceil(x1 * S)) - a0)
+ r0, r1 = max(0, int(np.floor(y0 * S)) - b0), min(self.z.shape[0], int(np.ceil(y1 * S)) - b0)
+ if c1 <= c0 or r1 <= r0: return None
+ return (slice(r0, r1), slice(c0, c1)), self.X[:, c0:c1], self.Y[r0:r1]
+
+ def put(self, sl, znew, alb, spec, rough, mat, thick):
+ up = znew > self.z[sl]
+ self.z[sl] = np.where(up, znew, self.z[sl])
+ self.alb[sl] = np.where(up[..., None], alb, self.alb[sl])
+ self.spec[sl] = np.where(up, spec, self.spec[sl])
+ self.rough[sl] = np.where(up, rough, self.rough[sl])
+ self.mat[sl] = np.where(up, mat, self.mat[sl])
+ self.thick[sl] = np.where(up, thick, self.thick[sl])
+
+
+class _Tweezers:
+ def __init__(self, tip, angle, length, lift, rise, holding, grip, open_w, pitch, seed):
+ self.tip, self.angle, self.L, self.lift, self.rise = tip, angle, length, lift, rise
+ self.holding, self.grip, self.open, self.p, self.seed = holding, grip, open_w, pitch, seed
+
+ def raster(self, cv):
+ S, p = cv.S, self.p
+ a = np.radians(self.angle)
+ ux, uy = np.cos(a), -np.sin(a) # from the tip toward the hinge
+ tx, ty = self.tip
+ ex, ey = tx + ux * self.L, ty + uy * self.L
+ pad = 30
+ ly = _Layer(cv, min(tx, ex) - pad, min(ty, ey) - pad, max(tx, ex) + pad, max(ty, ey) + pad)
+ X, Y = ly.X, ly.Y
+ dx, dy = X - tx, Y - ty
+ t = dx * ux + dy * uy # along, 0 at the tip
+ s = -dx * uy + dy * ux # across
+ L = self.L
+ tt = np.clip(t / L, 0, 1)
+ gap = self.open # tip opening (centre to centre)
+ wleg = 1.5 + 3.4 * tt ** 0.7 # half width of each leg
+ sc = (gap / 2) * (1 - tt) + wleg * 0.97 * tt # legs meet at the hinge
+ zplane = self.lift + self.rise * t
+ best = np.full(t.shape, -1.0, np.float32)
+ for sign in (-1, 1):
+ d = np.abs(s - sign * sc)
+ e = wleg - d
+ best = np.maximum(best, e)
+ inside = (t > -0.5) & (t < L)
+ et = np.minimum(t + 0.5, L - t)
+ e = np.minimum(best, et)
+ grip0, grip1 = 0.42 * L, 0.78 * L
+ gr = (t > grip0) & (t < grip1)
+ th = np.where(gr, 3.6, 2.6)
+ aa = 1.0 / S
+ prof = _shoulder(e, th, np.where(gr, 1.6, 0.9), aa) * inside
+ # stainless: brushed along the leg; a rubber grip sleeve in the middle with ribs
+ streak = noise2d(prof.shape[0], prof.shape[1], 2.0 * S, 2, self.seed % 9973)
+ streak = 0.5 + 0.5 * np.sin(2 * np.pi * (s / 2.3 + 3 * streak)) # brushed along the leg
+ metal = np.array([0.46, 0.47, 0.50], np.float32)[None, None] * (0.72 + 0.45 * streak[..., None])
+ ribs = 0.5 + 0.5 * np.cos(2 * np.pi * t / 5.0)
+ gc = _lin(_c(self.grip))[None, None] * (0.85 + 0.2 * ribs[..., None])
+ alb = np.where(gr[..., None], gc, metal)
+ mat = np.where(gr, PLASTIC, METAL).astype(np.uint8)
+ spec = np.where(gr, 0.25, 0.9)
+ rough = np.where(gr, 0.45, 0.12)
+ ly.put((slice(None), slice(None)), np.where(prof > 0.05, zplane + prof, -1e3), alb, spec, rough, mat,
+ np.where(prof > 0, prof + 0.5, 0))
+ if self.holding:
+ bx, by = tx + ux * 0.25 * p, ty + uy * 0.25 * p
+ _stamp_bead(cv, bx, by, self.holding, 'stand', self.angle, 0.12, p,
+ base=self.lift - BEAD_H * p * 0.45, layer=ly)
+ cv.over.append(ly)
+
+
+# ---------------------------------------------------------------- the painter
+class Perler:
+ def __init__(self, W=1920, H=1080, seed=0, pitch=22.0, tilt=0.32, ss=2, light=(-350.0, -520.0, 2300.0)):
+ self.W, self.H, self.seed = W, H, seed
+ self.rng = np.random.default_rng(seed)
+ self.pitch, self.tilt, self.ss = float(pitch), float(tilt), int(ss)
+ self.light = np.array(light, np.float32)
+ self.objs, self.stages = [], []
+ self.zmax = 3.4 * pitch
+ self.stage_ss = 1
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ # ---- surfaces
+ def desk(self, colour='#dcc5a0', kind='wood'):
+ """the table top: 'wood' (pale oak, long grain) or 'mat' (a plain craft mat)"""
+ o = _Desk(colour, kind, self._seed()); self.objs.append(o); return o
+
+ def sheet(self, draw, cx, cy, angle=0.0, **kw):
+ """a thin flat thing: draw(S) (or draw(S, data), data = the returned object's .data dict) returns an RGBA PIL
+ image at S x scale. kw: thick, translucency, drape (px: rests on what is under it), cut, curl, bump"""
+ o = _Sheet(draw, cx, cy, angle, **kw); self.objs.append(o); return o
+
+ def pegboard(self, cx, cy, cols, rows=None, shape='square', colour='clear', angle=0.0, translucency=None):
+ """a pegboard; colour 'clear' is frosted clear plastic (the table shows through), or any colour"""
+ colour_ = {'clear': '#e9eef0', 'white': '#f2f1ee'}.get(colour, colour)
+ tr = translucency if translucency is not None else (0.62 if colour == 'clear' else 0.18)
+ b = Board(cx, cy, cols, rows or cols, shape, colour_, angle, self.pitch, tr, self._seed())
+ self.objs.append(b); return b
+
+ def place(self, board, rows, key, at=(0, 0), only=None, keep=None):
+ """put beads on `board` from a text pattern: rows of characters, key maps a character to a bead colour
+ name (BEADS) or '#rrggbb'. only: the characters to place now (placing colour by colour); keep(r, c) -> bool
+ filters cells (e.g. only the part done so far). Returns the number of beads placed."""
+ n = 0
+ for i, line in enumerate(rows):
+ for j, ch in enumerate(line):
+ if ch not in key or (only is not None and ch not in only): continue
+ rr, cc = at[0] + i, at[1] + j
+ if not (0 <= rr < board.rows and 0 <= cc < board.cols) or not board.pegs[rr, cc]: continue
+ if keep is not None and not keep(rr, cc): continue
+ name = key[ch]
+ c = _c(name)
+ sh = board.shade[rr, cc]
+ c = np.clip(c * (1 + 0.035 * sh[0]) + 0.012 * sh[1], 0, 1) # dye-lot variation
+ board.occ[rr, cc] = True
+ board.col[rr, cc] = c
+ board.kind[rr, cc] = _KIND.get(name, 0) if isinstance(name, str) else 0
+ n += 1
+ return n
+
+ def iron(self, board, melt=0.7, where=None):
+ """iron the beads on `board`: melt 0.35-0.5 is the half-melt (holes open, beads stuck together), 0.8 is
+ flat and smooth. where(r, c) -> bool irons only part (the rest stays as it was)."""
+ for rr in range(board.rows):
+ for cc in range(board.cols):
+ if board.occ[rr, cc] and (where is None or where(rr, cc)):
+ board.melt[rr, cc] = melt
+
+ def lift_off(self, board):
+ """take the ironed piece off its pegboard: the plate and pegs go, the piece lies on the table"""
+ board.plate = False
+
+ def tray(self, cx, cy, colours, cell=100.0, angle=0.0, colour='#eef2f3', fill=20):
+ """a sorting tray with a compartment per colour (colours: list of rows), each holding a heap of beads"""
+ rows, cols = len(colours), max(len(r) for r in colours)
+ t = _Tray(cx, cy, cols, rows, cell, angle, colour, self._seed())
+ self.objs.append(t)
+ r = np.random.default_rng(self._seed())
+ items = []
+ W2, H2 = cols * cell / 2 + t.wall, rows * cell / 2 + t.wall
+ for j, row in enumerate(colours):
+ for i, name in enumerate(row):
+ if not name: continue
+ x0 = -W2 + t.wall * 1.5 + i * cell; y0 = -H2 + t.wall * 1.5 + j * cell
+ inner = cell - t.wall * 2 - BEAD_R * self.pitch * 2
+ cx0, cy0 = x0 + BEAD_R * self.pitch + inner / 2, y0 + BEAD_R * self.pitch + inner / 2
+ g = int(np.ceil(np.sqrt(fill)))
+ cells = [(a_, b_) for a_ in range(g) for b_ in range(g)]
+ r.shuffle(cells)
+ for q in range(fill):
+ a_, b_ = cells[q % len(cells)]
+ lx = cx0 - inner / 2 + (a_ + 0.5 + r.normal(0, 0.28)) * inner / g
+ lyy = cy0 - inner / 2 + (b_ + 0.5 + r.normal(0, 0.28)) * inner / g
+ lx, lyy = np.clip(lx, cx0 - inner / 2, cx0 + inner / 2), np.clip(lyy, cy0 - inner / 2, cy0 + inner / 2)
+ x, y = t.local_to_xy(lx, lyy)
+ pose = 'side' if r.random() < 0.55 else 'stand'
+ items.append((x, y, name, pose, r.uniform(0, 180), r.uniform(0, 0.55)))
+ o = _Beads(items, self.pitch, floor=1.6, cap=1.0); self.objs.append(o)
+ return t
+
+ def spill(self, cx, cy, colours, n=20, spread=60.0, standing=0.35, weights=None, seed=None):
+ """loose beads scattered on whatever is there (standing on end or lying on their side)"""
+ r = np.random.default_rng(self._seed() if seed is None else seed)
+ items = []
+ for q in range(n):
+ ang = r.random() * 2 * np.pi
+ rad = spread * np.sqrt(r.random()) * (1 + 0.4 * r.normal(0, 0.3))
+ name = colours[r.choice(len(colours), p=weights)]
+ items.append((cx + np.cos(ang) * rad * 1.25, cy + np.sin(ang) * rad * 0.9, name,
+ 'stand' if r.random() < standing else 'side', r.uniform(0, 180), r.uniform(0, 0.35)))
+ o = _Beads(items, self.pitch, floor=0.0, cap=0.9); self.objs.append(o); return o
+
+ def bead(self, x, y, colour, pose='stand', angle=0.0, tilt=0.0):
+ """one loose bead at (x, y)"""
+ o = _Beads([(x, y, colour, pose, angle, tilt)], self.pitch); self.objs.append(o); return o
+
+ def tweezers(self, tip, angle, length=300.0, lift=26.0, rise=0.09, holding=None, grip='#e8775f', open_w=None):
+ """bead tweezers held above the table: tip (x, y), pointing from the hinge toward the tip is angle+180.
+ holding: a bead colour pinched in the tips. lift: height of the tips; rise: how fast the legs climb."""
+ ow = open_w if open_w is not None else (2 * BEAD_R * self.pitch + 3.4 if holding else 3.0)
+ o = _Tweezers(tip, angle, length, lift, rise, holding, grip, ow, self.pitch, self._seed())
+ self.objs.append(o); return o
+
+ def ironing_paper(self, cx, cy, w, h, angle=0.0, cut=None, curl=6.0, colour='#f4f1ea', wrinkle=0.0):
+ """a sheet of ironing paper laid over the beads (drapes over them, translucent, fine grain).
+ cut=((x, y), (nx, ny)): peeled back -- only the part where (P - point) . n > 0 stays, its edge curled;
+ wrinkle: px of heat cockle (a used sheet)"""
+ seed = self._seed()
+
+ def draw(S, w=w, h=h):
+ W_, H_ = int(w * S), int(h * S)
+ n = noise2d(H_, W_, 1.6 * S, 2, seed % 9973)
+ cl = noise2d(H_, W_, 40 * S, 3, (seed + 1) % 9973)
+ c = hexc(colour)
+ rgb = c[None, None] * (0.97 + 0.03 * n[..., None] + 0.035 * (cl[..., None] - 0.5))
+ a = np.ones((H_, W_), np.float32)
+ im = np.dstack([rgb, a]) * 255
+ return Image.fromarray(im.clip(0, 255).astype(np.uint8), 'RGBA')
+ o = _Sheet(draw, cx, cy, angle, thick=0.8, translucency=0.42, drape=0.5 * self.pitch, spec=0.12,
+ rough=0.45, cut=cut, curl=curl, bump=wrinkle, seed=seed)
+ self.objs.append(o); return o
+
+ def tape(self, text, cx, cy, width=None, angle=0.0, colour='#f1e6c8', ink='#3a3a3a', size=26, font='cjk_sans',
+ sub=None, sub_font='hand', badge=None, badge_colour='#d3272f'):
+ """a strip of masking tape with a handwritten / printed label; badge='1' adds a round step number"""
+ seed = self._seed()
+
+ def draw(S):
+ f = _font(font, size * S)
+ f2 = _font(sub_font, size * 0.62 * S) if sub else None
+ tw = f.getlength(text) + (f2.getlength(sub) + size * 0.5 * S if sub else 0)
+ bw = size * 1.25 * S if badge else 0
+ W_ = int(width * S) if width else int(tw + bw + size * 1.6 * S)
+ H_ = int(size * 1.75 * S)
+ r = np.random.default_rng(seed)
+ im = Image.new('RGBA', (W_, H_), (0, 0, 0, 0))
+ d = ImageDraw.Draw(im)
+ zz = int(4 * S)
+ left = [(zz * r.random(), H_ * k / 8) for k in range(9)]
+ right = [(W_ - zz * r.random(), H_ * (8 - k) / 8) for k in range(9)]
+ c = tuple(int(v * 255) for v in hexc(colour))
+ d.polygon(left + right, fill=c + (235,))
+ x = size * 0.8 * S
+ if badge:
+ cy_ = H_ / 2
+ rr = size * 0.52 * S
+ bc = tuple(int(v * 255) for v in hexc(badge_colour))
+ d.ellipse([x - 0.1 * S, cy_ - rr, x + 2 * rr, cy_ + rr], fill=bc + (255,))
+ d.text((x + rr, cy_ + 0.5 * S), badge, font=_font('sans_bold', size * 0.72 * S), fill=(255, 255, 255, 255),
+ anchor='mm')
+ x += 2 * rr + size * 0.35 * S
+ ic = tuple(int(v * 255) for v in hexc(ink))
+ d.text((x, H_ / 2 + 1 * S), text, font=f, fill=ic + (255,), anchor='lm')
+ if sub:
+ d.text((x + f.getlength(text) + size * 0.45 * S, H_ / 2 + 2 * S), sub, font=f2, fill=ic + (215,),
+ anchor='lm')
+ n = noise2d(H_, W_, 2 * S, 2, seed % 9973)
+ arr = np.asarray(im, np.float32)
+ arr[..., :3] *= (0.96 + 0.06 * n)[..., None]
+ return Image.fromarray(arr.clip(0, 255).astype(np.uint8), 'RGBA')
+ o = _Sheet(draw, cx, cy, angle, thick=0.5, translucency=0.12, spec=0.05, rough=0.7)
+ self.objs.append(o); return o
+
+ def chart(self, rows, key, cx, cy, cell=16.0, angle=0.0, title='', subtitle='', number='', names=None,
+ done=(), note=None):
+ """a printed pattern chart on graph paper: the design as coloured cells with a symbol each, row / column
+ numbers, heavier lines every 5 cells, and a legend (bead icon, symbol, name, count). done: characters
+ already placed get a pencil tick in the legend."""
+ seed = self._seed()
+ nr, nc = len(rows), max(len(r) for r in rows)
+ counts = {ch: sum(line.count(ch) for line in rows) for ch in key}
+
+ order = [ch for ch in key if counts[ch]]
+ names = names or {}
+
+ def draw(S, data):
+ cs = cell * S
+ left, top = 2.2 * cs, 5.4 * cs
+ ncol_leg = 3
+ nleg = (len(order) + ncol_leg - 1) // ncol_leg
+ W_ = int(left + (nc + 1.4) * cs)
+ H_ = int(top + (nr + 1.2) * cs + nleg * 1.9 * cs + 1.2 * cs)
+ im = Image.new('RGBA', (W_, H_), (250, 248, 242, 255))
+ d = ImageDraw.Draw(im)
+ # graph paper everywhere (faint), on the same module as the pattern
+ gx0, gy0 = left % cs, top % cs
+ for i in range(int(W_ / cs) + 2):
+ x = gx0 + i * cs
+ d.line([(x, 0), (x, H_)], fill=(196, 220, 232, 255), width=max(1, int(0.5 * S)))
+ for j in range(int(H_ / cs) + 2):
+ y = gy0 + j * cs
+ d.line([(0, y), (W_, y)], fill=(196, 220, 232, 255), width=max(1, int(0.5 * S)))
+ # pattern cells
+ fs = _font('sans_bold', cs * 0.52)
+ for i, line in enumerate(rows):
+ for j, ch in enumerate(line):
+ if ch not in key: continue
+ c = _c(key[ch])
+ pc = 0.88 * c + 0.12
+ x0, y0 = left + j * cs, top + i * cs
+ d.rectangle([x0, y0, x0 + cs, y0 + cs], fill=tuple(int(v * 255) for v in pc) + (255,))
+ lum = 0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]
+ tc = (255, 255, 255, 235) if lum < 0.55 else (40, 40, 48, 220)
+ d.text((x0 + cs / 2, y0 + cs / 2 + 0.3 * S), ch, font=fs,
+ fill=tc, anchor='mm')
+ # chart grid over the pattern area
+ for i in range(nc + 1):
+ x = left + i * cs
+ heavy = i % 5 == 0 or i == nc
+ d.line([(x, top), (x, top + nr * cs)], fill=(70, 72, 80, 255) if heavy else (150, 152, 160, 255),
+ width=max(1, int((1.3 if heavy else 0.6) * S)))
+ for j in range(nr + 1):
+ y = top + j * cs
+ heavy = j % 5 == 0 or j == nr
+ d.line([(left, y), (left + nc * cs, y)], fill=(70, 72, 80, 255) if heavy else (150, 152, 160, 255),
+ width=max(1, int((1.3 if heavy else 0.6) * S)))
+ fn = _font('sans', cs * 0.5)
+ for i in range(nc):
+ if (i + 1) % 5 == 0 or i == 0:
+ d.text((left + (i + 0.5) * cs, top - 0.35 * cs), str(i + 1), font=fn, fill=(90, 92, 100, 255),
+ anchor='ms')
+ for j in range(nr):
+ if (j + 1) % 5 == 0 or j == 0:
+ d.text((left - 0.35 * cs, top + (j + 0.5) * cs), str(j + 1), font=fn, fill=(90, 92, 100, 255),
+ anchor='rm')
+ # centre arrows (as on printed charts)
+ for (ax, ay, dx_, dy_) in [(left + nc / 2 * cs, top - 0.05 * cs, 0, -1), (left - 0.05 * cs, top + nr / 2 * cs, -1, 0)]:
+ sz = 0.32 * cs
+ if dy_:
+ d.polygon([(ax, ay), (ax - sz, ay - 1.3 * sz), (ax + sz, ay - 1.3 * sz)], fill=(211, 60, 60, 255))
+ else:
+ d.polygon([(ax, ay), (ax - 1.3 * sz, ay - sz), (ax - 1.3 * sz, ay + sz)], fill=(211, 60, 60, 255))
+ # header
+ if number:
+ d.text((left, 1.0 * cs), number, font=_font('sans_bold', cs * 0.62), fill=(211, 60, 60, 255), anchor='ls')
+ if title:
+ d.text((left, 2.75 * cs), title, font=_font('cjk_sans', cs * 1.45), fill=(40, 40, 48, 255), anchor='ls')
+ if subtitle:
+ d.text((left, 3.9 * cs), subtitle, font=_font('sans', cs * 0.62), fill=(95, 97, 106, 255), anchor='ls')
+ # legend
+ ly0 = top + (nr + 1.3) * cs
+ colw = (nc * cs) / ncol_leg
+ fl = _font('cjk_sans', cs * 0.72)
+ fc = _font('sans', cs * 0.62)
+ rg = np.random.default_rng(seed)
+ for q, ch in enumerate(order):
+ gx_, gy_ = left + (q % ncol_leg) * colw, ly0 + (q // ncol_leg) * 1.9 * cs
+ c = _c(key[ch]); ci = tuple(int(v * 255) for v in c) + (255,)
+ rr = 0.52 * cs
+ cxx, cyy = gx_ + rr, gy_ + 0.75 * cs
+ d.ellipse([cxx - rr, cyy - rr, cxx + rr, cyy + rr], fill=ci, outline=(90, 90, 96, 255),
+ width=max(1, int(0.6 * S)))
+ d.ellipse([cxx - rr * 0.45, cyy - rr * 0.45, cxx + rr * 0.45, cyy + rr * 0.45], fill=(250, 248, 242, 255))
+ d.text((gx_ + 2.5 * rr, cyy), ch, font=_font('sans_bold', cs * 0.66),
+ fill=(50, 50, 58, 255), anchor='lm')
+ d.text((gx_ + 2.5 * rr + 0.9 * cs, cyy), names.get(ch, key[ch]), font=fl, fill=(50, 50, 58, 255), anchor='lm')
+ d.text((gx_ + colw - 0.6 * cs, cyy), f'x{counts[ch]}', font=fc, fill=(110, 112, 120, 255), anchor='rm')
+ if ch in data['done']: # pencil tick: already on the board
+ px_, py_ = cxx + 0.1 * cs, cyy + 0.05 * cs
+ pts = [(px_ - 0.35 * cs, py_ - 0.05 * cs), (px_ - 0.1 * cs + rg.normal(0, 0.3) * S, py_ + 0.35 * cs),
+ (px_ + 0.45 * cs, py_ - 0.55 * cs + rg.normal(0, 0.3) * S)]
+ d.line(pts, fill=(70, 70, 78, 235), width=max(1, int(1.9 * S)), joint='curve')
+ if note:
+ d.text((left, H_ - 0.55 * cs), note, font=_font('hand', cs * 0.7), fill=(88, 88, 96, 220), anchor='ls')
+ n = noise2d(H_, W_, 2.2 * S, 2, seed % 9973)
+ arr = np.asarray(im, np.float32)
+ arr[..., :3] *= (0.975 + 0.035 * n)[..., None]
+ return Image.fromarray(arr.clip(0, 255).astype(np.uint8), 'RGBA')
+ o = _Sheet(draw, cx, cy, angle, thick=0.9, spec=0.03, rough=0.85)
+ o.data['done'] = o.done = set(done) # chart.done.update('RD') ticks colours off
+ o.counts = counts
+ self.objs.append(o); return o
+
+ def on_top(self, *objs):
+ """move things to the top of the pile (drawn last), e.g. labels after a sheet slid under them"""
+ for o in objs:
+ if o in self.objs: self.objs.remove(o); self.objs.append(o)
+
+ def remove(self, obj):
+ """take something off the table (e.g. the ironing paper once it has been peeled)"""
+ if obj in self.objs: self.objs.remove(obj)
+
+ # ---- rendering
+ def _raster(self, S):
+ cv = _Canvas(self.W, self.H, S, self.tilt, self.zmax)
+ for o in self.objs: o.raster(cv)
+ return cv
+
+ def _march(self, f, s0, s1):
+ """f: (rows, cols) screen row of every world row (y - tilt z), +big where empty. For screen rows s0..s1-1
+ return the index of the nearest world row whose surface covers that pixel (-1 if none)."""
+ Hm, Wm = f.shape
+ f = np.minimum(f, s1 + 8.0) # empty rows: past every query
+ m = np.minimum.accumulate(f[::-1], axis=0)[::-1]
+ lo = float(m.min())
+ out = np.empty((s1 - s0, Wm), np.int32)
+ BIG = (s1 + 8.0 - lo) + 64.0 # > the value range of one column
+ q0 = np.arange(s0, s1, dtype=np.float64) - lo
+ for c0 in range(0, Wm, 384):
+ c1 = min(Wm, c0 + 384); n = c1 - c0
+ off = (np.arange(n, dtype=np.float64) * BIG)[:, None]
+ flat = (m[:, c0:c1].T.astype(np.float64) - lo + off).ravel()
+ q = (q0[None, :] + off).ravel()
+ idx = np.searchsorted(flat, q, side='right').reshape(n, -1) - (np.arange(n) * Hm)[:, None] - 1
+ out[:, c0:c1] = idx.T
+ return out
+
+ def _light(self, N, P, alb, spec, rough, mat, trans, sh, ao):
+ """shade (…, 3) normals at world points P (output px) -> linear RGB"""
+ V = np.array([0, self.tilt, 1], np.float32); V /= np.linalg.norm(V)
+ L = self.light[None, None] - P
+ L /= np.linalg.norm(L, axis=-1, keepdims=True)
+ ndl = np.clip((N * L).sum(-1), 0, 1)
+ vis = 1 - 0.82 * sh
+ amb = (0.40 + 0.26 * N[..., 2] + 0.16 * np.clip(N[..., 1], 0, 1)) * (1 - 0.82 * ao)
+ dif = 0.92 * ndl * vis
+ Hh = L + V[None, None]; Hh /= np.linalg.norm(Hh, axis=-1, keepdims=True)
+ ndh = np.clip((N * Hh).sum(-1), 0, 1)
+ shin = 10 + 420 * (1 - rough) ** 3
+ spk = spec * ndh ** shin * (0.15 + 1.2 * (1 - rough) ** 2) * vis
+ ndv = np.clip((N * V).sum(-1), 0, 1)
+ R = 2 * ndv[..., None] * N - V
+ # the key is a big soft box: every surface whose mirror direction points into it shows it as a bright
+ # patch -- a crisp arc on the upper-left shoulder of each bead's rim and on the far lip of its hole;
+ # rougher (melted) plastic spreads it into a broad waxy sheen that drifts across a flat piece
+ rl = np.clip((R * L).sum(-1), -1, 1)
+ a_in = np.radians(8.0)
+ a_out = a_in + np.radians(5.0 + 62.0 * rough)
+ win = smoothstep(np.cos(a_out), np.cos(a_in), rl)
+ F = 0.04 + 0.96 * (1 - ndv) ** 5
+ env = spec * (0.05 + 0.08 * F + 1.35 * win * (1 - 0.55 * rough)) * (1 - 0.6 * ao) * vis ** 0.5
+ a = alb
+ key = np.array([1.03, 1.0, 0.95], np.float32)
+ sky = np.array([0.95, 0.99, 1.05], np.float32)
+ col = a * (amb[..., None] * sky + dif[..., None] * key)
+ # translucent plastic: light that went through comes out coloured in the shade
+ col += a * np.sqrt(a) * (trans * 0.30 * (1 - ndl * vis) * (1 - 0.6 * ao))[..., None]
+ white = (spk + env)[..., None] * key
+ pearl = mat == PEARL
+ if pearl.any():
+ ph = ndv * 5.0 + N[..., 0] * 2.0
+ irid = 0.5 + 0.5 * np.cos(2 * np.pi * (ph[..., None] + np.array([0.0, 0.33, 0.67], np.float32)))
+ col = np.where(pearl[..., None], col + (0.16 * (1 - ndv) + 0.05)[..., None] * (0.55 + 0.6 * irid) * (1 - ao[..., None]), col)
+ metal = mat == METAL
+ if metal.any():
+ wm = win
+ mc = a * (0.34 * amb[..., None] + 0.30 * dif[..., None]) + a * (0.12 + 0.9 * wm[..., None])
+ col = np.where(metal[..., None], mc, col)
+ white = np.where(metal[..., None], white * 0.3, white)
+ return col + white
+
+ def _render(self, S):
+ cv = self._raster(S)
+ k = self.tilt
+ z = cv.z
+ Hm, Wm = z.shape
+ Hs = cv.H
+ # shadows and occlusion on the world grid (heights in internal px)
+ zi = z * S
+ Lc = self.light - np.array([self.W / 2, self.H / 2, 0], np.float32)
+ Ld = Lc / np.linalg.norm(Lc)
+ sh = height_shadow(zi, light=tuple(Ld), reach=int(self.zmax * 1.4 * S), step=max(1.0, 0.75 * S), soft=2.4 * S)
+ ao = ambient_occlusion(zi, radii=(2 * S, 6 * S, 16 * S), depth=(5.0 * S, 12.0 * S, 26.0 * S))
+ ao = np.clip(ao * 1.0, 0, 1)
+ for ly in cv.over: # things held in the air cast soft shadows
+ osh = np.zeros_like(z)
+ valid = ly.z > -100
+ if not valid.any(): continue
+ b0, a0 = ly.sl[0].start, ly.sl[1].start
+ ys, xs = np.nonzero(valid)
+ dz = ly.z[ys, xs] - z[b0 + ys, a0 + xs]
+ ox = np.rint((xs + a0) + dz * (-Ld[0] / Ld[2]) * S).astype(int)
+ oy = np.rint((ys + b0) + dz * (-Ld[1] / Ld[2]) * S).astype(int)
+ ok = (ox >= 0) & (ox < Wm) & (oy >= 0) & (oy < Hm)
+ osh[oy[ok], ox[ok]] = 1
+ osh = blur(_maxf(osh, int(S)), 2.2 * S)
+ sh = np.maximum(sh, np.clip(osh * 1.5, 0, 1) * 0.92)
+ gy, gx = np.gradient(z)
+ gx *= S; gy *= S
+ zb = blur(z, 2.2 * S)
+ gyb, gxb = np.gradient(zb)
+ y_idx = np.arange(Hm, dtype=np.float32)[:, None]
+ f = y_idx - k * zi
+ Y = self._march(f, 0, Hs)
+ cols = np.arange(Wm)[None, :]
+ Yc = np.clip(Y, 0, Hm - 2)
+ srow = np.arange(Hs, dtype=np.float32)[:, None]
+ fY = f[Yc, cols]
+ wall = fY < srow - 1.5 # > 1.5 rows past its surface point: a wall
+ zY = zi[Yc, cols] # (a gentle slope toward the camera
+ zN = zi[np.minimum(Yc + 1, Hm - 1), cols] # stretches a row over ~1.1 rows) # the foot of a wall: lowest of the next
+ for d in range(2, 2 * S + 2): # few rows (edges are anti-aliased steps)
+ zN = np.minimum(zN, zi[np.minimum(Yc + d, Hm - 1), cols])
+ zw = np.clip((Yc + 0.5 - srow) / k, zN, zY)
+ # normals: tops from the height gradient, walls horizontal and facing the camera
+ nt = np.stack([-gx[Yc, cols], -gy[Yc, cols], np.ones_like(zY)], -1)
+ wall |= (1.0 / np.linalg.norm(nt, axis=-1)) < 0.3 # steep anti-aliasing ramps shade as wall
+ nw = np.stack([-gxb[Yc, cols], np.maximum(-gyb[Yc, cols], 0.0), np.zeros_like(zY)], -1)
+ nwl = np.linalg.norm(nw, axis=-1, keepdims=True)
+ nw = np.where(nwl > 1e-4, nw / np.maximum(nwl, 1e-6), np.array([0, 1, 0], np.float32))
+ nw[..., 1] = np.maximum(nw[..., 1], 0.25)
+ N = np.where(wall[..., None], nw, nt)
+ N /= np.linalg.norm(N, axis=-1, keepdims=True)
+ zT = zY.copy() # the real top of a wall (not the ramp row)
+ for d in range(1, 2 * S + 1):
+ zT = np.maximum(zT, zi[np.maximum(Yc - d, 0), cols])
+ tw = np.clip((zw - zN) / np.maximum(zT - zN, 1e-3), 0, 1)
+ # walls read light from smooth maps, sampled at their foot and just inside their top edge: the edge row
+ # itself is an anti-aliased staircase and would streak the wall
+ aoB, shB = blur(ao, 2.0 * S), blur(sh, 1.5 * S)
+ foot, head = np.minimum(Yc + 2 * S, Hm - 1), np.maximum(Yc - 2 * S, 0)
+ aoY = ao[Yc, cols]
+ aop = np.where(wall, np.clip(0.42 * (1 - tw) ** 1.5 + 0.8 * aoB[foot, cols] * (1 - tw) + 0.05, 0, 1), aoY)
+ shp = np.where(wall, shB[foot, cols] * (1 - tw) + shB[head, cols] * tw, sh[Yc, cols])
+ zz = np.where(wall, zw, zY) / S
+ P = np.stack([np.broadcast_to((cols + 0.5) / S, zY.shape), (Yc + 0.5) / S, zz], -1).astype(np.float32)
+ col = self._light(N, P, cv.alb[Yc, cols], cv.spec[Yc, cols], cv.rough[Yc, cols], cv.mat[Yc, cols],
+ cv.trans[Yc, cols], shp, aop)
+ # lifted layers on top
+ for ly in cv.over:
+ col = self._composite_layer(col, ly, cv)
+ # room light falls off a little away from the window (upper left)
+ yy, xx = np.mgrid[0:Hs, 0:Wm].astype(np.float32)
+ xx /= Wm; yy /= Hs
+ fall = 1.06 - 0.10 * (0.6 * xx + 0.4 * yy) - 0.10 * ((xx - 0.5) ** 2 + (yy - 0.5) ** 2)
+ col *= fall[..., None]
+ col = np.maximum(col, 0)
+ col = np.where(col < 0.8, col, 0.8 + 0.2 * (1 - np.exp(-(col - 0.8) / 0.2))) # soft shoulder: whites keep form
+ img = np.power(np.clip(col, 0, 1), 1 / 2.2)
+ g = np.random.default_rng(self.seed + 7).normal(0, 0.006, img.shape[:2]).astype(np.float32)
+ img = np.clip(img + g[..., None], 0, 1)
+ im = Image.fromarray((img * 255 + 0.5).astype(np.uint8))
+ if S > 1: im = im.resize((self.W, self.H), Image.LANCZOS)
+ return im
+
+ def _composite_layer(self, col, ly, cv):
+ S, k = cv.S, self.tilt
+ b0, a0 = ly.sl[0].start, ly.sl[1].start
+ zi = ly.z * S
+ valid = ly.z > -100
+ h, w = zi.shape
+ top = int(np.floor(b0 - k * zi[valid].max())) - 2 if valid.any() else b0
+ s0, s1 = max(0, top), min(cv.H, b0 + h)
+ if s1 <= s0: return col
+ yw = (b0 + np.arange(h, dtype=np.float32))[:, None]
+ f = np.where(valid, yw - k * zi, 1e6)
+ Y = self._march(f, s0, s1)
+ have = Y >= 0
+ Yc = np.clip(Y, 0, h - 2)
+ cols = np.arange(w)[None, :]
+ srow = np.arange(s0, s1, dtype=np.float32)[:, None]
+ fY = f[Yc, cols]
+ wall = fY < srow - 1.0
+ zY = zi[Yc, cols]
+ zw = (b0 + Yc + 0.5 - srow) / k
+ bottom = zY - ly.thick[Yc, cols] * S
+ vis = have & valid[Yc, cols] & (~wall | (zw >= bottom))
+ gy, gx = np.gradient(np.where(valid, ly.z, np.nan))
+ gx = np.nan_to_num(gx) * S; gy = np.nan_to_num(gy) * S
+ nt = np.stack([-gx[Yc, cols], -gy[Yc, cols], np.ones(Yc.shape, np.float32)], -1)
+ nw = np.stack([np.zeros(Yc.shape, np.float32), np.ones(Yc.shape, np.float32), np.zeros(Yc.shape, np.float32)], -1)
+ N = np.where(wall[..., None], nw, nt)
+ N /= np.linalg.norm(N, axis=-1, keepdims=True)
+ zz = np.where(wall, zw, zY) / S
+ P = np.stack([np.broadcast_to((a0 + cols + 0.5) / S, Yc.shape), (b0 + Yc + 0.5) / S, zz], -1).astype(np.float32)
+ z0 = np.zeros(Yc.shape, np.float32)
+ lc = self._light(N, P, ly.alb[Yc, cols], ly.spec[Yc, cols], ly.rough[Yc, cols], ly.mat[Yc, cols], z0 + 0.4,
+ z0, z0 + np.where(wall, 0.35, 0.0))
+ a = vis.astype(np.float32)[..., None]
+ seg = col[s0:s1, a0:a0 + w]
+ col[s0:s1, a0:a0 + w] = seg * (1 - a) + lc * a
+ return col
+
+ def stage(self, name):
+ """snapshot for the draw-on animation: the table as it is now (a copy of every object). Rendered only when
+ save() is given a stages_dir, at stage_ss (1x by default, quick)."""
+ self.stages.append((name, copy.deepcopy(self.objs)))
+
+ def save(self, path, stages_dir=None, quality=88):
+ img = self._render(self.ss)
+ 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)
+ now = self.objs
+ for i, (name, objs) in enumerate(self.stages):
+ self.objs = objs
+ self._render(self.stage_ss).save(f"{stages_dir}/{i:02d}_{name}.png")
+ self.objs = now
+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")
+ return img