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.

Remove the flat-vector style (26 styles)

cloveric1c8affb56abf
diff --git a/README.md b/README.md
index c77f36d..b1edcc4 100644
--- a/README.md
+++ b/README.md
@@ -1,16 +1,12 @@
# Claude Drawing · Claude 绘图
-**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 and a synthwave sunset.
-**不用生图模型,Claude 用代码一笔一笔作画。** 二十七种画风,从水墨、油画到黏土、蓝晒、十字绣、黑板板书、赛博朋克、等轴小岛、光线追踪的小球海和 Synthwave 落日。
+**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 落日。
[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 | Soft 3D · 柔光 3D |
-|---|---|
-| ![isometric](examples/drawing_isometric_weather_island.gif) | ![soft3d](examples/drawing_soft3d_rise.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) |
@@ -20,10 +16,14 @@
| ![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 · 卡通手绘** | **Flat vector · 扁平矢量** | **Continuous line art · 单线画** | **Shape morph · 形变动画** |
-| ![cartoon](examples/drawing_cartoon_toaster.gif) | ![flatvector](examples/drawing_flatvector_bookshop.gif) | ![lineart](examples/drawing_lineart_paper_plane.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) |
+
+| 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) |
### Gallery · 画廊
@@ -31,26 +31,26 @@
|---|---|
| **八万四千法门** · *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> | **热气球小镇** · *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%"> |
-| **周末书店** · *The Weekend Bookshop*<br><sub>Flat vector · 扁平矢量</sub> | **从这扇窗到那扇窗** · *From Window to Window*<br><sub>Continuous line art · 单线画</sub> |
-| <img src="examples/flatvector_bookshop.jpg" width="100%"> | <img src="examples/lineart_paper_plane.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> |
@@ -58,7 +58,7 @@
| **形与色** · *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, faceless flat-vector figures, 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.
+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.
---
@@ -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-seven styles:
+A [Claude Code](https://claude.com/claude-code) skill and a small painting library with twenty-six styles:
| Style | Module | What makes it read as the real medium |
|---|---|---|
@@ -89,7 +89,6 @@ A [Claude Code](https://claude.com/claude-code) skill and a small painting libra
| **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 |
| **Hand-drawn cartoon** | `lib/cartoon.py` · `Cartoon` | drawn the way an animator draws one frame: a blue col-erase pencil rough left under everything; brush-pen ink that lands thin, swells and lifts off to a point, closed shapes inked in one stroke whose ends overlap, heavier on the shadow side; flat colour painted a little off the lines (a sliver of paper here, a spill there); hard one- or two-tone cel shadows and white glints; crayon that only catches the paper tooth, screentone, ink hatching; faces, rubber-hose arms with mitten gloves, sparkles, speed lines, starbursts; chunky extruded lettering; lines that boil from frame to frame; a staged replay rough → ink → colour → shadow → effects → type |
| **Isometric 2.5D** | `lib/isometric.py` · `Isometric` | a true isometric orthographic camera and a small ray tracer: every part is an exact analytic solid (chamfered boxes, roofs, rocks and hulls as convex polyhedra; cylinders and cones on any axis; ellipsoids cut by planes) in a G-buffer, so hiding never depends on draw order; one soft sun gives the three-tone faces and percentage-closer soft shadows that widen with distance; occlusion comes from a top-down map that knows eaves and tree crowns float; pastel albedos under a lilac sky, chamfer highlights, shore foam, glassy water walls, a floating slab whose shadow lands on the backdrop; data cards printed on iso planes |
-| **Flat vector** | `lib/flatvector.py` · `FlatVector` | crisp geometric shapes with no outlines (tapered capsules, filleted polygons, rounded rects, leaves); a seven-colour palette where every shade is a tone of it, never grey; volume from stacked flat blocks — a crescent cut as "the shape minus itself nudged toward the light", straight-cut planes, hard multiply cast shadows; translucent grainy light beams; faceless adult figures (7.5 heads, IK hands and feet, far limbs one tone darker); a whisper of print grain |
| **Continuous line art** | `lib/lineart.py` · `LineArt` | the whole picture is one path: shapes strung together in drawing order with tangent-continuous bridges, loop-the-loops laid along the path, invisible retraces to reach a window; rasterised once into a time map, so every draw-on stage is an exact prefix of the line; a hand-pressure width (touch-down and lift-off tapers, slow drift, heavier in sharp turns, a flick where the pen doubles back, a lighter hand for motion paths); a gilded wire with angle-dependent sheen and a faint, tight glow on night blue (or dark ink on cream); a hot pen tip while drawing; one glowing accent; letter-spaced Didot titles |
| **Soft 3D** | `lib/soft3d.py` · `Soft3D` | an actual little ray tracer: tens of thousands of balls found by walking a grid (DDA) with exact ray–sphere hits; puffy letters as signed distance fields (exact 2D distance transform of the glyph, extruded, rounded and inflated); a studio sky dome with ambient occlusion sampled in the scene's own distance field; a big softbox key with soft penumbra shadows, a rim light, softbox reflections and Fresnel edges; shade that turns deeper and more saturated instead of grey; displaced balls that settle into real hollows; aerial haze, layered depth of field, 1.5× supersampling |
| **Shape morph** | `lib/morph.py` · `Morph` | one closed outline per object: resampled to 256 points evenly along its arc length, given the same winding, start point aligned by FFT cross-correlation, then blended point by point while its centroid travels an eased motion path with squash & stretch; compound shapes (cloud, snowflake) are unions of primitives traced back to a single outline; colours switch through OKLab; the poster freezes the animation as a film strip: one flat colour panel per keyframe, onion-skin ghosts that change colour at the panel border, matched points dotted on the middle frame, a dashed motion path and a timeline of ease curves |
@@ -169,7 +168,6 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages
- **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.
- **Hand-drawn cartoon**: draw back to front, since every fill knocks out what is behind it; put limbs down before the body so the shoulder hides. Lines are heavier on the shadow side, and colour sits a few pixels off the line. Keep texture where it belongs (toasted edges, not across a face). Boil only the ink between frames: pencil and colour stay on the sheet, which also keeps the GIF small.
- **Isometric**: light real solids with one sun instead of painting three face tones by hand. Wall occlusion must look out along the normal and skip the building's own height and eaves, or white walls turn grey; never interpolate column tops and bottoms across an edge. Keep floating cards, clouds and hairlines out of the height map. Lay wave dashes along world y − x (screen horizontal), and leave a wide sea on the two front edges so the island reads as an island.
-- **Flat vector**: there are no outlines, so plan every value against what sits behind it (dark hair on a dark shelf vanishes). Save the accent colour for the one thing the picture is about. Cut hair at a hairline, or heads turn into hoods; in 3/4 view reach with the far arm so the arm doesn't sweep across the face. Keep grain around 1%.
- **Line art**: one path, drawn in order: string shapes with `chain()`, reach windows with an invisible retrace, let loops ride along the path, and put a loop where the path runs level, not on a climb. Draw motion paths with a lighter hand (~0.6) or they read as one more hill. Keep exactly one accent colour and plenty of empty space.
- **Soft 3D**: near a shape, light queries (AO, shadows, dropping a ball) need its exact distance, not its bounding box, or balls rest on thin air. Don't carve a trench around a subject: pile the displaced balls into the hollows at its feet. Fill shade with the material's own hue (grey mint looks dirty). Match the haze to the backdrop, and set the lens with the camera so every stage is soft.
- **Shape morph**: every object is one closed outline. Resample both shapes to the same point count, same winding, and align the start point before blending, or the in-betweens collapse into slivers. Keep keyframes around 0.6 of the panel width and show only three ghosts per transition, with the middle one filled. Dash the motion path so it doesn't mix with the dotted matched points. Shapes stay perfectly flat: paper tooth only where bare paper shows.
@@ -188,7 +186,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,加上一个小巧的绘图库,内置二十六种画风:
| 画风 | 模块 | 为什么看起来像真的 |
|---|---|---|
@@ -211,7 +209,6 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages
| **赛博朋克** | `lib/cyberpunk.py` · `Cyberpunk` | 一台针孔相机看向雨夜街道深处,HDR 缓冲加深度遮挡:玻璃管霓虹中心过曝、边缘彩色光晕,还有坏管和闪烁管;背光灯箱;半透明全息广告,带扫描线、撕裂切片和色边;每样东西按自己的着地行翻出湿路面和水洼里的倒影;被城市灯光照亮的深度雾;被招牌照亮的井盖蒸汽;三层雨,只在霓虹附近看得见;飞车光轨;泛光、胶片红晕、颗粒和一道故障扫描线 |
| **卡通手绘** | `lib/cartoon.py` · `Cartoon` | 照动画师画一张原画的办法画:蓝铅笔稿留在底下;毛笔线落笔细、中段粗、收笔尖,闭合轮廓一笔画完、首尾交叠,背光一侧更粗;平涂颜色略微错开线(这边露一条纸白,那边压过线);一到两层硬边赛璐璐阴影和白色高光;只挂在纸纹凸起上的蜡笔、网点纸、墨线排线;表情、橡皮管手臂和带拇指的白手套、闪光星、速度线、爆炸框;带挤出阴影的粗描边大字;墨线每一帧都轻微抖动;能按 起稿 → 勾线 → 上色 → 阴影 → 特效 → 字 的顺序回放 |
| **等轴 2.5D** | `lib/isometric.py` · `Isometric` | 正等轴正交相机加一个小光线追踪器:每个部件都是精确的解析实体(倒角盒子、屋顶、礁石、船体用凸多面体;任意轴向的圆柱圆锥;可被平面切开的椭球),写进 G-buffer,遮挡与绘制顺序无关;一个柔和的太阳照出三个面三种明度,PCSS 软阴影随遮挡距离变宽;AO 来自记得屋檐和树冠是悬空的顶视高度图;粉彩反照率配淡紫天光、倒角高光、岸边浪花、透亮的水体侧壁,漂浮底座的影子落在背景上;数据卡的文字印在等轴平面上 |
-| **扁平矢量** | `lib/flatvector.py` · `FlatVector` | 无描边的干净几何形(锥形胶囊、圆弧倒角多边形、圆角矩形、叶片);七色限定色板,所有明暗都是色板色的色调,不用灰黑;色块叠压出体积:「形状减去朝光源挪动的自己」切出月牙暗面、直线切面、硬边正片叠底投影;带颗粒的半透明光束;无五官的成年人(7.5 头身、手脚可指定落点、远侧手脚暗一档);极轻的印刷颗粒 |
| **单线画** | `lib/lineart.py` · `LineArt` | 整幅画是一条路径:各个形状按作画顺序串起来,断开处用切线连续的曲线接上,翻圈沿路径插入,够不到的窗户用看不见的原路折返;一次栅格化成「时间图」,每个动画阶段都是整条线精确的前一段;带手感的线宽(起笔轻、收笔尖、压力缓慢起伏、急转处变粗、原路折返处提笔收尖、航迹这类运动轨迹用轻手);深蓝底上是随角度变亮、只带一点柔光的金线(奶油底上是墨线);画的时候笔尖发光;唯一一处发光的点睛色;字距拉开的 Didot 标题 |
| **柔光 3D** | `lib/soft3d.py` · `Soft3D` | 真的是一台小光线追踪器:几万颗球靠逐格查找(DDA)加精确的光线–球求交;鼓鼓的字是有向距离场(字形精确距离变换→挤出、倒圆、吹胀);摄影棚天光穹顶,环境光遮蔽在场景自己的距离场里采样;大柔光箱主光投下边缘渐软的阴影,加轮廓光;光面上映出灯片,边缘有菲涅尔亮边;阴影和缝隙变深变饱和而不发灰;被挤开的球真的落进窝里堆起来;远处空气雾、分层景深、1.5 倍超采样 |
| **形变动画** | `lib/morph.py` · `Morph` | 每样东西都是一条闭合轮廓:按弧长等距重采样成 256 个点、统一绕向、用 FFT 互相关对齐起点,再逐点插值;质心沿缓动的运动路径走,快的时候沿运动方向挤压拉伸;云、雪花这类组合形状用圆、线、多边形拼好后描出外轮廓;颜色在 OKLab 里切换;海报把动画定格成一条胶片:每个关键帧一块纯色面板,洋葱皮残影跨面板时跟着换色,中间帧标出对应点,加虚线轨迹和缓动曲线时间轴 |
@@ -267,7 +264,6 @@ python3 examples/chalk_lesson.py out.png # 黑板板
python3 examples/cyberpunk_neon_street.py out.png # 赛博朋克:霓虹不夜城
python3 examples/cartoon_toaster.py out.png # 卡通手绘:早安吐司
python3 examples/isometric_weather_island.py out.png # 等轴 2.5D:岛上的气象站
-python3 examples/flatvector_bookshop.py out.png # 扁平矢量:周末书店
python3 examples/lineart_paper_plane.py out.png # 单线画:从这扇窗到那扇窗
python3 examples/soft3d_rise.py out.png # 柔光 3D:浮出
python3 examples/morph_water_cycle.py out.png # 形变动画:一滴水的旅程
@@ -296,7 +292,6 @@ python3 examples/synthwave_coastline.py out.png # 复古 Synt
- **赛博朋克**:倒影按每样东西自己的着地行翻转,不能按一条地平线整体翻;店内亮度压在 0.2–0.45,否则街面成了过曝的墙;雨丝只在霓虹附近被照亮;飞车光轨横穿街道,不要全都飞向灭点。
- **卡通手绘**:先远后近,因为每次平涂都会挖掉身后的东西;手臂先画、身体后画,把肩膀藏起来。背光一侧的线更粗,颜色错开线几像素。质感放在该在的地方(烤边,而不是脸上)。帧与帧之间只抖墨线,铅笔稿和颜色不动,动图也小。
- **等轴 2.5D**:三个面的明度靠一个太阳照出来,不要手涂;墙面 AO 要沿法线往外看,不能把楼自己和屋檐的高度算进去,否则白墙发灰;柱子的顶和底不能跨边插值;悬浮卡片、云和细线不进高度图;海浪短线沿世界 y − x(屏幕水平)画;岛的前两条边留宽海面,才看得出是岛。
-- **扁平矢量**:没有描边,每块颜色都要按身后的背景定明度(深色头发贴深色书架就消失);点睛色只留给画面要讲的那一样东西;头发要沿发际线切开,否则像头巾;3/4 侧身够东西用远侧手臂,免得手臂扫过脸;颗粒压在 1% 左右。
- **单线画**:整幅画只有一条线,按作画顺序串:用 `chain()` 串形状,够不到的窗户原路进出,翻圈沿路径插入,放在路径平缓处,别放在爬升段;航迹这类运动轨迹用轻手(约 0.6 倍),否则会读成又一座山;点睛色只留一处,留白要多。
- **柔光 3D**:AO、阴影、落球这些查询在物体附近要用精确距离,不能用包围盒,否则球会停在半空;主体周围别挖一圈空槽,把挤开的球堆进脚边的窝里;阴影用材质自身的色调去补(发灰的薄荷色很脏);雾色和背景一致;景深跟相机一起先设好,每个阶段都是柔的。
- **形变动画**:每样东西只用一条闭合轮廓;插值前先重采样成同样点数、统一绕向、对齐起点,否则中间帧会塌成碎片;关键帧约占面板宽的六成,每段只画三个残影,中间那帧填色;轨迹用虚线,别和对应点的圆点混;形状保持纯平,纸纹只加在露出的纸面上。
diff --git a/SKILL.md b/SKILL.md
index 3d2e3ce..af6ad4c 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 / flat vector / flat illustration / 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 without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。
---
# Claude 绘图
@@ -33,7 +33,6 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型
| 赛博朋克 | `lib/cyberpunk.py` · `Cyberpunk` | `examples/cyberpunk_neon_street.py` 霓虹不夜城 · Neon District(雨夜街道峡谷、真玻璃管霓虹竖招牌(坏管与闪烁管)、背光灯箱、过街天桥「不夜城」、全息海月水母广告、电线、飞车光轨、井盖蒸汽、透明伞背影、湿路面与水洼倒影、胶片颗粒与一道撕裂扫描线) | 约 10 秒 |
| 卡通手绘(逐帧手绘) | `lib/cartoon.py` · `Cartoon` | `examples/cartoon_toaster.py` 早安吐司(薄荷绿吐司机笑着弹出两片举手的吐司、「叮!」爆炸框、盘子上打瞌睡的化黄油、窗外日出、墙上 7 点的钟;左侧 ①按下拉杆 ②电热丝烧红 3 分钟 ③弹起来 的图解;蓝铅笔稿留底、毛笔线、错位平涂、赛璐璐阴影、蜡笔天空与烤边、网点橱柜、抖线) | 约 4 秒 |
| 等轴 2.5D | `lib/isometric.py` · `Isometric` | `examples/isometric_weather_island.py` 岛上的气象站(漂浮的分层底座、一格一格的倒角地砖与台地、带双道浪花的海;观测场里的百叶箱、雨量筒、带风杯和风向标的风杆;看守小屋与卫星天线、太阳能板、石板路、栈桥小船、风袋、浮标、开花灌木;探空气球和平底云;四张悬浮数据卡用细引线指向各自仪器,地面上一个指北针) | 约 5 秒 |
-| 扁平矢量 | `lib/flatvector.py` · `FlatVector` | `examples/flatvector_bookshop.py` 周末书店(无描边几何色块、七色限定色板、色块叠压出体积、极轻颗粒;梯子上的店员把唯一一本珊瑚色诗集递给仰头伸手的银发顾客,虚线标出它从顶层空位落下的路线;拱窗日落、OPEN 挂牌、台灯光锥下读书的人、窗台橘猫、¥10 旧书箱) | 约 1 秒 |
| 单线画 | `lib/lineart.py` · `LineArt` | `examples/lineart_paper_plane.py` 从这扇窗到那扇窗(一根不断开的金线:圆树、小屋、从窗口穿墙飞出的纸飞机航迹与顶部翻圈、飞镖形纸飞机穿墙飞进对面小屋的窗;窗子亮起是全画唯一的点睛色;字距拉开的衬线标题) | 约 6 秒 |
| 柔光 3D | `lib/soft3d.py` · `Soft3D` | `examples/soft3d_rise.py` 浮出(糖果色小球海里顶出鼓鼓的软字 rise:被挤开的球堆在字脚、几颗骑在字肩上、几颗滚落,i 的点是一颗黄球;天光穹顶、柔光箱主光、粉色轮廓光、环境光遮蔽、软阴影、次表面色调、景深) | 约 46 秒 |
| 形变动画 | `lib/morph.py` · `Morph` | `examples/morph_water_cycle.py` 一滴水的旅程(一条 256 点轮廓线依次变成水滴→云→雪花→雪山→河→海浪,六块纯色背景随之切换;洋葱皮残影、挤压拉伸、虚线运动轨迹、中间帧标出对应点、缓动曲线时间轴) | 约 1 秒 |
@@ -64,7 +63,6 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型
- 夜景、城市、雨、霓虹、电影感氛围、讲解片的「未来 / 科技 / 城市」封面 → 赛博朋克(要复古小尺寸或像素动画仍用像素风);
- 可爱的拟人小物件、日常小事讲故事、带表情的角色、讲解片里轻松的「步骤 / 原理」图解、要逐帧抖线的动画 → 卡通手绘(要立体手作感用黏土定格,要纸片感用剪纸拼贴);
- 小世界、城市 / 园区 / 工厂 / 校园示意,系统或流程的「微缩模型」图解,围着场景放数据卡的信息图,讲解片的「全景 / 系统概览」页 → 等轴 2.5D(要霓虹夜景用赛博朋克;要复古小尺寸用像素风);
-- 生活场景、人物小故事、产品 / App 讲解插图、MG 动画式讲解片分镜 → 扁平矢量(要立体手作感用黏土,要纸感用剪纸);
- 高级克制、极简、品牌感封面、要看「一笔画出来」的过程、讲一段路线或旅程 → 单线画(深蓝底金线或奶油底墨线,只一个点睛色);
- 产品感、软萌立体、糖果色、MG 片头大字、「3D 渲染」、讲解片封面的立体标题 → 柔光 3D(要手作、捏泥的质感仍用黏土定格);
- 过程、变化、循环、「从 A 变成 B」的小故事,讲解片的转场、片头和「演变」页 → 形变动画(要真的动起来,用 `Morph.at` 逐帧出图);
@@ -263,15 +261,6 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask
- 信息图:`card(x, y, z, w, h, facing='+x', title, tag, value, unit, note, series, icon='wind'|'temp'|'rain'|'balloon'|'sun', anchor=(x, y, z), accent)` 竖在空中的数据卡(文字印在等轴平面上,带细引线和锚点);`compass(x, y, z, r, north)` 平躺在地面上的指北针;`text()`、`rule()`、`dot()` 平面排版叠在最上层
- 光:太阳从左后上方来,顶面最亮,+x 面(左下)次之,+y 面(右下)只吃天光;`sun_c / sky_c / hor_c / gnd_c`、`soft`、`pen`(最小 / 最大半影)可调。不要霓虹发光、泛光和描边
-**扁平矢量 `FlatVector`**:
-- 思路:矢量软件的画板。每样东西都是边缘干净的几何形 `Mask`(覆盖率小块 + 偏移);`|` 并、`&` 交、`-` 减、`moved(dx, dy)` 平移,只算包围盒重叠处,上千个形状也在 1 秒内
-- 形状:`circle` `ellipse` `rect` `rrect(x0, y0, x1, y1, r 或 (左上, 右上, 右下, 左下), rot)`;`capsule(p0, p1, r0, r1)` 锥形胶囊,`limb(点列, 半径列)`,`tube(控制点, r)` 平滑曲线管;`poly(pts, round=)` 圆弧倒角多边形;`arc` 环段、`pie` 扇形、`leaf(p0, p1, 宽, bend)` 叶片、`star`;`split(m, p0, p1)` 取直线左侧的部分;`text_mask`
-- 上色:`fill(m, 颜色, alpha, grain)`;`tone(c, k)`:k<0 向墨色混、k>0 向奶油色混,所有明暗都是色板色的色调
-- 体积(色块叠压):`shade(m, strength, depth)` 背光侧月牙(形状减去朝光源挪动的自己);`glint()` 受光侧亮月牙;`plane(m, p0, p1)` 直线切面;`cast(m, dx, dy, clip=)` 硬边投影(乘墨色,落在几种颜色上各自变深);`darken` / `lighten`
-- 人物 `person(hip, 身高, facing, lean, head_tilt, arm=(上臂, 前臂), leg=(大腿, 小腿), sit, hand_to, hand_far_to, foot_to, foot_far_to, top, bottom, shoes, skin, hair, hair_style='short'|'bun'|'bob'|'long'|'pony', coat, skirt, apron, bag, draw_near_arm)`:7.5 头身、无五官,远侧手脚暗一档;角度从「竖直向下」量起、朝面向为正;返回关节字典(hand、hand_far、head、knee…);`draw_near_arm=False` 时先画道具,再调 `near_arm()` 让手压在道具上
-- 物件:`books(x0, x1, 书脚y, 最高, 颜色, gap_at, gap_w, stack_at, back=背板遮罩)` 一排书脊;`book(cx, cy, w, h, rot, colour, open)`;`plant(kind='leafy'|'snake'|'round')`;`pendant(x, 顶, y, r, beam_to=)`;`cat(tail_down=)`;`cloud`;`sun(rays)`;`dashes(点列, arrow=)` 运动虚线;`sparkle`;`text(s, x, y, size, font_style='geo'|'geo_medium', cjk='cjk'|'cjk_light')`
-- 颜色常量 `INK BLUE CORAL MUSTARD TEAL PEACH CREAM`;`light=(0.8, -0.6)` 是指向光源的屏幕方向;`save('x.jpg')` 默认 quality 88、4:4:4 色度
-
**单线画 `LineArt`**:
- 思路:整幅画是一条路径。先把各个形状做成点列,再 `chain()` 按作画顺序串成一条线;线只栅格化一次成「时间图」(每个子像素记住笔第一次经过时走了多少像素),画到哪一步就是 `时间 <= s`
- 底:`backdrop('night'|'cream')`:深蓝丝绒底(中间亮、细颗粒)或奶油纸,同时设定默认线色(金 / 墨)和点睛色(琥珀 / 朱红)
@@ -573,21 +562,6 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask
| 引线横穿房顶,画面乱 | 卡片围着各自仪器摆,用 `unproject()` 按屏幕位置定点,引线短、不跨主体 |
| 草地上散落的小花像彩色糖珠 | 花开在灌木上:`tree(kind='bush', flowers=…)` |
-**扁平矢量**
-
-| 问题 | 改法 |
-|---|---|
-| 头发像头巾,从前到后裹住脸一直到下巴 | 头发 = 大一圈的椭圆减去向前下方挪动的脸,再沿「后颈→太阳穴」的发际线切掉下半;波波头另加一块只在下颌后面的发帘 |
-| 耳朵画在脸中间 | 耳朵放在发际线上(头心向后约 0.12u),画在头发之后 |
-| 颗粒太重,大色块像砂纸 | 全画面颗粒约 1%,以细颗粒为主;只有光束、光斑用 `grain` 打散透明度 |
-| 手脚按角度摆,手伸进标题、脚踩空 | 用 `hand_to` / `foot_to` 目标点(两段 IK):手落在栏杆和书上,脚落在梯级上 |
-| 3/4 侧身用近侧手臂向前上方够东西,手臂横扫过脸 | 改用远侧手臂(从前肩出发,画在头后面),近侧手臂垂下挎包 |
-| 没有描边,深色头发、深色裤子、黑猫贴在深色书架或楼影上就消失 | 按身后背景定明度:银发、橘猫、深裤配中蓝护墙板、浅色鞋;深色衣服的远侧手脚改为提亮一档 |
-| 书脊的色带和书名短线交叉成「+」,像十字架 | 色带只放书头书脚,书名短线放中段 |
-| 抽走那本书留下的空位被人挡住,故事看不出来 | 空位放在开阔处,邻书以底角为支点倒进空位,从空位拉一条珊瑚色虚线到手里的书 |
-| 珊瑚色花盆、书架上的珊瑚色书跟主角抢眼 | 点睛色只留给画面要讲的那一样东西 |
-| 动图把小面积的珊瑚色量化成褐色;透明占位色是黑色时,最暗的阴影像素变透明 | 中值切分前饱和像素 ×5,强制放入七个色板色;占位色改成纯品红 |
-
**单线画**
| 问题 | 改法 |
@@ -691,10 +665,10 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask
- 各画风都有 `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)。
-- 调色板的另外几条经验(新增十种里反复出现):
- - 小面积的点睛色(扁平矢量的珊瑚色书、报刊拼贴的芥末黄纸片、单线画的琥珀色窗、柔光 3D 的黄球)会被量化成褐色、土黄或平色片:取调色板样本时饱和像素 ×5 左右,限定色板的画风可以把色板色强制放进调色板。
+- 调色板的另外几条经验(新增的几种里反复出现):
+ - 小面积的点睛色(报刊拼贴的芥末黄纸片、单线画的琥珀色窗、柔光 3D 的黄球)会被量化成土黄、米黄或平色片:取调色板样本时饱和像素 ×5 左右,限定色板的画风可以把色板色强制放进调色板。
- 大片渐变(弥散玻璃的背景、单线画的深蓝底、Synthwave 的天空)出现一圈圈色带:量化前叠一张固定的 4×4 Bayer 抖动,每帧同一张,「和上一帧相同」的透明差分照样有效。
- - 标记「和上一帧相同」的透明占位色不要用黑色:最暗的阴影像素会被当成透明(扁平矢量自检时 37 帧对不上),改用纯品红这类画面里没有的颜色。
+ - 标记「和上一帧相同」的透明占位色不要用黑色:最暗的阴影像素会被当成透明,自检时大批帧对不上,改用纯品红这类画面里没有的颜色。
- 最后一个 `stage()` 和成品完全相同时,Pillow 会把相同的帧合并,按帧数自检会报 EOFError:`save()` 前不要紧挨着再调一次 `stage()`。
- 卡通手绘的抖线动图只抖墨线,铅笔稿和颜色不动,否则每次叠化都整片重编码,体积翻倍。
- 形变动画可以直接出真动画:`Morph.at(keys, T)` 给出全局时间 T 的轮廓,逐帧渲染即可。
@@ -723,7 +697,6 @@ lib/chalk.py 黑板板书
lib/cyberpunk.py 赛博朋克
lib/cartoon.py 卡通手绘(逐帧手绘)
lib/isometric.py 等轴 2.5D
-lib/flatvector.py 扁平矢量
lib/lineart.py 单线画
lib/soft3d.py 柔光 3D
lib/morph.py 形变动画
diff --git a/examples/drawing_flatvector_bookshop.gif b/examples/drawing_flatvector_bookshop.gif
deleted file mode 100644
index 02b360f..0000000
Binary files a/examples/drawing_flatvector_bookshop.gif and /dev/null differ
diff --git a/examples/flatvector_bookshop.jpg b/examples/flatvector_bookshop.jpg
deleted file mode 100644
index 4649f5c..0000000
Binary files a/examples/flatvector_bookshop.jpg and /dev/null differ
diff --git a/examples/flatvector_bookshop.py b/examples/flatvector_bookshop.py
deleted file mode 100644
index b53feef..0000000
--- a/examples/flatvector_bookshop.py
+++ /dev/null
@@ -1,240 +0,0 @@
-"""Example (flat vector): 周末书店 / The Weekend Bookshop — a Saturday at dusk in a small bookshop, drawn as a
-modern flat illustration: no outlines, seven flat colours, volume from overlapping colour blocks, a whisper of
-grain. The one small story: the only coral book has just come down from the top poetry shelf. A bookseller on
-the rolling ladder hangs on to the rail with one hand and lowers it with the other; a silver-haired customer in a
-mustard coat reaches up for it; a dashed coral trail marks its drop from the gap it left (the neighbour has
-already tipped over into the space). Beside the arched window -- an OPEN sign on strings, the sun setting behind
-the street -- a reader sits in a lounge chair under a pendant lamp's beam, a mug steaming on the side table; the
-shop cat watches the street from the sill; a crate of second-hand books waits on the floor.
-No image model.
-python3 flatvector_bookshop.py [out.jpg] [--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 flatvector import FlatVector, Mask, INK, BLUE, CORAL, MUSTARD, TEAL, PEACH, CREAM
-
-out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'flatvector_bookshop.jpg'
-stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
-
-W, H = 1920, 1080
-fv = FlatVector(W, H, seed=5, light=(0.8, -0.6))
-T = fv.tone
-FLOOR_Y = 905
-WOOD = T(MUSTARD, -0.12)
-
-# ---------------------------------------------------------------- wall and floor
-fv.backdrop(BLUE)
-floor = fv.rect(0, FLOOR_Y, W, H)
-fv.fill(floor, T(MUSTARD, -0.3))
-for y in (938, 984, 1046): # plank joints, wider apart toward us
- fv.fill(fv.rect(0, y, W, y + 5), T(MUSTARD, -0.38))
-fv.fill(fv.rect(0, 738, W, FLOOR_Y), T(BLUE, -0.08)) # wainscot below the sill line
-fv.fill(fv.rect(0, 732, W, 744), T(BLUE, 0.12)) # dado rail
-fv.fill(fv.rect(0, FLOOR_Y - 22, W, FLOOR_Y), T(BLUE, -0.3)) # skirting board
-fv.stage('wall')
-
-# ---------------------------------------------------------------- the arched window, sunset outside
-WX0, WX1, WY0, WY1 = 1150, 1560, 170, 716
-wr = (WX1 - WX0) / 2
-opening = fv.rrect(WX0, WY0, WX1, WY1, (wr, wr, 0, 0))
-glass = fv.rrect(WX0 + 24, WY0 + 24, WX1 - 24, WY1, (wr - 24, wr - 24, 0, 0))
-fv.fill(opening, CREAM)
-sky = [(WY0, T(PEACH, 0.45)), (330, T(PEACH, 0.2)), (440, PEACH), (540, T(CORAL, 0.3))]
-for y, c in sky:
- fv.fill(glass & fv.rect(WX0, y, WX1, WY1), c)
-fv.fill(glass & fv.circle(1405, 560, 74), MUSTARD) # the low sun
-fv.fill(glass & fv.circle(1405, 560, 74) & fv.rect(0, 560, W, H), T(MUSTARD, 0.25))
-far = [(1150, 560), (1215, 505), (1262, 585), (1330, 540), (1470, 598), (1512, 520)]
-for x, y in far: # far blocks, brick-red
- fv.fill(glass & fv.rect(x, y, x + 64, WY1), T(CORAL, -0.28))
-near = [(1150, 610, 110), (1262, 640, 70), (1335, 596, 96), (1432, 650, 70), (1500, 612, 80)]
-for x, y, w in near: # near blocks with lit windows
- b = glass & fv.rect(x, y, x + w, WY1)
- fv.fill(b, T(BLUE, -0.42))
- for wy in range(y + 16, WY1 - 10, 30):
- for wx in range(x + 12, x + w - 12, 24):
- if (wx * 7 + wy * 3) % 5 < 2:
- fv.fill(glass & fv.rect(wx, wy, wx + 10, wy + 14), MUSTARD)
-fv.fill(glass & fv.rect(WX0, 686, WX1, WY1), T(BLUE, -0.55)) # the street wall opposite
-mull = fv.rect(1350, WY0, 1360, WY1) | fv.rect(WX0, 440, WX1, 450)
-fv.fill(mull & opening, CREAM)
-fv.fill(fv.rect(WX0 + 24, WY0, WX0 + 36, WY1) & glass, T(CREAM, -0.14)) # reveal: inner side of the frame
-# a little OPEN sign hanging inside the glass on two strings
-SX, SY = 1264, 322
-for dx in (-44, 44):
- fv.fill(fv.capsule((SX, 250), (SX + dx, SY - 20), 1.6), T(INK, 0.2))
-fv.fill(fv.circle(SX, 250, 5), T(INK, 0.2))
-sign = fv.rrect(SX - 64, SY - 22, SX + 64, SY + 44, 10)
-fv.fill(sign, TEAL); fv.shade(sign, 0.0, 6, colour=T(TEAL, -0.2))
-fv.text('OPEN', SX, SY + 8, 25, CREAM, anchor='ms', spacing=4)
-fv.text('10:00 — 22:00', SX, SY + 31, 14, T(TEAL, 0.6), anchor='ms', spacing=1, font_style='geo_medium')
-sill = fv.rrect(WX0 - 28, WY1 - 6, WX1 + 28, WY1 + 22, 6)
-fv.cast(sill, 0, 14, 0.28)
-fv.fill(sill, CREAM)
-fv.fill(fv.rect(WX0 - 28, WY1 + 14, WX1 + 28, WY1 + 22) & sill, T(CREAM, -0.14))
-# the low sun lays a patch of light across the floor, falling toward us and to the left
-patch = fv.poly([(1190, FLOOR_Y), (1520, FLOOR_Y), (1300, H), (820, H)])
-fv.fill(patch, T(PEACH, 0.2), 0.2, grain=0.5)
-fv.stage('window')
-
-# ---------------------------------------------------------------- the bookcase
-BX0, BX1, BY0 = 70, 1010, 66
-case = fv.rect(BX0, BY0, BX1, FLOOR_Y)
-fv.cast(case, 22, 0, 0.3, clip=fv.rect(0, 0, W, FLOOR_Y)) # hard shadow on the wall
-fv.fill(case, CREAM)
-fv.shade(case, 0.0, 14, colour=T(CREAM, -0.12))
-fv.fill(fv.rect(BX0 - 16, BY0 - 14, BX1 + 16, BY0 + 12), T(CREAM, -0.06)) # top cap
-fv.text('周末书店', 120, 142, 60, INK, cjk='cjk')
-x_dot = 120 + fv.text_width('周末书店', 60, cjk='cjk') + 22
-fv.fill(fv.circle(x_dot, 124, 6), CORAL)
-fv.text('WEEKEND BOOKS', x_dot + 22, 136, 30, T(BLUE, -0.1), spacing=6)
-rows = [(172, 316), (330, 474), (488, 632), (646, 790)] # (top, board) per row
-bays = [(BX0 + 22, 372), (390, 690), (708, BX1 - 22)]
-back = Mask(np.zeros((0, 0)))
-for (y0, y1) in rows:
- for (a, b) in bays:
- back = back | fv.rect(a, y0, b, y1)
-back = back | fv.rect(BX0 + 22, 804, BX1 - 22, 856)
-fv.fill(back, T(BLUE, -0.3))
-fv.darken(back & fv.rect(0, 0, W, 186) | back & fv.rect(0, 330, W, 344) | back & fv.rect(0, 488, W, 502)
- | back & fv.rect(0, 646, W, 660), 0.18) # under each board, a flat shadow
-fv.fill(fv.rect(BX0 + 22, 856, BX1 - 22, 872), CREAM)
-# the ladder rail runs along under the top cap
-fv.fill(fv.capsule((BX0 + 10, 162), (BX1 - 10, 162), 7), INK)
-for x in (BX0 + 30, 540, BX1 - 30):
- fv.fill(fv.rrect(x - 7, 150, x + 7, 176, 3), T(INK, 0.2))
-fv.stage('bookcase')
-
-# ---------------------------------------------------------------- books
-cols = [INK, CREAM, TEAL, MUSTARD, PEACH, T(BLUE, 0.45), T(TEAL, -0.3)]
-for ri, (y0, y1) in enumerate(rows):
- for bi, (a, b) in enumerate(bays):
- gap = (842, 40) if (ri, bi) == (0, 2) else (None, 0)
- stack = {(1, 0): 250, (2, 1): 560, (3, 2): 900, (0, 0): None}.get((ri, bi))
- fv.books(a + 4, b - 2, y1, (y1 - y0) * 0.9, cols, seed=100 + ri * 10 + bi, gap_at=gap[0], gap_w=gap[1],
- stack_at=stack, back=back)
-fv.books(BX0 + 26, BX1 - 24, 856, 48, [T(INK, 0.1), T(TEAL, -0.2), T(BLUE, 0.3)], seed=77, w_range=(0.9, 1.6), title=False)
-# category tabs hanging from the boards
-for (x, y, s) in [(918, 316, '诗歌 POETRY'), (240, 474, '小说 FICTION'), (470, 632, '旅行 TRAVEL')]:
- w = fv.text_width(s, 17, spacing=1.5) + 30
- tab = fv.rrect(x - w / 2, y + 2, x + w / 2, y + 34, (0, 0, 8, 8))
- fv.fill(tab, MUSTARD)
- fv.text(s, x, y + 25, 17, INK, anchor='ms', spacing=1.5)
-fv.stage('books')
-
-# ---------------------------------------------------------------- furniture: ladder, plant, table, chair, lamp
-# rolling ladder: hooks on the rail, stiles splay toward the wheels on the floor
-LT, LB = 162, 932
-stiles = [((598, LT), (578, LB)), ((724, LT), (744, LB))]
-for (p0, p1) in stiles:
- fv.cast(fv.capsule(p0, p1, 9), -10, 0, 0.25, clip=back | case)
-for yr in range(236, 900, 74):
- t = (yr - LT) / (LB - LT)
- xa, xb = 598 + (578 - 598) * t, 724 + (744 - 724) * t
- fv.fill(fv.rrect(xa, yr - 7, xb, yr + 7, 4), T(WOOD, -0.12))
-for (p0, p1) in stiles:
- s = fv.capsule(p0, p1, 11)
- fv.fill(s, WOOD); fv.shade(s, 0.0, 7, colour=T(WOOD, -0.2))
-fv.fill(fv.circle(598, LT, 13) | fv.circle(724, LT, 13), INK) # hooks over the rail
-fv.darken(fv.ellipse(661, LB + 14, 120, 10), 0.3)
-for x in (578, 744):
- fv.fill(fv.circle(x, LB, 15), INK); fv.fill(fv.circle(x, LB, 5), T(INK, 0.4))
-
-fv.stage('ladder')
-
-# tall plant between the bookcase and the window
-fv.darken(fv.ellipse(1090, 928, 80, 9), 0.3)
-fv.plant(1090, 928, 430, pot=CREAM, leaf=TEAL, kind='leafy', seed=8, n=9)
-
-# rug, lounge chair (facing left), side table
-rug = fv.rrect(1260, 912, 1880, 968, 28)
-fv.fill(rug, T(TEAL, -0.42))
-for x in range(1296, 1860, 44):
- fv.fill(fv.rect(x, 912, x + 14, 968) & rug, T(TEAL, -0.28))
-CH = T(TEAL, 0.0)
-for (p0, p1, k) in [((1560, 850), (1548, 928), -0.3), ((1790, 850), (1806, 928), -0.3)]:
- fv.fill(fv.capsule(p0, p1, 7, 5), T(WOOD, k)) # far legs
-fv.darken(fv.ellipse(1680, 934, 150, 10), 0.3)
-backrest = fv.rrect(1742, 590, 1836, 850, (46, 46, 30, 30), rot=-10)
-fv.cast(backrest, -26, 0, 0.22, clip=fv.rect(0, 0, W, FLOOR_Y - 22))
-fv.fill(backrest, CH); fv.shade(backrest, 0.0, 26, colour=T(CH, -0.2))
-fv.fill(fv.rrect(1760, 610, 1800, 720, 20, rot=-10), T(CH, 0.14)) # the button tuft band
-seat = fv.rrect(1530, 792, 1800, 850, 24)
-fv.fill(seat, CH); fv.shade(seat, 0.0, 18, colour=T(CH, -0.2))
-fv.fill(fv.rect(1540, 846, 1806, 862), WOOD)
-for (p0, p1) in [((1580, 860), (1568, 930)), ((1772, 860), (1788, 930))]:
- fv.fill(fv.capsule(p0, p1, 8, 6), WOOD)
-# side table with two books and a mug of tea
-TT = 816
-fv.darken(fv.ellipse(1390, 932, 70, 8), 0.3)
-fv.fill(fv.capsule((1390, TT), (1390, 924), 7), T(INK, 0.15))
-fv.fill(fv.rrect(1344, 918, 1436, 930, 6), T(INK, 0.15))
-top = fv.rrect(1316, TT, 1464, TT + 16, 8)
-fv.fill(top, WOOD); fv.shade(top, 0.0, 6, colour=T(WOOD, -0.2))
-yb = TT
-for (x, w, h, c) in [(1334, 116, 18, INK), (1344, 100, 16, T(BLUE, 0.45))]:
- bk = fv.rrect(x, yb - h, x + w, yb, 3)
- fv.fill(bk, c); fv.fill(fv.rect(x + w - 10, yb - h, x + w, yb) & bk, T(c, -0.2))
- fv.fill(fv.rect(x, yb - h * 0.6, x + w - 12, yb - h * 0.4), T(c, 0.5))
- yb -= h
-MX = 1398
-mug = fv.rrect(MX, yb - 44, MX + 40, yb, (4, 4, 10, 10))
-fv.fill(fv.arc(MX + 40, yb - 23, 8, 15, -90, 90), CREAM)
-fv.fill(mug, CREAM); fv.shade(mug, 0.0, 10, colour=T(CREAM, -0.14))
-fv.fill(fv.rect(MX, yb - 33, MX + 40, yb - 25), CORAL)
-MUG_TOP = yb - 44
-# pendant lamp over the chair (its beam comes later)
-LX, LY = 1655, 346
-fv.pendant(LX, 0, LY, 56, shade=INK, bulb=CREAM)
-# a crate of second-hand books on the floor, bottom left
-fv.darken(fv.ellipse(290, 1010, 200, 12), 0.3)
-fv.books(150, 430, 948, 118, [CREAM, T(BLUE, 0.45), TEAL, MUSTARD, PEACH, INK], seed=31, w_range=(0.16, 0.3), title=False)
-crate = fv.rrect(128, 930, 452, 1010, 6)
-fv.fill(crate, WOOD); fv.shade(crate, 0.0, 16, colour=T(WOOD, -0.2))
-for y in (955, 983):
- fv.fill(fv.rect(128, y, 452, y + 4), T(WOOD, -0.28))
-fv.fill(fv.rrect(250, 944, 330, 996, 6), CREAM) # a card pinned on the front
-fv.text('¥10', 290, 980, 26, INK, anchor='ms')
-fv.stage('furniture')
-
-# ---------------------------------------------------------------- people
-# the customer in front of the bookcase, reaching up for the book, head tipped back to look at it
-fv.darken(fv.ellipse(912, 962, 78, 9), 0.32)
-BOOK = (786, 372)
-B = fv.person((908, 748), 400, facing=-1, lean=-5, head_tilt=-20, hand_far_to=(826, 458), arm=(-6, 4),
- leg=(-3, 0), leg_far=(5, 0), top=MUSTARD, bottom=INK, coat=True, hair=T(CREAM, -0.2), hair_style='bob',
- bag=CREAM)
-# the bookseller on the ladder: near foot on a rung, far foot one rung up, far hand on the rail, the near hand
-# lowering the book
-RUNG = lambda y: (y - 7)
-A = fv.person((652, 404), 372, facing=1, lean=8, head_tilt=12, hand_to=(BOOK[0] - 14, BOOK[1] + 6),
- hand_far_to=(742, 166), foot_to=(648, RUNG(606) - 15), foot_far_to=(682, RUNG(532) - 15),
- top=CREAM, bottom=T(INK, 0.1), apron=TEAL, hair=T(MUSTARD, -0.62), hair_style='bun', draw_near_arm=False)
-fv.book(*BOOK, 66, 88, rot=-16, colour=CORAL)
-fv.near_arm()
-fv.stage('handoff')
-# the reader in the lounge chair, a book open in both hands, head bowed over it
-C = fv.person((1692, 790), 372, facing=-1, sit=True, lean=-6, head_tilt=18, hand_to=(1612, 716), hand_far_to=(1598, 728),
- foot_to=(1560, 884), foot_far_to=(1600, 892), top=CREAM, bottom=INK, shoes=CREAM, hair=T(CORAL, -0.6),
- hair_style='bob', draw_near_arm=False)
-fv.book(1600, 712, 104, 66, rot=-22, colour=MUSTARD, open=True)
-fv.near_arm()
-# the shop cat on the sill, watching the street
-fv.cat(1296, WY1 - 6, 78, T(MUSTARD, -0.12), facing=1, tail_down=WY1 + 80)
-fv.stage('reader')
-
-# ---------------------------------------------------------------- light and the story marks
-fv.fill(fv.poly([(LX - 40, LY), (LX + 40, LY), (1800, 912), (1500, 912)]), T(CREAM, 0.3), 0.12, grain=0.4)
-fv.fill(fv.circle(LX, LY + 3, 17), T(CREAM, 0.5))
-# a dashed trail from the empty slot on the top shelf down to the book in the bookseller's hand
-fv.dashes([(862, 262), (850, 318), (818, 338)], width=6, dash=14, gap=11, colour=CORAL)
-for (x, y, r, c) in [(884, 236, 15, MUSTARD), (744, 326, 10, CREAM), (824, 300, 8, CREAM)]:
- fv.sparkle(x, y, r, c)
-# steam off the mug
-for dx, h in ((-7, 48), (7, 36)):
- y0 = MUG_TOP - 8
- fv.fill(fv.tube([(MX + 20 + dx, y0), (MX + 26 + dx, y0 - h * 0.35), (MX + 16 + dx, y0 - h * 0.7), (MX + 21 + dx, y0 - h)],
- [3.2, 3, 2.2, 1.2]), CREAM, 0.75)
-img = fv.save(out, stages_dir=stages) # the final frame is the 'light' stage
-print('saved', out)
diff --git a/lib/flatvector.py b/lib/flatvector.py
deleted file mode 100644
index e8a3285..0000000
--- a/lib/flatvector.py
+++ /dev/null
@@ -1,943 +0,0 @@
-"""flatvector — modern flat vector illustration: geometric shapes, no outlines, a small saturated palette, volume
-built from overlapping blocks of flat colour, a whisper of print grain, and faceless grown-up people
-(numpy + Pillow only).
-
-Model: an artboard in a vector app, not a canvas with paint on it.
- shapes every mark is a closed geometric shape with a crisp anti-aliased edge: circles, ellipses, rounded
- rectangles (per-corner radii), tapered capsules (limbs, stems, cords), polygons whose corners are
- filleted with true arcs, ring segments and pies, leaves (a vesica between two points). A shape is a
- `Mask`: a coverage patch plus its offset on the artboard, so union `|`, intersection `&`,
- difference `-` and `moved()` only touch the overlap of bounding boxes -- a picture of a thousand
- shapes stays fast.
- no lines there are no outlines. Two neighbouring shapes are told apart only by value and hue, so every
- object is planned against what sits behind it (a cream shelf on a blue wall, a mustard coat on a
- cream shelf). Thin things (cords, rails, steam, dashes) are themselves filled capsules.
- palette five to seven flat hues (here INK, BLUE, CORAL, MUSTARD, TEAL, PEACH, CREAM). Every other colour
- is a *tone* of one of them: `tone(c, -k)` mixes toward the palette's ink, `tone(c, +k)` toward its
- cream. Shadows are never grey or black -- they are the ink mixed in, so they stay in the family.
- volume flat colour blocks stacked on top of each other, the way you would cut them in a vector app:
- `shade()` lays a darker block on the side away from the light, cut out as "the shape minus a
- copy of itself nudged toward the light" (a crisp crescent that follows the silhouette);
- `plane()` cuts an object with a straight line (the side face of a box, the dark half of a leaf);
- `glint()` is the same crescent in a lighter tone on the lit side; `cast()` drops a hard-edged
- flat shadow onto whatever is already underneath (it multiplies by an ink tint, so a shadow that
- falls across three colours darkens each in its own hue). No gradients, no blur.
- light a lamp's beam or a patch of low sun is one translucent flat shape (`fill(..., alpha)`), its alpha
- lightly broken by grain so it reads as light, not as a pane of glass.
- grain the finished artboard gets a very light monochrome print grain (about 1% in value, a little
- clumpy), just enough to stop large flat fields looking like a screen.
- people simplified, faceless, adult proportions (7.5 heads tall): a skeleton of hip, shoulders, elbows,
- wrists, knees and ankles driven by joint angles, or by hand / foot targets (two-bone IK: elbows
- drop, knees go forward); a 3/4 torso (shoulders wider than waist, rounded
- shoulder fillets), tapered limbs, mitten hands, flat shoes; a head that is one ellipse whose hair
- is "a slightly bigger ellipse minus the face ellipse nudged forward and down" (plus a bun, bob,
- long panel or pony). The far arm and far leg are one tone darker, so the body turns in space
- without a single line. Clothes: top, trousers or skirt, coat, apron, tote bag.
- objects a row of book spines (varied heights and widths, bands and a title dash in tones of the spine's
- own colour, a pile lying flat, the neighbour of a taken-out book tipped into the gap, the last book
- of a short row leaning on the side panel, each dropping a flat shadow on the shelf back), a single
- book (closed or open),
- potted plants (split two-tone leaves), a pendant lamp with a flat beam, a sitting cat, clouds,
- sun, dashed motion paths, four-point sparkles, and set lettering (geometric sans + CJK sans).
-Angles: `rot` for shapes is degrees counter-clockwise; a person's joint angles are degrees measured from
-"straight down", positive toward the way the person faces.
-
- from flatvector import FlatVector, INK, BLUE, CORAL, MUSTARD, TEAL, PEACH, CREAM
- fv = FlatVector(1920, 1080, seed=3)
- fv.backdrop(BLUE)
- floor = fv.rect(0, 880, 1920, 1080); fv.fill(floor, fv.tone(MUSTARD, -0.3))
- sofa = fv.rrect(1200, 700, 1700, 900, (60, 60, 12, 12)); fv.cast(sofa, 30, 0, clip=floor); fv.fill(sofa, TEAL)
- fv.shade(sofa, 0.2, depth=40) # a darker block on the side away from the light
- p = fv.person((1450, 760), 400, facing=-1, sit=True, top=CORAL, hair_style='bun')
- fv.book(*p['hand'], 90, 60, rot=10, colour=MUSTARD, open=True)
- fv.pendant(1450, 0, 320, 70, beam_to=(1300, 1600, 760))
- fv.text('周末 WEEKEND', 120, 160, 64, CREAM)
- fv.save('out.jpg')
-"""
-import glob
-import os
-import numpy as np
-from PIL import Image, ImageDraw, ImageFont
-from core import blur, spline, noise2d, load_font
-
-INK, BLUE, CORAL, MUSTARD, TEAL, PEACH, CREAM = '#1e1b45', '#3346d3', '#ff6150', '#ffb838', '#19b39a', '#f6b39b', '#fbf1df'
-PALETTE = dict(ink=INK, blue=BLUE, coral=CORAL, mustard=MUSTARD, teal=TEAL, peach=PEACH, cream=CREAM)
-
-
-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(PALETTE.get(c, c))
- return np.asarray(c, np.float32)
-
-
-def _is_cjk(ch):
- return ord(ch) >= 0x2e80
-
-
-# ---------------------------------------------------------------- fonts (local list; falls back to core.load_font)
-_FONTS = {
- 'geo': [('/System/Library/Fonts/Supplemental/Futura.ttc', 2), ('/System/Library/Fonts/Avenir Next.ttc', 0),
- ('/usr/share/fonts/**/URWGothic-Demi.*', 0), ('/usr/share/fonts/**/Montserrat-Bold.ttf', 0),
- ('C:/Windows/Fonts/GOTHICB.TTF', 0), ('C:/Windows/Fonts/arialbd.ttf', 0)],
- 'geo_medium': [('/System/Library/Fonts/Supplemental/Futura.ttc', 0), ('/System/Library/Fonts/Avenir Next.ttc', 5),
- ('/usr/share/fonts/**/URWGothic-Book.*', 0), ('C:/Windows/Fonts/GOTHIC.TTF', 0), ('C:/Windows/Fonts/arial.ttf', 0)],
- 'cjk': [('/System/Library/Fonts/Hiragino Sans GB.ttc', 2), ('/System/Library/Fonts/STHeiti Medium.ttc', 1),
- ('/usr/share/fonts/**/NotoSansCJK*Bold*.tt[cf]', 0), ('/usr/share/fonts/**/NotoSansCJK*.tt[cf]', 0),
- ('C:/Windows/Fonts/msyhbd.ttc', 0), ('C:/Windows/Fonts/msyh.ttc', 0)],
- 'cjk_light': [('/System/Library/Fonts/Hiragino Sans GB.ttc', 0), ('/System/Library/Fonts/STHeiti Light.ttc', 1),
- ('/usr/share/fonts/**/NotoSansCJK*Regular*.tt[cf]', 0), ('C:/Windows/Fonts/msyh.ttc', 0)],
-}
-_FONT_CACHE = {}
-
-
-def font(style, size):
- """PIL font for 'geo' (geometric sans bold), 'geo_medium', 'cjk' (CJK sans bold), 'cjk_light';
- any other name goes to core.load_font (sans, sans_bold, rounded, ...). $INKPAINT_FONT_<STYLE> overrides."""
- key = (style, int(size))
- if key in _FONT_CACHE: return _FONT_CACHE[key]
- f = None
- env = os.environ.get('INKPAINT_FONT_' + style.upper())
- cands = ([(env, 0)] if env and os.path.exists(env) else []) + _FONTS.get(style, [])
- for pat, idx in cands:
- for p in glob.glob(pat, recursive=True):
- try:
- f = ImageFont.truetype(p, int(size), index=idx); break
- except OSError:
- pass
- if f: break
- if f is None:
- f = load_font({'geo': 'sans_bold', 'geo_medium': 'sans', 'cjk': 'cjk_sans', 'cjk_light': 'cjk_sans'}.get(style, style), size)
- _FONT_CACHE[key] = f
- return f
-
-
-# ---------------------------------------------------------------- Mask: a coverage patch with an offset
-class Mask:
- """anti-aliased coverage `a` (0..1, float32) whose top-left pixel sits at artboard (x0, y0).
- a | b union, a & b intersection, a - b difference, a * k fade, a.moved(dx, dy) nudge (free)."""
- __slots__ = ('a', 'x0', 'y0')
-
- def __init__(self, a, x0=0, y0=0):
- self.a, self.x0, self.y0 = np.asarray(a, np.float32), int(x0), int(y0)
-
- @property
- def x1(self): return self.x0 + self.a.shape[1]
-
- @property
- def y1(self): return self.y0 + self.a.shape[0]
-
- @property
- def empty(self): return self.a.size == 0 or not self.a.any()
-
- def on(self, x0, y0, x1, y1):
- """this mask sampled on the box [x0, x1) x [y0, y1) (zero outside itself)"""
- out = np.zeros((max(0, y1 - y0), max(0, x1 - x0)), np.float32)
- ix0, iy0, ix1, iy1 = max(x0, self.x0), max(y0, self.y0), min(x1, self.x1), min(y1, self.y1)
- if ix1 > ix0 and iy1 > iy0:
- out[iy0 - y0:iy1 - y0, ix0 - x0:ix1 - x0] = self.a[iy0 - self.y0:iy1 - self.y0, ix0 - self.x0:ix1 - self.x0]
- return out
-
- def __or__(self, o):
- if o is None or o.a.size == 0: return self
- if self.a.size == 0: return o
- b = (min(self.x0, o.x0), min(self.y0, o.y0), max(self.x1, o.x1), max(self.y1, o.y1))
- return Mask(np.maximum(self.on(*b), o.on(*b)), b[0], b[1])
-
- def __and__(self, o):
- b = (max(self.x0, o.x0), max(self.y0, o.y0), min(self.x1, o.x1), min(self.y1, o.y1))
- if b[2] <= b[0] or b[3] <= b[1]: return Mask(np.zeros((0, 0)), 0, 0)
- return Mask(self.on(*b) * o.on(*b), b[0], b[1])
-
- def __sub__(self, o):
- if o is None or o.a.size == 0: return self
- return Mask(self.a * (1 - o.on(self.x0, self.y0, self.x1, self.y1)), self.x0, self.y0)
-
- def __mul__(self, k):
- return Mask(self.a * k, self.x0, self.y0)
-
- def moved(self, dx, dy):
- return Mask(self.a, self.x0 + int(round(dx)), self.y0 + int(round(dy)))
-
- def grown(self, r):
- """dilate (r > 0) or erode (r < 0) by about |r| px, keeping a crisp edge"""
- p = int(abs(r)) + 3
- a = np.pad(self.a, p)
- b = blur(a, abs(r) * 0.6 + 0.5)
- t = 0.5 - 0.42 * np.sign(r) * min(1.0, abs(r) / (abs(r) + 1.2))
- return Mask(np.clip((b - t) * 3.0 + 0.5, 0, 1) if r else a, self.x0 - p, self.y0 - p)
-
- @staticmethod
- def union(*ms):
- out = Mask(np.zeros((0, 0)))
- for m in ms: out = out | m
- return out
-
-
-def _fillet(pts, r, n=10):
- """polygon with every corner replaced by a true circular arc of radius r (scalar or per-vertex list)"""
- P = np.asarray(pts, np.float64)
- k = len(P)
- rs = np.broadcast_to(np.asarray(r, np.float64), (k,))
- out = []
- for i in range(k):
- p, a, b = P[i], P[i - 1], P[(i + 1) % k]
- if rs[i] <= 0.5:
- out.append(p); continue
- u, v = a - p, b - p
- lu, lv = np.linalg.norm(u), np.linalg.norm(v)
- if lu < 1e-6 or lv < 1e-6:
- out.append(p); continue
- u, v = u / lu, v / lv
- th = np.arccos(np.clip(u @ v, -1, 1))
- if th < 1e-3 or th > np.pi - 1e-3:
- out.append(p); continue
- t = min(rs[i] / np.tan(th / 2), 0.5 * lu, 0.5 * lv)
- rr = t * np.tan(th / 2)
- w = (u + v) / np.linalg.norm(u + v)
- c = p + w * rr / np.sin(th / 2)
- t1, t2 = p + u * t, p + v * t
- for s in np.linspace(0, 1, n):
- q = t1 * (1 - s) + t2 * s - c
- out.append(c + q / (np.linalg.norm(q) + 1e-9) * rr)
- return np.array(out)
-
-
-class FlatVector:
- def __init__(self, W=1920, H=1080, seed=0, light=(0.8, -0.6), ink=INK, cream=CREAM):
- self.W, self.H = W, H
- self.rng = np.random.default_rng(seed)
- self.img = np.ones((H, W, 3), np.float32)
- self.ink, self.cream = _c(ink), _c(cream)
- l = np.asarray(light, np.float32)
- self.light = l / (np.linalg.norm(l) + 1e-9) # unit vector pointing toward the light (screen)
- self._noise = None
- self.stages = []
-
- def _seed(self):
- return int(self.rng.integers(1 << 30))
-
- # ------------------------------------------------------------ colour
- def tone(self, c, k):
- """a tone of palette colour c: k < 0 mixes toward the ink (shade), k > 0 toward the cream (tint)"""
- c = _c(c)
- return c + (self.ink - c) * (-k) if k < 0 else c + (self.cream - c) * k
-
- @staticmethod
- def mix(a, b, t):
- return _c(a) * (1 - t) + _c(b) * t
-
- # ------------------------------------------------------------ shape masks
- def _grid(self, x0, y0, x1, y1):
- x0, y0 = max(0, int(np.floor(x0)) - 2), max(0, int(np.floor(y0)) - 2)
- x1, y1 = min(self.W, int(np.ceil(x1)) + 2), min(self.H, int(np.ceil(y1)) + 2)
- if x1 <= x0 or y1 <= y0: return None
- Y, X = np.mgrid[y0:y1, x0:x1].astype(np.float32)
- return X + 0.5, Y + 0.5, x0, y0
-
- @staticmethod
- def _cov(d):
- return np.clip(0.5 - d, 0, 1).astype(np.float32)
-
- def _mk(self, g, d):
- if g is None: return Mask(np.zeros((0, 0)))
- return Mask(self._cov(d), g[2], g[3])
-
- def circle(self, cx, cy, r):
- g = self._grid(cx - r, cy - r, cx + r, cy + r)
- return self._mk(g, None if g is None else np.hypot(g[0] - cx, g[1] - cy) - r)
-
- def ellipse(self, cx, cy, rx, ry, rot=0.0):
- R = max(rx, ry)
- g = self._grid(cx - R, cy - R, cx + R, cy + R)
- if g is None: return self._mk(g, None)
- t = np.deg2rad(rot)
- dx, dy = g[0] - cx, g[1] - cy
- u, v = dx * np.cos(t) - dy * np.sin(t), dx * np.sin(t) + dy * np.cos(t)
- k0 = np.hypot(u / rx, v / ry)
- k1 = np.hypot(u / rx ** 2, v / ry ** 2) + 1e-9
- return self._mk(g, k0 * (k0 - 1) / k1)
-
- def rect(self, x0, y0, x1, y1):
- return self.rrect(x0, y0, x1, y1, 0)
-
- def rrect(self, x0, y0, x1, y1, r=0, rot=0.0):
- """rounded rectangle; r scalar or (top-left, top-right, bottom-right, bottom-left); rot about its centre"""
- cx, cy, hw, hh = (x0 + x1) / 2, (y0 + y1) / 2, abs(x1 - x0) / 2, abs(y1 - y0) / 2
- R = np.hypot(hw, hh) if rot else 0
- g = self._grid(cx - (R or hw), cy - (R or hh), cx + (R or hw), cy + (R or hh))
- if g is None: return self._mk(g, None)
- t = np.deg2rad(rot)
- dx, dy = g[0] - cx, g[1] - cy
- u, v = dx * np.cos(t) - dy * np.sin(t), dx * np.sin(t) + dy * np.cos(t)
- rs = np.broadcast_to(np.asarray(r, np.float32), (4,))
- rr = np.where(v < 0, np.where(u < 0, rs[0], rs[1]), np.where(u < 0, rs[3], rs[2]))
- rr = np.minimum(rr, min(hw, hh))
- qx, qy = np.abs(u) - hw + rr, np.abs(v) - hh + rr
- d = np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) + np.minimum(np.maximum(qx, qy), 0) - rr
- return self._mk(g, d)
-
- def capsule(self, p0, p1, r0, r1=None):
- """a bar with round ends from p0 (radius r0) to p1 (radius r1): limbs, stems, cords, dashes"""
- r1 = r0 if r1 is None else r1
- (ax, ay), (bx, by) = p0, p1
- R = max(r0, r1)
- g = self._grid(min(ax, bx) - R, min(ay, by) - R, max(ax, bx) + R, max(ay, by) + R)
- if g is None: return self._mk(g, None)
- dx, dy = bx - ax, by - ay
- L2 = dx * dx + dy * dy + 1e-9
- t = np.clip(((g[0] - ax) * dx + (g[1] - ay) * dy) / L2, 0, 1)
- d = np.hypot(g[0] - ax - t * dx, g[1] - ay - t * dy) - (r0 + (r1 - r0) * t)
- return self._mk(g, d)
-
- def limb(self, pts, radii):
- """a chain of tapered capsules through pts with a radius per point (arms, legs, tails)"""
- m = Mask(np.zeros((0, 0)))
- for i in range(len(pts) - 1):
- m = m | self.capsule(pts[i], pts[i + 1], radii[i], radii[i + 1])
- return m
-
- def tube(self, pts, r, per=10):
- """a smooth capsule along a Catmull-Rom curve (cords, tails, steam)"""
- P = spline(pts, per) if len(pts) > 2 else np.asarray(pts, np.float32)
- rr = np.broadcast_to(np.asarray(r, np.float32), (len(P),)) if np.ndim(r) == 0 else np.interp(
- np.linspace(0, 1, len(P)), np.linspace(0, 1, len(r)), r)
- return self.limb(P, rr)
-
- def poly(self, pts, round=0, ss=4):
- """filled polygon; `round` fillets every corner (scalar or one radius per vertex) with a true arc"""
- P = _fillet(pts, round) if np.any(np.asarray(round) > 0) else np.asarray(pts, np.float64)
- x0, y0 = P.min(0); x1, y1 = P.max(0)
- g = self._grid(x0, y0, x1, y1)
- if g is None: return Mask(np.zeros((0, 0)))
- gx, gy = g[2], g[3]
- w, h = g[0].shape[1], g[0].shape[0]
- im = Image.new('L', (w * ss, h * ss), 0)
- ImageDraw.Draw(im).polygon([((x - gx) * ss, (y - gy) * ss) for x, y in P], fill=255)
- a = np.asarray(im.resize((w, h), Image.BOX), np.float32) / 255
- return Mask(a, gx, gy)
-
- def arc(self, cx, cy, r0, r1, a0, a1):
- """ring segment between radii r0 < r1, from angle a0 to a1 (degrees, counter-clockwise from +x)"""
- g = self._grid(cx - r1, cy - r1, cx + r1, cy + r1)
- if g is None: return self._mk(g, None)
- dx, dy = g[0] - cx, -(g[1] - cy)
- rad = np.hypot(dx, dy)
- dr = np.maximum(r0 - rad, rad - r1)
- mid, half = np.deg2rad((a0 + a1) / 2), np.deg2rad(abs(a1 - a0) / 2)
- ang = np.abs((np.arctan2(dy, dx) - mid + np.pi) % (2 * np.pi) - np.pi)
- da = (ang - half) * np.maximum(rad, 1)
- return self._mk(g, np.maximum(dr, da))
-
- def pie(self, cx, cy, r, a0, a1):
- return self.arc(cx, cy, -1, r, a0, a1)
-
- def leaf(self, p0, p1, width, bend=0.0, n=28):
- """a leaf / petal: a pointed vesica from base p0 to tip p1, `bend` bows it sideways (px)"""
- p0, p1 = np.asarray(p0, np.float64), np.asarray(p1, np.float64)
- d = p1 - p0; L = np.linalg.norm(d) + 1e-9
- nrm = np.array([-d[1], d[0]]) / L
- t = np.linspace(0, 1, n)
- spine = p0 + d * t[:, None] + nrm * (4 * t * (1 - t) * bend)[:, None]
- w = width / 2 * np.sin(np.pi * t) ** 0.75 * (1 - 0.25 * t)
- left = spine + nrm * w[:, None]; right = spine - nrm * w[:, None]
- return self.poly(np.vstack([left, right[::-1]]))
-
- def star(self, cx, cy, r, points=4, inner=0.28, rot=0.0):
- """a sparkle / star polygon"""
- a = np.deg2rad(rot) + np.arange(points * 2) * np.pi / points - np.pi / 2
- rr = np.where(np.arange(points * 2) % 2 == 0, r, r * inner)
- return self.poly(np.stack([cx + rr * np.cos(a), cy + rr * np.sin(a)], 1), round=r * 0.04)
-
- def split(self, m, p0, p1):
- """the part of m on the left of the line p0 -> p1 as you walk along it on screen
- (a line drawn left -> right keeps what is above it; top -> bottom keeps what is to its right)"""
- if m.a.size == 0: return m
- Y, X = np.mgrid[m.y0:m.y1, m.x0:m.x1].astype(np.float32)
- dx, dy = p1[0] - p0[0], p1[1] - p0[1]
- L = np.hypot(dx, dy) + 1e-9
- d = -((X + 0.5 - p0[0]) * dy - (Y + 0.5 - p0[1]) * dx) / L
- return Mask(m.a * self._cov(d), m.x0, m.y0)
-
- def text_mask(self, s, x, y, size, font_style='geo', anchor='ls', spacing=0.0, cjk='cjk'):
- """set lettering as a mask. Latin runs use `font_style`, CJK runs `cjk`; anchor: l/m/r + s (baseline)/m"""
- runs = []
- for ch in s:
- st = cjk if _is_cjk(ch) else font_style
- if runs and runs[-1][0] == st: runs[-1][1] += ch
- else: runs.append([st, ch])
- adv = []
- for st, t in runs:
- f = font(st, size)
- adv.append(sum(f.getlength(ch) + spacing for ch in t))
- total = sum(adv) - spacing
- x0 = x - total * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor[0]]
- if anchor[1] == 'm':
- y = y + size * 0.36
- pad = int(size * 0.6) + 4
- bx0, by0 = int(x0) - pad, int(y - size * 1.3) - pad
- w, h = int(total) + 2 * pad, int(size * 1.9) + 2 * pad
- im = Image.new('L', (w, h), 0)
- d = ImageDraw.Draw(im)
- cx = x0 - bx0
- for (st, t), a in zip(runs, adv):
- f = font(st, size)
- if spacing:
- for ch in t:
- d.text((cx, y - by0), ch, font=f, fill=255, anchor='ls'); cx += f.getlength(ch) + spacing
- else:
- d.text((cx, y - by0), t, font=f, fill=255, anchor='ls'); cx += a
- return Mask(np.asarray(im, np.float32) / 255, bx0, by0)
-
- def text_width(self, s, size, font_style='geo', spacing=0.0, cjk='cjk'):
- return sum(font(cjk if _is_cjk(ch) else font_style, size).getlength(ch) + spacing for ch in s) - spacing
-
- # ------------------------------------------------------------ painting
- def _region(self, m):
- x0, y0, x1, y1 = max(0, m.x0), max(0, m.y0), min(self.W, m.x1), min(self.H, m.y1)
- if x1 <= x0 or y1 <= y0: return None, None
- return (slice(y0, y1), slice(x0, x1)), m.a[y0 - m.y0:y1 - m.y0, x0 - m.x0:x1 - m.x0]
-
- def _grain_field(self):
- if self._noise is None:
- r = np.random.default_rng(12345)
- fine = blur(r.random((self.H, self.W)).astype(np.float32), 0.55)
- fine = (fine - fine.mean()) / (fine.std() + 1e-6)
- clump = noise2d(self.H, self.W, 3.0, 2, 777)
- self._noise = (0.85 * fine + 0.25 * (clump - 0.5) / 0.15).astype(np.float32)
- return self._noise
-
- def fill(self, m, colour, alpha=1.0, grain=0.0):
- """lay a flat colour through mask m. alpha < 1 is a translucent sheet; grain breaks its alpha into a
- fine speckle (light beams, sun patches)"""
- sl, a = self._region(m)
- if sl is None: return m
- a = a * alpha
- if grain:
- a = np.clip(a * (1 + grain * self._grain_field()[sl] * 0.5), 0, 1)
- c = _c(colour)
- self.img[sl] += (c - self.img[sl]) * a[..., None]
- return m
-
- def darken(self, m, strength=0.25, tint=None):
- """multiply what is already there by an ink tint (flat shadow on any colour, stays in the palette)"""
- sl, a = self._region(m)
- if sl is None: return m
- t = self.ink if tint is None else _c(tint)
- k = 1 + (t - 1) * strength
- self.img[sl] *= 1 + (k - 1) * a[..., None]
- return m
-
- def lighten(self, m, strength=0.25, tint=None):
- """screen toward the cream (a lit plane on any colour)"""
- sl, a = self._region(m)
- if sl is None: return m
- t = self.cream if tint is None else _c(tint)
- self.img[sl] += (t - self.img[sl]) * (a * strength)[..., None]
- return m
-
- def shade(self, m, strength=0.22, depth=14, colour=None):
- """a crisp crescent on the side away from the light: m minus m nudged `depth` px toward the light"""
- cr = m - m.moved(self.light[0] * depth, self.light[1] * depth)
- return self.fill(cr, colour) if colour is not None else self.darken(cr, strength)
-
- def glint(self, m, strength=0.3, depth=8, colour=None):
- """the lit-side crescent in a lighter tone"""
- cr = m - m.moved(-self.light[0] * depth, -self.light[1] * depth)
- return self.fill(cr, colour) if colour is not None else self.lighten(cr, strength)
-
- def plane(self, m, p0, p1, strength=0.22, colour=None):
- """cut m with the line p0 -> p1 and shade the part on its left (see split): box side faces, the dark half
- of a leaf. Pass colour for a flat block instead of a multiply"""
- part = self.split(m, p0, p1)
- return self.fill(part, colour) if colour is not None else self.darken(part, strength)
-
- def cast(self, m, dx, dy, strength=0.22, clip=None):
- """a hard flat shadow of m, offset (dx, dy), onto whatever is already painted (clip limits the surface).
- Call it before painting the object itself."""
- s = m.moved(dx, dy)
- if clip is not None: s = s & clip
- return self.darken(s, strength)
-
- def backdrop(self, colour):
- self.img[:] = _c(colour)
-
- # ------------------------------------------------------------ lettering and graphic marks
- def text(self, s, x, y, size, colour=INK, font_style='geo', anchor='ls', spacing=0.0, cjk='cjk', alpha=1.0):
- m = self.text_mask(s, x, y, size, font_style, anchor, spacing, cjk)
- return self.fill(m, colour, alpha)
-
- def dashes(self, pts, width=6, dash=22, gap=16, colour=CREAM, per=16, arrow=None):
- """a dashed motion path along a smooth curve (round-capped dashes); arrow=size puts a head at the end"""
- P = spline(pts, per)
- seg = np.hypot(*np.diff(P, axis=0).T)
- s = np.concatenate([[0], np.cumsum(seg)])
- L = s[-1]
- m = Mask(np.zeros((0, 0)))
- t = 0.0
- stop = L - (arrow * 0.9 if arrow else 0)
- while t < stop:
- t1 = min(t + dash, stop)
- a = (np.interp(t, s, P[:, 0]), np.interp(t, s, P[:, 1]))
- b = (np.interp(t1, s, P[:, 0]), np.interp(t1, s, P[:, 1]))
- m = m | self.capsule(a, b, width / 2)
- t += dash + gap
- if arrow:
- tip = P[-1]; back = np.array([np.interp(L - arrow, s, P[:, 0]), np.interp(L - arrow, s, P[:, 1])])
- d = (tip - back) / (np.linalg.norm(tip - back) + 1e-9); n = np.array([-d[1], d[0]])
- m = m | self.poly([tip + d * arrow * 0.2, back + n * arrow * 0.62, back - n * arrow * 0.62], round=arrow * 0.14)
- return self.fill(m, colour)
-
- def sparkle(self, cx, cy, r, colour=CREAM, rot=0.0):
- return self.fill(self.star(cx, cy, r, 4, 0.26, rot), colour)
-
- def sun(self, cx, cy, r, colour=MUSTARD, rays=0, ray_colour=None, ray_len=0.45, ray_w=0.07):
- """a flat disc; rays > 0 adds that many short round-capped rays"""
- m = self.fill(self.circle(cx, cy, r), colour)
- for i in range(rays):
- a = 2 * np.pi * i / rays
- p0 = (cx + np.cos(a) * r * 1.25, cy + np.sin(a) * r * 1.25)
- p1 = (cx + np.cos(a) * r * (1.25 + ray_len), cy + np.sin(a) * r * (1.25 + ray_len))
- self.fill(self.capsule(p0, p1, r * ray_w), ray_colour or colour)
- return m
-
- def cloud(self, cx, cy, w, colour=CREAM, seed=None):
- """flat cloud: a rounded base bar with three or four bumps on top"""
- r = np.random.default_rng(self._seed() if seed is None else seed)
- h = w * 0.26
- m = self.rrect(cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2, h / 2)
- k = int(r.integers(2, 4))
- xs = np.linspace(cx - w * 0.2, cx + w * 0.16, k) + r.uniform(-0.03, 0.03, k) * w
- for i, x in enumerate(xs):
- rr = w * (0.14 + 0.05 * r.random()) * (1.35 if i == k // 2 else 1)
- m = m | self.circle(x, cy + h / 2 - rr * 1.05, rr)
- m = m & self.rect(cx - w, cy - w, cx + w, cy + h / 2)
- return self.fill(m, colour)
-
- # ------------------------------------------------------------ objects
- def book(self, cx, cy, w, h, rot=0.0, colour=CORAL, open=False, pages=CREAM, band=None):
- """a single book seen from the front: closed (cover, page block showing on the fore-edge, spine band)
- or open (two pages fanning from the gutter over a slightly larger cover)"""
- t = np.deg2rad(rot)
- ca, sa = np.cos(t), np.sin(t)
- P = lambda lx, ly: (cx + lx * ca + ly * sa, cy - lx * sa + ly * ca)
- if not open:
- cover = self.rrect(cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2, (w * 0.06, w * 0.12, w * 0.12, w * 0.06), rot)
- bx, by = P(w * 0.08, 0) # page block peeks out on the fore-edge
- block = self.rrect(bx - w * 0.48, by - h * 0.45, bx + w * 0.48, by + h * 0.45, w * 0.06, rot)
- self.fill(block, pages)
- self.fill(cover, colour)
- hinge = self.split(cover, P(-w / 2 + w * 0.16, -h), P(-w / 2 + w * 0.16, h)) # the cover right of the hinge
- self.fill(cover - hinge, self.tone(colour, -0.18)) # the spine strip
- b = self.rrect(cx - w * 0.18, cy - h * 0.2, cx + w * 0.34, cy - h * 0.06, h * 0.07, rot)
- self.fill(b & cover, band or self.tone(colour, 0.55))
- return cover
- # open: two page quads over a cover
- cov = self.poly([P(-w / 2 - w * 0.03, -h / 2 + h * 0.02), P(0, -h / 2 + h * 0.1), P(w / 2 + w * 0.03, -h / 2 + h * 0.02),
- P(w / 2 + w * 0.03, h / 2 + h * 0.04), P(0, h / 2 + h * 0.12), P(-w / 2 - w * 0.03, h / 2 + h * 0.04)], round=w * 0.03)
- self.fill(cov, colour)
- left = self.poly([P(-w / 2, -h / 2), P(0, -h / 2 + h * 0.09), P(0, h / 2 + h * 0.06), P(-w / 2, h / 2 - h * 0.02)], round=w * 0.02)
- right = self.poly([P(0, -h / 2 + h * 0.09), P(w / 2, -h / 2), P(w / 2, h / 2 - h * 0.02), P(0, h / 2 + h * 0.06)], round=w * 0.02)
- self.fill(left, pages); self.fill(right, self.tone(pages, -0.08))
- for i in range(3): # three lines of text
- for side in (-1, 1):
- y = -h * 0.22 + i * h * 0.16
- self.fill(self.capsule(P(side * w * 0.08, y), P(side * w * 0.36, y - side * 0), h * 0.022), self.tone(pages, -0.2))
- return cov
-
- def books(self, x0, x1, y_base, h_max, colours, seed=None, w_range=(0.13, 0.3), gap_at=None, gap_w=0,
- stack_at=None, back=None, shadow=0.3, title=True):
- """a row of spines standing on a shelf from x0 to x1 with their feet at y_base (h_max = tallest book).
- colours: palette colours to draw from (neighbours never repeat). gap_at / gap_w: one book has been taken
- out there -- the book on the left of the gap has tipped over into it, pivoting on its bottom corner until
- its top rests on the next book. stack_at: x of a small pile lying flat. If the row does not fill the
- shelf, the last book leans against the side panel. Each spine: base colour, a darker block on the side
- away from the light, bands and a title dash in tones of its own colour, and a hard flat shadow on the
- shelf `back` mask. Returns a list of (mask, colour)"""
- r = np.random.default_rng(self._seed() if seed is None else seed)
- plan, x, prev = [], float(x0), None
- while True:
- if stack_at is not None and x <= stack_at < x + h_max * 0.3:
- plan.append(dict(kind='stack', x=x, w=h_max * 0.84)); x += h_max * 0.9; prev = None; continue
- if gap_at is not None and x <= gap_at < x + h_max * 0.3:
- if plan and plan[-1]['kind'] == 'stand': plan[-1]['lean'] = gap_at + gap_w - (plan[-1]['x'] + plan[-1]['w'])
- x = gap_at + gap_w; prev = None; continue
- bw = h_max * r.uniform(*w_range)
- if x + bw > x1: break
- opts = [c for c in colours if prev is None or not np.allclose(_c(c), _c(prev))]
- c = opts[r.integers(len(opts))]
- plan.append(dict(kind='stand', x=x, w=bw, h=h_max * r.uniform(0.68, 0.98), c=c, lean=0.0))
- prev = c
- x += bw + (h_max * 0.012 if r.random() < 0.3 else 0)
- if plan and plan[-1]['kind'] == 'stand' and x1 - x > h_max * 0.12:
- plan[-1]['lean'] = x1 - (plan[-1]['x'] + plan[-1]['w'])
- out = []
- for b in plan:
- if b['kind'] == 'stack':
- sw, yb = b['w'], y_base
- for i in range(int(r.integers(3, 5))):
- bh = h_max * r.uniform(0.1, 0.16); bw = sw * r.uniform(0.8, 1.0)
- c = colours[r.integers(len(colours))]
- xa = b['x'] + (sw - bw) / 2 + r.uniform(-0.04, 0.04) * sw
- bm = self.rrect(xa, yb - bh, xa + bw, yb, 2)
- if back is not None: self.cast(bm, -h_max * 0.06, 0, shadow, clip=back)
- self.fill(bm, c)
- self.fill(self.rect(xa, yb - bh * 0.62, xa + bw * 0.9, yb - bh * 0.38), self.tone(c, 0.5))
- self.fill(self.rect(xa + bw * 0.92, yb - bh, xa + bw, yb) & bm, self.tone(c, -0.2))
- out.append((bm, c)); yb -= bh
- continue
- x, bw, bh, c = b['x'], b['w'], b['h'], b['c']
- if b['lean'] > 1: # tipped over to the right
- th = np.arcsin(min(b['lean'] / bh, 0.55))
- t = -th
- px, py = x + bw, y_base # pivot: bottom-right corner
- ox = bw / 2 * np.cos(t) + bh / 2 * np.sin(t); oy = -bw / 2 * np.sin(t) + bh / 2 * np.cos(t)
- cx, cy = px - ox, py - oy
- m = self.rrect(cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2, (bw * 0.12, bw * 0.12, 0, 0), np.rad2deg(t))
- if back is not None: self.cast(m, -bw * 0.45, 0, shadow, clip=back)
- self.fill(m, c)
- P = lambda lx, ly: (cx + lx * np.cos(t) + ly * np.sin(t), cy - lx * np.sin(t) + ly * np.cos(t))
- self.fill(self.split(m, P(-bw * 0.26, bh), P(-bw * 0.26, -bh)), self.tone(c, -0.2)) # left strip
- q0, q1 = P(-bw * 0.26, -bh * 0.2), P(bw * 0.5, -bh * 0.2)
- self.fill(self.capsule(q0, q1, bh * 0.03) & m, self.tone(c, 0.55))
- out.append((m, c)); continue
- m = self.rrect(x, y_base - bh, x + bw, y_base, (bw * 0.12, bw * 0.12, 0, 0))
- if back is not None: self.cast(m, -bw * 0.45, 0, shadow, clip=back)
- self.fill(m, c)
- self.fill(self.rect(x, y_base - bh, x + bw * 0.26, y_base) & m, self.tone(c, -0.2))
- bc = self.tone(c, 0.55) if r.random() < 0.6 else self.tone(c, -0.35) # bands sit near the head and foot
- style = r.integers(0, 4)
- if style in (1, 3):
- yy = r.uniform(0.8, 0.88)
- self.fill(self.rect(x + bw * 0.26, y_base - bh * yy - bh * 0.03, x + bw, y_base - bh * yy + bh * 0.03), bc)
- if style in (2, 3):
- yy = r.uniform(0.1, 0.16)
- self.fill(self.rect(x + bw * 0.26, y_base - bh * yy - bh * 0.03, x + bw, y_base - bh * yy + bh * 0.03), bc)
- if title and bw > h_max * 0.15 and r.random() < 0.75: # the title: one dash in the middle
- ty = y_base - bh * r.uniform(0.44, 0.54)
- self.fill(self.capsule((x + bw * 0.62, ty - bh * 0.13), (x + bw * 0.62, ty + bh * 0.13), bw * 0.09),
- self.tone(c, 0.6) if r.random() < 0.7 else self.tone(c, -0.4))
- out.append((m, c))
- return out
-
- def plant(self, x, y, h, pot=CORAL, leaf=TEAL, kind='leafy', seed=None, n=None):
- """a potted plant standing at (x, y) (pot bottom centre), total height h.
- kind: 'leafy' (split two-tone leaves on stems), 'snake' (upright blades with bands), 'round' (bushy)"""
- r = np.random.default_rng(self._seed() if seed is None else seed)
- pw, ph = h * 0.34, h * 0.26
- top = y - ph
- stems, leaves = Mask(np.zeros((0, 0))), []
- if kind == 'snake':
- for i in range(n or 6):
- bx = x + (i - (n or 6) / 2 + 0.5) * pw * 0.16
- tip = (bx + r.uniform(-0.2, 0.2) * h * 0.4, top - h * r.uniform(0.45, 0.72))
- leaves.append(((bx, top + 4), tip, pw * r.uniform(0.2, 0.28), r.uniform(-8, 8)))
- else:
- k = n or (7 if kind == 'leafy' else 11)
- for i in range(k):
- a = np.deg2rad(-90 + (i - (k - 1) / 2) * (150 / k) + r.uniform(-8, 8))
- L = h * r.uniform(0.38, 0.62) * (1 - 0.35 * abs(np.cos(a)))
- base = (x + r.uniform(-0.1, 0.1) * pw, top + 2)
- mid = (base[0] + np.cos(a) * L * 0.55, base[1] + np.sin(a) * L * 0.55)
- if kind == 'leafy':
- stems = stems | self.tube([base, (base[0] + np.cos(a) * L * 0.3, base[1] + np.sin(a) * L * 0.34), mid], max(2, h * 0.008))
- tip = (mid[0] + np.cos(a + 0.35 * np.sign(np.cos(a))) * L * 0.5, mid[1] + np.sin(a + 0.35 * np.sign(np.cos(a))) * L * 0.5)
- leaves.append((mid, tip, L * 0.42, np.sign(np.cos(a)) * L * 0.06))
- else:
- leaves.append((base, (base[0] + np.cos(a) * L, base[1] + np.sin(a) * L), L * 0.34, 0))
- self.fill(stems, self.tone(leaf, -0.35))
- order = sorted(range(len(leaves)), key=lambda i: -abs(leaves[i][1][0] - x))
- for i in order:
- p0, p1, wd, bend = leaves[i]
- m = self.leaf(p0, p1, wd, bend)
- self.fill(m, leaf)
- if kind == 'snake': self.plane(m, p0, p1, colour=self.tone(leaf, -0.2)) # left half of an upright blade
- elif p1[0] > p0[0]: self.plane(m, p1, p0, colour=self.tone(leaf, -0.2)) # lower half of the leaf
- else: self.plane(m, p0, p1, colour=self.tone(leaf, -0.2))
- if kind == 'snake':
- for j in range(3):
- tt = 0.25 + j * 0.2
- q = (p0[0] + (p1[0] - p0[0]) * tt, p0[1] + (p1[1] - p0[1]) * tt)
- self.fill(self.ellipse(q[0], q[1], wd * 0.34, wd * 0.08, -np.rad2deg(np.arctan2(-(p1[1] - p0[1]), p1[0] - p0[0])) + 90) & m,
- self.tone(leaf, 0.35))
- body = self.poly([(x - pw / 2, top + ph * 0.18), (x + pw / 2, top + ph * 0.18), (x + pw * 0.38, y), (x - pw * 0.38, y)],
- round=[0, 0, pw * 0.08, pw * 0.08])
- rim = self.rrect(x - pw / 2 - pw * 0.04, top, x + pw / 2 + pw * 0.04, top + ph * 0.24, ph * 0.05)
- self.fill(body, pot)
- self.shade(body, 0.2, pw * 0.3)
- self.fill(rim, self.tone(pot, 0.12))
- self.shade(rim, 0.2, pw * 0.2)
- return body | rim
-
- def pendant(self, x, y_top, y, r, shade=INK, bulb=CREAM, beam_to=None, beam_alpha=0.13, beam_colour=None, cord=3):
- """a pendant lamp hanging from y_top: a cord, a dome shade of radius r whose bottom edge is at y, a bulb,
- and optionally a flat translucent beam spreading down to (x_left, x_right, y_floor)"""
- if beam_to is not None:
- bl, br, by = beam_to
- beam = self.poly([(x - r * 0.72, y), (x + r * 0.72, y), (br, by), (bl, by)])
- self.fill(beam, beam_colour or self.tone(bulb, 0.2), beam_alpha, grain=0.35)
- self.fill(self.capsule((x, y_top), (x, y - r * 0.95), cord), self.tone(shade, 0.05))
- dome = self.pie(x, y, r, 0, 180)
- self.fill(self.circle(x, y + r * 0.05, r * 0.3), bulb)
- self.fill(dome, shade)
- self.plane(dome, (x + r * 0.08, y - r - 10), (x + r * 0.34, y + 10), colour=self.tone(shade, 0.12)) # lit right side
- self.fill(self.rrect(x - r * 0.12, y - r - r * 0.12, x + r * 0.12, y - r + r * 0.05, r * 0.04), self.tone(shade, 0.12))
- return dome
-
- def cat(self, x, y, size, colour=INK, facing=1, pose='sit', tail_down=None):
- """a flat cat seen from behind / side, sitting with its base centre at (x, y); size = body height.
- tail_down: a y to let the tail hang down to (over a sill edge)"""
- s = size
- f = facing
- body = self.ellipse(x, y - s * 0.38, s * 0.34, s * 0.42) | self.ellipse(x, y - s * 0.12, s * 0.42, s * 0.2)
- body = body & self.rect(x - s, y - s * 2, x + s, y)
- hx, hy = x + f * s * 0.08, y - s * 0.86
- head = self.ellipse(hx, hy, s * 0.26, s * 0.22)
- ears = self.poly([(hx - s * 0.24, hy - s * 0.02), (hx - s * 0.2, hy - s * 0.34), (hx - s * 0.04, hy - s * 0.16)], round=s * 0.03) | \
- self.poly([(hx + s * 0.24, hy - s * 0.02), (hx + s * 0.2, hy - s * 0.34), (hx + s * 0.04, hy - s * 0.16)], round=s * 0.03)
- if tail_down is not None:
- tail = self.tube([(x - f * s * 0.2, y - s * 0.08), (x - f * s * 0.42, y + s * 0.05), (x - f * s * 0.46, (y + tail_down) / 2),
- (x - f * s * 0.36, tail_down)], [s * 0.07, s * 0.07, s * 0.065, s * 0.06])
- else:
- tail = self.tube([(x - f * s * 0.3, y - s * 0.05), (x + f * s * 0.1, y + s * 0.02), (x + f * s * 0.5, y - s * 0.04),
- (x + f * s * 0.62, y - s * 0.18)], s * 0.065)
- allm = body | head | ears | tail
- self.fill(allm, colour)
- self.shade(body | head, 0.0, s * 0.12, colour=self.tone(colour, 0.12) if _c(colour).mean() < 0.3 else self.tone(colour, -0.2))
- return allm
-
- # ------------------------------------------------------------ people
- def person(self, hip, height, facing=1, lean=0.0, head_tilt=0.0, arm=(10, 20), arm_far=(-8, -2),
- leg=(2, 0), leg_far=(-4, 0), sit=False, top=MUSTARD, bottom=INK, shoes=None, skin=PEACH,
- hair=INK, hair_style='short', sleeve='long', coat=False, skirt=False, apron=None, bag=None,
- collar=None, build=1.0, far_tone=-0.2, draw_near_arm=True, hand_to=None, hand_far_to=None,
- foot_to=None, foot_far_to=None):
- """a faceless adult (about 7.5 heads tall) with the hip centre at `hip`, facing +1 right / -1 left.
- Joint angles are degrees from straight down, positive toward the facing side:
- arm=(upper, fore) of the near arm, arm_far the far arm, leg=(thigh, shin), leg_far the far leg.
- sit=True is a shortcut for thighs forward (90) and shins down.
- hand_to / hand_far_to / foot_to / foot_far_to: put that hand or ankle on a point instead (two-bone IK:
- elbows drop, knees go forward; a point out of reach gets the limb stretched straight toward it).
- Clothes: top (sweater / shirt colour), bottom (trousers), skirt=colour, coat=True (top becomes a long coat),
- apron=colour, bag=colour (a tote hanging from the near shoulder), collar=colour. hair_style: short, bun, bob, long, pony.
- Returns the joints: head, neck, shoulder, hand, hand_far, elbow, knee, knee_far, foot, foot_far, u."""
- f = 1 if facing >= 0 else -1
- u = height / 7.5
- H = np.array(hip, np.float64)
- lam = np.deg2rad(lean)
- up = np.array([f * np.sin(lam), -np.cos(lam)])
- fwd = np.array([f * np.cos(lam), np.sin(lam)])
-
- def dv(a):
- a = np.deg2rad(a)
- return np.array([f * np.sin(a), np.cos(a)])
-
- if sit:
- leg = leg if leg != (2, 0) else (88, 4)
- leg_far = leg_far if leg_far != (-4, 0) else (92, 0)
- shoes = shoes if shoes is not None else self.tone(bottom, -0.35)
- S = H + up * 2.78 * u
- N = H + up * 3.02 * u
- tilt = np.deg2rad(head_tilt)
- head_up = np.array([f * np.sin(lam + tilt), -np.cos(lam + tilt)])
- C = N + head_up * 0.62 * u + fwd * 0.1 * u
- sh_n, sh_f = S - fwd * 0.36 * u * build, S + fwd * 0.34 * u * build
- hp_n, hp_f = H - fwd * 0.26 * u, H + fwd * 0.22 * u
- joints = dict(u=u, hip=tuple(H), shoulder=tuple(S), neck=tuple(N), head=tuple(C))
-
- def ang(v):
- return float(np.rad2deg(np.arctan2(f * v[0], v[1])))
-
- def ik(root, target, L1, L2, knee):
- d = np.asarray(target, np.float64) - root
- dist = float(np.clip(np.linalg.norm(d), abs(L1 - L2) + 1e-3, L1 + L2 - 1e-3))
- base = np.arctan2(d[1], d[0])
- al = np.arccos(np.clip((L1 * L1 + dist * dist - L2 * L2) / (2 * L1 * dist), -1, 1))
- cands = [root + L1 * np.array([np.cos(base + s_ * al), np.sin(base + s_ * al)]) for s_ in (1, -1)]
- J = max(cands, key=lambda e: f * e[0]) if knee else max(cands, key=lambda e: e[1] - 0.3 * f * e[0])
- tip = root + d / (np.linalg.norm(d) + 1e-9) * dist
- return (ang(J - root), ang(tip - J))
-
- if hand_to is not None: arm = ik(S - fwd * 0.36 * u * build, hand_to, 1.42 * u, 1.42 * u, False)
- if hand_far_to is not None: arm_far = ik(S + fwd * 0.34 * u * build, hand_far_to, 1.42 * u, 1.42 * u, False)
- if foot_to is not None: leg = ik(H - fwd * 0.26 * u, foot_to, 1.92 * u, 1.86 * u, True)
- if foot_far_to is not None: leg_far = ik(H + fwd * 0.22 * u, foot_far_to, 1.92 * u, 1.86 * u, True)
-
- def arm_pts(sh, a):
- E = sh + dv(a[0]) * 1.42 * u
- Wr = E + dv(a[1]) * 1.22 * u
- Hd = Wr + dv(a[1]) * 0.2 * u
- return E, Wr, Hd
-
- def leg_pts(hp, a):
- K = hp + dv(a[0]) * 1.92 * u
- A = K + dv(a[1]) * 1.86 * u
- return K, A
-
- def tn(c, k): # a darker far limb; a dark colour
- return self.tone(c, k) if k >= 0 or _c(c).mean() > 0.3 else self.tone(c, -k * 0.6) # lifts instead
-
- def draw_arm(sh, a, tone_k):
- E, Wr, Hd = arm_pts(sh, a)
- sc = tn(top, tone_k)
- if sleeve == 'long':
- am = self.fill(self.limb([sh, E, Wr], [0.27 * u, 0.22 * u, 0.18 * u]), sc)
- self.shade(am, 0.16, 0.1 * u)
- self.fill(self.capsule(Hd - dv(a[1]) * 0.05 * u, Hd + dv(a[1]) * 0.05 * u, 0.16 * u), tn(skin, tone_k))
- self.fill(self.capsule(Wr - dv(a[1]) * 0.14 * u, Wr - dv(a[1]) * 0.02 * u, 0.2 * u), tn(top, tone_k - 0.1))
- else:
- self.fill(self.limb([E, Wr], [0.19 * u, 0.15 * u]), tn(skin, tone_k))
- self.fill(self.capsule(Hd - dv(a[1]) * 0.05 * u, Hd + dv(a[1]) * 0.05 * u, 0.16 * u), tn(skin, tone_k))
- self.fill(self.limb([sh, sh + dv(a[0]) * 0.8 * u], [0.3 * u, 0.25 * u]), sc)
- return E, Wr, Hd
-
- def draw_leg(hp, a, tone_k):
- K, A = leg_pts(hp, a)
- m = self.limb([hp, K, A], [0.38 * u, 0.27 * u, 0.2 * u])
- self.fill(m, tn(bottom, tone_k))
- toe = A + np.array([f * 0.78 * u, 0.1 * u])
- heel = A + np.array([-f * 0.18 * u, 0.1 * u])
- if a[1] < -25: # on tiptoe / foot on a rung behind
- toe = A + np.array([f * 0.7 * u, 0.26 * u])
- shoe = self.capsule(heel, toe, 0.2 * u, 0.17 * u) | self.rrect(min(heel[0], toe[0]), A[1] - 0.05 * u, max(heel[0], toe[0]),
- A[1] + 0.3 * u, (0.14 * u, 0.14 * u, 0.04 * u, 0.04 * u)) & \
- self.rect(min(heel[0], toe[0]) - u, A[1] - u, max(heel[0], toe[0]) + u, max(heel[1], toe[1]) + 0.3 * u)
- self.fill(self.limb([A - dv(a[1]) * 0.12 * u, A + np.array([0, 0.06 * u])], [0.21 * u, 0.21 * u]), tn(bottom, tone_k - 0.05))
- self.fill(shoe, tn(shoes, tone_k * 0.5))
- return K, A, m
-
- # long hair panel sits behind everything
- if hair_style == 'long':
- self.fill(self.rrect(C[0] - f * 0.55 * u - 0.1 * u, C[1] - 0.2 * u, C[0] + f * 0.2 * u + 0.1 * u, S[1] + 1.0 * u, 0.3 * u)
- if f > 0 else self.rrect(C[0] - 0.3 * u, C[1] - 0.2 * u, C[0] + 0.65 * u, S[1] + 1.0 * u, 0.3 * u), self.tone(hair, -0.1))
- E_f, W_f, H_f = draw_arm(sh_f, arm_far, far_tone)
- K_f, A_f, _ = draw_leg(hp_f, leg_far, far_tone)
- pelvis = self.ellipse(H[0], H[1] + 0.05 * u, 0.72 * u, 0.5 * u, -np.rad2deg(lam) * f)
- self.fill(pelvis, bottom)
- K_n, A_n, legm = draw_leg(hp_n, leg, 0.0)
- self.shade(legm, 0.16, 0.1 * u)
- if skirt:
- sk_len = 1.9 * u
- if sit:
- K = K_n
- sk = self.poly([H - fwd * 0.72 * u + up * 0.3 * u, H + fwd * 0.6 * u + up * 0.3 * u, K + np.array([f * 0.2 * u, -0.3 * u]),
- K + np.array([f * 0.25 * u, 0.4 * u]), H - fwd * 0.8 * u + np.array([0, 0.6 * u])], round=0.15 * u)
- else:
- sk = self.poly([H - fwd * 0.7 * u + up * 0.3 * u, H + fwd * 0.62 * u + up * 0.3 * u, H + fwd * 0.9 * u + np.array([0, sk_len]),
- H - fwd * 1.0 * u + np.array([0, sk_len])], round=[0.2 * u, 0.2 * u, 0.1 * u, 0.1 * u])
- self.fill(sk, skirt)
- self.shade(sk, 0.18, 0.3 * u)
- # torso
- def at(k, w_front, w_back):
- c = H + up * k * u
- return c + fwd * w_front * u * build, c - fwd * w_back * u * build
- s_f, s_b = at(2.82, 0.72, 0.78)
- c_f, c_b = at(2.1, 0.78, 0.7)
- w_f, w_b = at(1.1, 0.62, 0.66)
- hem = -0.12 if not coat else -2.1
- if coat and sit: hem = -0.5
- h_f, h_b = at(hem, 0.72 if not coat else 0.95, 0.76 if not coat else 1.0)
- torso = self.poly([s_b, s_f, c_f, w_f, h_f, h_b, w_b, c_b],
- round=[0.55 * u, 0.5 * u, 0.3 * u, 0.2 * u, 0.1 * u, 0.1 * u, 0.2 * u, 0.3 * u])
- self.fill(torso, top)
- self.shade(torso, 0.2, 0.34 * u)
- if coat: # front panel overlaps: a placket block
- pl = self.split(torso, tuple(H + fwd * 0.3 * u + up * 3 * u), tuple(H + fwd * 0.42 * u - up * 3 * u))
- self.fill(pl, self.tone(top, -0.1))
- self.fill(self.poly([N + fwd * 0.05 * u, N + fwd * 0.5 * u + up * -0.1 * u, H + fwd * 0.42 * u + up * 1.7 * u]), self.tone(top, -0.16))
- if apron is not None:
- ap = self.poly([H + fwd * 0.05 * u + up * 2.35 * u, H + fwd * 0.78 * u + up * 2.35 * u, H + fwd * 0.95 * u - up * 1.3 * u,
- H - fwd * 0.35 * u - up * 1.3 * u], round=[0.08 * u, 0.08 * u, 0.12 * u, 0.12 * u])
- self.fill(ap, apron)
- self.shade(ap, 0.16, 0.2 * u)
- self.fill(self.capsule(H + fwd * 0.2 * u + up * 2.35 * u, N + fwd * 0.12 * u, 0.06 * u), self.tone(apron, -0.1))
- self.fill(self.capsule(H - fwd * 0.4 * u + up * 1.1 * u, H + fwd * 0.4 * u + up * 1.1 * u, 0.07 * u), self.tone(apron, -0.12))
- self.fill(self.rrect(*(H + fwd * 0.18 * u + up * 0.1 * u + np.array([-0.26, -0.22]) * u),
- *(H + fwd * 0.18 * u + up * 0.1 * u + np.array([0.26, 0.22]) * u), 0.06 * u), self.tone(apron, -0.12))
- # neck and head
- neck = self.capsule(N - up * 0.1 * u, C, 0.17 * u)
- self.fill(neck, skin)
- self.darken(neck & self.circle(C[0] + f * 0.02 * u, C[1] + 0.3 * u, 0.4 * u), 0.22)
- if collar is not None:
- self.fill(self.poly([N - fwd * 0.3 * u, N + fwd * 0.35 * u, N + fwd * 0.05 * u + up * -0.35 * u], round=0.05 * u), collar)
- else:
- self.fill(self.ellipse(N[0], N[1], 0.34 * u, 0.13 * u, -np.rad2deg(lam) * f) & torso.grown(2), self.tone(top, -0.14))
- rot_h = -np.rad2deg(lam + tilt) * f
- hr = self.ellipse(C[0], C[1], 0.42 * u, 0.52 * u, rot_h)
- self.fill(hr, skin)
- # hair = a slightly bigger ellipse minus the face (the head nudged forward and down), then cut at the
- # hairline: from the nape at the back up to the temple in front, so the jaw and the ear show below it
- face = hr.moved(*(fwd * 0.2 * u + np.array([0, 0.2 * u])))
- cap = self.ellipse(C[0] - f * 0.03 * u, C[1] - 0.04 * u, 0.47 * u, 0.56 * u, rot_h) - face
- back_pt = C - fwd * 0.6 * u
- front_pt = C + fwd * 0.6 * u
- nape, temple = {'short': (0.2, -0.16), 'bun': (0.16, -0.12), 'pony': (0.16, -0.12)}.get(hair_style, (0.62, 0.1))
- bp = back_pt + np.array([0, nape * u]) + head_up * 0; fp = front_pt + np.array([0, temple * u])
- lo, hi = (bp, fp) if bp[0] < fp[0] else (fp, bp)
- cap = self.split(cap, tuple(lo), tuple(hi)) # keep what is above the hairline
- extra = Mask(np.zeros((0, 0)))
- if hair_style == 'bun':
- extra = self.circle(*(C - fwd * 0.3 * u + np.array([0, -0.5 * u])), 0.23 * u)
- elif hair_style == 'pony':
- extra = self.tube([C - fwd * 0.4 * u + np.array([0, -0.2 * u]), C - fwd * 0.7 * u + np.array([0, 0.25 * u]),
- C - fwd * 0.6 * u + np.array([0, 0.85 * u])], [0.2 * u, 0.16 * u, 0.08 * u])
- elif hair_style in ('bob', 'long'): # a curtain behind the jaw, down to the chin
- bx0, bx1 = sorted([C[0] - f * 0.5 * u, C[0] + f * 0.02 * u])
- extra = self.rrect(bx0, C[1] - 0.2 * u, bx1, C[1] + 0.62 * u, (0, 0, 0.18 * u, 0.18 * u) if f > 0 else (0, 0, 0.18 * u, 0.18 * u)) - face
- if not extra.empty and hair_style in ('bun', 'pony'):
- self.fill(extra, self.tone(hair, -0.08))
- self.fill(cap | (extra if hair_style in ('bob', 'long') else Mask(np.zeros((0, 0)))), hair)
- self.glint(cap, 0.14, 0.06 * u)
- if hair_style in ('short', 'bun', 'pony'):
- ear = self.ellipse(*(C - fwd * 0.12 * u + np.array([0, 0.08 * u])), 0.085 * u, 0.12 * u, rot_h)
- self.fill(ear, self.tone(skin, -0.1))
- if bag is not None: # a tote on the near shoulder
- bc = H - fwd * 0.62 * u + np.array([0, 0.62 * u])
- bw_, bh_ = 1.05 * u, 1.15 * u
- for dx in (-0.36, 0.3):
- self.fill(self.capsule(sh_n + np.array([0, 0.05 * u]), bc + np.array([dx * u, -bh_ / 2 + 0.05 * u]), 0.055 * u),
- self.tone(bag, -0.3))
- bm = self.rrect(bc[0] - bw_ / 2, bc[1] - bh_ / 2, bc[0] + bw_ / 2, bc[1] + bh_ / 2, (0.05 * u, 0.05 * u, 0.12 * u, 0.12 * u))
- self.fill(bm, bag); self.shade(bm, 0.0, 0.22 * u, colour=self.tone(bag, -0.14))
- self.fill(self.rect(bc[0] - bw_ / 2, bc[1] + 0.08 * u, bc[0] + bw_ / 2, bc[1] + 0.26 * u) & bm, self.tone(bag, -0.3)
- if _c(bag).mean() > 0.6 else self.tone(bag, 0.5))
- E_n, W_n, H_n = draw_arm(sh_n, arm, 0.0) if draw_near_arm else arm_pts(sh_n, arm)
- joints.update(hand=tuple(H_n), hand_far=tuple(H_f), elbow=tuple(E_n),
- knee=tuple(K_n), knee_far=tuple(K_f), foot=tuple(A_n), foot_far=tuple(A_f), shoulder_near=tuple(sh_n),
- shoulder_far=tuple(sh_f))
- self._last_person = dict(sh_n=sh_n, arm=arm, top=top, skin=skin, sleeve=sleeve, u=u, f=f, draw=draw_arm)
- return joints
-
- def near_arm(self):
- """draw the near arm of the last person() called with draw_near_arm=False (after a prop it should cover)"""
- p = self._last_person
- E, Wr, Hd = p['draw'](p['sh_n'], p['arm'], 0.0)
- return tuple(Hd)
-
- def hand(self, x, y, r, skin=PEACH):
- return self.fill(self.circle(x, y, r), skin)
-
- # ------------------------------------------------------------ output
- def composite(self, grain=0.012):
- img = self.img
- if grain:
- n = self._grain_field()
- img = img * (1 + grain * n[..., None])
- return Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8))
-
- def stage(self, name):
- self.stages.append((name, self.composite()))
-
- def save(self, path, stages_dir=None, quality=88):
- img = self.composite()
- 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