Skip to content

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

Add sixteen styles (43 total): petroglyph, Egyptian tomb painting, Roman mosaic, stained glass, illuminated manuscript, Leonardo codex, silhouette, letterpress playbill, constructivism, Art Deco, golden-age comic, pop silkscreen, ASCII line printer, low-poly 3D, stencil graffiti, embroidered patch

cloveric63b1d201e8d3
diff --git a/README.md b/README.md
index 40ff61e..b32c362 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,7 @@
# 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, perler beads and a synthwave sunset.
-**不用生图模型,Claude 用代码一笔一笔作画。** 二十七种画风,从水墨、油画到黏土、蓝晒、十字绣、黑板板书、赛博朋克、等轴小岛、光线追踪的小球海、拼豆和 Synthwave 落日。
+**Claude paints with code — no image model.** Forty-three styles, from ink wash and impasto oil to clay, cyanotype, stained glass, an Egyptian tomb painting, a Roman mosaic, a cyberpunk street, a ray-traced ball pit, low-poly 3D, an ASCII line printer and a synthwave sunset.
+**不用生图模型,Claude 用代码一笔一笔作画。** 四十三种画风,从水墨、油画到黏土、蓝晒、彩色玻璃花窗、古埃及墓室壁画、罗马马赛克、赛博朋克、光线追踪的小球海、低多边形 3D、ASCII 字符画和 Synthwave 落日。
[English](#english) · [中文](#中文)
@@ -25,6 +25,16 @@
| **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) |
+| Petroglyph · 岩画 | Egyptian tomb painting · 古埃及墓室壁画 | Roman mosaic · 罗马马赛克 | Stained glass · 彩色玻璃花窗 |
+|---|---|---|---|
+| ![petroglyph](examples/drawing_petroglyph_migration.gif) | ![tomb](examples/drawing_tomb_harvest.gif) | ![mosaic](examples/drawing_mosaic_harbor.gif) | ![stainedglass](examples/drawing_stainedglass_seasons.gif) |
+| **Illuminated manuscript · 泥金手抄本** | **Leonardo codex · 达·芬奇手稿** | **Silhouette · 剪影** | **Letterpress poster · 凸版印刷海报** |
+| ![illuminated](examples/drawing_illuminated_starchart.gif) | ![codex](examples/drawing_codex_ornithopter.gif) | ![silhouette](examples/drawing_silhouette_family.gif) | ![letterpress](examples/drawing_letterpress_circus.gif) |
+| **Soviet constructivism · 苏联构成主义** | **Art Deco · 装饰艺术** | **Golden-age comic · 黄金时代漫画** | **Pop silkscreen · 波普丝网** |
+| ![constructivism](examples/drawing_constructivism_radio.gif) | ![artdeco](examples/drawing_artdeco_express.gif) | ![comic](examples/drawing_comic_rocket.gif) | ![popart](examples/drawing_popart_cat_moods.gif) |
+| **ASCII art (line printer) · ASCII 字符画** | **Low poly · 低多边形** | **Stencil graffiti · 喷漆模板涂鸦** | **Embroidered patches · 刺绣徽章** |
+| ![lineprinter](examples/drawing_lineprinter_launch.gif) | ![lowpoly](examples/drawing_lowpoly_canyon.gif) | ![stencil](examples/drawing_stencil_kite.gif) | ![patch](examples/drawing_patch_camping.gif) |
+
### Gallery · 画廊
| | |
@@ -57,6 +67,22 @@
| <img src="examples/aurora_morning.jpg" width="100%"> | <img src="examples/bauhaus_form_colour.jpg" width="100%"> |
| **海岸线 1987** · *Coastline 1987*<br><sub>Retro synthwave · 复古 Synthwave</sub> | **草莓杯垫** · *Strawberry Coaster*<br><sub>Perler beads · 拼豆</sub> |
| <img src="examples/synthwave_coastline.jpg" width="100%"> | <img src="examples/perler_strawberry_coaster.jpg" width="100%"> |
+| **迁徙季** · *Migration Season*<br><sub>Petroglyph · 岩画</sub> | **尼罗河丰收** · *Harvest on the Nile*<br><sub>Egyptian tomb painting · 古埃及墓室壁画</sub> |
+| <img src="examples/petroglyph_migration.jpg" width="100%"> | <img src="examples/tomb_harvest.jpg" width="100%"> |
+| **港口渔获** · *The Day's Catch*<br><sub>Roman mosaic · 罗马马赛克</sub> | **四季之窗** · *Window of the Seasons*<br><sub>Stained glass · 彩色玻璃花窗</sub> |
+| <img src="examples/mosaic_harbor.jpg" width="100%"> | <img src="examples/stainedglass_seasons.jpg" width="100%"> |
+| **星辰之书** · *Liber Stellarum*<br><sub>Illuminated manuscript · 泥金手抄本</sub> | **扑翼机** · *The Ornithopter*<br><sub>Leonardo codex · 达·芬奇手稿</sub> |
+| <img src="examples/illuminated_starchart.jpg" width="100%"> | <img src="examples/codex_ornithopter.jpg" width="100%"> |
+| **剪影小像** · *Shades of the Wren Household*<br><sub>Silhouette · 剪影</sub> | **马戏团来了** · *The Circus Is Coming*<br><sub>Letterpress poster · 凸版印刷海报</sub> |
+| <img src="examples/silhouette_family.jpg" width="100%"> | <img src="examples/letterpress_circus.jpg" width="100%"> |
+| **无线电** · *Radio*<br><sub>Soviet constructivism · 苏联构成主义</sub> | **夜行快车** · *Night Express*<br><sub>Art Deco · 装饰艺术</sub> |
+| <img src="examples/constructivism_radio.jpg" width="100%"> | <img src="examples/artdeco_express.jpg" width="100%"> |
+| **火箭小队** · *Rocket Squad*<br><sub>Golden-age comic · 黄金时代漫画</sub> | **猫的六种心情** · *Six Moods of a Cat*<br><sub>Pop silkscreen · 波普丝网</sub> |
+| <img src="examples/comic_rocket.jpg" width="100%"> | <img src="examples/popart_cat_moods.jpg" width="100%"> |
+| **发射记录** · *Liftoff Trace*<br><sub>ASCII art (line printer) · ASCII 字符画(行式打印机)</sub> | **峡谷飞行** · *Canyon Run*<br><sub>Low poly · 低多边形</sub> |
+| <img src="examples/lineprinter_launch.jpg" width="100%"> | <img src="examples/lowpoly_canyon.jpg" width="100%"> |
+| **放风筝** · *Hold On*<br><sub>Stencil graffiti · 喷漆模板涂鸦</sub> | **三晚露营** · *Three Nights Out*<br><sub>Embroidered patches · 刺绣徽章</sub> |
+| <img src="examples/stencil_kite.jpg" width="100%"> | <img src="examples/patch_camping.jpg" width="100%"> |
Every mark above is computed: paper fibres, ink washes and mist, dry-brush strokes, pigment granulation and blooms, torn-paper edges, pencil wax on paper tooth, cel-shaded clouds, risograph grain and halftones, lit impasto relief, woodblock grain and bokashi, dithered pixels, plasticine lit like a film set, sunlight through leaves on Prussian blue, twisted thread on Aida cloth, machined knobs behind a backlit dial, die-cut vinyl with a laminate gloss, streaky thermal print, graphite catching the tooth of graph paper, highlighter pooling at the start of a swipe, chalk dust settling under half-erased lessons, rain-lit neon glass mirrored in a wet street, a blue-pencil rough under boiling brush ink, an island ray-traced under one soft sun, a single unbroken gold line, candy balls with softbox glints, one outline morphing through six shapes, halftone photos cut out with scissors, frosted glass blurring the real pixels behind it, screen-printed primaries out of register, a slit sun sinking behind a neon grid played off tape, hollow fuse beads on a pegboard melting together under an iron. No diffusion model, no API, no stock art. It is just Python with **numpy + Pillow** on a CPU: from 0.1 s (pixel art) to about 45 s (the soft 3D ray tracer) per 1920×1080 image.
@@ -66,7 +92,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 forty-three styles:
| Style | Module | What makes it read as the real medium |
|---|---|---|
@@ -97,6 +123,22 @@ A [Claude Code](https://claude.com/claude-code) skill and a small painting libra
| **Bauhaus geometric** | `lib/bauhaus.py` · `Bauhaus` | a press sheet printed screen by screen, light to dark, on cream uncoated stock (cloudy pulp, fibres, flecks, tooth, a slight cockle); each screen has its own registration error, so colour meets black with a sliver of paper or a dark overlap and the register targets print as a stack of offset crosshairs; an ink film streaked along the squeegee pull and thinning toward the end of the stroke, with bare tooth pits and pinholes where it is thin and a mesh-ragged stencil edge; semi-opaque inks that darken where they overprint; circles, sectors, triangles and heavy bars on a strict module grid; Futura-style caps and heavy Hei, knocked out of solids; crop marks, a colour bar and a pencilled edition number |
| **Retro synthwave** | `lib/synthwave.py` · `Synthwave` | an 80s retro-future dusk through a pinhole camera: a gradient sun cut by slits that thicken toward the horizon; an analytic neon grid with honest line widths that fades to its average instead of moiré; wireframe mountains glowing magenta to cyan; a sea whose reflection is torn into bars stretched about the sun's column; palm silhouettes with sunset rims; chrome caps mirroring sky over ground with a sharp horizon, extrusion and glints; neon script; then played back off tape: chroma bleed, a tracking band, head-switching noise, on-screen display and scanlines |
| **Perler beads** | `lib/perler.py` · `Perler` | a height field of real tubes seen by a camera leaning back a little (each pixel walks its column to the first surface), so every bead shows a sliver of side wall, its hole shows the inner wall and the peg inside tinted by light through the plastic, and the gaps show the pegboard; a translucent pegboard (square, round, hexagonal) with empty pegs; per-bead dye-lot shade and wobble; opaque, pearl, clear and glow plastics; ironing as melt: tubes slump and spread, holes close from the rim, neighbours flow together through a smooth union until the gaps shrink to diamonds and the top becomes one flat waxy sheet with paper grain; translucent ironing paper that drapes over the beads and peels back with a curl; a soft box seen in reflection (crisp arcs on glossy rims, a drifting sheen on melted plastic); sorting-tray heaps, spilled beads, tweezers held in the air with their own shadow, a printed chart with pencil ticks |
+| **Petroglyph** | `lib/petroglyph.py` · `Petroglyph` | the picture is knocked out of the rock, not painted on: a sandstone height field (swells, faint bedding, grain, solution pockets, a stepped ledge) under desert varnish that grows as a near-uniform dark coat with crisp blue-black runoff streaks; every glyph is drafted as a mask and hammered out with hundreds to thousands of irregular pits that break the varnish and crush the grains pale, so outlines are ragged at the scale of one blow and interiors are shallow granular hollows; tally marks are ground V-grooves instead; age re-varnishes old work toward a ghost, so superimposed layers show; cracks bleed seep streaks; spalls are scalloped step-down scars of fresh orange stone that took part of the old work; crustose lichen; one low raking sun with a cast shadow in every pit |
+| **Egyptian tomb painting** | `lib/tomb.py` · `TombPainting` | the wall is built in the painters' own order and every layer is kept: straw-tempered mud under gypsum plaster, a red-ochre squaring grid snapped at one canon unit per cell, a searching red underdrawing, a ground wash brushed round the figures, flat matte secco colour one pigment at a time (red-ochre men, yellow-ochre women, translucent pleated linen, glittering Egyptian blue, green frit) z-ordered so the pots can go in any order, then even black and red-brown outlines; figures in the composite view on a posable canon rig (profile head with a frontal kohl-lined eye, frontal shoulders and collar that turn toward profile when the body bends, both feet from the big-toe side, IK elbows) at hierarchical scale; oxen with all four legs visible, an emmer field gathered into the reapers' fists, polychrome pseudo-hieroglyphs laid out in quadrats, kheker frieze and block border; then age as strata: clustered flaking down to the wash, or to the plaster where the red grid and sketch come back, plaster losses down to the mud as a real height field with a broken gypsum rim and a cast shadow, cracks, blue decaying to grey-green, soot, a tide-line, salt and fly specks |
+| **Roman mosaic** | `lib/mosaic.py` · `Mosaic` | a hidden cartoon that every stone samples and snaps to a finite box of stones (limestone, veined marble, smalti glass, terracotta), matched on hue before lightness; rows traced along iso-lines of distance fields (marching squares) so they wrap every outline and ring every eye (opus vermiculatum), halo rows round each figure, straight or wavy background rows (opus tessellatum), mitred border rows; each row fitted with a whole number of hand-cut stones that turn into wedges on curves and stop at the figure's spine; later stones cut to fit against earlier ones with a grout gap; stroke Roman capitals in a tabula ansata; a height field: polished, slightly domed tops with worn edges, recessed sandy grout, a per-stone tilt so equal stones catch the raking light differently, cast shadows in the joints; red-ochre sinopia on the wet bed; lacunae that leave the sockets of lost stones in the old bed, a settling crack, dirt in patches |
+| **Stained glass** | `lib/stainedglass.py` · `StainedGlass` | the glazier's process: a cartoon cut into pieces (Voronoi mosaics, explicit cut sites for borders, slivers merged away); pot-metal glass coloured all the way through, every piece with its own shade and thickness (transmission ** thickness), reams running one way per piece and seed bubbles drawn out along them; grisaille trace lines, stippled matt with sticklight scratched out of it, silver stain; lead came on every boundary, lit as an H-section, with brighter solder blobs and a wide rim came; iron saddle bars wired to the leads, a crack mended with a strap lead; an ashlar wall with splayed reveals and voussoir joints; daylight from behind: coloured spill on the stone, glowing reveals, a soft upside-down projection on the sill, halation over the leads, grime and corrosion pits |
+| **Illuminated manuscript** | `lib/illuminated.py` · `Illuminated` | textura written with a simulated broad-edged quill (a stroke is the area an angled nib sweeps, so the diamond feet and hairline joins come from the pen, not a font), with long s, the Tironian et and a per-letter wobble; iron-gall ink that browns as the quill runs dry and pools at the stroke edges; vermilion rubrics, red-touched capitals, red and blue paragraph marks, line fillers, hyphenation; burnished gold as a mirror on a raised gesso cushion (each pixel reflects a studio window through its gesso normal, so the leaf shows bands, flares on the cushion edge and glittering punchwork, while shell gold stays matte); granular azurite, rose with lead-white tracery; an ivy spray grown recursively from a bar border; compass-drawn diagrams with a true stereographic astrolabe plate; vellum with follicles, veins, cockle, prickings, ruling, show-through and a flaw hole; foxing, thumb soil, gold flaked down to the red bole |
+| **Leonardo codex** | `lib/codex.py` · `Codex` | laid rag paper on a mount (laid and chain lines, fibre tooth), aged unevenly: browned ragged edges, a lost corner, yellowed clouds, crisp foxing, a water stain with a darker tide line, writing from the verso showing through; iron-gall ink from a quill whose width follows the nib, that runs dry stroke by stroke and is re-dipped (darker again, sometimes a pooled bead), warm amber where thin and umber where thick, darker where strokes cross; left-handed '\\' hatching laid in bands, interleaved for darker tones and crossed only in the deepest shadow; red chalk that only catches the paper tooth, rubbed into a soft tone; colourless stylus and compass lines lit by raking light, prick holes at the centres, leadpoint underdrawing; contours searched twice before the final line; mirror writing right to left in pseudo-Italian; machine parts (gears, lantern pinions, crown wheels, cranks, pulleys) drawn by a pen renderer with a z-buffer: hidden lines dropped, faces hatched by how far they turn from the light, only silhouettes and creases inked; blots and struck-out ideas |
+| **Silhouette** | `lib/silhouette.py` · `Silhouette` | black paper that is actually cut: a glued outline re-cut into tiny straight scissor facets, separately snipped strands (plume barbs, lashes, whiskers, ringlets, rigging) that lift a little and throw a longer shadow, and cut-outs where the card shows through (an eye, lace piercings), all drawn at 4× so one-pixel strands survive; thin shell-gold bronzing that stays on the paper; an oval gilt frame built as a height field from a real moulding profile (sight-edge bead, cove, pearls, rope-twist torus) that mirrors a room lit by one window, with leaf-square seams, red bole rubbed through on the crests and grime in the hollows; a verre églomisé mount, the rebate's shadow on the card and a convex-glass reflection; iron-gall captions in roundhand; a block-printed Regency stripe wallpaper (misregistration, pin dots, mismatched seams, sheet joins) hung from a picture rail on twisted silk cords |
+| **Letterpress poster** | `lib/letterpress.py` · `Letterpress` | one forme per ink, pressed one pass at a time, and each pass lands a few pixels off: the red tint creeps out from under the black key on one side and leaves a sliver of paper on the other; wood type set to full measure, every letter its own block with wood-grain streaks, an end that prints light, dents, nicked corners and the odd split, shaded letters carrying their drop shade on the other forme; stiff oil ink with a ragged edge, a squeezed darker rim, starved mottled solids that let the paper tooth show through, dust dropouts; brass rules made of several pieces with joints; a woodcut cut the way wood is left standing: key lines thicker on the shadow side, swelling hatching whose line width follows the tone and tapers out in the light, a loose separately cut red block; after printing the bill is folded in thirds (ink cracked along the creases), a date strip is pasted on, tacked up, browned from the edges and foxed |
+| **Soviet constructivism** | `lib/constructivism.py` · `Constructivism` | one sheet, two plates: everything red is on one plate and everything black (solids, type, every halftone dot) on the other, each laid down with its own registration error, so red and black meet with a sliver of paper or a dark overprint; transparent inks that multiply (black over red is a warm black), a mottled film with voids, fibre-ragged edges and a letterpress halo; the "photographs" are real renders (a tiny z-buffer rasteriser: hyperboloid lattices, lathes, swept tubes, procedural wood grain and dial scales) screened in poster space into one 45° AM halftone and cut out with scissors that leave a paper margin and never cut into a gap; heavy condensed Cyrillic grotesque with a hand-drawn wobble; cheap cream stock yellowed at the edges, folded in four with the ink cracked along the creases, foxing, a tide line and rusty pin holes |
+| **Art Deco** | `lib/artdeco.py` · `ArtDeco` | nothing is ever outlined: every shape is a knife-cut frisket sprayed with an airbrush, so edges are crisp and every inside is one smooth fade, with droplet grain only where the coat is thin; a sunburst of alternating rays that fades with distance, a moon sprayed off-centre so it reads as a sphere; stepped set-back towers sprayed dark-to-light across each face with fluting, lit ledges, window grids and lit slits, pushed into the haze by distance; a river that mirrors the scene in ripple dashes, bright things reflecting more; the streamliner and its arched viaduct are a real little 3D scene (signed distances, sphere-traced, edge pixels supersampled) but shaded like an illustrator models a cylinder: a poster colour ramp per material, an airbrushed highlight band on the upper shoulder, moon rim light, reflected light under the belly, speed stripes that converge on the raked nose, the headlamp lighting the rails ahead; a Deco display alphabet built from strokes and elliptical bowls, gilt with a hard horizon line |
+| **Golden-age comic** | `lib/comic.py` · `ComicCover` | made the way the shop made it, printed the way the press printed it: brush key lines on the black plate that land thin, swell, lift off and run heavier on the shadow side, spotted blacks, feathering that grows out of shadow edges in uneven waves; a colour guide in which every area is a mix of Ben-Day tints (0/20/40/70/100 %) of three process inks, skies stepped in bands cut along wavy film edges; each plate screened at its own angle (dots grow, touch at 50 %, turn into holes, overlaps beat into rosettes) and printed a few pixels out of register, the hand-cut flats wandering off the line art; newsprint that has gone tan and drinks the ink (ragged dots, dropped highlights, mottled solids with bare pits); a perspective block logo extruded toward a vanishing point, price box, caption, speech, shout and thought balloons, hand lettering, sound effects; afterwards spine stress ticks, rusted staples, a rubbed corner, a crease and foxing; the stages proof the key plate, then yellow, + red, + blue |
+| **Pop silkscreen** | `lib/popart.py` · `PopSilkscreen` | the Factory method rebuilt step by step on one gessoed cotton-duck canvas (a plain-weave height field with slubs), taped into a grid with paint creeping under the tape. Each panel is hand-painted first in loud flat acrylic: the background, then loose shapes traced off the photo, a little too big or too small and drifting off it, with faint brush streaks, a dry drag at the edge and a low ridge that catches the light. Then the same photographic key is pulled through it: shadow masses with the grainy edge of a photo threshold, mid-tones as a coarse 45° halftone, dust specks on the film. Every pull lands with its own shift, a hair of rotation and its own ink load: streaks along the squeegee, the skipped line of a nicked blade, a clogged dry patch where the colour shows through the black, or flooded shapes that swell and fill in, and now and then a faint second impression |
+| **ASCII art (line printer)** | `lib/lineprinter.py` · `LinePrinter` | the scene is never drawn on the paper: it is painted into a hidden role map at six by ten samples per character cell, then every cell picks its character: lines and silhouette turns by their direction measured in real pixels and where they sit in the cell (\| / \\ for steep, ' - . _ for flat so curves come out as _.-', X where struts cross, ( ) for round sides, one cell kept per row), fills from each role's own ramp with error diffusion inside the role (smoke . : % @ #), the darkest cells overstruck in extra passes; then a drum printer strikes each line through a fabric ribbon: every character slug sits a little high or low the same way each time, a weak hammer leaves a pale column, weak strikes thin out and break up on the ribbon weave and paper tooth instead of turning grey, worn slugs print the same nick, the ribbon fades down the page; a whole greenbar sheet lying on the desk between two tear lines, with feed holes you can see the desk through, micro-perforations, page-break creases and a blank bottom margin; a red ballpoint tick list and a ring around the plotted point |
+| **Low poly (1999 3D)** | `lib/lowpoly.py` · `LowPoly` | an actual little software rasterizer drawing into a 384×216 framebuffer: a pinhole camera, vertices snapped to whole pixels, back-face culling, every triangle of the scene in one painter's-sorted list (the console ordering table) with a depth bias for decals, near-plane clipping, an optional z-buffer; flat shading per face (hemisphere ambient + sun + a per-facet glint, so gold flashes facet by facet); tiny procedural textures sampled nearest-neighbour and interpolated affinely, so strata bend on big polygons near the camera; per-vertex fog that swallows the far clip plane; alpha-cut crossed-quad trees; the era's four blend modes for a propeller disc, blob shadows, sparkles and a lens flare; then 15-bit colour through the 4×4 ordered dither and a ×5 nearest-neighbour blow-up; a stamped bitmap HUD (italic ramp digits with outline and drop shadow, a stepped speed bar, a minimap) |
+| **Stencil graffiti** | `lib/stencil.py` · `Stencil` | a board-marked concrete wall built as albedo plus height and lit by a low sun (sawn-plank bands and wood grain pressed into the cement, broken paste fins along the seams, cone-shaped form-tie holes with rusted rods or mortar plugs, bug holes, rust and rain streaks, a damp tide line with efflorescence, a hairline crack); stencils that are real cut card: every island the cuts isolate is found and held by the shortest bridge, letters get bridged counters, and the bridges show as hairlines of bare wall; a picture in tones is several cards sprayed light to dark, each a few pixels off; the can moves in overlapping sweeps whose gaussian cones add up to a paint film, crisp where the card lay flat, creeping under where it lifted, with a drifting overspray halo; coverage is droplets, so thin film is a scatter of dots, not a blur; paint misses the bottom of pits, lies on the relief with a satin sheen, and runs from heavy lower edges as drips with a neck and a bead; freehand skinny-cap lines that follow the hand's speed; a council roller buff in stepped vertical passes with an old tag ghosting through; snapshots with the card still taped up |
+| **Embroidered patches** | `lib/patch.py` · `Patch` | stitched the way an embroidery machine does it: every shape is cut into parallel rows at its own angle and each row into stitches — short staggered tatami for backgrounds, one long float per row for satin (split above a max length) — so every edge is made of stitch ends; each stitch is a round glossy thread that dives into the cloth at both needle holes and carries an anisotropic (Kajiya–Kay) highlight, so one colour sewn at two angles catches the light differently; padded satin domes into a light-to-dark sheen along each float; merrowed edges are a rolled cord of slanted wraps, die-cut shapes get a hot-cut satin border, both supersampled and faded where stitches crowd into tight corners; a 3/1 right-hand twill denim (warp denser than weft, ~60° wales, ring-dyed slubby warp, worn high points) with a felled seam and double topstitching; one patch still being whip-stitched on, the needle and thread lying on the cloth |
Ask Claude to *"draw it yourself"*, *"paint this with code"*, or *"claude绘图"*, and name a style if you like. Claude then:
@@ -177,6 +219,22 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages
- **Bauhaus**: print light to dark, one ink per screen, and keep everything of one colour on its screen so misregistration moves it together. Keep bare-paper pits to ~2% and only in thin-film streaks, or solids turn to sandpaper and type to a worn rubber stamp. Use a light 3×3 edge blur (a big blur rounds the corners). Knock labels out of dark solids instead of printing black on blue, and keep margin text clear of the crop marks.
- **Synthwave**: keep the sun's base colour low and let the bloom lift it, or it burns to white and the slits fill in. Break the sea's reflection into bands stretched about the sun's column, and let light sources reflect more strongly than the sky. Measure grid lines in screen pixels and swap dense cells for their average. Keep tape damage mild: one tracking band, sub-pixel jitter.
- **Perler beads**: build real tubes and let the light make the bead: the hole, the peg inside it and a sliver of side wall are what separate it from pixel art. Iron with melt, not paint: 0.4 is the half-melt (holes open, beads stuck, diamond gaps), 0.7 a finished piece; drop seam grooves and fine grain once it is flat, or it turns into hex nuts and frosting. Shade walls from smoothed maps sampled at their foot, never from the anti-aliased edge row. Keep heaps about one bead deep. Gloss comes from a soft box seen in reflection (an arc on the upper-left rim), not a Fresnel ring around every hole.
+- **Petroglyph**: knock the varnish off, don't paint light on: pits break through to paler stone and the low sun shades each one. Peck densely (about 3× the pit area) or it reads as sprinkled chalk. Varnish is a near-uniform dark coat; streaks are separate crisp-edged runs that narrow and fade downward — full-frame stripe noise turns into wood grain, hard-topped rectangles into a barcode, blur into smoke. Spalls need small scalloped lips and fresh orange stone; keep AO light or every step grows a black ring. Pad the height map by edge before marching shadows. Show at least three ages (fresh, centuries, ghost).
+- **Egyptian tomb painting**: declare everything first, then paint in the old order (grid, red sketch, ground round the figures, one pigment per pass, outlines, text, age) and keep every layer, so damage can uncover the one beneath. Bending figures must turn their shoulders toward profile, or the back shoulder rides above the head. Labourers go bare-chested; collars and size belong to the overseer and the scribe. A plaster loss needs depth (a height field and a cast shadow on its upper-left wall), not a brown patch with a bright rim. Keep detail z-offsets tiny (+0.002), so a basket's weave never jumps over the arm that holds it.
+- **Roman mosaic**: let the rows do the drawing: eyes and details first, then the outline row, then fill inward along the outline, halo the figures, and only then lay the background — the flow of the rows (andamento) is what reads as mosaic. Keep stone tops polished and low (1.5–2 px) or the floor turns into cobbles. Match stones on hue before lightness so greys stay grey. The spine filter must see past the next row, or outline rows swell. Set whatever must stay whole (eyes, the fish in a net) before the lines that cross it. Age it last: lacunae with sockets in the old bed, one crack, dirt in patches.
+- **Stained glass**: every colour edge is a lead, so plan the pieces like a glazier: one `glass()` call per area of one glass (a separate region always leaves a ring of lead), cut only what glass can be cut (trunks and boughs about 16 px and wider; paint the twigs), and model volume with matt and sticklight, not extra pieces. Keep the leads near-black and let halation eat only their edges. Fix the saddle-bar heights first and keep birds, faces and words clear of them. Light the room only at `daylight()`, so the stone stays still between stages.
+- **Illuminated manuscript**: work in the scriptorium's order: rule, write (leaving the rubrics and initials blank), rubricate, draw the diagrams, gild, paint, then pen. Gold goes down before any paint, and the paint goes round it. Treat burnished gold as a mirror whose colour is the room it reflects: give the gesso a gentle burnished wave and put flat gold on the slope of the window light, and keep the camera far away so one side of the spread doesn't turn olive. Measure every line before writing (about 45 characters at an 18 px x-height), hyphenate rather than over-justify, and keep the sprays clear of the text and of the bar.
+- **Leonardo codex**: hatch the way a left hand does: '\\' everywhere, laid in bands with shared, slightly staggered breaks, never a chain of bowed dashes (that reads as fur). Model a form by where hatching stops, not by darkening everything: across a membrane panel use t² from one rib to the next, and cross-hatch only the deepest band. Bat-wing edges sag inward between rib tips. In a fanned wing draw only what shows of each feather and keep the tips round. Keep the paper old (yellowed clouds, crisp foxing, a tide line) and the ink warm. Let the pen run dry and be re-dipped; mirror-write the notes right to left, ragged on the left.
+- **Silhouette**: write each profile once as control points and splined outlines, and fix proportions with `warp=` instead of retyping coordinates. Cut fine detail rather than drawing it: plumes, lashes, whiskers and rigging are separate snips at 4×, and one cut-out (an eye, the slit in a bow loop) does more than ten lines. Bronze sparingly: six strands of hair, a brim edge, a few folds; dense parallel lines read as a striped helmet and random arcs as bubbles. Leave a sliver of card between overlapping shapes (sails, jibs, ribbon loops) or they fuse into one black mass. Size each caption to the oval's half-width at its height.
+- **Letterpress poster**: press one ink at a time and let the second pass land a few pixels off; never draw the misregistration by hand. Set every wood-type line to the full measure (squeeze or stretch the face, then letter-space) and ink each letter as its own block. Keep salt to the inside of solids, about 1–5 %; any more and it reads as a noise filter. Hatch with line width following a tone so lines taper out in the light instead of stopping. Build an animal as one silhouette with a single outer key line plus a few internal contours; the legs stand vertical under a body tilted about its hip.
+- **Constructivism**: keep every colour on its own plate and only misregister whole plates, so red and black move against each other together. Black on black cannot be knocked out: keep wave lines and slabs clear of labels with reversed numbers. Lattice photos need sparse, thick members, a paler far side and a light pre-screen blur, or the halftone fills in to a dotted cone. Put cut-out photos over red or black, or the paper margin disappears; let the scissors bridge narrow gaps and fill enclosed holes. Hide the end of a wedge under the photo it points at. Pad the plates before shifting them, or the edge of the sheet shows bare paper.
+- **Art Deco**: never draw a line; cut a frisket and spray a fade into it, and let form come from light and dark only. Keep droplet grain to the thin part of a coat (noise × d(1 − d)); everywhere-grain reads as sand. For the 3D machine, build an exact distance field (a core segment dilated by a radius, stretched only along the track) — scaling a cross-section toward a point gives fingerprint artefacts on the nose. Measure where the nose surface really is before placing the headlamp and ending the stripes. Make bright things reflect more than dark sky in the river. Keep the towers below the title band and put the clock on the tower face, not above it.
+- **Golden-age comic**: let the press make the look: give flats as Ben-Day tint mixes, screen each plate at its own angle and print it a few pixels off; never paint dots or misregistration by hand. Keep the blue plate out of browns (C+M+Y rosettes read green at a coarse screen) and keep two-plate tints to a few areas so the figures stay legible. Draw what is behind first and let each `part` erase the lines it covers (the crew before the hull). Feathering lengths should drift in waves, not tick like a ruler, and must not run through lettering. Make sure wind-blown props (scarves, ears) don't cover the next character's face.
+- **Pop silkscreen**: paint first, print last, and never trace the colour shapes from the key: simplify them, make them a little too big or too small, and give each panel its own paint drift and key shift, so the misregistration changes from panel to panel. Put the expression in the key and the mood in the colour scheme. Draw closed eyes as bold arcs, never as a thin line over an eye-shaped patch, which reads as a brow. Keep the ink believable: density 0.92–0.95 is starved but legible, 1.1–1.15 is heavy, and flood above about 0.5 fills half the face. Starved ink should break into squeegee streaks and clumps, not into the canvas weave (that reads as a digital grid). Build masks with a running np.maximum, not a list of full-size masks.
+- **ASCII art (line printer)**: paint roles and tones into the hidden map, never characters by hand; give each material its own symbol ramp (letters in a fill read as words). Pick line characters by direction in real pixels, not by template match, and keep one cell per row; run lattice braces one column per row so crossings land in a cell centre and print X. Outline lit puff tops only and let tone carry the shadows. A flame is a column that widens from the nozzle: sparse ! | ' . streaks inside, a % @ # smoke sheath at the rim, running into the cloud. Weak strikes must break up on the ribbon and paper tooth, not go grey.
+- **Low poly (1999 3D)**: build the frame the way the hardware did and let its limits show: a small framebuffer blown up with no smoothing, flat-shaded facets, blocky texels, fog that hides the far plane, 15-bit dither. Don't make the painter's sort fight hidden geometry: leave out faces nobody sees (the river bed under the water) and give decals a depth bias. Compose with the camera: put the hero on a third with aim(), bend the track so the targets step away diagonally, and keep some sky for the sun and its flare. Gold wants a thick tube, few facets, a low-shine glint and a warm base, or the blue sky light turns it olive; if the sun is in frame, light the scene from higher than the sun you see. Keep the flare to dots and solid hexagons, away from the subject.
+- **Stencil graffiti**: cut it like a real stencil: run `bridges()` (or check `islands()` is 0) on every card, or the middle of every O and every gap between an arm and the body silently falls out. Do tones as separate cards, light to dark, with `shade_side()` for the grey and black plates; make the black plate bold (a third of the figure), keep the grey clearly between white and black. Keep the card mostly flat: the crisp core is the point, and a lifted card everywhere turns every edge furry. Spend drips where they tell (the black plate, the lettering, under the reel), a couple at most on the light plate, never from bridges. Things that stick out of a figure (a scarf, a fringe) must not read as limbs: two tails from one knot, stripes, fringe strands that do not touch.
+- **Embroidered patches**: give every shape its own stitch angle and change it between neighbours — the angle, not the colour, is what separates two pieces of thread. Tatami for anything wider than ~60 px; satin for letters, peaks, flames and other narrow shapes, laid across the narrow dimension (flames sideways, not up). Keep the lit face of a mountain mid-tone so white satin snowcaps pop. Draw small details before whatever sits on top of them, and clip running stitches to the patch. Die-cut corners need a radius of at least twice the border width. Merrow for circles, ovals and rockers; a hot-cut satin border for any other outline.
### Roadmap
@@ -188,7 +246,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,加上一个小巧的绘图库,内置四十三种画风:
| 画风 | 模块 | 为什么看起来像真的 |
|---|---|---|
@@ -219,6 +277,22 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages
| **包豪斯几何** | `lib/bauhaus.py` · `Bauhaus` | 在奶油色未涂布纸(云状纸浆、纤维、纸屑、纸齿、微微不平)上按色版先浅后深逐版刮印;每块网版有自己的套准误差,色块和黑线相接处露出一丝纸白或压出一道深边,套准十字叠成几色错开的样子;墨膜顺刮板方向有条纹、行程末端变薄,薄处露出纸齿坑点和针孔,版边有网目锯齿;墨半透明,叠印变深;圆、扇形、三角、粗黑条都落在严格的模数网格上;Futura 式几何无衬线大写和粗黑体,可从色块里挖空;裁切线、色标条和铅笔版号 |
| **复古 Synthwave** | `lib/synthwave.py` · `Synthwave` | 针孔相机看 80 年代复古未来的黄昏:横条切口越往下越厚的渐变落日;逐像素解析的霓虹网格,线宽准确,远处换成平均值不出摩尔纹;从品红渐变到青色的线框山脉;倒影按横带拉伸、碎成一条条光带的海面;带落日轮廓光的棕榈剪影;上映天空、下映地面、中间一道锐利地平线的镀铬大字,带挤出和星闪;霓虹手写字;最后「过一遍录像带」:色度渗色、跟踪噪带、磁头噪声、屏显字和扫描线 |
| **拼豆** | `lib/perler.py` · `Perler` | 整张桌面是高度图,豆子是真的短管,相机略向后仰、逐列找最近的表面:每颗豆露一条侧壁,孔里看得到内壁和被塑料透光染色的钉子,珠间缝里露出钉板;半透明钉板(方、圆、六边形)上的空钉;每颗豆色号深浅略有不同、在钉上略有歪斜;不透明、珠光、透明、夜光几种塑料;熨烫是真的熔化:管子塌低变宽、孔从边缘收小、相邻的豆通过平滑并集流到一起,缝缩成小菱形直到合拢,顶面变成一片带纸纹的蜡质平面;半透明熨烫纸顺着豆子盖下去,可以卷边揭开;镜面里看得到灯箱(亮面豆沿上一道锐利高光弧,熔化后变成一片蜡光);分色收纳盒里的豆堆、散落的豆、悬空带投影的镊子、带铅笔勾的图纸 |
+| **岩画** | `lib/petroglyph.py` · `Petroglyph` | 图是从石头上敲出来的,不是画上去的:砂岩高度图(大起伏、淡层理、砂粒、溶蚀浅坑、一道岩檐台阶)上长着沙漠漆,近乎均匀的深色漆膜加一条条清晰的蓝黑流痕;每个图形先起稿成遮罩,再用成百上千个不规则凹坑敲出来,凹坑打穿漆层、把砂粒碾白,所以轮廓在一锤的尺度上毛糙、内部是浅浅的颗粒状凹面;计日刻痕则是磨出来的 V 形槽;年代让旧图慢慢被漆盖回成鬼影,叠刻的层次自然出现;裂缝往下渗出漆痕;剥落是带小贝壳弧唇口的台阶疤,露出鲜橙色石面并带走部分旧图;壳状地衣;一盏低角度侧光,每个凹坑都有自己的投影 |
+| **古埃及墓室壁画** | `lib/tomb.py` · `TombPainting` | 按古代画工的工序一层层做墙,每层都留着:草筋泥上一层石膏灰泥,红赭石弹线的比例格(一格一个比例单位),带「找形」的红稿,绕开人物刷的底色,一罐颜料一遍的干壁画平涂(男子红赭、女子黄赭、半透明的褶裥亚麻、带亮晶的埃及蓝、绿釉料),按 z 叠放所以先上哪种颜色都不会叠错,最后是均匀的黑线和红褐线;人物照「正面律」画在可摆姿势的比例骨架上(侧脸正眼带眼线、正面肩膀和项圈、弯腰时肩膀转向侧面、两只脚都露大脚趾一侧、IK 求肘),按身份放大;四条腿都看得见的牛、被割麦人攥在拳里的二粒小麦、按方块排的彩色伪象形文字、凯凯尔饰带和色块边框;然后按地层做旧:成簇剥落到底色,或者剥到灰泥、露出红格和红稿,灰泥脱落到草筋泥(真的高度图:断续的白边和投影),裂缝、埃及蓝发灰绿、烟熏、潮痕、盐霜和蝇斑 |
+| **罗马马赛克** | `lib/mosaic.py` · `Mosaic` | 一张看不见的底稿,每块石子取脚下的平均色,从有限的石料盒(石灰石、带纹大理石、smalti 玻璃、陶片)里挑最接近的一种,先比色相再比亮度;石子沿距离场的等值线(marching squares)一排排铺,绕着每条轮廓、一圈圈围住眼睛(opus vermiculatum),图形外留一两圈光环,背景平铺或沿波浪排(opus tessellatum),边框排在转角斜接;每排切成整数块手凿石子,弯处变成楔形、在图形脊线处停住;后铺的石子贴着先铺的切掉一角并留灰缝;燕尾铭牌里的罗马大写字一笔一排石子;高度场打光:打磨过、微拱的石面和磨圆的边,下凹带砂的灰缝,每块石子略有倾斜,同色石子在斜光下明暗不一,灰缝里有投影;湿灰浆上的赭红起稿;脱落处露出旧灰浆床和石子留下的方坑,一道沉降裂缝,成片积灰 |
+| **彩色玻璃花窗** | `lib/stainedglass.py` · `StainedGlass` | 照玻璃匠的工序:画稿切块(Voronoi 拼块、边框按点切、切不出来的碎块自动并掉);通体着色的玻璃,每块深浅厚薄不同(透光率 ** 厚度),每块一个方向的条纹和顺纹拉长的气泡;grisaille 描线、带点彩颗粒的 matt 和木签刮白、银染;每条交界都上铅,按 H 形铅条打光,焊点更亮更鼓,窗边一圈宽铅;横铁条用铜丝扎在铅上,裂片用细铅条补;方石墙、斜面窗侧和楔石缝;日光从背后透进来:石头上的彩色溢光、发亮的窗侧、斜窗台上倒过来的柔和投影、亮玻璃吃掉一点铅条的光晕、积灰和腐蚀麻点 |
+| **泥金手抄本** | `lib/illuminated.py` · `Illuminated` | 字是一支模拟的宽头鹅毛笔写的:笔画是斜握的笔尖扫过的面积,菱形头脚和发丝连笔都出自笔,不是字体;有长 s、提罗速记的 et,每个字母略有抖动。铁胆墨随笔里的墨变干而由黑转褐,笔画边缘积墨。朱红标题、首字母点红、红蓝段落符、行尾填充、断词连字号。打磨金箔是凸起石膏底上的镜子:每个像素按石膏底的法线映出房间里的大窗,所以有明暗带、鼓边的反光和闪烁的打孔纹;壳金则是哑光颗粒。带颗粒的石青,玫瑰色配铅白描线。条形边框上递归长出常春藤花枝。尺规画的图解,星盘盘面是真实的球极投影。羊皮纸有毛孔、筋脉、起伏、针孔、打格线、背面透字和天然破洞;还有狐斑、翻页手印,金箔剥落处露出红色底料 |
+| **达·芬奇手稿** | `lib/codex.py` · `Codex` | 裱在卡纸上的帘纹碎布纸(帘纹、链线、纤维纸齿),不均匀地老化:发褐的毛边、缺一角、泛黄云斑、清楚的霉斑、潮线更深的水渍、背面的字透过来;铁胆墨水和鹅毛笔:笔宽随宽笔尖方向变化,墨一笔笔用干、再蘸又变浓(偶尔落笔积一个墨珠),薄处琥珀褐、厚处深赭,交叉处更深;左手「\」排线一排排下笔,越暗插得越密,只有最暗处才交叉;红粉笔只挂在纸齿上,再用手指揉开;尖笔和圆规的无色刻痕靠侧光显形,圆心有针孔,底下有铅笔起稿;轮廓先找两遍再定线;右到左的意大利语伪文镜像手写;齿轮、灯笼齿轮、冠齿轮、曲柄、滑轮由带 z-buffer 的笔绘渲染器画出:被挡住的线不画,面按背光程度排线,只描轮廓和折边;墨点和被划掉的废稿 |
+| **剪影** | `lib/silhouette.py` · `Silhouette` | 黑纸是真「剪」出来的:贴平的主轮廓重采样成一小段一小段剪口;单独剪下的细丝(羽枝、睫毛、胡须、垂卷、缆绳)微微翘起、影子更长;剪空处露出底卡(眼睛、蕾丝孔);全部 4× 超采样,1 像素的细丝也留得住;薄金粉只留在黑纸上;椭圆金框按真实线脚剖面(内口圆珠、凹槽、珠饰、绳纹大圆脚)建高度图,金面映出一扇窗照亮的房间,有金箔方块接缝、棱顶磨出的红色底漆、凹处积灰;玻璃背面的黑底金线圈(verre églomisé)、框口投在卡纸上的影子、凸面玻璃反光;铁胆墨圆体手写题签;木版印花的摄政时期条纹墙纸(错版、定位针点、对花略错、拼纸接缝),挂镜线铜钩垂下绞丝绳 |
+| **凸版印刷海报** | `lib/letterpress.py` · `Letterpress` | 每种油墨一块版,一次压一色,每次纸张落点都差几像素:红色套色块从黑轮廓下面一边探出来、另一边露出一线白纸;木活字一行排满版心,每个字是一块木头:木纹条痕、一端偏浅、凹坑、缺角、偶有顺纹裂缝,带投影的字把投影印在另一块版上;油墨边缘参差、边上挤出一圈深墨、大实地缺墨发花露出纸齿、灰尘留下圆形漏印;几段拼成的铜线,接头有细缝;木刻按「留下木头」的方式画:背光一侧加粗的轮廓线,线宽随明暗胀缩、亮处收尖的排线,另刻的松动红色色块;印完以后三折(折痕处油墨裂开)、贴日期条、钉上墙、边缘泛黄、长霉斑 |
+| **苏联构成主义** | `lib/constructivism.py` · `Constructivism` | 一张纸两块版:红的都在红版、黑的(色块、字、每个网点)都在黑版,每块版整体带自己的套印误差,红黑相接处一边露纸、一边叠出深色;墨是透明的、相乘叠印(黑压红是暖黑),墨层有浓淡、有漏墨小白点、边缘随纸纤维毛糙、色块边缘略积墨;「照片」是真渲染出来的(小型 z-buffer 光栅器:双曲面网格、旋转体、变径管、程序木纹和刻度盘),在海报坐标里统一加 45° 网点,再用剪刀沿轮廓留边剪下,剪刀进不去的窄缝和洞不剪;粗体压缩西里尔字带一点手绘抖动;便宜的奶油色纸边缘发黄,对折两次、折痕处墨层裂开,有霉斑、水渍潮线和图钉锈孔 |
+| **装饰艺术** | `lib/artdeco.py` · `ArtDeco` | 从不描边:每个形状都是刀刻的遮片,用喷枪喷色,所以边缘锐利、里面是一段平滑渐变,只有薄涂处才有雾滴颗粒;交替射线随距离变淡,月亮偏心喷涂出球感;阶梯退台高楼每层从暗侧喷到亮侧,带竖向凹槽、受光的退台边、窗格和竖条灯带,越远越淡入雾里;河面把画面镜像成一道道横向波纹,亮的东西反射更强;流线型列车和拱桥是真的小 3D 场景(距离场、球面步进、边缘像素超采样),但按插画家画圆柱的方式上色:每种材质一条海报色阶、上肩一道喷枪高光、月光轮廓光、下腹反光,速度线在倾斜车鼻上收拢,头灯照亮前方铁轨;Deco 展示字母由笔画和椭圆字碗拼成,金色渐变中间一道硬分界 |
+| **黄金时代漫画** | `lib/comic.py` · `ComicCover` | 按当年的分工做、按当年的印法印:黑版上的毛笔墨线起笔细、中段鼓、收笔尖,背光一侧加粗,实黑块,从阴影边长出来、长短成波浪起伏的羽状排线;色稿里每块颜色都是三原色 Ben-Day 网点比例(0/20/40/70/100%)的组合,天空是沿手裁波浪边分档的色带;每版按自己的角度加网(网点逐渐变大、50% 相接、再变成白孔,两版叠加出玫瑰斑),各自错开几像素,手绘分色还会游离墨线;新闻纸已经泛黄,并且吸墨(网点毛边、亮部小点丢失、实地发花、露出纸坑);朝灭点挤出的透视立体刊名、价格框、旁白框、对白 / 喊叫 / 想法框、手写字、拟声字;印完后书脊白色裂纹、生锈订书钉、磨角、折痕、霉斑;阶段动图先出黑版线稿,再依次叠印黄、红、蓝 |
+| **波普丝网** | `lib/popart.py` · `PopSilkscreen` | 按「工厂」的做法,在一张刷了白底漆的棉帆布上一步步重做(平纹布纹高度场和粗节);胶带隔出格子,颜料渗进胶带下。每格先手涂撞色丙烯:先是底色,再是照着照片描得很松的形状,偏大或偏小、和照片对不准,带顺笔的轻微明暗、边缘干笔拖痕和一道受光的漆脊。然后把同一块照相黑版刮印上去:阴影块带照相阈值的颗粒边,中间调变成 45° 粗网点,膜上有灰尘点。每次放版都有自己的偏移、极小的转角和自己的墨量:顺刮板方向的条纹、刮板缺口留下的细白线、墨干在网上的一块露底,或者墨多糊版、形状变胖、细缝填死,偶尔还印了两次,留下一层灰影 |
+| **ASCII 字符画(行式打印机)** | `lib/lineprinter.py` · `LinePrinter` | 画面不直接画在纸上,而是画进一张隐藏的角色图(每个字符格 6×10 个采样),再逐格选字:线条和剪影转折按真实像素里的方向和在格里的位置选字(陡的 \| / \\,平的 ' - . _,曲线自然成 _.-',交叉处 X,圆的侧边 ( ),每行只留一格),填色按各自角色的字符阶梯、在角色内做误差扩散(烟是 . : % @ #),最暗的格多走几遍叠打;然后鼓式打印机隔着布色带一行行击打:同一个字总是偏高或偏低一点,弱锤留下一道淡列,力度弱的字变细、在色带织纹和纸纹上断开起麻点而不是变灰,磨损的字模每次缺同一块,色带越往下越淡;桌上一整张绿条连续纸,上下两道撕线和折痕、底部留页边,导孔里看得到桌面,两侧微孔撕线;读的人用红圆珠笔打勾、圈出绘图里的点 |
+| **低多边形(1999 年代 3D)** | `lib/lowpoly.py` · `LowPoly` | 一个真的软件光栅化器,画进 384×216 的帧缓冲:针孔相机,顶点吸附到整像素,背面剔除,整个场景的三角形排成一张按深度排序的表(主机的 ordering table)从远到近画,贴花带排序偏置,近平面裁剪,可选 z-buffer;每个面一个颜色的平面着色(半球环境光 + 太阳 + 逐面闪光,金环一面一面地闪);几十像素的程序贴图最近邻取样、仿射插值,靠近镜头的大三角形上岩层会弯;逐顶点雾吞掉远裁剪面;alpha 硬裁切的十字插片树;当年的四种半透明模式画螺旋桨盘、圆斑影子、星光和镜头光晕;最后 15 位色加 4×4 有序抖动,最近邻放大 5 倍;点阵 HUD(带描边和投影的渐变斜体数字、阶梯速度条、小地图) |
+| **喷漆模板涂鸦** | `lib/stencil.py` · `Stencil` | 木纹模板清水混凝土墙是反照率加高度图、低太阳打光(木板压出的色带和木纹、板缝的断续水泥浆棱、锥形对拉螺栓孔里的锈铁头或灰浆堵头、气泡孔、锈水和雨痕、返潮水线和泛碱、发丝裂缝);模板是真的刻开的卡纸:刻断的孤岛自动找出来、补最短的桥,字腔自带桥,桥在漆上是露墙的细缝;多层就是多张卡纸先浅后深、每张贴歪几像素;喷罐来回扫,高斯喷锥叠成漆膜,卡纸贴平处边缘锐利、翘起处往里渗、外面一圈雾化;漆是雾滴,薄处是散点不是模糊;盖不进小孔、贴着墙面起伏、带缎面光泽,下边缘太厚就流成带细颈和圆珠的滴痕;徒手细喷嘴线条随手速变粗变重;竖向滚道的市政灰漆,底下的旧签名还透出来;快照里模板还贴在墙上 |
+| **刺绣徽章** | `lib/patch.py` · `Patch` | 像绣花机一样绣:每块形状按自己的针向切成平行的行、每行再切成针——大面积用短针错位的填充绣(tatami),细长形用一行一根长线的缎面绣(太长自动拆成分段缎面),所以形状的边缘就是一排针脚;每针都是一根有光泽的圆线,两头扎进布里,高光是各向异性的(Kajiya–Kay),同一种颜色换个针向亮度就不同;缎面按衬垫拱起,一根线上从亮到暗;圆章、弧形条章包锁边(斜着一圈圈绕的圆绳),异形章包热切缎面边,两者都做了子采样,在急弯处针距过密时把线的起伏淡成平滑的扇形;3/1 右斜纹牛仔布(经密纬疏、斜纹约 60°、环染竹节纱、高处磨白),折边缝压双道明线;最后一枚徽章正在手缝,针和线还躺在布上 |
对 Claude 说「claude绘图」「你自己画」「用代码画」,也可以指定画风。它会:
1. **先定构图**:层次、焦点、留白,而且画面要图解内容本身;
@@ -275,6 +349,22 @@ python3 examples/aurora_morning.py out.png # 弥散玻
python3 examples/bauhaus_form_colour.py out.png # 包豪斯几何:形与色
python3 examples/synthwave_coastline.py out.png # 复古 Synthwave:海岸线 1987
python3 examples/perler_strawberry_coaster.py out.png # 拼豆:草莓杯垫
+python3 examples/petroglyph_migration.py out.png # 岩画:迁徙季
+python3 examples/tomb_harvest.py out.png # 古埃及墓室壁画:尼罗河丰收
+python3 examples/mosaic_harbor.py out.png # 罗马马赛克:港口渔获
+python3 examples/stainedglass_seasons.py out.png # 彩色玻璃花窗:四季之窗
+python3 examples/illuminated_starchart.py out.png # 泥金手抄本:星辰之书
+python3 examples/codex_ornithopter.py out.png # 达·芬奇手稿:扑翼机
+python3 examples/silhouette_family.py out.png # 剪影:剪影小像
+python3 examples/letterpress_circus.py out.png # 凸版印刷海报:马戏团来了
+python3 examples/constructivism_radio.py out.png # 苏联构成主义:无线电
+python3 examples/artdeco_express.py out.png # 装饰艺术:夜行快车
+python3 examples/comic_rocket.py out.png # 黄金时代漫画:火箭小队
+python3 examples/popart_cat_moods.py out.png # 波普丝网:猫的六种心情
+python3 examples/lineprinter_launch.py out.png # ASCII 字符画(行式打印机):发射记录
+python3 examples/lowpoly_canyon.py out.png # 低多边形:峡谷飞行
+python3 examples/stencil_kite.py out.png # 喷漆模板涂鸦:放风筝
+python3 examples/patch_camping.py out.png # 刺绣徽章:三晚露营
```
### 作画要点(Claude 交图前逐条自查)
@@ -304,6 +394,22 @@ python3 examples/perler_strawberry_coaster.py out.png # 拼豆:
- **包豪斯**:先浅后深,一种颜色一块版,同色的东西放在同一块版上,错位才会整体一起动;露纸坑点约 2%、只在墨膜薄的条纹里,否则色块像砂纸、字像旧橡皮章;版边只做 3×3 轻模糊(大模糊会把直角磨圆);深色块上的标注用挖空,不要黑字压蓝;页边小字让开裁切线。
- **复古 Synthwave**:太阳底色压低、靠泛光提亮,否则冲成白团、切口被填平;海面倒影按横带以太阳所在列为中心拉伸打碎,光源的倒影比天空更强;网格线按屏幕像素算宽度,格子太密就换成平均值;录像带损伤要轻:一条跟踪噪带、不到一像素的逐行抖动。
- **拼豆**:先搭出真的管子,让光把豆子「画」出来:孔、孔里的钉子和那一条侧壁,才是它和像素风的区别。熨烫用 melt 控制,不要手涂:0.4 是半熔(孔在、珠粘、留菱形缝),0.7 是成品;熨平后去掉接缝沟和细纹,否则像六角螺母、像糖霜。侧壁从平滑后的图、在墙脚取样着色,别用抗锯齿的边缘行。豆堆只堆一层左右。光泽靠镜面里的灯箱(左上沿一道弧),不要每个孔一圈菲涅尔白环。
+- **岩画**:是把漆敲掉,不是往上画亮色:凹坑打穿到浅色石头,低角度侧光给每个坑打出明暗。凿点要密(约单坑面积的 3 倍数量),否则像撒了一层粉笔末。沙漠漆是近乎均匀的深色漆膜,流痕是一条条边缘清楚、往下变窄变淡的独立痕迹:全幅竖条噪声会变木纹,硬顶矩形会变条形码,糊开会变烟。剥落要有小贝壳弧唇口和鲜橙色石面;AO 要轻,否则每个台阶都长一圈黑边。投影步进前先用边缘复制 pad 高度图。至少给三档年代(新凿、几百年、鬼影)。
+- **古埃及墓室壁画**:先把东西都声明好,再按古代工序画(比例格、红稿、绕开人物刷底色、一种颜料一遍、勾线、写字、做旧),每层都留着,剥落时才露得出下面那层。弯腰的人肩膀要往侧面转,否则后肩会翘到头顶上。劳工赤膊,项圈和放大的身形留给总管和书吏。灰泥脱落要有深度(高度图加左上内壁的投影),不是一块带亮边的褐色补丁。部件细节的 z 只加 0.002,扛着的筐的编织纹才不会跳到手臂上面。
+- **罗马马赛克**:让石子的排向去画:先眼睛和细节,再轮廓一排,再沿轮廓往里填,再给图形加光环,最后才铺背景——排向(andamento)才是马赛克的样子。石面要低而平(1.5–2 px),否则成了碎石路。取石先比色相再比亮度,灰色里才不会混进蓝粉。判断脊线的滤波要看得到下一排,否则轮廓排会变胖。要保持完整的东西(眼睛、网里的鱼)先铺,横穿它的线后铺。最后才做旧:脱落处露出旧灰浆床和石子方坑,一道裂缝,成片积灰。
+- **彩色玻璃花窗**:每条色边都是一条铅,要像玻璃匠一样分块:同一种料只用一次 `glass()`(另起一块区域就会多一圈铅);只切玻璃切得出来的形状(树干、大枝宽 16 px 以上,细枝用画的);体积靠 matt 和刮白,不靠多切块。铅条要接近黑,光晕只吃掉一点边。先定铁条高度,鸟、脸、字都避开它。`daylight()` 时才点亮室内,阶段之间石墙不动。
+- **泥金手抄本**:照作坊的顺序来:打格 → 抄写(红字和首字母留空)→ 朱笔 → 画图 → 贴金 → 上色 → 勾线。先贴金后上色,颜料要绕开金。打磨金箔当镜子算,颜色就是它映出的房间:给石膏底一点打磨留下的起伏,让平面的反射落在窗光的斜坡上,才有明暗带;相机放远,免得跨页一侧的金发黑。动笔前先量行宽(x 高 18 px 时一行约 45 个字符),宁可断词加连字号,也不要硬撑词距;花枝离正文和边框条都要留空。
+- **达·芬奇手稿**:照左手的习惯排线:处处是「\」,一排一排下笔,同一排共用略有错位的断点,别把弯弯的短笔首尾接成一串(会像卷毛);明暗靠排线停在哪里,而不是整片加深:蒙皮从前一根肋到后一根肋取 t²,只在最深的一条交叉;蝙蝠翼的后缘在两个肋尖之间往里凹;扇形展开的翅膀每根羽毛只画露出来的部分,羽尖要圆;纸要旧(泛黄云斑、清楚的霉斑、潮线),墨要暖;让笔里的墨用干再蘸;笔记右到左镜像书写,左边参差。
+- **剪影**:轮廓用控制点一次写好再样条化,比例不对用 `warp=` 改,别逐点重敲。细节要「剪」出来而不是画:羽毛、睫毛、胡须、缆绳都是 4× 超采样的单独细条,剪一个空(眼睛、蝴蝶结里的缝)比画十条线都管用。金粉要省:六根发丝、一道帽檐、几道衣褶就够,密排平行线像条纹头盔,随机小弧像气泡。互相重叠的形状(帆、三角帆、蝴蝶结环)之间留一道卡纸缝,否则连成一块黑。题签字号按那一行椭圆的半宽来定。
+- **凸版印刷海报**:一次只压一种油墨,让第二次压印自己差几像素,不要手画错位。每行木活字都排满版心(先压扁或拉宽字面,再加字距),每个字当成一块木头单独上墨。漏白只放在实地内部、约 1%–5%,多了就像噪点滤镜。排线的线宽跟着明暗走,亮处收尖消失,不要一刀切断。动物合成一个剪影只刻一圈外轮廓,再补几笔内部轮廓;身体绕髋抬起,腿竖直落下。
+- **苏联构成主义**:一种颜色一块版,套印误差只按整块版加,红黑才会整体错开。黑上加黑挖不出空:电波线、黑条要让开带反白数字的标注。网格类照片要杆件少而粗、远侧变浅、加网前少模糊,否则网点糊成一根点状锥体。剪下的照片要压在红或黑上,否则白边看不出;剪刀进不去的窄缝要桥接,围住的洞要填平。楔形末端藏到它指向的照片下面。错位前先 pad 版,否则纸边露白。
+- **装饰艺术**:不画线,先刻遮片再往里喷渐变,形体只靠明暗。雾滴颗粒只留在薄涂处(噪声 × d(1−d)),处处都有就像撒沙。3D 列车要用合格的距离场(核心线段膨胀一个半径,只沿轨道拉伸),把截面朝一个点缩放会在车鼻上出指纹纹。先实测车鼻表面在哪,再放头灯、收条纹。河面里亮的东西要比黑天空反射得多。高楼都压在标题带下面,钟画在楼身上,别浮在楼顶上。
+- **黄金时代漫画**:网点和错版交给印刷模型,不要手画:色块只给 Ben-Day 比例,每版按自己的角度加网、错开几像素去印。棕色别带蓝版(粗网下 C+M+Y 的玫瑰斑发绿),两版叠网只留在少数区域,人物才看得清。先画后面的东西,让 `part` 擦掉被挡住的墨线(先画座舱里的人,再画船体)。羽状排线的长短要成波浪起伏,别像尺子刻度,也别穿过字。顺风飘的围巾、耳朵别挡住后面角色的脸。
+- **波普丝网**:先涂色、后印黑。颜色形状别照着黑版描:要简化,偏大或偏小,每格的颜色漂移和放版偏移都不一样,错位才会一格一个样。表情放在黑版里,心情交给配色。闭眼要画成粗弧线,别在眼睛形状的色块上压一道细线,那样会读成眉毛。墨量要可信:density 0.92–0.95 缺墨但认得出,1.1–1.15 墨多,flood 超过约 0.5 会糊掉半张脸。缺墨时要碎成刮板条纹和团块,别碎成布纹方格(像数码图案)。遮罩用 np.maximum 就地累积,别把几十张整幅遮罩放进列表。
+- **ASCII 字符画(行式打印机)**:把角色和调子画进隐藏的角色图,不要手摆字符;每种材料一套符号阶梯,填色里用字母远看就成了单词。线条字符按真实像素里的方向选、不用模板匹配,每行只留一格;桁架斜撑一列一行地走,交点落在格心才打得出 X。云团只在亮顶描边,阴影交给调子。尾焰是从喷口往下变宽的亮柱:里面稀疏的 ! | ' . 条纹,边缘一圈 % @ # 烟套,接进烟云。弱的击打要在色带和纸纹上断开起麻点,不是变灰。
+- **低多边形**:照当年硬件的做法画,并且让它的局限露出来:小帧缓冲无平滑放大、平面着色的小面、块状纹素、用雾藏住远裁剪面、15 位色抖动;别让画家排序去和看不见的几何打架:没人看得见的面(水下的河床)干脆不生成,贴花加排序偏置;构图靠相机:用 aim() 把主角放到三分点,让赛道转弯、目标沿对角线排开,留出天空给太阳和光晕;金环要粗管、少面、低 shine 的闪光和偏暖的底色,否则蓝天光一照就发橄榄色;太阳在画里时,着色光比看得见的太阳抬高一些;光晕只用小圆点和实心六边形,别压在主体上。
+- **喷漆模板涂鸦**:照真模板来刻:每张卡纸都跑一遍 `bridges()`(或者确认 `islands()` 是 0),否则每个 O 的中间、手臂和身体之间的卡纸都会悄悄掉掉。分几个色调就分几张卡纸,先浅后深,灰版、黑版用 `shade_side()` 切;黑版要大胆(约占人物三分之一),灰色要明显介于黑白之间。卡纸以平贴为主:清晰的核心是这种画风的看点,到处翘起来,所有边都会长毛。滴痕用在有戏的地方(黑版、字、线轮下),白版最多一两道,桥上不起滴。从人物身上伸出去的东西(围巾、流苏)别让它像胳膊:一个结里分出两条尾巴、画横条纹、流苏散开别碰在一起。
+- **刺绣徽章**:每块形状给自己的针向,相邻的要换角度——分开两块线的是针向,不是颜色。宽过约 60 px 的用填充绣;字、山尖、火焰等细长形用缎面绣,针横跨窄的那一边(火焰横着走,不是竖着)。山的亮面用中间调,白色缎面雪顶才跳得出来。小细节要先于压在它上面的东西画,平针用 `clip=` 限在徽章里。异形章的圆角半径至少是边框宽度的两倍。圆、椭圆、弧形条章用锁边,其他轮廓用热切缎面边。
### 计划
diff --git a/SKILL.md b/SKILL.md
index 378505b..7813c6b 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -1,6 +1,6 @@
---
name: claude绘图
-description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。内置二十七种画风:中国水墨、水彩、剪纸拼贴、韩国彩铅、日本动漫、编辑风手绘(Riso)、油画厚涂(梵高式流向笔触+颜料浮雕打光)、浮世绘木版画(晕色、木纹、墨线主版、青海波)、像素风(低分辨率+Bayer 抖动+像素字体)、黏土定格(高度图捏出的彩泥+影棚打光)、蓝晒(普鲁士蓝日光晒图,植物剪影透光)、十字绣(Aida 布十字绣+回针绣+缎面绣+法式结)、复古仪器面板(60 年代收音机/仪器正面:柚木、拉丝铝、旋钮、刻度窗、指示灯)、贴纸拼贴·小票(模切乙烯贴纸、热敏小票、和纸胶带、吊牌、橡皮章)、实验笔记本·贴纸(线圈方格本、铅笔图表、荧光笔、红笔圈、便利贴)、黑板板书(墨绿石板、粉笔颗粒、板擦残影、示意图与公式)、赛博朋克(雨夜霓虹街道、玻璃管霓虹招牌、全息广告、湿路面倒影)、卡通手绘(蓝铅笔稿、毛笔线、错位平涂、赛璐璐阴影、逐帧抖线)、等轴 2.5D(正等轴微缩模型、一个太阳照出三面明暗、悬浮数据卡)、单线画(一根不断开的线一笔画完、唯一点睛色)、柔光 3D(光线追踪的糖果色小球海和鼓鼓的软字、景深)、形变动画(一条轮廓依次变形、洋葱皮残影、缓动曲线)、报刊拼贴(牛皮纸、手撕旧报纸、网点老照片、勒索信拼贴字)、弥散玻璃(弥散渐变、磨砂玻璃卡片界面)、包豪斯几何(三原色几何、丝网印刷海报)、复古 Synthwave(切口落日、霓虹网格、镀铬字、录像带质感)、拼豆(钉板上的熔珠小管、熨烫熔合)。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」,或点名以上任一画风(含黏土、彩泥、定格动画、蓝晒、晒图、十字绣、刺绣、复古面板、老式收音机、贴纸、小票、收据、手帐拼贴、实验笔记本、方格本、荧光笔、便利贴、黑板、板书、粉笔、赛博朋克、霓虹、雨夜街道、卡通、手绘卡通、逐帧手绘、抖线、等轴、2.5D、微缩模型、单线画、一笔画、线条动画、柔光 3D、3D 渲染、C4D 风、软糖字、小球海、形变、变形动画、报刊拼贴、剪报、达达、勒索信字、网点印刷、弥散渐变、玻璃拟态、毛玻璃、包豪斯、几何构成、丝网印刷、Synthwave、蒸汽波、合成器浪潮、80 年代复古、拼豆、拼拼豆、熔珠、熨豆、豆豆画、钉板、烫豆),或 "draw it yourself", "paint with code", "procedural painting", "watercolor / collage / colored pencil / anime / editorial / impasto oil / ukiyo-e / pixel art / clay / claymation / cyanotype / sun print / cross-stitch / embroidery / retro instrument panel / vintage radio / sticker collage / receipt / lab notebook / graph paper / chalkboard / blackboard / cyberpunk / neon city / cartoon / hand-drawn animation / isometric / 2.5D / continuous line / one-line drawing / soft 3D / 3D render / puffy letters / ball pit / shape morph / morphing / newspaper collage / Dada / ransom note / halftone / glassmorphism / aurora gradient / Bauhaus / geometric poster / screen print / synthwave / retrowave / outrun / perler beads / hama beads / artkal / fuse beads / melty beads / pegboard beads without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。
+description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。内置四十三种画风:中国水墨、水彩、剪纸拼贴、韩国彩铅、日本动漫、编辑风手绘(Riso)、油画厚涂(梵高式流向笔触+颜料浮雕打光)、浮世绘木版画(晕色、木纹、墨线主版、青海波)、像素风(低分辨率+Bayer 抖动+像素字体)、黏土定格(高度图捏出的彩泥+影棚打光)、蓝晒(普鲁士蓝日光晒图,植物剪影透光)、十字绣(Aida 布十字绣+回针绣+缎面绣+法式结)、复古仪器面板(60 年代收音机/仪器正面:柚木、拉丝铝、旋钮、刻度窗、指示灯)、贴纸拼贴·小票(模切乙烯贴纸、热敏小票、和纸胶带、吊牌、橡皮章)、实验笔记本·贴纸(线圈方格本、铅笔图表、荧光笔、红笔圈、便利贴)、黑板板书(墨绿石板、粉笔颗粒、板擦残影、示意图与公式)、赛博朋克(雨夜霓虹街道、玻璃管霓虹招牌、全息广告、湿路面倒影)、卡通手绘(蓝铅笔稿、毛笔线、错位平涂、赛璐璐阴影、逐帧抖线)、等轴 2.5D(正等轴微缩模型、一个太阳照出三面明暗、悬浮数据卡)、单线画(一根不断开的线一笔画完、唯一点睛色)、柔光 3D(光线追踪的糖果色小球海和鼓鼓的软字、景深)、形变动画(一条轮廓依次变形、洋葱皮残影、缓动曲线)、报刊拼贴(牛皮纸、手撕旧报纸、网点老照片、勒索信拼贴字)、弥散玻璃(弥散渐变、磨砂玻璃卡片界面)、包豪斯几何(三原色几何、丝网印刷海报)、复古 Synthwave(切口落日、霓虹网格、镀铬字、录像带质感)、拼豆(钉板上的熔珠小管、熨烫熔合)、岩画(沙漠漆上凿出的凹坑图形、新旧凿痕、剥落)、古埃及墓室壁画(灰泥墙、红格起稿、分栏叙事、象形文字、剥落)、罗马马赛克(石子与玻璃沿轮廓一排排铺、灰缝、燕尾铭牌)、彩色玻璃花窗(哥特尖拱窗、通体着色玻璃、grisaille 彩绘与银染、铅条、透光)、泥金手抄本(羊皮纸、鹅毛笔哥特体、朱红标题、打磨金箔首字母)、达·芬奇手稿(铁胆墨水、左手排线、红粉笔、镜像手写、机械分解图)、剪影(黑纸剪出的侧影小像、薄金粉、椭圆金框)、凸版印刷海报(木活字、红黑双色错版、木刻插图)、苏联构成主义(红黑两版、斜条与楔形、西里尔大字、网点照片拼贴)、装饰艺术 Art Deco(1930 年代喷枪流线型海报、交替射线、阶梯高楼、金色 Deco 字)、黄金时代漫画(毛笔墨线、Ben-Day 网点、四色错版、新闻纸)、波普丝网(多格撞色平涂 + 错位的照相黑版)、ASCII 字符画(行式打印机、绿条连续纸、叠打)、低多边形(1999 年代 3D:平面着色、仿射贴图、逐顶点雾、15 位色抖动)、喷漆模板涂鸦(混凝土墙上多层卡纸模板喷绘、雾化与滴痕)、刺绣徽章(牛仔布上的机绣徽章:填充绣、缎面绣、锁边)。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」,或点名以上任一画风(含黏土、彩泥、定格动画、蓝晒、晒图、十字绣、刺绣、复古面板、老式收音机、贴纸、小票、收据、手帐拼贴、实验笔记本、方格本、荧光笔、便利贴、黑板、板书、粉笔、赛博朋克、霓虹、雨夜街道、卡通、手绘卡通、逐帧手绘、抖线、等轴、2.5D、微缩模型、单线画、一笔画、线条动画、柔光 3D、3D 渲染、C4D 风、软糖字、小球海、形变、变形动画、报刊拼贴、剪报、达达、勒索信字、网点印刷、弥散渐变、玻璃拟态、毛玻璃、包豪斯、几何构成、丝网印刷、Synthwave、蒸汽波、合成器浪潮、80 年代复古、拼豆、拼拼豆、熔珠、熨豆、豆豆画、钉板、烫豆、岩画、岩刻、凿刻、石刻、沙漠漆、史前壁刻、大角羊、古埃及、埃及壁画、墓室壁画、法老时代、象形文字、尼罗河、底比斯、罗马马赛克、马赛克镶嵌、镶嵌画、石子拼画、地砖画、古罗马地板、彩色玻璃、彩绘玻璃、花窗、玻璃花窗、教堂花窗、哥特花窗、铅条玻璃、泥金手抄本、手抄本、彩饰手抄本、中世纪手稿、羊皮纸、哥特体、花体首字母、泥金、贴金、星盘、达芬奇、达·芬奇、达芬奇手稿、手稿风、文艺复兴手稿、发明手稿、镜像字、镜像书写、扑翼机、红粉笔、钢笔排线、机械草图、分解图、剪影、剪影肖像、侧影、侧面像、黑纸剪影、剪影小像、椭圆金框、乔治时代肖像、摄政时期肖像、凸版印刷、活版印刷、木活字、铅字海报、马戏团海报、复古海报、老海报、19 世纪海报、双色套印、错版、套色错位、木刻插图、构成主义、苏联海报、苏联构成主义、俄国先锋派、罗德琴科风、红黑海报、照片蒙太奇、照片拼贴海报、西里尔字、装饰艺术、装饰风、流线型、流线型海报、1930 年代海报、旅行海报、铁路海报、火车海报、喷枪画、喷笔画、阶梯高楼、射线背景、盖茨比风、黄金时代漫画、老漫画、复古漫画、美漫封面、漫画封面、Ben-Day 网点、本戴点、网点上色、四色印刷、四色错版、新闻纸、对白框、拟声字、1940 年代漫画、波普、波普艺术、波普丝网、沃霍尔风、丝网版画头像、撞色头像、多格重复头像、六宫格撞色头像、ASCII、字符画、字符艺术、文字画、行式打印机、绿条纸、连续打印纸、针孔打印纸、老电脑打印、叠打、低多边形、低面数、低模、多边形风、千禧年 3D、90 年代 3D、复古 3D 游戏、老游戏截图、PS1 风、N64 风、平面着色、线框、游戏 HUD、飞行游戏、穿环、喷漆、模板涂鸦、镂空模板、喷漆模板、模板喷绘、街头涂鸦、街头艺术、墙绘、滴漆、班克西风格、刺绣徽章、徽章、布章、臂章、刺绣贴、绣标、锁边、牛仔外套徽章、户外徽章、营地徽章、弧形条章),或 "draw it yourself", "paint with code", "procedural painting", "watercolor / collage / colored pencil / anime / editorial / impasto oil / ukiyo-e / pixel art / clay / claymation / cyanotype / sun print / cross-stitch / embroidery / retro instrument panel / vintage radio / sticker collage / receipt / lab notebook / graph paper / chalkboard / blackboard / cyberpunk / neon city / cartoon / hand-drawn animation / isometric / 2.5D / continuous line / one-line drawing / soft 3D / 3D render / puffy letters / ball pit / shape morph / morphing / newspaper collage / Dada / ransom note / halftone / glassmorphism / aurora gradient / Bauhaus / geometric poster / screen print / synthwave / retrowave / outrun / perler beads / hama beads / artkal / fuse beads / melty beads / pegboard beads / petroglyph / rock art / rock carving / desert varnish / Egyptian tomb painting / ancient Egypt / hieroglyphs / Theban tomb / Roman mosaic / floor mosaic / tesserae / opus vermiculatum / Pompeii mosaic / stained glass / leaded glass / church window / Gothic window / grisaille / illuminated manuscript / medieval manuscript / book of hours / gold leaf / illuminated initial / blackletter / vellum / astrolabe / da Vinci notebook / Leonardo codex / Renaissance sketchbook / mirror writing / iron-gall ink / red chalk / sanguine / ornithopter / exploded view / inventor's sketch / silhouette / silhouette portrait / cut-paper profile / shade portrait / Georgian portrait / Regency portrait / oval gilt frame / letterpress / wood type / playbill / circus poster / Victorian poster / two-colour misregistration / woodcut poster / constructivism / constructivist poster / Soviet avant-garde / Russian avant-garde / Rodchenko style / photomontage poster / art deco / streamline moderne / 1930s travel poster / railway poster / airbrush poster / sunburst rays / Gatsby style / golden age comic / vintage comic book / comic cover / Ben-Day dots / four-color printing / newsprint / speech balloon / pulp cover / pop art / Warhol-style / pop silkscreen / silkscreen portrait / repeated pop portrait grid / ASCII art / text art / typewriter art / line printer / greenbar / fanfold paper / tractor feed / overstrike / printer plot / low poly / low-poly / retro 3D / 90s 3D game / PS1 style / N64 style / software rasterizer / flat shading / affine texture mapping / vertex fog / game HUD / stencil / stencil graffiti / spray paint stencil / street art / drips and overspray / Banksy-style stencil / embroidered patch / embroidery patch / iron-on patch / sew-on patch / merit badge / camp badge / merrow border / rocker patch / denim jacket patches without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。单独说「剪纸」指剪纸拼贴、「刺绣」指十字绣、「丝网印刷 / screen print」指包豪斯几何;「打马赛克」是打码,不是马赛克画风。
---
# Claude 绘图
@@ -41,6 +41,22 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型
| 包豪斯几何 | `lib/bauhaus.py` · `Bauhaus` | `examples/bauhaus_form_colour.py` 形与色 · Form & Colour(奶油色纸上的丝网印刷讲座海报:黄三角、红方、蓝圆站在粗黑地线上,60° 弧、直角框、挖空的圆心和半径,下面大字角数 3 / 4 / 0;「形与色」大标题、挖空字的黑条论点「角越尖,色越亮」;构成网格、套准十字、裁切线、色标条、铅笔版号) | 约 2 秒 |
| 复古 Synthwave | `lib/synthwave.py` · `Synthwave` | `examples/synthwave_coastline.py` 海岸线 1987(横条切口的渐变落日沉入海面、倒影碎成一条条光带、线框小岛与线框山脉、霓虹网格地面、霓虹边线的海岸公路、灭点处亮灯的小城、带落日轮廓光的棕榈剪影、驶向城市的尾灯、镀铬大字 COASTLINE 与霓虹手写 Last Sunset、录像机 PLAY 与日期屏显、色度渗色、跟踪噪带和扫描线) | 约 4 秒 |
| 拼豆 | `lib/perler.py` · `Perler` | `examples/perler_strawberry_coaster.py` 草莓杯垫(方格图纸上的草莓图样与图例,铅笔勾掉已摆的颜色;透明方钉板上摆到一半:草莓摆完、天蓝底色一行行往下铺,镊子夹着下一颗悬在空钉上,旁边散豆;九格分色收纳盒;熨平的圆杯垫:豆子熔成一片蜡质平面、孔缩小、外沿扇贝形,压着揭下的熨烫纸) | 约 9 秒 |
+| 岩画(凿刻砂岩) | `lib/petroglyph.py` · `Petroglyph` | `examples/petroglyph_migration.py` 迁徙季(带沙漠漆的砂岩岩面:一群大角羊朝同一方向往上走,一串偶蹄印通向同心圆水源,弓手和举投矛器的猎人等在后面;新月和一个月的计日刻痕、螺旋太阳、岩檐下一大一小两只手印;新、中、旧三档凿痕,几乎被漆盖回的旧符号;渗漆的裂缝、鲜橙色剥落疤、壳状地衣;左上低角度侧光) | 约 10 秒 |
+| 古埃及墓室壁画 | `lib/tomb.py` · `TombPainting` | `examples/tomb_harvest.py` 尼罗河丰收(底比斯墓室的一面墙,三栏讲一件事:犁地播种(并轭的牛、扶犁人、撒种人、挥锄人),割二粒小麦(弯腰的割麦人、拾穗的女人、挂水囊的无花果树),书吏点数粮袋(蹲坐的书吏、堆成 5-4-3 的 12 袋粮和上方的象形数字 12、用量斗倒粮的人);按身份放大的庄园总管、伪象形文字栏、凯凯尔饰带、墙脚的尼罗河;剥落处露出红格和红稿,灰泥脱落、裂缝、潮痕、烟熏) | 约 4 秒 |
+| 罗马马赛克 | `lib/mosaic.py` · `Mosaic` | `examples/mosaic_harbor.py` 港口渔获 · The Day's Catch(赭红起稿的灰浆床上铺约一万六千块石子与玻璃:黑白奔浪纹边框、火焰灯塔、船首画眼的渔船和鼓起的方帆、挑在杆上的渔网、把鱼从网里拖走的章鱼、游鱼和海鸥;燕尾铭牌 CAPTVRA · DIEI / ET POLYPVS FVR「今日渔获——以及章鱼小偷」;人物沿轮廓一排排铺,背景平铺并留光环;脱落处露出石子方坑,沉降裂缝,灰缝积灰) | 约 12 秒 |
+| 彩色玻璃花窗 | `lib/stainedglass.py` · `StainedGlass` | `examples/stainedglass_seasons.py` 四季之窗 · Window of the Seasons(石墙上四扇哥特尖拱窗,同一棵树的春夏秋冬:春花与燕子、夏天的苹果和一窝雏鸟、秋天金红树冠和离开的雁阵、冬天积雪的枝和知更鸟,太阳高度随季节变;VER / AESTAS / AVTVMNVS / HIEMS 银染题字带;铅条与焊点、横铁条、一处补过的裂片,窗侧斜面和窗台上的彩色光) | 约 4 秒 |
+| 泥金手抄本 | `lib/illuminated.py` · `Illuminated` | `examples/illuminated_starchart.py` 星辰之书 · Liber Stellarum(暗色书桌上摊开的天文书。左页「行星的次序」:打磨贴金方框里的玫瑰色 Q 首字母,字腔里是夜空和观星塔;鹅毛笔哥特体伪拉丁正文、朱红标题、长出常春藤花枝的条形边框、一幅诸天圆图。右页「怎样量一颗星的高度」:蓝色首字母 O 配红色花笔卷须,按纬度 48° 投影的尺规星盘,规尺瞄向页边的贴金星。羊皮纸毛孔、针孔与打格线、背面透字、破洞、狐斑、金箔剥落露出红色底料) | 约 9 秒 |
+| 达·芬奇手稿 | `lib/codex.py` · `Codex` | `examples/codex_ornithopter.py` 扑翼机(裱在卡纸上、缺一角的泛黄帘纹纸;一串飞鸟画出一次振翅,红粉笔鸢翼写生和一根大羽毛;中间是蝙蝠翼扑翼机仰视图:右翼用左手「\」排线画完,左翼只起了头、露着铅笔稿;尖笔圆规画的比例圆,曲柄、灯笼齿轮、冠齿轮、滑轮的传动分解图,腕关节特写,划掉的废稿;右到左的镜像伪文笔记、墨点、霉斑、水渍) | 约 8 秒 |
+| 剪影 | `lib/silhouette.py` · `Silhouette` | `examples/silhouette_family.py` 剪影小像(木版印花条纹墙纸上,挂镜线铜钩的绞丝绳吊着三幅椭圆金框剪影:中间是戴鸵鸟羽毛宽檐帽、螺旋垂卷的女主人,右边一艘满帆回家的双桅横帆船,左边坐在流苏垫子上望着她的猫;单独剪下的羽枝、睫毛、胡须和缆绳,剪空的猫眼和蕾丝孔;薄金粉、铁胆墨圆体题签、玻璃背面的金线圈、凸面玻璃反光、棱顶磨出红色底漆的旧金框) | 约 3 秒 |
+| 凸版印刷海报 | `lib/letterpress.py` · `Letterpress` | `examples/letterpress_circus.py` 马戏团来了(1890 年代红黑两色马戏团海报:左栏每行木活字排满版心——THE GRAND TRAVELLING、带投影的红色大字 CIRCUS、宋体黑木活字「马戏团来了」、星号节目单;右边木刻:走钢丝的舞者端着平衡杆,下面戴非斯帽的大象踩在条纹鼓上扬鼻致意,40 FT. 尺寸线;红版色块与黑版轮廓错开几像素;三折折痕裂墨、贴上的日期条 SATURDAY · MAY 17、钉孔锈斑、泛黄与霉斑) | 约 6 秒 |
+| 苏联构成主义 | `lib/constructivism.py` · `Constructivism` | `examples/constructivism_radio.py` 无线电 · РАДИО(虚构的 1920 年代无线电爱好者杂志封面,红黑两版:仰拍的双曲面网格广播塔印成网点、叠在红色圆盘上,塔尖射出红色楔形和越传越细的黑色波前,送进剪刀剪下的网点照片——带号角喇叭的电子管收音机;黑色斜条里反白 СЛУШАЙТЕ ВЕСЬ МИР(收听全世界),粗体压缩西里尔大字 РАДИО,三个编号标注;对折两次的折痕裂墨、霉斑、水渍潮线、图钉锈孔) | 约 6 秒 |
+| 装饰艺术(Art Deco) | `lib/artdeco.py` · `ArtDeco` | `examples/artdeco_express.py` 夜行快车 · Night Express(1930 年代喷枪流线型铁路海报:午夜蓝长渐变天空、满月外一圈交替射线、探照灯;雾中远城和阶梯退台高楼,钟楼的钟停在 11:40;河面把城市和月亮反射成横向波纹;栗红流线型列车从城里驶上拱桥迎面而来,金色速度线收拢在车鼻上,头灯照亮铁轨;Deco 金字 NIGHT EXPRESS、阶梯角双金线边框;全画没有一根描边,形体全靠明暗) | 约 12 秒 |
+| 黄金时代漫画 | `lib/comic.py` · `ComicCover` | `examples/comic_rocket.py` 火箭小队 No. 3(1940 年前后的报摊漫画封面:朝灭点挤出的立体刊名 ROCKET SQUAD、价格框和黄色旁白框;暮色天空分档网点、大月亮;红色火箭起飞,June 舰长指着月亮喊「NEXT STOP -- THE MOON!」,后座小狗 Pip 戴着护目镜;没赶上的机修工 Sparky 吊在绳梯上喊「HEY!! WAIT FOR ME!!」;拟声字 WHOOOSH!;毛笔墨线与羽状排线、Ben-Day 网点、三色版错位、泛黄新闻纸、书脊裂纹和生锈订书钉) | 约 5 秒 |
+| 波普丝网 | `lib/popart.py` · `PopSilkscreen` | `examples/popart_cat_moods.py` 猫的六种心情(白底漆帆布用胶带隔出 3×2 六格,同一只虎斑猫按顺序讲一件小事:歪头好奇 → 馋得吐舌头 → 吃到了眯眼笑 → 被抓包瞪圆眼 → 压耳哈气 → 歪头睡着;每格先手涂一套撞色、描得很松,再刮印同一块照相黑版,中间调成 45° 粗网点;六格放版的位置、角度和墨量各不相同:糊版、缺墨、横刮、印了两次留灰影、干版露底) | 约 3 秒 |
+| ASCII 字符画(行式打印机) | `lib/lineprinter.py` · `LinePrinter` | `examples/lineprinter_launch.py` 发射记录(桌上一整张 1970 年代 132 列绿条连续纸,两侧导孔、微孔撕线;左边整幅火箭发射的字符画:尖拱头锥、. : + % # 侧光箭身、叠打 #@ 的滚转标记、从喷口往下变宽的尾焰亮柱扎进翻滚的烟云,旁边是桁架勤务塔、塔吊、远处水塔、清晨太阳和人字形鸟群;右栏是事件日志、高度-时间打印机绘图和通道状态表;鼓式打印机的上下跳字、弱锤淡列、色带渐淡;读的人用红圆珠笔打勾、圈点、写了 on plan) | 约 2.3 秒 |
+| 低多边形(1999 年代 3D) | `lib/lowpoly.py` · `LowPoly` | `examples/lowpoly_canyon.py` 峡谷飞行 · Canyon Run(一帧虚构的 1999 年飞行游戏:小特技飞机在沙漠峡谷的右弯处压坡度,对准九个金环里的第五个,第六个挂在天然石拱下;阶梯状分层岩壁、起伏小面的河、十字插片杜松、雾里化开的方山;半透明螺旋桨盘、金环闪光、镜头光晕;384×216 帧缓冲、15 位色 4×4 有序抖动、无平滑放大 5 倍;HUD:金环计数 04/09、单圈时间、阶梯速度条、赛道小地图) | 约 0.2 秒 |
+| 喷漆模板涂鸦 | `lib/stencil.py` · `Stencil` | `examples/stencil_kite.py` 放风筝 · Hold On(木纹模板清水混凝土墙:木纹、浆棱、对拉螺栓孔、锈水雨痕、返潮泛碱、发丝裂缝;三张卡纸模板白 → 灰 → 黑喷出的小孩:毛线帽、羽绒服、往前飘的条纹围巾,身子后仰攥着线轮;徒手喷的风筝线连到左上角的红色菱形风筝;同一张小模板转着角度喷的燕子和树叶;带桥的 HOLD ON 模板字;清晰核心、外溢雾化、飞沫、滴痕;滚筒灰漆盖掉的旧签名、被水枪冲淡的粉色签名) | 约 6 秒 |
+| 刺绣徽章 | `lib/patch.py` · `Patch` | `examples/patch_camping.py` 三晚露营(牛仔夹克后背,过肩缝压着双道明线,一晚一枚徽章:第一晚是热切缎面边的拱形异形章——日落分层天空、远山、湖面倒影、亮灯的帐篷;第二晚是金色锁边圆章——雪峰、松林、营火与火星、弯月,缎面字 HIGH CAMP / NIGHT 2,上方弧形条章 THREE NIGHTS OUT;第三晚是正在手缝的指南针章,针和线还留在牛仔布上;一条刺子绣虚线把三枚徽章串成路线) | 约 6 秒 |
各画风共用 `lib/core.py` 里的底层工具:噪声、模糊、样条曲线、多边形遮罩、有机轮廓 `blob_pts`、毛笔 `bristle_stroke`、中文字体查找;新四种还用到补零平移 `shift`、文字遮罩 `text_mask`、西文字体查找 `latin_font`/`load_font`,以及高度图打光 `height_normals`、`height_shadow`(沿光线步进的投影)、`ambient_occlusion`。
@@ -71,7 +87,23 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型
- 产品界面、App / 小组件展示、效率工具与数据面板、明亮通透的科技感、讲解片的「功能 / 界面」页 → 弥散玻璃(要暗夜霓虹氛围仍用赛博朋克);
- 设计感海报、讲座 / 展览 / 活动海报、概念图解(形状、比例、对比、原则)、讲解片里的「定义 / 原理」页 → 包豪斯几何;
- 80 年代复古未来、怀旧、夏夜公路与海边、音乐和歌单封面、讲解片的「复古科技 / 回到过去」封面 → 复古 Synthwave(要雨夜城市用赛博朋克,要低分辨率游戏感用像素风);
-- 手作、DIY 教程、「从图纸到成品」的步骤图、把像素图案做成可爱实物(杯垫、挂件、冰箱贴)、讲解片里的「动手做」页 → 拼豆(要屏幕上的像素游戏感用像素风,要布上的针线用十字绣)。
+- 手作、DIY 教程、「从图纸到成品」的步骤图、把像素图案做成可爱实物(杯垫、挂件、冰箱贴)、讲解片里的「动手做」页 → 拼豆(要屏幕上的像素游戏感用像素风,要布上的针线用十字绣);
+- 远古、史前、起源、「人类最早的记录」、狩猎与迁徙、动物群、天文与历法、讲解片里的「历史开端 / 最早怎么记事」页 → 岩画(凿刻砂岩);
+- 古代文明、历史与考古、农业和劳动场面、「一步一步」的工序或流程讲成分栏连环画、讲解片里的「最早的记录 / 起源 / 古人怎么做」页 → 古埃及墓室壁画;
+- 古典、地中海、古罗马 / 古希腊题材,海洋生物、港口与渔猎、动物图鉴,门槛或地面铭文,讲解片里的「历史 / 起源 / 古代」页 → 罗马马赛克(要屏幕上的像素格子感用像素风,要熔珠小管的手作感用拼豆);
+- 教堂、中世纪、哥特、庄严而温暖的透光,节日与季节,「一年四季 / 时间流转」的分格叙事,讲解片里的「历史 / 传统工艺」页 → 彩色玻璃花窗(要现代霓虹发光用赛博朋克);
+- 中世纪、古籍、典藏感、「古老的学问」(天文、历法、草药、炼金这类老知识)的图解、书名页和章节首页、讲解片里的「历史 / 起源」页 → 泥金手抄本(一页里要有字:正文、红字标题和首字母是它的主体);
+- 发明、机械原理、「这东西是怎么动的」、从自然到设计(仿生)、工程手稿感的讲解页、「草图 / 构思 / 研究笔记」页、复古科学插图 → 达·芬奇手稿(要现代实验记录用实验笔记本,要讲课推导用黑板板书);
+- 人物小传、宠物、家族与纪念、复古肖像、「这个人 / 这只猫 / 这条船是谁」的介绍页、怀旧礼物卡片,不能用真人照片时 → 剪影(要童趣的彩纸故事用剪纸拼贴;要老照片拼贴感用报刊拼贴);
+- 活动 / 演出 / 开业 / 讲座的复古海报、「XX 来了」式的宣告、节目单与价目、旧时代广告、19 世纪美式或民国风的印刷品、讲解片里的「历史 / 老派做法」页 → 凸版印刷海报(要几何构成的现代海报用包豪斯几何,要剪报拼贴用报刊拼贴);
+- 工业、技术、发明史,「从 A 传到 B」的原理图解(广播、电报、铁路、流水线),强对角线的海报和杂志封面,讲解片里的「年代 / 历史 / 先驱」页,需要老照片质感又不能用真人照片 → 苏联构成主义(不写政治口号;要三原色几何讲座海报用包豪斯几何,要剪报和勒索信字用报刊拼贴);
+- 旅行、交通、城市主题海报,复古而有高级感的主视觉(开业、晚会、发布会、酒店、邮轮、列车),「速度 / 现代 / 黄金年代」主题,讲解片里「历史上的未来 / 1930 年代」的封面 → 装饰艺术(要 80 年代霓虹复古用复古 Synthwave,要几何构成和三原色用包豪斯几何);
+- 复古漫画、冒险故事的「出发 / 登场 / 大事件」、怀旧玩具与少儿读物感、讲解片的「故事开场 / 角色介绍」封面、需要对白框和拟声字的画面 → 黄金时代漫画(要现代日漫用日本动漫,要拟人小物件的轻松图解用卡通手绘,要红黑两色木刻海报用凸版印刷海报);
+- 同一个东西的几种状态、情绪、版本或配色并排对比,系列头像(宠物、角色、吉祥物),「一图多版」的潮流海报,讲解片里的「同一个东西的几副面孔 / 变体对比」页,要有名人肖像的波普感又不能用真人 → 波普丝网(要单张几何海报的套色印刷用包豪斯几何;要剪报和网点老照片用报刊拼贴);
+- 计算机史、老机房、复古科技、数据和日志、「当年的电脑怎么画画」、程序员 / 极客向的配图、讲解片里的「输出结果 / 运行日志 / 打印报告」页 → ASCII 字符画(行式打印机)(要屏幕上的低分辨率游戏感用像素风,要手写板书用黑板板书);
+- 游戏感、复古 3D、「90 年代末 / 千禧年」怀旧、飞行 / 赛车 / 闯关、带 HUD 的「关卡 / 进度 / 任务」页、讲解片里的「早期 3D 图形是怎么画出来的」(线框 → 平面着色 → 贴图 → 雾)→ 低多边形(要 2D 小尺寸游戏感用像素风,要柔和现代的 3D 渲染用柔光 3D,要正交微缩模型用等轴 2.5D);
+- 街头、城市、态度与幽默、一句短口号配一个小人物的海报、公益与社区宣传、「一个人 + 一件小事」的极简故事、讲解片的「观点 / 金句」页 → 喷漆模板涂鸦(要霓虹夜景用赛博朋克;要设计感的丝网海报用包豪斯几何;要剪报拼贴用报刊拼贴);
+- 徽章、勋章、打卡 / 成就 / 里程碑、旅行与户外、社团与活动标志、讲解片里的「收集 / 解锁 / 第 N 关」页 → 刺绣徽章(要手作布艺的十字格子感用十字绣;要贴纸质感用贴纸拼贴)。
每种画风一幅范例作为质量基准(范例都不用禅意主题);水墨另加一幅「月印万川」(留白托月、水面倒影)。
@@ -368,6 +400,281 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask
- 层次与动画:`on_top(*objs)` 提到最上层,`remove(obj)` 拿走;`stage(name)` 只存快照,`save(path, stages_dir)` 时才按 1× 渲染各阶段
- 颜色常量 `BEADS`;角度逆时针为正;`save('x.jpg')` 默认 quality 88、4:4:4 色度
+**岩画 `Petroglyph`**:
+- 思路:岩画不是画上去的,是把岩面的深色皮(沙漠漆)敲掉。一切都是高度(px)和颜色场,最后用左上一盏低角度侧光照亮:法线明暗、沿光线步进的投影(每个凹坑左上壁暗、右下壁亮)、凹处的 AO
+- 构造:`Petroglyph(W, H, seed, light=(-0.62, -0.5, 0.6))`
+- 岩石:
+ - `rock(colour, relief, bedding, grain)`:砂岩高度图(大起伏、时有时无的层理、砂粒、浅凹坑)和漆下的石色;
+ - `ledge(y, drop=34)`:一道折线岩檐,下面的岩面退后一个台阶、漆更薄;
+ - `varnish(strength, streaks, top, scour, patches)`:沙漠漆,近乎均匀的深色漆膜 + 清晰的蓝黑流痕 + 浅色流痕,顶部更厚、近地面被风沙磨薄;
+ - `fracture(pts, width, depth, seep, branches)`:裂缝,锯齿窄槽、圆肩、分叉,往下渗出深色漆痕
+- 起稿:`draft()` 返回 `Draft`(`stroke(pts, w, end_w)`、`fill(pts)`、`dot`、`ring`、`add(mask)`);现成图形都返回 Draft,可用 `into=` 合成一个:
+ - `bighorn(x, y, size, facing, kind='ram'|'ewe'|'lamb', gait, rot)` 大角羊(扭转透视的角);
+ - `hunter(x, y, size, facing, weapon='bow'|'atlatl')` 拉弓 / 举投矛器的猎人;
+ - `sun_spiral(x, y, r, turns, rays)`、`crescent(x, y, r, thick, rot)`、`concentric(x, y, r, rings)` 水源;
+ - `hand(x, y, size, rot, outline, spread)`、`hoofprints(pts, size, every)` 偶蹄印、`meander(pts, width, smooth)` 任意线
+- 凿与磨:
+ - `peck(glyph, density, size, depth, age, scatter)`:用成百上千个不规则凹坑把图形敲出来,打穿漆层、碾白砂粒;
+ - `abrade(pts, width, depth, age)`:磨出 V 形槽(比凿点光滑、发亮,带顺向擦痕);
+ - `abrade_tally(x, y, counts, gap, length, width, row_gap, slant, age, strike_every)`:成排计日刻痕
+- 年代:`age` 0 新凿(亮、锐),0.3 几百年,0.6–0.8 几乎被漆重新盖住;新图凿在旧图上自然更亮、更深
+- 风化:`spall(pts, depth, impact, age)` 剥落(小贝壳弧唇口、台阶投影、贝壳状波纹、鲜橙石面,带走上面的图);`lichen(x, y, r, kind='green'|'orange'|'grey', n)` 壳状地衣
+- 顺序:rock → ledge → varnish → fracture → 旧图(age 大)→ 新图 → spall → lichen
+- 颜色常量 `STONE SCAR CRUSH VARNISH_FE VARNISH_MN LICHEN`;`stage(name)` 立即合成快照;`save('x.jpg')` 默认 quality 88、4:4:4 色度
+
+**古埃及墓室壁画 `TombPainting`**:
+- 思路:先「声明」整面墙上的东西,再按古代画工的工序一遍遍画:`wall()` 草筋泥上抹一层石膏灰泥 → `grid(box, cell, base)` 红赭石弹线的比例格(一格是人物的一个比例单位,脚底到发际 18 格)、`guide(p0, p1)` 分栏线 → `sketch()` 红稿 → `ground(颜色)` 绕开人物刷底色 → `colour([颜料…])` 一罐颜料画一遍、`ink()` 最后勾线 → `colour(layer='text')`、`ink(layer='text')` 写字 → `age()`。每一层都留在内存里,剥落时按层露出来
+- 部件:`part(pts 或 [多边形…], 颜料, paths=, ink=, width=, z=, alpha=, clip=, layer=)`;颜料名见 `PIGMENTS`(skin 男子红赭、skin_f 女子黄赭、linen、white、yellow 雌黄、blue 埃及蓝、lblue、green、dkgreen、lgreen、red、brown、ochre、black);按逐像素 z 图叠放,所以按颜料分批画也不会叠错;勾线被上层遮住的部分自动不画
+- 人物:`figure(x, 地线y, 身高, pose, facing, sex='m'|'f', wig='short'|'long'|'woman'|'cap', dress='kilt'|'long'|'loin'|'dress', collar)`;`POSES` 有 stand / walk / staff / plough / reap / sow / hoe / glean / carry / hold / scoop / squat,任一关键字都可覆盖(髋 hip、前倾 lean、膝 kf/kb、踝 af/ab、腕 wf/wb、肘弯向 bf/bb、手型 hf/hb、`turn`、脚镜像 `mb`);返回手、腕、肩、耳的画面坐标和 z(`hand_f`、`z_hand_b`…),`S((x, y))` 把比例单位换成画面坐标,用来挂道具
+- 道具:`staff()`、`sickle()`、`hoe(fig)`、`rod()`、`basket(full=)`、`sack(lean=)`、`heap()`、`measure(tilt=)`、`grain_stream()`、`scoop()`、`papyrus()`、`palette()`;拿在手里的东西 z 给 `fig['z_hand_x'] - 0.01`(从拳头后面穿过)
+- 动植物:`ox(x, 地线, 长度, facing, colour, patches)` 长角牛(远侧两条腿错开一步,四条腿都看得见),返回 `poll`(架轭处);`wheat(x0, x1, 地线, 顶, stubble=[(xa, xb)], grab=[(拳x, 拳y, (xa, xb))])` 麦田、留茬和被攥住的麦秆;`sheaf()`、`tree(waterskin=(dx, 长))`、`papyrus_clump()`
+- 边饰:`block_border()` 色块边框、`kheker()` 凯凯尔饰带、`band(x0, x1, y, [(颜料, 高), ('rule', 2), …])` 分栏底带、`river()` 尼罗河
+- 文字:`column(x0, y0, x1, y1, facing, n, seed)` 按方块(quadrat)排一栏伪象形文字(高窄的并排、扁的上下叠);`glyph(名字, x, y, 字号, facing)` 单个符号(`SIGNS` 里 23 个,另有 hoe、stroke、heel、coil);`numerals(12, x, y, 字号)` 象形数字
+- 岁月:`age(losses=[(x, y, rx, ry)], zones=[(x, y, r)], cracks, flake, soot, fade, salt, tide, wear_amt)`:成簇剥落(蓝色和裂缝边先掉)、剥到灰泥露出红格红稿、颜料磨薄、灰泥脱落到草筋泥(断续白边、台阶、投影)、裂缝、埃及蓝发灰绿、顶部烟熏、墙脚潮痕和盐霜、蝇斑、灯光暗角
+- `stage(name)`、`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度
+
+**罗马马赛克 `Mosaic`**:
+- 思路:工匠先画一张谁也看不见的「底稿」(cartoon,平涂和渐变的颜色图),再一块块铺石子:每块石子取自己脚下底稿的平均色,从石料盒 `STONES` 里挑最接近的一种(先比色相再比亮度,带一点抖动,色阶交界像工匠混用两种石子)。石子的排向(andamento)就是画法:每种铺法都沿某个标量场(距离场或坐标)的等值线走一排(marching squares),把一排切成整数块,所以每块略长略短;弯处每块自动成小楔形,急转角处断开换一块;靠近图形脊线的石子停在距离场的脊上,两侧在中线会合。后铺的石子大半压在已铺的上面就不要,压一点就「切掉」并留灰缝(先铺的优先)。渲染是 `ss` 倍超采样的高度场:石面微拱、边缘磨圆(每块石子自己的有符号距离做倒角),灰缝更低、带砂,灰浆床再低;左上方一盏斜光,按材质的漫反射 + 高光,每块石子略有倾斜,所以同色石子明暗不一;石子在灰缝里投影、灰缝有 AO
+- 构造:`Mosaic(W, H, seed, tile=13, gap=1.8, ss=2, light, bed, grout, stones=None)`;tile 是背景石子边长,gap 是灰缝宽(px);图形里用更小的石子(size 约 6–8)
+- 底稿与起稿:`paint(mask, 颜色)`;`shade(mask, c0, c1, p0, p1, gamma)` 线性渐变(鱼背深、肚白);`sinopia(mask=… 或 pts=…)` 在湿灰浆上用赭红起稿,没铺到的地方一直看得见(动画第一帧)
+- 遮罩:`poly_mask(pts)`、`ellipse(cx, cy, rx, ry, rot)`、`rect()`、`band(pts, w0, w1)` 渐细粗线(触手、船尾柱、浪尖);`everything()` 已铺的,`free(region)` 还空着的
+- 铺石子(按调用顺序,先铺的优先,要保持完整的先铺):
+ - `point(x, y, 颜色, size, 'round'|'square'|'tri', angle)`:单块(眼珠、隔字点);
+ - `line(pts, 颜色=None, size, across)`:沿路径一排(字的笔画、鳍线、桅杆、索具、网线);颜色 None 时从底稿取色,做触手的中脊;
+ - `outline(mask, 'black', rows, size)`:图形内侧的第一排深色轮廓;
+ - `fill(mask, size, stones, wrap=True)`:沿轮廓往里一排排铺(opus vermiculatum);wrap 让石子也绕着已铺的眼睛、鳃线一圈圈排;`figure()` = outline + fill;
+ - `halo(region, rows, size, stones, around)`:背景里贴着图形外轮廓的一两圈「光环」;
+ - `rows(region, size, angle, wobble, field, stones)`:背景平铺(opus tessellatum);给 `field`(H×W)就沿它的等值线排,海水用波浪场;
+ - `frame(x0, y0, x1, y1, width, size, stones)`:平行于矩形四边的边框排,转角斜接;带宽取排距的整数倍,黑白镶边就和排对齐;
+ - `tuck(region, size, small)`:剩下的洞用切小的碎石补上,大洞先补
+- 铭文:`letters(文字, x, y, 字高, 颜色)` 罗马大写(A–Y 常用字母,U 写作 V,无 J K W Z),每一笔一排石子,`·` 是三角隔字点;`tabula(x0, y0, x1, y1, [(文字, 字高, 颜色)], ear, frame=('black', 'red'))` 带燕尾耳的铭牌(tabula ansata):字、黑框、红框、白底横排、红耳
+- 岁月(最后做):`lacuna(mask)` 一片石子脱落,露出旧灰浆床和石子留下的方坑;`crack(pts)` 沉降裂缝(穿过石子和灰缝的黑细线,带凹陷);`patina()` 灰缝成片积灰、局部失光
+- 石料:`STONES` 名字 → (颜色, 材质),材质 stone(石灰石,哑光、斑驳、麻点)/ marble(纹理、微光)/ glass(smalti 玻璃,饱和、亮、带气泡)/ terracotta;`stones=[…]` 限定这一步能用的石料(天空只用 white / bone / cream,海只用蓝色玻璃)
+- 工具函数:`edt(mask)` 跳步泛洪欧氏距离场、`iso_lines(f, step)` 一次求出所有等值线、`maxfilt()`;`STONES MATERIALS LETTERS SINOPIA`
+- 动画:`stage(name)` 只记进度,`save(path, stages_dir)` 时按 `stage_ss`(默认 1×)渲染各阶段和收尾帧;`save('x.jpg')` 默认 quality 88、4:4:4 色度
+
+**彩色玻璃花窗 `StainedGlass`**:
+- 思路:照玻璃匠的工序——画稿分块 → 选料切玻璃 → grisaille 彩绘、刮白、银染 → 上铅焊接 → 装铁条 → 从室内看日光透进来。颜色全在玻璃里,颜料只有一种棕黑;铅条落在每两块玻璃的交界上
+- 构造:`StainedGlass(W, H, seed, record=True, ambient=0.05)`;`stage(name, cartoon=False)`(cartoon=True 出纸上的切线画稿);`save(path, stages_dir)`
+- 石墙:`wall(colour, mortar, course, block)` 错缝方石墙(每块石料深浅不同、斜向凿痕、磨损的棱、凹进的灰缝);`lancet(cx, top, bottom, width, arch=1, splay, sill, hood)` 开一个尖拱窗洞,返回 `Light`,带斜面窗侧(拱上是放射状楔石缝)、斜窗台、拱上的滴水线脚;`string_course(y, h)` 腰线
+- `Light`:`pt(lx, ly)` / `P(点列)` 把局部坐标(原点在拱尖,y 向下)换成画面坐标;`inner(b)` 向内缩 b 的窗形遮罩;`band(b0, b1)` 沿窗边的一圈带(边框、白条);`outline(b, step)` 沿窗边取点(给边框切块);`sdf()`;`half(ly, b)` 某高度的半宽
+- 玻璃:`glass(遮罩, 颜色或颜色列表, cell, streak, seeds, thick, vary, flashed, aspect, angle, around, spokes, sites, streak_dir)`。颜色是透光时的样子;给 cell 就按 Voronoi 切块,每块从列表里取一种颜色、深浅厚薄各不相同;sites 按给定点切(边框、长条);aspect / angle 把块拉长;around 绕一点放射切;flashed 是红色套料那种强条纹。后铺的料从先铺的里切出来;太小太窄的碎块自动并进同料的邻块。`cut(点列)` 加一道切线
+- 遮罩:`circle()`、`ellipse()`、`poly()`、`blob()`、`branch(点列, 起宽, 止宽)` 渐细的枝
+- 彩绘:
+ - `trace(点列, width, taper, opacity, clip)` 不透明描线(五官、叶脉、羽毛、细枝),clip 限定只画在某个遮罩里;
+ - `matt(遮罩, strength, soft, stipple)` 半透明晕染,带点彩颗粒;`shade(遮罩, offset, strength, clip)` 背光一侧的月牙形 matt;
+ - `scratch(点列, width)` / `scratch_mask(遮罩)` 用木签刮掉颜料,让光透出来;
+ - `diaper(遮罩, spacing, motif='cross'|'dot'|'ring'|'flake'|'quatrefoil', jitter)` 底纹,默认从一层薄 matt 里刮出,jitter 撒开就是雪花;
+ - `stain(遮罩, strength)` 银染:白料变柠檬黄到琥珀,蓝料变绿;
+ - `inscribe(字, x, y, size, font='lombardic', scratched)` 题字(Luminari / Herculanum,可用 `INKPAINT_FONT_LOMBARDIC` 指定)
+- 上铅与铁件:`lead(width=6, rim=10, solder=True)` 在每条交界上铅(按 H 形铅条打光,焊点更亮更鼓,窗边一圈宽铅);`crack(点列, mend=True)` 裂片和修补用的细铅条,要在 `lead()` 之前;`saddle_bar(light, y, width)` 横铁条(y 是画面坐标),两端插进石头,扎几处铜丝结,要在 `lead()` 之后
+- 光:`weather(grime, pits)` 铅条边和窗下部积灰、部分玻璃的腐蚀麻点;`daylight(strength, spill, halation, sky)` 打开室内光:墙上一层彩色溢光、窗侧斜面靠玻璃处发亮、斜窗台上倒过来的模糊投影、亮玻璃的光晕吃掉一点铅条(蓝色最明显)。`daylight()` 之前墙用固定的中性光,阶段快照之间石墙不变
+- 颜色常量 `RUBY BLUE DEEP_BLUE SKY GREEN LEAF SPRING OLIVE GOLD AMBER ORANGE MURREY WHITE PALE BROWN FLESH`;`save('x.jpg')` 默认 quality 88、4:4:4 色度
+
+**泥金手抄本 `Illuminated`**:
+- 思路:
+ - 按作坊顺序作画:打格 → 抄写(红字和首字母留空)→ 朱笔 → 画图 → 贴金 → 上色 → 勾线;
+ - 字是一支模拟的宽头鹅毛笔写的:笔尖是一段约 40° 斜握的短线段,笔画就是它扫过的面积,所以粗细随行笔方向变;菱形的头脚和发丝般的连笔都来自笔,不来自字体;
+ - 打磨金箔是凸起石膏底上的一面镜子:每个像素按自己的法线(石膏底的鼓面、打孔、金箔接缝、打磨纹)反射相机光线,去查一间左上方有大窗的房间;
+ - 壳金是哑光的颗粒;
+ - 先贴金后上色,后画的颜料和墨会盖住金。
+- 书和皮:
+ - `desk()` 胡桃木书桌;
+ - `codex(x0, y0, x1, y1, cover, squares, stack, dip)` 摊开的书(皮面封板、书口纸叠、页面在书脊处下陷变暗),返回左右两页的矩形;
+ - `flaw(cx, cy, rx, ry, rot)` 羊皮上的天然破洞;
+ - `rule(x0, x1, ys, prick_x)` 针孔、每行 x 高处的打格线、上下贯通的边框竖线;
+ - `show_through(x0, x1, ys, xh, opacity)` 背面的字透过来。
+- 文字:
+ - `column(text, x0, x1, y, xh, leading, indent=[(行数, 左边 x)], align, filler)` 排一栏,返回 Block:
+ - 标记 `*红字*`(留给朱笔)、`^词`(首字母点红)、`¶` 段落符、`|` 段落结束;
+ - 自动长 s / 圆 s、断词加连字号、行尾填充;
+ - `7` 写成提罗速记的 et(⁊),`ꝑ` 是 per。
+ - `scribe(blk, dip)` 抄写黑字:每隔若干字重新蘸墨,铁胆墨由黑变褐,笔画边缘积墨;
+ - `rubricate(blk, blue_first)` 朱红字、首字母点红、红蓝交替的段落符、行尾红锯齿加蓝点;
+ - `write(s, x, y, xh, kind, rot, load)` 写一行,返回行尾 x;
+ - `arc_text(s, cx, cy, r, at, xh, kind)` 沿圆弧书写;
+ - `text_width()` 量宽度;
+ - kind 可选 'iron' / 'red' / 'blue' / 'white' / 'diagram'。
+- 金和颜料:
+ - `gild(mask, cushion)` 红色底料上的凸起打磨金;
+ - `punch(pts, r, depth)` 打孔装饰;
+ - `shell_gold(mask)` 壳金;
+ - `paint(mask, 颜色, mix=(颜色2, 0..1 场), granular)` 蛋彩,边缘积色,石青有颗粒;
+ - `wash(mask, 颜色, opacity)` 透明淡彩;
+ - `pen(paths, width, kind, dash)` 圆头笔线;
+ - `outline(mask, width)` 沿形状描墨边。
+- 遮罩:`mask(polys, lines, dots, holes)`、`circle()`、`ring()`、`ellipse()`、`star()`。
+- 装饰物件(按作坊顺序调用各自的 `.draw()`、`.gild()`、`.paint()`、`.pen()`):
+ - `initial('Q'|'O', x0, y0, size, body)` 历史化首字母:伦巴第体字身配白线描、打孔金底、字腔里的夜景;
+ - `border(path, width, avoid, bounds, seed, every, reach)` 金 / 群青 / 玫瑰色条形边框,递归长出常春藤花枝(金叶、花、金珠、卷须),避开 avoid 矩形;
+ - `versal('O', x, y, size, colour, flourish, reach)` 两行高的分裂伦巴第字配红色花笔;
+ - `astrolabe(cx, cy, R, lat, rete, rule, star)` 星盘;`.pen(labels=[(字, (x, y), (指向的 x, y))])` 加红色标注;
+ - `spheres(cx, cy, R, angles, label_at)` 诸天圆图。
+- 收尾和输出:
+ - `age(foxing, soil, flakes, halo)` 六百年:铁胆墨晕、狐斑、翻页手印、金箔剥落露出红色底料、石青崩口;
+ - `stage(name)`、`save(path, stages_dir)`。
+- 颜色常量 `VELLUM INK RED AZURE ROSE GREEN WHITE SILVER LEAD OCHRE BOLE`;角度逆时针为正;`save('x.jpg')` 默认 quality 88、4:4:4 色度。
+
+**达·芬奇手稿 `Codex`**:
+- 纸:`sheet(tone, mount, margin, laid, chain, lost_corner='br', fold=x, stains=[(x, y, r)], foxing, edges, age)`:裱在卡纸上的帘纹碎布纸(帘纹、链线、纤维、纸齿),自带边缘氧化、缺角、泛黄云斑、霉斑、水渍潮线、可选旧折痕、手翻处的污渍;`show_through(x, y, width, lines)` 背面的字透过纸,左右反过来(所以是正着读的)
+- 铁胆墨水和鹅毛笔:`quill(pts, width, ink)` / `quills([...])`,笔宽随宽笔尖方向变、落笔重收笔尖;笔里的墨会用完:越画越淡,再蘸一次又变浓,偶尔在落笔处积一个小墨珠;`contour(pts, searching=2)` 先轻轻找两三遍再定线(修改痕);`ruled(p0, p1)` 靠尺直线;`dotted(pts, dot_dash=True)` 虚线 / 点划线(轴线);`arrow(pts)`
+- 排线:`hatch(mask, shade, angle=55, spacing, levels=(…), cross=0.76, cross_angle=-38, length, origin, medium='ink'|'chalk')`。55° 是左撇子的「\」;shade 0 亮 1 暗,每多一级 level 就在两线之间再插一层,超过 cross 加一层「/」交叉;按「排」下笔。明暗场:`between(a0, a1, b0, b1)`(从一条线到另一条线 0→1,蒙皮、圆杆)、`radial_shade(cx, cy, r)`;遮罩:`poly_mask(pts)`、`disc_mask(cx, cy, r)`、`Codex.arc(cx, cy, r, a0, a1)` 取弧上的点
+- 红粉笔和铅笔:`sanguine(pts, width, pressure)` / `sanguines([...])` 只挂在纸齿上,`rub(mask, amount)` 用手指揉开;`leadpoint(pts)` 淡灰的铅笔起稿
+- 尖笔和圆规:`incise(pts)` 无色的刻痕(侧光下一边亮一边暗),`compass(cx, cy, r, a0, a1)` 刻圆弧并在圆心留针孔,`prick(x, y)`
+- 常画的东西:`cane(p0, p1, w0, w1, bend, lashings)` 两条线画的藤杆 / 木杆加绑绳,返回轮廓用来挖掉排线;`feather(base, angle, length, width, medium, side, overlapped)` 羽毛(返回轮廓、羽轴、宽羽片外缘);`bird(x, y, size, phase)` 背视的小飞鸟,phase 从 π/2(翅膀最高)到 −π/2(最低)
+- 镜像手写:`write(文本或行列表, x, y, width, size, mirror=True, max_lines)`,mirror 时 x 是右边距、每行从右往左写、左边参差;`prose(n)` 生成意大利语伪文;`label('a', x, y)` 字母标注(`mirror=False` 写正字,如收藏者的页码)
+- 意外:`blot(x, y, r)` 带深色潮线和小溅点的墨点、`spatter(x, y, n)`、`strike(x0, y0, x1, y1)` 划掉废稿
+- 机械零件(笔绘渲染):`Camera(cx, cy, scale, azim, elev)` 正交相机;零件 `gear(r, teeth, depth, h, hub)`、`lantern(r, h, staves)` 灯笼齿轮、`crown(r, h, teeth)` 冠齿轮、`crank(arm, r_axle, handle_len, handle_r)`、`pulley(r, h)`、`cylinder()`、`box()`、`extrude()`;`.place(origin, axis, spin)` 摆放、`.named('wheel')` 命名表面组、`merge(...)` 合成一个网格;`solid(mesh, cam, hatch=dict(...), hatch_groups={'wheel.face': dict(...) 或 None})`:z-buffer 去掉被挡住的线、先擦掉身后的墨、按每个面背光的程度排线、只描轮廓 / 折边 / 开口边并连成长笔画;分解图就是把零件沿轴拉开再画点划线
+- 颜色常量 `INK_DARK INK_LIGHT SANGUINE LEADPOINT PAPER MOUNT`;字体自动找 Apple Chancery / URW Chancery(Linux)/ Segoe Script(Windows),可用 `INKPAINT_FONT_CHANCERY` 指定;`save('x.jpg')` 默认 quality 88、4:4:4 色度
+
+**剪影 `Silhouette`**:
+- 思路:剪影是黑纸用小剪刀剪出来的,贴在象牙白卡纸上,用薄金粉描几笔,装进玻璃椭圆金框挂到墙上。墙纸、金框、玻璃都按真实材料做,左上方一扇窗照亮整面墙
+- 墙:`wallpaper(ground, ink, tint, period, repeat, length)` 木版印花条纹墙纸(刷涂的胶彩底、两块印版、错版、干斑、定位针点、每幅纸对花略错、拼纸接缝);`picture_rail(y, h)` 挂镜线;`chair_rail(y, h, dado)` 护墙线和下面的墙裙
+- 框:`frame(cx, cy, rx, ry, width, pearls, twist, eglomise, card, hook, cord, spread)` 返回 `Frame`。按线脚剖面建高度图(内口圆珠、凹槽、一圈珠饰、大圆脚、平条、外圆边;`twist` 把大圆脚做成绳纹),金面反射房间环境(窗亮、屋暗、地黑),所以出现一圈圈明暗环;有金箔方块接缝,棱顶磨出红色底漆,凹处积灰;墙上有接触阴影和柔影。`hook=True` 从挂镜线铜钩垂下两股丝绳(V 形,伸进框后面);卡纸边缘泛黄、带霉斑;`eglomise` 是玻璃背面的黑底金线圈
+- 剪纸:`sheet(f, at, scale, flip, warp)` 返回 `Sheet`,坐标用设计单位(px = at + scale × 点);`warp` 是一个函数,可以整体改比例(头大一点、身子短一点):
+ - 贴平的主体:`shape(pts)` 主轮廓(只有一丝影子,边缘重采样成一小段一小段剪口)、`disc(x, y, r)`;`hole(pts)` 剪空,露出卡纸(眼睛、腿间、蝴蝶结的缝)
+ - 单独剪下、微微翘起、影子更长的细条:`snip(pts, w0, w1)` 渐细的条(睫毛、胡须、发丝、飘带,宽度可传数组);`line(pts, w)` 等粗的条(缆绳、桅杆);`fringe(pts, n, length, angle, width, side, bend)` 沿曲线一排细丝(鸵鸟羽毛的羽枝、胸前的毛);`scallop(pts, r, outset)` 一排鼓出的小圆(卷发团、帽冠抽褶、收起的帆);`ringlet(x, y, length, width, turns, sway)` 螺旋垂卷,返回中线给金粉用;`lace(pts, depth, step)` 带一排穿孔的蕾丝花边
+- `paste(sheet)` 把剪好的纸贴到卡纸上:4× 超采样再缩小,1 px 的细丝也留得住;黑纸带纤维和光泽,朝光的剪边有一道细亮线
+- `bronze(sheet, strokes, width, tip, bright)` 薄金粉:每笔渐细、亮度各不相同、带颗粒,只留在黑纸上
+- 字:`caption(f, 文字, x, y, size, style='roundhand'|'italic')` 铁胆墨手写题签(`sil_font` 找 Snell Roundhand / Baskerville Italic,可用 `INKPAINT_FONT_ROUNDHAND`、`INKPAINT_FONT_ITALIC` 指定);`pen(f, pts)` 墨线
+- `glaze()` 装上玻璃:凸面玻璃的柔光和窗户倒影;`smooth(pts, per, closed)` 闭合或开放的 Catmull-Rom 曲线
+- `stage(name)`、`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度
+
+**凸版印刷海报 `Letterpress`**:
+- 思路:每种油墨一块版(forme),先把要印这个颜色的东西都「锁」进版里,`press(ink)` 一次压印。每过一次机器纸张落得不一样:每块版有自己的平移和极小旋转(`register(ink, dx, dy, rot)`),红版和黑版永远对不齐。先红后黑
+- 纸:`paper(colour, warm, tone)`:已经泛黄的廉价海报纸(云状纸浆、短纤维、杂点、纸齿、微微不平)
+- 版:`lock(mask, ink, film)` 锁进任意遮罩;`clear(mask, ink, keep)` 刻掉(木刻高光、前后遮挡);`with lp.layer('key'):` 把东西锁进版的某一部分,`press(ink, only=['key'])` 只压这一部分(阶段动图先出轮廓线、再出排线);`press(ink, density)`:边缘随纸齿参差、边上积一圈深墨、大实地缺墨发花并露出纸齿白点、灰尘留下圆形漏印;黑压红更深
+- 木活字:`type_line(s, x0, x1, base, cap, face, ink, align='justify', stretch, track, shade=(dx, dy, 另一版颜色, gap), inline=(inset, width), wear, grain, limits)`:默认把一行排满版心(字面横向压扁或拉宽、再加字距),每个字是一块木头:木纹条痕、一端偏浅、凹坑软斑、边角缺口、偶尔一道顺纹裂缝;shade 是印在另一块版上的投影,inline 是笔画中间刻一道白线。face 用 clarendon / antique / gothic / fatface / cjk(宋体黑);`type_width()` 量宽度
+- 铅字与花饰:`text(s, x, y, size, face='roman'|'roman_bold'|'italic'|…, ink, anchor, spacing, rot, stretch)`、`text_mask()`、`text_width()`;`rule(x0, x1, y, kind='single'|'double'|'thick_thin'|'thin_thick'|'dotted', ink, weight, joints)` 铜线(长线由几段拼成,接头有细缝和 1 像素错位);`leaders()` 引线点;`star()`;`ornament(字符, ...)` 花饰字体(缺字体时画星);`border()` 粗细双线框加方角
+- 形状(整页浮点遮罩,可加减乘):`shape(控制点)` 平滑闭合曲线、`poly()` 直边多边形、`tube(点列, widths=[...])` 变粗细的管子(腿、鼻、尾、绳)、`ellipse(cx, cy, rx, ry, rot, a0, a1)`、`rect()`、`outline_pts()`
+- 木刻:`key(mask, width, heavy)` 轮廓线刻在形状内侧、背光一侧加粗;`hatch(mask, angle 或 centre+aspect, spacing, tone, lo, gain, wobble)` 线宽随明暗变化的排线,tone 低于 lo 处收尖消失、高处并成实地;`form_tone(mask, soft)` 把遮罩当成鼓起的体积打光得到 tone;`ramp(p0, p1)` 线性渐变 tone;`cast(mask, dx, dy, onto)` 投影;`line(pts, width, taper)` 两头收尖的刻线(皱纹、绳子);`solid()`;`stipple(mask, density, size, tone)` 点刻;`tint(mask, ink=RED, loose, grow)` 另刻的套色块,边缘游走、比轮廓略胖
+- 印后:`fold('v'|'h', pos, depth, crack)` 折痕(油墨裂开、积灰、两侧受光不同);`tone_edges()` 边缘泛黄;`foxing(n)` 霉斑;`stain()` 水渍;`tack(x, y, r)` 钉孔和锈斑;`nicks(n, size)` 纸边缺口;`strip(x0, y0, x1, y1, rot, colour, draw=fn)` 另印一条日期条贴上去(fn 拿到一个小 Letterpress 往上排字,周围有浆糊印)
+- 颜色常量 `RED BLACK PAPER`;`save('x.jpg')` 默认 quality 88、4:4:4 色度
+
+**苏联构成主义 `Constructivism`**:
+- 思路:一张纸、两块版。红的都在红版上,黑的(色块、字、每张照片的每个网点)都在黑版上。画东西就是「把遮罩印到某块版上」或「从某几块版上挖掉、露出纸」。合成时每块版整体带一个套准误差(平移加极小旋转),所以红黑相接处一边露纸、一边叠出深色。墨是透明滤色,相乘叠印,黑压红是暖黑
+- 构造:`Constructivism(W, H, seed, misreg=2.4, red=RED, black=BLACK)`
+- 纸:`paper(colour, aged, yellow)`:便宜的奶油色海报纸(云状纸浆、纤维、纸屑、微微不平、边缘发黄)
+- 遮罩(全画布、抗锯齿,可加减):`circle()`、`ring()`、`arc(cx, cy, r, a0, a1, width)`、`sector()`、`rect(x0, y0, x1, y1, rot)`、`bar(x0, y0, x1, y1, width)` 斜条或细线、`wedge(apex, angle, half, length)` 楔形、`poly()`;`along(p, angle, d, side)`:从 p 沿某个角度走 d、再往左偏 side,用来摆斜排的字和标注
+- 印:
+ - `ink(mask, 'red'|'black', knock=, density)`:印一版,knock 是从这块色里挖掉的字;
+ - `knock(mask, plates)`:从这几块版上挖空;
+ - `tint(mask, plate, level, cell, angle)`:平网;
+ - `waves(cx, cy, r0, r1, step, width, a0, a1, plates, grow)`:限定角度内的同心波前,grow 为负时越传越细
+- 字:`text(s, x, y, size, plate, font_style='grotesk'|'din'|'narrow'|'futura', anchor, spacing, rot, wobble, scale_x, knock)`;`text_mask()` 用来反白;`text_width()` 量宽度。grotesk 是 Helvetica Neue Condensed Black(退回 Impact / DejaVu Sans Condensed Bold),din 是 DIN Condensed(退回 Arial Narrow / PT Sans Narrow);缺西里尔字形的字体自动跳过;`wobble` 给大字一点手绘的抖动
+- 照片 `Photo(w, h, eye, target, fov, ss, key, fill, haze, shift, ...)`:小型透视 z-buffer 光栅器,单位米,Z 朝上:
+ - `material(albedo, gloss, shine, metal, tex, interior)` 返回材质号,tex 是按世界坐标算的程序纹理(木纹、刻度、线圈绕线);
+ - `cylinder()`、`lathe(base, axis, [(t, r), ...])` 旋转体、`sweep(path, radii)` 变径管(鹅颈、喇叭、软线)、`box()`、`hyperboloid(z0, z1, r0, r1, n, twist, mid)` 双曲面网格塔的一节;
+ - `project()` 把世界坐标点换成照片像素,用来让海报上的其他元素对准照片里的东西(如楔形对准喇叭口);
+ - `render()` 只调一次:只给有物体的像素着色,渲染后释放缓冲
+- 拼贴:`montage(photo, cx, cy, rot, scale, plate, cut, close, backdrop, cell, angle, contrast, soften)`:缩放、旋转、放上去,再在海报坐标里统一加 45° 网点(所有照片共用一张网)。
+ - `cut=` 沿轮廓留边剪下:盖住下面已印的东西,露出纸色白边和背景的高光小点;
+ - `close=` 桥接剪刀剪不进的窄缝;
+ - 不给 cut 就是去了底的照片,网点直接叠印在红色上;
+ - `soften` 是加网前的模糊(单位:网格),网格塔这类细杆用 0.12
+- 做旧:`age(folds=(竖, 横), foxing, stain, pins, crack, grime)`:折痕裂墨与磨损、霉斑、水渍潮线、磨旧的角、图钉锈孔
+- 顺序:paper → 红版色块(圆、楔形、色块)→ 黑色波线、斜条(`knock` 掉下面的红)→ 照片 → 字和标注 → age
+- 颜色常量 `RED BLACK PAPER AGED`;角度逆时针为正,0° 指 3 点钟;`stage(name)` 立即合成快照;`save('x.jpg')` 默认 quality 88、4:4:4 色度
+
+**装饰艺术 `ArtDeco`**:
+- 思路:画家不画线。每个形状都是一张用刀刻出来的遮片(frisket),盖在板上用喷枪喷色,所以边缘锐利、里面是一段平滑渐变;形体只靠明暗:楼是一张平剪影、一侧喷暗一侧喷亮,圆柱体上肩一道高光、下腹一条反光
+- 喷枪:`spray(mask, 颜色或整幅颜色场, density, grain, blend='paint'|'screen'|'add')` 一次喷涂;薄涂处有雾滴颗粒(固定噪声 × d(1−d)),实涂处没有;`fade(mask, stops, p0, p1)` 线性渐变,`glow(cx, cy, r, 颜色)` 径向光晕;遮片 `rect()`、`poly()`、`disc()`(都抗锯齿);`ramp(t, stops)` 色阶
+- 天空:`sky(stops, top, bottom)` 长渐变;`burst(cx, cy, rays, contrast, reach, colour, dark, glow, phase, taper, bottom)` 明暗交替射线(亮楔靠近中心略宽,对比随距离衰减,bottom 处截止);`moon(cx, cy, r)` 偏心径向渐变的球形月亮、光晕、柔边月海;`searchlight(x, y, angle, length, spread)` 探照灯光束
+- 城市:`tower(x, base, [(宽, 高), ...], body, rim, light=±1, flutes, windows, slits, far, spire, spire_w, mast, ledge, top_windows)` 阶梯退台高楼,返回顶层顶部中心;`far` 0..1 推进雾里(变浅变蓝变平);`crown(x, y, w, steps)` 扇形阶梯冠顶(放射窗),返回顶点 y;`clock(cx, cy, r, 时, 分)` 钟面
+- 河:`water(horizon, stops, reflect)` 先喷河面渐变,再把地平线以上已经画好的东西镜像进来,打碎成横向波纹,亮的东西反射更强
+- 3D 列车:`camera(f, cx, horizon, height)` 水平针孔相机;`express(nose=(X, Z), vp_x, deck, cars, loco, car, gap, nose_len, rake, light, moon)` 在拱桥上渲染流线型列车(距离场 + numpy 球面步进,只对边缘像素 3×3 超采样),返回分层结果 `r`;按画家的顺序叠上去:`frisket(r)` 遮片平涂底色 → `model(r)` 明暗塑形(半朗伯色阶、上肩喷枪高光带、月光轮廓光、下腹反光、远处雾色)→ `lights(r, beam, beam_len, bloom, reflect)` 车窗(卧铺窗帘拉下一半)、头灯、光束、辉光、灯照铁轨、可选的河面倒影;`project(X, Y, Z)` 世界坐标转像素
+- 字:`lettering(s, x, base, cap, fill, track, shadow, anchor)` 库内自建的 Deco 展示字母 A–Z(粗竖笔、发丝横笔、高腰线、椭圆字碗),金属渐变填色(中线一道硬分界),可加块状投影;`deco_width()` 量宽度;`caption(s, x, y, size, colour, track, anchor)` 宽字距几何无衬线小字(返回宽度);`rule()` 金线;`border(inset, gap, width, step)` 阶梯角双金线边框
+- 印刷:`finish(paper, tooth, warm, vignette)` 纸纹、微颗粒、暖色偏、轻微暗角
+- 颜色常量 `NAVY MIDNIGHT TEAL JADE GOLD BRASS IVORY CREAM MAROON CRIMSON WARM`;坐标像素、y 向下,3D 世界单位米、y 向上;`save('x.jpg')` 默认 quality 88、4:4:4 色度
+
+**黄金时代漫画 `ComicCover`**:
+- 思路:先按当年的分工把封面「做」出来,再按当年的印法「印」出来。墨线师在黑版上勾 key 线;上色师在色稿上给每块区域指定三原色的 Ben-Day 网点比例(0 / 20 / 40 / 70 / 100%),整张封面只有几十种颜色;印刷时每版按自己的角度加网、各自错开几像素,新闻纸吸墨让网点变毛、小点丢失、实地发花;油墨透明相乘。网点和错版都不手画
+- 构造:`ComicCover(W, H, seed, screen=11, misreg=4, slop=1.6, light=(-0.6, -0.8))`:screen 是网点间距(px),misreg 是各色版的错位量,slop 是手绘分色的游走量;`register(plate, dx, dy, rot)` 手动指定某版的落点
+- 纸:`paper(colour, tone, fibres, flecks)` 泛黄新闻纸(云状纸浆、深浅短纤维、树皮屑、不吃墨的纸坑)
+- 形状(整页抗锯齿遮罩,可加减乘):`mask(pts, smooth)`、`circle()`;静态方法 `ellipse_pts()`、`smooth()`(闭合样条)、`tube_pts(路径, 宽度列表)`(四肢、绳子、围巾、耳朵)、`burst_pts()`(星星、爆炸框)、`edge_normals(pts)`(轮廓点和外法线,给 `feather` 用);`grow()` / `shrink()`
+- 色稿:`flat(shape, 颜色)`,颜色是 (蓝, 红, 黄, 黑) 四个网点比例;`graded(shape, [颜色…], p0, p1, edges=[…])` 沿手裁波浪边分档的色带;`rings()` 同心色环;`knock()` 挖白
+- 黑版:`part(pts, 颜色, width, heavy)` 是放前景物件的标准做法:擦掉身后的墨线和颜色、铺色、勾一圈背光侧加粗的轮廓;`brush(pts, width, taper, swell)` 两头尖、中段鼓的毛笔线;`pen()` 细笔;`outline()` / `edge()` 闭合 / 开放轮廓;`ink()` 实黑块;`erase()`;`mask_outline(mask, width, heavy)` 给任意遮罩(圆的并集、字)描边;`feather(P, N, length, width, spacing, clip, along, toward, curl)` 从阴影边长出来的羽状排线;`hatch()` 平行排线;`speed()` 速度线;`dot()`
+- 字:`letter(text, x, y, size, face, colour)` 手写字,逐字微转、微跳(face:letter 漫画手写体 / logo 窄粗体 / bold / slab / heavy);`text_mask()`;`balloon(text, x, y, size, tail, kind='speech'|'yell'|'thought')` 对白框 / 喊叫爆炸框 / 想法云;`caption(x0, y0, x1, y1, text, colour)` 旁白框;`sfx(text, x, y, size, colour, rot, shade)` 拟声字;`logo(text, quad, vp, depth, colours, shade, shadow, glints)` 透视立体刊名:四个角点定透视,朝灭点挤出 depth 像素,正面上浅下深分档,加挤出面、投影、粗黑外框和高光斜纹
+- 做旧(印完以后再加,只作用在各自区域):`brown_edges()` 边缘泛黄;`spine(ticks, staples)` 书脊折痕、白色应力裂纹、两枚生锈订书钉;`corner('br', radius)` 角上磨掉油墨、折角;`crease(p0, p1)` 折痕处油墨裂开露白;`foxing(n)` 霉斑
+- 阶段:`stage(name, plates='CMYK')` 记下当时的各版,出图时只印列出的版:先用 'K' 出黑版线稿,再依次 'YK'、'YMK'、'CMYK',就是印刷厂的「渐进打样」
+- 颜色常量(色稿比例):`WHITE CREAM PALE YELLOW GOLD ORANGE DEEP_ORANGE RED CRIMSON PINK SKIN TAN BROWN DARK_BROWN SKY LIGHT_BLUE BLUE NAVY VIOLET MAUVE LILAC GREEN LIME GREY LIGHT_GREY SILVER`;油墨颜色 `INK`;`save('x.jpg')` 默认 quality 88、4:4:4 色度
+
+**波普丝网 `PopSilkscreen`**:
+- 思路:重做 60 年代「工厂」的做法。一张照片做成黑色照相丝网版;一张画布用胶带隔出几格,每格先手涂撞色平涂(底色,再是脸、眼、鼻、项圈……),形状照着照片描得很松、对不准;然后把同一块黑版逐格刮印上去,每格放版的位置、角度和墨量都不同
+- 构造:`PopSilkscreen(W, H, seed, light=(-0.55, -0.8))`;`canvas(gesso, thread=3.8, slub=0.18)`:刷了白底漆的棉帆布(平纹布纹高度场、粗节、均匀布光)
+- 分格:`grid(cols, rows, gap, margin, origin=(0.5, 0.53), unit=0.285)` 返回 `Panel` 列表。每格里用「单位」作画:origin 是单位原点在格内的位置(宽、高的比例),unit 是每单位占格高的比例
+- `Panel` 上取遮罩(局部窗口,四周留 pad 像素,方便渗边和错位):
+ - `shape(pts)`:闭合样条
+ - `stroke(pts, w0, w1, profile=)`:渐细笔画,宽度用单位;`profile(t)` 自定粗细
+ - `ellipse(u, v, ru, rv, rot)`、`dots([(u, v, r)])`
+ - `soft(mask, sigma)`:柔化成给网点用的调子;`blank()`
+ - 坐标换算:`at(u, v)` 单位 → 局部像素,`xy(u, v)` 单位 → 画布像素
+ - 模块函数:`turn(pts, deg, about)` 屏幕上逆时针转(歪头用)、`mirror(pts)` 左右镜像、`closed_spline()`
+- 手涂丙烯:
+ - `ground(p, 颜色, direction, bleed)`:一格的底色,刷到胶带为止,有几处渗进胶带下的毛边
+ - `paint(p, mask, 颜色, direction, wobble, drift, opacity, dry, streak)`:手涂一块平涂色。wobble 是边缘手抖(px),drift 是这块颜色描偏了多少(px);顺笔方向有轻微明暗,边缘有干笔拖痕和一道受光的漆脊;只涂在本格里
+- 黑版 `key(p, solid, tone, ink, shift, rot, density, flood, starve, pull, nicks, ghost, cell, angle)`,返回印上的覆盖率:
+ - solid 是实黑的阴影块;tone 是中间调,印成 45° 粗网点(cell 约 7 px);照相阈值的颗粒边和膜上的灰尘点自动加;`stencil()` 可以单独取照相版遮罩
+ - shift、rot:这一格放版的偏移(px)和转角(度)
+ - density:墨量,0.92 缺墨、1.0 正常、1.15 墨多,低于约 0.9 就印不出脸
+ - flood:墨多糊版,形状变胖、细缝填死、挤出墨团
+ - starve:干在网上的一块墨斑;pull:刮板方向(90 自上而下,0 自左向右);nicks:刮板缺口留下的细白线
+ - ghost=(dx, dy, 强度):版放了两次,留下一层灰影
+- `stage(name)`、`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度
+- 颜色常量(60 年代丙烯撞色):`HOT_PINK PINK BLUSH RED ORANGE TANGERINE LEMON YELLOW CREAM LIME GREEN MINT TURQUOISE SKY BLUE ULTRA VIOLET LILAC WHITE`,底漆 `GESSO`,黑墨 `INK`
+
+**ASCII 字符画(行式打印机) `LinePrinter`**:
+- 思路:画面不直接画在纸上,而是画进一张隐藏的「角色图」(每个字符格 6×10 个采样):每块区域带一个角色(用哪套字符)和一个调子(要多少墨),后画的盖住先画的;`compose()` 再逐格决定打哪个字:线条格按线的方向和在格里的位置选 \| / \\ _ - . ' X +,剪影转折处同样处理,填色格按调子从角色的字符阶梯里选(同角色内误差扩散),最暗的格用叠打。最后模拟鼓式行式打印机逐行击打
+- 构造:`LinePrinter(W, H, seed, cols=132, top=40, cpi=10, lpi=6, form_in=14.875, ss=2, weight='bold', ppi=None, page_in=11.0)`;`top` 是撕线的位置,`ppi=None` 让纸宽撑满画面,调小就整张纸躺在桌上、左右露出桌面;`page_in` 是纸深(11 英寸 66 行,8.5 英寸 51 行,配合 ppi 能让上下两道撕线都入画),`page_rows` 是一页的行数;`rows` 是看得见的行数,坐标一律用(列, 行),可以是小数;`xy(col, row)` / `centre(col, row)` 换算成像素
+- 纸:`form(white, green, desk, band=3, first_green, holes)`:14 7/8 英寸宽的绿条连续纸,每 3 行一条浅绿带,两侧导孔(孔里看得到桌面和纸的投影,偶有被拉长的破孔)、微孔撕线、每 `page_rows` 行一道横向撕线和折痕;纸比画面窄时两侧是桌面和纸的投影。要留页边就在 `compose()` 前 `erase(rect(0, page_rows − 2, cols, rows))`
+- 角色:`role(name, ramp, edge='outer'|'all'|None, outline='straight'|'round'|dict, dither, noise, group, inner_max)`;ramp 从浅到深,如 `['', '.', ':', '%', '@', '#', '#@']`,`'#@'` 表示 # 上再叠打 @;`group` 相同的角色之间不描边;`inner_max` 只在亮处给同角色的块与块之间描边
+- 形状(子格遮罩):`circle(col, row, 半径列数)`(自动按格子比例变圆)、`ellipse()`、`poly(点列)`、`shape(控制点)` 平滑闭合曲线、`rect()`、`blob()`
+- 调子:`sphere_tone(col, row, r, light, amb)` 球(烟团)、`cylinder_tone(c0, c1, light, amb)` 竖圆柱(箭身)、`ramp_tone(p0, p1, t0, t1)` 线性渐变
+- 作画:`fill(mask, role, tone)`;`erase(mask)` 挖回白纸;`stroke(点列, width, glyphs=None|'round'|单个字符, smooth)` 画线(单个字符如 `'='` 强制用它,平台、横梁用);`billow([(col, row, r), ...], role, light, amb, shadow, glow=(col, row, r, 强度), lift=调子场)` 一团云:每团按球打光、给身后的云团投接触阴影,glow 是火焰从里面照亮,lift 给云底加暗
+- 文字:`text(s, col, row, strike=2)` 原样打字(strike=2 两次叠打成粗体,opaque 让空格挖掉底下的画)、`text_v()` 竖排;`plot(col, row, w, h, xlim, ylim, [(xs, ys, 字符), ...], xticks, yticks)` 打印机绘图(I 纵轴、- 横轴、+ 刻度),返回把数据坐标换成格子坐标的函数(好在上面圈点)
+- 打印:`compose()` 出字符网格(`listing(path)` 存成纯文本);`print_rows(r0, r1)` 逐行击打(同一行所有叠打在走纸前打完):同一个字符总是偏高或偏低一点(鼓的相位)、每列锤子力度不同(有一两列弱锤)、叠打的那一遍整行错开零点几像素、色带随作业变淡并沿宽度磨损、偶有色带偏低的行字头发虚、磨损的字模每次都缺同一块、墨往纸里洇、锤子压出极浅的凹痕
+- 批注:`pen(点列, colour, width)` 圆珠笔(起落笔略积墨、快处变淡、在纸纹上断续)、`ring(x, y, rx, ry)` 顺手画的不闭合圈、`tick(x, y, size)` 打勾、`pen_text(s, x, y, size)` 手写字;这些用像素坐标
+- 层次与动画:先 `fill`/`stroke`/`text` 摆完整张画,再 `compose()`,然后分几段 `print_rows` 并各 `stage(name)`,就是一行行打出来的动画;`save('x.jpg')` 默认 quality 88、4:4:4 色度
+- 颜色常量 `INK`;`save(path, stages_dir)` 时按 1× 输出各阶段
+
+**低多边形 `LowPoly`**:
+- 思路:一个只用 numpy 写的软件光栅化器,照 1999 年代主机的做法画:小帧缓冲(默认 384×216)、顶点吸附到整像素、背面剔除、整个场景的三角形按平均深度排成一张表从远到近画(画家算法 / ordering table)、近平面裁剪;每个三角形一个颜色(平面着色),贴图仿射插值、不做透视校正,逐顶点雾;最后 15 位色加 4×4 有序抖动,最近邻放大。调用顺序不影响遮挡
+- 构造:`LowPoly(W, H, scale=5, seed, record=True, zbuffer=False, near=0.6, far=260)`;世界坐标 X 右、Y 上、Z 向前,单位米;`zbuffer=True` 是 N64 式逐像素深度
+- 相机:`camera(eye, target 或 yaw=, pitch=, fov, roll)`;`aim(世界点, at=(fx, fy))` 转动相机让这个点落在画面的指定比例位置(构图用);`project(p)`、`ray(sx, sy)`
+- 天与光:`sky(zenith, horizon, glow, bands)` 按仰角渐变、太阳周围暖光晕、可选细条云;`sun(screen=(fx, fy) 或 direction=)` 画太阳并定光照方向;`light(lift=度)` 着色光单独抬高;`ambient(sky, ground)` 半球环境光;`fog(near, far)` 逐顶点雾,颜色默认等于地平线
+- 地形:`path([(x, z), ...])` 中心线,`along(path, s, u, y)` 取点、`heading(path, s)` 取方向;`canyon(path, step, height, width, wobble, strata, buried)` 沿中心线放样的峡谷(河床、沙岸、碎石坡、两级悬崖和台阶、崖顶、台地;岩壁按高度贴岩层,平面俯贴沙地 / 灌丛);`river(path, half, ripple, spec)` 起伏小面的河;`mesa(x, z, r, h, base)` 方山;`arch(path, s, span, rise, base)` 天然石拱;`boulder(x, y, z, r)`;`tree(x, y, z, height)` 十字插片杜松(贴图 alpha 硬裁切)
+- 物件:`ring(centre, facing, radius, tube)` 多面金环;`aircraft(pos, heading, roll, pitch, size, body, trim, canopy, spinner)` 约 230 个三角形的小特技飞机加半透明螺旋桨盘;`torus()`;`mesh(V, F, colour, uv, tex, lit, spec, shine, blend, alpha, two_sided, fog, bias, cutout, glow)` 任意网格:blend 用 'opaque' | 'half' | 'add' | 'sub' | 'quarter'(当年的四种半透明模式),bias 是排序偏置(负数后画),glow 把面往全亮拉(拾取物)
+- 特效:`shadow(x, z, y, radius)` 正下方的圆斑影子('sub' 混合);`sparkle(p, size)` 加色四角星;`flare()` 屏幕空间镜头光晕(太阳被挡住就不画)
+- 贴图:`texture('strata'|'ledge'|'sand'|'water'|'rock'|'juniper'|'spark')` 32–64 像素的程序贴图,最近邻取样
+- HUD(帧缓冲像素坐标):`text(s, x, y, scale, fill=颜色或自上而下的渐变列表, italic, anchor)` 5×7 点阵字(加粗、斜切、1 px 黑描边加投影);`counter(label, value, x, y, icon, anchor)` 小标签加大号斜体数字;`icon('ring'|'plane'|'clock')`;`gauge(x, y, value, number, unit)` 阶梯速度条;`panel()` 半透明框;`minimap(x0, y0, x1, y1, path, s0, s1, rings, done, plane, heading, finish, title)` 转到机头朝上的赛道小地图
+- 动画:`stage(name)`;`stage(name, wire=True)` 隐藏线线框;`stage(name, fog=False, textures=False)` 平面着色预览(每个面取中心那个纹素)
+- 颜色常量 `GOLD WHITE BLACK HUD_YELLOW HUD_ORANGE HUD_RED HUD_GREEN HUD_CYAN`;`save('x.jpg')` 默认 quality 88、4:4:4 色度
+
+**喷漆模板涂鸦 `Stencil`**:
+- 思路:一面真的墙,一张张真的卡纸模板,一罐喷漆。墙是反照率加高度图、左上方一个低太阳照亮;模板是卡纸上刻开的洞,被刻断的卡纸(O 的中间、手臂和身体之间、轮辐之间)会掉,所以要留「桥」,桥在漆上是一道道露墙的细缝;喷漆是罐子来回扫,每扫一道落下一个高斯锥,漆膜就是这些笔画的和;漆是一颗颗雾滴,厚的地方连成实色,薄的地方是散点,所以所有软边都是麻点而不是模糊;漆盖不进小孔、贴着墙面起伏、带缎面光泽;漆太厚的下边缘会往下流成滴痕
+- 墙:`wall(colour, planks, ties, ground, damp, crack)` 木纹模板清水混凝土:一条条木板压出的色带和木纹(绕着树节走)、板头接缝、板缝挤出的断续水泥浆棱、对拉螺栓孔(锈铁头 / 灰浆堵头 / 空孔)、气泡孔、雨痕和锈水、返潮水线与泛碱、发丝裂缝;`pavement(colour)` 墙脚的沥青人行道(骨料、补缝沥青、口香糖渍、油渍、墙脚灰土和杂草)
+- 旧痕迹:`buff(x0, y0, x1, y1, colour, roller, ragged)` 市政灰漆滚筒覆盖(竖向滚道、台阶状上下边、发干的两头、重叠处偏深,底下的东西透一点出来);`freehand(..., wash=0.7)` 被高压水枪冲掉一半的旧签名
+- 模板:`card(x0, y0, x1, y1, origin, scale, tape, material='manila'|'board')` 返回 `Card`,形状用设计单位(px = origin + scale × 点),返回局部遮罩,可以用 numpy 相加相减:
+ - `poly(pts, smooth, facet)`(facet 是刀沿曲线一小段一小段切的抖动)、`capsule(p0, p1, r0, r1)`、`ellipse(c, rx, ry, rot)`、`ring(c, 外, 内)`、`stroke(pts, w0, w1)` 渐变宽度的带子
+ - `text(s, x, y, size, font='stencil'|'slab'|'block', anchor, spacing, bridge)` 模板字:每个字腔自动上下各一座桥
+ - `cut(mask)` 刻开;`keep(mask)` 留住卡纸(反白字、细节);`bridge(p0, p1, width)` 手放一座桥;`bridges(width)` 自动找出所有会掉的孤岛、补最短的桥(大孤岛两座、方向相反);`islands()` 还剩多少像素的卡纸会掉(0 才算刻好)
+- 明暗分版:`shade_side(mask, light, depth, soft, wobble, seed)` 背光一侧 depth 像素宽的月牙,多层模板的灰版、黑版用它切;wobble 让边像手刻的
+- 喷:`spray(card, colour, coats, cone, angle, misreg, at, rot, lift, mist, drips, drip_len, wet, linger, ghost)`。cone 是喷幅(像素);misreg 是贴歪的随机误差(多版套色用约 2);at / rot 把同一张小模板挪到别处、转个角度再喷(燕子、树叶、蝴蝶结);lift 卡纸翘起量(软边和渗漆);mist 外溢雾化;drips 滴痕多少,wet 起滴的漆膜厚度
+- 徒手:`freehand(pts, colour, width, coats, speed, spits, drips, mist, wash)` 细喷嘴:线宽和浓淡跟着手速(speed 每个控制点一个系数,慢 = 重),起笔一团、停顿处滴、旁边几颗喷嘴吐出的大漆点
+- `stage(name, card=c)` 快照里模板还贴在墙上(胶带、卡纸上积的漆、切口一侧亮一侧暗、卡纸投影),动图用;`save(path, stages_dir)` 默认 quality 88、4:4:4 色度
+- 颜色常量 `BLACK WHITE GREY RED CONCRETE`;`HIDE` 各色遮盖力(白最差),`GLOSS` 光泽;字体 `stencil_font(style, size)` 找 DIN Condensed Bold / Impact、Rockwell、Arial Black,可用 `INKPAINT_FONT_STENCIL` 等指定
+
+**刺绣徽章 `Patch`**:
+- 思路:像绣花机那样绣:每块形状按自己的针向切成平行的行(扫描线),每行再切成针,所以形状的边缘就是一排针脚。每根线按圆柱打光,两头扎进布里(针孔是小凹坑),高光是各向异性的(Kajiya-Kay),同一种颜色换个针向亮度就不同,这正是「绣出来」而不是「印出来」的关键。徽章先是一块裁好的斜纹底布放在牛仔布上(有厚度、有投影),再绣、再包边,最后手缝上去
+- 牛仔布:`denim(colour, weft, warp_px, pick_px, fade)` 3/1 右斜纹(经密纬疏,斜纹约 60°,露白纬点、竹节纱、磨白),2× 渲染;`seam(pts, thread, rows, stitch, gap, fold)` 双明线的折边缝,折棱磨白
+- 底布:`blank(pts, 颜色)` 返回 `Blank`(`.pts` 轮廓、`.mask` 遮罩);轮廓:`circle_pts(cx, cy, r)`、`arch_pts(cx, top, w, h, corner)` 拱形异形章、`rocker_pts(cx, cy, r0, r1, span, centre)` 弧形条章;遮罩:`circle()`、`ring()`、`poly(pts, smooth)`、`text_mask()`,用 `*`、`np.maximum`、`1 - m` 组合
+- 填充:`fill(mask, 颜色, angle, kind='tatami'|'satin', pitch, length, stagger, maxlen)`:tatami 是大面积底色(短针约 15 px,每行错开 0.3 针);satin 一行一根长线(字、雪顶、火焰、细长形),超过 maxlen 自动拆成交错的分段缎面;angle 是针向(度,逆时针,0 = 左右走)
+- 沿路径:`column(pts, 颜色, width, closed)` 缎面柱,针和路径垂直(圆环分隔线、木柴、帐篷杆);`run(pts, 颜色, stitch, gap, width, clip=)` 平针 / 刺子绣虚线 / 明线;`knot(x, y, 颜色, r)` 法式结(星点、火星);`star(x, y, r, 颜色)` 四角缎面小星
+- 包边:`merrow(blank, 颜色, width)` 锁边:斜着一圈圈绕过布边的圆绳,用于圆、椭圆、弧形条章;`satin_border(blank, 颜色, width)` 热切缎面边,用于其他异形轮廓
+- 字:`text(s, x, y, size, 颜色)`、`arc_text(s, cx, cy, r, size, 颜色, centre=90, bottom=False)` 缎面字,每个字母斜着走针;bottom=True 沿下弧读、字头朝里
+- 手缝:`whip(blank, 颜色, frm, to)` 卷边针,按轮廓长度的比例缝一段,返回最后一针的位置;`thread(pts, 颜色, lift)` 散落的缝线(有捻度,抬起越高影子越远);`needle(eye, tip)` 躺在布上的钢针(先画线:线会从针眼里露出来)
+- `stage(name)`、`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度
+
**顺序**:都是先远后近、先大后小,文字最后叠加。水墨的雾要画在它该吞没的东西之后;水彩的叶梗要先画,并且只画在叶子外面。
## 三、毛病清单(都真实出现过)
@@ -687,6 +994,309 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask
| 熨烫纸盖住标签,字变半透明 | 后放的会盖住先放的,用 `on_top()` 把标签、杯垫提到最上层 |
| 图例铅笔勾挤到前一栏数量上;深绿、叶绿都印成 G | 勾直接打在豆子图标上;符号原样印,不转大写 |
+**岩画(凿刻砂岩)**
+
+| 问题 | 改法 |
+|---|---|
+| 沙漠漆像木纹、像一整幅竖条窗帘 | 不用全幅竖条噪声;漆膜近乎均匀(0.86 ± 0.09),流痕是一条条独立的对象:多从顶部起、往下变窄变淡、略左右漂移,边缘 ±2.5 px |
+| 流痕像条形码(硬顶的黑色矩形) | 流痕顶端 50 px 渐入、长度 30%–100% 段渐隐,不从硬边矩形源往下涂 |
+| 流痕糊成一团团烟,挂在羊身下面像投影 | 不要整体 bicubic 放大成软团;只在横向留 ±2.5 px 的过渡,纵向才平滑 |
+| 流痕像一根根火柴棍 / 芦苇帘 | 宽度取对数正态(中位约 18 px)、约 110 条、只把漆加厚 0.2、锰色 0.6;再加约 26 条更宽的浅色流痕(漆被水流冲薄) |
+| 薄漆的「窗口」成了迷彩斑块 | 不用块状窗口,浅色也做成竖向流痕 |
+| 凿点太稀,图形像撒了一层粉笔末 | 凹坑数 ≈ 3.4 × 图形面积 / 单坑面积;坑深相加后饱和(dmax ≈ 2.9 px),内部打满只留小暗缝,轮廓在一个坑的尺度上毛糙 |
+| 羊身细长像腊肠,整群首尾相连成一条带 | 身体加深(-0.20 到 0.15 个身长)、颈粗;大羊一排、母羊小羊一排错开,彼此留空 |
+| 剥落像贴上去的光滑椭圆,四周一圈黑 | 轮廓拆成 14–40 px 的小段、每段向内弯成小贝壳弧;AO 减弱(深度 2.4 / 7 / 22);疤面颗粒减半、鲜橙色带铁质色带,唇口一圈浅色风化皮 |
+| 地衣像绿色颜料点、像一枚枚硬币 | 低饱和橄榄色,椭圆加不规则叶状边、龟裂纹、小黑子实体、周围卫星小点,alpha 约 0.7 |
+| 太阳螺旋中心成了「f」,光芒离螺旋太远像飘着 | 螺旋从 1.4 rad、10% 半径起步,中心只点一个小点;光芒从最外圈外 1.7 倍线宽处开始 |
+| 蹄印像等号或乱点 | 两瓣从蹄跟到蹄尖向中线收拢成心形(尺寸 ≥ 30 px,凿点 size 0.66);第一枚离羊蹄远一点 |
+| 小孩手印糊成一团 | 手印 ≥ 约 95 px,凿点 size 0.62、density 1.2,手指才分得开 |
+| 光秃砂岩像一块木板(层理像木纹、小凹坑像钉眼) | 层理振幅减半且时有时无,石色只随层理变 1–3%;凹坑改成 7–26 px 的浅碟 |
+| 画面顶边、左边多出一条黑带 | 投影步进前用边缘复制把高度图 pad 一圈(越界补 0 会被当成一堵墙投下影子) |
+| 岩檐只像一道裂缝 | 台阶 34 px 才有一条看得见的檐下投影;檐口折线 + 轻微倒圆 |
+| 新旧凿痕只有「全新」和「鬼影」两档 | 加中间档 age 0.3(新月、计日刻痕、掷矛手):0 新凿、0.3 几百年、0.6–0.7 几乎被漆盖回 |
+| 动图里橄榄绿地衣被量化成灰 | 给偏绿像素单独留 6 个调色板位,「和上一帧相同」的占位色用品红 |
+
+**古埃及墓室壁画**
+
+| 问题 | 改法 |
+|---|---|
+| 弯腰的人还是正面宽肩,后肩翘到头顶上,横过胸前的手臂像一条绶带 | 按前倾角把肩宽往侧面收(前倾 32° 时只剩约 15%),两只手臂都从胸前出发;坐姿直接给 `turn` |
+| 蹲坐的书吏把脚转 180° 后脚底朝天,两臂缠在一起 | 压在身下的脚左右镜像(`mb=True`,脚尖朝后),肘部 IK 一律朝下弯,`turn=0.45` 收窄躯干 |
+| 灰泥脱落像贴上去的褐色石片,带一圈发亮的白边 | 做成真的高度图:洞深 8 px,低角度光沿高度图投影(左上内壁一道影),洞底近壁处加环境遮蔽;石膏白边只留 2–4 px 且断断续续,洞口四周的颜料按台阶剥落 |
+| 底色把人物里的红稿整个盖掉,剥落处只露出黄底 | 底色绕开要上色的形状刷(`ground(around=True)`):动画里红稿一直留到上色那一步;人物上的剥落露出灰泥上的红格和红稿(`age(zones=...)` 可以指定几处) |
+| 干活的人都戴宽项圈,分不出主仆 | 只有总管和书吏戴项圈;劳工赤膊,有的剃短发(`wig='cap'`,露耳朵) |
+| 象形数字 ∩‖ 读成「ΛI」:一竖藏在 ∩ 的腿后面 | 每个 ∩ 之后让 0.78 em,竖笔间距 0.3 em,字号 46 px 以上 |
+| 粮袋正中那道褶像一张笑脸 | 褶线挪到袋子一侧,竖着走 |
+| 无花果树冠是一格格圆点,像波点布 | 尖叶按行排、隔行错开、下一行压住上一行(像鳞片),深浅绿隔行;水囊挂在一根截断的枝上 |
+| 锄地的人像在推棍子,量斗像一本书 | 锄头画成倒 V:双手握柄,柄顶绑宽木刃斜插进土,中间一道绳;量斗是上宽下窄的木桶,口上堆着粮,倾斜着倒出一股粮粒 |
+| 扛东西的人手捂额头,袋子盖住了脸 | 后手举起扶住,货物压在后肩、在头后面(z 夹在躯干和举起的手臂之间);部件细节的 z 偏移只给 +0.002,否则筐的编织纹会跳到手臂上面 |
+| 埃及蓝像一层蠕虫状噪点 | 蓝、绿两色改用稀疏的亮晶粒加暗颗粒(`T_cryst`),通用颗粒压到 0.05 |
+| 底色的斜向刷痕整面平铺,像雨丝 | 两个方向、按大块噪声时有时无,幅度 0.012–0.015 |
+| 潮痕像一条钢笔线横穿人物 | 宽约 0.012 H 的柔和带,上沿稍清楚,往下逐渐泛褐 |
+| 动图 3.7 MB(满墙颗粒让每次叠化都改掉一半像素) | 关键帧先做 1 px 高斯平滑;量化时新颜色和上一帧已显示的颜色相差不超过 10 级就沿用上一帧的索引(透明差分照样有效,自检仍逐帧比对)→ 1.85 MB |
+
+**罗马马赛克**
+
+| 问题 | 改法 |
+|---|---|
+| 石子像一个个鼓起的枕头,整幅像碎石路 | 地面是打磨过的:石面只高 1.5–2 px、倒角半径约 1.7 px,漫反射 0.45 + 0.55;切石抖动 4.5%、缺角 20%、转角 ±1.6° |
+| 灰色的鱼身里混进淡蓝、粉色石子 | 取石在「亮度 + 红绿 + 黄蓝」对立色空间里比,色度权重 2.6,抖动主要加在亮度上(已处理) |
+| 轮廓那一排又宽又长(约 13 px 深而不是 8 px),第二排轮廓铺不出来 | 判断「里面还有没有下一排」用的脊线最大值滤波半径小于一排间距,每排都以为自己是最后一排、往里加宽:半径取 2 × 排距(已修) |
+| 波浪纹边框整圈不见了,只剩白排 | 局部坐标的周期被带高乘了两次,波浪画到几千像素外:周期 / (1.5 × 带高) 再乘带高 |
+| 边框的浪是一条条细 S 线,像卷草不像浪 | 浪身是从黑框边长出来的实心块,浪尖沿一条渐细的粗线卷回去,中间留一个白「眼」 |
+| 收起挂在帆桁上的帆像一把伞 | 改成从帆桁垂下、向一侧鼓起的方帆,竖向缩帆索用浅色石子 |
+| 小海鸥外面套两圈背景光环,像装在泡泡里 | 所有东西先一圈光环;第二圈只给大图形(船、灯塔、铭牌、网、章鱼),量距离时把第一圈也算进去 |
+| 网里的鱼被网线切成碎块,看不出是鱼 | 网里的鱼先铺(眼、鳃线、轮廓、填满),网线后铺,碰到鱼自动断开 |
+| 被偷的那条鱼太小、贴着网,看不出章鱼在偷 | 鱼放大到约 150 px、拖到网外,章鱼最长的那条腕绕住鱼尾 |
+| 天空里的脱落像一个灰色加号 | 脱落放在边框和海里、靠着裂缝;旧灰浆床压暗偏暖,留下石子方坑 |
+| 铭牌燕尾耳尖上散着红色碎屑,小字像虚线 | 耳朵填完只补大于半块的洞(`tuck(small=0.55)`);字的石子边长取字高 / 5.6,不小于 5.6 px |
+| 动图 3.2 MB:最后一次叠化整幅都在变 | 阶段快照和收尾帧都按 `stage_ss` 渲染(分辨率一致);积灰只成片出现、不整幅压暗;和屏上颜色差 ≤ 10/255 的像素按「没变」透明 → 1.57 MB |
+| 动图里金色火焰、光芒变成粉橙色 | 调色板分两份:饱和像素按 12 个色相区等量抽样,单独中值切分 48 色,其余 207 色 |
+| 峰值内存 2.6 GB | 2× 渲染按 96 行条带做,起稿、噪声、裂缝图留在 1× 逐条放大;paint / shade / sinopia 只在遮罩外接框里算 → 1.35 GB |
+
+**彩色玻璃花窗**
+
+| 问题 | 改法 |
+|---|---|
+| 铅条像半透明的灰色铅笔线 | 光晕叠到铅条上只留约两成,铅的颜色压到 #2c2d31 左右(已处理) |
+| 同一道条纹横穿相邻几块玻璃,像盖了一层滤镜 | 每块玻璃取自整张料的不同位置:条纹按块加随机相位,方向也按块随机(已处理) |
+| 树冠每个圆团单独一块料,铅条围出一圈圈圆,像肥皂泡、像葡萄 | 整个树冠用一次 `glass()`(多种绿随机分给各块),团块的体积靠彩绘:背光侧月牙 `shade`、下缘一串扇贝形描线、受光侧从 matt 里刮出叶形 |
+| 小叶子用描线勾轮廓,缩小后成了一团乱线 | 暗部画实心叶片(不透明度约 0.8)再刮出叶脉;亮部从 matt 里刮出叶形 |
+| 细枝也切成玻璃,两条铅夹一道棕线像梯子;冬树成了一个「Y」 | 玻璃只切树干和宽 16 px 以上的大枝,大枝要弯;更细的枝和小枝用 `trace` 画在天空上 |
+| 太阳周围另切一圈放射块,外沿多出一道圆形铅条 | 区域交界一定是铅条:同一片天空只用一次 `glass()` |
+| 燕子像喷气式飞机 | 用从下往上看的雨燕剪影:镰刀形后掠弯翼、短身、深叉尾 |
+| 横铁条正好横穿知更鸟的头和鸟巢 | 先定铁条高度(范例是 286 / 490 / 694),鸟、巢、太阳、字都避开 |
+| 每个铅条交叉处都扎一个铜丝结,铁条像一排缝线 | 每根铁条只扎几个小结(已处理) |
+| 题字带从中间切开,铅条正好穿过字 | 短题字的饰带用一整块料 |
+| 树干被切成一节节竹子 | 树干和大枝用竖向拉长的块(`aspect=1.8, angle=π/2`) |
+| 秋天透过树冠的画枝和画的叶子拼成像字母的黑块 | 画枝只画在露出天空的地方(`trace(..., clip=)`) |
+| 上铅之后整扇窗发暗发闷 | 铅条下面的玻璃压暗只做 4.5 px、0.22(已处理) |
+| 带 `--stages` 和不带出的图不一样 | 渲染时才生成的噪声和气泡改用构造时就定好的种子,阶段快照不再挪动随机序列(已处理) |
+| 动图 3.3 MB:每个阶段墙面溢光都跟着窗变,整面墙在每次叠化里重编码 | `daylight()` 之前墙用固定的中性溢光;叠化帧里色差 ≤ 18(关键帧 ≤ 6)的像素沿用上一帧(1.8 MB) |
+| 小形状也开整幅数组做模糊和遮罩:44 秒、1.6 GB | `matt / shade / circle / ellipse / poly / saddle_bar / lancet` 都只在包围盒里算(约 4 秒、约 1 GB) |
+
+**泥金手抄本**
+
+| 问题 | 改法 |
+|---|---|
+| 羊皮纸像拉毛墙、灰泥墙 | 封皮的细颗粒起伏误铺到了书页底下:封皮起伏只加在露出的封皮上;皮面起伏只用低频(尺度约 240 px、振幅约 6 px,靠近页边加倍) |
+| 正文溢出压进圆图;首行红字标题被挤成两行 | 动笔前用 `text_width` 量:x 高 18 px 时一行约 45 个字符,标题写短;正文按行数算好再定图的位置 |
+| 首字母旁窄栏两端对齐后,词距大得像空洞 | 拉伸上限 2.2 个词距;放不下就按拉丁音节加连字号断词(已处理),还不行就左对齐 |
+| 打磨金箔像一块黄颜料,带横向稻草纹 | 金是镜子,颜色就是它映出的房间:让平面的反射落在窗光的斜坡上(窗方向 z≈0.8),给石膏底加打磨留下的大尺度起伏(尺度约 60 px、±2 px),才映得出明暗带;拉丝纹振幅压到 0.04,金箔接缝 0.12 |
+| 同样的金,在跨页一边亮、另一边发橄榄黑 | 相机放远(z≈6000,接近正交),明暗只看表面法线,不随画面位置漂移 |
+| 星盘的网架金色太粗,盖住盘面,看不出是星盘 | 网架变细(黄道环 0.06R、横梁 0.017R、星指针 0.024R),盘面加方位圈(过天顶和天底的圆,只画地平线以上),墨线 0.75 px、不透明度 0.85 |
+| 圆图里的行星名字摞成一竖排 | 每个名字沿自己的环写,角度错开成阶梯(150° → 36°) |
+| 恒星天里的金星被群青盖掉 | 先贴金后上色,颜料遮罩要乘 (1 − 金),绕开已贴金的地方 |
+| 常春藤叶子像金色小铃铛,压到正文和边框条上 | 叶形要有两侧尖角和深缺口;叶、花、金珠放下前先检查:叶尖和两侧角离正文至少 9 px,离边框条至少「叶长 + 3」px;卷须不能弯回去穿过边框条 |
+| 首字母上的白色短划像随手画的加号 | 去掉短划,只留沿笔画中线的白线和三点一组的白点 |
+| 次级首字母的红色卷须压进红字标题,像鱼骨 | 卷须放在字左侧 16 px 外;钩子只朝页边一侧,长短交替,末端打卷 |
+| 背面透过来的字太重,像渲染错误 | 透印不透明度 0.03,模糊 1.6 px |
+| 动图里玫瑰色和金色被量化成褐色 | 调色板取样时,饱和像素算 5 倍 |
+
+**达·芬奇手稿**
+
+| 问题 | 改法 |
+|---|---|
+| 排线像一团卷毛、像波浪 | 不要把一条长排线切成一串各自弯曲的短笔首尾相接;手是一排一排地排线:同一层排线共用一组带轻微错位的「排界」,长线只在排界处断开,留 0–2 px 的空隙或交叠;手抖 jitter 降到 0.1,所有笔画朝同一边微弯 |
+| 蒙皮整片涂黑,像一幅幅窗帘 | 每片蒙皮用 `between()` 取「从前一根肋到后一根肋」的 0→1 场,明暗取 t²:靠前那根肋留白、靠后那根肋才排线、最深处才交叉,蒙皮才会鼓起来 |
+| 翼后缘一段段往外鼓 | 蝙蝠翼蒙皮在两个肋尖之间往里凹;镜像到左翼时法线方向会反,弯曲方向按「朝翼内某一点」决定,不按左右写死 |
+| 翼形又钝又圆,像一面帆 | 指骨肋从腕点呈扇形散开,翼尖收成尖角,越往外翼弦越短 |
+| 红粉笔鸟翼像梳子、像流苏 | 羽毛不画完整轮廓:只画宽羽片的外缘、圆的羽尖和窄羽片的尾段(`overlapped=True`),一片压一片;羽尖要圆不要尖;初级飞羽比次级飞羽长,外侧几根张开约 7° 成「指」;宽羽片靠外缘处排线(被下一根羽毛压出的影子),覆羽画成成排的小圆弧再揉开 |
+| 单根羽毛像一片带叶脉的叶子 | 羽枝每 2.6 px 一根、很细很轻,朝羽尖斜;加一段光秃的羽管和两处羽枝分叉的缺口 |
+| 扇形排线时有时无,一块一块 | 明暗值不要正好压在排线阈值上(噪声会让它一半过线一半不过),整片均匀的排线 shade 给得比阈值高一截 |
+| 尖笔辅助线横穿整页、像划痕 | 圆规只在需要的地方刻一小段弧(翼尖 ±12°),中心线、肩线可以长;刻痕没有颜色,只靠侧光的明暗 |
+| 曲柄看起来像个 L 形铁片 | 曲柄臂在轴端加一个套轴的凸台,木把手更长更粗,并用点划线示意它沿轴滑上去 |
+| 分解图的零件和机翼撞在一起 | 先算好投影:相机方位角改为 +22°,轴往左下伸,轴缩短到 250,曲柄落在空白处 |
+| 旧纸太干净、像新打印纸 | 除了霉斑还要大片柔和的泛黄云斑(纸的施胶老化不均);霉斑要有清楚的小核,不能只是一团模糊的晕 |
+| 霉斑的晕被切成小方块 | 每个斑点的计算框要按晕的半径(约 7 倍斑点半径)开,不能按斑点本身 |
+| 墨色发灰 | 铁胆墨水偏暖:淡处琥珀褐、浓处深赭,叠处更深;纸纤维把墨线轻轻打散 |
+| 飞鸟序列只是一串「V」 | 每只鸟加身体、尾羽、腕部转折和翼尖张开的初级飞羽,按 `phase` 走完一次上扑下扑 |
+
+**剪影**
+
+| 问题 | 改法 |
+|---|---|
+| 垂卷用一串椭圆叠成,像一串葡萄 | `ringlet()`:一条左右摆动、每圈鼓一下、越往下越细的长条(约 5 圈),金粉只在每圈上画一笔短斜线 |
+| 头发的金粉画成随机小弧,像一串气泡;改成 10 条等距平行线,又像条纹头盔 | 只画 6 条左右长短不一的发丝,顺着发团从额头梳向脑后,线宽约 2 个设计单位 |
+| 帽檐是等粗的直条,像一根签子插穿了头 | 帽檐沿一条 S 形中线 `snip`:靠帽冠处最厚(约 22),两头收到 3,前沿上翘,后沿下垂 |
+| 帽冠的褶纹全汇到一点,像顶帐篷 | 褶纹画成互不相交的短弧;帽冠上沿用 `scallop` 鼓出一排小圆,做出抽褶感 |
+| 蝴蝶结是两个圆环加圆洞,像眼镜,还被帽檐挡掉一半 | 环拉长成椭圆,中间剪一道窄缝(宽约 0.12 倍);放在帽檐上方、背后是底卡的地方 |
+| 猫又高又窄、头很小,像保龄球瓶 | `sheet(warp=)` 只改比例、不重敲坐标:头放大 1.12 倍并下移,身体朝垫子压到 0.62,臀部加宽;再剪出眼睛和前后腿之间的空隙 |
+| 船的两面三角帆互相重叠、又压着前桅帆;主帆和后纵帆连成一大块黑 | 第二面三角帆整个放在第一面后缘的右边;主桅最下面的大横帆收起(帆桁下一排小圆);后纵帆缩到主上桅帆下面;上下横帆之间至少留 14 个设计单位;三角帆保留尖角,只让后缘鼓 |
+| 侧框外圈的红色底漆磨成一大片一大片棕斑 | 底漆只在棱顶露出:噪声尺度 5 px(2× 采样再 ×2),阈值 0.66–0.80,强度 0.6 |
+| 名字和小字贴到黑色描边带上 | 椭圆越往下越窄:先按 hw = rx·√(1−(dy/ry)²) 算那一行的半宽再定字号;名字 32 px,小字不超过 25 个字符 |
+| 墙纸条纹笔直清晰,像现代印刷 | 印版遮罩加约 ±0.9 px 的横向漂移,奶白色墨不透明度 0.66,每幅纸单独印、各自错位和对花,再加一层泛黄 |
+| 动图里深红丝绳被量化成棕色,玻璃反光下的黑纸出现一块块色阶 | 调色板样本加权:饱和像素 ×5、深红 ×15、被反光抬亮的黑(亮度 0.075–0.28)×7,再叠同一张 4×4 Bayer(约 ±2.4 级) |
+| 峰值内存 1.1 GB:整幅 `blur` 和细尺度 `noise2d` 产生大量 float64 中间数组 | 挂镜线、护墙线的阴影只和 y 有关,按一维算;整幅细噪声换成白噪声加 3×3 均值;2× 金框按 192 行一带分带渲染(重叠 24 行),降到约 0.6 GB |
+
+**凸版印刷海报**
+
+| 问题 | 改法 |
+|---|---|
+| 大面积实地满是白点,像加了噪点滤镜,木刻黑块发灰 | 漏白(salt)只出现在实地内部,纸齿阈值 0.975 以上,约占 1%–5%;边缘积墨处几乎不漏;木活字凹坑软斑浓度降到 0.15–0.35 |
+| 大象前腿斜着伸到老远的鼓上,像撑地的肘 | 以髋为轴把身体整体抬起(约 22°),四条腿都竖直向下;鼓放在前肩正下方,鼓顶 = 前肩高度 + 前腿长(腿比后腿短 4%) |
+| 大象像秃头圆球加一根水管,耳朵像第二个头、像垂耳狗、像兜帽 | 象鼻根部宽约一个头高(104→26 渐细),并进前额;耳朵是扇形:前缘弧形贴在眼后,顶端低于头顶让圆顶露出来,后缘波浪、下端收尖;加小象牙和张开的嘴 |
+| 腿根在身体里画出一圈圆头轮廓,像插上去的柱子 | 先刻远侧两条腿;近侧身体、头、鼻、近侧腿、尾巴合成一个剪影只刻一圈外轮廓,内部只补大腿、肘几笔短轮廓线 |
+| 排线整片一样密,大象像条纹木桶 | 排线线宽跟随明暗(`hatch` 的 tone),lo 约 0.3:背上最亮处线条自然收尖消失;身体用绕远处圆心的弧线,腿用竖线,鼻子斜线加横向皱纹 |
+| 鼓上的条纹印成一整块红色楔形 | 条纹相位 = arcsin(u)·9 − y/9,一圈正面看到 4–5 条斜纹,上下各留出箍 |
+| 象头上的小帽画成红色贝雷帽、像一颗樱桃 | 非斯帽用直边多边形 `poly`(不用平滑闭合曲线),流苏从帽顶垂到后面 |
+| 象鼻尖碰到钢丝,看着像要去抓钢丝 | 鼻尖离钢丝留约 70 px,卷向演员 |
+| 画面偏右,桅杆和大象之间空出一大片 | 大象放在两根桅杆正中;背后加雕版衬线:横向细线、椭圆向外渐隐,每样东西周围先 blur 出一圈白再清掉 |
+| 舞者的站立腿是两根细线,平衡杆横穿胸口 | 腿加粗(17→9 px)、加黑色舞鞋;手肘弯下,杆放到腰的高度 |
+| 马戏圈的圈沿伸出画面右边;锯末和地面投影太黑,像污渍 | 圈的半宽按两根桅杆间距算;锯末密度 0.0035、只在脚边,投影用横向排线(tone 0.55) |
+| 纸边的小缺口是一颗颗黑点,像墨团 | 缺口只留 3 个、3–7 px |
+| 峰值内存 1.5 GB | `press` 按 240 行一带处理;木刻印完就释放整页遮罩(1.19 GB) |
+
+**苏联构成主义**
+
+| 问题 | 改法 |
+|---|---|
+| 网格塔印成网点后是一根实心的点状锥体,看不出格子 | 每节每组杆件从 24 根减到 16 → 8 根(越往上越少),杆件加粗(0.55 m 往上收到约 0.27 m);远侧半圈的杆件反照率最多 ×6.5,显得浅;雾的距离从 520 m 改到 2600 m(否则全塔被雾冲成均匀的中灰);塔照片加网前的模糊从 0.3 格降到 0.12 格(`soften=0.12`),塔顶的横担才分得开 |
+| 收音机照片认不出:喇叭正对镜头成了一个黑球,电子管是白疙瘩 | 喇叭口轴线与视线约成 60°,侧面看得到外扩的喇叭口和口内暗面;黄铜反照率 0.45、金属度 0.5,底座改黑漆;玻璃管反照率 0.42,加一道内部阳极暗带 |
+| 收音机面板像照相机(两个一样大的象牙色刻度盘像镜头) | 改成一个黑色胶木大刻度盘(镍圈 + 白刻线)加两个小旋钮、接线柱、铭牌,机顶加蜂巢线圈,喇叭到机身拉一根软线;照片放大到 1.16 倍,网点格从 6.5 px 改成 5.5 px |
+| 编号方块里的数字不见了 | 黑色电波弧压在了标注上,黑上加黑挖不出空。电波只占楔形 ±9° 的范围、到喇叭口为止,标注都放在电波范围外 |
+| 电波弧铺满半张纸,像梳子、像肋骨 | 波前只画在楔形附近,从塔尖画到喇叭口;线宽随半径变细(`grow=-0.045`);上沿只到 +6.5°,别碰到标题 |
+| 斜排的标注里,数字跑到方块外面 | 方块和数字都用 `along()` 从同一个左下角算;不要一个绕自身中心转、一个绕角点转 |
+| 剪下的照片放在纸色上,剪刀留的白边看不出来 | 让照片压在红块、黑条或楔形上:收音机后面垫一块从黑条升起的大红块,楔形一直伸到喇叭口下面 |
+| 红块只从照片缝里露出几条细缝,像渲染错误 | 红块要比照片大一圈(高 410 px),从黑条一直顶到标题下面;剪刀剪不进的窄缝用 `close=` 桥接,被照片围住的洞自动填平(剪刀只能绕着外轮廓剪) |
+| 楔形末端的直边在喇叭口旁边露出一个红角 | 楔形只伸到喇叭口再多 20 px,半角 5.6°,宽度和喇叭口差不多,末端整个藏在剪下的照片下面 |
+| 折痕太弱,像画上去的一根细线 | 折痕处墨层断断续续地裂开(约 2–3 px 宽),两侧约 ±3 px 的磨损带墨最多淡 22%,再加一亮一暗的折棱和一道污渍带 |
+| 图钉孔像一个黑点 | 孔周围加一圈偏向一侧的锈色晕 |
+| 红版套印错位后,画面右边缘露出 2 px 纸白 | 错位前先把版用边缘复制 pad 8 px:成品是印完再裁切的,边上不会露白 |
+| 填洞后剪下的照片反而整片印满底色网点 | `ImageDraw.floodfill` 对 `Image.fromarray()` 得到的图不起作用(不报错),要先 `.copy()` 再填 |
+
+**装饰艺术**
+
+| 问题 | 改法 |
+|---|---|
+| 车鼻前下方一圈圈指纹状条纹,法线乱跳 | 「把截面朝一个点缩放」得到的不是合格的距离场(命中点残差 0.19 m);改成竖直核心线段膨胀 R 的精确截面(直侧壁、圆车顶、底部平切),车鼻只沿轨道方向拉伸(只会低估距离,步进安全),残差降到 0.008 m |
+| 车头竖直,像电车 | 核心前缘做成斜线(`rake` 约 2.2 m),车鼻向前下方倾斜 |
+| 头灯飘在车头前面;奶油窗带在车鼻上被一刀竖直切断 | 斜车头实际伸出的长度比 nose_len 长得多(垂直斜边膨胀):用二分法实测车鼻表面,头灯、条纹收拢、车鼻素色端头都以实测车尖为准;条纹在最后 14% 前停下,窗带收成尖头 |
+| 车身只有几道细金线,远看是一整块红 | 加奶油色窗带(1.95–3.15 m)和上下金线;腰线在车鼻上按截面坐标向车鼻收拢,成为速度线 |
+| 钟和扇形冠顶浮在楼顶上面,戳进标题 | 钟画在顶层楼身上(`top_windows=False` 把这层的窗空出来),冠顶从顶层上沿起;近景楼顶都压在副标题下方 |
+| 副标题两侧的金线穿过副标题文字 | 先画副标题拿到宽度,金线从标题两端画到副标题外侧 28 px |
+| 头灯是一大团白光,像一只眼睛 | 灯球半径 0.3 m、铬圈 0.47 m,光晕 80 / 10 px,自发光 0.85 |
+| 头灯光束指回车身 | 光束终点取 60 m 前方会跑到相机后面、投影翻转;终点改为 min(60, 0.6·Z/dz) |
+| 头灯照亮前方铁轨,但画面里看不见 | 护栏 0.56 m 高、相机只比轨面高 1.4 m,桥面被护栏挡住;护栏降到 0.25 m、相机抬到轨面上 2 m;掠射角的朗伯项只有约 0.1,改成包裹式(×5 封顶),铁轨成了从左下引进画面的两道亮线 |
+| 喷枪颗粒太粗,光束和射线像撒了沙 | 颗粒 = 固定噪声 × 0.2 × d(1−d):只在薄涂处有,实涂和空白处没有;射线的颗粒 0.45 |
+| 河面倒影是一块块迷彩斑 | 波纹按压缩后的深度坐标取噪声,横向拉长约 90 倍、只用两层:近处长而稀、远处细而密 |
+| 月亮倒影太弱,黑天空和月亮反射得一样多 | 镜像按亮度加权(0.45 + 1.3·smoothstep(0.35, 0.85, 亮度)),月亮和窗灯拉出一条光路 |
+| 车窗倒影成了高架下面一串孤立亮点 | 范例里关掉(`lights(r, reflect=False)`);要用就把拉伸调长 |
+| 月海是脏兮兮的斑点 | 月海用 smoothstep 柔边、浓度 0.13、颗粒 0.25 |
+| 动图里红色车身被量化成棕色色块,天空出色带 | 加权调色板(饱和像素 ×5、亮像素 ×2)+ 每帧同一张 4×4 Bayer(约 ±2.4 级);量化只用 255 个真实颜色,占位透明色用品红,否则最暗的像素被当成透明(自检 9 帧对不上) |
+
+**黄金时代漫画**
+
+| 问题 | 改法 |
+|---|---|
+| 羽状排线像一排梳齿、像尺子刻度:等长、等距、完全平行 | 长度跟着两层慢噪声起伏(0.25–1.15 倍),间距 ±30%,每根略弯、偏离平行约 4°;起笔压在阴影边上,越往亮处越短 |
+| 羽状排线穿过白色色环上的字,RS-1 被看成 RS-T | 排线的 clip 去掉文字所在的区域 |
+| C40 M70 Y100 的棕色(头盔、山体暗面)在 11 px 粗网下花成发绿的斑 | 棕色不用蓝版:M70 Y100 + 黑 40% / 70%(`BROWN` / `DARK_BROWN`) |
+| 天空七条等宽色带像一面旗;中间几档两版都挂网,花点太闹,压住人物 | 色带用 `edges=` 指定不等宽;过渡档尽量只挂一个版(蓝 40%、蓝 20%、黄 40%),两版叠网只留在顶部一两档 |
+| 月亮光晕的同心色环盖过所有色带,在橙色带里切出一个蓝色圆盘 | 去掉光晕;`rings()` 只用在单一色带里 |
+| 顺风飘的围巾正好盖住后座小狗的头,小狗只剩一团白 | 围巾往后上方飘(漫画夸张),小狗后移;先画后座再画前座;狗脸用纯白(不挂网)配黑耳、黑鼻、金色护目镜 |
+| 护目镜比脸还大,像第二个头;挡风玻璃像两颗牙、像多出来的尾翼 | 护目镜只露一只镜片推在额头上;去掉挡风玻璃,只留座舱口沿 |
+| 座舱里的人画在船体之后,下半身露在船体外面 | 先画人,再画船体:`part` 会擦掉被挡住的墨线和颜色,最后补座舱口沿 |
+| 尾喷管是一块挂网灰方盒;火焰外层深橙和橙色天空同色,又被下尾翼和烟挡掉 | 喷管涂黑加银色口沿;火焰由外到内红、深橙、橙、黄、白五层,烟只吞掉火焰末端,下尾翼缩小,去掉横穿舷窗的中间尾翼 |
+| 烟团是锯齿星形、挂橙色网,像一堆石头 | 烟团用近圆形加轻微起伏,白底;只在右下月牙挂黑 20%,靠火焰的一侧挂黄 40% |
+| 右边台地看不出是悬崖:斜面、羽线、暗面混成一团,暗面花成墨绿 | 平顶加竖直崖壁:崖顶下一道黑影,裂缝从黑影往下用 `feather(along=(0, 1))`;崖脚另起一道碎石坡,换一种颜色 |
+| 地平线正好穿过 Sparky 的头;他在画面里太小,故事的笑点看不见 | 地平线下移到胸口;人物放大 1.15 倍,飞走的帽子挪开、别压在手上 |
+| 动图超过 2 MB(2.34 MB),网点缩小后成了摩尔纹 | 缩到 720 宽时用 BOX 不用 LANCZOS:1.79 MB,网点仍隐约可见 |
+| 内存峰值 1.25 GB | 网点阈值图等缓存改成 float16;印刷按 180 行一带处理;刊名只在自己的裁切区里算;做旧效果只作用在各自区域:峰值约 0.85 GB |
+
+**波普丝网**
+
+| 问题 | 改法 |
+|---|---|
+| 好几格里多出贯穿整格的黑斜线 | 闭眼弧线的粗细用 `sin(πt) ** 0.7`,末端 sin 是 −1e-16,幂运算得 NaN,多边形就连到了窗口原点。`stroke()` 里已把宽度 `nan_to_num` 并截到 ≥ 0;自己写 `profile` 时先 `clip(sin, 0, 1)` |
+| 底色上一道道白色横纹,像划痕 | 底色 `dry=0`,`streak` 约 0.012;笔触纹拉长(长约 140 px、宽约 7 px);干笔拖痕只出现在形状边缘一圈 |
+| 缺墨时黑块里露出规整的方格编织纹,像数码图案 | 布纹对墨膜的影响降到 0.035;露底主要来自顺刮板方向的条纹、约 5 px 的团块噪声和一块干版斑 |
+| 闭眼的 ∩ 太细,下面又垫一块椭圆眼影,读成「眉毛 + 睁着的眼」 | 闭眼弧线宽约 0.10 单位,两端收细;开心那格不垫眼影,改用腮红;困那格的眼影做成闭合的眼皮形状,只在闭眼线上方 |
+| density 0.84 的缺墨格,脸几乎印不出来 | 0.92–0.95 是「缺墨但认得出」,1.0 正常,1.1–1.15 墨多;flood 超过约 0.5 会糊掉半张脸 |
+| 墨多那格,远侧耳朵糊成一顶黑礼帽;耳朵压平后,耳背描边和头顶虎斑纹交叉成一个 X | 耳朵外转超过 40° 时,耳窝只印网点、只描上沿;被耳朵挡住的那道头顶虎斑纹不印 |
+| 远侧耳朵的阴影和耳背描边分成两块:描边像一根飘着的棍子,耳毛像羽毛球 | 远侧整只耳朵做成一块暗面,一直到外缘;耳毛 4 根,宽约 0.026 单位 |
+| 吐舌头只是嘴下面一团红点 | 舌头色块伸出嘴外(下沿到约 0.74 单位);黑版给舌尖描 U 形轮廓和一道中线 |
+| 每格边缘一圈浅色细线,像内描边 | 漆脊的 relief 从 0.9 降到 0.35 |
+| 左肩上的长弧形虎斑纹像几道「翅膀」 | 受光一侧的胸前斑纹不印实线,只印成网点带(tone 约 0.38) |
+| 峰值内存 1.08 GB | 脚本把 60 多张整窗遮罩放进列表再 `np.stack`;`canvas()` 和合成时又整幅算临时数组。改成用 `np.maximum` 就地累积遮罩,颜色层按格现算,布纹和合成按 180 行一带计算,降到约 0.46 GB(改遮罩累积这一步前后,成品逐字节相同) |
+| 动图里黑网点和六套配色的混合色量化错(p99 误差 100) | 调色板样本里,已上黑版的后半关键帧 ×3,再用 `kmeans=4` 精修:p99 降到 39,误差大于 70 的像素从 3.7% 降到 0.03%,体积不变 |
+
+**ASCII 字符画(行式打印机)**
+
+| 问题 | 改法 |
+|---|---|
+| 箭身和烟用 I H M N 之类字母铺调子,远看像一行行单词「IMM」「HNM」 | 填色字符只用符号:箭身 `. : + % # #@`,烟 `. : % @ # #@`;字母只留给真正的文字 |
+| 按形状相关度给线条挑字,桁架塔变成一串 `<> <>`、`^V` | 改成按方向和位置选:方向在真实像素里量(格子是瘦高的),陡的 \| / \\,平的按在格里的高低选 `' - . _`,两条线交叉才用 X / + |
+| 斜线、竖线同时压到左右两格,到处是 `//`、`\\`、`)\|` | 同一条线、同一方向的相邻两格只留笔画更多的那格(非极大值抑制;斜线还要求字符相同,免得吃掉尖顶的 /\\) |
+| 桁架斜撑交点落在四格交角,中间成了 `\_/`、`/-\`,没有 X | 斜撑按「一列一行」走、过格心:塔宽取 6 列(中间 5 格),交点正好落在格心出 X;横撑放在行中心,压在行界上会被两行平分、谁也不到阈值 |
+| 箭身和黑色滚转标记、尾焰之间也描出一圈轮廓,箭身里横七竖八的 \| 和 ---- | 角色分组(`group='rocket'`):同组之间不描边,只有对外的剪影描边 |
+| 烟云每个云团都描边、调子又加误差扩散,底下一片乱码 | 云团用 `edge='all'` 但 `inner_max=0.5`:只在亮的云顶画 ( ) 和 .-',暗部只靠调子;光从上方来、云底再加一层自身阴影(`lift`),抖动降到 0.2;云团改成少而大(半径 5.5–10 列) |
+| 字太干净,像激光打印或屏幕截图 | 字模先按墨的洇开模糊约 0.5 px,再和色带织纹、纸面齿纹一起过阈值:力度够就满铺,力度弱就变细、断开、起麻点,而不是变灰;改用粗体字模 |
+| 火焰内部加了一根根 ' ! 的条纹,像引号和珠串;内焰锥画成一串 () | 尾焰从箭身底部直接长出来、和箭身同组,不用随机抖动 |
+| 尾焰只剩两条 ( ) 竖线围出的空白,读不出是在点火 | 尾焰做成从喷口往下变宽的亮柱:外层 `plume` 角色按离轴距离 u 从 . 过渡到 % @ # 的烟套(u>0.45 起变暗),内层 `core` 角色是几道从喷口散开、沿长度明暗闪动的条纹(! \| 在喷口、往下变成 : . '),两层都不加随机抖动才对称 |
+| 下面两团前排烟云从两侧压住亮柱,形成往下收窄的漏斗,看着像火焰变细 | 前排烟团外移(离轴 13.5 列),亮柱两侧各放一个小烟团接住烟套,中间那团的云顶 ____ 正好接住柱底 |
+| 头锥用平滑闭合曲线,肩部鼓出一块,又一版太钝像圆顶 | 头锥按弹头曲线 半宽 = R·(2s − s²) 逐点算多边形,不用样条 |
+| 左边天空加一层随机点「晨雾」,像纸上的脏点,还在第 94 列切出一条竖边 | 去掉;空的天空留白,右侧大空位放一座远处水塔平衡构图 |
+| 表头「RUN … PAGE」和参考图的格式太像 | 换成 JOB 4471 / SHEET 2 这类自编字段 |
+| 最底下一行烟云被画面下边切掉半行字 | 改用 8½ 英寸深的连续纸(`page_in=8.5`,51 行一页),`ppi` 调小让整张纸连同上下两道撕线都在画面里,左右露出桌面;画面在 `page_rows − 2` 行 `erase` 掉,留两行页边再到撕线;横向撕线和折痕加深 |
+| 太阳只是一圈线加几根离得很远的光芒,鸟东一只西一只,像随手的符号 | 太阳盘面用 . : 填出边缘发暗(中间 .、边上 :),光芒贴着盘面、8 根等长;鸟排成一队人字形往太阳方向飞 |
+| 动图里红圆珠笔被量化成灰色 | 红色像素太少,加权也抢不到颜色:调色板单独给红色留 14 格 |
+| 峰值内存约 1 GB | 纸张按通道就地合成、成图分 480 行一带合成,降到约 0.7 GB |
+
+**低多边形**
+
+| 问题 | 改法 |
+|---|---|
+| 悬崖上满是竖向的绿条纹,平台上反而是横向岩层 | 材质错位一格:每个面的材质取剖面里靠内侧的那个点(两端下标取小的),悬崖才贴岩层、平台才贴灌丛 |
+| 河床三角形一块块从水面里戳出来 | 画家排序按平均深度,埋在水下的河床有时算得比水面「更近」:完全在水下的面干脆不生成(`canyon(buried=)`),水面带 −2 的排序偏置,像贴花一样后画 |
+| 水面一片发白的青色 | 涟漪短划减到 16 条、颜色压暗,水面 spec 0.35;逆光看水本来就亮,别再加 |
+| 构图照搬参考图:飞机在正下方、大环正居中、后面的环一个个叠在环里 | 赛道改成右转弯,相机放到飞机右后方,用 `aim()` 把飞机放到左下三分点,金环沿对角线往右上排开 |
+| 外弯的岩壁把天空整个挡住,太阳和光晕都没了 | 峡谷整体压低(`height=0.75`),相机降到飞机上方约 2.6 m,视场 52°,留出约两成天空 |
+| 从正后方追尾看,飞机只剩一个「十」字,还被画面底边切掉 | 相机放在右后上方,能看到机翼上表面;飞机离镜头约 11 m |
+| 一级台阶和相机差不多高,被看成一道发亮的裂缝 | 相机高度避开台阶高度(台阶约 11.8 / 20 m,相机约 16.6 m) |
+| 金环又细又发橄榄色,看不出多面体 | 管径 0.6(半径 3.4)、12×5 个面、暖金 #ffaa1a、glow 0.28、spec 2.0、shine 4:暗面偏橙、亮面发黄、迎光的面闪白 |
+| 逆光下飞机和金环发灰发闷 | 着色光和画里的太阳分开设:`light(lift=26)` 把着色光抬高 26°(当年的游戏也这么做) |
+| 光晕里的空心圆像多出来的金环,正中的绿色六边形像一块石头 | 光晕只用小圆点和实心六边形;画面中心附近只放 2 px 的小点,大六边形放到远端并调淡 |
+| 「"」加粗后两撇连成一道横线,「1'07"42」读成「1'07-42」 | 两撇之间空两列(`'# #'`);零不加斜杠,斜体时才不像 8 |
+| 螺旋桨盘几乎看不见,像一块灰斑 | 半透明盘 alpha 0.36,再加一圈更亮的桨尖圆环 |
+| 杜松在逆光里成了黑剪影 | 树带 glow 0.3,叶色提亮 |
+| 动图 2.08 MB,金色 HUD 偏棕 | 缩小用 BOX 而不是 LANCZOS(像素硬边不出振铃噪点),调色板样本里饱和像素 ×5:1.63 MB |
+
+**喷漆模板涂鸦**
+
+| 问题 | 改法 |
+|---|---|
+| 每张模板四周都有一圈带麻点的大方框(风筝、燕子、字周围最明显),一开始还是贴着卡纸边的几条细直线 | 喷的区域按 2.5 倍喷幅往外扩,卡纸外的漆才落得到墙上;扫过卡纸边的「卡纸残影」系数降到 0.0035;扫到头折返时只减速到 0.55,不再在边上积一大团 |
+| 所有边缘都是 6–8 像素的毛刺,像发霉,清晰核心没了 | 卡纸翘起量不再按「离胶带越远越高」涨到 1:平贴为主(0.15 + 0.35 × 离胶带距离 + 0.5 × 局部鼓起);底下渗漆只用 1.8 像素模糊、权重 0.2 + 0.5 × 翘起量;外溢雾化 7 / 24 像素两层,强度 0.022 / 0.012 |
+| 滴痕到处都是:白漆滴痕从围巾一路流过外套和裤子,每座桥上面都往下滴 | 只从真正的下边缘起滴(往下 7 和 12 像素都是空的,桥不算);数量按 amount × min(26, 2 + 过量/40) 封顶,白版 0.06、灰版 0.2、黑版 0.7;滴痕的凸起降到 0.45 + 0.25 × 宽度/3,否则被后面几版盖住了还以白色棱线透出来 |
+| 三版叠起来灰糊糊:灰版跟黑版几乎一样深,白版喷不匀一片麻点,黑版只剩细边 | 灰改 #7b7c79;白漆遮盖力 2.0、喷 3 层;黑版阴影加深(躯干 34、腿 18 / 44 像素),`shade_side(wobble=)` 让阴影边像手刻的 |
+| 燕子像喷气式飞机 | 弯月形后掠翅(一上一下)、细身子、长长的分叉尾 |
+| 围巾先像面条,再像「VAV」字母,最后像一只举起来带手指的条纹胳膊 | 从脖子前一个结里分出两条长短不一的窄尾巴,往前稍往上飘;只画横条纹,尾巴上不加阴影月牙;流苏扇形散开、互不相碰(碰上了会围出孤岛被桥切成方框) |
+| 帽檐压住眼睛,下巴下的黑阴影像小胡子 | 帽檐整体上移 6 个单位,眼睛放大、鼻头往前凸、嘴是轮廓上的一个缺口;下巴阴影改进灰版、变细 |
+| 小孩像在往前走,躯干像一只蛋 | 上半身绕髋部再后仰 9°,前腿伸直、脚跟着地脚尖翘起,后腿弯着撑住;羽绒服缩短到胯部、收窄 |
+| 黑版快照里卡纸整张喷成黑的,看不出刻了什么 | 卡纸上的漆按「粉尘」画(0.82 × (1 − e^−0.55D),透出牛皮纸),切口边按卡纸厚度一侧亮一侧暗 |
+| 墙像木板墙,木纹太清楚;裂缝像画上去的黑线;泛碱像一条白色虚线 | 木纹起伏减半,只在一块块区域里压出来;加水泥色斑和浮浆;裂缝变细变淡;泛碱用噪声断开 |
+| 市政灰漆像一块模糊的圆角方块 | 改成一道道竖着的滚筒:每道起止高度不同(上下边缘成台阶)、两头发干拉丝、相邻两道重叠处颜色深一点,底下的旧签名透一点出来 |
+| 动图里红风筝变成砖红色、粉色签名没了 | 调色板样本加权:红 ×12、其他饱和色 ×5、黑 ×3,再叠同一张 4×4 Bayer(约 ±2.4 级);透明占位色用品红,不用黑 |
+
+**刺绣徽章**
+
+| 问题 | 改法 |
+|---|---|
+| 牛仔布像印出来的 45° 斜条纹,白纬又亮又粗 | 经纱比纬纱密(1.5 × 2.5 px),斜纹约 60°;纬纱只露一小点、每点露多少随机;经纱加竹节纱的染色起伏和磨白;2× 渲染再缩小 |
+| 缎面边框像条形码,黑白条太硬 | 缎面线截面压扁(起伏 ×0.6),线与线之间的暗沟只降到 0.74 |
+| 填充绣满片像砖墙 | 针孔凹陷只暗 30%;每行起针位置加 ±6% 的漂移 |
+| 缎面平平的,看不出「线的光泽渐变」 | 缎面长线按衬垫拱起(拱高约 0.11 × 线长,最多 3.2 px),一根线上就有从亮到暗的过渡 |
+| 深色线被高光冲淡,指南针每个尖角的明暗两半分不出来 | 高光整体 ×0.62;亮半边别用太亮的颜色(亮红 #cf4637 / 暗红 #721a14) |
+| 雪峰亮面太白,雪顶糊进山里 | 山的亮面用中灰蓝,白只留给缎面雪顶;阴面明显更暗 |
+| 火焰用竖向缎面,长线被拆成交错短针,看着像填充绣 | 针向横着走(约 ±15°),maxlen 放到 90;外焰、中焰、内焰一层压一层 |
+| 湖面波纹穿过帐篷,还伸出徽章压到边框和牛仔布上 | 细节针按层次排在压在它上面的东西之前画;`run(clip=徽章遮罩)`,路径留在边框以内 |
+| 异形章圆角的缎面边框出现放射状摩尔纹 | 按相位梯度算每处针距,小于约 2 px 时把单根线的起伏淡掉;圆角半径至少是边框宽度的两倍(34 px 对 17 px) |
+| 锁边上周期性的暗条和小黑点,底下的颜色从里面透出来 | 两个原因:2.6 px 的绕线和像素网格拍频,改成按 (s, d) 4 次子采样再平均;PIL 粗折线画的带状区域有针眼大的洞,再做一次 5×5 最大值滤波 |
+| 弧形条章的字挤到两头的锁边上 | 字号 42、跨角 98°,字间距 0.05 倍字号 |
+| 整组徽章太小,画面上方三成空着 | 设计坐标统一乘 1.14 再上移;针单独按画布坐标摆,别跟着放大推出画面 |
+| 动图里金色锁边和营火被量化成橙褐色 | 调色板样本里暖色饱和像素 ×5、亮色 ×2(暖色平均误差 9.5 → 5.6) |
+
## 四、做成动画
- 各画风都有 `stage(name)` 和 `save(path, stages_dir)`,按阶段依次淡入叠化,就是「一幅画被逐步画出来」。README 里的动图就是这样做的。
@@ -698,6 +1308,11 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask
- 标记「和上一帧相同」的透明占位色不要用黑色:最暗的阴影像素会被当成透明,自检时大批帧对不上,改用纯品红这类画面里没有的颜色。
- 最后一个 `stage()` 和成品完全相同时,Pillow 会把相同的帧合并,按帧数自检会报 EOFError:`save()` 前不要紧挨着再调一次 `stage()`。
- 卡通手绘的抖线动图只抖墨线,铅笔稿和颜色不动,否则每次叠化都整片重编码,体积翻倍。
+- 后来新增的十六种(岩画到刺绣徽章)动图又反复用到几条通用做法;改版的动图脚本放在各画风自己的工作目录(如 `claude_drawing/mosaic_work/`),没有进仓库:
+ - 加权调色板:取样时饱和像素 ×5 左右、亮色 ×2;红、金、橄榄绿这类面积小的点睛色加权也抢不到颜色时,单独给它们留调色板位(先中值切分出约 240 色,再从这类像素里单独切 6–14 色补上;饱和色多的可按色相区等量抽样,单独分几十色)。
+ - 大片渐变、深色上的反光出色带:量化前每帧叠同一张固定的 4×4 Bayer 抖动(约 ±2.4 级)。
+ - 满屏网点或硬边像素(漫画网点、低多边形)缩到 720 宽时用 BOX 不用 LANCZOS,否则网点成摩尔纹、硬边出振铃,体积也更大。
+ - 满屏细纹理(灰泥、石子、玻璃)每次叠化都会改掉大半像素:叠化帧里和屏上已显示颜色只差一点(约 10/255)的像素沿用上一帧、记成透明,自检按实际显示的帧逐帧比对;墓室壁画、马赛克、彩色玻璃花窗都是靠这一条(再加各自的小改动,见第三节)把动图从 3 MB 多压到 2 MB 以下。
- 形变动画可以直接出真动画:`Morph.at(keys, T)` 给出全局时间 T 的轮廓,逐帧渲染即可。
- 更细的逐笔动画:把一组笔画单独画到透明层上导出,再用 Motion Canvas 遮罩按顺序显现。这个还没做成现成接口。
@@ -732,6 +1347,22 @@ lib/aurora.py 弥散玻璃(弥散渐变 · 玻璃拟态)
lib/bauhaus.py 包豪斯几何(丝网印刷海报)
lib/synthwave.py 复古 Synthwave
lib/perler.py 拼豆(钉板、熔珠小管、熨烫融合)
+lib/petroglyph.py 岩画(凿刻砂岩:沙漠漆、锤击凹坑、磨刻、剥落)
+lib/tomb.py 古埃及墓室壁画(灰泥、红格红稿、分栏、象形文字、剥落)
+lib/mosaic.py 罗马马赛克(底稿取色、沿轮廓排石、光环、灰缝、铭牌、脱落)
+lib/stainedglass.py 彩色玻璃花窗(玻璃切块、grisaille 彩绘与银染、铅条焊点、透光)
+lib/illuminated.py 泥金手抄本(羊皮纸、宽头鹅毛笔哥特体、打磨金箔、尺规图解)
+lib/codex.py 达·芬奇手稿(铁胆墨水鹅毛笔、左手排线、红粉笔、尖笔圆规、镜像手写、机械零件分解图)
+lib/silhouette.py 剪影(黑纸剪影、薄金粉、椭圆金框、木版印花墙纸)
+lib/letterpress.py 凸版印刷海报(木活字、红黑双色错版、木刻插图)
+lib/constructivism.py 苏联构成主义(红黑两版、套印错位、网点照片拼贴、剪刀留边、折痕老化)
+lib/artdeco.py 装饰艺术(Art Deco 流线型海报:喷枪渐变 + 遮片硬边、交替射线、阶梯高楼、3D 流线型列车、Deco 字母)
+lib/comic.py 黄金时代漫画(毛笔墨线、Ben-Day 网点、四色错版、新闻纸)
+lib/popart.py 波普丝网(沃霍尔式:手涂撞色平涂、错位的照相黑版、刮印的墨不匀)
+lib/lineprinter.py ASCII 字符画(行式打印机:绿条连续纸、按区域选字、叠打、色带渐淡)
+lib/lowpoly.py 低多边形(1999 年代 3D:软件光栅化、平面着色、仿射贴图、逐顶点雾、15 位色抖动、点阵 HUD)
+lib/stencil.py 喷漆模板涂鸦(清水混凝土墙、卡纸模板与桥、喷雾、滴痕)
+lib/patch.py 刺绣徽章(牛仔斜纹、填充绣 / 缎面绣、锁边、热切边、手缝针线)
examples/*.py 范例脚本;*.jpg 成品;drawing_*.gif 逐步画出的动图
中文字体:自动找 Kaiti/Songti(macOS)、Noto CJK(Linux)、KaiTi/SimSun(Windows),或设 INKPAINT_FONT
西文字体(后来新增的画风用):core.latin_font(style) 按 sans / sans_bold / rounded / script / hand / typewriter 等找系统字体,可用 INKPAINT_FONT_<STYLE> 指定;字体文件不要放进仓库
diff --git a/examples/artdeco_express.jpg b/examples/artdeco_express.jpg
new file mode 100644
index 0000000..bdd9d36
Binary files /dev/null and b/examples/artdeco_express.jpg differ
diff --git a/examples/artdeco_express.py b/examples/artdeco_express.py
new file mode 100644
index 0000000..bea08ff
--- /dev/null
+++ b/examples/artdeco_express.py
@@ -0,0 +1,88 @@
+"""Example (Art Deco / Streamline poster): NIGHT EXPRESS — a 1930s airbrushed railway poster for a (fictional)
+overnight train from the city to the coast. It tells one small thing: the night express pulls out at 23:40 -- the
+clock on the tallest tower says twenty to twelve -- and runs out of the lit city over the river viaduct toward
+the coast, sleeping-car blinds already half drawn. A full moon rises over the stepped skyline inside a sunburst of
+alternating rays, searchlights sweep the sky, the river mirrors it all in ripple dashes; the streamlined
+locomotive (bullet nose, gold speed stripes that converge on the nose) comes at us with its headlamp beam.
+Every surface is a sprayed gradient through a cut frisket -- no outlines anywhere. No image model.
+python3 artdeco_express.py [out.jpg] [--stages DIR]
+"""
+import os, sys, time
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+from artdeco import ArtDeco, GOLD, IVORY
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'artdeco_express.jpg'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+t0 = time.time()
+
+a = ArtDeco(1920, 1080, seed=1938)
+W, H = a.W, a.H
+HZ = 690 # horizon row (the camera is level)
+MX, MY, MR = 1190, 432, 100 # the moon
+
+# ---- 1. the sky: one long airbrushed fade, midnight blue down to the green glow over the city
+a.sky([(0, '#060d24'), (0.38, '#0d1f3f'), (0.72, '#1b4a5c'), (1, '#4c9488')], bottom=HZ)
+a.stage('sky')
+
+# ---- 2. moonburst: alternating rays, then the moon and its halo
+a.burst(MX, MY, rays=40, contrast=0.13, reach=1300, colour='#cfeadb', glow=0.55, phase=4.5, bottom=HZ)
+a.moon(MX, MY, MR)
+a.stage('moonburst')
+
+# ---- 3. the far city in the haze, searchlights behind it
+for x, ang, ln in ((1560, 116, 900), (840, 62, 820), (1720, 98, 700)):
+ a.searchlight(x, HZ - 210, ang, ln, spread=1.7, strength=0.2)
+far = [(640, 70, 150), (700, 60, 210), (760, 80, 120), (905, 70, 230), (990, 64, 170), (1060, 76, 220),
+ (1300, 70, 200), (1370, 60, 250), (1590, 80, 230), (1680, 60, 280), (1760, 90, 190), (1850, 70, 250)]
+for x, w, h in far:
+ a.tower(x, HZ, [(w, h * 0.6), (w * 0.72, h * 0.28), (w * 0.45, h * 0.12)], far=0.72, flutes=3, windows=0.12,
+ light=-1 if x < MX else 1, ledge=2)
+a.stage('far_city')
+
+# ---- 4. the near towers: set-backs, fluting, lit windows; the clock tower says 11:40
+a.tower(820, HZ, [(120, 140), (92, 70), (60, 50)], flutes=4, windows=0.4, light=-1, spire=110, spire_w=22,
+ far=0.25)
+a.tower(985, HZ, [(110, 190), (80, 80), (52, 46)], flutes=5, slits=4, light=-1, spire=60, far=0.2)
+a.tower(1290, HZ, [(96, 120), (70, 70)], flutes=4, windows=0.3, light=1, far=0.35)
+cx, cy = a.tower(1470, HZ, [(170, 170), (132, 80), (100, 64)], flutes=6, windows=0.45, light=1, ledge=3,
+ top_windows=False)
+a.clock(cx, cy + 33, 23, 11, 40) # departure time: twenty to twelve
+top = a.crown(cx, cy, 100, steps=3)
+a.tower(cx, top + 3, [(6, 3)], mast=22, ledge=0)
+a.tower(1665, HZ, [(150, 160), (110, 110), (70, 56)], flutes=5, slits=5, light=1, spire=90, spire_w=20, far=0.15)
+a.tower(1835, HZ, [(140, 240), (96, 80)], flutes=4, windows=0.35, light=1, far=0.3)
+a.stage('towers')
+
+# ---- 5. the river: mirrors the sky and the city in ripple dashes
+a.water(HZ, stops=((0, '#1f5560'), (0.35, '#0f2c40'), (1, '#050b1d')), reflect=0.7)
+a.stage('river')
+
+# ---- 6-8. the streamliner on its viaduct: friskets, modelling, lights
+a.camera(f=1500, cx=960, horizon=HZ, height=12.0)
+r = a.express(nose=(-6.9, 23.8), vp_x=1180, cars=9, moon=(MX, MY))
+a.frisket(r)
+a.stage('friskets')
+a.model(r)
+a.stage('modelling')
+a.lights(r, beam_len=760, reflect=False)
+a.stage('lights')
+
+# ---- 9. lettering, small print, gilt border
+title = 'NIGHT EXPRESS'
+cap = 124
+wt = a.deco_width(title, cap, track=0.16)
+a.lettering(title, W / 2, 228, cap, track=0.16, anchor='m', shadow=(6, 6))
+sw = a.caption('OVERNIGHT · FROM THE CITY TO THE COAST', W / 2, 286, 25, colour='#e9dcbc', track=0.42,
+ anchor='ms')
+a.rule(W / 2 - wt / 2, W / 2 - sw / 2 - 28, 277, 2, GOLD)
+a.rule(W / 2 + sw / 2 + 28, W / 2 + wt / 2, 277, 2, GOLD)
+a.caption('DEPARTS 23:40', 1880 - 60, 1000, 30, colour=IVORY, track=0.36, anchor='rs')
+a.caption('SLEEPING CARS · DINING CAR · ARRIVES AT DAWN', 1880 - 60, 1036, 19, colour='#d8c9a4', track=0.38,
+ anchor='rs')
+a.border()
+a.stage('lettering')
+
+# ---- the print
+a.finish()
+a.save(out, stages_dir=stages)
+print(f'{out} {time.time() - t0:.1f}s')
diff --git a/examples/codex_ornithopter.jpg b/examples/codex_ornithopter.jpg
new file mode 100644
index 0000000..1d34e64
Binary files /dev/null and b/examples/codex_ornithopter.jpg differ
diff --git a/examples/codex_ornithopter.py b/examples/codex_ornithopter.py
new file mode 100644
index 0000000..fe2f97e
--- /dev/null
+++ b/examples/codex_ornithopter.py
@@ -0,0 +1,353 @@
+"""Example (Leonardo-style codex page / 达·芬奇手稿): 扑翼机 · The Ornithopter — one leaf of an engineer's notebook
+working out how a machine could beat its wings like a bird. Upper left, the idea: little birds drawn in flight
+through one wing-beat, and a red-chalk study of a bird's wing from below (bones along the leading edge, fanned
+primaries, coverts). Centre, the answer: a bat-winged flying machine seen from below -- the right wing fully
+worked (cane spars with lashings, hinged elbow and wrist, finger ribs, cords over a pulley, a membrane hatched
+'\\' by a left hand so that each panel billows), the left wing left half-done over its leadpoint underdrawing.
+Upper right, the geometry: a compass-scored proportion circle, the front view of the stroke -- wings up and down,
+the swept sector hatched, the short lever arm that is a quarter of the wing. Lower right, an exploded view of
+the drive: crank, lantern pinion, crown wheel and the pulley that winds the cord. A close-up of the wrist joint,
+a rejected wing struck out, mirror-written pseudo-Italian notes, blots, foxing, a water stain.
+Draw-on stages: the blank leaf -> stylus & leadpoint construction -> the bird -> the frame -> hatching ->
+the proportion circle -> the drive & joint -> the notes -> corrections and blots. No image model.
+python3 codex_ornithopter.py [out.jpg] [--stages DIR]
+"""
+import os, sys, time
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from codex import Codex, Camera, crown, lantern, crank, cylinder, pulley, merge
+from core import curve, spline, blur
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'codex_ornithopter.jpg'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+t0 = time.time()
+
+c = Codex(1920, 1080, seed=7)
+c.sheet(stains=[(170, 985, 205)], lost_corner='br')
+c.show_through(1080, 590, 560, lines=6, size=21) # the verso's writing, seen through the leaf
+c.stage('carta')
+
+MX = 960 # the machine's centre line
+mir = lambda p: (2 * MX - p[0], p[1])
+
+# ------------------------------------------------------------------ geometry of the machine (right wing)
+S, E, WR, T = (1004, 300), (1146, 248), (1272, 234), (1470, 286) # shoulder, elbow, wrist, tip
+TIPS = [T, (1436, 382), (1356, 452), (1252, 500), (1128, 520), (996, 500)] # rib tips along the trailing edge
+RIBS = [(WR, TIPS[1]), (WR, TIPS[2]), (WR, TIPS[3]), (E, TIPS[4])]
+BODY_R = [(MX, 166), (976, 200), (988, 262), (992, 332), (989, 432), (980, 522), (970, 582), (MX, 604)]
+BODY = BODY_R + [mir(p) for p in BODY_R[-2:0:-1]]
+HUB = (MX, 412)
+TAIL = (MX, 604)
+TAIL_TIPS = [(MX + np.cos(np.deg2rad(a)) * L, 604 + np.sin(np.deg2rad(a)) * L)
+ for a, L in zip(np.linspace(58, 122, 7), [100, 112, 120, 122, 120, 112, 100])]
+
+
+def scallop(p, q, k=0.12, toward=None):
+ """membrane edge between two rib tips: sags in toward the wing (toward a point inside it)"""
+ p, q = np.asarray(p, np.float32), np.asarray(q, np.float32)
+ d = q - p
+ L = float(np.hypot(*d))
+ nrm = np.array([-d[1], d[0]]) / (L + 1e-6)
+ inside = np.asarray(toward if toward is not None else ((WR if p[0] > MX else mir(WR))), np.float32)
+ sgn = 1.0 if np.dot(inside - (p + q) / 2, nrm) > 0 else -1.0
+ return curve(p, q, sgn * L * k, 26)
+
+
+def leading_edge(mirror=False):
+ P = spline([S, (1074, 262), E, (1210, 232), WR, (1372, 248), T], 10)
+ return np.array([mir(p) for p in P]) if mirror else P
+
+
+# ------------------------------------------------------------------ 1. construction: stylus, compass, leadpoint
+c.incise([(MX, 140), (MX, 740)], 0.9, smooth=False) # the centre line
+c.incise([(470, 300), (1470, 300)], 0.8, smooth=False) # the shoulder line
+for sgn in (1, -1):
+ sx = MX + sgn * 46
+ c.compass(sx, 300, 466, -13 if sgn > 0 else 167, 11 if sgn > 0 else 193, 0.7) # the wing's reach
+O, R, r_lever = (1690, 292), 148, 37
+c.compass(*O, R)
+c.compass(*O, r_lever, prick=False)
+c.incise([(1515, 292), (1866, 292)], 0.9, smooth=False)
+c.incise([(1690, 120), (1690, 470)], 0.7, smooth=False)
+# leadpoint: the whole machine searched out lightly before the pen
+for m in (False, True):
+ f = (lambda p: mir(p)) if m else (lambda p: p)
+ c.leadpoint(leading_edge(m) + c.rng.normal(0, 1.5, 2), 1.1, 0.55)
+ for a, b in RIBS: c.leadpoint(curve(f(a), f(b), 10, 16) + c.rng.normal(0, 2, 2), 1.0, 0.5)
+ for p, q in zip(TIPS[:-1], TIPS[1:]): c.leadpoint(scallop(f(p), f(q)) + c.rng.normal(0, 2.5, 2), 1.0, 0.5)
+c.leadpoint(np.vstack([BODY, BODY[:1]]) + 2, 1.0, 0.5, smooth=True)
+c.stage('costruzione')
+
+# ------------------------------------------------------------------ 2. the bird: flight sequence + red-chalk wing
+path = [(92, 128), (190, 108), (290, 132), (392, 112), (500, 126)]
+for (x, y), ph in zip(path, [np.pi / 2, np.pi / 7, -np.pi / 3, -np.pi / 2, np.pi / 4]):
+ c.bird(x, y, 30, ph, 0.85)
+c.dotted(spline([(70, 150), (190, 136), (290, 158), (392, 138), (540, 150)], 10), 4, 7, 1.1, 0.55)
+c.arrow([(548, 146), (575, 140), (604, 134)], 1.6, 0.85, 10)
+
+
+def bird_wing(ox, oy, k):
+ """red-chalk study of a kite's wing seen from below, pointing left: bones along the leading edge, primaries
+ fanned from the hand, secondaries from the forearm, two rows of coverts; nominal geometry scaled by k"""
+ T_ = lambda p: (ox + p[0] * k, oy + p[1] * k)
+ Sh, El, Wb, Ht = (0, 0), (-80, -34), (-178, -28), (-270, 8)
+ lerp = lambda p, q, u, dy=0: (p[0] + (q[0] - p[0]) * u, p[1] + (q[1] - p[1]) * u + dy)
+ spec = [(lerp(Sh, El, i / 3, 6), 84 + 4 * i, 128 + 8 * i, 30, 0.45) for i in range(3)]
+ spec += [(lerp(El, Wb, i / 7, 5), 96 + 1.6 * i, 166 + 1.5 * i, 30, 0.45) for i in range(8)]
+ lens = [186, 204, 220, 232, 238, 234, 220, 198, 166] # the outer primaries splay into 'fingers'
+ spec += [(lerp(Wb, Ht, 0.05 + 0.95 * i / 8), 116 + 7 * i, lens[i], 26 - 0.8 * i, 0.34) for i in range(9)]
+ shade_m = np.zeros((c.H, c.W), np.float32)
+ shade_v = np.zeros((c.H, c.W), np.float32)
+ for b, ang, L, wd, ld in spec:
+ ang += c.rng.normal(0, 1.6); L *= c.rng.uniform(0.96, 1.04)
+ poly, rach, edge = c.feather(T_(b), ang, L * k, wd * k, curl=0.05, lead=ld, pressure=c.rng.uniform(0.62, 0.8), side=-1,
+ overlapped=True)
+ pm = c.poly_mask(poly)
+ t = c.between(rach[0], rach[-1], edge[len(edge) // 3], edge[2 * len(edge) // 3])
+ upd = pm > shade_m
+ shade_v[upd] = t[upd]; shade_m = np.maximum(shade_m, pm)
+ # tone: the broad vane darkens toward its edge, where the next feather shades it
+ c.hatch(shade_m, np.clip(shade_v * 1.15 - 0.15, 0, 1) * 0.9, angle=55, spacing=4.6, levels=(0.42, 0.66), cross=None,
+ width=1.6, ink=0.6, length=(14, 28), medium='chalk')
+ # coverts: rows of short rounded feathers, only their lower edges drawn, rubbed into a soft band
+ cov = np.zeros((c.H, c.W), np.float32)
+ for L, wd, off, n in [(70, 15, 16, 13), (40, 11, 4, 15)]:
+ for i in range(n):
+ u = i / (n - 1)
+ b = lerp(Sh, Wb, u / 0.45, off) if u < 0.45 else lerp(Wb, Ht, (u - 0.45) / 0.55, off)
+ ang = np.deg2rad(86 + 18 * min(1, u / 0.45) + (40 * (u - 0.45) / 0.55 if u >= 0.45 else 0))
+ d, nv = np.array([np.cos(ang), np.sin(ang)]), np.array([-np.sin(ang), np.cos(ang)])
+ bb = np.array(T_(b)); Lk, wk = L * k, wd * k
+ u_pts = [bb + d * Lk * 0.45 - nv * wk, bb + d * Lk * 0.92 - nv * wk * 0.55, bb + d * Lk, bb + d * Lk * 0.92 + nv * wk * 0.55,
+ bb + d * Lk * 0.45 + nv * wk]
+ c.sanguine(u_pts, 2.0, 0.6)
+ cov = np.maximum(cov, c.poly_mask([bb - nv * wk, *u_pts, bb + nv * wk]))
+ c.rub(cov, 0.2, 3.0)
+ c.hatch(cov, 0.5, angle=55, spacing=5.0, levels=(0.3,), cross=None, width=1.5, ink=0.45, length=(10, 20), medium='chalk')
+ for i in range(3): # the alula at the wrist
+ c.feather(T_((Wb[0] - 2, Wb[1] - 4)), 196 + 9 * i, (52 - 8 * i) * k, 8 * k, curl=-0.05, pressure=0.7, line=2.0, rachis=False)
+ arm = spline([T_(Sh), T_((-40, -22)), T_(El), T_((-130, -36)), T_(Wb), T_((-226, -16)), T_(Ht)], 10)
+ c.sanguine(arm, 4.4, 0.95)
+ c.sanguine(arm + [0, 4], 2.6, 0.6)
+
+
+def feather_study(x0, y0, length, width):
+ """one primary feather, large, pointing left: the bare quill, rachis, both vanes with their barbs drawn as
+ fine chalk lines, a couple of splits where the barbs have parted"""
+ poly, rach, edge = c.feather((x0, y0), 186, length, width, curl=0.05, lead=0.4, pressure=0.85, side=-1, line=2.4)
+ a = np.deg2rad(6)
+ c.sanguine([(x0, y0), (x0 + np.cos(a) * 46, y0 + np.sin(a) * 46)], 2.6, 0.9) # the bare quill (calamus)
+ idx = np.linspace(0, len(rach) - 1, int(length / 2.6)).astype(int) # a barb every ~2.6 px
+ tg = np.gradient(rach, axis=0); tg /= np.linalg.norm(tg, axis=1, keepdims=True) + 1e-6
+ nv = np.stack([-tg[:, 1], tg[:, 0]], 1) * -1
+ n = len(idx)
+ gaps = set(range(int(n * 0.40), int(n * 0.43))) | set(range(int(n * 0.66), int(n * 0.68))) # where barbs have parted
+ strokes = []
+ for k, i in enumerate(idx[2:-3]):
+ u = k / n
+ for sgn, wf in ((1, 1.0), (-1, 0.4)):
+ if sgn == 1 and k in gaps: continue
+ w_ = np.linalg.norm(edge[i] - rach[i]) * wf * c.rng.uniform(0.86, 0.98)
+ p0 = rach[i]; p1 = p0 + nv[i] * sgn * w_ + tg[i] * w_ * (0.75 - 0.3 * u)
+ strokes.append([p0, (p0 + p1) / 2 + nv[i] * sgn * 1.5 - tg[i] * 1.2, p1])
+ c.sanguines(strokes, 0.95, 0.44, True, 0.15)
+
+
+bird_wing(402, 230, 0.82)
+feather_study(392, 482, 320, 40)
+c.stage('uccello')
+
+# ------------------------------------------------------------------ 3. the frame of the machine
+# body: an almond-shaped cradle with cross bars, the crank housing in the middle
+c.contour(np.vstack([BODY, BODY[:2]]), 2.4, 1.0, searching=1)
+bars = []
+for y, hw in [(236, 22), (300, 44), (488, 24), (560, 12)]:
+ bars.append(c.cane((MX - hw, y), (MX + hw, y), 7, 7, 0, (), 1.5, 0.95, cap=False))
+c.quill(c.arc(*HUB, 31), 2.2, 1.0, False, 0.2)
+gear_pts = []
+for k in range(48):
+ a = 2 * np.pi * k / 48
+ rr = 25 if (k // 2) % 2 == 0 else 20
+ gear_pts.append((HUB[0] + np.cos(a) * rr, HUB[1] + np.sin(a) * rr))
+c.quill(np.vstack([gear_pts, gear_pts[:1]]), 1.4, 0.9, False, 0.15)
+c.quill(c.arc(*HUB, 6), 1.6, 1.0, False, 0.1)
+for sgn in (1, -1): # the pilot's crank handles
+ c.cane((MX + sgn * 30, HUB[1] + 6), (MX + sgn * 64, HUB[1] + 34), 6, 5, 0, (), 1.4, 0.9)
+
+# right wing: spars, finger ribs, hinges, the membrane's scalloped edge
+spars = [c.cane(S, E, 10, 8, -10, (0.5,), 1.9), c.cane(E, WR, 8, 7, -6, (0.5,), 1.9), c.cane(WR, T, 7, 3, -10, (0.45,), 1.8)]
+ribs = [c.cane(a, b, 6, 2.4, 12, (0.35,), 1.6) for a, b in RIBS]
+edge = [scallop(p, q) for p, q in zip(TIPS[:-1], TIPS[1:])]
+for e in edge: c.contour(e, 1.7, 0.95, searching=1, spread=1.6)
+c.quill([S, TIPS[-1]], 1.6, 0.9)
+for p, rr in [(S, 8), (E, 7), (WR, 7)]:
+ c.quill(c.arc(p[0], p[1], rr), 1.8, 1.0, False, 0.15)
+ c.blot(p[0], p[1], 1.6, 0.9, 0)
+c.quill(c.arc(WR[0] - 2, WR[1] + 18, 13), 1.7, 1.0, False, 0.2) # the pulley under the wrist
+c.quill(c.arc(WR[0] - 2, WR[1] + 18, 8), 1.2, 0.8, False, 0.2)
+# cords: from the crank housing over the shoulder, along the spar, round the pulley to each finger
+cord = spline([HUB, (985, 360), (S[0] + 4, S[1] + 14), (1090, 270), (E[0] + 4, E[1] + 16), (1250, 258), (WR[0] - 14, WR[1] + 22)], 10)
+c.quill(cord, 1.1, 0.8, True, 0.3)
+for a, b in RIBS[:3]:
+ m_ = (a[0] * 0.45 + b[0] * 0.55, a[1] * 0.45 + b[1] * 0.55)
+ c.quill([(WR[0] + 8, WR[1] + 26), ((WR[0] + m_[0]) / 2 + 4, (WR[1] + m_[1]) / 2 + 8), m_], 1.0, 0.75, True, 0.3)
+
+# tail: a fan of ribs with a scalloped edge
+for tp in TAIL_TIPS: c.cane(TAIL, tp, 4, 1.8, 0, (), 1.3, 0.85, cap=False)
+for p, q in zip(TAIL_TIPS[:-1], TAIL_TIPS[1:]): c.quill(scallop(p, q, 0.16, TAIL), 1.4, 0.85)
+
+# left wing: only begun -- single light lines over the leadpoint, edge half drawn
+c.quill(leading_edge(True), 1.7, 0.6)
+for a, b in RIBS: c.quill(curve(mir(a), mir(b), -12, 16), 1.3, 0.5)
+for i, (p, q) in enumerate(zip(TIPS[:-1], TIPS[1:])):
+ if i in (0, 3, 4): c.quill(scallop(mir(p), mir(q)), 1.3, 0.5)
+for p in (S, E, WR): c.quill(c.arc(mir(p)[0], mir(p)[1], 6), 1.4, 0.6, False, 0.2)
+# a scale of braccia under the right wing
+c.ruled((1112, 596), (1412, 596), 1.5, 0.85)
+for i in range(7):
+ x = 1112 + i * 50
+ c.quill([(x, 590), (x, 603 if i % 2 == 0 else 599)], 1.3, 0.85, False, 0.05)
+c.hatch(c.poly_mask([(1112, 593), (1162, 593), (1162, 599), (1112, 599)]), 0.8, spacing=2.6, levels=(0.3,), cross=None, ink=0.8,
+ length=(6, 8))
+c.stage('telaio')
+
+# ------------------------------------------------------------------ 4. hatching: the membrane billows between ribs
+canes = np.zeros((c.H, c.W), np.float32)
+for p in spars + ribs + bars: canes = np.maximum(canes, c.poly_mask(p))
+canes = np.clip(blur(canes, 1.5) * 3, 0, 1)
+panels = [np.vstack([curve(WR, T, -10, 20), edge[0], curve(TIPS[1], WR, -12, 20)]),
+ np.vstack([curve(WR, TIPS[1], 12, 20), edge[1], curve(TIPS[2], WR, -12, 20)]),
+ np.vstack([curve(WR, TIPS[2], 12, 20), edge[2], curve(TIPS[3], WR, -12, 20)]),
+ np.vstack([curve(WR, TIPS[3], 12, 20), edge[3], curve(TIPS[4], E, -12, 20), curve(E, WR, -6, 12)]),
+ np.vstack([curve(E, TIPS[4], 12, 20), edge[4], [S], curve(S, E, -10, 16)])]
+pairs = [((WR, T), RIBS[0]), (RIBS[0], RIBS[1]), (RIBS[1], RIBS[2]), (RIBS[2], RIBS[3]), (RIBS[3], (S, TIPS[-1]))]
+for poly, (ra, rb) in zip(panels, pairs):
+ m = c.poly_mask(poly) * (1 - canes)
+ t = c.between(ra[0], ra[1], rb[0], rb[1])
+ sh = np.clip(0.92 * t ** 2.0, 0, 1)
+ c.hatch(m, sh, spacing=5.0, levels=(0.3, 0.56), cross=0.84, ink=0.72)
+# body: rounded, darker toward the right
+bm = c.poly_mask(BODY) * (1 - canes) * (1 - c.disc_mask(*HUB, 33))
+c.hatch(bm, np.clip(0.12 + 0.75 * c.between((MX - 40, 0), (MX - 40, 1), (MX + 40, 0), (MX + 40, 1)) ** 1.3, 0, 1), spacing=4.6,
+ levels=(0.3, 0.55), cross=0.82, ink=0.7)
+# tail membrane, lightly
+tm = c.poly_mask(np.vstack([[TAIL], np.vstack([scallop(p, q, 0.16, TAIL) for p, q in zip(TAIL_TIPS[:-1], TAIL_TIPS[1:])])]))
+c.hatch(tm, 0.4, spacing=5.5, levels=(0.3,), cross=None, ink=0.6)
+# left wing: a patch of hatching begun near the body and abandoned
+YY, XX = np.mgrid[0:c.H, 0:c.W].astype(np.float32)
+lm = c.poly_mask([mir(p) for p in panels[4]]) * ((YY < 420) & (XX > MX - 150))
+c.hatch(lm, np.clip(0.95 - (MX - 30 - XX) / 150 - np.clip(YY - 330, 0, 99) / 140, 0, 1), spacing=5.2, levels=(0.4,), cross=None,
+ ink=0.62, length=(18, 30))
+c.stage('tratteggio')
+
+# ------------------------------------------------------------------ 5. the proportion circle: the stroke seen from the front
+ox, oy = O
+c.quill(c.arc(ox, oy, R, -150, 30, step=2), 1.9, 0.95, False, 0.12)
+c.quill(c.arc(ox, oy, R, 28, 212, step=2), 1.9, 0.9, False, 0.12)
+c.quill(c.arc(ox, oy, r_lever, 0, 362, step=1.5), 1.4, 0.85, False, 0.1)
+c.ruled((1522, oy), (1862, oy), 1.1, 0.6)
+c.ruled((ox, 132), (ox, 458), 1.0, 0.5)
+UP, DN = -36, 22
+P_ = lambda ang, rad: (ox + np.cos(np.deg2rad(ang)) * rad, oy + np.sin(np.deg2rad(ang)) * rad)
+sector = np.vstack([[O], c.arc(ox, oy, R, UP, DN)])
+c.hatch(c.poly_mask(sector) * (1 - c.disc_mask(ox, oy, r_lever + 3)), 0.5, spacing=6, levels=(0.3,), cross=None, ink=0.55)
+for ang in (DN, 180 - DN): # wings down: drawn as canes (front view of the spar)
+ c.cane(P_(ang, 10), P_(ang, R), 8, 3, 0, (0.5,), 1.7)
+for ang in (UP, 180 - UP): # wings up: a lighter, dashed position
+ c.dotted([P_(ang, 12), P_(ang, R)], 9, 6, 1.5, 0.8)
+for ang in (DN + 180, UP + 180): # the short lever beyond the pivot
+ c.quill([O, P_(ang, r_lever)], 3.0, 1.0, False, 0.1)
+ c.blot(*P_(ang, r_lever), 2.0, 0.9, 0)
+for i in range(1, 4): # the wing divided into four lever-lengths
+ p = P_(DN, r_lever * i); n_ = np.deg2rad(DN + 90)
+ c.quill([(p[0] - np.cos(n_) * 6, p[1] - np.sin(n_) * 6), (p[0] + np.cos(n_) * 6, p[1] + np.sin(n_) * 6)], 1.3, 0.9, False, 0.1)
+for a in range(-40, 31, 6): # degree ticks on the rim
+ p0, p1 = P_(a, R + 2), P_(a, R + (9 if a % 30 == 0 else 5))
+ c.quill([p0, p1], 1.1, 0.8, False, 0.05)
+c.arrow(c.arc(ox, oy, R + 18, UP + 3, DN - 3)[::-1], 1.5, 0.9, 9)
+c.arrow(c.arc(ox, oy, R + 18, UP + 3, DN - 3), 1.5, 0.9, 9)
+c.prick(ox, oy, 1.4)
+c.stage('cerchio')
+
+# ------------------------------------------------------------------ 6. the drive, exploded; the wrist joint close up
+cam = Camera(1520, 818, 1.0, azim=22, elev=29)
+wheel = crown(104, 14, teeth=18, tooth_h=19, tooth_w=13)
+axle_v = cylinder(8, 112, 16, 'axle_end', 'axle', -112)
+pul = pulley(28, 32).place((0, 0, -164))
+pinion = lantern(30, 60, 8).place((-30, 92, 126), axis=(1, 0, 0))
+shaft = cylinder(6.5, 250, 16, 'shaft_end', 'shaft').place((-206, 92, 126), axis=(1, 0, 0))
+handle = crank(58, 6.5, 60, 9.0).place((-262, 92, 126), axis=(-1, 0, 0), spin=90)
+drive = merge(wheel.named('wheel'), axle_v.named('axle'), pul.named('pulley'), pinion.named('pinion'), shaft.named('shaft'),
+ handle.named('crank'))
+c.solid(drive, cam, width=2.0, hatch=dict(spacing=4.4, levels=(0.3, 0.56), cross=0.84),
+ hatch_groups={'pinion.disc': dict(levels=(0.45,)), 'wheel.face': dict(levels=(0.5,), cross=None)})
+pr = lambda p: cam.project(np.array([p], np.float32))[0][0]
+c.dotted([pr((-254, 92, 126)), pr((-212, 92, 126))], 7, 5, 1.2, 0.7, dot_dash=True) # the crank slides onto the shaft
+c.dotted([pr((50, 92, 126)), pr((120, 92, 126))], 9, 5, 1.2, 0.7, dot_dash=True)
+c.dotted([pr((0, 92, 94)), pr((0, 92, 38))], 6, 5, 1.2, 0.7, dot_dash=True) # the pinion drops onto the pegs
+c.dotted([pr((0, 0, -116)), pr((0, 0, -130))], 5, 4, 1.2, 0.7, dot_dash=True) # the pulley slides up the axle
+# the cord leaves the pulley toward the wings
+p0 = pr((-28, 0, -150))
+CORD_END = (p0[0] - 150, p0[1] - 34)
+c.quill([p0, (p0[0] - 70, p0[1] - 4), CORD_END], 1.1, 0.8)
+
+# close-up of the wrist joint in a circle
+J = (768, 884)
+c.quill(c.arc(*J, 104, -80, 275, step=2), 1.4, 0.7, False, 0.3)
+jc = [c.cane((686, 916), (752, 890), 18, 16, 3, (0.35,), 1.8)]
+for b, bend in [((846, 818), 6), ((862, 892), 4), ((826, 960), -4)]:
+ jc.append(c.cane((J[0] + 6, J[1] - 2), b, 15, 10, bend, (0.55,), 1.8))
+for rr, w in [(23, 2.0), (16, 1.4)]:
+ c.quill(c.arc(J[0], J[1] - 1, rr), w, 1.0, False, 0.15)
+c.blot(J[0], J[1] - 1, 3.2, 1.0, 0)
+c.quill(spline([(690, 856), (730, 862), (J[0] - 4, J[1] - 24), (J[0] + 18, J[1] - 16)], 10), 1.2, 0.85)
+c.quill(spline([(694, 866), (732, 870), (J[0] - 10, J[1] - 22)], 10), 1.0, 0.75)
+for p in jc:
+ pm = c.poly_mask(p)
+ q = p[: len(p) // 2]
+ t = c.between(q[0], q[-1], p[-1], p[len(p) // 2])
+ c.hatch(pm * (1 - c.disc_mask(J[0], J[1] - 1, 25)), np.clip(t * 1.1 - 0.1, 0, 1), spacing=3.8, levels=(0.4, 0.66), cross=None,
+ ink=0.75, length=(10, 20))
+# a rejected idea: a wing of hinged boards (louvres), struck out later
+REJ = (936, 806)
+c.quill([(REJ[0], REJ[1] + 44), (REJ[0] + 128, REJ[1])], 2.0, 0.95)
+c.quill([(REJ[0] + 4, REJ[1] + 82), (REJ[0] + 126, REJ[1] + 50)], 1.6, 0.9)
+lv = []
+for i in range(6):
+ x = REJ[0] + 10 + i * 20; y = REJ[1] + 41 - i * 6.6
+ c.quill([(x, y), (x + 9, y + 36 - i * 1.2)], 1.5, 0.9)
+ lv.append([(x, y), (x + 9, y + 36 - i * 1.2), (x + 20, y + 30 - i * 1.2), (x + 11, y - 6.6)])
+for q in lv[1::2]: c.hatch(c.poly_mask(q), 0.6, spacing=3.6, levels=(0.3,), cross=None, ink=0.7, length=(8, 14))
+c.stage('ingranaggi')
+
+# ------------------------------------------------------------------ 7. the notes, mirror-written right to left
+c.write(['Dell ala che batte e del suo moto'], 1452, 104, size=29, ink=1.0)
+c.write(c.prose(14), 1452, 140, width=470, size=19, max_lines=1)
+c.write(c.prose(70), 566, 586, width=486, size=20, max_lines=7)
+c.write(c.prose(40), 1866, 512, width=392, size=19, max_lines=4)
+c.write(c.prose(100), 616, 812, width=548, size=20, max_lines=9)
+c.write(c.prose(60), 1868, 676, width=196, size=19, max_lines=14)
+for s_, p in [('a', (S[0] + 8, S[1] - 18)), ('b', (E[0] + 2, E[1] - 20)), ('c', (WR[0] + 4, WR[1] - 18)), ('d', (T[0] + 16, T[1] + 4)),
+ ('n', (1060, 286)), ('m', (MX + 46, HUB[1] - 18))]:
+ c.label(s_, *p, size=22)
+for s_, p in [('a', (ox - 14, oy - 8)), ('b', P_(UP, R + 34)), ('c', P_(DN, R + 34)), ('d', P_(UP + 180, r_lever + 16)), ('1', P_(DN, r_lever - 2)),
+ ('4', P_(DN, R - 18))]:
+ c.label(s_, p[0], p[1] + 7, size=21)
+for s_, p in [('e', pr((-262, 92, 200))), ('f', pr((-30, 92, 186))), ('g', pr((112, -70, 20))), ('h', pr((46, 0, -160)))]:
+ c.label(s_, p[0], p[1], size=22)
+c.label('c', J[0] - 96, J[1] - 70, size=24)
+c.label('n', CORD_END[0] - 12, CORD_END[1] + 4, size=22)
+for i, n_ in enumerate(['0', '2', '4', '6']):
+ c.label(n_, 1112 + i * 100, 624, size=18)
+c.label('37', 1842, 72, size=22, ink=0.55, mirror=False) # a later collector's folio number
+c.stage('note')
+
+# ------------------------------------------------------------------ 8. corrections and accidents
+c.strike(REJ[0] - 4, REJ[1] - 4, REJ[0] + 132, REJ[1] + 86, n=3, width=1.9)
+c.blot(1212, 132, 6.5, 1.3, 6)
+c.blot(642, 742, 3.5, 1.2, 3)
+c.spatter(1500, 470, 8, 18, 0.9)
+c.spatter(330, 590, 5, 14, 0.8)
+
+c.save(out, stages)
+print(f'{out} {time.time() - t0:.1f}s')
diff --git a/examples/comic_rocket.jpg b/examples/comic_rocket.jpg
new file mode 100644
index 0000000..5a06c61
Binary files /dev/null and b/examples/comic_rocket.jpg differ
diff --git a/examples/comic_rocket.py b/examples/comic_rocket.py
new file mode 100644
index 0000000..fe878ef
--- /dev/null
+++ b/examples/comic_rocket.py
@@ -0,0 +1,503 @@
+"""Example (golden-age comic cover / 黄金时代漫画): 火箭小队 · Rocket Squad No. 3 -- a newsstand comic cover of about
+1940, inked with a brush, coloured with Ben-Day tints on the three process plates and printed slightly out of
+register on newsprint that has gone tan.
+The story on the cover: at sunset the Rocket Squad blasts off for the moon. Captain June stands in the front
+cockpit pointing the way ("NEXT STOP -- THE MOON!"), Pip the dog rides behind her in flying goggles, ears and tongue
+flapping -- and Sparky the mechanic, who was still tightening a bolt, hangs from the rope ladder under the belly,
+wrench in hand, cap flying off, yelling "HEY!! WAIT FOR ME!!". Below: the launch tower and its beacon, billowing
+smoke, a desert of mesas and, on a butte, the squad's observatory with its telescope trained on the rocket; above:
+a banded twilight sky, stars and a big cratered moon. Cover furniture: the perspective block logo ROCKET SQUAD with
+its COMICS ribbon, a price box (No. 3, 10 cents, MAY), a caption, a sound effect. All characters, names and the title
+are invented for this example.
+Draw-on stages: newsprint -> key plate (setting) -> key plate (rocket) -> key plate (the squad) -> key plate
+(lettering) -> progressive proofs: yellow -> + red -> + blue -> the cover decades on (browned edges, spine ticks,
+staples, rubbed corner, crease, foxing). No image model.
+python3 comic_rocket.py [out.jpg] [--stages DIR]
+"""
+import os, sys, time
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from comic import (ComicCover, WHITE, CREAM, PALE, YELLOW, GOLD, ORANGE, DEEP_ORANGE, RED, PINK, SKIN, TAN, BROWN,
+ DARK_BROWN, LIGHT_BLUE, BLUE, NAVY, LIGHT_GREY, SILVER)
+from core import spline
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'comic_rocket.jpg'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+t0 = time.time()
+
+c = ComicCover(1920, 1080, seed=40, screen=11.0, misreg=4.6, slop=1.6)
+W, H = c.W, c.H
+rng = np.random.default_rng(7)
+c.paper()
+c.stage('newsprint', plates='')
+
+tube, smooth, ell = c.tube_pts, c.smooth, c.ellipse_pts
+HORIZON = 940
+
+# ================================================================ frames
+# the rocket's own frame: u runs along the axis from the tail to the nose, v across it toward the belly (px)
+T0 = np.array([600.0, 790.0], np.float32)
+TH = np.deg2rad(26)
+D = np.array([np.cos(TH), -np.sin(TH)], np.float32)
+NRM = np.array([np.sin(TH), np.cos(TH)], np.float32)
+
+
+def R(pts):
+ P = np.asarray(pts, np.float32).reshape(-1, 2)
+ return T0 + P[:, :1] * D + P[:, 1:] * NRM
+
+
+def R1(u, v):
+ return tuple(float(t) for t in R([(u, v)])[0])
+
+
+_prof = spline([(45, 80), (120, 95), (260, 102), (470, 100), (620, 86), (740, 58), (820, 28), (866, 0)], 14)
+
+
+def rad(u):
+ return float(np.interp(u, _prof[:, 0], _prof[:, 1]))
+
+
+def frame(u0, v0, rot=0.0, s=1.0):
+ """a figure's own frame (x toward the nose, y down) set into the rocket at (u0, v0), tilted rot deg"""
+ cr, sr = np.cos(np.deg2rad(rot)), np.sin(np.deg2rad(rot))
+
+ def f(pts):
+ P = np.asarray(pts, np.float32).reshape(-1, 2) * s
+ return R(np.stack([P[:, 0] * cr + P[:, 1] * sr + u0, -P[:, 0] * sr + P[:, 1] * cr + v0], 1))
+ return f
+
+
+def sheet_frame(x0, y0, rot=0.0, s=1.0):
+ cr, sr = np.cos(np.deg2rad(rot)), np.sin(np.deg2rad(rot))
+
+ def f(pts):
+ P = np.asarray(pts, np.float32).reshape(-1, 2) * s
+ return np.stack([P[:, 0] * cr + P[:, 1] * sr + x0, -P[:, 0] * sr + P[:, 1] * cr + y0], 1).astype(np.float32)
+ return f
+
+
+def feather_shape(pts, mask, length, **kw):
+ P, N = c.edge_normals(pts)
+ c.feather(P, N, length=length, clip=mask, **kw)
+
+
+# ================================================================ sky, stars, moon
+# twilight in stepped Ben-Day bands: night blue at the top, through pale, to the yellow-orange glow at the horizon
+TWILIGHT = [(1, .4, 0, 0), (.7, .2, 0, 0), (.4, 0, 0, 0), (.2, 0, 0, 0), (0, 0, .4, 0), YELLOW, GOLD, ORANGE]
+c.graded(None, TWILIGHT, (0, -10), (0, HORIZON + 10), edges=[0.15, 0.28, 0.40, 0.50, 0.57, 0.70, 0.84], wave=9)
+MX, MY, MR = 1702, 250, 166
+for i in range(80):
+ x, y = rng.uniform(20, W - 20), rng.uniform(12, 470)
+ if np.hypot(x - MX, y - MY) < MR + 16: continue
+ s = rng.uniform(4, 9) if rng.random() < 0.6 else rng.uniform(10, 17)
+ star = c.mask(c.burst_pts(x, y, s, s, 4, 0.72, int(rng.integers(1 << 30)), rot=rng.uniform(-10, 10)))
+ c.flat(star, WHITE if (rng.random() < 0.5 or y > 330) else YELLOW)
+for i in range(90):
+ x, y = rng.uniform(10, W - 10), rng.uniform(10, 380)
+ c.flat(c.circle(x, y, rng.uniform(1.6, 3.0)), WHITE)
+
+moon = c.part(ell(MX, MY, MR, MR), CREAM, width=6.5, heavy=1.1)
+c.flat(moon * np.clip(1 - c.circle(MX - 46, MY - 40, MR + 6), 0, 1), (0, 0, .4, .2)) # the night side
+for (cx, cy, rr, rot) in [(1650, 190, 34, 10), (1745, 166, 20, -5), (1772, 290, 40, 15), (1675, 318, 22, 0),
+ (1612, 258, 14, 0), (1730, 224, 11, 0), (1800, 216, 13, 0)]:
+ cr_ = c.mask(ell(cx, cy, rr, rr * 0.82, rot))
+ c.flat(cr_ * moon, (0, 0, .4, .2))
+ c.edge(ell(cx, cy, rr, rr * 0.82, rot, 30, 220), width=2.6 + rr * 0.05, heavy=0.4, taper=(0.2, 0.3))
+mP, mN = c.edge_normals(ell(MX, MY, MR, MR))
+c.feather(mP, mN, length=44, width=3.2, spacing=8, clip=moon, curl=0.1)
+
+# ================================================================ desert: mesas, plain, the butte with the HQ
+mesas = [(-20, 150, 70), (300, 520, 96)]
+for k, (xa, xb, hgt) in enumerate(mesas):
+ top = HORIZON - hgt
+ xs = np.linspace(xa + 34, xb - 30, 9)
+ ys = top + np.concatenate([[0], np.cumsum(rng.normal(0, 1.6, 8))])
+ rim = [(xa, HORIZON + 4), (xa + 12, top + hgt * 0.45), (xa + 30, top + 4)] + list(zip(xs, ys)) + \
+ [(xb - 24, top + 6), (xb - 10, top + hgt * 0.5), (xb + 2, HORIZON + 4)]
+ m = c.part(rim, (.4, .7, .2, 0), width=0, line=False)
+ shade = [(xb - 30, top + 5), (xb - 24, top + 6), (xb - 10, top + hgt * 0.5), (xb + 2, HORIZON + 4),
+ (xb - 46, HORIZON + 4), (xb - 40, top + hgt * 0.5)]
+ c.flat(c.mask(shade) * m, (.7, .7, .2, 0))
+ c.edge(rim[1:-1], width=3.2, heavy=0.6, taper=(0.05, 0.05), smooth=False)
+ for j in range(3):
+ yy = top + hgt * (0.35 + 0.2 * j)
+ c.brush([(xa + 22 + j * 6, yy), (xb - 48, yy + rng.normal(0, 2))], 2.0, taper=(0.3, 0.5), clip=m)
+plain = [(-10, HORIZON), (W + 10, HORIZON), (W + 10, H + 10), (-10, H + 10)]
+pm = c.part(plain, None, width=0, line=False)
+c.graded(pm, [(0, .4, .7, 0), (0, .4, 1, 0), (0, .7, 1, 0)], (0, HORIZON), (0, H + 10), wave=5)
+c.brush([(-5, HORIZON + 1), (W * 0.5, HORIZON + 2), (W + 5, HORIZON)], 3.0, taper=(0, 0), swell=0)
+for i in range(18):
+ x, y = rng.uniform(1000, 1560), rng.uniform(HORIZON + 14, H - 16)
+ L = rng.uniform(30, 110) * (0.5 + (y - HORIZON) / 260)
+ c.brush([(x, y), (x + L * 0.5, y + rng.normal(0, 1.5)), (x + L, y + rng.normal(0, 2))], 2.0 + (y - HORIZON) / 80,
+ taper=(0.3, 0.5), swell=0.3)
+
+# the butte: a flat top, a tall cliff with a black shadow under its rim and cracks running down, a talus slope
+rim_x = np.linspace(1606, 1945, 40)
+rim_y = 735 + np.cumsum(rng.normal(0, 0.9, 40)) * 0.6
+butte = [(1488, H + 10), (1500, 984), (1540, 930), (1584, 886), (1588, 840), (1592, 790), (1598, 760)] + \
+ list(zip(rim_x, rim_y)) + [(1945, H + 10)]
+bm_ = c.part(butte, (0, .7, 1, 0), width=5.5, heavy=1.0)
+toe = spline([(1584, 886), (1660, 902), (1760, 914), (1860, 908), (1950, 912)], 10)
+talus = np.vstack([[(1470, H + 10), (1500, 984), (1540, 930)], toe, [(1960, H + 10)]])
+tm = c.mask(talus) * bm_
+c.flat(tm, TAN)
+c.edge(toe, width=3.6, heavy=0.4, taper=(0.05, 0.3), smooth=False)
+under = list(zip(rim_x, rim_y + 4)) + list(zip(rim_x[::-1], rim_y[::-1] + 15 + 6 * np.sin(rim_x[::-1] / 37)))
+c.ink(c.mask(under) * bm_)
+rimP = np.array(spline(np.stack([rim_x[2:-1], rim_y[2:-1] + 17 + 6 * np.sin(rim_x[2:-1] / 37)], 1), 4))
+c.feather(rimP, np.tile([[0.0, -1.0]], (len(rimP), 1)), length=128, width=3.8, spacing=12, clip=bm_ * (1 - tm),
+ toward=(0.0, -1.0), along=(0.0, 1.0), curl=0.04)
+c.brush([(1596, 772), (1603, 830), (1598, 876)], 2.6, taper=(0.2, 0.5))
+for (x, y, r_) in [(1540, 1010, 16), (1606, 950, 11), (1700, 990, 20), (1830, 1000, 14), (1650, 1050, 22), (1880, 1060, 18)]:
+ rk = c.part(smooth([(x - r_, y + r_ * 0.4), (x - r_ * 0.6, y - r_ * 0.5), (x + r_ * 0.4, y - r_ * 0.6), (x + r_, y + r_ * 0.4)], 6),
+ (0, .7, 1, 0), width=3.2)
+ c.ink(c.mask(smooth([(x + r_ * 0.1, y - r_ * 0.5), (x + r_ * 0.5, y - r_ * 0.45), (x + r_, y + r_ * 0.4), (x, y + r_ * 0.4)], 6)) * rk)
+
+HX, HY = 1790, 736 # observatory on the butte
+c.part([(HX - 84, HY - 56), (HX + 84, HY - 56), (HX + 86, HY + 4), (HX - 86, HY + 4)], CREAM, width=4.5)
+c.flat(c.mask([(HX + 38, HY - 56), (HX + 84, HY - 56), (HX + 86, HY + 4), (HX + 38, HY + 4)]), (0, .2, .4, .2))
+c.part([(HX - 70, HY - 40), (HX - 46, HY - 40), (HX - 46, HY + 4), (HX - 70, HY + 4)], RED, width=3.5)
+c.dot(HX - 50, HY - 16, 2.4)
+c.letter('R.S. H.Q.', HX + 4, HY - 26, 20, face='bold')
+dome = ell(HX, HY - 56, 92, 76, 0, 0, 180)
+dm = c.part(np.vstack([dome, [(HX - 92, HY - 56)]]), SILVER, width=5)
+c.flat(c.mask(ell(HX + 32, HY - 70, 52, 50)) * dm, (.2, 0, 0, .2))
+c.flat(c.mask(ell(HX - 36, HY - 98, 18, 11, 30)) * dm, WHITE)
+slot = [(HX - 16, HY - 130), (HX + 8, HY - 130), (HX + 10, HY - 58), (HX - 18, HY - 58)]
+c.ink(c.mask(slot))
+c.part(tube([(HX - 4, HY - 100), (HX - 82, HY - 166)], [26, 32], caps=False), NAVY, width=4)
+c.part(ell(HX - 84, HY - 168, 11, 18, 40), CREAM, width=3.5)
+c.ink(c.mask([(HX - 86, HY - 3), (HX + 86, HY - 3), (HX + 88, HY + 4), (HX - 88, HY + 4)]))
+
+# ================================================================ the launch tower
+LX0, LX1, LTOP = (176, 302), (214, 264), 530
+
+
+def leg_x(side, y):
+ a, b = (LX0[0], LX1[0]) if side == 0 else (LX0[1], LX1[1])
+ return a + (b - a) * (H + 10 - y) / (H + 10 - LTOP)
+
+
+ys = np.arange(H - 20, LTOP + 30, -64.0)
+for y0, y1 in zip(ys[:-1], ys[1:]):
+ c.pen([(leg_x(0, y0), y0), (leg_x(1, y1), y1)], 3.0, smooth=False)
+ c.pen([(leg_x(1, y0), y0), (leg_x(0, y1), y1)], 3.0, smooth=False)
+for y in ys:
+ c.part([(leg_x(0, y) - 2, y - 5), (leg_x(1, y) + 2, y - 5), (leg_x(1, y) + 2, y + 5), (leg_x(0, y) - 2, y + 5)], RED, width=3)
+for side in (0, 1):
+ c.part(tube([(leg_x(side, H + 10), H + 10), (leg_x(side, LTOP), LTOP)], [18, 13], caps=False), RED, width=4.2)
+arm = [(leg_x(1, 640) - 4, 632), (420, 600), (424, 616), (leg_x(1, 650) - 4, 652)]
+c.part(arm, RED, width=3.8)
+for k in range(5):
+ xk = 280 + k * 28
+ c.pen([(xk, 634 - k * 6.5), (xk + 14, 648 - k * 6.5)], 2.2, smooth=False)
+c.pen([(414, 614), (416, 666)], 2.2, smooth=False)
+c.part(ell(416, 674, 9, 9), SILVER, width=3)
+c.part([(LX1[0] - 22, LTOP - 4), (LX1[1] + 22, LTOP - 4), (LX1[1] + 22, LTOP + 10), (LX1[0] - 22, LTOP + 10)], RED, width=3.8)
+for x in np.linspace(LX1[0] - 18, LX1[1] + 18, 6):
+ c.pen([(x, LTOP - 4), (x, LTOP - 30)], 2.4, smooth=False)
+c.pen([(LX1[0] - 20, LTOP - 30), (LX1[1] + 20, LTOP - 30)], 2.6, smooth=False)
+BX, BY = (LX1[0] + LX1[1]) / 2, LTOP - 44
+c.part(ell(BX, BY, 14, 14), RED, width=4)
+c.flat(c.circle(BX - 4, BY - 5, 4), WHITE)
+for a in np.deg2rad(np.arange(0, 360, 36) + 18):
+ c.brush([(BX + np.cos(a) * 22, BY + np.sin(a) * 22), (BX + np.cos(a) * 40, BY + np.sin(a) * 40)], 3.0, taper=(0.1, 0.6))
+c.stage('key_setting', plates='K')
+
+# ================================================================ speed lines and the flame
+c.speed(R1(-40, -165), -D, n=6, length=300, spread=90, width=4.2, seed=3)
+c.speed(R1(120, -150), -D, n=3, length=180, spread=40, width=3.4, seed=4)
+
+
+def flame_pts(length, width, tongues, seed, u0=-6):
+ """a flame from the nozzle backwards: swelling body, ragged tongues at the far end"""
+ r = np.random.default_rng(seed)
+ n = 60
+ t = np.linspace(0, 1, n)
+ half = width * 0.5 * np.sin(np.pi * np.clip(t * 0.85 + 0.12, 0, 1)) ** 0.8 * (1 - 0.25 * t)
+ top = [(u0 - length * tt, -hw) for tt, hw in zip(t, half)]
+ bot = [(u0 - length * tt, hw) for tt, hw in zip(t, half)]
+ tips = []
+ for k in range(tongues):
+ f = (k + 0.5) / tongues
+ tips.append((u0 - length * (1.0 + 0.18 * r.random() + 0.12 * np.sin(np.pi * f)), (f - 0.5) * width * 0.9))
+ tail_pts = []
+ for k, (tu, tv) in enumerate(tips):
+ tail_pts.append((tu, tv))
+ if k < len(tips) - 1:
+ nu, nv = tips[k + 1]
+ tail_pts.append(((tu + nu) / 2 + length * 0.16, (tv + nv) / 2))
+ return R(np.asarray(top[:-2] + tail_pts + bot[:-2][::-1], np.float32))
+
+
+fm = c.part(flame_pts(430, 196, 5, 11), RED, width=4.5, heavy=0.6)
+c.part(flame_pts(350, 146, 4, 12), DEEP_ORANGE, width=0, line=False)
+c.part(flame_pts(300, 118, 3, 15), ORANGE, width=0, line=False)
+c.part(flame_pts(270, 96, 3, 13), YELLOW, width=0, line=False)
+c.part(flame_pts(160, 46, 2, 14), WHITE, width=0, line=False)
+for k in range(5):
+ v = (k - 2) * 26
+ c.brush([R1(-190, v), R1(-250 - 24 * (k % 2), v * 1.25), R1(-310 - 34 * (k % 2), v * 1.5)], 2.8, taper=(0.3, 0.6), clip=fm)
+
+# ================================================================ Captain June and Pip (drawn before the hull, which hides
+# everything below the cockpit rims)
+def june():
+ f = frame(565, -rad(565) + 14, rot=9)
+ scarf = [(-4, -104), (-40, -136), (-80, -150), (-116, -180), (-150, -190), (-184, -220)]
+ sm = c.part(f(tube(scarf, [24, 28, 24, 20, 14, 8])), RED, width=4.2)
+ for (x, y) in [(-30, -128), (-62, -148), (-96, -158), (-126, -186), (-160, -200), (-48, -136), (-108, -172)]:
+ c.flat(c.circle(*f([(x, y)])[0], 4.2) * sm, WHITE)
+ torso_pts = [(-36, 40), (-40, -36), (-30, -82), (-6, -98), (22, -94), (36, -56), (38, 40)]
+ torso = c.part(f(smooth(torso_pts, 8)), BLUE, width=5)
+ c.flat(c.mask(f(smooth([(12, -70), (36, -56), (38, 40), (18, 40)], 6))) * torso, NAVY)
+ c.part(f([(-20, -94), (-2, -78), (16, -92), (2, -104), (-10, -104)]), YELLOW, width=3.2)
+ star = c.part(f(c.burst_pts(-8, -48, 14, 14, 5, 0.55, 3, rot=-90)), YELLOW, width=2.8, heavy=0.3)
+ c.part(f(tube([(-4, -96), (0, -114)], [17, 17], caps=False)), SKIN, width=3)
+ hx, hy = 6, -146
+ S = lambda pts: f([(hx + x, hy + y) for x, y in pts])
+ head = [(-36, -4), (-28, -30), (-2, -42), (26, -34), (38, -18), (40, -8), (51, 4), (42, 10), (43, 17), (38, 23),
+ (38, 31), (26, 38), (8, 36), (-8, 28), (-26, 18)]
+ hm = c.part(S(smooth(head, 8)), SKIN, width=4.4)
+ for (x, y, r) in [(-34, 18, 9), (-24, 26, 8), (-38, 6, 8)]:
+ c.part(S(ell(x, y, r, r)), DEEP_ORANGE, width=3)
+ helmet = [(30, -30), (18, -44), (-6, -50), (-30, -42), (-44, -20), (-42, 2), (-28, 12), (-14, 16), (-6, 8),
+ (-10, -4), (-4, -16), (14, -26)]
+ hel = c.part(S(smooth(helmet, 8)), BROWN, width=4.4)
+ c.flat(c.mask(S(smooth([(-30, -34), (-8, -45), (16, -40), (-12, -34), (-36, -14)], 6))) * hel, TAN)
+ c.part(S(smooth([(-16, 10), (-6, 6), (-2, 22), (-10, 30), (-18, 24)], 6)), BROWN, width=3.4)
+ c.brush(S([(-6, 26), (10, 36), (24, 38)]), 2.6, taper=(0.1, 0.3))
+ c.ink(c.mask(S(tube([(-42, -18), (-16, -36), (8, -42)], [8, 8, 8]))))
+ g = c.part(S(ell(14, -40, 11, 9, 20)), GOLD, width=5)
+ c.flat(c.circle(*S([(10, -43)])[0], 3.0) * g, WHITE)
+ c.part(S(smooth([(22, -8), (30, -12), (36, -8), (30, -4)], 6)), WHITE, width=2.4)
+ c.ink(c.circle(*S([(31, -8)])[0], 3.2))
+ c.brush(S([(20, -11), (27, -14), (35, -12), (39, -14)]), 2.6, taper=(0.2, 0.2))
+ c.brush(S([(20, -20), (29, -24), (38, -21)]), 3.0, taper=(0.3, 0.4))
+ mouth = c.mask(S(smooth([(43, 15), (34, 16), (28, 20), (36, 26), (42, 21)], 6)))
+ c.ink(mouth)
+ c.flat(c.mask(S(ell(38, 17, 5, 2.4))), WHITE); c.erase(c.mask(S(ell(38, 17, 5, 2.4))) * mouth)
+ c.brush(S([(26, 15), (30, 11)]), 2.0, taper=(0.2, 0.2))
+ c.flat(c.circle(*S([(18, 8)])[0], 7) * hm, PINK)
+ c.brush(S([(2, 2), (6, 12)]), 2.0, taper=(0.3, 0.3))
+ arm = [(14, -84), (58, -68), (100, -50)]
+ c.part(f(tube(arm, [27, 24, 20])), BLUE, width=4.5)
+ c.part(f(tube([(96, -52), (110, -46)], [24, 22])), YELLOW, width=3.5)
+ c.part(f(smooth([(108, -60), (126, -58), (134, -44), (124, -32), (110, -36)], 6)), BROWN, width=3.8)
+ c.part(f(tube([(126, -56), (160, -46)], [10, 8])), BROWN, width=3.4)
+ c.brush(f([(114, -50), (126, -48)]), 2.0, taper=(0.2, 0.2))
+ c.brush(f([(114, -42), (124, -40)]), 2.0, taper=(0.2, 0.2))
+ return S
+
+
+def pip():
+ f = frame(378, -rad(378) + 16, rot=2)
+ c.part(f(smooth([(-30, 30), (-32, -36), (-12, -62), (20, -60), (34, -28), (32, 30)], 8)), WHITE, width=4.5)
+ c.part(f(tube([(-24, -54), (30, -52)], [14, 12])), RED, width=3.4)
+ c.part(f(c.burst_pts(8, -40, 7, 7, 4, 0.35, 2)), YELLOW, width=2.4)
+ for x in (6, 28):
+ c.part(f(smooth([(x - 10, -2), (x - 8, -16), (x + 8, -18), (x + 13, -4)], 6)), WHITE, width=3.4)
+ c.brush(f([(x + 1, -12), (x + 2, -4)]), 1.8, taper=(0.2, 0.2))
+ tongue = [(48, -72), (30, -62), (8, -60), (-10, -50)]
+ c.part(f(tube(tongue, [12, 13, 11, 7])), PINK, width=3.2)
+ head = [(-24, -78), (-26, -102), (-8, -120), (18, -120), (34, -108), (48, -100), (72, -98), (90, -94), (92, -84),
+ (80, -76), (54, -74), (30, -66), (6, -62), (-14, -66)]
+ hm = c.part(f(smooth(head, 8)), WHITE, width=4.5)
+ c.ink(c.mask(f(smooth([(-18, -96), (-10, -112), (4, -110), (2, -94), (-10, -86)], 6))) * hm)
+ c.ink(c.mask(f(smooth([(80, -100), (95, -96), (96, -84), (82, -84)], 6))))
+ c.flat(c.circle(*f([(85, -96)])[0], 2.6), WHITE); c.erase(c.circle(*f([(85, -96)])[0], 2.6))
+ c.brush(f([(90, -82), (72, -78), (52, -76)]), 3.0, taper=(0.2, 0.3))
+ c.brush(f([(44, -102), (64, -100)]), 2.0, taper=(0.3, 0.4))
+ ear = [(-6, -112), (-36, -128), (-66, -118), (-90, -130)]
+ em = c.part(f(tube(ear, [24, 26, 18, 8])), None, width=0, line=False)
+ c.ink(em)
+ c.erase(c.mask(f(tube([(-28, -130), (-58, -124), (-80, -132)], [3, 4, 2]))) * em)
+ c.ink(c.mask(f(tube([(-22, -104), (10, -112)], [7, 7]))))
+ g = c.part(f(ell(22, -100, 14, 13)), GOLD, width=5.5)
+ c.flat(c.circle(*f([(17, -105)])[0], 3.6) * g, WHITE)
+ c.ink(c.circle(*f([(26, -98)])[0], 4.2) * g)
+ return f
+
+
+pip()
+S_june = june()
+
+# ================================================================ the rocket
+fin_top = [(215, -96), (110, -160), (18, -236), (-16, -236), (-2, -170), (30, -110), (60, -84)]
+fin_bot = [(215, 96), (120, 140), (34, 196), (4, 198), (8, 150), (34, 104), (60, 84)]
+for fp, side in ((fin_top, -1.0), (fin_bot, 1.0)):
+ fmk = c.part(R(smooth(fp, 8)), YELLOW, width=5)
+ c.flat(c.mask(R(smooth([(fp[2][0] + 2, fp[2][1] * 0.97), (fp[3][0] + 10, fp[3][1] * 0.95), (fp[4][0] + 14, fp[4][1]),
+ (fp[5][0] + 20, fp[5][1] * 1.02)], 6))) * fmk, RED)
+ c.ink(c.mask(R(smooth([(70, side * 90), (40, side * 116), (16, side * 150), (8, side * 116), (40, side * 86)], 6))) * fmk)
+bell = [(50, -50), (50, 50), (8, 62), (-10, 76), (-10, -76), (8, -62)]
+bmk = c.part(R(bell), None, width=5)
+c.ink(bmk)
+c.part(R([(-10, -76), (2, -70), (2, 70), (-10, 76)]), SILVER, width=3.4)
+c.flat(c.mask(R(tube([(40, -40), (12, -56)], [6, 4]))), WHITE); c.erase(c.mask(R(tube([(40, -40), (12, -56)], [6, 4]))))
+
+us = np.linspace(45, 866, 90)
+BODY = R([(u, -rad(u)) for u in us] + [(u, rad(u)) for u in us[::-1]])
+bm = c.part(BODY, RED, width=6.5, heavy=1.0)
+NOSE_U = 690
+c.flat(c.mask(R([(u, -rad(u) - 4) for u in np.linspace(NOSE_U, 870, 30)] + [(u, rad(u) + 4) for u in np.linspace(870, NOSE_U, 30)])) * bm, YELLOW)
+c.pen(R([(NOSE_U, -rad(NOSE_U)), (NOSE_U + 6, 0), (NOSE_U, rad(NOSE_U))]), 3.4)
+c.flat(c.mask(R([(u, -rad(u) - 4) for u in np.linspace(828, 870, 12)] + [(u, rad(u) + 4) for u in np.linspace(870, 828, 12)])) * bm, RED)
+c.pen(R([(828, -rad(828)), (831, 0), (828, rad(828))]), 3.0)
+BAND = (590, 640)
+c.flat(c.mask(R([(BAND[0], -110), (BAND[1], -110), (BAND[1], 110), (BAND[0], 110)])) * bm, WHITE)
+for u in BAND:
+ c.pen(R([(u, -rad(u)), (u + 5, 0), (u, rad(u))]), 3.2)
+c.letter('RS-1', *R1(615, 4), 30, face='slab', rot=-64, jitter=0.3)
+c.flat(c.mask(R(tube([(110, -64), (330, -76), (560, -68)], [7, 18, 6]))) * bm, WHITE)
+c.flat(c.mask(R(tube([(150, -44), (330, -52), (500, -48)], [3, 7, 2]))) * bm, (0, .4, .4, 0))
+shadow_band = [(60, 62), (200, 70), (400, 68), (560, 58), (700, 40), (800, 18), (850, 2), (850, rad(850) + 6),
+ (700, rad(700) + 6), (400, rad(400) + 6), (200, rad(200) + 6), (60, rad(60) + 6)]
+c.ink(c.mask(R(smooth(shadow_band, 8))) * bm)
+fe = np.array([(u, 60 - 6 * np.sin((u - 60) / 800 * np.pi) - max(0, (u - 560)) * 0.16) for u in np.linspace(70, 830, 140)], np.float32)
+band_m = c.mask(R([(BAND[0] - 3, -110), (BAND[1] + 3, -110), (BAND[1] + 3, 110), (BAND[0] - 3, 110)]))
+c.feather(R(fe), np.tile(NRM, (len(fe), 1)), length=46, width=3.2, spacing=10, clip=bm * (1 - band_m), toward=NRM, along=-NRM,
+ curl=-0.12)
+for u in (160, 470, 760):
+ for v in np.linspace(-rad(u) + 12, rad(u) - 30, 7):
+ c.dot(*R1(u + 2 * (1 - (v / rad(u)) ** 2), v), 2.0)
+for (u, v) in [(200, -8), (290, -8)]:
+ c.part(R(ell(u, v, 22, 22)), SILVER, width=5)
+ c.part(R(ell(u, v, 14, 14)), LIGHT_BLUE, width=3)
+ c.flat(c.circle(*R1(u - 5, v - 6), 4.0), WHITE)
+
+for u0 in (378, 565):
+ lip = [(u0 - 52, -rad(u0 - 52) + 2), (u0, -rad(u0) + 16), (u0 + 46, -rad(u0 + 46) + 4)]
+ c.brush(R(lip), 4.4, taper=(0.15, 0.15))
+
+# the hatch and the rope ladder, swinging back in the slipstream
+HU = 362
+c.ink(c.mask(R(ell(HU, rad(HU) - 6, 26, 9))))
+LB = np.array([898.0, 836.0])
+A0, B0 = np.array(R1(HU - 16, rad(HU) - 6)), np.array(R1(HU + 16, rad(HU) - 6))
+A1, B1 = LB + np.array([-19.0, -4.0]), LB + np.array([19.0, 4.0])
+railA = spline([A0, (A0 + A1) / 2 + np.array([9, 0]), A1], 10)
+railB = spline([B0, (B0 + B1) / 2 + np.array([9, 0]), B1], 10)
+for k in range(1, 6):
+ t = k / 5.0
+ pa = railA[int(t * (len(railA) - 1))]; pb = railB[int(t * (len(railB) - 1))]
+ dv = (pb - pa) / np.linalg.norm(pb - pa)
+ nv = np.array([-dv[1], dv[0]])
+ c.part([pa - dv * 6 - nv * 5, pb + dv * 6 - nv * 5, pb + dv * 6 + nv * 5, pa - dv * 6 + nv * 5], TAN, width=3)
+for rail in (railA, railB):
+ c.part(tube(rail[::3], [7, 7, 7, 7], caps=True), (0, .2, .7, 0), width=2.8)
+c.stage('key_rocket_and_crew', plates='K')
+
+
+# ================================================================ smoke billowing round the pad
+puffs = [(70, 905, 72), (180, 900, 70), (300, 950, 90), (140, 975, 104), (470, 985, 96), (620, 1000, 78),
+ (720, 1030, 64), (40, 1050, 120), (230, 1056, 126), (420, 1060, 118), (590, 1070, 96), (770, 1080, 70)]
+flame_tip = np.array(R1(-430, 0))
+for (x, y, r) in puffs:
+ pts = c.ellipse_pts(x, y, r, r * 0.9, rng.uniform(0, 180), n=72)
+ pts = pts + (pts - (x, y)) * (0.035 * np.sin(np.linspace(0, 2 * np.pi, 72, endpoint=False) * rng.integers(5, 8)
+ + rng.uniform(0, 6)))[:, None]
+ m = c.part(pts, WHITE, width=4.6, heavy=0.8)
+ c.flat(m * np.clip(1 - c.circle(x - r * 0.2, y - r * 0.22, r * 0.98), 0, 1), LIGHT_GREY)
+ near = np.hypot(x - flame_tip[0], y - flame_tip[1])
+ if near < 300:
+ c.flat(m * c.circle(x - r * 0.2, y - r * 0.32, r * 0.55), PALE)
+ P_, N_ = c.edge_normals(pts)
+ c.feather(P_, N_, length=r * 0.4, width=3.0, spacing=9, clip=m, curl=0.2)
+
+
+# ================================================================ Sparky on the ladder
+def sparky():
+ f = sheet_frame(LB[0], LB[1] + 2, rot=-6, s=1.15)
+ leg_l = [(22, 128), (2, 166), (-24, 160)]
+ leg_r = [(46, 128), (74, 160), (98, 146)]
+ for leg, foot, ang in ((leg_l, (-34, 156), 20), (leg_r, (106, 140), -30)):
+ c.part(f(tube(leg, [30, 26, 22])), BLUE, width=4.5)
+ c.part(f(tube([leg[-1], (foot[0] * 0.6 + leg[-1][0] * 0.4, foot[1] * 0.6 + leg[-1][1] * 0.4)], [22, 20])), (0, 0, .4, 0), width=3)
+ c.part(f(ell(foot[0], foot[1], 18, 11, ang)), BROWN, width=4)
+ tp = [(4, 62), (20, 54), (52, 58), (66, 76), (62, 132), (36, 142), (10, 136), (2, 100)]
+ torso = c.part(f(smooth(tp, 8)), BLUE, width=5)
+ c.part(f(smooth([(8, 60), (22, 52), (54, 56), (62, 70), (50, 80), (30, 84), (14, 80)], 6)), (0, .4, 1, 0), width=3.6)
+ c.part(f([(14, 78), (24, 74), (26, 112), (16, 114)]), BLUE, width=3)
+ c.part(f([(44, 76), (54, 80), (50, 114), (40, 112)]), BLUE, width=3)
+ for (x, y) in [(20, 82), (48, 84)]:
+ c.part(f(ell(x, y, 4.5, 4.5)), YELLOW, width=2.2)
+ c.part(f(smooth([(20, 102), (46, 102), (46, 124), (20, 124)], 4)), (1, .7, 0, .2), width=3)
+ c.brush(f([(24, 140), (36, 136), (60, 128)]), 2.4, taper=(0.3, 0.3))
+ feather_shape(f(smooth(tp, 8)), torso, 22, width=3.0, spacing=8)
+ c.part(f(tube([(-2, 14), (4, 38), (10, 64)], [17, 19, 22])), (0, .4, 1, 0), width=4.2)
+ c.part(f(smooth([(-14, -6), (-2, -14), (14, -10), (16, 6), (6, 14), (-10, 10)], 6)), CREAM, width=4)
+ c.brush(f([(-8, -2), (8, -4)]), 2.0, taper=(0.2, 0.2))
+ c.part(f(tube([(56, 80), (86, 76), (108, 52)], [20, 18, 16])), (0, .4, 1, 0), width=4.2)
+ c.part(f(tube([(116, 52), (130, 4)], [11, 10], caps=False)), SILVER, width=3.6)
+ c.part(f(smooth([(118, 4), (122, -18), (134, -22), (146, -10), (140, 0), (132, -6), (128, 6)], 6)), SILVER, width=3.6)
+ c.part(f(smooth([(102, 48), (114, 40), (124, 50), (118, 62), (106, 60)], 6)), CREAM, width=3.6)
+ hx, hy = 40, 30
+ c.part(f(smooth([(hx - 26, hy + 4), (hx - 22, hy - 20), (hx, hy - 30), (hx + 24, hy - 22), (hx + 30, hy + 2),
+ (hx + 22, hy + 26), (hx, hy + 32), (hx - 18, hy + 24)], 8)), SKIN, width=4.5)
+ c.part(f(ell(hx - 26, hy + 4, 7, 10)), SKIN, width=3.4)
+ hair = [(hx - 26, hy - 6), (hx - 30, hy - 26), (hx - 14, hy - 22), (hx - 12, hy - 42), (hx + 2, hy - 28), (hx + 10, hy - 46),
+ (hx + 16, hy - 26), (hx + 30, hy - 34), (hx + 26, hy - 16), (hx + 6, hy - 22), (hx - 12, hy - 14)]
+ c.part(f(hair), DARK_BROWN, width=3.8)
+ for ex in (hx + 4, hx + 20):
+ c.part(f(ell(ex, hy - 6, 6.5, 9)), WHITE, width=3)
+ c.ink(c.circle(*f([(ex + 2.5, hy - 10)])[0], 3.2))
+ c.brush(f([(hx - 2, hy - 20), (hx + 6, hy - 24), (hx + 12, hy - 22)]), 2.6, taper=(0.2, 0.3))
+ c.brush(f([(hx + 16, hy - 22), (hx + 22, hy - 25), (hx + 28, hy - 21)]), 2.6, taper=(0.2, 0.3))
+ c.brush(f([(hx + 13, hy - 2), (hx + 17, hy + 5), (hx + 12, hy + 7)]), 2.4, taper=(0.2, 0.3))
+ mouth = c.mask(f(smooth([(hx + 6, hy + 12), (hx + 16, hy + 9), (hx + 24, hy + 13), (hx + 18, hy + 24), (hx + 9, hy + 22)], 6)))
+ c.ink(mouth)
+ tongue = c.mask(f(ell(hx + 15, hy + 20, 6, 3.5))) * mouth
+ c.flat(tongue, RED); c.erase(tongue)
+ for (x, y) in [(hx - 4, hy + 4), (hx + 1, hy + 8), (hx + 27, hy + 4), (hx - 8, hy + 9)]:
+ c.dot(*f([(x, y)])[0], 1.6)
+ cap = [(-22, 0), (-18, -16), (0, -22), (18, -14), (22, 0)]
+ cf = sheet_frame(LB[0] + 150, LB[1] - 62, rot=-34, s=1.15)
+ c.part(cf(np.vstack([spline(cap, 8), [(30, 4), (34, 8), (-22, 4)]])), RED, width=4)
+ c.part(cf(ell(0, -20, 5, 3)), RED, width=2.6)
+ for k, (a0, a1) in enumerate([(200, 250), (210, 260)]):
+ c.edge(ell(LB[0] + 150, LB[1] - 62, 52 + k * 15, 46 + k * 13, 0, a0, a1), width=2.8, heavy=0, taper=(0.2, 0.4))
+ for (x0, y0, x1, y1) in [(-58, 150, -76, 132), (-52, 172, -76, 170), (122, 128, 140, 110), (126, 150, 148, 146)]:
+ c.brush(f([(x0, y0), (x1, y1)]), 3.0, taper=(0.3, 0.7))
+ for (x, y, rr) in [(hx - 34, hy - 20, 6), (hx + 38, hy - 28, 5)]:
+ c.part(f(smooth([(x, y - rr * 1.6), (x + rr, y), (x, y + rr), (x - rr, y)], 6)), WHITE, width=2.4)
+ return f
+
+
+S_sparky = sparky()
+c.stage('key_smoke_and_sparky', plates='K')
+
+# ================================================================ cover furniture and lettering
+c.logo('ROCKET SQUAD', [(232, 62), (1150, 28), (1150, 208), (232, 184)], vp=(690, 2600), depth=26,
+ colours=(YELLOW, GOLD, ORANGE), shade=RED, shadow=NAVY, shadow_off=(9, 11), outline=8.5, inner=3.4, glints=4)
+rib = [(256, 228), (568, 214), (552, 240), (570, 266), (258, 280), (276, 254)]
+c.part(rib, BLUE, width=4.2)
+c.letter('COMICS', 414, 247, 34, face='bold', colour=WHITE, rot=2.5, jitter=0, tracking=0.18)
+c.part([(28, 26), (206, 22), (210, 240), (30, 244)], WHITE, width=5.5)
+c.letter('No.', 64, 66, 26, face='slab', jitter=0.3)
+c.letter('3', 112, 66, 58, face='heavy', jitter=0)
+c.brush([(40, 106), (198, 104)], 3.4, taper=(0.05, 0.05), swell=0)
+c.letter('10¢', 118, 158, 70, face='heavy', jitter=0)
+c.letter('MAY', 118, 214, 26, face='bold', jitter=0.3, tracking=0.2)
+c.caption(36, 318, 566, 470, 'COUNTDOWN COMPLETE! THE\nROCKET SQUAD BLASTS OFF\nFOR THE MOON -- BUT ONE\nMEMBER IS RUNNING LATE!', 27,
+ colour=YELLOW, width=4.2)
+mouth = S_june([(44, 18)])[0]
+c.balloon('NEXT STOP --\nTHE MOON!', 1352, 136, 38, tail=(mouth[0] + 26, mouth[1] - 22), seed=2)
+c.balloon('HEY!! WAIT\nFOR ME!!', 1240, 960, 46, tail=tuple(S_sparky([(70, 50)])[0]), kind='yell', seed=5)
+c.sfx('WHOOOSH!', 380, 1006, 104, colour=YELLOW, rot=7, width=6.5, shade=RED, shade_off=(7, 7))
+c.stage('key_lettering', plates='K')
+
+# ================================================================ progressive proofs, then decades on a shelf
+c.stage('proof_yellow', plates='YK')
+c.stage('proof_red', plates='YMK')
+c.stage('proof_blue', plates='CMYK')
+c.brown_edges(width=55, amount=0.9)
+c.spine(x=0, ticks=80, staples=(0.27, 0.73))
+c.corner('br', radius=80)
+c.corner('tr', radius=46, fold=False)
+c.crease((1560, 1080), (1920, 820), strength=0.8)
+c.foxing(46)
+print(f'drawn in {time.time() - t0:.1f}s')
+c.save(out, stages_dir=stages)
+print(f'{out} {time.time() - t0:.1f}s')
diff --git a/examples/constructivism_radio.jpg b/examples/constructivism_radio.jpg
new file mode 100644
index 0000000..914860d
Binary files /dev/null and b/examples/constructivism_radio.jpg differ
diff --git a/examples/constructivism_radio.py b/examples/constructivism_radio.py
new file mode 100644
index 0000000..2d45d93
--- /dev/null
+++ b/examples/constructivism_radio.py
@@ -0,0 +1,220 @@
+"""Example (Soviet constructivism / 苏联构成主义): РАДИО · Radio -- the cover poster of a (fictional) 1920s magazine
+for radio amateurs, printed in red and black. It diagrams one small thing: how a broadcast reaches you.
+① a hyperboloid lattice radio tower, photographed from below (the transmitter), ② its waves running down a red
+wedge as concentric fronts that thin out as they spread, ③ a valve receiver with a horn loudspeaker, cut out of a
+photograph with scissors, the horn's bell catching the end of the wedge. A red disc behind the tower, a black diagonal slab with СЛУШАЙТЕ ВЕСЬ МИР ("listen to
+the whole world") reversed out, the title РАДИО in heavy condensed grotesque, numbered labels, price and the
+printer's imprint; then a century of folds, foxing and pin holes.
+Draw-on stages: paper -> red plate -> waves -> black slab -> tower photo -> receiver photo -> title -> labels
+-> age.
+No image model; the two "photographs" are rendered meshes screened into a 45-degree halftone.
+python3 constructivism_radio.py [out.jpg] [--stages DIR]
+"""
+import os, sys, time
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from constructivism import Constructivism, Photo
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'constructivism_radio.jpg'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+t0 = time.time()
+
+c = Constructivism(1920, 1080, seed=26, misreg=2.6)
+
+
+# ---------------------------------------------------------------- photo 1: the lattice tower, from below
+def tower_photo():
+ a = np.deg2rad(235)
+ d = 104
+ eye = np.array((d * np.cos(a), d * np.sin(a), 1.7))
+ p = Photo(900, 1080, eye=eye, target=(0, 0, 84), fov=46, ss=2, seed=4, key=(-0.55, -0.2, 0.75),
+ fill=(0.6, -0.5, 0.2), key_k=0.8, fill_k=0.3, amb=0.3, haze=2600, haze_tone=0.85, shift=(0, -0.11),
+ grain=0.02)
+ cam = eye[:2] / np.linalg.norm(eye[:2])
+
+ def far_side(pos, n): # the far half of the lattice, seen through the near half, is paler
+ f = (pos[:, 0] * cam[0] + pos[:, 1] * cam[1]) / (np.hypot(pos[:, 0], pos[:, 1]) + 1e-6)
+ return 1 + 5.5 * (1 - np.clip((f + 0.3) / 0.6, 0, 1))
+
+ steel = p.material(albedo=0.11, gloss=0.12, shine=14, tex=far_side)
+ R = [20, 15.2, 11.6, 8.9, 6.9, 5.4, 4.3] # ring radii at the joints of the six sections
+ N = [16, 14, 12, 10, 9, 8] # members per family, thinned out toward the top
+ for k in range(6):
+ p.hyperboloid(25 * k, 25 * (k + 1), R[k], R[k + 1], N[k], 360 / N[k] * 3, steel, member=0.55 - 0.055 * k,
+ rings=3 if k < 3 else 2, ring_member=0.36 - 0.03 * k, phase=7 * k)
+ p.cylinder((0, 0, 150), (0, 0, 168), 0.45, steel, sides=8, r1=0.22) # the mast on top
+ for z, L in ((154, 3.4), (159, 2.6), (164, 1.8)):
+ p.cylinder((-L, 0, z), (L, 0, z), 0.16, steel, sides=5)
+ return p, p.project([(0, 0, 168)])
+
+
+# ---------------------------------------------------------------- photo 2: a valve receiver with a horn speaker
+def receiver_photo():
+ p = Photo(760, 700, eye=(-0.7, -1.75, 0.95), target=(-0.25, 0, 0.36), fov=40, ss=2, seed=7,
+ key=(-0.6, -0.55, 0.6), fill=(0.8, -0.3, 0.15), key_k=1.0, fill_k=0.35, amb=0.3, grain=0.025)
+ X0, X1, Y0, Y1, ZT = -0.34, 0.34, -0.15, 0.15, 0.2
+
+ def wood(pos, n):
+ x, y, z = pos[:, 0], pos[:, 1], pos[:, 2]
+ u = np.where(np.abs(n[:, 2]) > 0.7, y, z)
+ g = np.sin(2 * np.pi * (u * 23 + 0.6 * np.sin(x * 7 + u * 31) + 0.25 * np.sin(x * 23)))
+ return 0.9 + 0.1 * g * (0.6 + 0.4 * np.sin(x * 5 + u * 3))
+
+ def scale(cx, cz, r0, r1): # white engraved ticks on black bakelite, every 3rd long
+ def tex(pos, n):
+ dx, dz = pos[:, 0] - cx, pos[:, 2] - cz
+ r = np.hypot(dx, dz)
+ ang = np.degrees(np.arctan2(dz, dx)) % 360
+ arc = (ang < 200) | (ang > 340)
+ tick = (np.abs(((ang + 2.5) % 10) - 2.5) < 1.0) & (r > r1 - 0.012) & (r < r1 - 0.002) & arc
+ big = (np.abs(((ang + 2.5) % 30) - 2.5) < 1.4) & (r > r0) & (r < r1 - 0.002) & arc
+ return np.where(tick | big, 9.0, 1.0)
+ return tex
+
+ def valve(pos, n):
+ z = pos[:, 2]
+ return np.where((z > ZT + 0.06) & (z < ZT + 0.105), 0.35, 1.0) * np.where(z > ZT + 0.13, 0.6, 1.0)
+
+ def coil(pos, n): # honeycomb winding: criss-cross wire
+ a = np.arctan2(pos[:, 1] - 0.06, pos[:, 0] - 0.24)
+ z = pos[:, 2]
+ w = np.sin(a * 18 + z * 520) * np.sin(a * 18 - z * 520)
+ return 0.75 + 0.25 * np.sign(w)
+
+ wood_m = p.material(albedo=0.4, gloss=0.12, shine=12, tex=wood)
+ ebon = p.material(albedo=0.06, gloss=0.4, shine=40)
+ dial = p.material(albedo=0.08, gloss=0.5, shine=40, tex=scale(-0.14, 0.11, 0.05, 0.078))
+ knob = p.material(albedo=0.07, gloss=0.6, shine=50)
+ nickel = p.material(albedo=0.7, gloss=0.5, shine=60, metal=0.85)
+ brass = p.material(albedo=0.45, gloss=0.35, shine=30, metal=0.5, interior=0.4)
+ japan = p.material(albedo=0.1, gloss=0.5, shine=40)
+ glass = p.material(albedo=0.42, gloss=1.0, shine=90, tex=valve)
+ ivory = p.material(albedo=0.8, gloss=0.2, shine=30)
+ coil_m = p.material(albedo=0.55, gloss=0.1, shine=10, tex=coil)
+
+ p.box((X0, Y0, 0.0), (X1, Y1, ZT), wood_m) # the cabinet
+ p.box((X0 - 0.015, Y0 - 0.015, ZT - 0.004), (X1 + 0.015, Y1 + 0.015, ZT + 0.014), wood_m) # its lid
+ p.box((X0 + 0.03, Y0 - 0.008, 0.022), (X1 - 0.03, Y0, ZT - 0.022), ebon) # ebonite front panel
+ F = Y0 - 0.008 # panel front face
+ # the big tuning dial: nickel bezel, black bakelite scale with white ticks, fluted knob; ivory pointer above
+ p.lathe((-0.14, F, 0.11), (0, -1, 0), [(0, 0.084), (0.004, 0.086), (0.008, 0.08)], nickel, sides=56, cap=False)
+ p.lathe((-0.14, F, 0.11), (0, -1, 0), [(0, 0.079), (0.006, 0.079)], dial, sides=56)
+ p.lathe((-0.14, F - 0.006, 0.11), (0, -1, 0), [(0, 0.032), (0.008, 0.034), (0.03, 0.03), (0.038, 0.024),
+ (0.042, 0.0)], knob, sides=28)
+ p.box((-0.146, F - 0.006, 0.192), (-0.134, F, 0.2), ivory)
+ for cx, cz in ((0.06, 0.135), (0.17, 0.135)): # two small knobs
+ p.lathe((cx, F, cz), (0, -1, 0), [(0, 0.03), (0.003, 0.031), (0.006, 0.0)], nickel, sides=32)
+ p.lathe((cx, F - 0.005, cz), (0, -1, 0), [(0, 0.02), (0.006, 0.021), (0.022, 0.018), (0.026, 0.0)],
+ knob, sides=24)
+ p.box((0.03, F - 0.004, 0.052), (0.1, F, 0.068), ivory) # makers' plate
+ for k in range(4): # terminal posts
+ x = 0.16 + 0.03 * k
+ p.lathe((x, F, 0.06), (0, -1, 0), [(0, 0.009), (0.012, 0.009), (0.014, 0.012), (0.022, 0.012),
+ (0.024, 0.0)], brass, sides=14)
+ for x in (-0.22, -0.1, 0.02): # three valves on top
+ p.cylinder((x, 0.0, ZT + 0.014), (x, 0.0, ZT + 0.036), 0.026, knob, sides=20, cap=True)
+ p.lathe((x, 0.0, ZT + 0.036), (0, 0, 1), [(0, 0.017), (0.012, 0.02), (0.03, 0.03), (0.06, 0.032),
+ (0.085, 0.028), (0.1, 0.016), (0.108, 0.007), (0.114, 0.0)],
+ glass, sides=28)
+ p.lathe((0.24, 0.06, ZT + 0.014), (0, 0, 1), [(0, 0.0), (0.0, 0.07), (0.03, 0.07), (0.03, 0.0)], coil_m, sides=40)
+ # horn
+ bx, by = -0.5, 0.07
+ p.lathe((bx, by, 0.0), (0, 0, 1), [(0, 0.1), (0.014, 0.1), (0.026, 0.088), (0.032, 0.05), (0.085, 0.046),
+ (0.1, 0.03), (0.105, 0.0)], japan, sides=36)
+ d = np.array([-0.75, -0.2, 0.55]); d /= np.linalg.norm(d)
+ P0 = np.array([bx, by, 0.1]); P1 = P0 + [0, 0, 0.26]; P3 = P0 + [0, 0, 0.36] + d * 0.26; P2 = P3 - d * 0.16
+ s = np.linspace(0, 1, 110)[:, None]
+ path = (1 - s) ** 3 * P0 + 3 * (1 - s) ** 2 * s * P1 + 3 * (1 - s) * s ** 2 * P2 + s ** 3 * P3
+ t = s[:, 0]
+ rad = np.where(t < 0.45, 0.016 + 0.006 * t,
+ 0.0187 * np.exp(np.log(0.19 / 0.0187) * np.clip((t - 0.45) / 0.55, 0, 1) ** 1.7))
+ p.sweep(path, rad, brass, sides=40)
+ p.lathe(P3 - d * 0.005, d, [(0, 0.186), (0.005, 0.197), (0.01, 0.19)], brass, sides=56, cap=False)
+ # the flex from the horn to the terminals
+ c0 = np.array([bx + 0.06, by - 0.05, 0.01]); c3 = np.array([X0 + 0.01, -0.02, 0.05])
+ s = np.linspace(0, 1, 40)[:, None]
+ cord = (1 - s) ** 2 * c0 + 2 * (1 - s) * s * (np.array([(c0[0] + c3[0]) / 2, -0.2, -0.02])) + s ** 2 * c3
+ p.sweep(cord, np.full(40, 0.006), japan, sides=10)
+ return p, p.project([P3])
+
+
+# ---------------------------------------------------------------- the sheet
+c.paper()
+c.stage('paper')
+
+tp, (tx, ty, _) = tower_photo()
+TCX, TCY = 400, 540 # where the tower photo is centred on the poster
+TIP = (TCX - 450 + float(tx[0]), TCY - 540 + float(ty[0]))
+
+rp, (hx, hy, _) = receiver_photo()
+RCX, RCY, RROT, RS = 1500, 560, 10.5, 1.16 # the receiver photo: centre, tilt (= the slab's), scale
+t = np.deg2rad(RROT)
+u, v = (float(hx[0]) - 380) * RS, (float(hy[0]) - 350) * RS
+BELL = (RCX + u * np.cos(t) + v * np.sin(t), RCY - u * np.sin(t) + v * np.cos(t)) # the horn's mouth on the poster
+REACH = float(np.hypot(BELL[0] - TIP[0], BELL[1] - TIP[1]))
+
+# ---- red plate: the disc behind the tower, the wedge of the broadcast from the mast to the horn
+c.ink(c.circle(TCX + 12, 330, 222), 'red')
+BEAM = -np.degrees(np.arctan2(BELL[1] - TIP[1], BELL[0] - TIP[0]))
+c.ink(c.wedge(TIP, BEAM, 5.6, REACH + 20), 'red')
+S0, S1 = (470, 1052), (1990, 772) # the slab's axis (printed in black later)
+ang = np.degrees(np.arctan2(S0[1] - S1[1], S1[0] - S0[0]))
+c.ink(c.poly([c.along(S0, ang, a, b) for a, b in ((930, 0), (1700, 0), (1700, 410), (930, 410))]), 'red')
+c.stage('red')
+
+# ---- waves: fronts radiating from the mast, black over the red, thinning as they spread, ending at the horn
+c.waves(TIP[0], TIP[1], 120, REACH - 60, 76, 12, BEAM - 9, BEAM + 6.5, plates=('black',), grow=-0.045)
+c.stage('waves')
+
+# ---- the black slab rising under the receiver, the line reversed out of it
+mid = c.along(S0, ang, 600, 0)
+slab = c.bar(S0[0], S0[1], S1[0], S1[1], 112)
+c.ink(slab, 'black', knock=c.text_mask('СЛУШАЙТЕ ВЕСЬ МИР', mid[0], mid[1], 66, 'grotesk', anchor='mm',
+ spacing=5, rot=ang))
+c.knock(slab, 'red')
+c.stage('slab')
+
+# ---- photo 1: tower, retouched out of its sky, printed over the red
+c.montage(tp, TCX, TCY, cell=5.5, contrast=1.1, soften=0.12) # thin blur keeps the lattice open
+c.stage('tower')
+
+# ---- photo 2: receiver, cut out with scissors, standing on the slab
+c.montage(rp, RCX, RCY, rot=RROT, scale=RS, cut=13, close=16, cell=5.5, contrast=1.2)
+c.stage('receiver')
+
+# ---- type
+c.text('ЖУРНАЛ ДЛЯ РАДИОЛЮБИТЕЛЕЙ · № 7 · 1926', 1868, 74, 30, 'black', 'din', anchor='rs', spacing=2)
+c.text('ЦЕНА 15 КОП.', 1868 - c.text_width('ЖУРНАЛ ДЛЯ РАДИОЛЮБИТЕЛЕЙ · № 7 · 1926', 30, 'din', 2) - 40, 74, 30, 'red',
+ 'din', anchor='rs', spacing=2)
+c.text('РАДИО', 1868, 300, 268, 'black', anchor='rs', wobble=0.7)
+c.ink(c.bar(1300, 332, 1868, 332, 7), 'black')
+c.stage('title')
+
+
+def label(n, text, x, y, rot=0.0, plate='black'):
+ """a numbered label: the number reversed out of a black square, the word beside it; (x, y) = bottom-left"""
+ sq = c.poly([c.along((x, y), rot, a, b) for a, b in ((0, 0), (46, 0), (46, 46), (0, 46))])
+ cx, cy = c.along((x, y), rot, 23, 23)
+ c.ink(sq, 'black', knock=c.text_mask(n, cx, cy, 40, 'din', anchor='mm', rot=rot))
+ lx, ly = c.along((x, y), rot, 60, 5)
+ c.text(text, lx, ly, 40, plate, 'din', spacing=1.5, rot=rot)
+
+
+label('1', 'ПЕРЕДАТЧИК', 640, 600)
+wx, wy = c.along(TIP, BEAM, 400, -175)
+label('2', 'ВОЛНА 1450 М', wx, wy, rot=BEAM)
+lx, ly = c.along(S0, ang, 1060, 330)
+label('3', 'ПРИЁМНИК', lx, ly, rot=ang)
+# the contents of the issue, a small block of type in the open field
+for k, line in enumerate(['В НОМЕРЕ:', 'ДЕТЕКТОРНЫЙ ПРИЁМНИК', 'АНТЕННА НА КРЫШЕ', 'ЛАМПЫ И БАТАРЕИ']):
+ y = 750 + k * 40
+ if k:
+ c.ink(c.rect(642, y - 22, 658, y - 6), 'red')
+ c.text(line, 640 + (30 if k else 0), y, 30, 'black', 'din', spacing=1.2)
+c.text('ТИП. № 3 · ТИРАЖ 5000 ЭКЗ.', 30, 1040, 17, 'black', 'din', anchor='ls', spacing=1.5, rot=90)
+c.stage('labels')
+
+# ---- a hundred years later
+c.age(folds=(1, 1))
+c.save(out, stages_dir=stages)
+print(f'{out} {time.time() - t0:.1f}s')
diff --git a/examples/drawing_artdeco_express.gif b/examples/drawing_artdeco_express.gif
new file mode 100644
index 0000000..c5b1fe2
Binary files /dev/null and b/examples/drawing_artdeco_express.gif differ
diff --git a/examples/drawing_codex_ornithopter.gif b/examples/drawing_codex_ornithopter.gif
new file mode 100644
index 0000000..8bd5682
Binary files /dev/null and b/examples/drawing_codex_ornithopter.gif differ
diff --git a/examples/drawing_comic_rocket.gif b/examples/drawing_comic_rocket.gif
new file mode 100644
index 0000000..b180a24
Binary files /dev/null and b/examples/drawing_comic_rocket.gif differ
diff --git a/examples/drawing_constructivism_radio.gif b/examples/drawing_constructivism_radio.gif
new file mode 100644
index 0000000..494351e
Binary files /dev/null and b/examples/drawing_constructivism_radio.gif differ
diff --git a/examples/drawing_illuminated_starchart.gif b/examples/drawing_illuminated_starchart.gif
new file mode 100644
index 0000000..1519409
Binary files /dev/null and b/examples/drawing_illuminated_starchart.gif differ
diff --git a/examples/drawing_letterpress_circus.gif b/examples/drawing_letterpress_circus.gif
new file mode 100644
index 0000000..bc6afa9
Binary files /dev/null and b/examples/drawing_letterpress_circus.gif differ
diff --git a/examples/drawing_lineprinter_launch.gif b/examples/drawing_lineprinter_launch.gif
new file mode 100644
index 0000000..fc06f35
Binary files /dev/null and b/examples/drawing_lineprinter_launch.gif differ
diff --git a/examples/drawing_lowpoly_canyon.gif b/examples/drawing_lowpoly_canyon.gif
new file mode 100644
index 0000000..c3dd6c5
Binary files /dev/null and b/examples/drawing_lowpoly_canyon.gif differ
diff --git a/examples/drawing_mosaic_harbor.gif b/examples/drawing_mosaic_harbor.gif
new file mode 100644
index 0000000..17dacb8
Binary files /dev/null and b/examples/drawing_mosaic_harbor.gif differ
diff --git a/examples/drawing_patch_camping.gif b/examples/drawing_patch_camping.gif
new file mode 100644
index 0000000..9314e1d
Binary files /dev/null and b/examples/drawing_patch_camping.gif differ
diff --git a/examples/drawing_petroglyph_migration.gif b/examples/drawing_petroglyph_migration.gif
new file mode 100644
index 0000000..d03a227
Binary files /dev/null and b/examples/drawing_petroglyph_migration.gif differ
diff --git a/examples/drawing_popart_cat_moods.gif b/examples/drawing_popart_cat_moods.gif
new file mode 100644
index 0000000..f943787
Binary files /dev/null and b/examples/drawing_popart_cat_moods.gif differ
diff --git a/examples/drawing_silhouette_family.gif b/examples/drawing_silhouette_family.gif
new file mode 100644
index 0000000..e3b2d57
Binary files /dev/null and b/examples/drawing_silhouette_family.gif differ
diff --git a/examples/drawing_stainedglass_seasons.gif b/examples/drawing_stainedglass_seasons.gif
new file mode 100644
index 0000000..988fa76
Binary files /dev/null and b/examples/drawing_stainedglass_seasons.gif differ
diff --git a/examples/drawing_stencil_kite.gif b/examples/drawing_stencil_kite.gif
new file mode 100644
index 0000000..1df220d
Binary files /dev/null and b/examples/drawing_stencil_kite.gif differ
diff --git a/examples/drawing_tomb_harvest.gif b/examples/drawing_tomb_harvest.gif
new file mode 100644
index 0000000..7f5629c
Binary files /dev/null and b/examples/drawing_tomb_harvest.gif differ
diff --git a/examples/illuminated_starchart.jpg b/examples/illuminated_starchart.jpg
new file mode 100644
index 0000000..bc9d455
Binary files /dev/null and b/examples/illuminated_starchart.jpg differ
diff --git a/examples/illuminated_starchart.py b/examples/illuminated_starchart.py
new file mode 100644
index 0000000..4e48c46
--- /dev/null
+++ b/examples/illuminated_starchart.py
@@ -0,0 +1,119 @@
+"""Example (illuminated manuscript / 泥金手抄本): 星辰之书 · Liber Stellarum — an opening of a (fictional) early-15th-
+century astronomy book lying on a dark desk. It teaches two small things. Left leaf: the order of the planets -- a
+historiated initial Q (rose letter with white-lead tracery on tooled burnished gold; in its counter a night sky, a
+crescent moon and an observatory tower on a hill), a textura column in iron-gall ink with vermilion rubrics, a gold /
+azure / rose bar border sprouting ivy sprays, and a roundel of the spheres: the earth as a T-O map, the seven planets
+on a spiral with their names written round the rings, the azure sphere of the fixed stars in a gold frame. Right leaf:
+how to take the altitude of a star -- a blue penwork initial O with red filigree, and an astrolabe drawn with
+compass and rule (a real stereographic plate for latitude 48, shell-gold rete and limb), its rule sighted along a red
+dotted line to a gilded star in the margin, the angle marked "xl gradus".
+Draw-on stages follow the workshop: vellum -> ruling -> scribe -> rubricator -> diagrams -> gilder -> painter -> pen.
+No image model.
+python3 illuminated_starchart.py [out.jpg] [--stages DIR]
+"""
+import os, sys, time
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from illuminated import Illuminated
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'illuminated_starchart.jpg'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+t0 = time.time()
+
+il = Illuminated(1920, 1080, seed=14)
+XH, LEAD = 18, 50 # x-height and line pitch of the main hand
+TOP = 140 # first baseline
+
+# ---- the book: two leaves of hair-side vellum, a flaw hole the scribe wrote round
+il.desk()
+(L0, LY0, L1, LY1), (R0, RY0, R1, RY1) = il.codex(200, 40, 1720, 1040)
+il.flaw(1655, 985, 9, 5.5, rot=12)
+
+# ---- ruling: prickings in the outer margins, a ruled line at every x-height; the far side shows through
+LX0, LX1 = 350, 885 # left text column
+RX0, RX1 = 1035, 1570 # right text column
+ys = [TOP - XH + LEAD * i for i in range(17)]
+il.show_through(LX0, LX1, [TOP + LEAD * i for i in range(17)], XH, opacity=0.03)
+il.show_through(RX0, RX1, [TOP + LEAD * i for i in range(17)], XH, opacity=0.03)
+il.rule(LX0, LX1, ys, prick_x=214)
+il.rule(RX0, RX1, ys, prick_x=1706)
+il.stage('vellum')
+
+# ---- left leaf: the order of the planets
+PANEL = 4 * LEAD + XH + 12
+left = il.column(
+ '*incipit liber de ordine planetarum.* | '
+ 'uoniam planete circa terram mouentur, ordinem eorum hic breuiter describimus. '
+ '^prima est luna, deinde mercurius et uenus, in medio sol; postea mars, iupiter et saturnus tardus. '
+ '^super omnes est firmamentum stellarum fixarum, ut in hac figura patet. |',
+ LX0, LX1, TOP, XH, LEAD, indent=[(1, LX0), (5, LX0 + PANEL + 14)])
+q = il.initial('Q', LX0, TOP + LEAD - XH - 6, PANEL)
+orbs = il.spheres(618, 805, 178)
+
+# ---- right leaf: the altitude of a star
+right = il.column(
+ '*de altitudine stelle per astrolabium.* | '
+ 'stendit hec figura quomodo altitudo stelle inuenitur. ^suspende astrolabium ꝑ anulum ut pendeat recte, '
+ '7 uide stellam per ambo foramina regule; postea numera gradus in limbo ab orizonte: *hic sunt xl gradus.* |',
+ RX0, RX1, TOP, XH, LEAD, indent=[(1, RX0), (2, RX0 + 2 * LEAD - 18)])
+coda = il.column('^nota quod in nocte serena melius uidentur. |', RX0, RX1, TOP + 16 * LEAD, XH, LEAD)
+o = il.versal('O', RX0, TOP + LEAD - XH - 8, 2 * LEAD - 30, reach=(70, 120))
+ACX, ACY, AR = 1262, 700, 180
+astro = il.astrolabe(ACX, ACY, AR, lat=48, rete=24, rule=40,
+ star=(ACX + 2.28 * AR * np.cos(np.radians(40)), ACY - 2.28 * AR * np.sin(np.radians(40))))
+border = il.border([(282, 92), (282, 985)], width=12, seed=5, every=88,
+ avoid=[(LX0, TOP - XH - 30, LX1, TOP + 8 * LEAD + 12), (436, 623, 800, 987)],
+ bounds=(L0 + 6, LY0 + 6, LX1, LY1 - 8))
+
+# ---- the scribe: black text, leaving the rubrics and the initials blank
+il.scribe(left)
+il.scribe(right)
+il.scribe(coda)
+il.write('xxiij', 1648, 96, 13, 'iron', load=0.7) # folio number, upper outer corner
+il.stage('text')
+
+# ---- the rubricator
+il.rubricate(left)
+il.rubricate(right)
+il.rubricate(coda, blue_first=True)
+il.stage('rubrics')
+
+# ---- the draftsman: compass work in brown ink
+orbs.draw()
+astro.draw()
+il.stage('diagrams')
+
+# ---- the gilder: gold first, before any paint
+q.gild()
+border.gild()
+orbs.gild()
+astro.gild()
+il.stage('gold')
+
+# ---- the painter
+q.paint()
+border.paint()
+orbs.paint()
+astro.paint()
+o.paint()
+il.stage('colours')
+
+# ---- pen work: outlines, white tracery, ivy sprays, filigree, labels
+q.pen()
+border.pen()
+orbs.pen()
+o.pen()
+sx, sy = astro.star_xy
+astro.pen(labels=[('anulus', (RX0 + 8, 452), (ACX - 0.13 * AR, ACY - 1.36 * AR)),
+ ('rete', (RX0 + 8, 590), (ACX - 0.60 * AR, ACY - 0.42 * AR)),
+ ('limbus', (RX0 + 8, 820), (ACX - 0.85 * AR, ACY + 0.45 * AR)),
+ ('regula', (RX0 + 8, 900), (ACX - 0.72 * AR, ACY + 0.62 * AR)),
+ ('orizon', (ACX + 1.36 * AR, ACY + 5), (ACX + 1.3 * AR, ACY)),
+ ('xl gradus', (ACX + 1.20 * AR, ACY - 0.22 * AR), (ACX + 1.16 * AR, ACY - 0.2 * AR)),
+ ('stella', (sx + 30, sy + 6), (sx + 26, sy))], xh=12)
+il.stage('penwork')
+
+# ---- six hundred years
+il.age(foxing=36)
+il.save(out, stages)
+print(out, f'{time.time() - t0:.1f}s')
diff --git a/examples/letterpress_circus.jpg b/examples/letterpress_circus.jpg
new file mode 100644
index 0000000..0e6fc48
Binary files /dev/null and b/examples/letterpress_circus.jpg differ
diff --git a/examples/letterpress_circus.py b/examples/letterpress_circus.py
new file mode 100644
index 0000000..5d4895b
--- /dev/null
+++ b/examples/letterpress_circus.py
@@ -0,0 +1,426 @@
+"""Example (letterpress poster / 凸版印刷海报): 马戏团来了 · The Circus Is Coming — a two-colour show bill of the
+1890s kind, set from wood type and printed red, then black, a hair out of register. Left: the bill's type, every
+line set to full measure in a different face (gothic, a shaded red Clarendon, Chinese wood type), brass rules, a
+starred list of the acts with leaders, the parade line in red. Right: the woodcut -- a high wire strung between
+two masts, the wire walker in mid-crossing with her balance pole, and below her the elephant, front feet up on a
+striped drum, raising its trunk to her; a dimension line on the mast gives the height. The red block (pennants,
+blanket, cap, drum stripes, ring curb, costume) was cut loose of the black key. Afterwards the bill was folded in
+thirds, a date strip pasted on, tacked up and left to brown and fox.
+Draw-on stages: stock -> red forme (type) -> red forme (woodcut tint) -> black wood type -> black key lines ->
+black hatching -> small type and rules -> folds and age -> date strip and tacks. No image model.
+python3 letterpress_circus.py [out.jpg] [--stages DIR]
+"""
+import os, sys, time
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from letterpress import Letterpress, RED, BLACK
+from core import spline
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'letterpress_circus.jpg'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+t0 = time.time()
+
+lp = Letterpress(1920, 1080, seed=11, misreg=3.4)
+lp.register(BLACK, 0, 0, 0)
+lp.register(RED, 3.4, -2.2, 0.05) # the second pass landed a little up and to the right
+W, H = lp.W, lp.H
+XX, YY = lp.XX, lp.YY
+lp.paper(tone=0.55)
+lp.stage('stock')
+
+# ================================================================ geometry of the picture
+G = 905 # floor of the ring
+POLE_L, POLE_R, POLE_TOP = 958, 1786, 170
+WIRE_Y = 228
+WX = 1262 # where the walker stands on the wire
+
+
+def wire_y(x):
+ """the wire sags a little, and dips under the walker's weight"""
+ x = np.asarray(x, np.float32)
+ u = (x - POLE_L) / (POLE_R - POLE_L)
+ return WIRE_Y + 6 * np.sin(np.pi * u) + 10 * np.exp(-((x - WX) / 110) ** 2)
+
+
+# ---- the elephant: drawn in its own frame (facing left, origin at the near hip, y down, units before scaling),
+# then tilted up so that its front feet stand on the drum
+TILT, S = np.deg2rad(22), 0.74
+LEG = 300.0 # hip to ground in the elephant's own units
+HIP = np.array([1540.0, G - LEG * S])
+
+
+def E(pts):
+ P = np.asarray(pts, np.float32) * S
+ c, s = np.cos(TILT), np.sin(TILT)
+ x, y = P[:, 0], P[:, 1]
+ return np.stack([HIP[0] + x * c - y * s, HIP[1] + x * s + y * c], 1)
+
+
+def E1(x, y):
+ return tuple(float(v) for v in E([(x, y)])[0])
+
+
+body_pts = [(-380, -205), (-300, -232), (-150, -238), (-10, -218), (52, -170), (78, -92), (70, -10), (22, 42),
+ (-150, 66), (-300, 52), (-385, 8), (-410, -72)]
+head_pts = [(-350, -204), (-390, -258), (-458, -280), (-526, -250), (-562, -174), (-556, -96), (-532, -46),
+ (-486, -20), (-428, -28), (-378, -64)]
+ear_pts = [(-448, -214), (-404, -236), (-352, -232), (-308, -204), (-288, -152), (-298, -104), (-284, -58),
+ (-302, -12), (-334, 24), (-374, 50), (-408, 54), (-424, 20), (-440, -40), (-456, -110), (-462, -170)]
+trunk_path = [(-536, -120), (-578, -150), (-606, -205), (-612, -268), (-596, -322), (-566, -346), (-540, -342),
+ (-530, -322)]
+trunk_w = [104, 80, 62, 50, 41, 33, 28, 26]
+SH_N, SH_F, HP_N, HP_F = E1(-322, 0), E1(-282, 12), E1(0, 0), E1(-44, 12)
+DRUM_TOP = SH_N[1] + LEG * S * 0.96 # the front legs are a little shorter
+DRUM_C, DRUM_RX, DRUM_RY = SH_N[0] + 22, 100.0, 22.0
+
+
+def leg(top, foot_y, w0, w1, lean=0.0):
+ foot = (top[0] + lean, foot_y)
+ mid = ((top[0] + foot[0]) / 2 + 3, (top[1] + foot_y) / 2)
+ m = lp.tube([top, mid, foot], widths=[w0 * S, (w0 * 0.55 + w1 * 0.45) * S, w1 * S]) * (YY <= foot_y)
+ return np.maximum(m, lp.ellipse(foot[0], foot_y - 9 * S, w1 * S * 0.6, 12 * S) * (YY <= foot_y))
+
+
+m_body = lp.shape(E(body_pts))
+m_head = lp.shape(E(head_pts))
+m_ear = lp.shape(E(ear_pts))
+m_trunk = lp.tube(E(trunk_path), widths=np.array(trunk_w) * S)
+m_nh = leg((HP_N[0], HP_N[1] - 40), G, 120, 86, -6)
+m_fh = leg((HP_F[0], HP_F[1] - 40), G - 10, 104, 80, -4)
+m_nf = leg((SH_N[0], SH_N[1] - 30), DRUM_TOP + 6, 112, 84, -4)
+m_ff = leg((SH_F[0], SH_F[1] - 30), DRUM_TOP - 6, 100, 78, 2)
+m_tail = lp.tube(E([(66, -150), (86, -92), (94, -26), (88, 22)]), widths=[13, 9, 7, 6])
+tip = E1(88, 22)
+m_tuft = lp.shape([(tip[0] - 6, tip[1] - 6), (tip[0] + 7, tip[1] - 4), (tip[0] + 9, tip[1] + 22),
+ (tip[0] - 1, tip[1] + 30), (tip[0] - 8, tip[1] + 18)])
+m_tusk = lp.tube(E([(-512, -66), (-546, -52), (-576, -54), (-596, -70)]), widths=np.array([20, 16, 10, 4]) * S)
+m_mouth = lp.shape(E([(-532, -78), (-508, -60), (-486, -48), (-500, -36), (-524, -50)]))
+near = np.maximum.reduce([m_body, m_head, m_trunk, m_nh, m_nf, m_tail])
+m_eleph = np.maximum.reduce([near, m_ear, m_ff, m_fh])
+m_blanket = lp.shape(E([(-300, -238), (-200, -248), (-90, -242), (-36, -226), (-28, -130), (-38, -18),
+ (-120, -4), (-230, -6), (-302, -22), (-320, -130)])) * m_body
+m_inner = lp.shape(E([(-286, -226), (-200, -234), (-96, -230), (-50, -214), (-42, -130), (-52, -34),
+ (-122, -20), (-230, -22), (-288, -36), (-304, -130)])) * m_body
+m_cap = lp.poly(E([(-478, -258), (-462, -322), (-418, -326), (-400, -268), (-440, -252)]))
+
+
+def star_mask(cx, cy, r, inner=0.4, rot=90.0):
+ t = np.deg2rad(rot) + np.arange(10) * np.pi / 5
+ rr = np.where(np.arange(10) % 2 == 0, r, r * inner)
+ return lp.poly(np.stack([cx + np.cos(t) * rr, cy - np.sin(t) * rr], 1))
+
+
+sc = E1(-170, -124)
+m_star = star_mask(sc[0], sc[1], 34, rot=90 + np.rad2deg(TILT) * 0)
+
+# ---- the drum
+dtop = lp.ellipse(DRUM_C, DRUM_TOP, DRUM_RX, DRUM_RY)
+dside = np.clip(np.maximum(lp.rect(DRUM_C - DRUM_RX, DRUM_TOP, DRUM_C + DRUM_RX, G - 4),
+ lp.ellipse(DRUM_C, G - 4, DRUM_RX, DRUM_RY)) - dtop, 0, 1)
+u = np.clip((XX - DRUM_C) / DRUM_RX, -1, 1)
+stripes = (np.sin(np.arcsin(u) * 9.0 - (YY - DRUM_TOP) / 9.0) > 0.1).astype(np.float32)
+
+# ---- the ring: curb (front arc) and floor
+RC, RRX, RRY = (1372.0, 938.0), 462.0, 56.0
+ring_out = lp.ellipse(RC[0], RC[1], RRX, RRY)
+ring_in = lp.ellipse(RC[0], RC[1] - 3, RRX - 20, RRY - 8)
+curb_top = np.clip(ring_out - ring_in, 0, 1) * (YY > RC[1] - 6)
+curb_face = np.clip(lp.ellipse(RC[0], RC[1] + 20, RRX, RRY) - ring_out, 0, 1) * (YY > RC[1])
+
+# ---- masts and pennants
+m_poleL = lp.tube([(POLE_L - 1, G + 2), (POLE_L, POLE_TOP)], 17, 11)
+m_poleR = lp.tube([(POLE_R + 1, G + 2), (POLE_R, POLE_TOP)], 17, 11)
+
+
+def pennant(x, d):
+ return lp.shape([(x, POLE_TOP - 6), (x + d * 40, POLE_TOP - 24), (x + d * 88, POLE_TOP - 30),
+ (x + d * 62, POLE_TOP - 12), (x + d * 80, POLE_TOP + 6), (x + d * 38, POLE_TOP + 4),
+ (x, POLE_TOP + 14)])
+
+
+m_penL, m_penR = pennant(POLE_L, -1), pennant(POLE_R, 1)
+
+# ---- the walker (her feet on the wire at the origin, y up is negative), a little arabesque
+WY = float(wire_y(WX))
+K = 1.15
+
+
+def Wk(pts):
+ P = np.asarray(pts, np.float32) * K
+ return np.stack([WX + P[:, 0], WY + P[:, 1]], 1)
+
+
+w_leg_s = lp.tube(Wk([(-2, -80), (-4, -44), (0, -4)]), widths=np.array([17, 13, 9]) * K)
+w_foot = lp.poly(Wk([(-5, -10), (5, -10), (3, 1), (-2, 1)]))
+w_leg_l = lp.tube(Wk([(6, -80), (34, -71), (64, -78)]), widths=np.array([16, 11, 6]) * K)
+w_torso = lp.shape(Wk([(-11, -80), (-12, -100), (-15, -120), (-8, -127), (8, -127), (15, -120), (12, -100), (11, -80)]))
+w_skirt = lp.shape(Wk([(-12, -88), (-30, -78), (-42, -68), (-28, -65), (-15, -69), (0, -65), (15, -69), (28, -65),
+ (42, -68), (30, -78), (12, -88)]))
+w_arm_l = lp.tube(Wk([(-12, -121), (-34, -108), (-50, -96)]), widths=np.array([7, 6, 5]) * K)
+w_arm_r = lp.tube(Wk([(12, -121), (34, -108), (50, -96)]), widths=np.array([7, 6, 5]) * K)
+w_head = lp.ellipse(WX, WY - 139 * K, 11.5 * K, 12.5 * K)
+w_hair = lp.shape(Wk([(-12, -140), (-10, -150), (0, -153), (10, -150), (12, -140), (6, -146), (-6, -146)]))
+w_bun = lp.ellipse(WX + 1, WY - 156 * K, 6 * K, 5 * K)
+w_pole = lp.tube(Wk([(-190, -72), (-100, -91), (0, -97), (100, -91), (190, -72)]), widths=[4.5, 5, 5.5, 5, 4.5])
+
+# ================================================================ red forme: wood type
+X0, X1 = 96, 846
+lp.type_line('CIRCUS', X0, X1, 382, 196, face='clarendon', ink=RED, shade=(10, 9, BLACK, 3))
+for y in (664, 714, 764):
+ lp.star(X0 + 14, y - 13, 15, RED)
+lp.type_line('GRAND STREET PARADE AT TEN', X0, X1, 862, 50, face='gothic', ink=RED)
+lp.press(RED)
+lp.stage('red_type')
+
+# ================================================================ red forme: the colour block of the woodcut
+lp.tint(np.clip(m_blanket - m_star, 0, 1))
+lp.tint(m_cap)
+lp.tint(m_penL)
+lp.tint(m_penR)
+lp.tint(dside * stripes * (YY > DRUM_TOP + 16) * (YY < G - 20))
+lp.tint(curb_face)
+lp.tint(np.maximum(w_torso, w_skirt), loose=1.0, grow=1)
+lp.press(RED)
+lp.stage('red_block')
+
+# ================================================================ black forme: wood type
+lp.type_line('THE GRAND TRAVELLING', X0, X1, 150, 58, face='gothic', ink=BLACK)
+lp.type_line('马戏团来了', X0 + 4, X1 - 4, 566, 136, face='cjk', ink=BLACK)
+lp.press(BLACK)
+lp.stage('black_type')
+
+
+# ================================================================ black forme: the woodcut, back to front
+def part(mask, key=(3.4, 7.0), tone=None, angle=None, centre=None, aspect=1.0, spacing=8.0, lo=0.14, gain=1.0,
+ clear=True):
+ """cut one piece of the block: clear what is behind it, key line ('key' layer), hatching ('hatch' layer)"""
+ if clear: lp.clear(mask)
+ if key:
+ with lp.layer('key'):
+ lp.key(mask, *key)
+ if angle is not None or centre is not None:
+ with lp.layer('hatch'):
+ lp.hatch(mask, angle=angle or 0, centre=centre, aspect=aspect, spacing=spacing, tone=tone, lo=lo, gain=gain)
+
+
+def wrinkle(p, q, bow, width=2.4, layer='hatch'):
+ p, q = np.array(p, np.float32), np.array(q, np.float32)
+ m = (p + q) / 2
+ d = q - p
+ n = np.array([-d[1], d[0]]) / (np.linalg.norm(d) + 1e-6)
+ with lp.layer(layer):
+ lp.line([p, m + n * bow, q], width, taper=(0.35, 0.35))
+
+
+# ---- masts, platforms, pennants, wire, guy ropes, ladder
+for x, m in ((POLE_L, m_poleL), (POLE_R, m_poleR)):
+ part(m, key=(2.2, 4.2), angle=90, spacing=6, tone=lp.ramp((x - 8, 0), (x + 8, 0)) * m, lo=0.3)
+ with lp.layer('key'):
+ lp.solid(lp.ellipse(x, POLE_TOP - 6, 9, 9)) # finial
+ plat = lp.rect(x - 34, WIRE_Y - 18, x + 34, WIRE_Y - 9)
+ lp.clear(plat)
+ lp.key(plat, 2.0, 3.6)
+ lp.line([(x - 26, WIRE_Y - 9), (x - 3, WIRE_Y + 30)], 3, taper=(0.1, 0.1))
+ lp.line([(x + 26, WIRE_Y - 9), (x + 3, WIRE_Y + 30)], 3, taper=(0.1, 0.1))
+for x, d, m in ((POLE_L, -1, m_penL), (POLE_R, 1, m_penR)):
+ part(m, key=(2.2, 4.0), angle=-12 * d, spacing=6, tone=lp.ramp((x + d * 30, 0), (x + d * 88, 0)) * 0.7 * m, lo=0.3)
+xs = np.linspace(POLE_L + 6, POLE_R - 6, 48)
+with lp.layer('key'):
+ lp.line(np.stack([xs, wire_y(xs)], 1), 3.4, taper=(0.0, 0.0))
+ lp.line([(POLE_L, POLE_TOP + 22), (POLE_L - 62, G - 2)], 2.2, taper=(0.02, 0.02))
+ lp.line([(POLE_R, POLE_TOP + 22), (POLE_R + 62, G - 2)], 2.2, taper=(0.02, 0.02))
+ for x in (POLE_L - 62, POLE_R + 62): # stakes
+ lp.solid(lp.poly([(x - 4, G - 10), (x + 4, G - 10), (x + 1, G + 8), (x - 1, G + 8)]))
+ lx0, lx1 = POLE_L + 22, POLE_L + 44 # rope ladder up the left mast
+ lp.line([(lx0, WIRE_Y - 6), (lx0 + 2, G - 2)], 2.2, taper=(0.02, 0.02))
+ lp.line([(lx1, WIRE_Y - 6), (lx1 + 4, G - 2)], 2.2, taper=(0.02, 0.02))
+ for y in np.arange(WIRE_Y + 22, G - 10, 30):
+ lp.line([(lx0, y), (lx1 + 2, y + 2)], 2.6, taper=(0.05, 0.05))
+
+# ---- engraver's tint lines behind the scene: ruled across, fading out to the edges, cleared round every figure
+things = np.maximum.reduce([m_eleph, m_tuft, dside, dtop, m_poleL, m_poleR, w_pole, w_head, w_skirt, w_torso,
+ w_leg_l, w_leg_s, w_arm_l, w_arm_r, w_hair, w_bun])
+halo = lp.ellipse(1372, 610, 400, 300)
+from core import blur as _blur
+vign = np.clip(_blur(halo, 60) * 1.4 - 0.25, 0, 1) * (YY < G - 30)
+with lp.layer('hatch'):
+ lp.hatch(np.clip(vign - np.clip(_blur(things, 3) * 6, 0, 1), 0, 1), angle=0, spacing=7,
+ tone=0.30 * vign, lo=0.08, wobble=0.4)
+
+# ---- the ring: sawdust, cast shadows, curb
+with lp.layer('hatch'):
+ floor = np.clip(ring_in - m_eleph - dside - dtop, 0, 1) * (YY > G - 40)
+ lp.stipple(floor, 0.0035, (0.6, 1.4), tone=np.clip((YY - (G - 44)) / 70, 0, 1))
+ sh = np.clip(lp.ellipse(1660, G + 4, 110, 12) + lp.ellipse(DRUM_C + 70, G + 2, 110, 11), 0, 1)
+ sh = sh * (1 - m_eleph) * (1 - dside)
+ lp.hatch(sh, angle=0, spacing=6, tone=0.55 * sh, lo=0.1)
+part(curb_top, key=(2.0, 3.0))
+part(curb_face, key=(2.4, 4.0), angle=90, spacing=7,
+ tone=(0.35 + 0.45 * lp.ramp((RC[0] - 100, 0), (RC[0] + RRX, 0))) * curb_face, lo=0.3)
+with lp.layer('key'):
+ for k in np.linspace(-0.9, 0.9, 13): # joints between the curb boards
+ x = RC[0] + k * RRX
+ y = RC[1] + RRY * np.sqrt(max(0.0, 1 - k * k))
+ lp.line([(x, y + 1), (x, y + 19)], 2.2, taper=(0.05, 0.05))
+
+# ---- the drum: shaded side, hoops, light top
+part(dside, key=(3.0, 6.0), angle=90, spacing=7,
+ tone=np.clip(0.05 + 0.8 * lp.ramp((DRUM_C - 10, 0), (DRUM_C + DRUM_RX, 0)), 0, 1) * dside, lo=0.3)
+with lp.layer('key'):
+ for yb in (DRUM_TOP + 12, G - 14):
+ hoop = np.clip(lp.ellipse(DRUM_C, yb, DRUM_RX + 1, DRUM_RY) - lp.ellipse(DRUM_C, yb - 8, DRUM_RX + 1, DRUM_RY), 0, 1)
+ lp.solid(hoop * dside)
+part(dtop, key=(3.0, 5.0))
+
+# ---- the elephant: far legs, then the near silhouette, internal contours, ear, details
+for m in (m_ff, m_fh):
+ part(m, key=(3.0, 5.5), angle=90, spacing=8, tone=np.clip(0.5 + 0.55 * lp.form_tone(m), 0, 1) * m)
+belly = lp.ramp(E1(-150, -120), E1(-150, 70))
+tone_n = np.clip(lp.form_tone(near, soft=40) * 0.8 + 0.3 * belly - 0.05, 0, 1)
+lp.clear(near)
+with lp.layer('key'):
+ lp.key(near, 4.0, 8.5)
+with lp.layer('hatch'):
+ body_only = np.clip(m_body - m_nh - m_nf, 0, 1)
+ lp.hatch(np.clip(body_only - m_inner, 0, 1), centre=E1(-160, -1000), spacing=8.5, tone=tone_n, lo=0.32)
+ for m in (m_nh, m_nf):
+ lp.hatch(m, angle=92, spacing=8, tone=np.clip(lp.form_tone(m, soft=16) + 0.1, 0, 1), lo=0.2)
+ lp.hatch(np.clip(m_head - m_trunk, 0, 1), centre=E1(-470, -470), spacing=8,
+ tone=np.clip(lp.form_tone(m_head, soft=30) * 0.9 + 0.2 * lp.ramp(E1(-470, -200), E1(-470, -30)), 0, 1), lo=0.22)
+ lp.hatch(m_trunk, angle=-70, spacing=7, tone=np.clip(lp.form_tone(m_trunk, soft=10) * 0.9 + 0.05, 0, 1), lo=0.3)
+with lp.layer('key'):
+ lp.solid(m_tuft)
+ lp.line([E1(-60, -40), E1(-48, 10), E1(-60, 60)], 3.0, taper=(0.5, 0.1)) # thigh
+ lp.line([E1(-262, -30), E1(-256, 20), E1(-268, 62)], 3.0, taper=(0.5, 0.1)) # elbow
+# the blanket over the back: cut clear of the body hatching, border line, studs, fringe, shading over the red
+lp.clear(m_blanket)
+with lp.layer('key'):
+ lp.key(m_blanket, 3.0, 5.5)
+ lp.key(m_inner, 1.8, 2.6)
+ for t in np.linspace(0.05, 0.95, 11):
+ a = E1(-296 + t * 252, -14 + 6 * np.sin(t * np.pi))
+ lp.solid(lp.ellipse(a[0], a[1], 3.6, 3.6))
+ for t in np.linspace(0.02, 0.98, 26):
+ a = E1(-298 + t * 262, -4 + 8 * np.sin(t * np.pi))
+ lp.line([a, (a[0] + 1, a[1] + 13)], 2.0, taper=(0.1, 0.5))
+with lp.layer('hatch'):
+ lp.hatch(np.clip(m_inner - m_star, 0, 1), angle=-70, spacing=8, tone=np.clip(tone_n - 0.1, 0, 1) * m_inner, lo=0.42)
+# the ear and its shadow on the neck
+ear_tone = np.clip(lp.form_tone(m_ear, soft=20) * 0.6 + 0.5 * lp.ramp(E1(-440, -100), E1(-300, -100)), 0, 1)
+part(m_ear, key=(3.6, 7.5), centre=E1(-470, -110), spacing=7.5, tone=ear_tone, lo=0.2)
+with lp.layer('hatch'):
+ sh = lp.cast(m_ear, 12, 10, np.clip(near - m_ear - m_blanket, 0, 1), 1.5)
+ lp.hatch(sh, angle=95, spacing=7.5, tone=0.8 * sh, lo=0.1)
+# cap, tusk, mouth, eye
+part(m_cap, key=(2.4, 4.0), angle=-60, spacing=6, tone=lp.ramp(E1(-470, -290), E1(-396, -290)) * 0.7 * m_cap, lo=0.35)
+cap_top = E1(-440, -324)
+with lp.layer('key'): # the fez's tassel hangs off the back
+ lp.line([cap_top, E1(-404, -316), E1(-392, -290)], 2.4, taper=(0.05, 0.05))
+ t = E1(-390, -282)
+ lp.solid(lp.poly([(t[0] - 4, t[1] - 6), (t[0] + 5, t[1] - 6), (t[0] + 8, t[1] + 12), (t[0] - 6, t[1] + 12)]))
+part(m_tusk, key=(2.4, 4.0))
+with lp.layer('key'):
+ lp.solid(np.clip(m_mouth - m_tusk, 0, 1))
+ eye = E1(-498, -170)
+ lp.solid(lp.ellipse(eye[0], eye[1], 7.0, 4.4, rot=-30))
+ lp.line([E1(-518, -192), E1(-498, -198), E1(-476, -188)], 2.6)
+# trunk rings, toenails, knee wrinkles
+path = spline(E(trunk_path), 10)
+dd = np.gradient(path, axis=0)
+dd /= np.linalg.norm(dd, axis=1, keepdims=True) + 1e-6
+nrm = np.stack([-dd[:, 1], dd[:, 0]], 1)
+wd = np.interp(np.linspace(0, 1, len(path)), np.linspace(0, 1, len(trunk_w)), np.array(trunk_w) * S)
+for i in range(8, len(path) - 6, 3):
+ p, n, w = path[i], nrm[i], wd[i]
+ s = 0.40 if i % 2 else 0.28
+ wrinkle(p + n * w * s, p - n * w * 0.44, w * 0.10, 2.0)
+for top, foot_y, lean in ((SH_N, DRUM_TOP + 6, -4), (HP_N, G, -6), (HP_F, G - 10, -4)):
+ fx = top[0] + lean
+ for k in (-0.5, -0.1, 0.3):
+ nx = fx + k * 28
+ with lp.layer('key'):
+ lp.line([(nx - 6, foot_y - 2), (nx, foot_y - 8), (nx + 6, foot_y - 2)], 2.2, taper=(0.2, 0.2))
+ for yy in (foot_y - 38, foot_y - 50):
+ wrinkle((fx - 22, yy), (fx + 20, yy + 2), 4, 2.0)
+
+# ---- the walker, last: she is in front of the wire
+for m in (w_leg_l, w_leg_s):
+ part(m, key=(2.0, 3.4), angle=80, spacing=5, tone=0.75 * lp.form_tone(m, soft=4) * m, lo=0.3)
+with lp.layer('key'):
+ lp.solid(w_foot)
+part(w_skirt, key=(2.0, 3.0), angle=-60, spacing=5,
+ tone=0.5 * lp.ramp(Wk([(0, -88)])[0], Wk([(0, -65)])[0]) * w_skirt, lo=0.25)
+part(w_torso, key=(2.0, 3.0))
+part(w_head, key=(1.8, 3.0))
+with lp.layer('key'):
+ lp.solid(w_hair)
+ lp.solid(w_bun)
+ lp.solid(lp.ellipse(WX - 4 * K, WY - 138 * K, 1.4, 1.6))
+ lp.solid(lp.ellipse(WX + 4 * K, WY - 138 * K, 1.4, 1.6))
+for m in (w_arm_l, w_arm_r):
+ part(m, key=(1.8, 2.8))
+part(w_pole, key=(2.6, 2.6))
+with lp.layer('key'):
+ for s in (-1, 1):
+ lp.solid(lp.ellipse(WX + s * 50 * K, WY - 95 * K, 4.5, 4.5)) # hands on the pole
+
+# ---- dimension line beside the right mast: how high the wire is
+DX = POLE_R - 40
+with lp.layer('key'):
+ y0, y1 = float(wire_y(DX)) + 10, G - 8
+ lp.line([(DX, y0 + 14), (DX, 548)], 2.0, taper=(0.0, 0.0))
+ lp.line([(DX, 640), (DX, y1 - 14)], 2.0, taper=(0.0, 0.0))
+ lp.solid(lp.poly([(DX, y0), (DX - 7, y0 + 18), (DX + 7, y0 + 18)]))
+ lp.solid(lp.poly([(DX, y1), (DX - 7, y1 - 18), (DX + 7, y1 - 18)]))
+ lp.rule(DX - 10, DX + 10, y0 - 1, 'single', BLACK, 2)
+ lp.rule(DX - 10, DX + 10, y1 + 1, 'single', BLACK, 2)
+ lp.text('40 FT.', DX + 9, 594, 26, 'roman_bold', anchor='mm', rot=90)
+
+lp.press(BLACK, only=['key'])
+lp.stage('key_lines')
+lp.press(BLACK, only=['hatch'])
+lp.stage('hatching')
+# the block is printed: let go of the woodcut's full-sheet masks before the rest of the run
+for _k in [k for k, v in list(globals().items()) if isinstance(v, np.ndarray) and v.shape == (H, W) and k not in ('XX', 'YY')]:
+ del globals()[_k]
+
+# ================================================================ small type, rules, border
+lp.border(36, 30, 1884, 1050, BLACK, 4.0)
+lp.rule(X0, X1, 604, 'thick_thin', BLACK, 4)
+acts = [('THE HIGH WIRE', 'forty feet above the ring'), ('THE ELEPHANT', 'dances upon a drum'),
+ ('CLOWNS & PONIES', 'and a brass band')]
+for (name, note), y in zip(acts, (664, 714, 764)):
+ w1 = lp.text(name, X0 + 40, y, 34, 'antique')
+ w2 = lp.text_width(note, 30, 'italic')
+ lp.text(note, X1, y, 30, 'italic', anchor='rs')
+ lp.leaders(X0 + 40 + w1 + 14, X1 - w2 - 14, y - 6, 3.6, 12)
+lp.rule(X0, X1, 796, 'double', BLACK, 3)
+lp.text('— will exhibit at —', (X0 + X1) / 2, 906, 26, 'italic', anchor='ms')
+lp.text('RIVERSIDE SHOW PRINT, No. 27', 1844, 1032, 15, 'roman', anchor='rs', spacing=1.5)
+lp.press(BLACK)
+lp.stage('small_type')
+
+# ================================================================ the life of the bill
+lp.fold('v', 640, 1.0)
+lp.fold('v', 1281, 0.9)
+lp.fold('h', 541, 0.8)
+lp.tone_edges(1.0)
+lp.foxing(170)
+lp.stain(250, 1000, 230, 90, 0.08)
+lp.stage('folded_aged')
+
+
+def date(s):
+ s.type_line('SATURDAY · MAY 17', 36, s.W - 36, 74, 44, face='clarendon', ink=BLACK, wear=0.2)
+ s.text('ON THE RIVER MEADOW · RAIN OR SHINE', s.W / 2, 104, 17, 'roman_bold', anchor='ms', spacing=2.5)
+
+
+lp.strip(140, 922, 802, 1022, rot=-0.7, draw=date)
+lp.tack(66, 58)
+lp.tack(1858, 62)
+lp.tack(70, 1022)
+lp.tack(1852, 1018)
+lp.nicks(3, (3, 7))
+
+lp.save(out, stages)
+print(out, f'{time.time() - t0:.1f}s')
diff --git a/examples/lineprinter_launch.jpg b/examples/lineprinter_launch.jpg
new file mode 100644
index 0000000..50ab308
Binary files /dev/null and b/examples/lineprinter_launch.jpg differ
diff --git a/examples/lineprinter_launch.py b/examples/lineprinter_launch.py
new file mode 100644
index 0000000..37dc056
--- /dev/null
+++ b/examples/lineprinter_launch.py
@@ -0,0 +1,189 @@
+"""Example (ASCII art, 1970s line printer): Liftoff Trace / 发射记录 — sheet 2 of a launch report, a whole 8.5 in
+greenbar sheet lying on the desk between two tear lines. On the left, an ASCII picture of the moment of liftoff: a
+slender rocket with a roll pattern rising beside its lattice service tower (arms swung back, an umbilical hose still
+swinging), a white-hot column widening from the nozzle (! | ' . streaks inside a % @ # smoke sheath) that runs
+into rolling exhaust clouds shaded % -> @ -> # with overstruck cores, a limb-darkened sun and a V of birds. On the
+right, what the computer logged: the countdown events and a printer plot of altitude against time (planned
+'.' vs measured '*', X = this picture). A reader went over it with a red ballpoint. No image model.
+python3 lineprinter_launch.py [out.jpg] [--stages DIR] [--txt]
+"""
+import os, sys, time
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from lineprinter import LinePrinter
+from core import smoothstep
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'lineprinter_launch.jpg'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+t0 = time.time()
+
+lp = LinePrinter(1920, 1080, seed=7, top=14, ppi=123.8, page_in=8.5) # a whole 8.5 in sheet, tear line to tear line
+BOTTOM = lp.page_rows - 2 # the picture stops two lines above the next tear line
+rng = np.random.default_rng(7)
+lp.form()
+lp.stage('form')
+
+# ------------------------------------------------------------------ roles: which characters each thing is made of
+lp.role('hull', ['', '.', ':', '+', '%', '#', '#@'], dither=0.35, group='rocket')
+lp.role('paint', ['#@', '#@', '#@M'], dither=0.0, noise=0.0, group='rocket')
+lp.role('metal', ['', '=', '=', '#', '#='], dither=0.3, group='rocket')
+lp.role('plume', ['', '.', ':', '%', '@', '#'], edge=None, dither=0.2, noise=0.0, group='rocket')
+lp.role('core', ['', "'", '.', ':', '!', '|'], edge=None, dither=0.0, noise=0.0, group='rocket')
+lp.role('smoke', ['', '.', ':', '%', '@', '#', '#@'], edge='all', outline='round', dither=0.2, noise=0.0,
+ inner_max=0.5)
+lp.role('land', ['', '.', ',', ':'], edge=None, dither=0.9, noise=0.06)
+lp.role('sun', ['', '.', '.', ':', ':'], outline=dict(left='(', right=')', top='_'), dither=0.7, noise=0.03)
+lp.role('tank', ['', '.', ':', '%', '#'], outline=dict(left='(', right=')', top='_'), dither=0.3)
+
+CX = 44.0 # rocket axis (column)
+H0, NB, BASE = 3.0, 11.0, 30.4 # nose tip, nose base, body base (rows)
+R = 4.8 # body radius in columns
+GROUND = 42.5
+
+lp.fill(lp.rect(0, GROUND, 94, lp.rows), 'land', lp.ramp_tone((0, GROUND), (0, lp.rows), 0.15, 0.5))
+lp.stroke([(0, GROUND), (94, GROUND)], glyphs='_')
+
+# ------------------------------------------------------------------ a water tower further off (deluge water for the pad)
+WX, WY, WR = 81.5, 27.0, 4.2
+for x0, x1 in ((WX - 2.6, WX - 5.6), (WX + 2.6, WX + 5.6), (WX - 0.9, WX - 1.9), (WX + 0.9, WX + 1.9)):
+ lp.stroke([(x0, WY + 1.5), (x1, GROUND)])
+for yb in (32.5, 37.5): # braces on a row centre, or they split in two
+ k = (yb - WY - 1.5) / (GROUND - WY - 1.5)
+ lp.stroke([(WX - 2.6 - 3.0 * k, yb), (WX + 2.6 + 3.0 * k, yb)], glyphs='-')
+lp.fill(lp.circle(WX, WY, WR), 'tank', lp.sphere_tone(WX, WY, WR, (-0.6, -0.5, 0.6), amb=0.1) * 0.9)
+lp.stroke([(WX, WY - WR * lp.cw / lp.ch - 0.2), (WX, WY - WR * lp.cw / lp.ch - 1.6)], glyphs='|')
+
+# ------------------------------------------------------------------ the service tower (behind the rocket)
+TL, TW, TT = 58.5, 6, 8.0 # left leg (cell centre), width in columns, top row
+TR = TL + TW
+lp.stroke([(TL, TT), (TL, GROUND)])
+lp.stroke([(TR, TT), (TR, GROUND)])
+lp.stroke([(TL - 0.5, TT + 0.5), (TR + 0.5, TT + 0.5)], glyphs='=')
+y = TT + 1 # bays: braces go one column per row, so each cell gets one clean \ or /
+while y + TW < GROUND:
+ lp.stroke([(TL + 0.5, y), (TR - 0.5, y + TW - 1)]) # crossing lands in a cell centre -> X
+ lp.stroke([(TR - 0.5, y), (TL + 0.5, y + TW - 1)])
+ lp.stroke([(TL - 0.5, y + TW - 0.5), (TR + 0.5, y + TW - 0.5)], glyphs='=')
+ y += TW
+# crane jib and hook, mast, warning light
+lp.stroke([(TL - 5, TT - 0.5), (TR + 2, TT - 0.5)], glyphs='=')
+lp.stroke([(TL - 4.0, TT), (TL - 4.0, TT + 2.5)], glyphs='|')
+lp.text('J', int(TL - 4.0), int(TT + 2.6))
+lp.stroke([((TL + TR) / 2, TT - 4.2), ((TL + TR) / 2, TT - 0.8)], glyphs='|')
+lp.text('O', int((TL + TR) / 2), int(TT - 5), strike=2)
+# swing arms, retracted; one umbilical hose still swinging
+for ya in (15.5, 25.5):
+ lp.stroke([(TL - 3.5, ya), (TL - 0.5, ya)], glyphs='=')
+lp.stroke([(TL - 3.4, 16.0), (TL - 4.4, 18.0), (TL - 3.6, 20.0), (TL - 1.8, 21.2)], smooth=True)
+
+# ------------------------------------------------------------------ the rocket
+body_light = (-0.7, -0.15, 0.7)
+sv = np.linspace(0, 1, 40) # ogive nose: half-width grows like a bullet
+half = R * (2 * sv - sv * sv)
+nose = lp.poly([(CX + h, H0 + s_ * (NB - H0)) for s_, h in zip(sv, half)] + [(CX + R, NB + 0.3), (CX - R, NB + 0.3)]
+ + [(CX - h, H0 + s_ * (NB - H0)) for s_, h in zip(sv[::-1], half[::-1])])
+body = lp.rect(CX - R, NB, CX + R, BASE)
+tone = lp.cylinder_tone(CX - R, CX + R, body_light, amb=0.12)
+for sgn in (-1, 1): # fins first so the body covers their roots
+ fin = lp.poly([(CX + sgn * (R - 0.4), BASE - 6.0), (CX + sgn * (R + 3.6), BASE + 0.2),
+ (CX + sgn * (R + 3.6), BASE + 0.9), (CX + sgn * (R - 0.4), BASE + 0.9)])
+ lp.fill(fin, 'hull', 0.15 if sgn < 0 else 0.75)
+lp.fill(np.maximum(nose, body), 'hull', tone)
+for (r0, r1, side) in ((12.6, 16.0, -1), (16.0, 19.4, 1)): # roll pattern: black quarters
+ q = lp.rect(CX if side > 0 else CX - R, r0, CX + R if side > 0 else CX, r1)
+ lp.fill(q * body, 'paint', tone)
+lp.fill(lp.rect(CX - R, 22.4, CX + R, 23.4), 'metal', np.clip(tone + 0.3, 0, 1))
+lp.text_v('LARK', int(CX - 2), 24, strike=2) # painted name, on the sunlit side
+
+# ------------------------------------------------------------------ the flame: a hot white column widening from the nozzle
+FT, FB = BASE, 46.0
+ys = np.linspace(FT, FB, 40)
+hw = 2.6 + 5.0 * np.clip((ys - FT) / 9.0, 0, 1) ** 0.8 + 0.3 * np.maximum(ys - FT - 9.0, 0) # half-width (columns)
+hw_at = np.interp(lp.Y, ys, hw)
+u = np.abs(lp.X - CX) / hw_at # 0 on the axis .. 1 at the plume's edge
+plume = lp.poly([(CX + h, y_) for y_, h in zip(ys, hw)] + [(CX - h, y_) for y_, h in zip(ys[::-1], hw[::-1])])
+lp.fill(plume, 'plume', np.clip(0.2 + 0.95 * smoothstep(0.45, 1.0, u), 0, 1)) # smoke sheath, thickening outwards
+# white-hot inside: streaks that fan out from the nozzle, flickering along their length
+d = lp.Y - FT
+lanes = np.zeros_like(lp.X)
+for off, k, amp in ((-0.5, 0.0, 1.0), (0.5, 0.0, 1.0), (-1.5, 0.18, 0.75), (1.5, 0.18, 0.75), (-2.6, 0.3, 0.5), (2.6, 0.3, 0.5)):
+ xc = CX + off * (1 + k * d)
+ flick = 0.62 + 0.38 * np.sin(d * 1.9 + off * 2.1)
+ lanes = np.maximum(lanes, amp * flick * np.exp(-((lp.X - xc) / 0.42) ** 2))
+inner = lp.poly([(CX + 0.6 * h, y_) for y_, h in zip(ys, hw)] + [(CX - 0.6 * h, y_) for y_, h in zip(ys[::-1], hw[::-1])])
+lp.fill(inner, 'core', np.clip(1.6 * lanes * (1.0 - 0.55 * np.clip(d / 10.0, 0, 1)), 0, 1))
+
+# ------------------------------------------------------------------ exhaust clouds rolling out both ways
+puffs = [(CX - 9.6, 39.6, 3.6), (CX + 9.6, 39.8, 3.6)] # smoke peeling off the plume
+puffs += [(CX - 14, 39.5, 7.0), (CX + 14, 40.0, 7.0), # back, high
+ (CX - 29, 42.0, 8.0), (CX + 28, 42.5, 7.5), (CX - 13.5, 44.0, 7.0), (CX + 13.5, 44.0, 7.0),
+ (CX - 39, 45.5, 6.0), (CX + 38, 46.0, 5.5), # rolling out sideways
+ (CX - 20, 47.0, 10.0), (CX + 19, 47.5, 9.5), # front, on the pad
+ (CX - 35, 50.5, 8.5), (CX + 34, 51.0, 8.0), (CX, 49.5, 10.0)]
+puffs = [(c + rng.uniform(-0.8, 0.8), r + rng.uniform(-0.3, 0.3), R_ * rng.uniform(0.95, 1.05)) for c, r, R_ in puffs]
+sink = 0.32 * np.clip((lp.Y - 41.0) / 8.0, 0, 1) # the cloud's underside is in its own shade
+lp.billow(puffs, 'smoke', light=(-0.35, -0.85, 0.4), amb=0.2, shadow=0.3, glow=(CX, 42.5, 8.0, 0.3), lift=sink)
+
+# ------------------------------------------------------------------ the low morning sun the light comes from
+SC, SR, SRAD = 15.5, 9.5, 4.6
+rr = np.hypot(lp.X - SC, (lp.Y - SR) * lp.ch / lp.cw) / SRAD # limb darkening: . in the middle, : at the rim
+lp.fill(lp.circle(SC, SR, SRAD), 'sun', np.clip(0.28 + 0.75 * rr ** 1.6, 0, 1))
+for k in range(8):
+ a = k / 8 * 2 * np.pi
+ ca, sa = np.cos(a), np.sin(a) * lp.cw / lp.ch
+ r0, r1 = SRAD + 1.0, SRAD + 3.0
+ lp.stroke([(SC + ca * r0, SR + sa * r0), (SC + ca * r1, SR + sa * r1)])
+
+# ------------------------------------------------------------------ birds leaving in a hurry
+for (c, r) in [(23, 16), (26, 15), (29, 14), (32, 13), (26, 17), (29, 18), (35, 15)]: # a loose V heading off left
+ lp.text('\\/', c, r)
+
+# ------------------------------------------------------------------ header and the right-hand column
+lp.text('LARK-7 ASCENT TRACE', 0, 1, strike=2)
+lp.text('PAD 2 JOB 4471 74.103 06:41:10 LP02', 38, 1)
+lp.text('SHEET 2', 124, 1)
+L0 = 97
+lp.text('EVENT LOG', L0, 4, strike=2)
+lp.text('-' * 35, L0, 5)
+events = [('T-00:10', 'GUIDANCE', 'INTERNAL'), ('T-00:05', 'IGNITION', 'START'), ('T-00:02', 'MAIN STAGE', '100 PCT'),
+ ('T+00:00', 'HOLD-DOWN', 'RELEASE'), ('T+00:01', 'LIFTOFF', '06:41:07'), ('T+00:03', 'CLEARING TOWER', '11 M')]
+for i, (t, ev, val) in enumerate(events + [('T+00:06', 'TOWER CLEAR', 'NEXT')]):
+ lp.text(f'{t} {ev} ' + '.' * (16 - len(ev)) + f' {val}', L0, 6 + i)
+
+lp.text('ALTITUDE (M)', L0, 15, strike=2)
+lp.text('* MEASURED . PLAN', L0 + 17, 15)
+tt = np.linspace(0, 6, 49)
+plan = 0.5 * 2.4 * tt ** 2
+tm = np.linspace(0, 3, 13)
+meas = 0.5 * 2.45 * tm ** 2 + np.array([0, .1, -.1, .2, 0, -.2, .1, .3, 0, .2, .4, .2, 0])
+cell = lp.plot(L0, 17, 25, 13, (0, 6), (0, 40), [(tt, plan, '.'), (tm[:-1], meas[:-1], '*'), (tm[-1:], meas[-1:], 'X')],
+ xticks=[0, 1, 2, 3, 4, 5, 6], yticks=[0, 10, 20, 30, 40], ylab_w=4)
+lp.text('T+ SECONDS', L0 + 21, 32)
+stat = [('CHANNEL', 'VALUE', 'LIMIT', ''), ('THRUST PCT', '101.2', '95.0', 'OK'), ('CHAMBER P', '48.7', '45.0', 'OK'),
+ ('ROLL DEG', '+0.4', '2.0', 'OK'), ('PITCH DEG', '-0.1', '2.0', 'OK'), ('VIBRATION G', '1.8', '3.5', 'OK')]
+for i, (a, b, c, d) in enumerate(stat):
+ lp.text(f'{a:<12}{b:>6}{c:>8} {d}', L0, 36 + i, strike=2 if i == 0 else 1)
+lp.text('ALL CHANNELS WITHIN LIMITS', L0, 43)
+
+lp.erase(lp.rect(0, BOTTOM, lp.cols, lp.rows)) # bottom margin and the next sheet stay blank
+lp.compose()
+if '--txt' in sys.argv: lp.listing(os.path.splitext(out)[0] + '.txt')
+
+# ------------------------------------------------------------------ print, a few lines at a time
+for r0, r1, name in ((0, 8, 'print_header'), (8, 16, 'print_tower_top'), (16, 24, 'print_body'),
+ (24, 32, 'print_fins'), (32, 40, 'print_flame'), (40, lp.rows, 'print_clouds')):
+ lp.print_rows(r0, r1)
+ lp.stage(name)
+
+# ------------------------------------------------------------------ somebody read it with a red ballpoint
+RED = '#b3312b'
+for i in range(6):
+ x, y = lp.xy(L0 - 1.2, 6 + i + 0.8)
+ lp.tick(x, y, size=13, colour=RED, width=1.4)
+cx, cy = lp.centre(*[int(round(v)) for v in cell(3, meas[-1])])
+lp.ring(cx, cy, 30, 20, colour=RED, width=1.5)
+lp.pen([(cx + 26, cy - 14), (cx + 60, cy - 46), (cx + 95, cy - 58)], colour=RED, width=1.4)
+lp.pen_text('on plan', cx + 100, cy - 52, size=24, colour=RED, rot=6)
+
+lp.save(out, stages)
+print(out, f'{time.time() - t0:.1f}s')
diff --git a/examples/lowpoly_canyon.jpg b/examples/lowpoly_canyon.jpg
new file mode 100644
index 0000000..62c0760
Binary files /dev/null and b/examples/lowpoly_canyon.jpg differ
diff --git a/examples/lowpoly_canyon.py b/examples/lowpoly_canyon.py
new file mode 100644
index 0000000..30cf3fc
--- /dev/null
+++ b/examples/lowpoly_canyon.py
@@ -0,0 +1,91 @@
+"""Example (low poly): 峡谷飞行 · Canyon Run — one frame of an imaginary 1999 flying game, rendered by a tiny
+software rasterizer: a small white-and-teal stunt plane banks into a right-hand bend of a desert canyon, lining up
+the fifth of nine gold hoops; the sixth hangs under a natural stone arch and the rest swing round the bend toward
+the finish. Stepped strata walls (one in sun, one in lavender shade), a river of uneven facets, billboard junipers,
+boulders, buttes dissolving in the per-vertex fog; a half-transparent propeller disc, a lens flare; everything
+crushed to 15-bit colour through the 4x4 dither and blown up x5 with no smoothing.
+HUD: hoop counter, lap time, stepped speed bar, altitude, course minimap. No image model.
+python3 lowpoly_canyon.py [out.jpg] [--stages DIR]
+"""
+import os, sys, time
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from lowpoly import LowPoly, HUD_GREEN
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'lowpoly_canyon.jpg'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+t0 = time.time()
+
+g = LowPoly(1920, 1080, scale=5, seed=1999, record=stages is not None, far=270)
+path = g.path([(0, -60), (0, -20), (0, 10), (4, 35), (16, 58), (36, 76), (60, 88), (88, 96), (120, 102),
+ (150, 110), (175, 128), (190, 155), (196, 190), (194, 240), (186, 300)])
+
+# ---- the shot: a chase camera at the right-rear of the plane, the plane on the lower-left third
+S_PLANE = 70.0
+plane = g.along(path, S_PLANE, u=-1.5, y=14.0)
+fwd = g.heading(path, S_PLANE); right = np.array([fwd[2], 0, -fwd[0]])
+g.camera(eye=plane - fwd * 11 + right * 4.0 + [0, 2.6, 0], target=plane, fov=52, roll=-3)
+g.aim(plane, at=(0.35, 0.68))
+
+g.sky('#33509e', '#c4bedd', glow='#fff2cc')
+g.sun(screen=(0.4, 0.1))
+g.light(lift=26) # shade as if the sun stood higher, as games of the era did
+g.stage('sky')
+
+# ---- the canyon, the river, buttes on the plateau, the arch over the sixth hoop
+g.canyon(path, s0=0, s1=330, step=7.0, height=0.75)
+g.river(path, s0=0, s1=330, step=7.0)
+for s, u, rad, h in ((150, -70, 14, 24), (200, -55, 11, 30), (250, 60, 18, 20), (280, -45, 15, 26), (120, 70, 9, 18)):
+ p = g.along(path, s, u=u)
+ g.mesa(p[0], p[2], rad, h, base=29.5)
+g.arch(path, 121, span=44, rise=10, base=21)
+g.stage('wireframe', wire=True)
+g.stage('flat', fog=False, textures=False)
+g.stage('textures', fog=False)
+
+# ---- junipers on the banks and ledges, boulders in the river
+r = np.random.default_rng(7)
+for s in np.arange(60, 240, 8.0):
+ for side in (-1, 1):
+ if r.random() < 0.55:
+ k = r.choice(3, p=[0.5, 0.3, 0.2])
+ u, y = [(9.2, 0.9), (15.8, 11.8), (20.6, 20.0)][k]
+ p = g.along(path, s + r.uniform(-3, 3), u=side * (u + r.uniform(-0.6, 0.8)), y=y - 0.2)
+ g.tree(*p, height=r.uniform(3.0, 4.6))
+for s, u in ((78, -4.5), (96, 5.2), (131, -5.0), (150, 3.5), (171, -2.5)):
+ p = g.along(path, s, u=u)
+ g.boulder(p[0], -0.1, p[2], r=r.uniform(0.9, 1.5))
+g.fog(55, 250)
+g.stage('fog')
+
+# ---- the course: nine hoops (four already flown), the plane lining up the fifth
+course = [(0, 0.0, 12.0), (15, 1.5, 11.0), (30, -1.0, 13.0), (45, 0.5, 12.0),
+ (90, 1.0, 14.0), (121, 1.0, 16.0), (147, -1.0, 18.0), (178, 2.0, 15.0), (210, 0.0, 19.0)]
+hoops = []
+for s, u, y in course:
+ c = g.along(path, s, u=u, y=y)
+ hoops.append(c)
+ g.ring(c, g.heading(path, s), radius=3.4)
+g.stage('hoops')
+
+aim = hoops[4] - plane
+g.aircraft(plane, aim, roll=34, pitch=3)
+g.stage('plane')
+
+# ---- sparkles on the next hoop, the lens flare
+for k in (2, 6):
+ a = np.radians(110 + k * 28)
+ g.sparkle(hoops[4] + np.array([np.cos(a) * 3.4, np.sin(a) * 3.4, -0.7]), size=2.6)
+g.flare()
+g.stage('effects')
+
+# ---- HUD
+g.counter('HOOPS', '04/09', 8, 6, icon='ring')
+g.counter('LAP 2/3', "1'07\"42", 376, 6, anchor='r')
+g.gauge(8, 196, 0.72, label='SPD', number='214', unit='KM/H')
+g.text('ALT 014 M', 8, 170, 1, HUD_GREEN)
+g.minimap(306, 136, 378, 208, path, 0, 225, hoops, done=4, plane=plane, heading=aim, finish=g.along(path, 214),
+ title='MESA RUN')
+
+g.save(out, stages_dir=stages)
+print(f'{out} {time.time() - t0:.1f}s')
diff --git a/examples/mosaic_harbor.jpg b/examples/mosaic_harbor.jpg
new file mode 100644
index 0000000..0d9dc68
Binary files /dev/null and b/examples/mosaic_harbor.jpg differ
diff --git a/examples/mosaic_harbor.py b/examples/mosaic_harbor.py
new file mode 100644
index 0000000..65697dd
--- /dev/null
+++ b/examples/mosaic_harbor.py
@@ -0,0 +1,383 @@
+"""Example (Roman floor mosaic): The Day's Catch / 港口渔获 — a harbour panel set in stone and glass tesserae.
+A lighthouse burns on its mole, a fishing boat with an eye on its bow has hauled its net out on a pole, and an
+octopus has reached up and pulled one fish back out through the mesh while three more escape below.
+Gulls overhead. A tabula ansata reads CAPTVRA · DIEI / ET POLYPVS FVR ("the day's catch -- and the octopus,
+a thief"). Black-and-white running-wave border with red corner diamonds. Figures in opus vermiculatum (rows
+follow every outline and ring every eye), the ground in opus tessellatum with a halo round each figure, the sea
+in wavy rows; then time: lost patches showing the sockets in the old bed, a settling crack, dirt in the joints.
+No image model.
+python3 mosaic_harbor.py [out.jpg] [--stages DIR]
+"""
+import os, sys, time
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from mosaic import Mosaic
+from core import spline, blob_pts, blur
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'mosaic_harbor.jpg'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+t0 = time.time()
+
+W, H = 1920, 1080
+m = Mosaic(W, H, seed=11, tile=13)
+rng = m.rng
+YY, XX = np.mgrid[0:H, 0:W].astype(np.float32)
+
+# ------------------------------------------------------------------ layout
+BT = 10.0 # border stone
+BP = BT + m.gap # border row pitch
+F0 = 12 * BP # the field starts 12 border rows in
+FX0, FY0, FX1, FY1 = F0, F0, W - F0, H - F0
+field = m.rect(FX0, FY0, FX1, FY1)
+
+
+def waterline(x):
+ return 598 + 5 * np.sin(x / 52.0) + 3 * np.sin(x / 23.0 + 1.3)
+
+
+sea = field * (YY >= waterline(XX))
+sky = field * (YY < waterline(XX))
+FIG = 7.5 # figure stones are smaller (vermiculatum)
+
+
+def tf(pts, cx, cy, ang=0.0, flip=False):
+ """local -> canvas: rotate (deg, ccw), optional mirror, translate"""
+ P = np.asarray(pts, np.float32).copy()
+ if flip: P[:, 0] = -P[:, 0]
+ a = np.radians(ang); c, s = np.cos(a), np.sin(a)
+ return np.stack([cx + P[:, 0] * c + P[:, 1] * s, cy - P[:, 0] * s + P[:, 1] * c], 1)
+
+
+# ------------------------------------------------------------------ the cartoon: what the stones will copy
+m.paint(np.ones((H, W), np.float32), 'white')
+m.shade(sky, '#e6decb', '#ece5d4', (0, FY0), (0, 600))
+m.shade(sea, 'sky', 'blue', (0, 600), (0, FY1), gamma=0.8)
+
+# border: two outer white rows, two black, a band of running waves, one black row
+yy_d = np.minimum(np.minimum(XX + 0.5, W - XX - 0.5), np.minimum(YY + 0.5, H - YY - 0.5))
+m.paint((yy_d >= 2 * BP) & (yy_d < 4 * BP), 'black')
+m.paint((yy_d >= 11 * BP) & (yy_d < 12 * BP), 'black')
+WB0, WBH = 4 * BP, 7 * BP # wave band: offset from the edge and height
+waves = []
+
+
+def wave_parts(u0, period):
+ """one running wave in band coordinates (u along the travel direction, v inward from the outer fillet, unit =
+ band height): a solid body rising from the fillet, and a crest that curls forward round a white eye"""
+ k = period / (1.5 * WBH)
+ body = [(0.0, -0.12), (0.2, 0.04), (0.42, 0.26), (0.6, 0.55), (0.76, 0.74), (0.86, 0.66), (0.86, 0.44),
+ (0.9, 0.22), (1.0, 0.06), (1.12, -0.12)]
+ curl = [(0.62, 0.62), (0.8, 0.8), (1.0, 0.84), (1.16, 0.72), (1.22, 0.52), (1.14, 0.34), (1.0, 0.3),
+ (0.92, 0.4), (0.96, 0.54), (1.06, 0.56)]
+ f = lambda pts: [(u0 + x * k * WBH, y * WBH) for x, y in pts]
+ return f(body), f(curl)
+
+
+def band_to_canvas(side, u, v):
+ if side == 0: return WB0 + WBH + u, WB0 + v # top, travelling right
+ if side == 1: return W - WB0 - v, WB0 + WBH + u # right, travelling down
+ if side == 2: return W - WB0 - WBH - u, H - WB0 - v # bottom, travelling left
+ return WB0 + v, H - WB0 - WBH - u # left, travelling up
+
+
+for side in range(4):
+ length = (W if side % 2 == 0 else H) - 2 * (WB0 + WBH)
+ n = int(round(length / (1.5 * WBH)))
+ per = length / n
+ for i in range(n):
+ body, curl = wave_parts(i * per, per)
+ body = [band_to_canvas(side, u, v) for u, v in body]
+ curl = spline([band_to_canvas(side, u, v) for u, v in curl], 8)
+ waves.append((body, curl))
+corner_d = []
+for cx, cy in ((WB0 + WBH / 2, WB0 + WBH / 2), (W - WB0 - WBH / 2, WB0 + WBH / 2),
+ (W - WB0 - WBH / 2, H - WB0 - WBH / 2), (WB0 + WBH / 2, H - WB0 - WBH / 2)):
+ r = WBH * 0.45
+ corner_d.append(((cx, cy), m.poly_mask([(cx, cy - r), (cx + r, cy), (cx, cy + r), (cx - r, cy)])))
+wave_mask = lambda w: np.clip(m.poly_mask(spline(w[0] + [w[0][0]], 5)) + m.band(w[1], WBH * 0.2, WBH * 0.12), 0, 1)
+all_waves = np.zeros((H, W), np.float32)
+for w in waves: all_waves = np.maximum(all_waves, wave_mask(w))
+m.paint(all_waves, 'black')
+for (cx, cy), dm in corner_d:
+ m.paint(dm, 'red')
+
+# --- lighthouse on its mole (left)
+rocks = m.poly_mask(spline([(158, 652), (172, 612), (204, 590), (242, 576), (282, 569), (330, 565), (374, 572),
+ (412, 589), (440, 612), (452, 642), (428, 664), (370, 672), (290, 674), (210, 668), (158, 652)], 6))
+m.shade(rocks, 'grey', 'slate', (300, 565), (300, 672))
+tier1 = m.poly_mask([(232, 578), (368, 578), (359, 447), (241, 447)])
+corn1 = m.poly_mask([(226, 449), (374, 449), (374, 434), (226, 434)])
+tier2 = m.poly_mask([(250, 436), (350, 436), (344, 348), (256, 348)])
+corn2 = m.poly_mask([(244, 350), (356, 350), (356, 336), (244, 336)])
+tier3 = m.poly_mask([(264, 338), (336, 338), (332, 276), (268, 276)])
+deck = m.poly_mask([(254, 278), (346, 278), (346, 264), (254, 264)])
+flame = m.poly_mask(spline([(264, 266), (258, 236), (266, 212), (276, 226), (282, 196), (294, 168), (304, 194),
+ (314, 214), (324, 200), (338, 228), (336, 266)], 6))
+inner_flame = m.poly_mask(spline([(282, 266), (280, 242), (290, 222), (298, 202), (306, 224), (318, 244), (318, 266)], 6))
+tower = np.clip(tier1 + tier2 + tier3, 0, 1)
+m.shade(tower, 'white', 'buff', (230, 0), (372, 0), gamma=1.6)
+for c_ in (corn1, corn2, deck):
+ m.shade(c_, 'ochre', 'brown', (230, 0), (372, 0))
+m.shade(flame, 'gold', 'scarlet', (300, 266), (300, 180))
+m.paint(inner_flame, 'gold')
+
+# --- boat
+hull_top = [(612, 530), (700, 541), (800, 547), (900, 547), (1000, 543), (1100, 535), (1176, 524)]
+hull_bot = [(1196, 546), (1183, 580), (1150, 609), (1050, 631), (900, 640), (760, 632), (672, 612), (632, 586), (612, 556)]
+hull = m.poly_mask(spline(hull_top + hull_bot + [hull_top[0]], 6))
+m.shade(hull, 'brown', 'umber', (0, 535), (0, 640))
+wale = m.band(spline([(618, 547), (700, 556), (800, 562), (900, 562), (1000, 558), (1100, 551), (1182, 541)], 6), 13)
+m.paint(wale * hull, 'red')
+stern = spline([(626, 548), (603, 506), (594, 462), (604, 426), (628, 410), (648, 420), (644, 442), (627, 442)], 8)
+stern_m = m.band(stern, 22, 11)
+m.shade(stern_m, 'brown', 'umber', (600, 400), (600, 550))
+blade = m.ellipse(578, 664, 12, 30, rot=-28)
+m.shade(blade, 'ochre', 'brown', (560, 640), (600, 690))
+sail = m.poly_mask(spline([(770, 344), (880, 337), (992, 341), (1010, 382), (1012, 428), (996, 470), (940, 466),
+ (880, 470), (820, 474), (780, 476), (786, 430), (776, 386), (770, 344)], 5))
+m.shade(sail, 'white', 'buff', (790, 0), (1012, 0), gamma=1.5)
+
+# --- net on its pole, with fish piled in it
+bag = m.poly_mask(spline([(1242, 495), (1222, 560), (1212, 630), (1224, 704), (1258, 758), (1302, 770), (1338, 742),
+ (1352, 690), (1346, 610), (1328, 530), (1302, 470), (1270, 482), (1242, 495)], 6))
+
+FISH = { # back, belly, fin colours; stripe; dark bars
+ 'bream': ('slate', 'white', 'grey', None, False),
+ 'mullet': ('red', 'rose', 'pink', 'yellow', False),
+ 'mackerel': ('teal', 'white', 'sky', None, True),
+}
+
+
+def fish(cx, cy, L, ang=0.0, kind='bream', flip=False, hh=0.36):
+ """a fish in local coordinates (snout toward +x); returns its parts already painted into the cartoon"""
+ Hh = L * hh
+ t = np.linspace(0, 1, 36)
+ xb = -0.32 * L + t * 0.82 * L
+ hb = Hh / 2 * np.sin(np.pi * np.clip(t, 0, 1) ** 0.85) ** 0.7
+ body_l = list(zip(xb, -hb)) + list(zip(xb[::-1], 0.9 * hb[::-1]))
+ tail_l = [(-0.29 * L, -0.08 * Hh), (-0.5 * L, -0.46 * Hh), (-0.44 * L, 0.0), (-0.5 * L, 0.46 * Hh), (-0.29 * L, 0.08 * Hh)]
+ dors_l = [(-0.1 * L, -0.36 * Hh), (0.0, -0.66 * Hh), (0.16 * L, -0.7 * Hh), (0.22 * L, -0.4 * Hh)]
+ anal_l = [(-0.16 * L, 0.32 * Hh), (-0.08 * L, 0.58 * Hh), (0.06 * L, 0.36 * Hh)]
+ back, belly, fin, stripe, bars = FISH[kind]
+ tr = lambda p: tf(p, cx, cy, ang, flip)
+ body = m.poly_mask(tr(body_l)); tail = m.poly_mask(tr(tail_l))
+ fins = np.clip(m.poly_mask(tr(dors_l)) + m.poly_mask(tr(anal_l)) + tail, 0, 1)
+ m.paint(fins, fin)
+ p0, p1 = tr([(0, -0.5 * Hh)])[0], tr([(0, 0.48 * Hh)])[0]
+ m.shade(body, back, belly, p0, p1, gamma=0.9)
+ whole = np.clip(body + fins, 0, 1)
+ eye = tr([(0.36 * L, -0.08 * Hh)])[0]
+ gill = tr([(0.25 * L, -0.3 * Hh), (0.2 * L, -0.05 * Hh), (0.22 * L, 0.2 * Hh), (0.27 * L, 0.32 * Hh)])
+ lines = []
+ if stripe: lines.append((tr([(-0.26 * L, 0.0), (0.0, -0.02 * Hh), (0.24 * L, 0.02 * Hh)]), stripe))
+ if bars:
+ for bx in (-0.18, -0.06, 0.06):
+ lines.append((tr([(bx * L, -0.42 * Hh), (bx * L + 0.04 * L, -0.12 * Hh)]), 'navy'))
+ return dict(mask=whole, eye=eye, gill=gill, lines=lines, size=L)
+
+
+net_fish = [fish(1284, 726, 118, 8, 'bream'), fish(1282, 652, 112, -18, 'mullet', flip=True)]
+stolen = fish(1436, 680, 150, 22, 'mullet', flip=True) # pulled out through the mesh
+free_fish = [fish(470, 790, 190, 4, 'mullet', flip=True), fish(760, 868, 160, -6, 'mackerel', flip=True),
+ fish(276, 872, 150, 8, 'bream', flip=True)]
+
+# --- the octopus: mantle, eyes, eight arms; the long one has wrapped round the stolen fish's tail
+OX, OY = 1606, 736
+mantle = m.ellipse(OX, OY, 54, 70, rot=-24)
+m.shade(mantle, 'red', 'brick', (OX + 28, OY - 66), (OX - 22, OY + 64))
+arms_p = [[(OX + x, OY + y) for x, y in a] for a in [
+ [(-44, 56), (-78, 44), (-100, 16), (-110, -22), (-104, -56), (-90, -82), (-72, -88), (-66, -72), (-80, -64)],
+ [(-40, 70), (-78, 104), (-100, 146), (-92, 174), (-66, 178), (-58, 158)],
+ [(-14, 78), (-14, 128), (4, 164), (38, 172), (54, 154), (40, 142)],
+ [(12, 72), (52, 104), (100, 118), (136, 102), (140, 76), (120, 72)],
+ [(28, 56), (74, 58), (118, 38), (144, 6), (136, -22), (116, -18)],
+ [(-56, 62), (-112, 76), (-150, 106), (-164, 146), (-142, 166), (-124, 150)],
+ [(-26, 76), (-44, 122), (-40, 160), (-22, 182)],
+]]
+arms = []
+for i, p in enumerate(arms_p):
+ path = spline(p, 10)
+ a = m.band(path, 22 if i == 0 else 20, 5)
+ arms.append((path, a))
+ m.shade(a, 'brick', 'pink', tuple(path[0]), tuple(path[-1]))
+octo = np.clip(mantle + sum(a for _, a in arms), 0, 1)
+
+# --- gulls
+gulls = [(530, 300, 66, 6), (668, 236, 52, -8), (1530, 412, 58, 4)]
+
+
+def gull_strokes(cx, cy, w, ang):
+ L_ = tf([(-w / 2, -w * 0.05), (-w * 0.3, -w * 0.2), (-w * 0.1, -w * 0.12), (0, 0)], cx, cy, ang)
+ R_ = tf([(0, 0), (w * 0.1, -w * 0.13), (w * 0.3, -w * 0.21), (w / 2, -w * 0.06)], cx, cy, ang)
+ return [L_, R_]
+
+
+# --- tabula ansata (top right)
+TX0, TY0, TX1, TY1 = 1088, 172, 1614, 318
+
+# ------------------------------------------------------------------ 1. sinopia: the design brushed on the wet bed
+for msk in [rocks, tower, flame, hull, stern_m, sail, bag, mantle, blade] + [f['mask'] for f in net_fish + free_fish + [stolen]] + [a for _, a in arms]:
+ m.sinopia(msk, width=3.2)
+for w in waves[::2]: m.sinopia(pts=w[1][::4], width=3.0, strength=0.55)
+m.sinopia(pts=[(880, 546), (880, 300)], width=3.0)
+m.sinopia(pts=[(TX0, TY0), (TX1, TY0), (TX1, TY1), (TX0, TY1), (TX0, TY0)], width=2.6, strength=0.6)
+m.sinopia(pts=[(FX0, 600), (FX1, 600)], width=2.4, strength=0.45)
+for x in (FX0, FX1):
+ m.sinopia(pts=[(x, FY0), (x, FY1)], width=2.4, strength=0.5)
+for y in (FY0, FY1):
+ m.sinopia(pts=[(FX0, y), (FX1, y)], width=2.4, strength=0.5)
+m.stage('sinopia')
+
+# ------------------------------------------------------------------ 2. the border
+for w in waves:
+ wm = wave_mask(w)
+ m.line(w[1], 'black', BT * 0.9)
+ m.outline(wm, 'black', 1, BT * 0.9)
+ m.fill(wm, BT * 0.9, colour='black')
+for (cx, cy), dm in corner_d:
+ m.point(cx, cy, 'white', BT * 0.9, 'square', angle=45)
+ m.outline(dm, 'black', 1, BT * 0.9)
+ m.fill(dm, BT * 0.9, stones=['red', 'brick'])
+band = ((yy_d >= WB0) & (yy_d < WB0 + WBH)).astype(np.float32)
+m.halo(band, rows=1, size=BT, stones=['white', 'bone'], around=np.clip(all_waves + sum(d for _, d in corner_d), 0, 1))
+m.frame(0, 0, W, H, 12 * BP, size=BT, stones=['white', 'bone', 'black'])
+m.stage('border')
+
+# ------------------------------------------------------------------ 3. eyes, details and outlines
+def eye(x, y, s=FIG):
+ m.point(x, y, 'black', s * 0.85, 'round')
+ ring = m.ellipse(x, y, s * 1.6, s * 1.6)
+ m.halo(ring, rows=1, size=s * 0.75, colour='white', around=m.ellipse(x, y, s * 0.5, s * 0.5))
+
+
+# lighthouse: door, windows, masonry courses, flame tongues
+m.line([(300, 576), (300, 540)], 'black', 9, across=16)
+for wy in (488, 392, 306):
+ m.line([(300, wy - 12), (300, wy + 12)], 'black', 8, across=10)
+for y_ in (552, 526, 500, 474):
+ m.line([(240, y_), (362, y_)], 'buff', 7, across=4.5, keep=0.6)
+for y_ in (412, 384, 360):
+ m.line([(256, y_), (346, y_)], 'buff', 7, across=4.5, keep=0.6)
+for a_ in (28, 62, 118, 152):
+ r0, r1 = 66, 104
+ m.line([(300 + r0 * np.cos(np.radians(a_)), 222 - r0 * np.sin(np.radians(a_))),
+ (300 + r1 * np.cos(np.radians(a_)), 222 - r1 * np.sin(np.radians(a_)))], 'gold', 8)
+for p in ([(176, 646), (206, 616), (244, 606), (262, 630), (250, 662)], [(262, 630), (300, 618), (340, 628), (356, 664)],
+ [(340, 628), (372, 600), (412, 604), (436, 630)], [(244, 606), (262, 580)], [(372, 600), (360, 574)]):
+ m.line(p, 'black', 6, across=5)
+
+# boat: oculus, planks, mast, yard, rigging, steering oar
+eye(1124, 564, 8)
+for off in (36, 62):
+ pl = [(x_, y_ + off) for x_, y_ in [(640, 548), (720, 556), (820, 561), (920, 561), (1020, 557), (1110, 549), (1160, 543)]]
+ m.line(pl, 'umber', 7, across=5)
+m.line([(880, 548), (880, 302)], 'umber', 10, across=11)
+m.line([(758, 340), (880, 330), (1002, 336)], 'umber', 9, across=9)
+for x_, b_ in ((812, 4), (846, 8), (916, 12), (954, 14)):
+ m.line([(x_, 350), (x_ + b_, 410), (x_ + b_ * 0.6, 464)], 'buff', 6, across=4.5)
+m.line([(880, 306), (1170, 524)], 'slate', 6, across=5)
+m.line([(880, 306), (640, 418)], 'slate', 6, across=5)
+m.line([(652, 522), (616, 586), (590, 636)], 'brown', 8, across=9)
+m.line(stern, None, 8) # spine row of the stern post
+m.line([(1160, 532), (1230, 500), (1310, 466)], 'umber', 9, across=9) # net pole
+
+# net: the fish in it are set first and whole; the cords run between them and over the water behind
+for f in net_fish:
+ eye(*f['eye'], 6)
+ m.line(f['gill'], 'umber', 5, across=4)
+ for p, c in f['lines']: m.line(p, c, 5, across=4)
+ m.outline(f['mask'], 'black', 1, 6)
+ m.fill(f['mask'], 6.5)
+bag_d = (bag > 0.5)
+for k in range(-5, 7):
+ for sgn in (1, -1):
+ x_a = 1280 + k * 40
+ p = np.array([(x_a + sgn * t_ * 0.75, 460 + t_) for t_ in np.linspace(0, 330, 120)])
+ inside = bag_d[np.clip(p[:, 1].astype(int), 0, H - 1), np.clip(p[:, 0].astype(int), 0, W - 1)]
+ if inside.sum() < 6: continue
+ idx = np.nonzero(inside)[0]
+ m.line(p[idx[0]:idx[-1] + 1], 'black', 5.5, across=3.8, smooth=False, keep=0.45)
+bag_edge = spline([(1242, 495), (1222, 560), (1212, 630), (1224, 704), (1258, 758), (1302, 770), (1338, 742),
+ (1352, 690), (1346, 610), (1328, 530), (1302, 470)], 6)
+m.line(bag_edge, 'umber', 6, across=6)
+
+# octopus: eyes, suckers, spine rows of the arms, outline
+eye(OX - 30, OY + 40, 9); eye(OX + 14, OY + 52, 9)
+for i, (path, a) in enumerate(arms):
+ n_ = len(path)
+ for j in range(int(n_ * 0.08), int(n_ * 0.7), 5):
+ p, q = path[j], path[min(j + 2, n_ - 1)]
+ d = q - p; d /= np.linalg.norm(d) + 1e-6
+ w_ = (22 - 17 * j / n_) * 0.28
+ m.point(p[0] - d[1] * w_, p[1] + d[0] * w_, 'rose', 5.5, 'round')
+ m.line(path, None, 6.5, stones=['brick', 'pink', 'red', 'rose'])
+m.outline(octo, 'umber', 1, 6.5)
+for sx, sy in ((OX + 16, OY - 40), (OX - 12, OY - 14), (OX + 28, OY + 2), (OX + 4, OY - 62)):
+ m.point(sx, sy, 'umber', 6, 'round')
+
+# free fish (and the stolen one), rocks, tower, hull, stern, sail, blade
+for f in free_fish + [stolen]:
+ eye(*f['eye'], 7)
+ m.line(f['gill'], 'umber', 6, across=4.5)
+ for p, c in f['lines']: m.line(p, c, 6, across=4.5)
+ m.outline(f['mask'], 'black', 1, FIG * 0.95)
+for msk, c in ((rocks, 'black'), (tower, 'umber'), (corn1, 'umber'), (corn2, 'umber'), (deck, 'umber'),
+ (flame, 'red'), (hull, 'black'), (stern_m, 'black'), (blade, 'umber')):
+ m.outline(msk, c, 1, FIG)
+m.outline(sail, 'brown', 1, 6)
+for gx, gy, gw, ga in gulls:
+ for p in gull_strokes(gx, gy, gw, ga):
+ m.line(p, 'slate', 6.5, across=6)
+m.stage('outlines')
+
+# ------------------------------------------------------------------ 4. fill the figures (colours from the cartoon)
+for f in free_fish + [stolen]:
+ m.fill(f['mask'], FIG)
+m.fill(mantle * (1 - m.everything()), 7)
+m.fill(octo, 6.5)
+m.fill(inner_flame, 6, stones=['gold', 'yellow'])
+for msk in (flame, corn1, corn2, deck, tower, rocks, sail, blade, stern_m, hull):
+ m.fill(msk, FIG)
+m.stage('figures')
+
+# ------------------------------------------------------------------ 5. the inscription
+m.tabula(TX0, TY0, TX1, TY1, [('CAPTVRA · DIEI', 44, 'black'), ('ET POLYPVS FVR', 31, 'red')], ear=58, size=8)
+m.stage('inscription')
+
+# ------------------------------------------------------------------ 6. halo, ground, sea
+big = np.clip(rocks + tower + flame + hull + stern_m + sail + mantle + bag + m.poly_mask([(TX0 - 60, TY0), (TX1 + 60, TY0), (TX1 + 60, TY1), (TX0 - 60, TY1)]), 0, 1)
+m.halo(sky, rows=1, size=11, stones=['white', 'bone'])
+m.halo(sea, rows=1, size=11, stones=['pale', 'sky', 'blue'])
+near_big = (blur(big, 9) > 0.08) * m.everything() # the big figures and their first ring
+m.halo(sky, rows=1, size=11, stones=['white', 'bone'], around=near_big)
+m.halo(sea, rows=1, size=11, stones=['pale', 'sky', 'blue'], around=near_big)
+m.stage('halo')
+m.rows(sky, size=12.5, wobble=6, stones=['white', 'bone', 'cream'])
+m.stage('ground')
+# water: dark wave strokes and white crests, then wavy rows
+for wy in range(650, 930, 46):
+ for k in range(9):
+ x_ = FX0 + 60 + k * 190 + (wy * 7) % 120 + rng.uniform(-30, 30)
+ pts = [(x_ + t_, wy + rng.uniform(-6, 6) + 7 * np.sin(t_ / 22.0)) for t_ in np.linspace(0, 120, 10)]
+ if x_ + 130 > FX1: continue
+ m.line(pts, 'navy', 8, across=6, keep=0.6)
+for k in range(14):
+ x_ = FX0 + 20 + k * 118 + rng.uniform(-10, 10)
+ pts = [(x_ + t_, waterline(x_ + t_) + 13 + 4 * np.sin(t_ / 14.0)) for t_ in np.linspace(0, 70, 8)]
+ if x_ + 80 > FX1: continue
+ m.line(pts, 'white', 7, across=6, keep=0.6)
+wav = YY - 7 * np.sin(XX / 38.0 + YY / 60.0)
+m.rows(sea, size=11, field=wav, stones=['pale', 'sky', 'blue', 'navy', 'teal'])
+m.stage('sea')
+
+# ------------------------------------------------------------------ 7. two thousand years
+m.lacuna(m.poly_mask(blob_pts(176, 984, 84, 52, rough=0.3, seed=4)))
+m.lacuna(m.poly_mask(blob_pts(1912, 640, 40, 70, rough=0.3, seed=8)))
+m.lacuna(m.poly_mask(blob_pts(1030, 900, 52, 30, rough=0.3, seed=9, rot=0.3)))
+m.crack([(1004, 1080), (1012, 1010), (1046, 950), (1040, 890), (1078, 830), (1120, 790), (1136, 744)])
+m.crack([(1920, 210), (1862, 236), (1808, 232), (1760, 262)])
+m.patina(1.0)
+
+print('laid', len(m.poly), 'stones in', round(time.time() - t0, 1), 's')
+m.save(out, stages_dir=stages)
+print('done', round(time.time() - t0, 1), 's')
diff --git a/examples/patch_camping.jpg b/examples/patch_camping.jpg
new file mode 100644
index 0000000..9058c82
Binary files /dev/null and b/examples/patch_camping.jpg differ
diff --git a/examples/patch_camping.py b/examples/patch_camping.py
new file mode 100644
index 0000000..3989a41
--- /dev/null
+++ b/examples/patch_camping.py
@@ -0,0 +1,211 @@
+"""Example (embroidered patches / 刺绣徽章): 三晚露营 · Three Nights Out — the back of a denim jacket that keeps a
+camping trip: one patch per night, joined by a sashiko trail. Night 1, a die-cut arch with a hot-cut satin border:
+a tent with its lantern lit on a lake shore at sunset. Night 2, a round merrowed badge: high camp, a campfire under
+a two-tone peak with snowcaps, moon and stars, lettering on the ring. Night 3, the way home: a compass rose on cream
+twill, still being sewn on -- whip stitches have gone two-thirds of the way round and the needle lies on the denim
+with the thread running back to the last stitch. A curved rocker over the middle badge reads THREE NIGHTS OUT; a
+felled yoke seam with double topstitching runs across the top.
+Draw-on stages: denim -> blanks -> background fills -> scenery -> satin -> details -> lettering -> edges -> trail
+-> sewing. No image model.
+python3 patch_camping.py [out.jpg] [--stages DIR]
+"""
+import os, sys, time
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from patch import Patch
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'patch_camping.jpg'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+t0 = time.time()
+
+CREAM, GOLD, NAVY = '#f1e5c6', '#d89c33', '#24325a'
+K = 1.14 # the patches are drawn in design units around (960, 660)
+
+
+def T(*pts):
+ """design units -> canvas pixels"""
+ return [((x - 960) * K + 960, (y - 660) * K + 612) for x, y in pts]
+
+
+def P1(x, y):
+ return T((x, y))[0]
+
+
+p = Patch(1920, 1080, seed=7)
+
+# ---- 0. the denim: a jacket back with a felled yoke seam
+p.denim()
+p.seam([(-30, 132), (480, 146), (960, 158), (1440, 146), (1950, 132)])
+p.stage('denim')
+
+# ---- 1. the cut blanks
+AX, AY = P1(960, 660); AR = 238 * K # night 2: round badge
+BX, BTOP = P1(430, 455); BW, BH = 330 * K, 400 * K # night 1: die-cut arch
+CX, CY = P1(1500, 612); CR = 172 * K # night 3: compass, being sewn on
+rocker = p.blank(p.rocker_pts(AX, AY, 266 * K, 334 * K, span=98), '#a8322a')
+bA = p.blank(p.circle_pts(AX, AY, AR), '#1a2346')
+bB = p.blank(p.arch_pts(BX, BTOP, BW, BH, corner=34), '#2e3a6e')
+bC = p.blank(p.circle_pts(CX, CY, CR), '#ece2c9')
+p.stage('blanks')
+
+# ---- 2. background fills (tatami)
+p.fill(rocker.mask, '#ad3328', angle=8)
+p.fill(bA.mask, '#1a2346', angle=32)
+scene = p.circle(AX, AY, 176 * K)
+p.fill(scene * p.poly(T((760, 470), (1160, 470), (1160, 640), (1060, 628), (960, 642), (860, 630), (760, 645))),
+ '#22336a', angle=-24)
+p.fill(scene * p.poly(T((760, 645), (860, 630), (960, 642), (1060, 628), (1160, 640), (1160, 860), (760, 860))),
+ '#34508a', angle=-24)
+archm = bB.mask
+bands = [('#2e3a6e', 455, 585), ('#7b4a86', 585, 640), ('#d0566a', 640, 680), ('#f08a48', 680, 712)]
+edges = {585: [(250, 590), (330, 580), (430, 592), (530, 578), (610, 588)],
+ 640: [(250, 636), (340, 646), (440, 634), (540, 646), (610, 638)],
+ 680: [(250, 682), (350, 676), (450, 684), (550, 676), (610, 682)]}
+for col, ya, yb in bands:
+ top = edges.get(ya, [(250, ya), (610, ya)])
+ bot = edges.get(yb, [(250, yb), (610, yb)])
+ p.fill(archm * p.poly(T(*top, *bot[::-1])), col, angle=0, length=14)
+p.stage('fills')
+
+# ---- 3. scenery: hills, lake, shore (night 1); peaks, ground (night 2)
+p.fill(archm * p.circle(*P1(470, 712), 44 * K) * p.poly(T((400, 640), (540, 640), (540, 712), (400, 712))), '#f7c84a',
+ angle=90, kind='satin', maxlen=40)
+hills = [(250, 712), (250, 690), (290, 682), (330, 694), (380, 678), (430, 690), (520, 676), (570, 690), (610, 684), (610, 712)]
+p.fill(archm * p.poly(T(*hills)), '#30574a', angle=15, length=12)
+p.fill(archm * p.poly(T((250, 710), (610, 710), (610, 790), (250, 790))), '#3b74a8', angle=0, length=16)
+shore = [(250, 790), (330, 784), (420, 792), (520, 780), (610, 786), (610, 860), (250, 860)]
+p.fill(archm * p.poly(T(*shore)), '#557c3a', angle=12, length=13)
+
+# night 2: a far ridge, the back peak, the main peak (lit side / shade side), the ground
+p.fill(scene * p.poly(T((760, 800), (760, 700), (800, 690), (830, 712), (1080, 700), (1120, 676), (1160, 690), (1160, 800))),
+ '#2b3f6e', angle=20, length=12)
+p.fill(scene * p.poly(T((790, 800), (872, 612), (912, 690), (900, 800))), '#7d93ba', angle=62)
+p.fill(scene * p.poly(T((872, 612), (912, 690), (972, 760), (960, 800), (900, 800), (905, 700), (884, 650))),
+ '#4a5e88', angle=-60)
+lit = [(842, 800), (925, 650), (944, 662), (985, 548), (994, 606), (976, 662), (1003, 724), (990, 800)]
+shade = [(985, 548), (1046, 640), (1062, 630), (1130, 800), (990, 800), (1003, 724), (976, 662), (994, 606)]
+p.fill(scene * p.poly(T(*lit)), '#9fb4d4', angle=60)
+p.fill(scene * p.poly(T(*shade)), '#4b6089', angle=-55)
+ground = [(760, 800), (820, 786), (900, 795), (960, 788), (1020, 796), (1100, 784), (1160, 794), (1160, 860), (760, 860)]
+p.fill(scene * p.poly(T(*ground)), '#26472e', angle=10, length=13)
+p.stage('scenery')
+
+# ---- 4. satin: snowcaps, tent, sun glints, campfire, moon, compass rose
+p.fill(scene * p.poly(T((985, 548), (994, 606), (984, 598), (976, 612), (966, 600), (957, 606), (964, 585))), '#f6f3ec',
+ angle=-58, kind='satin')
+p.fill(scene * p.poly(T((985, 548), (1018, 597), (1006, 592), (996, 604), (994, 606))), '#aebbd3', angle=58, kind='satin')
+p.fill(scene * p.poly(T((925, 650), (944, 662), (930, 664), (921, 676), (912, 668))), '#e9edf3', angle=-60, kind='satin')
+p.fill(scene * p.poly(T((872, 612), (888, 642), (879, 638), (872, 650), (864, 640), (858, 645))), '#e9edf3', angle=-62, kind='satin')
+# the tent: front panel lit, side panel in shade, the door glowing from the lantern inside
+p.fill(archm * p.poly(T((352, 702), (300, 800), (404, 800))), '#ec7a30', angle=-28, kind='satin')
+p.fill(archm * p.poly(T((352, 702), (404, 800), (470, 792), (418, 700))), '#a9441f', angle=30, kind='satin')
+p.fill(archm * p.poly(T((352, 734), (333, 800), (371, 800))), '#f8c24a', angle=90, kind='satin')
+p.column(T((352, 698), (352, 800)), '#6b3418', width=3.4)
+for i, (x, w) in enumerate([(470, 46), (462, 34), (474, 24), (468, 14)]):
+ y = 724 + i * 15
+ p.column(T((x - w / 2, y), (x + w / 2, y)), '#f7c84a' if i % 2 == 0 else '#f3a24a', width=4.6)
+# campfire: crossed logs, then three flames, outer to inner
+p.column(T((912, 826), (1006, 802)), '#7a4a2a', width=11)
+p.column(T((914, 801), (1008, 826)), '#5e3820', width=11)
+flame = lambda cx, by, w, h, lean: T((cx - w, by), (cx - w * 0.9, by - h * 0.35), (cx - w * 0.35, by - h * 0.7),
+ (cx + lean, by - h), (cx + w * 0.45, by - h * 0.62), (cx + w * 0.95, by - h * 0.3), (cx + w, by))
+p.fill(scene * p.poly(flame(960, 814, 34, 100, 5), smooth=2), '#d8432c', angle=14, kind='satin', maxlen=90)
+p.fill(scene * p.poly(flame(961, 814, 23, 72, -4), smooth=2), '#f08a24', angle=-16, kind='satin', maxlen=90)
+p.fill(scene * p.poly(flame(962, 814, 12, 42, 2), smooth=2), '#fadb68', angle=10, kind='satin')
+# the moon: a crescent
+mx, my = P1(1052, 548)
+moon = p.circle(mx, my, 25 * K) * (1 - p.circle(mx + 12 * K, my - 8 * K, 21 * K))
+p.fill(moon, '#f3e7bd', angle=-40, kind='satin')
+
+
+# compass rose: four cardinal points split light / dark, four gold diagonals behind
+def kite(ang, length, half, light, dark):
+ a = np.deg2rad(ang)
+ tip = (CX + length * np.cos(a), CY - length * np.sin(a))
+ l = (CX + half * np.cos(a + np.pi / 2), CY - half * np.sin(a + np.pi / 2))
+ r = (CX + half * np.cos(a - np.pi / 2), CY - half * np.sin(a - np.pi / 2))
+ p.fill(p.poly([(CX, CY), l, tip]), light, angle=ang + 90, kind='satin', pitch=2.1)
+ p.fill(p.poly([(CX, CY), tip, r]), dark, angle=ang + 90, kind='satin', pitch=2.1)
+
+
+for ang in (45, 135, 225, 315):
+ kite(ang, 82 * K, 16 * K, '#eab04a', '#9c6a1a')
+kite(90, 112 * K, 24 * K, '#cf4637', '#721a14')
+for ang in (0, 180, 270):
+ kite(ang, 112 * K, 24 * K, '#6f8bc2', '#1f2b52')
+p.stage('satin')
+
+# ---- 5. details: rings, ticks, stars, sparks, ripples, trees
+p.column(p.circle_pts(AX, AY, 179 * K), GOLD, width=11, closed=True) # ring separator, night 2
+p.column(p.circle_pts(CX, CY, 140 * K), NAVY, width=5.5, closed=True) # compass ring
+for k in range(36):
+ a = np.deg2rad(k * 10)
+ r0, r1 = ((144 * K, 157 * K) if k % 3 == 0 else (145 * K, 151 * K))
+ p.run([(CX + r0 * np.cos(a), CY - r0 * np.sin(a)), (CX + r1 * np.cos(a), CY - r1 * np.sin(a))], NAVY,
+ stitch=1e6, gap=0, width=2.6, smooth=False, shadow=0.3)
+p.knot(CX, CY, CREAM, r=8)
+
+
+def pine(x, base, h, w, col):
+ tiers = 4
+ zig_l, zig_r = [], []
+ for i in range(tiers):
+ y = base - h * i / tiers; ww = w * 0.5 * (1 - i / tiers)
+ zig_l += [(x - ww, y), (x - ww * 0.45, y - h / tiers * 0.55)]
+ zig_r += [(x + ww * 0.45, y - h / tiers * 0.55), (x + ww, y)]
+ outline = zig_l + [(x, base - h)] + zig_r[::-1]
+ p.fill(scene * p.poly(T(*outline)), col, angle=0, kind='satin', pitch=2.0)
+ p.column(T((x, base + 6), (x, base - 2)), '#4a2e1c', width=3.2)
+
+
+for x, h, w, c in [(812, 58, 30, '#1d4632'), (838, 76, 36, '#2b5e41'), (866, 52, 28, '#1d4632'), (892, 64, 30, '#2b5e41'),
+ (1032, 60, 30, '#2b5e41'), (1060, 80, 38, '#1d4632'), (1090, 56, 28, '#2b5e41'), (1114, 44, 24, '#1d4632')]:
+ pine(x, 806, h, w, c)
+for x, y, r in [(870, 532, 10), (912, 506, 7), (1118, 604, 8), (838, 586, 6), (1006, 506, 6)]:
+ p.star(*P1(x, y), r * K, CREAM, angle=12)
+for x, y in [(944, 700), (982, 688), (962, 672)]:
+ p.knot(*P1(x, y), '#fadb68', r=2.4)
+for x, y, r in [(300, 552, 6), (380, 560, 5), (476, 548, 7), (566, 566, 5), (330, 578, 4)]:
+ p.star(*P1(x, y), r * K, CREAM, angle=0)
+for y, xa, xb in [(732, 504, 572), (748, 520, 578), (764, 262, 300), (776, 486, 566), (742, 262, 288)]:
+ p.run(T((xa, y), ((xa + xb) / 2, y - 3), (xb, y)), '#bcd6ec', stitch=12, gap=5, width=2.3, shadow=0.25, clip=archm)
+p.run(T((300, 800), (276, 822)), '#d9d2c2', stitch=1e6, gap=0, width=1.9, smooth=False) # guy lines
+p.run(T((470, 792), (500, 815)), '#d9d2c2', stitch=1e6, gap=0, width=1.9, smooth=False)
+p.stage('details')
+
+# ---- 6. lettering
+p.arc_text('THREE NIGHTS OUT', AX, AY, 300 * K, size=42, colour=CREAM, spacing=0.05)
+p.arc_text('HIGH CAMP', AX, AY, 205 * K, size=42, colour=CREAM)
+p.arc_text('NIGHT 2', AX, AY, 207 * K, size=38, colour=CREAM, centre=270, bottom=True)
+p.star(AX - 205 * K, AY, 9, GOLD); p.star(AX + 205 * K, AY, 9, GOLD)
+p.arc_text('NIGHT 1', BX, BTOP + BW / 2, 132 * K, size=34, colour=CREAM, spacing=0.12)
+for ch, ang in (('N', 90), ('E', 0), ('S', 270), ('W', 180)):
+ a = np.deg2rad(ang)
+ p.text(ch, CX + 124 * K * np.cos(a), CY - 124 * K * np.sin(a), 34, '#c63a2c' if ch == 'N' else NAVY)
+p.stage('lettering')
+
+# ---- 7. edges: merrow round the round ones, hot-cut satin round the die-cut arch
+p.merrow(rocker, GOLD, width=19)
+p.merrow(bA, GOLD, width=20)
+p.satin_border(bB, CREAM, width=17)
+p.merrow(bC, NAVY, width=20)
+p.stage('edges')
+
+# ---- 8. the sashiko trail: night 1 -> night 2 -> night 3
+p.run(T((606, 868), (650, 910), (720, 936), (800, 918), (840, 884)), '#ebe5d6', stitch=15, gap=9, width=4.2,
+ twist=1.0, sheen=0.35, shadow=0.45)
+p.run(T((1080, 884), (1150, 930), (1250, 938), (1340, 884), (1390, 800)), '#ebe5d6', stitch=15, gap=9, width=4.2,
+ twist=1.0, sheen=0.35, shadow=0.45, start=5)
+p.stage('trail')
+
+# ---- 9. sewing night 3 on: whip stitches two-thirds of the way round, needle and thread left on the denim
+last = p.whip(bC, '#efe6d2', frm=0.28, to=0.86, spacing=21, reach=(6, 19), lean=8, width=2.6)
+eye, tip = np.array([1716.0, 806.0]), np.array([1842.0, 990.0])
+u = (tip - eye) / np.linalg.norm(tip - eye); nrm = np.array([-u[1], u[0]])
+e = eye + u * 18
+p.thread([last, last + (18, 34), (1700, 790), e - nrm * 13, e, e + nrm * 13, (1680, 846), (1672, 876), (1686, 904)],
+ '#efe6d2', width=2.8, lift=1.2)
+p.needle(tuple(eye), tuple(tip), radius=3.7)
+
+img = p.save(out, stages)
+print(f'{out} {time.time() - t0:.1f}s')
diff --git a/examples/petroglyph_migration.jpg b/examples/petroglyph_migration.jpg
new file mode 100644
index 0000000..1840752
Binary files /dev/null and b/examples/petroglyph_migration.jpg differ
diff --git a/examples/petroglyph_migration.py b/examples/petroglyph_migration.py
new file mode 100644
index 0000000..82dcfe1
--- /dev/null
+++ b/examples/petroglyph_migration.py
@@ -0,0 +1,78 @@
+"""Example (petroglyph, pecked sandstone): Migration Season / 迁徙季 -- a panel of rock art hammered through desert
+varnish. A herd of bighorn sheep (rams, ewes, two lambs) walks one way along the rock toward a spring; hoofprints run
+ahead of the lead ram to the concentric rings of the waterhole, where a bowman waits; a second hunter with a raised
+atlatl follows the herd. Up top a spiral sun and a crescent moon with two rows of ground tally marks (a month of days).
+Two hands are pecked on the lower face under the ledge. Older work shows through, re-varnished almost to a ghost: a
+wavy river line and a large rake. The rock has cracks that bleed darker varnish streaks, spalls that took part of the
+older work with them, and lichen. No image model.
+python3 petroglyph_migration.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 petroglyph import Petroglyph
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'petroglyph_migration.jpg'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+
+pg = Petroglyph(1920, 1080, seed=11)
+
+# ---- the sandstone face, a ledge, desert varnish, cracks
+pg.rock()
+pg.ledge(912, drop=34)
+pg.stage('sandstone')
+pg.varnish()
+pg.fracture([(1010, -10), (985, 120), (948, 260), (930, 340)], width=3.2, depth=10, seep=0.7, branches=2)
+pg.fracture([(1930, 610), (1840, 700), (1760, 800), (1716, 912)], width=3.6, depth=11, seep=0.6, branches=1)
+pg.fracture([(560, 1090), (600, 1000), (640, 930)], width=2.6, depth=8, seep=0.0, branches=1)
+pg.stage('varnish')
+
+# ---- older work, re-varnished almost to a ghost: a wavy river line and a big rake
+river = [(380, 846), (520, 806), (660, 856), (800, 816), (940, 862), (1080, 822), (1220, 858), (1330, 828)]
+pg.peck(pg.meander(river, 16), age=0.66, density=0.8)
+rake = pg.meander([(700, 410), (1010, 392)], 14, smooth=False)
+for i in range(7):
+ x = 712 + i * 49
+ pg.meander([(x, 400 - i * 2.6), (x + 4, 462 - i * 2.6)], 12, into=rake, smooth=False)
+pg.peck(rake, age=0.6, density=0.85)
+pg.stage('old_marks')
+
+# ---- sky: spiral sun, crescent moon and a month of ground tally marks
+pg.peck(pg.sun_spiral(1590, 215, 100, turns=3.0, rays=13, width=13))
+pg.peck(pg.crescent(150, 168, 62, thick=0.45, rot=-20), age=0.32) # the day count is older
+pg.abrade_tally(250, 112, [15, 14], gap=27, length=58, width=8.5, row_gap=86, slant=5, age=0.3)
+pg.stage('sun_and_days')
+
+# ---- the herd, walking right (uphill) toward the spring: big animals in the upper file, ewes and lambs below
+herd = [(330, 712, 132, 'ewe', 0.6), (500, 608, 160, 'ram', -0.5), (520, 770, 92, 'lamb', -0.8),
+ (720, 590, 142, 'ewe', 0.7), (870, 716, 128, 'ewe', -0.3), (935, 566, 166, 'ram', -0.7),
+ (1035, 742, 94, 'lamb', 0.4), (1135, 548, 146, 'ewe', 0.5), (1330, 520, 192, 'ram', 0.6)]
+for i, (x, y, s, kind, g) in enumerate(herd):
+ pg.peck(pg.bighorn(x, y, s, facing=1, kind=kind, gait=g, rot=4))
+ if i == 4: pg.stage('herd_rear')
+pg.stage('herd')
+
+# ---- hoofprints from the lead ram down to the waterhole; the bowman waiting beyond it; a hunter following
+pg.peck(pg.hoofprints([(1468, 628), (1520, 656), (1572, 680)], size=34, every=50, stagger=10), size=0.66)
+pg.peck(pg.concentric(1672, 724, 78, rings=3, width=11))
+pg.peck(pg.hunter(1815, 560, 236, facing=-1, weapon='bow'))
+pg.peck(pg.hunter(140, 600, 214, facing=1, weapon='atlatl'), age=0.3)
+pg.stage('hunt')
+
+# ---- two hands on the lower face, under the ledge: a grown-up's and a child's
+pg.peck(pg.hand(1330, 1004, 132, rot=-8))
+pg.peck(pg.hand(1462, 1012, 98, rot=12, spread=1.15), size=0.62, density=1.2)
+pg.stage('hands')
+
+# ---- time: spalls take part of the old work, lichen in the shade of the ledge and along cracks
+pg.spall([(292, 1080), (300, 1030), (338, 984), (372, 960), (430, 928), (488, 918), (540, 934), (552, 972),
+ (526, 1010), (506, 1048), (480, 1080)], depth=9, impact=(440, 1000))
+pg.spall([(1920, 0), (1920, 156), (1884, 140), (1850, 118), (1828, 84), (1812, 40), (1800, 0)], depth=7, impact=(1900, 26), age=0.12)
+pg.spall([(1236, 806), (1262, 786), (1300, 780), (1338, 792), (1356, 818), (1344, 846), (1306, 856), (1268, 850), (1246, 832)],
+ depth=5, impact=(1300, 815), age=0.3)
+pg.lichen(1010, 992, 50, 'green', n=7)
+pg.lichen(1790, 952, 38, 'orange', n=6)
+pg.lichen(968, 152, 30, 'green', n=4)
+
+pg.save(out, stages_dir=stages)
+print('saved', out)
diff --git a/examples/popart_cat_moods.jpg b/examples/popart_cat_moods.jpg
new file mode 100644
index 0000000..49d6c1b
Binary files /dev/null and b/examples/popart_cat_moods.jpg differ
diff --git a/examples/popart_cat_moods.py b/examples/popart_cat_moods.py
new file mode 100644
index 0000000..bf9fb6d
--- /dev/null
+++ b/examples/popart_cat_moods.py
@@ -0,0 +1,356 @@
+"""Example (pop silkscreen, after the 1960s Factory method): 猫的六种心情 · Six Moods of a Cat -- one tabby cat,
+one photographic key screen, six panels on one canvas. Read in order, the panels tell a small story: the cat is
+curious (something smells good on the table), craves it (tongue out), is happy (got it), is startled (caught!),
+angry (hissing, ears flat) and finally sleepy. Each panel is hand-painted first -- a loud flat background, the cat,
+then a muzzle and bib, inner ears, nose, eyes, collar and tag -- in its own colour scheme, loosely traced and
+drifting off the photograph; then the same black key (shadow masses, tabby stripes, the features of that mood) is
+pulled through it, each time placed a little differently and with a different ink load: one flooded, one starved
+with a dry patch, one printed twice. No image model.
+python3 popart_cat_moods.py [out.jpg] [--stages DIR]
+"""
+import os, sys, time
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from popart import (PopSilkscreen, turn, mirror, HOT_PINK, PINK, BLUSH, RED, ORANGE, LEMON, YELLOW, CREAM, LIME,
+ TURQUOISE, SKY, BLUE, ULTRA, WHITE)
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'popart_cat_moods.jpg'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+t0 = time.time()
+
+ps = PopSilkscreen(1920, 1080, seed=15)
+ps.canvas()
+panels = ps.grid(3, 2, gap=12, margin=14, origin=(0.5, 0.53), unit=0.285)
+ps.stage('canvas')
+
+# ---------------------------------------------------------------- six moods, one cat
+# ear: outward rotation (deg) and length; eye: openness, pupil ('round' r | 'slit' w | 'happy' | 'sleepy');
+# gaze: pupil offset; tilt: head rotation about the neck (deg ccw); mouth; whisk: whisker sweep (+ forward, - back)
+MOODS = [
+ dict(name='curious', ear=(-6, 1.06), eye=1.12, pupil=('round', 0.118), gaze=(0.0, -0.01), tilt=9, mouth='closed', whisk=0.10,
+ bg=TURQUOISE, cat=LEMON, muzzle=CREAM, accent=HOT_PINK, iris='#3ddc6e', collar=ORANGE, tag=HOT_PINK),
+ dict(name='craving', ear=(0, 1.0), eye=1.0, pupil=('round', 0.100), gaze=(-0.03, -0.035), tilt=-4, mouth='lick', whisk=0.05,
+ bg=ORANGE, cat='#ff74b4', muzzle=BLUSH, accent=RED, iris=LEMON, collar=BLUE, tag=LEMON),
+ dict(name='happy', ear=(10, 0.98), eye=1.0, pupil=('happy',), gaze=(0, 0), tilt=4, mouth='smile', whisk=0.0,
+ bg=HOT_PINK, cat=YELLOW, muzzle=LEMON, accent=RED, iris=TURQUOISE, collar=TURQUOISE, tag=LEMON, blush=RED),
+ dict(name='startled', ear=(-2, 1.12), eye=1.34, pupil=('round', 0.042), gaze=(0, 0), tilt=0, mouth='o', whisk=0.2,
+ bg=LIME, cat=WHITE, muzzle=BLUSH, accent=HOT_PINK, iris=SKY, collar=RED, tag=YELLOW),
+ dict(name='angry', ear=(60, 0.74), eye=0.62, pupil=('slit', 0.026), gaze=(0, 0.0), tilt=0, mouth='hiss', whisk=-0.25,
+ bg=RED, cat='#2ccf74', muzzle=LEMON, accent=PINK, iris='#f3ff3a', collar=ULTRA, tag=LIME, brows=True),
+ dict(name='sleepy', ear=(16, 0.96), eye=1.0, pupil=('sleepy',), gaze=(0, 0), tilt=-11, mouth='closed', whisk=-0.08,
+ bg=ULTRA, cat=PINK, muzzle=WHITE, accent=HOT_PINK, iris=LIME, collar=LEMON, tag=TURQUOISE),
+]
+# how each panel was painted and printed: tracing drift (px), key shift (px), key rotation, ink load ...
+PRINT = [
+ dict(drift=(9, -5), key=(-8, 6), rot=0.5, density=1.02, flood=0.25, starve=0.0, nicks=1, pull=90),
+ dict(drift=(-8, 6), key=(7, -5), rot=-0.4, density=1.14, flood=0.6, starve=0.0, nicks=0, pull=90),
+ dict(drift=(6, 9), key=(-5, -8), rot=0.3, density=0.95, flood=0.1, starve=0.24, nicks=2, pull=0),
+ dict(drift=(-7, -7), key=(10, 7), rot=-0.6, density=1.0, flood=0.2, starve=0.0, nicks=1, pull=90, ghost=(15, -10, 0.38)),
+ dict(drift=(10, 4), key=(-11, -4), rot=0.9, density=1.1, flood=0.38, starve=0.0, nicks=1, pull=90),
+ dict(drift=(-5, 10), key=(6, 9), rot=-0.7, density=0.94, flood=0.05, starve=0.3, nicks=1, pull=90),
+]
+PIVOT = (0.0, 0.80) # the head turns about the neck
+
+
+class Cat:
+ """unit geometry of the cat for one mood (head centre at 0, 0; light from the upper left)"""
+
+ def __init__(self, m):
+ self.m = m
+ self.tilt = m['tilt']
+ rot, ln = m['ear']
+ b_in, b_out = np.array([0.22, -0.86]), np.array([0.94, -0.47])
+ mid = (b_in + b_out) / 2
+
+ def ear_tf(P, keep_base=False):
+ P = np.asarray(P, np.float32)
+ Q = mid + (P - mid) * ln
+ if keep_base:
+ Q[0], Q[-1] = P[0], P[-1]
+ return turn(Q, -rot, mid) # outward = clockwise for the right ear
+ self.ear_r = ear_tf([b_in, (0.38, -1.16), (0.62, -1.45), (0.73, -1.54), (0.81, -1.42), (0.92, -1.02), b_out], True)
+ self.cav_r = ear_tf([(0.34, -0.87), (0.47, -1.13), (0.66, -1.39), (0.74, -1.42), (0.80, -1.12), (0.82, -0.72), (0.60, -0.70)])
+ self.dark_r = ear_tf([(0.36, -0.86), (0.47, -1.12), (0.64, -1.40), (0.735, -1.50), (0.82, -1.40), (0.93, -1.0),
+ (0.95, -0.55), (0.80, -0.62), (0.60, -0.70)]) # the far ear, in shadow
+ self.cavl_r = ear_tf([(0.33, -0.88), (0.45, -1.12), (0.62, -1.34), (0.66, -1.30), (0.58, -1.08), (0.50, -0.84)])
+ self.tufts_r = [ear_tf(P) for P in ([(0.40, -0.84), (0.46, -0.98), (0.56, -1.12)],
+ [(0.50, -0.80), (0.55, -0.97), (0.63, -1.16)],
+ [(0.62, -0.78), (0.65, -0.95), (0.70, -1.12)],
+ [(0.74, -0.76), (0.75, -0.90), (0.77, -1.02)])]
+ cheek = [(1.00, -0.22), (1.07, 0.10), (1.03, 0.34), (0.88, 0.56), (0.62, 0.74), (0.30, 0.84)]
+ right = np.concatenate([[(0.0, -0.93)], self.ear_r, cheek], 0)
+ left = mirror(right[1:])[::-1]
+ self.head = self.T(np.concatenate([right, [(0.0, 0.87)], left], 0))
+ self.cheek_r = np.asarray(cheek, np.float32)
+
+ def T(self, P):
+ return turn(P, self.tilt, PIVOT)
+
+
+BODY = [(-0.80, 0.40), (-0.96, 0.86), (-1.36, 1.20), (-1.86, 1.58), (-2.22, 2.02), (-2.45, 2.7),
+ (2.45, 2.7), (2.22, 2.02), (1.86, 1.58), (1.36, 1.20), (0.96, 0.86), (0.80, 0.40)]
+COLLAR = [(-0.88, 0.80), (-0.46, 0.95), (0.0, 1.0), (0.46, 0.95), (0.88, 0.80)]
+TAG = (0.05, 1.17, 0.105)
+TONGUE = [(-0.02, 0.48), (-0.22, 0.48), (-0.26, 0.60), (-0.20, 0.71), (-0.11, 0.74), (-0.04, 0.68), (-0.02, 0.58)]
+
+
+def eye_pts(cx, cy, ew, eh, side, slant=7.0):
+ P = np.array([(-ew, 0.0), (-0.55 * ew, -0.86 * eh), (0, -eh), (0.55 * ew, -0.9 * eh), (ew, -0.02 * eh),
+ (0.55 * ew, 0.84 * eh), (0, 0.95 * eh), (-0.55 * ew, 0.82 * eh)], np.float32)
+ return turn(P, slant * side, (0, 0)) + np.array([cx, cy], np.float32)
+
+
+def tracing(P, rng, jit=0.022, grow=1.02, about=(0.0, 0.0)):
+ """the painter's loose tracing of an outline: slightly enlarged and wobbled"""
+ P = np.asarray(P, np.float32)
+ a = np.asarray(about, np.float32)
+ return a + (P - a) * grow + rng.normal(0, jit, P.shape).astype(np.float32)
+
+
+def colour_layers(p, c, m, rng):
+ """the hand-painted shapes for one panel, as (name, mask, colour) in painting order"""
+ T = c.T
+ head = p.shape(tracing(c.head, rng, 0.02, 1.025, (0, 0)))
+ body = p.shape(tracing(BODY, rng, 0.03, 1.0))
+ cat = np.maximum(head, body)
+ muzzle = p.shape(T(tracing([(-0.40, 0.30), (-0.16, 0.18), (0, 0.21), (0.16, 0.18), (0.40, 0.30), (0.36, 0.56),
+ (0.18, 0.74), (0, 0.79), (-0.18, 0.74), (-0.36, 0.56)], rng, 0.02)))
+ bib = p.shape(tracing([(-0.50, 1.06), (0, 1.0), (0.50, 1.06), (0.62, 1.55), (0.42, 2.1), (0, 2.5),
+ (-0.42, 2.1), (-0.62, 1.55)], rng, 0.03))
+ ears = np.maximum(p.shape(T(tracing(c.cav_r, rng, 0.02, 0.92, c.cav_r.mean(0)))),
+ p.shape(T(mirror(tracing(c.cav_r, rng, 0.02, 0.92, c.cav_r.mean(0))))))
+ nose = p.shape(T(tracing([(-0.14, 0.215), (0, 0.235), (0.14, 0.215), (0.02, 0.37), (-0.02, 0.37)], rng, 0.012)))
+ L = [('cat', cat, m['cat']), ('muzzle', muzzle, m['muzzle']), ('bib', bib, m['muzzle']),
+ ('ears', ears, m['accent']), ('nose', nose, m['accent'])]
+ kind = m['pupil'][0]
+ if kind == 'sleepy': # closed lids: a pop "eyeshadow" patch above the line
+ lid = [(-0.25, -0.02), (-0.16, -0.17), (0.0, -0.21), (0.16, -0.17), (0.25, -0.02), (0.1, 0.05), (-0.1, 0.05)]
+ lids = np.maximum(p.shape(T(np.array(lid) + [0.41, -0.11])), p.shape(T(np.array(lid) + [-0.41, -0.11])))
+ L.append(('lids', lids, m['iris']))
+ elif kind == 'happy':
+ pass
+ else:
+ e = m['eye']
+ irises = np.maximum(p.ellipse(*T([(0.41, -0.11)])[0], 0.25, 0.17 * e + 0.02, rot=7),
+ p.ellipse(*T([(-0.41, -0.11)])[0], 0.25, 0.17 * e + 0.02, rot=-7))
+ L.append(('irises', irises, m['iris']))
+ if m['mouth'] == 'lick':
+ L.append(('tongue', p.shape(T(TONGUE)), m['accent']))
+ if m['mouth'] == 'hiss':
+ L.append(('tongue', p.ellipse(*T([(0.0, 0.66)])[0], 0.15, 0.08), m['accent']))
+ if m.get('blush'):
+ L.append(('blush', np.maximum(p.ellipse(*T([(0.62, 0.24)])[0], 0.17, 0.11),
+ p.ellipse(*T([(-0.62, 0.24)])[0], 0.17, 0.11)), m['blush']))
+ collar = p.stroke(tracing(COLLAR, rng, 0.012), 0.13, 0.13)
+ L.append(('collar', collar, m['collar']))
+ L.append(('tag', p.ellipse(TAG[0], TAG[1], TAG[2] * 1.08), m['tag']))
+ return L
+
+
+class Union:
+ """running union of masks (keeps memory flat: no list of full-size masks)"""
+
+ def __init__(self, p):
+ self.a = p.blank()
+
+ def append(self, m):
+ np.maximum(self.a, m, out=self.a)
+
+
+class Tones(Union):
+ def append(self, item):
+ m, level = item
+ np.maximum(self.a, self.p.soft(m, 0.05) * level, out=self.a)
+
+ def __init__(self, p):
+ super().__init__(p)
+ self.p = p
+
+
+def key_masks(p, c, m):
+ """the photographic shadow masses and features of this mood -> (solid, tone)"""
+ T = c.T
+ S = Union(p) # solid masses
+ tone = Tones(p) # (mask, level) -> halftone areas
+ st = lambda pts, w0, w1=None, **k: p.stroke(T(pts), w0, w1, **k)
+ # --- shadow side of the head (light from the upper left): a crescent down the far cheek and jaw
+ outer = [(0.96, -0.40), (1.03, -0.20), (1.10, 0.10), (1.06, 0.36), (0.90, 0.60), (0.62, 0.79), (0.28, 0.89)]
+ inner = [(0.30, 0.76), (0.60, 0.62), (0.80, 0.40), (0.88, 0.12), (0.86, -0.16), (0.84, -0.38)]
+ cres = p.shape(T(outer + inner))
+ S.append(cres)
+ tone.append((p.shape(T(outer + [(0.10, 0.80), (0.42, 0.52), (0.66, 0.28), (0.70, -0.02), (0.72, -0.40)])), 0.38))
+ # fur tufts along the shadowed cheek ruff and the chin
+ for k, t in enumerate(np.linspace(0.05, 0.95, 9)):
+ P = c.cheek_r
+ i = t * (len(P) - 1); j = int(i); f = i - j
+ a = P[j] * (1 - f) + P[min(j + 1, len(P) - 1)] * f
+ n = np.array([a[0] - 0.25, a[1] - 0.05]); n /= np.linalg.norm(n)
+ L = 0.11 + 0.05 * np.sin(k * 2.3)
+ S.append(st([a - n * 0.04, a + n * L * 0.6 + np.array([0, 0.02]), a + n * L + np.array([0, 0.05])], 0.07, 0.0))
+ # --- under the chin, on the neck above the collar
+ chin = [(-0.62, 0.74), (-0.30, 0.86), (0.0, 0.90), (0.30, 0.87), (0.66, 0.76), (0.80, 0.80), (0.50, 0.95),
+ (0.0, 1.0), (-0.48, 0.95)]
+ chin_m = p.shape(T(chin))
+ S.append(chin_m * (p.XX > p.at(-0.25, 0)[0]))
+ tone.append((chin_m, 0.55))
+ # --- ears: the far one is a dark cavity, the near one only shadowed along its inner edge; light fur tufts
+ cav = p.shape(T(c.dark_r if m['ear'][0] < 40 else c.cav_r))
+ cavl = p.shape(T(mirror(c.cavl_r)))
+ tufts = p.blank()
+ for P in c.tufts_r:
+ tufts = np.maximum(tufts, st(P, 0.026, 0.0))
+ tufts = np.maximum(tufts, st(mirror(P), 0.026, 0.0))
+ if m['ear'][0] > 40: # ears pinned back: we see their backs, not the cavity
+ tone.append((cav, 0.5))
+ S.append(st([c.ear_r[1], c.ear_r[2], c.ear_r[3]], 0.03, 0.07))
+ else:
+ S.append(np.clip(cav - tufts * 0.9, 0, 1))
+ S.append(np.clip(cavl - tufts * 0.9, 0, 1))
+ tone.append((p.shape(T(mirror(c.cav_r))), 0.35))
+ # --- forehead: the tabby "M"
+ for P, w in [([(0, -0.92), (0.0, -0.72), (0.0, -0.50)], 0.075),
+ ([(0.18, -0.90), (0.18, -0.70), (0.12, -0.47)], 0.062),
+ ([(-0.18, -0.90), (-0.18, -0.70), (-0.12, -0.47)], 0.062),
+ ([(0.42, -0.82), (0.40, -0.60), (0.31, -0.40)], 0.06),
+ ([(-0.42, -0.82), (-0.40, -0.60), (-0.31, -0.40)], 0.05)]:
+ S.append(st(P, w, 0.012))
+ # stripes running back over the top of the head (hidden under the ear when it is pinned back)
+ if m['ear'][0] < 40:
+ S.append(st([(0.55, -0.62), (0.70, -0.50), (0.86, -0.42)], 0.05, 0.02))
+ # --- eyes
+ e, kind = m['eye'], m['pupil'][0]
+ for side in (1, -1):
+ cx, cy = 0.41 * side, -0.11
+ if kind in ('happy', 'sleepy'):
+ if kind == 'happy':
+ P = [(cx - 0.20, cy + 0.07), (cx - 0.11, cy - 0.04), (cx, cy - 0.075), (cx + 0.11, cy - 0.04), (cx + 0.20, cy + 0.07)]
+ S.append(st(P, 0.10, profile=lambda t: 0.35 + 0.65 * np.clip(np.sin(np.pi * t), 0, 1) ** 0.7))
+ else:
+ P = [(cx - 0.23, cy - 0.03), (cx - 0.11, cy + 0.045), (cx, cy + 0.06), (cx + 0.11, cy + 0.045), (cx + 0.23, cy - 0.02)]
+ S.append(st(P, 0.095, profile=lambda t: 0.4 + 0.6 * np.clip(np.sin(np.pi * t), 0, 1) ** 0.6))
+ S.append(st([(cx - 0.17, cy - 0.10), (cx, cy - 0.075), (cx + 0.17, cy - 0.09)], 0.03, 0.008))
+ continue
+ ew, eh = 0.215, 0.135 * e
+ inner = p.shape(T(eye_pts(cx, cy, ew, eh, side)))
+ outer = p.shape(T(eye_pts(cx, cy - 0.016, ew + 0.05, eh + 0.07, side)))
+ S.append(np.clip(outer - inner, 0, 1))
+ gx, gy = m['gaze']
+ if kind == 'round':
+ r = m['pupil'][1]
+ pc = (cx + gx, cy + gy)
+ pupil = p.ellipse(*T([pc])[0], r, r * 1.04) * inner
+ hole = p.ellipse(*T([(pc[0] - r * 0.35 - 0.02, pc[1] - r * 0.4 - 0.02)])[0], max(0.028, r * 0.26))
+ S.append(np.clip(pupil - hole, 0, 1))
+ else:
+ w = m['pupil'][1]
+ lens = p.shape(T([(cx, cy - eh * 1.1), (cx + w, cy), (cx, cy + eh * 1.1), (cx - w, cy)])) * inner
+ S.append(lens)
+ tone.append((p.shape(T(eye_pts(cx, cy - eh * 0.45, ew * 0.9, eh * 0.5, side))) * inner, 0.42)) # upper-lid shade
+ if m.get('brows'):
+ S.append(st([(cx - 0.18 * side, cy - 0.15), (cx + 0.02 * side, cy - 0.24), (cx + 0.24 * side, cy - 0.33)], 0.10, 0.03))
+ # tabby lines from the outer corners of the eyes, and under the eyes
+ for side in (1, -1):
+ S.append(st([(0.63 * side, -0.10), (0.78 * side, -0.07), (0.94 * side, -0.01)], 0.05, 0.01))
+ S.append(st([(0.56 * side, 0.04), (0.72 * side, 0.09), (0.88 * side, 0.16)], 0.04 if side < 0 else 0.05, 0.008))
+ # cheek stripes: bold in the shadow, thin and broken in the light
+ S.append(st([(0.68, 0.22), (0.84, 0.21), (1.02, 0.25)], 0.06, 0.02))
+ S.append(st([(0.64, 0.38), (0.80, 0.40), (0.96, 0.46)], 0.055, 0.02))
+ S.append(st([(-0.70, 0.22), (-0.84, 0.21), (-0.98, 0.25)], 0.035, 0.006))
+ S.append(st([(-0.68, 0.39), (-0.80, 0.41), (-0.92, 0.46)], 0.03, 0.004))
+ # --- nose: bridge shadow on the far side, nostrils, the shadow under the leather
+ S.append(st([(0.09, -0.04), (0.12, 0.10), (0.14, 0.21)], 0.025, 0.06))
+ tone.append((st([(0.06, -0.10), (0.11, 0.08), (0.16, 0.22)], 0.12, 0.16), 0.45))
+ for side in (1, -1):
+ S.append(st([(0.085 * side, 0.27), (0.06 * side, 0.305), (0.03 * side, 0.315)], 0.045, 0.02))
+ S.append(st([(0.14, 0.22), (0.08, 0.30), (0.02, 0.37)], 0.04, 0.03))
+ if m.get('brows'): # a wrinkled nose
+ for k in range(3):
+ S.append(st([(-0.10, 0.02 + 0.06 * k), (0.0, 0.0 + 0.06 * k), (0.10, 0.02 + 0.06 * k)], 0.024, 0.024))
+ # --- mouth
+ mo = m['mouth']
+ if mo != 'hiss':
+ S.append(st([(0, 0.36), (0, 0.42), (0, 0.46)], 0.032, 0.03))
+ if mo in ('closed', 'lick', 'smile', 'o'):
+ up = 0.05 if mo == 'smile' else 0.0
+ for side in (1, -1):
+ S.append(st([(0, 0.45), (0.08 * side, 0.505), (0.16 * side, 0.50 - up * 0.4), (0.23 * side, 0.45 - up)],
+ 0.034, 0.012))
+ if mo == 'o':
+ S.append(p.ellipse(*T([(0.0, 0.565)])[0], 0.062, 0.075))
+ if mo == 'lick':
+ S.append(st([(-0.07, 0.49), (-0.10, 0.57), (-0.12, 0.64)], 0.026, 0.004)) # the groove
+ S.append(st([(-0.04, 0.50), (-0.02, 0.60), (-0.07, 0.69), (-0.15, 0.725), (-0.23, 0.69), (-0.25, 0.58),
+ (-0.22, 0.50)], 0.022, 0.04)) # the tip's outline
+ if mo == 'hiss':
+ mouth = p.shape(T([(-0.29, 0.47), (-0.13, 0.42), (0, 0.45), (0.13, 0.42), (0.29, 0.47), (0.24, 0.63),
+ (0.11, 0.74), (0, 0.76), (-0.11, 0.74), (-0.24, 0.63)]))
+ fangs = p.blank()
+ for side in (1, -1):
+ fangs = np.maximum(fangs, p.shape(T([(0.125 * side, 0.445), (0.195 * side, 0.465), (0.16 * side, 0.585)]), smooth=False))
+ fangs = np.maximum(fangs, p.shape(T([(0.085 * side, 0.735), (0.14 * side, 0.715), (0.115 * side, 0.645)]), smooth=False))
+ tongue = p.ellipse(*T([(0.0, 0.675)])[0], 0.12, 0.055)
+ S.append(np.clip(mouth - fangs - tongue * 0.95, 0, 1))
+ S.append(st([(0, 0.34), (0, 0.40), (0, 0.45)], 0.032, 0.03))
+ # --- whisker pads and whiskers
+ spots = []
+ for side in (1, -1):
+ for row in range(3):
+ for k in range(4):
+ u = side * (0.12 + 0.055 * k + 0.025 * (row % 2))
+ spots.append((u, 0.405 + 0.045 * row + 0.008 * k, 0.0145 if side > 0 else 0.012))
+ pads = p.blank()
+ for u, v, r in spots:
+ x, y = T([(u, v)])[0]
+ pads = np.maximum(pads, p.ellipse(x, y, r))
+ S.append(pads)
+ wk = m['whisk']
+ for side in (1, -1):
+ for k in range(3):
+ a = (0.31 * side, 0.43 + 0.045 * k)
+ spread = (k - 1) * (0.16 + 0.12 * wk)
+ b = (1.55 * side * (1 - 0.1 * (wk < 0) * abs(wk) * 2), 0.36 + spread - 0.12 * wk + 0.06)
+ mid = ((a[0] + b[0]) / 2, (a[1] + b[1]) / 2 - 0.05 + 0.02 * k)
+ S.append(st([a, mid, b], 0.024, 0.005, caps=False))
+ # --- body: far shoulder in shadow, tabby rings round the chest (broken over the light bib), collar shadow
+ S.append(p.shape([(0.82, 0.78), (1.00, 0.92), (1.40, 1.22), (1.90, 1.60), (2.25, 2.05), (2.5, 2.7), (1.62, 2.7),
+ (1.45, 2.0), (1.24, 1.55), (1.0, 1.22)]))
+ tone.append((p.shape([(0.82, 0.78), (1.40, 1.22), (1.90, 1.60), (2.5, 2.7), (1.1, 2.7), (0.9, 1.7), (0.7, 1.15)]), 0.4))
+ for v, sw in ((1.36, 0.075), (1.70, 0.085), (2.05, 0.09)):
+ tone.append((p.stroke([(-1.7, v + 0.26), (-1.3, v + 0.04), (-0.86, v - 0.02)], sw * 1.3, 0.02), 0.38))
+ S.append(p.stroke([(0.62, v - 0.04), (1.2, v + 0.02), (1.75, v + 0.30)], 0.02, sw))
+ S.append(p.stroke([(-0.30, 1.04), (0.2, 1.06), (0.6, 1.0), (0.86, 0.90)], 0.018, 0.05)) # under the collar
+ tag = p.ellipse(TAG[0], TAG[1], TAG[2]) - p.ellipse(TAG[0] - 0.012, TAG[1] - 0.012, TAG[2] * 0.82)
+ S.append(np.clip(tag, 0, 1) * (p.XX > p.at(TAG[0] - 0.02, 0)[0]))
+ S.append(p.ellipse(TAG[0], TAG[1] - TAG[2] - 0.02, 0.03) - p.ellipse(TAG[0], TAG[1] - TAG[2] - 0.02, 0.016))
+ return np.clip(S.a, 0, 1), tone.a
+
+
+# ---------------------------------------------------------------- 1. backgrounds, up to the tape
+for p, m in zip(panels, MOODS):
+ ps.ground(p, m['bg'], direction=float(np.random.default_rng(p.index).uniform(-8, 8)))
+ps.stage('grounds')
+
+# ---------------------------------------------------------------- 2. the cat, then the loose colour shapes
+cats = [Cat(m) for m in MOODS]
+layers = lambda p: colour_layers(p, cats[p.index], MOODS[p.index], np.random.default_rng(40 + p.index))
+for p, pr in zip(panels, PRINT):
+ name, mask, col = layers(p)[0]
+ ps.paint(p, mask, col, drift=pr['drift'], wobble=3.0)
+ps.stage('cats')
+for p, pr in zip(panels, PRINT):
+ r = np.random.default_rng(70 + p.index)
+ for name, mask, col in layers(p)[1:]:
+ d = (pr['drift'][0] + r.uniform(-6, 6), pr['drift'][1] + r.uniform(-6, 6))
+ ps.paint(p, mask, col, drift=d, wobble=2.2 if name in ('nose', 'irises', 'tag') else 3.0)
+ps.stage('shapes')
+
+# ---------------------------------------------------------------- 3. the black key, pulled panel by panel
+for p, c, m, pr in zip(panels, cats, MOODS, PRINT):
+ solid, tone = key_masks(p, c, m)
+ ps.key(p, solid, tone=tone, shift=pr['key'], rot=pr['rot'], density=pr['density'], flood=pr['flood'],
+ starve=pr['starve'], nicks=pr['nicks'], pull=pr['pull'], ghost=pr.get('ghost'))
+ if p.index < 5:
+ ps.stage(f'key_{p.index + 1}')
+
+ps.save(out, stages)
+print(out, f'{time.time() - t0:.1f}s')
diff --git a/examples/silhouette_family.jpg b/examples/silhouette_family.jpg
new file mode 100644
index 0000000..49b30d8
Binary files /dev/null and b/examples/silhouette_family.jpg differ
diff --git a/examples/silhouette_family.py b/examples/silhouette_family.py
new file mode 100644
index 0000000..d2500b5
--- /dev/null
+++ b/examples/silhouette_family.py
@@ -0,0 +1,276 @@
+"""Example (cut-paper silhouette / 剪影): 剪影小像 · Shades of the Wren Household — three oval gilt frames hung from a
+picture rail on a block-printed Regency stripe wallpaper, c. 1791. In the middle Mrs. Hannah Wren, cut in black
+paper in a wide-brimmed hat with ostrich plumes, frizzed hair and ringlets, a puffed fichu; she looks to the right,
+toward the brig Dove coming home under full sail past the lighthouse; on the left her tabby Tibbs sits on a
+tasselled cushion and looks at her. Loose snips for plume barbs, lashes, whiskers, ribbon ends and rigging;
+thin shell-gold bronzing over the black; iron-gall captions; verre eglomise mounts and convex glass.
+All three sitters are invented. Draw-on stages: wall -> frames -> lady -> cat -> ship -> bronzing -> captions ->
+glass. No image model.
+python3 silhouette_family.py [out.jpg] [--stages DIR]
+"""
+import os, sys, time
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from silhouette import Silhouette, smooth
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'silhouette_family.jpg'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+t0 = time.time()
+
+s = Silhouette(1920, 1080, seed=11)
+rng = np.random.default_rng(5)
+s.wallpaper(ground='#7d95a0', ink='#ebe0c4')
+s.picture_rail(0, 42)
+s.chair_rail(1004, 26)
+s.stage('wall')
+
+FL = s.frame(440, 604, 158, 204, width=50, hook=True, spread=30)
+FC = s.frame(960, 566, 222, 286, width=62, hook=True, spread=34, twist=1.0)
+FR = s.frame(1480, 604, 158, 204, width=50, hook=True, spread=30)
+s.stage('frames')
+
+
+def ellipse(cx, cy, rx, ry, rot=0.0, n=36):
+ t = np.linspace(0, 2 * np.pi, n, endpoint=False)
+ c, si = np.cos(np.radians(rot)), np.sin(np.radians(rot))
+ x, y = rx * np.cos(t), ry * np.sin(t)
+ return np.stack([cx + x * c - y * si, cy + x * si + y * c], 1)
+
+
+def arc(cx, cy, r, a0, a1, n=12, ry=None):
+ t = np.radians(np.linspace(a0, a1, n))
+ return np.stack([cx + r * np.cos(t), cy + (ry or r) * np.sin(t)], 1)
+
+
+# ==================================================================== Mrs. Hannah Wren (faces right)
+L = s.sheet(FC, at=(722, 268), scale=0.5)
+body = [(515, 330), (540, 352), (552, 384), (558, 410), (554, 428), (563, 452), (576, 474), (585, 488), (580, 497),
+ (568, 500), (558, 504), (562, 514), (566, 520), (557, 526), (561, 532), (556, 542), (549, 550), (555, 565),
+ (550, 578), (530, 586), (508, 592), (498, 610), (497, 640),
+ (505, 652), (535, 668), (572, 696), (598, 735), (606, 778), (598, 815), (584, 842), (576, 862), (586, 880),
+ (566, 896), (510, 906), (430, 910), (350, 903), (298, 888), (276, 866),
+ (283, 830), (298, 782), (318, 734), (350, 692), (392, 658), (412, 622), (412, 570), (406, 510), (414, 440),
+ (440, 375), (478, 340)]
+L.shape(smooth(body, 6))
+frizz = [(552, 350), (566, 336), (578, 318), (582, 300), (540, 296), (470, 304), (400, 316), (340, 336), (306, 372),
+ (300, 420), (314, 466), (348, 500), (392, 516), (430, 505), (470, 450), (520, 380)]
+L.shape(smooth(frizz, 6))
+L.scallop(smooth([(394, 518), (350, 502), (316, 468), (300, 420), (306, 372), (334, 338)], 8, closed=False), r=(9, 14), outset=0.25)
+L.scallop(smooth([(576, 312), (568, 330), (556, 346)], 6, closed=False), r=(6, 8), outset=0.2)
+for k in range(9): # a few loose wisps
+ a0 = np.radians(150 + k * 14); x0, y0 = 440 + 128 * np.cos(a0), 410 + 100 * np.sin(a0)
+ L.snip(smooth([(x0, y0), (x0 - 10 + rng.normal(0, 3), y0 + 4), (x0 - 16, y0 + 14 + rng.normal(0, 3))], 4, closed=False), 2.6, 0.3)
+# hat: a wide brim seen almost edge-on (thick at the crown, tapering, front turned up, back drooping),
+# a low ruched crown, a ribbon bow with long loops, two streamers, three ostrich plumes
+u = np.linspace(0, 1, 60)
+brim_c = smooth([(232, 362), (300, 342), (380, 320), (470, 302), (560, 288), (640, 277), (694, 266), (722, 252), (732, 240)], 6, closed=False)
+L.snip(brim_c, 3 + 19 * np.sin(np.pi * np.clip(u * 1.08 - 0.04, 0, 1)) ** 0.8 + 2 * u, loose=False)
+crown = [(388, 316), (372, 286), (376, 250), (398, 222), (440, 202), (495, 195), (548, 202), (588, 224), (604, 254),
+ (598, 284), (588, 300)]
+L.shape(smooth(crown, 6))
+L.scallop(smooth([(374, 262), (384, 234), (412, 210), (452, 198), (500, 193), (548, 200), (586, 222), (604, 250)], 8, closed=False),
+ r=(6, 8), outset=0.1, step=1.15)
+knot = np.array([378.0, 262.0])
+for (ang, ln, wd) in [(-142, 50, 18), (-178, 44, 15)]:
+ d_ = np.array([np.cos(np.radians(ang)), np.sin(np.radians(ang))])
+ c_ = knot + d_ * ln * 0.55
+ L.shape(ellipse(c_[0], c_[1], ln * 0.6, wd * 0.62, ang, 30))
+ L.hole(ellipse(c_[0] + d_[0] * 4, c_[1] + d_[1] * 4, ln * 0.36, wd * 0.12, ang, 20)) # the slit inside the loop
+L.disc(knot[0], knot[1], 11)
+streamers = []
+for k, (x0, ln, ph) in enumerate([(366, 300, 0.0), (376, 250, 1.6)]):
+ p = np.stack([x0 - 66 * u - 8 * u ** 2 + 12 * np.sin(2 * np.pi * 1.2 * u + ph), 290 + ln * u], 1)
+ L.snip(p, 16 * (0.25 + 0.75 * np.abs(np.cos(np.pi * 1.5 * u + ph))) + 2)
+ e = p[-1]; streamers.append(p)
+ L.snip([e - (0, 8), e + (-8, 14)], 8, 0); L.snip([e - (0, 8), e + (7, 13)], 8, 0)
+# ostrich plumes: a tapering rachis with long curly barbs both sides
+plumes = [[(468, 198), (452, 142), (412, 106), (360, 96), (320, 112), (298, 144), (302, 178)],
+ [(510, 194), (526, 142), (560, 106), (606, 98), (640, 116), (646, 148)],
+ [(432, 206), (394, 186), (350, 190), (318, 214), (302, 252)]]
+for k, pl in enumerate(plumes):
+ c = smooth(pl, 10, closed=False)
+ L.snip(c, 14, 3, loose=False)
+ L.fringe(c, 120 if k < 2 else 80, (46, 18), angle=55, width=3.4, side=(1, -1), bend=0.55, jitter=0.3, start=0.04)
+# corkscrew ringlets falling behind the neck
+rings = [L.ringlet(x, y, ln, 19, 5, 5, lean=-0.06) for (x, y, ln) in [(380, 500, 200), (402, 508, 176), (358, 492, 150)]]
+# lashes, a lace frill at the neckline
+for (x, y, dx, dy) in [(549, 431, 16, 3), (550, 433, 15, 7), (551, 435, 12, 10)]:
+ L.snip([(x, y), (x + dx * 0.6, y + dy * 0.3), (x + dx, y + dy)], 2.4, 0.3)
+L.lace(smooth([(497, 640), (512, 656), (534, 668), (558, 684)], 6, closed=False), depth=8, step=7)
+s.paste(L)
+s.stage('lady')
+
+# ==================================================================== Tibbs the cat (faces right, toward her)
+def cat_warp(P):
+ """re-proportion the cat: head 1.12x and lowered, body squashed toward the cushion, haunch a little fuller"""
+ x, y = P[:, 0], P[:, 1]
+ hx, hy = 640 + (x - 640) * 1.12, 340 + (y - 340) * 1.12 + 151
+ by = 855 - (855 - y) * 0.62
+ bx = x - 16 * np.clip((y - 560) / 200, 0, 1) * np.clip((640 - x) / 80, 0, 1)
+ w = np.clip((y - 390) / 80, 0, 1); w = w * w * (3 - 2 * w)
+ return np.stack([hx * (1 - w) + bx * w, hy * (1 - w) + by * w], 1)
+
+
+C = s.sheet(FL, at=(206, 342), scale=0.42, warp=cat_warp)
+cushion = [(330, 872), (350, 852), (460, 846), (600, 846), (740, 850), (776, 862), (786, 884), (760, 912),
+ (640, 922), (460, 922), (350, 914), (326, 894)]
+C.shape(smooth(cushion, 6))
+for (tx, ty, sg) in [(330, 878, -1), (786, 872, 1)]:
+ C.disc(tx + sg * 6, ty + 4, 10)
+ for j in range(11):
+ x = tx + sg * 6 + (j - 5) * 2.4
+ C.snip([(x, ty + 8), (x + (j - 5) * 1.3, ty + 28), (x + (j - 5) * 2.0 + rng.normal(0, 1), ty + 48 + rng.normal(0, 3))], 3.4, 1.2)
+cat = [(708, 350), (700, 335), (690, 318), (676, 302), (662, 292), # nose, bridge, forehead
+ (652, 286), (646, 262), (640, 238), # near ear: front edge to tip
+ (628, 256), (614, 278), # back edge of the ear
+ (600, 290), (584, 306), (574, 330), (564, 362), # skull, nape
+ (548, 404), (524, 462), (498, 530), (474, 596), (456, 662), (450, 730), (458, 790), (478, 828), (506, 848), # back, haunch
+ (560, 854), (640, 855), (692, 855), (708, 850), (706, 840), (694, 834), # base, front paw
+ (688, 800), (684, 740), (684, 690), # front leg
+ (690, 630), (698, 566), (704, 510), (700, 466), # chest
+ (692, 436), (688, 414), (694, 398), (704, 388), (710, 376), (712, 364)] # throat, chin, muzzle
+C.shape(smooth(cat, 6))
+C.shape(smooth([(600, 290), (606, 256), (616, 230), (628, 262), (626, 284)], 4)) # the far ear, just behind
+tail = smooth([(486, 842), (540, 858), (620, 862), (700, 860), (742, 846), (764, 822), (766, 798), (754, 784)], 8, closed=False)
+C.snip(tail, np.linspace(30, 16, 20), loose=False)
+C.disc(754, 786, 8)
+C.hole(smooth([(670, 838), (668, 796), (656, 772), (638, 778), (628, 808), (632, 838)], 5)) # gap between the legs
+C.hole(ellipse(672, 330, 10, 5, rot=-12, n=24)) # the eye
+C.shape(ellipse(673, 330, 1.9, 4.4, n=12)) # its slit pupil
+for w in [[(706, 368), (752, 358), (806, 354)], [(706, 372), (754, 374), (808, 382)], [(704, 376), (746, 390), (790, 408)],
+ [(702, 366), (744, 352), (786, 334)], [(680, 312), (698, 290), (712, 268)], [(675, 310), (688, 286), (694, 262)]]:
+ C.snip(smooth(w, 8, closed=False), 2.8, 0.3)
+C.fringe(smooth([(700, 470), (702, 520), (696, 570), (690, 620)], 6, closed=False), 18, (18, 12), angle=55, width=4, side=(1,), bend=0.3)
+C.fringe(smooth([(564, 362), (552, 396), (538, 430)], 6, closed=False), 8, 13, angle=60, width=4, side=(1,), bend=0.3)
+for (x, y) in [(646, 268), (644, 256)]:
+ C.snip([(x, y), (x + 9, y - 6), (x + 15, y - 14)], 2.4, 0.3)
+for (bx, by, rot) in [(712, 418, -30), (710, 436, 25)]: # ribbon bow at the throat
+ C.shape(ellipse(bx, by, 14, 7.5, rot, n=20), loose=True)
+ C.hole(ellipse(bx + 2, by, 6.5, 2.8, rot, n=16))
+C.disc(698, 426, 6.5)
+s.paste(C)
+s.stage('cat')
+
+# ==================================================================== the brig Dove, homeward (sails left)
+R = s.sheet(FR, at=(1322, 400), scale=0.39)
+sea_y = lambda x: 756 + 5 * np.sin(x / 26.0) + 4 * np.sin(x / 61.0 + 1.3)
+top = [(x, sea_y(x)) for x in np.arange(14, 797, 8)]
+bot = [(x, 784 + 3 * np.sin(x / 40.0)) for x in np.arange(790, 20, -10)]
+R.shape(np.array(top + [(800, 772)] + bot + [(10, 772)]))
+crests = np.arange(40, 790, 64) + rng.uniform(-8, 8, 12)
+for x0 in crests: # crests curling forward (left)
+ y0 = sea_y(x0)
+ R.snip(smooth([(x0 + 26, y0 + 2), (x0 + 8, y0 - 9), (x0 - 6, y0 - 9), (x0 - 12, y0 - 2), (x0 - 7, y0 + 1)], 6, closed=False), 7, 1.5)
+hull = [(236, 676), (250, 692), (264, 714), (284, 738), (308, 754), (360, 762), (500, 766), (640, 764), (690, 756),
+ (712, 740), (722, 716), (726, 690), (730, 668), (714, 663), (692, 668), (640, 672), (560, 680), (460, 684),
+ (360, 684), (300, 680), (262, 672), (244, 666)]
+R.shape(smooth(hull, 5))
+for (x, y) in [(712, 680), (712, 696)]:
+ R.hole([(x - 3, y - 4), (x + 4, y - 4), (x + 4, y + 3), (x - 3, y + 3)]) # stern windows
+R.snip([(380, 686), (380, 300), (380, 258)], 8, 3, loose=False) # foremast
+R.snip([(560, 682), (560, 262), (560, 218)], 9, 3, loose=False) # mainmast
+R.snip([(266, 672), (150, 622), (110, 604)], 8, 3, loose=False) # bowsprit + jib-boom
+R.line([(566, 636), (722, 646)], 4); R.line([(566, 552), (672, 518)], 4) # boom, gaff
+TIERS = [(380, [(322, 374, 30), (388, 452, 40), (466, 544, 52), (558, 646, 62)]),
+ (560, [(276, 334, 40), (348, 424, 52), (438, 526, 64)])]
+
+
+def sail(xt0, xt1, yt, xb0, xb1, yb, roach=6):
+ left = smooth([(xt0, yt), (xt0 - 4 - (xt0 - xb0) * 0.5, (yt + yb) / 2), (xb0, yb)], 5, closed=False)
+ foot = smooth([(xb0, yb), ((xb0 + xb1) / 2, yb - roach), (xb1, yb)], 5, closed=False)
+ right = smooth([(xb1, yb), (xt1 + 4 + (xb1 - xt1) * 0.5, (yt + yb) / 2), (xt1, yt)], 5, closed=False)
+ R.shape(np.vstack([left, foot, right]))
+ R.line([(xt0 - 8, yt - 1), (xt1 + 8, yt - 1)], 4.5) # the yard
+
+
+for (mx, tiers) in TIERS:
+ for i, (yt, yb, hw) in enumerate(tiers):
+ sail(mx - hw, mx + hw, yt, mx - hw - 7, mx + hw + 7, yb, roach=8 + i * 3)
+R.line([(478, 539), (642, 539)], 4.5) # main course furled on its yard
+R.scallop(smooth([(486, 541), (530, 545), (560, 546), (600, 545), (636, 541)], 6, closed=False), r=(5, 7), outset=-0.5, step=1.2)
+for tri in [[(378, 318), (122, 600), (200, 602)], [(308, 470), (216, 612), (266, 614)]]: # jibs
+ h_, t_, c_ = (np.array(v, float) for v in tri) # sharp corners, bellied leech
+ foot = smooth([t_, (t_ + c_) / 2 + (0, 4), c_], 5, closed=False)
+ leech = smooth([c_, (c_ + h_) / 2 + (10, 2), h_], 6, closed=False)
+ R.shape(np.vstack([[h_, t_], foot[1:], leech[1:]]))
+R.shape(smooth([(570, 552), (664, 524), (688, 576), (708, 628), (570, 630)], 4)) # spanker
+for (a_, b_) in [((380, 258), (112, 604)), ((380, 360), (166, 624)), ((380, 500), (252, 668)), ((560, 218), (382, 296)),
+ ((560, 340), (382, 410)), ((380, 300), (420, 682)), ((560, 262), (640, 674)), ((560, 218), (712, 666)),
+ ((150, 622), (256, 704)), ((380, 500), (352, 682)), ((380, 500), (366, 682)), ((560, 480), (534, 680)),
+ ((560, 480), (548, 680)), ((672, 518), (722, 646))]:
+ R.line([a_, b_], 2.2)
+for (x, y, ln) in [(380, 258, 90), (560, 218, 110)]: # pennants streaming forward
+ p = np.array([(x - u * ln, y - 2 + 6 * np.sin(u * 7) * u) for u in np.linspace(0, 1, 14)])
+ R.snip(p, 9, 0.5)
+# the lighthouse on its rock, far off to the left: home
+R.shape(smooth([(60, 764), (72, 744), (96, 732), (128, 728), (158, 734), (180, 750), (190, 766)], 5))
+R.shape([(118, 734), (122, 668), (142, 668), (146, 734)])
+R.shape([(114, 662), (150, 662), (150, 668), (114, 668)])
+R.shape([(120, 640), (144, 640), (144, 662), (120, 662)])
+R.shape([(116, 640), (132, 626), (148, 640)])
+R.hole([(124, 645), (130, 645), (130, 657), (124, 657)]); R.hole([(134, 645), (140, 645), (140, 657), (134, 657)])
+for (gx, gy, k) in [(232, 432, 1.1), (200, 468, 0.85)]:
+ R.snip(smooth([(gx - 16 * k, gy - 2), (gx - 8 * k, gy - 8 * k), (gx, gy), (gx + 8 * k, gy - 8 * k), (gx + 16 * k, gy - 2)], 4, closed=False), 3.4, 1.2)
+s.paste(R)
+s.stage('ship')
+
+# ==================================================================== bronzing: thin shell gold on the black
+hair = [smooth([(568, 318), (520, 316), (468, 326), (420, 346), (380, 380)], 8, closed=False),
+ smooth([(560, 336), (512, 342), (470, 362), (436, 398)], 8, closed=False),
+ smooth([(548, 350), (506, 372), (478, 408), (466, 446)], 8, closed=False),
+ smooth([(470, 318), (420, 334), (368, 362), (336, 404), (330, 446)], 8, closed=False),
+ smooth([(430, 380), (392, 410), (366, 452), (362, 488)], 8, closed=False),
+ smooth([(520, 400), (500, 432), (494, 462)], 6, closed=False)]
+s.bronze(L, hair, width=2.2)
+s.bronze(L, [np.array([c_[i] + (-4, 0), c_[i + 3] + (3, 4)]) for c_ in rings for i in range(8, 100, 20)], width=2.4)
+s.bronze(L, [brim_c[8:-4] + (0, -5), smooth([(382, 276), (440, 268), (520, 266), (598, 272)], 6, closed=False),
+ smooth([(388, 298), (450, 292), (530, 290), (594, 292)], 6, closed=False)], width=2.6)
+s.bronze(L, [smooth([(420 + dx, 214), (430 + dx * 1.15, 240), (436 + dx * 1.2, 262)], 5, closed=False) for dx in (0, 46, 92, 138)], width=1.8, bright=0.7)
+s.bronze(L, [p[44:-4] + (3, 0) for p in streamers], width=1.8, bright=0.85)
+s.bronze(L, [ellipse(knot[0] + np.cos(np.radians(a_)) * l_ * 0.55, knot[1] + np.sin(np.radians(a_)) * l_ * 0.55, l_ * 0.5, 4, a_, 16)[2:7]
+ for (a_, l_) in [(-142, 50), (-178, 44)]], width=1.8)
+s.bronze(L, [smooth(p, 10, closed=False) for p in plumes], width=2.2)
+s.bronze(L, [smooth([(512, 664), (546, 694), (572, 736)], 5, closed=False), smooth([(518, 694), (556, 734), (578, 784)], 5, closed=False),
+ smooth([(530, 742), (562, 786), (574, 828)], 5, closed=False), smooth([(380, 682), (396, 760), (420, 860)], 5, closed=False),
+ smooth([(420, 680), (452, 700), (470, 740)], 5, closed=False)], width=2.8)
+beads = smooth([(497, 626), (470, 618), (440, 610), (418, 604)], 6, closed=False)
+s.bronze(L, [[p, p + (2.5, 0.5)] for p in beads[::2]], width=3.2)
+# cat: fur combed along the back and haunch, ear, collar, cushion piping and buttons
+back = np.array([(572, 340), (560, 372), (545, 410), (520, 470), (495, 540), (470, 600), (452, 680), (450, 750), (462, 805)])
+fur = []
+for k in range(22):
+ i = rng.integers(0, len(back) - 2); off = rng.uniform(14, 60)
+ seg_ = back[i:i + 2] + np.array([off, rng.uniform(-6, 6)])
+ seg_ = seg_[0] + (seg_[1] - seg_[0]) * np.linspace(0, rng.uniform(0.5, 0.9), 4)[:, None]
+ fur.append(seg_)
+s.bronze(C, fur, width=2.2)
+s.bronze(C, [smooth([(632, 252), (626, 268), (622, 286)], 4, closed=False),
+ smooth([(694, 420), (650, 404), (604, 382), (566, 364)], 6, closed=False),
+ smooth([(692, 434), (648, 418), (600, 396), (562, 378)], 6, closed=False)], width=2.6)
+s.bronze(C, [smooth([(334, 870), (356, 856), (420, 849), (470, 847)], 5, closed=False), smooth([(756, 852), (778, 862)], 4, closed=False),
+ smooth([(330, 888), (360, 900), (460, 904), (640, 904), (760, 896), (784, 882)], 6, closed=False)], width=3.0)
+# ship: gunport band, sail cloths, a glint on every crest, the lighthouse lamp
+band = smooth([(268, 700), (360, 708), (500, 711), (640, 709), (712, 700)], 10, closed=False)
+s.bronze(R, [band[i:i + 3] for i in range(0, len(band) - 3, 4)], width=6.0, tip=6.0)
+s.bronze(R, [smooth([(250, 690), (360, 694), (500, 696), (640, 694), (720, 682)], 8, closed=False)], width=2.2)
+cloth = []
+for (mx, tiers) in TIERS:
+ for (yt, yb, hw) in tiers:
+ for q in (-0.5, 0.0, 0.5):
+ cloth.append([(mx + q * hw, yt + 4), (mx + q * hw * 1.08, (yt + yb) / 2), (mx + q * (hw + 7), yb - 8)])
+s.bronze(R, cloth, width=1.6, bright=0.8)
+s.bronze(R, [smooth([(x0 + 20, sea_y(x0) - 1), (x0 + 4, sea_y(x0) - 7), (x0 - 8, sea_y(x0) - 5)], 4, closed=False) for x0 in crests], width=2.4)
+s.stage('bronze')
+
+# ==================================================================== captions in iron-gall ink
+s.caption(FC, 'Mrs. Hannah Wren', 960, 768, 32)
+s.caption(FC, 'cut in the parlour · 1791', 960, 798, 18, style='italic', alpha=0.86)
+s.caption(FL, 'Tibbs', 440, 752, 32)
+s.caption(FL, 'who kept the hearth', 440, 776, 16, style='italic', alpha=0.86)
+s.caption(FR, 'the Brig Dove', 1480, 752, 30)
+s.caption(FR, 'homeward bound · 1792', 1480, 776, 16, style='italic', alpha=0.86)
+s.stage('captions')
+
+s.glaze()
+s.save(out, stages)
+print(out, f'{time.time() - t0:.1f}s')
diff --git a/examples/stainedglass_seasons.jpg b/examples/stainedglass_seasons.jpg
new file mode 100644
index 0000000..0af37df
Binary files /dev/null and b/examples/stainedglass_seasons.jpg differ
diff --git a/examples/stainedglass_seasons.py b/examples/stainedglass_seasons.py
new file mode 100644
index 0000000..7795f3e
--- /dev/null
+++ b/examples/stainedglass_seasons.py
@@ -0,0 +1,396 @@
+"""Example (stained glass / 彩色玻璃花窗): 四季之窗 · Window of the Seasons — four Gothic lancets in a stone wall,
+lit by daylight from behind. Every light shows the same tree (the same trunk and boughs) in one season, and the
+sun stands at a different height in each: highest in summer, level at the two equinoxes, low behind bare
+branches in winter. The birds tell the year: swallows arrive in spring, a nest of chicks in summer, geese leave
+in a V in autumn, a robin stays through the snow. Latin names in the label bands (VER, AESTAS, AVTVMNVS, HIEMS).
+Pot-metal glass with streaks and seeds, grisaille trace lines and stippled matt, leaves scratched out of the
+matt, silver stain, lead came with soldered joints, saddle bars, a mended crack, coloured light on the reveals
+and the sill.
+Draw-on stages: stone -> cutline cartoon -> glass -> trace -> matt and stain -> lead -> iron -> daylight.
+No image model.
+python3 stainedglass_seasons.py [out.jpg] [--stages DIR]
+"""
+import os, sys, time
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from stainedglass import StainedGlass
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'stainedglass_seasons.jpg'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+t0 = time.time()
+
+g = StainedGlass(1920, 1080, seed=4, record=bool(stages), ambient=0.08)
+rng = np.random.default_rng(12)
+g.wall('#8e8474', '#6b6358')
+
+TOP, BOT, WID = 64, 930, 330
+CX = [342, 754, 1166, 1578]
+lights = [g.lancet(cx, TOP, BOT, WID, splay=28, sill=44, hood=14) for cx in CX]
+g.string_course(BOT + 44, 24)
+g.stage('stone')
+
+BORDER, FILLET = 30, 42 # sdf bands: border 0..30, white fillet 30..42, field beyond
+LABEL_Y = (770, 824) # label band (local y)
+GROUND_Y = 700
+
+SEASONS = [
+ dict(name='VER', sky=['#6f9ed6', '#5c8ccc', '#7aa8dc'], sun=(-46, 250, 26), border=['#4e9a3c', '#e6e0cc'],
+ ground=['#6aae3e', '#7cbc48', '#5a9a36'], crown=['#a6d05a', '#8fc24c', '#bcd96e', '#9ccd52'], lobe=0.8),
+ dict(name='AESTAS', sky=['#2456b0', '#1d4aa0', '#2b61bd'], sun=(0, 150, 30), border=['#b3182c', '#f2c230'],
+ ground=['#3c8a34', '#2f7a2e', '#4a9a3a'], crown=['#2f8a3c', '#3f9c45', '#257034', '#4aa040'], lobe=1.0),
+ dict(name='AVTVMNVS', sky=['#3a4fa2', '#33459a', '#4558ae'], sun=(46, 250, 26), border=['#e0922a', '#7a2c5c'],
+ ground=['#9a6a2a', '#8a5a24', '#a87a34'], crown=['#e0922a', '#d0601e', '#e8b830', '#b8401e'], lobe=0.92),
+ dict(name='HIEMS', sky=['#8fa9cc', '#9db4d4', '#839fc6'], sun=(-52, 404, 24), border=['#3a64b0', '#e8ecef'],
+ ground=['#eef1f2', '#dfe8ef', '#cddcea'], crown=None, lobe=0),
+]
+
+# the one tree, in local coordinates (ly down from the apex), shared by all four lights.
+# Glass can only be cut so thin: the trunk and main boughs are cut glass, everything thinner is painted.
+TRUNK = [(0, 730), (-4, 682), (2, 634), (-2, 594)]
+CUT_BOUGHS = [([(-4, 604), (-30, 572), (-54, 548), (-80, 530), (-100, 506)], 27, 16), # left
+ ([(4, 600), (32, 566), (62, 546), (86, 518), (98, 492)], 26, 16), # right
+ ([(-2, 598), (-9, 548), (-4, 500), (4, 462)], 23, 16)] # leader
+PAINTED = [([(-100, 506), (-110, 486), (-114, 462)], 9, 3),
+ ([(98, 492), (106, 468), (108, 440)], 9, 3),
+ ([(4, 462), (8, 430), (2, 396), (-4, 372)], 10, 3),
+ ([(-7, 528), (-30, 496), (-50, 462), (-60, 424)], 10, 3),
+ ([(0, 486), (24, 458), (44, 428), (52, 394)], 9, 3),
+ ([(-40, 556), (-64, 576), (-92, 586)], 7, 2.5),
+ ([(48, 554), (78, 568), (104, 570)], 7, 2.5)]
+NEST = [(18, 432), (82, 432), (74, 452), (50, 460), (26, 452)]
+CHICKS = [(24, 433), (26, 420), (34, 414), (42, 420), (46, 414), (54, 410), (62, 416), (68, 414), (76, 420), (78, 433)]
+LOBES = [(-84, 476, 46), (-46, 420, 54), (14, 392, 56), (70, 420, 50), (90, 486, 36), (-62, 536, 44),
+ (56, 528, 46), (-4, 470, 56)]
+
+
+def twigs(p, ang, length, width, depth, out):
+ """a little recursive tree of painted twigs"""
+ q = (p[0] + np.cos(ang) * length, p[1] + np.sin(ang) * length)
+ mid = ((p[0] + q[0]) / 2 + rng.normal(0, length * 0.07), (p[1] + q[1]) / 2 + rng.normal(0, length * 0.07))
+ out.append(([p, mid, q], width))
+ if depth > 0:
+ for da in (-0.5, 0.45):
+ twigs(q, ang + da + rng.normal(0, 0.18), length * rng.uniform(0.58, 0.74), width * 0.66, depth - 1, out)
+
+
+def _place(L, pts, x, y, s, flip, rot):
+ P = np.asarray(pts, np.float32) * s
+ if flip: P[:, 0] *= -1
+ c, sn = np.cos(rot), np.sin(rot)
+ return L.P(P @ np.array([[c, sn], [-sn, c]], np.float32) + [x, y])
+
+
+def swallow(L, x, y, s=1.0, flip=False, rot=0.0):
+ """a swallow seen from below: scythe-curved wings swept back, short body, deeply forked tail"""
+ from core import spline as sp
+ up = [(6, -3), (3, -12), (-4, -24), (-16, -36), (-32, -46), (-22, -32), (-14, -20), (-9, -9), (-8, -3)]
+ lo = [(px, -py) for px, py in up[::-1]]
+ body = [(20, 0), (17, -4), (8, -5), (-8, -4), (-14, -3), (-36, -14), (-24, 0), (-36, 14), (-14, 3), (-8, 4), (8, 5), (17, 4)]
+ m = 0
+ for part in (up, body, lo):
+ P = sp(part + [part[0]], 6) if part is not body else np.asarray(part, np.float32)
+ m = m + g.poly(_place(L, P, x, y, s, flip, rot))
+ return np.clip(m, 0, 1)
+
+
+def leaf_pts(cx, cy, ang, ln, wd, n=30):
+ t = np.linspace(0, 2 * np.pi, n, endpoint=False)
+ u = np.cos(t) * ln / 2
+ v = np.sin(t) * wd / 2 * (1 - 0.35 * np.cos(t)) # a pointed tip
+ c, s = np.cos(ang), np.sin(ang)
+ return np.stack([cx + u * c - v * s, cy + u * s + v * c], 1)
+
+
+def lobe_masks(L, lobes, field):
+ return [g.blob(*L.pt(x, y), r, r * 0.93, rough=0.1, seed=sd) * field for (x, y, r, sd) in lobes]
+
+
+def wood_mask(L, field):
+ m = g.branch(L.P(TRUNK), 46, 30) + g.poly(L.P([(-32, 731), (-18, 700), (18, 700), (32, 731), (0, 737)]))
+ for pts, w0, w1 in CUT_BOUGHS:
+ m = np.maximum(m, g.branch(L.P(pts), w0, w1))
+ return np.clip(m, 0, 1) * field
+
+
+paint = [] # painting jobs, done after all the glass is cut
+for L, S in zip(lights, SEASONS):
+ field = L.inner(FILLET)
+ # ---- sky: a mosaic of blues
+ g.glass(field, S['sky'], cell=46, streak=0.6)
+ sx, sy, sr = S['sun']
+ scx, scy = L.pt(sx, sy)
+ # ---- the sun: a disc of yellow with cut rays of gold and amber
+ nr = 12
+ for k in range(nr):
+ a = k * 2 * np.pi / nr + 0.13
+ tip = sr * (2.05 if k % 2 == 0 else 1.62)
+ ray = [(scx + np.cos(a - 0.21) * sr * 0.9, scy + np.sin(a - 0.21) * sr * 0.9), (scx + np.cos(a) * tip, scy + np.sin(a) * tip),
+ (scx + np.cos(a + 0.21) * sr * 0.9, scy + np.sin(a + 0.21) * sr * 0.9)]
+ g.glass(g.poly(ray) * field, '#f0b02a' if k % 2 == 0 else '#f6d24a', streak=0.4)
+ g.glass(g.circle(scx, scy, sr) * field, '#f3cf4a' if S['name'] != 'HIEMS' else '#f4e3a0', streak=0.3, seeds=0.6)
+ # ---- ground: a wavy band of pieces
+ gx = np.linspace(-130, 130, 9)
+ gy = GROUND_Y + 10 * np.sin(gx / 40 + CX.index(L.cx)) - 6 * np.cos(gx / 23)
+ ground = g.poly(L.P(np.vstack([np.stack([gx, gy], 1), [(130, LABEL_Y[0]), (-130, LABEL_Y[0])]]))) * field
+ g.glass(ground, S['ground'], cell=42, streak=0.5, aspect=1.6)
+ if S['name'] == 'HIEMS': # snow drifts: blue shadows lying in the hollows
+ for (dx, dy, rx, ry) in [(-84, 748, 46, 13), (74, 744, 52, 12), (0, 763, 66, 8)]:
+ g.glass(g.ellipse(*L.pt(dx, dy), rx, ry) * ground, '#b9cde4', streak=0.3)
+ # ---- trunk and main boughs, cut in brown glass
+ wood = wood_mask(L, field)
+ g.glass(wood, ['#6e4526', '#7a4e2c', '#62401f'], cell=62, aspect=1.8, angle=np.pi / 2, streak=0.5, streak_dir=np.pi / 2)
+ if S['name'] == 'HIEMS': # snow lying on the upper half of the two side boughs
+ for pts, w0, w1 in CUT_BOUGHS[:2]:
+ P = np.asarray(pts, np.float32)
+ up = g.branch(L.P(P[1:] + [0, -6]), w0 * 0.9, w1 * 0.9) # snow bulges a little above the bough
+ down = g.branch(L.P(P[1:] + [0, 8]), w0 * 0.9, w1)
+ g.glass(np.clip(up - down, 0, 1) * field, '#f1f2ee', streak=0.3)
+ # ---- crown: one area of mixed greens (or golds), cut into small pieces; lobes are modelled in paint later
+ lobes = []
+ if S['crown']:
+ keep = range(len(LOBES)) if S['name'] != 'AVTVMNVS' else [0, 1, 2, 3, 5, 6, 7]
+ for i in sorted(keep, key=lambda i: LOBES[i][1]): # back (high) to front (low)
+ x, y, r = LOBES[i]
+ r *= S['lobe']
+ lobes.append((x, y, r, 500 + 10 * len(lobes) + CX.index(L.cx))) # keep the seed, rebuild the mask later
+ crown = np.clip(sum(lobe_masks(L, lobes, field)), 0, 1)
+ g.glass(crown, S['crown'], cell=30, streak=0.5, vary=1.2)
+ # ---- the season's birds and fruit, in glass
+ details = []
+ if S['name'] == 'VER':
+ blossom = [(-80, 446), (-44, 400), (-10, 432), (24, 386), (60, 410), (84, 470), (-90, 500), (-52, 470),
+ (18, 470), (50, 500), (-24, 520), (-66, 548), (64, 540), (0, 396), (40, 440), (-30, 452)]
+ for k, (x, y) in enumerate(blossom):
+ g.glass(g.circle(*L.pt(x, y), 11) * field, '#ef9ab8' if k % 3 else '#f2ece0', streak=0.2, seeds=0.4)
+ details.append(('blossom', x, y))
+ for (x, y, s, fl, rt) in [(38, 156, 1.1, False, -0.25), (64, 334, 0.85, False, -0.1)]:
+ g.glass(swallow(L, x, y, s, fl, rt) * field, '#1c2a58', streak=0.3)
+ details.append(('swallow', x, y, s, fl, rt))
+ for x in (-96, -40, 30, 92): # daisies in the grass
+ y = 742 + (x % 3) * 6
+ g.glass(g.circle(*L.pt(x, y), 9) * field, '#f2ece0', streak=0.2)
+ details.append(('flower', x, y))
+ if S['name'] == 'AESTAS':
+ for (x, y) in [(-80, 452), (-40, 516), (-8, 420), (36, 454), (80, 494), (-92, 530), (16, 540), (56, 396), (-52, 410)]:
+ g.glass(g.circle(*L.pt(x, y), 11) * field, '#b3182c', streak=0.6, flashed=True)
+ details.append(('apple', x, y))
+ nest = g.poly(L.P(NEST)) * field
+ chicks = g.poly(L.P(CHICKS)) * field
+ g.glass(chicks, '#e9dfb8', streak=0.2)
+ g.glass(nest, '#7a4a24', streak=0.6, streak_dir=0.0)
+ g.glass(swallow(L, 84, 350, 0.85, True, 0.3) * field, '#1c2a58', streak=0.3) # a parent flying back to the nest
+ details.append(('nest',))
+ if S['name'] == 'AVTVMNVS':
+ falling = [(-96, 614, 0.6), (-60, 654, -0.9), (86, 622, 1.2), (98, 352, 0.3), (-96, 364, -0.5), (60, 672, 0.4)]
+ pile = [(-72, 716, 0.2), (-46, 724, -0.5), (-20, 716, 0.9), (36, 720, -0.2), (64, 712, 0.6), (90, 724, -0.8),
+ (-98, 728, 0.4)]
+ for k, (x, y, a) in enumerate(falling + pile):
+ col = ['#e0922a', '#d0601e', '#e8b830', '#b8401e'][k % 4]
+ g.glass(g.poly(leaf_pts(*L.pt(x, y), a, 30, 15)) * field, col, streak=0.4)
+ details.append(('leaf', x, y, a))
+ if S['name'] == 'HIEMS':
+ rx_, ry_ = 50, 522 # a robin perched on the right bough
+ body = g.blob(*L.pt(rx_, ry_), 24, 17, rough=0.04) + g.circle(*L.pt(rx_ + 19, ry_ - 13), 12) \
+ + g.poly(L.P([(rx_ - 18, ry_ - 2), (rx_ - 44, ry_ + 8), (rx_ - 40, ry_ + 16), (rx_ - 14, ry_ + 11)]))
+ body = np.clip(body, 0, 1) * field
+ g.glass(body, '#7a5434', streak=0.4)
+ g.glass(g.blob(*L.pt(rx_ + 16, ry_ - 1), 14, 15, rough=0.04) * body, '#d4502a', streak=0.4)
+ details.append(('robin', rx_, ry_))
+ # ---- label band (white glass, stained gold later, painted letters)
+ band = g.poly(L.P([(-200, LABEL_Y[0]), (200, LABEL_Y[0]), (200, LABEL_Y[1] + 30), (-200, LABEL_Y[1] + 30)])) * field
+ g.glass(band, '#ece6d2', streak=0.3)
+ # ---- white fillet and the border
+ g.glass(L.band(BORDER, FILLET), '#efeadb', sites=L.outline((BORDER + FILLET) / 2, 140), streak=0.3)
+ bsites = L.outline(BORDER / 2 + 2, 40)
+ g.glass(L.band(-2, BORDER), S['border'], sites=bsites, streak=0.5, flashed=S['border'][0] == '#b3182c')
+ paint.append((L, S, lobes, details, bsites))
+
+g.stage('cartoon', cartoon=True)
+g.stage('glass')
+
+# ================================================================== trace lines
+for L, S, lobes, details, bsites in paint:
+ lm = lobe_masks(L, lobes, L.inner(FILLET))
+ sx, sy, sr = S['sun']
+ scx, scy = L.pt(sx, sy)
+ t = np.linspace(0, 2 * np.pi, 40)
+ g.trace(np.stack([scx + (sr - 7) * np.cos(t), scy + (sr - 7) * np.sin(t)], 1), 2.2, taper=(0, 0))
+ # bark: long wavering lines up the trunk and along the boughs
+ for k in range(5):
+ off = -15 + k * 7.5
+ g.trace(L.P([(off * 0.95, 722), (off * 0.8 - 2, 672), (off * 0.62 + 1, 626), (off * 0.5, 596)]), 2.0, taper=(0.3, 0.4))
+ for pts, w0, w1 in CUT_BOUGHS:
+ g.trace(L.P(np.asarray(pts, np.float32) + [1, 3]), 1.8, taper=(0.3, 0.5))
+ # painted branches and twigs, too thin to cut in glass (seen in full in winter, through gaps otherwise)
+ if S['name'] in ('HIEMS', 'AVTVMNVS'):
+ tw = []
+ depth = 3 if S['name'] == 'HIEMS' else 2
+ sky_clip = None if not lobes else 1 - np.clip(sum(lm), 0, 1) # autumn: twigs only where the sky shows
+ for pts, w0, w1 in PAINTED:
+ P = np.asarray(pts, np.float32)
+ g.trace(L.P(P), w0, taper=(0.02, 0.7), clip=sky_clip)
+ d = P[-1] - P[-2]; a = np.arctan2(d[1], d[0])
+ twigs(tuple(P[-1]), a, 22, w1 * 1.2, depth, tw)
+ for j in range(1, len(P) - 1):
+ twigs(tuple(P[j]), a + (0.9 if j % 2 else -0.9), 20, w1 * 1.3, depth - 1, tw)
+ for p, w in tw:
+ g.trace(L.P(p), max(w, 1.2), taper=(0.05, 0.9), clip=sky_clip)
+ # crown: a scalloped line of leaf tips along the lower, shaded rim of every lobe that is in front
+ for i, (x, y, r, _) in enumerate(lobes):
+ later = np.clip(sum(lm[i + 1:]), 0, 1) if i + 1 < len(lobes) else 0
+ th = np.linspace(-0.5, np.pi + 0.3, int(r * 3.6))
+ rr = r * (0.96 + 0.07 * np.abs(np.sin(th * r / 7)))
+ P = np.stack([x + rr * np.cos(th), y + rr * np.sin(th) * 0.93], 1)
+ Q = L.P(P)
+ vis = [(0 <= int(q[1]) < g.H and 0 <= int(q[0]) < g.W and (np.isscalar(later) or later[int(q[1]), int(q[0])] < 0.5)) for q in Q]
+ run = []
+ for q, v in zip(Q, vis):
+ if v: run.append(q)
+ elif len(run) > 3: g.trace(np.array(run), 2.2, taper=(0.3, 0.3), smooth=False, wobble=0); run = []
+ else: run = []
+ if len(run) > 3: g.trace(np.array(run), 2.2, taper=(0.3, 0.3), smooth=False, wobble=0)
+ # a few painted leaves with midribs in the shadowed lower half
+ for k in range(int(r / 9)):
+ a = rng.uniform(0.2, 2.6); d = r * rng.uniform(0.45, 0.8)
+ lx, ly = x + d * np.cos(a), y + d * np.sin(a) * 0.93
+ if not np.isscalar(later) and later[int(L.pt(lx, ly)[1]), int(L.pt(lx, ly)[0])] > 0.5: continue
+ ang = a + rng.normal(0, 0.5)
+ Pl = leaf_pts(*L.pt(lx, ly), ang, 24, 11, 24)
+ np.maximum(g.trace_a, g.poly(Pl) * 0.8, out=g.trace_a)
+ c, s_ = np.cos(ang), np.sin(ang)
+ g.scratch([L.pt(lx - 10 * c, ly - 10 * s_), L.pt(lx + 9 * c, ly + 9 * s_)], 1.3)
+ for d in details:
+ if d[0] == 'blossom':
+ cx_, cy_ = L.pt(d[1], d[2])
+ for k in range(5):
+ a = k * 2 * np.pi / 5 + 0.3
+ g.trace(np.array([(cx_ + 3 * np.cos(a), cy_ + 3 * np.sin(a)), (cx_ + 8 * np.cos(a), cy_ + 8 * np.sin(a))]), 1.5)
+ elif d[0] == 'flower':
+ cx_, cy_ = L.pt(d[1], d[2])
+ g.trace(np.array([(cx_, cy_ + 8), (cx_ + 1, cy_ + 24)]), 2.2, taper=(0.1, 0.6))
+ for k in range(6):
+ a = k * 2 * np.pi / 6
+ g.trace(np.array([(cx_ + 2.5 * np.cos(a), cy_ + 2.5 * np.sin(a)), (cx_ + 7 * np.cos(a), cy_ + 7 * np.sin(a))]), 1.3)
+ elif d[0] == 'swallow':
+ pass
+ elif d[0] == 'apple':
+ cx_, cy_ = L.pt(d[1], d[2])
+ g.trace(np.array([(cx_ + 1, cy_ - 9), (cx_ + 4, cy_ - 17)]), 2.4, taper=(0.1, 0.5))
+ elif d[0] == 'leaf':
+ _, x, y, a = d
+ c, s_ = np.cos(a), np.sin(a)
+ cx_, cy_ = L.pt(x, y)
+ g.trace(np.array([(cx_ - 14 * c, cy_ - 14 * s_), (cx_ + 12 * c, cy_ + 12 * s_)]), 1.8, taper=(0.1, 0.6))
+ for j in (-1, 1):
+ for u in (-5, 2):
+ g.trace(np.array([(cx_ + u * c, cy_ + u * s_), (cx_ + (u + 5) * c - j * 5 * s_, cy_ + (u + 5) * s_ + j * 5 * c)]), 1.1)
+ elif d[0] == 'nest':
+ for k in range(6):
+ y0 = 436 + k * 4
+ g.trace(L.P([(22 + k * 2, y0), (50, y0 + 3 + rng.normal(0, 1)), (78 - k * 2, y0)]), 1.4, taper=(0.2, 0.2))
+ for (x, y) in [(34, 418), (54, 414), (70, 418)]: # open beaks and eyes
+ cx_, cy_ = L.pt(x, y)
+ g.trace(np.array([(cx_ - 4, cy_ - 2), (cx_, cy_ - 9), (cx_ + 4, cy_ - 2)]), 1.6, smooth=False)
+ g.trace(np.array([(cx_ - 3, cy_ + 3), (cx_ - 2.5, cy_ + 3.5)]), 2.6)
+ elif d[0] == 'robin':
+ _, x, y = d
+ ex, ey = L.pt(x + 23, y - 16)
+ g.trace(np.array([(ex, ey), (ex + 0.5, ey + 0.5)]), 3.8)
+ g.trace(L.P([(x + 30, y - 15), (x + 39, y - 12), (x + 30, y - 9)]), 2.0, smooth=False) # beak
+ g.trace(L.P([(x - 16, y - 7), (x - 4, y - 11), (x + 6, y - 7)]), 1.7) # wing
+ g.trace(L.P([(x - 14, y + 1), (x - 4, y - 2), (x + 4, y + 1)]), 1.4)
+ for lx_ in (x - 2, x + 7): # legs
+ g.trace(L.P([(lx_, y + 15), (lx_ + 1, y + 24)]), 1.8, taper=(0.1, 0.1))
+ if S['name'] == 'AVTVMNVS': # geese leaving in a V, painted on the sky
+ for k in range(7):
+ i = (k + 1) // 2
+ side = 1 if k % 2 else -1
+ x, y = -46 + i * 25, 112 + side * i * 17 + i * 17
+ cx_, cy_ = L.pt(x, y)
+ flap = 1 if k % 3 else -0.4
+ g.trace(np.array([(cx_ - 15, cy_ - 8 * flap), (cx_ - 6, cy_ - 1), (cx_, cy_ + 1.5), (cx_ + 6, cy_ - 1),
+ (cx_ + 15, cy_ - 8 * flap)]), 2.8, taper=(0.3, 0.3))
+ g.trace(np.array([(cx_ - 5, cy_ + 2), (cx_ + 5, cy_ + 0.5)]), 4.4, taper=(0.4, 0.2))
+ # border: a painted lozenge with a dot on every piece
+ ctr = np.array(L.pt(0, 520))
+ for (x, y) in bsites:
+ n_ = ctr - [x, y]; n_ /= np.linalg.norm(n_) + 1e-6
+ p_ = np.array([-n_[1], n_[0]])
+ c_ = np.array([x, y]) + n_ * 2
+ lz = np.array([c_ + p_ * 9, c_ + n_ * 6, c_ - p_ * 9, c_ - n_ * 6, c_ + p_ * 9])
+ g.trace(lz, 1.6, taper=(0, 0), smooth=False, wobble=0)
+ g.trace(np.array([c_, c_ + 0.4]), 3.4)
+ lx, ly = L.pt(0, (LABEL_Y[0] + LABEL_Y[1]) / 2 + 1)
+ g.inscribe(S['name'], lx, ly, 34 if len(S['name']) < 7 else 29, spacing=1.0)
+g.stage('trace')
+
+# ================================================================== matt, sticklight, silver stain
+for L, S, lobes, details, bsites in paint:
+ field = L.inner(FILLET)
+ sx, sy, sr = S['sun']
+ scx, scy = L.pt(sx, sy)
+ g.shade(wood_mask(L, field), offset=(10, 3), strength=0.6, soft=3)
+ # crown: an overall matt, every lobe shaded toward the lower right, leaves scratched out on the lit side
+ lm = lobe_masks(L, lobes, field)
+ for i, (x, y, r, _) in enumerate(lobes):
+ m = lm[i]
+ later = np.clip(sum(lm[i + 1:]), 0, 1) if i + 1 < len(lobes) else 0
+ vis = m * (1 - later)
+ g.matt(vis, 0.3, soft=2)
+ g.shade(m, offset=(r * 0.3, r * 0.36), strength=0.5, soft=6, clip=vis)
+ for k in range(int(r * r / 150)):
+ a = rng.uniform(np.pi * 0.9, np.pi * 1.85); d = r * np.sqrt(rng.uniform(0.05, 0.75))
+ lx, ly = x + d * np.cos(a), y + d * np.sin(a)
+ Pl = leaf_pts(*L.pt(lx, ly), a + rng.normal(0, 0.6), rng.uniform(13, 19), rng.uniform(6, 8), 16)
+ g.scratch_mask(g.poly(Pl) * vis)
+ # sky: a light matt badgered toward the edges of each light, so the middle reads brighter
+ edge = np.clip(1 - g.circle(*L.pt(0, 470), 210), 0, 1)
+ g.matt(field * edge, 0.16, soft=30)
+ if S['name'] == 'HIEMS': # snowflakes scratched out of a thin matt on the sky
+ sky_only = field * (1 - g.circle(scx, scy, sr * 2.2)) * (g.YY < L.top + GROUND_Y - 10) * (1 - wood_mask(L, field))
+ g.diaper(sky_only, spacing=34, motif='flake', size=3.6, paint=0.22, jitter=1.0, width=1.5)
+ if S['name'] == 'AESTAS': # a faint diaper of crosses on the summer sky
+ sky_only = field * (1 - g.circle(scx, scy, sr * 2.2)) * (g.YY < L.top + 330)
+ g.diaper(sky_only, spacing=30, motif='cross', size=3.4, paint=0.16, width=1.5)
+ g.stain(g.circle(scx, scy, sr) * (1 - g.circle(scx, scy, sr * 0.55) * 0.6), 0.9 if S['name'] != 'HIEMS' else 0.45)
+ for d in details:
+ if d[0] == 'apple':
+ cx_, cy_ = L.pt(d[1], d[2])
+ g.matt(g.circle(cx_ + 3, cy_ + 3, 10), 0.45, soft=2)
+ g.scratch([(cx_ - 6, cy_ - 2), (cx_ - 3, cy_ - 6)], 2.4)
+ elif d[0] in ('blossom', 'flower'):
+ g.stain(g.circle(*L.pt(d[1], d[2]), 3.2), 1.3)
+ elif d[0] == 'robin':
+ g.shade(g.blob(*L.pt(d[1], d[2]), 24, 17, rough=0.04), offset=(0, 9), strength=0.5, soft=3)
+ elif d[0] == 'nest':
+ g.matt(g.poly(L.P([(18, 444), (82, 444), (74, 452), (50, 460), (26, 452)])), 0.5, soft=2)
+ g.stain(g.poly(L.P(CHICKS)), 0.5)
+ # ground: darker toward the bottom; grass blades scratched out in spring and summer
+ gm = field * (g.YY > L.top + GROUND_Y - 16) * (g.YY < L.top + LABEL_Y[0])
+ g.matt(gm * np.clip((g.YY - (L.top + GROUND_Y)) / 70, 0, 1), 0.35, soft=4)
+ if S['name'] in ('VER', 'AESTAS'):
+ for k in range(26):
+ x = rng.uniform(-118, 118); y = rng.uniform(GROUND_Y + 14, LABEL_Y[0] - 8)
+ g.scratch(L.P([(x, y), (x + rng.normal(0, 2), y - rng.uniform(7, 13))]), 1.6)
+ # label band: stained gold, a painted rule above and below the letters
+ lb = g.poly(L.P([(-200, LABEL_Y[0]), (200, LABEL_Y[0]), (200, LABEL_Y[1]), (-200, LABEL_Y[1])])) * field
+ g.stain(lb, 0.9)
+ for yy in (LABEL_Y[0] + 7, LABEL_Y[1] - 7):
+ g.trace(L.P([(-118, yy), (118, yy)]), 1.6, taper=(0.02, 0.02), smooth=False)
+ # border: matt toward the outer edge, so the colours deepen into the stone
+ g.matt(L.band(-2, BORDER) * np.clip(1 - (L.sdf() - 8) / 24, 0, 1), 0.3, soft=2)
+g.stage('matt')
+
+# ================================================================== lead, iron, a mended crack
+w4 = lights[3]
+g.crack([w4.pt(30, 236), w4.pt(52, 262), w4.pt(70, 300), w4.pt(84, 322)], mend=True)
+g.lead(width=6.0, rim=9.0)
+g.stage('lead')
+for L in lights:
+ for y in (286, 490, 694):
+ g.saddle_bar(L, L.top + y, width=9)
+g.stage('iron')
+g.weather(grime=0.55, pits=0.6)
+g.daylight(strength=1.0, spill=1.0, halation=1.0)
+g.save(out, stages)
+print('saved', out, f'{time.time() - t0:.1f}s')
diff --git a/examples/stencil_kite.jpg b/examples/stencil_kite.jpg
new file mode 100644
index 0000000..d469ac2
Binary files /dev/null and b/examples/stencil_kite.jpg differ
diff --git a/examples/stencil_kite.py b/examples/stencil_kite.py
new file mode 100644
index 0000000..3bba7d9
--- /dev/null
+++ b/examples/stencil_kite.py
@@ -0,0 +1,307 @@
+"""Example (spray-paint stencil): 放风筝 · Hold On — a kid flying a kite, sprayed on a board-marked concrete wall.
+
+The wind comes from the right. A small kid in a puffer jacket, beanie and knitted scarf leans back against the pull,
+front heel dug in, holding a round kite reel; the two tails of the scarf and a few leaves fly ahead of him toward
+the kite. The string (sprayed freehand with a skinny cap) sags up across the wall to a red diamond kite high on the
+left, its bow tail streaming downwind; three swallows from one little stencil ride the same wind. HOLD ON is sprayed
+in stencil letters with bridged counters. The wall had a past: a grey council buff over an old blue tag that still
+ghosts through, and a pink tag half taken off by a pressure washer.
+
+How it was made, in order: the wall -> old graffiti -> the kid in three cards, light -> grey -> black (each card
+a few px off, every island held by bridges) -> the kite in red, then dark red -> string and tail freehand; bows,
+swallows and leaves from small reusable cards turned to fit -> lettering. No image model.
+python3 stencil_kite.py [out.jpg] [--stages DIR]
+"""
+import os, sys, time
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from stencil import Stencil, shade_side, BLACK, WHITE, GREY, RED
+from core import spline
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'stencil_kite.jpg'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+t0 = time.time()
+
+GROUND = 1000
+KID = (1420, GROUND - 6) # the kid's feet, wall px
+KS = 1.36 # the kid's design units -> px
+LIGHT = (-1.0, -0.9) # the photo the stencil was cut from was lit from the upper left
+
+
+def kid_design(c):
+ """the kid, facing left, leaning back on the string. Returns the three tone plates (masks) and where the
+ string leaves the reel. Parts are drawn back to front; each plate only gets what is visible."""
+ U = np.maximum
+ PIV, LEAN, DROP = (30.0, -172.0), np.radians(9), 14.0 # the upper body leans back about the hips
+
+ def R(*pts):
+ out = []
+ for x, y in pts:
+ dx, dy = x - PIV[0], y - PIV[1]
+ out.append((PIV[0] + dx * np.cos(LEAN) - dy * np.sin(LEAN), PIV[1] + dx * np.sin(LEAN) + dy * np.cos(LEAN) + DROP))
+ return out if len(out) > 1 else out[0]
+
+ def above(p0, p1):
+ """the side of line p0 -> p1 that is up (screen y smaller)"""
+ (a, b) = c.P([p0, p1])
+ d = b - a
+ cr = (d[0] * (c.YY - a[1]) - d[1] * (c.XX - a[0])) / (np.hypot(*d) + 1e-6)
+ return np.clip(-cr + 0.5, 0, 1).astype(np.float32)
+
+ def hide(part, *front):
+ v = part.copy()
+ for f in front: v *= 1 - f
+ return v
+
+ # --- legs: front leg braced straight forward, rear leg bent under the weight
+ leg_f = U(c.capsule((14, -176), (-28, -102), 22, 17), c.capsule((-28, -102), (-68, -32), 17, 14))
+ leg_r = U(c.capsule((42, -180), (82, -104), 23, 18), c.capsule((82, -104), (54, -32), 18, 14))
+ leg_f = U(leg_f, c.ellipse((-68, -34), 16, 10, rot=-35))
+ leg_r = U(leg_r, c.ellipse((54, -32), 16, 9, rot=15))
+ # --- sneakers: front one on its heel with the toe up; rear one flat, pushing
+ shoe_f = c.poly([(-56, -2), (-54, -22), (-64, -36), (-86, -44), (-110, -50), (-124, -44), (-122, -30),
+ (-102, -18), (-76, -4)], smooth=True)
+ shoe_r = c.poly([(78, -2), (78, -22), (66, -32), (46, -34), (26, -26), (8, -16), (6, -4), (36, 0)], smooth=True)
+ sole_f = c.stroke([(-56, -4), (-80, -8), (-106, -22), (-124, -36)], 7, 6) * shoe_f
+ sole_r = c.stroke([(78, -3), (40, -2), (6, -3)], 7, 7) * shoe_r
+ shoes = U(shoe_f, shoe_r)
+ # --- the upper body
+ torso = c.poly(R((-4, -184), (-9, -226), (-3, -266), (22, -304), (58, -316), (84, -300), (90, -256),
+ (86, -214), (76, -180), (36, -170)), smooth=True)
+ sleeve_f = U(c.capsule(*R((66, -298), (30, -268)), 17, 15), c.capsule(*R((30, -268), (-16, -292)), 15, 13))
+ sleeve_n = U(c.capsule(*R((58, -292), (14, -254)), 19, 17), c.capsule(*R((14, -254), (-24, -272)), 17, 15))
+ hand_f = c.ellipse(R((-28, -296)), 11, 10)
+ hand_n = c.ellipse(R((-36, -276)), 12, 11)
+ neck = c.capsule(*R((54, -318), (60, -336)), 12)
+ skull = c.ellipse(R((64, -366)), 37, 36)
+ face = c.ellipse(R((44, -352)), 25, 21, rot=-25 - 9)
+ nose = c.ellipse(R((15, -361)), 7, 5.5)
+ chin = c.ellipse(R((40, -336)), 12, 9)
+ head = U(U(skull, face), U(U(nose, chin), neck))
+ ear = c.ellipse(R((72, -360)), 8, 10, rot=-15 - 9)
+ # beanie: a dome above the brim line, a ribbed turn-up, a pom-pom
+ b0, b1 = R((24, -398)), R((108, -374))
+ dome = c.ellipse(R((70, -394)), 41, 33, rot=-14 - 9) * above(b0, b1)
+ band = c.stroke(R((22, -394), (64, -384), (110, -370)), 15, 15) * c.ellipse(R((66, -384)), 47, 42)
+ pc = R((100, -422))
+ pom = c.poly([(pc[0] + 15 * (1 + 0.2 * (i % 2)) * np.cos(a), pc[1] + 15 * (1 + 0.2 * (i % 2)) * np.sin(a))
+ for i, a in enumerate(np.linspace(0, 2 * np.pi, 22, endpoint=False))], facet=0.5)
+ hat = U(dome, band)
+ hair = U(c.poly(R((98, -360), (112, -348), (101, -347), (108, -336), (93, -342), (88, -352))),
+ c.poly(R((24, -384), (14, -376), (26, -378))))
+ # --- scarf: wound round the neck, two tails streaming forward on the wind (they do not lean with the body)
+ wrap = c.stroke(R((30, -320), (52, -330), (82, -324)), 24, 22)
+ n0 = R((36, -324))
+ tails = [([(0, 0), (-20, -14), (-42, -10), (-64, -24), (-86, -20), (-108, -34), (-126, -30)],
+ [15, 12, 15, 11, 14, 11, 13]),
+ ([(-2, 4), (-20, 6), (-40, 0), (-58, 8), (-76, 4)], [13, 10, 13, 10, 11])]
+ tail1 = np.zeros_like(wrap); fringe = np.zeros_like(wrap); stripes = np.zeros_like(wrap)
+ for pts, widths in tails:
+ path = [(n0[0] + dx, n0[1] + dy) for dx, dy in pts]
+ sp = spline(np.array(path, np.float32), 12)
+ wv = np.interp(np.linspace(0, len(widths) - 1, len(sp)), np.arange(len(widths)), widths)
+ band = np.zeros_like(wrap)
+ for i in range(len(sp) - 1):
+ band = U(band, c.capsule(sp[i], sp[i + 1], wv[i] / 2, wv[i + 1] / 2))
+ tail1 = U(tail1, band)
+ e = path[-1]
+ for k in range(4): # fringe: strands fanning out, not touching
+ ang = np.radians(160 + k * 14)
+ fringe = U(fringe, c.stroke([(e[0] + 2, e[1] - 3 + k * 2.2),
+ (e[0] + 2 + 14 * np.cos(ang), e[1] - 3 + k * 2.2 - 14 * np.sin(ang))], 2.4, 1.5,
+ smooth=False))
+ Ls = np.concatenate([[0], np.cumsum(np.linalg.norm(np.diff(sp, axis=0), axis=1))])
+ for d in np.arange(26, Ls[-1] - 10, 22): # knitted stripes across the tail
+ i = int(np.searchsorted(Ls, d)); t = sp[min(i + 1, len(sp) - 1)] - sp[max(i - 1, 0)]
+ t = t / (np.hypot(*t) + 1e-6); nx, ny = -t[1], t[0]
+ q = sp[i]
+ stripes = U(stripes, c.stroke([(q[0] - nx * 12, q[1] - ny * 12), (q[0] + nx * 12, q[1] + ny * 12)], 6,
+ smooth=False) * band)
+ scarf = U(U(wrap, tail1), fringe)
+ # --- the reel in the near hand: a ring with six spokes (the gaps between them need bridges)
+ RC = R((-64, -286)); RR = 25
+ reel = c.ring(RC, RR, RR - 6)
+ for a in np.radians(np.arange(15, 375, 60)):
+ reel = U(reel, c.capsule(RC, (RC[0] + RR * np.cos(a), RC[1] + RR * np.sin(a)), 2.6))
+ reel = U(reel, c.ellipse(RC, 7))
+ reel = U(reel, c.capsule(RC, R((-38, -276)), 4)) # the handle, into the fist
+
+ # visibility, back to front: far arm, rear leg, front leg, shoes, torso, head, hat, near arm, scarf, reel
+ v_sleeve_f = hide(sleeve_f, torso, sleeve_n, hand_n, scarf, reel)
+ v_hand_f = hide(hand_f, sleeve_n, hand_n, reel, scarf)
+ v_leg_r = hide(leg_r, leg_f, shoes, torso)
+ v_leg_f = hide(leg_f, shoes, torso)
+ v_torso = hide(torso, sleeve_n, scarf)
+ v_head = hide(head, hat, scarf)
+ v_hat = hide(U(hat, pom), scarf)
+ v_sleeve_n = hide(sleeve_n, hand_n, reel)
+ v_hand_n = hide(hand_n, reel)
+ v_scarf = hide(scarf, reel)
+ legs = U(v_leg_f, v_leg_r)
+ jacket = U(v_torso, U(v_sleeve_n, v_sleeve_f))
+ body = U(U(U(leg_f, leg_r), shoes), U(U(torso, sleeve_n), U(sleeve_f, U(hand_n, hand_f))))
+ body = U(body, U(U(head, hat), U(pom, U(scarf, hair))))
+
+ # ---------------- plate 1: light -- the whole figure, so the busy wall drops out behind it
+ light = body
+ # ---------------- plate 2: grey -- jacket (its lit rim stays light), hat, trousers, shadow sides
+ grey = jacket * (1 - shade_side(torso, (-LIGHT[0], -LIGHT[1]), 6, soft=1.2))
+ grey = U(grey, v_hat * (1 - pom))
+ grey = U(grey, legs)
+ grey = U(grey, shade_side(head, LIGHT, 20, soft=2, wobble=0.4, seed=1) * v_head)
+ grey = U(grey, shade_side(U(hand_n, hand_f), LIGHT, 7) * U(v_hand_n, v_hand_f))
+ grey = U(grey, shade_side(wrap, LIGHT, 8, soft=1.5, wobble=0.5, seed=2) * v_scarf * (1 - tail1))
+ grey = U(grey, stripes * v_scarf)
+ grey = U(grey, c.stroke(R((40, -326), (66, -334), (86, -326)), 4) * wrap) # a fold in the wrap
+ grey = U(grey, ear * v_head)
+ grey = U(grey, shade_side(shoes, LIGHT, 10))
+ grey = U(grey, shade_side(pom, LIGHT, 9) * v_hat)
+ # ---------------- plate 3: black -- the deep shadows, seams, features, the reel
+ black = shade_side(torso, LIGHT, 34, soft=3.0, wobble=0.35, seed=3) * v_torso
+ black = U(black, shade_side(sleeve_f, LIGHT, 40) * v_sleeve_f) # the far arm is in shadow
+ black = U(black, shade_side(sleeve_n, LIGHT, 9, soft=1.5) * v_sleeve_n)
+ seams = np.zeros_like(torso)
+ for k in range(4): # puffer quilting
+ y = -202 - k * 27
+ seams = U(seams, c.stroke(R((-14, y + 6), (30, y - 2), (104, y - 12)), 3.2))
+ black = U(black, seams * v_torso)
+ black = U(black, c.stroke(R((52, -286), (14, -248), (-20, -262)), 3.0) * v_sleeve_n) # elbow crease
+ black = U(black, shade_side(leg_f, LIGHT, 18, soft=2.0) * v_leg_f)
+ black = U(black, shade_side(leg_r, LIGHT, 44, soft=2.0) * v_leg_r)
+ black = U(black, U(sole_f, sole_r))
+ black = U(black, c.stroke([(-84, -42), (-92, -30)], 2.6) * shoe_f) # laces
+ black = U(black, c.stroke([(-96, -46), (-104, -34)], 2.6) * shoe_f)
+ black = U(black, c.stroke([(40, -30), (46, -20)], 2.6) * shoe_r)
+ black = U(black, shade_side(hat, LIGHT, 18, soft=2.0, wobble=0.3, seed=5) * v_hat * (1 - pom))
+ for k in range(10): # ribbing of the turn-up
+ q0 = R((28 + k * 8.2, -390 + k * 8.2 * 0.29 + 6)); q1 = R((30 + k * 8.2, -390 + k * 8.2 * 0.29 - 7))
+ black = U(black, c.stroke([q0, q1], 2.0, smooth=False) * band * v_hat)
+ black = U(black, hair)
+ black = U(black, c.ellipse(R((33, -366)), 4.0, 5.4, rot=-20) * v_head) # eye, looking up at the kite
+ black = U(black, c.stroke(R((26, -377), (34, -380), (43, -378)), 2.6) * v_head) # brow
+ black = U(black, c.poly(R((21, -347), (34, -343), (28, -337))) * v_head) # open mouth
+ black = U(black, c.ellipse(R((17, -356)), 2.0, 1.4) * v_head) # nostril
+ black = U(black, c.stroke(R((72, -366), (76, -360), (72, -354)), 2.4) * ear * v_head)
+ black = U(black, shade_side(head, LIGHT, 7, soft=1.0) * v_head)
+ grey = U(grey, c.stroke(R((46, -330), (70, -334), (92, -324)), 5) * wrap * v_scarf) # under the chin
+ black = U(black, reel)
+ black = U(black, c.stroke(R((-42, -282), (-32, -286)), 2.2) * v_hand_n) # knuckles
+ black = U(black, shade_side(pom, LIGHT, 3) * v_hat)
+ string_from = (RC[0] - RR * 0.7, RC[1] - RR * 0.7)
+ return dict(light=light, grey=grey, black=black, string_from=string_from)
+
+
+def kite_design(c):
+ """a diamond kite: four panels between two spars; the spars are the bridges of the red card"""
+ T, Lf, R, B = (0, -150), (-92, -46), (92, -46), (0, 120)
+ body = c.poly([T, R, B, Lf], facet=0.35)
+ spar = np.maximum(c.capsule(T, B, 3.4), c.capsule(Lf, R, 3.4))
+ red = body * (1 - spar)
+ # the right-hand panels in shade (the kite bows into the wind)
+ shade = np.clip(c.poly([T, R, B, (4, -46)]) - spar * 1.4, 0, 1) * body
+ return dict(red=red, shade=shade, cross=(0, -46), tail=B)
+
+
+def bow_design(c):
+ """one little bow for the tail (reused)"""
+ return np.maximum(np.maximum(c.poly([(0, 0), (-16, -9), (-16, 9)]), c.poly([(0, 0), (16, -9), (16, 9)])),
+ c.ellipse((0, 0), 4.5))
+
+
+def leaf_design(c):
+ """a small leaf on the wind; its midrib is a bridge that runs right through it"""
+ blade = c.poly([(-15, 0), (-7, -6.5), (6, -6), (14, 0), (6, 6), (-7, 6.5)], smooth=True)
+ stem = c.stroke([(13, 0), (21, 3)], 2.2, 1.6, smooth=False)
+ m = np.maximum(blade, stem)
+ return m * (1 - c.stroke([(-20, 0), (16, 0)], 1.8, smooth=False))
+
+
+def bird_design(c):
+ """a swallow heading left: slim body, swept-back crescent wings (one up, one down), long forked tail"""
+ U = np.maximum
+ body = c.poly([(-30, 0), (-23, -4), (-8, -5), (10, -3), (16, 0), (10, 4), (-8, 5), (-23, 4)], smooth=True)
+ tail = c.poly([(8, -2), (44, -10), (24, 0), (46, 12), (8, 3)])
+ up = c.poly([(-7, -3), (-3, -18), (5, -32), (21, -44), (13, -29), (9, -15), (5, -2)], smooth=True)
+ down = c.poly([(-5, 3), (1, 13), (13, 24), (8, 12), (5, 3)], smooth=True)
+ return U(U(body, tail), U(up, down))
+
+
+s = Stencil(1920, 1080, seed=23)
+
+# ---- the wall: board-marked concrete, tie holes, weather; the pavement
+s.wall(ground=GROUND)
+s.pavement()
+s.stage('wall')
+
+# ---- what was here before: a faded tag washed half off, a roller buff over another
+s.freehand([(96, 668), (110, 600), (140, 655), (150, 610), (180, 650), (196, 596), (214, 660), (232, 616),
+ (268, 640), (300, 606), (322, 652), (360, 628)], '#b98293', width=11, coats=1.3, wash=0.7, per=12)
+s.freehand([(120, 690), (220, 682), (340, 694)], '#b98293', width=7, coats=1.1, wash=0.7)
+s.freehand([(1430, 160), (1470, 110), (1500, 190), (1540, 120), (1590, 200), (1640, 130), (1700, 170)],
+ '#3d6fa8', width=14, coats=2.0, drips=0.0)
+s.buff(1390, 96, 1770, 290)
+s.stage('history')
+
+# ---- the kid: three cards, light -> grey -> black
+box = (KID[0] - 200 * KS, KID[1] - 480 * KS, KID[0] + 175 * KS, KID[1] + 4)
+cards = {}
+for name in ('light', 'grey', 'black'):
+ cards[name] = s.card(*box, origin=KID, scale=KS, tape=[(0, 0), (1, 0), (0, 1), (1, 1)])
+plates = kid_design(cards['light'])
+for name in ('light', 'grey', 'black'):
+ cards[name].cut(plates[name]).bridges(width=3.0)
+s.spray(cards['light'], WHITE, coats=3.0, misreg=0.0, drips=0.06)
+s.stage('card_light', card=cards['light'])
+s.stage('light')
+s.spray(cards['grey'], GREY, coats=2.0, misreg=2.0, drips=0.2)
+s.stage('grey')
+s.spray(cards['black'], BLACK, coats=2.0, misreg=2.0, drips=0.7)
+s.stage('card_black', card=cards['black'])
+s.stage('kid')
+
+# ---- the kite: red, then the shaded panels in dark red
+KITE, KK = (560, 260), 0.85
+kc = s.card(KITE[0] - 150, KITE[1] - 200, KITE[0] + 150, KITE[1] + 170, origin=KITE, scale=KK)
+kd = kite_design(kc)
+kc.cut(kd['red'])
+ks = s.card(KITE[0] - 150, KITE[1] - 200, KITE[0] + 150, KITE[1] + 170, origin=KITE, scale=KK)
+ks.cut(kd['shade'])
+s.spray(kc, RED, coats=2.0, misreg=0.0, drips=0.8, angle=-30)
+s.spray(ks, '#8c1c16', coats=1.6, misreg=1.5, drips=0.4)
+s.stage('kite')
+
+# ---- string and tail, freehand with a skinny cap; bows and birds from little reusable cards
+sf = plates['string_from']
+x0, y0 = KID[0] + sf[0] * KS, KID[1] + sf[1] * KS
+x1, y1 = KITE[0] + kd['cross'][0] * KK, KITE[1] + kd['cross'][1] * KK
+sag = [(x0 + (x1 - x0) * t, y0 + (y1 - y0) * t + 90 * 4 * t * (1 - t) * (1 - 0.3 * t)) for t in np.linspace(0, 1, 9)]
+s.freehand(sag, BLACK, width=2.8, coats=1.9, speed=[0.6, 1.2, 1.4, 1.4, 1.3, 1.2, 1.2, 1.0, 0.8], drips=0.8)
+tb = (KITE[0] + kd['tail'][0] * KK, KITE[1] + kd['tail'][1] * KK)
+tail = [tb, (tb[0] - 20, tb[1] + 60), (tb[0] - 70, tb[1] + 100), (tb[0] - 110, tb[1] + 90),
+ (tb[0] - 160, tb[1] + 130), (tb[0] - 200, tb[1] + 200)]
+s.freehand(tail, BLACK, width=2.6, coats=1.6, drips=0.3, spits=1)
+bow = s.card(-60, -50, 60, 50, origin=(0, 0))
+bow.cut(bow_design(bow))
+tp = spline(np.array(tail, np.float32), 20)
+for k, idx in enumerate(np.linspace(0.18, 0.95, 5) * (len(tp) - 1)):
+ i = int(idx)
+ tx, ty = tp[min(i + 2, len(tp) - 1)] - tp[max(i - 2, 0)]
+ s.spray(bow, RED, coats=1.8, cone=10, at=(tp[i][0], tp[i][1]), rot=np.degrees(np.arctan2(-ty, tx)) + 90,
+ misreg=0.5, drips=0.2)
+bird = s.card(-80, -80, 80, 80, origin=(0, 0))
+bird.cut(bird_design(bird))
+for bx, by, br in [(860, 160, 6), (960, 236, -4), (790, 318, 12)]:
+ s.spray(bird, BLACK, coats=1.8, cone=12, at=(bx, by), rot=br, misreg=0.5, drips=0.2)
+leaf = s.card(-50, -40, 50, 40, origin=(0, 0))
+leaf.cut(leaf_design(leaf))
+for lx, ly, lr in [(1150, 470, 30), (1040, 610, -20), (1210, 790, 70), (930, 520, 110)]:
+ s.spray(leaf, BLACK, coats=2.0, cone=10, at=(lx, ly), rot=lr, misreg=0.5, drips=0.0)
+s.stage('string')
+
+# ---- lettering under it all
+tc = s.card(80, 800, 640, 960, origin=(80, 800))
+tc.cut(tc.text('HOLD ON', 280, 130, 118, anchor='ms', spacing=6))
+s.spray(tc, BLACK, coats=2.0, misreg=0.0, drips=1.0, wet=2.2)
+
+s.save(out, stages)
+print(out, f'{time.time() - t0:.1f}s')
diff --git a/examples/tomb_harvest.jpg b/examples/tomb_harvest.jpg
new file mode 100644
index 0000000..9514130
Binary files /dev/null and b/examples/tomb_harvest.jpg differ
diff --git a/examples/tomb_harvest.py b/examples/tomb_harvest.py
new file mode 100644
index 0000000..1679572
--- /dev/null
+++ b/examples/tomb_harvest.py
@@ -0,0 +1,195 @@
+"""Example (Egyptian tomb painting): Harvest on the Nile / 尼罗河丰收 -- a wall in a Theban tomb chapel, three
+registers read as one story: ploughing and sowing after the flood, reaping the emmer, and the scribe counting the
+sacks of grain (twelve sacks in the stack, written ∩|| above it). An estate overseer at hierarchical scale stands
+on the main ground line and watches, under columns of (pseudo-)hieroglyphs. Kheker frieze, block border, striped
+register bands, the river with fish and lotus at the foot of the wall. Painted the way it was done: plaster,
+red squaring grid, red sketch, ground wash, one pigment at a time, black outlines, the text -- then 3,300 years.
+No image model.
+python3 tomb_harvest.py [out.png] [--stages DIR]
+"""
+import os, sys
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from tomb import TombPainting
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'tomb_harvest.png'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+
+W, H = 1920, 1080
+tp = TombPainting(W, H, seed=11)
+tp.wall()
+tp.stage('plaster')
+
+# ---------------------------------------------------------------- layout
+BL, BR = 22, W - 22 # block border inside edges
+TOP = 105 # top of the scene area (under the kheker frieze and its band)
+REG = [(TOP, 375), (387, 657), (669, 940)] # registers: (top, ground line)
+XR = 432 # registers start right of the overseer
+HF = 212 # worker height (sole to top of wig)
+U = HF / 19.6
+OV_H, OV_X = 548, 178 # overseer height and hip x
+RIV = (952, 1014)
+
+# ---- red cords first: register guides and squaring grids (one canon unit per cell)
+for (t, b) in REG:
+ tp.grid((XR, t + 4, BR, b), cell=U, base=b)
+tp.grid((BL + 8, 395, XR - 10, REG[2][1]), cell=OV_H / 19.6, base=REG[2][1])
+for y in (TOP, RIV[0], RIV[1]) + tuple(b for _, b in REG):
+ tp.guide((BL, y), (BR, y))
+tp.guide((XR - 6, TOP), (XR - 6, REG[2][1]))
+tp.stage('grid')
+
+# ---------------------------------------------------------------- declare the frame
+tp.block_border(0, 0, W, BL)
+tp.block_border(0, H - BL, W, H)
+tp.block_border(0, BL, BL, H - BL)
+tp.block_border(BR, BL, W, H - BL)
+tp.kheker(BL, BR, BL + 2, 86)
+tp.band(BL, BR, 86, [('rule', 2), ('blue', 8), ('rule', 2), ('yellow', 5), ('rule', 2)])
+for (t, b) in REG[:2]:
+ tp.band(XR, BR, b, [('rule', 2), ('red', 7), ('rule', 2)])
+tp.band(BL, BR, REG[2][1], [('rule', 2), ('red', 8), ('rule', 2)])
+tp.river(BL, RIV[0], BR, RIV[1], fish=6, lotus=9, seed=4)
+tp.band(BL, BR, RIV[1], [('rule', 2), ('yellow', 6), ('rule', 2), ('red', 9), ('rule', 2), ('black', 13)])
+tp.part(None, None, paths=[np.array([[XR - 6, TOP], [XR - 6, REG[2][1]]])], width=2.2, sketch=False)
+
+# ---------------------------------------------------------------- the overseer and his titles
+ov = tp.figure(OV_X, REG[2][1], OV_H, 'staff', facing=1, wig='long', dress='long')
+tp.staff(ov['hand_f'], OV_H * 0.98, facing=1, z=ov['z_hand_f'] - 0.01, lw=ov['lw'])
+cl = ov['hand_b'] # a folded linen cloth hangs from the other fist
+cloth = np.array([[cl[0] - 7, cl[1] - 4], [cl[0] + 7, cl[1] - 4], [cl[0] + 9, cl[1] + 62], [cl[0] + 6, cl[1] + 72],
+ [cl[0] - 4, cl[1] + 73], [cl[0] - 8, cl[1] + 64]], np.float32)
+tp.part(cloth, 'white', z=ov['z_hand_b'] - 0.01, width=ov['lw'] * 0.8)
+tp.part(None, None, paths=[np.array([[cl[0] - 1, cl[1] + 8], [cl[0] + 1, cl[1] + 70]]),
+ np.array([[cl[0] + 4, cl[1] + 8], [cl[0] + 6, cl[1] + 68]])], ink='#b9a58c', width=1.6,
+ z=ov['z_hand_b'] - 0.005)
+cols = np.linspace(BL + 22, XR - 22, 6)
+for i in range(5):
+ tp.column(cols[i], TOP + 10, cols[i + 1], 372, facing=1, n=20, seed=100 + i, rules=(i == 0))
+ tp.part(None, None, paths=[np.array([[cols[i + 1], TOP + 10], [cols[i + 1], 372]])], width=1.6, layer='text')
+
+# ---------------------------------------------------------------- register 1: ploughing and sowing after the flood
+t1, g1 = REG[0]
+soil = np.array([[XR + 4, g1], [1460, g1], [1460, g1 - 7], [XR + 4, g1 - 5]], np.float32)
+tp.part(soil, 'black', outline=False, rag=0.8)
+far = tp.ox(1010, g1, 252, facing=-1, colour='brown', patches=None, seed=3)
+pole_z = tp._z; tp._z += 1
+near = tp.ox(1040, g1, 252, facing=-1, colour='white', patches='black', seed=8)
+pm = tp.figure(1225, g1, HF, 'plough', facing=-1, wig='cap', collar=False)
+share = np.array([1092, g1 - 3], np.float32)
+heel = np.array([1112, g1 - 16], np.float32)
+tp.rod(heel, pm['hand_f'] + (0, -4), 6, 'ochre', z=pm['z_hand_f'] - 0.01)
+tp.rod(heel + (6, 0), pm['hand_b'] + (0, -4), 6, 'ochre', z=pm['z0'] - 0.5)
+tp.part(np.array([share, heel + (-4, -6), heel + (12, -2), heel + (8, 10)]), 'brown', z=pm['z0'] - 0.4)
+tp.rod(heel + (-2, -4), near['poll'] + (14, 6), 7, 'ochre', z=pole_z)
+yoke0, yoke1 = far['poll'] + (-14, -2), near['poll'] + (16, 4)
+tp.rod(yoke0, yoke1, 9, 'ochre', z=near['z'] + 0.5)
+for p in (far['poll'], near['poll']):
+ tp.part(None, None, paths=[np.array([p + (-6, -10), p + (6, 8)]), np.array([p + (-1, -11), p + (10, 6)])], width=2.2,
+ z=near['z'] + 0.6, ink='#6b5a3a')
+sw = tp.figure(560, g1, HF, 'sow', facing=-1, collar=False)
+tp.basket(sw['wrist_b'][0] + 4, sw['wrist_b'][1] + 6, 46, 30, z=sw['z_hand_b'] - 0.02, full='yellow')
+tp.grain_stream(sw['hand_f'] + (-14, 6), sw['hand_f'] + (-60, 96), n=34, spread=7, colour='brown')
+for x in (1395, 1545):
+ hm = tp.figure(x, g1, HF, 'hoe', facing=-1, wig='cap' if x > 1400 else 'short', collar=False)
+ tp.hoe(hm)
+# the canal at the end of the field: a pool seen from above, with lotus and papyrus
+px0, px1 = 1640, BR - 22
+tp.part(np.array([[px0, g1 - 108], [px1, g1 - 108], [px1, g1], [px0, g1]], np.float32), 'blue', rag=0.4)
+rows = []
+for k, yy in enumerate(np.arange(g1 - 92, g1 - 8, 18.0)):
+ xs = np.arange(px0 + 8 + (k % 2) * 7, px1 - 6, 14.0)
+ rows.append(np.stack([np.repeat(xs, 2)[:-1] + np.tile([0, 7], len(xs))[:-1], np.tile([yy - 4, yy + 4], len(xs))[:-1]], 1))
+tp.part(None, None, paths=rows, width=1.4, sketch=False)
+for i, x in enumerate(np.linspace(px0 + 30, px1 - 30, 4)):
+ tp.papyrus_clump(x, g1 - 106, 112 - 14 * (i % 2), n=3, seed=60 + i)
+for k, (cx, cy) in enumerate([(700, t1 + 8), (1300, t1 + 8)]):
+ for j in range(4):
+ tp.column(cx + j * 34, cy, cx + (j + 1) * 34, cy + 74, facing=-1, n=6, seed=200 + 10 * k + j, rules=False, lw=1.4)
+ for j in range(5):
+ tp.part(None, None, paths=[np.array([[cx + j * 34, cy], [cx + j * 34, cy + 74]])], width=1.4, layer='text')
+
+# ---------------------------------------------------------------- register 2: reaping the emmer
+t2, g2 = REG[1]
+reapers = [650, 840, 1030]
+grabs, stub = [], []
+for x in reapers:
+ grabs.append((x - 79 * U / 10.7 * 0 - 7.4 * U, g2 - 9.0 * U, (x - 7.4 * U - 34, x - 7.4 * U + 6)))
+ stub.append((x - 7.4 * U + 10, x + 50))
+tp.wheat(XR + 30, reapers[-1] + 60, g2, t2 + 62, every=8.5, stubble=stub, grab=grabs, seed=5)
+for i, x in enumerate(reapers):
+ rp = tp.figure(x, g2, HF, 'reap', facing=-1, wig='short' if i != 1 else 'cap', collar=False)
+ tp.sickle(rp['hand_b'], 34, facing=-1, angle=-20, z=rp['z_hand_b'] - 0.01)
+for x in (1110, 1150):
+ tp.sheaf(x, g2, 46, 92)
+gl = tp.figure(1265, g2, HF * 0.95, 'glean', facing=-1, sex='f', wig='woman', dress='dress')
+tp.basket(1195, g2 - 30, 52, 30, z=gl['z0'] - 0.5, full='yellow')
+tr = tp.tree(1470, g2, 250, 196, waterskin=(-62, 58))
+cr = tp.figure(1700, g2, HF, 'carry', facing=1, collar=False)
+bc = cr['S']((-3.0, 17.2)) # the basket rides on the back shoulder, behind the head
+tp.basket(bc[0], bc[1], 72, 40, z=cr['z_hand_b'] - 0.05, full='yellow')
+for k, (cx, cy) in enumerate([(560, t2 + 6), (1180, t2 + 8)]):
+ for j in range(3):
+ tp.column(cx + j * 34, cy, cx + (j + 1) * 34, cy + 72, facing=-1, n=6, seed=300 + 10 * k + j, rules=False)
+ for j in range(4):
+ tp.part(None, None, paths=[np.array([[cx + j * 34, cy], [cx + j * 34, cy + 72]])], width=1.4, layer='text')
+
+# ---------------------------------------------------------------- register 3: the scribe counts the sacks
+t3, g3 = REG[2]
+sc = tp.figure(520, g3, HF, 'squat', facing=1, wig='short')
+tp.papyrus(sc['hand_b'] + (-6, 4), sc['hand_f'] + (6, -4), 13, z=sc['z_hand_b'] - 0.05)
+tp.part(None, None, paths=[np.array([sc['hand_b'], sc['hand_b'] + (14, -16)])], ink='#3a2a22', width=1.6,
+ z=sc['z_hand_b'] + 0.5)
+ear = sc['ear']
+tp.part(None, None, paths=[np.array([ear + (8, -2), ear + (-24, 6)])], ink='#7b4a2c', width=2.0, z=sc['z_top'] + 0.5)
+tp.palette(478, g3 - 7, 60, angle=0.0)
+# the stack: twelve sacks (5 + 4 + 3)
+sw_, sh_ = 40, 50
+stack_x = 640
+for row, n in enumerate((5, 4, 3)):
+ for i in range(n):
+ tp.sack(stack_x + (i + row * 0.5) * (sw_ + 2), g3 - row * (sh_ - 6), sw_, sh_)
+tp.numerals(12, stack_x + 58, g3 - 3 * sh_ - 58, 46, facing=1)
+po = tp.figure(930, g3, HF, 'carry', facing=-1, wig='cap', collar=False)
+sb = po['S']((-0.4, 15.9)) # the sack lies across the back shoulder
+tp.sack(sb[0], sb[1], 48, 72, lean=-1.2, z=po['z_hand_b'] - 0.05)
+ho = tp.figure(1030, g3, HF, 'hold', facing=1, collar=False, wf=(5.6, 9.6), wb=(4.6, 9.3))
+tp.sack(1098, g3, 50, 112, z=ho['z_hand_f'] - 0.5)
+scp = tp.figure(1250, g3, HF, 'scoop', facing=-1, collar=False, wf=(7.2, 12.4), wb=(6.2, 10.9), lean=28)
+mq = scp['hand_f']
+tp.measure(mq[0] - 14, mq[1] + 16, 38, 40, z=scp['z_hand_f'] - 0.01, tilt=-0.8)
+tp.grain_stream((mq[0] - 34, mq[1] + 2), (1100, g3 - 108), n=26, spread=2.5)
+tp.heap(1450, g3, 250, 150)
+wn = tp.figure(1680, g3, HF * 0.95, 'walk', facing=-1, sex='f', wig='woman', dress='dress', wf=(4.6, 16.4), wb=(2.6, 17.3),
+ hf='fist', hb='fist', bf=-1, bb=-1, cross=True, collar=False)
+tp.scoop(wn['hand_f'], 30, angle=30, facing=-1, z=wn['z_hand_f'] - 0.01)
+tp.scoop(wn['hand_b'], 30, angle=55, facing=-1, z=wn['z_hand_b'] - 0.01)
+tp.grain_stream(wn['hand_f'] + (-40, -40), wn['hand_f'] + (-60, 150), n=40, spread=9, chaff=14)
+tp.heap(1800, g3, 120, 70)
+for k, (cx, cy) in enumerate([(800, t3 + 6), (1300, t3 + 8)]):
+ for j in range(3):
+ tp.column(cx + j * 34, cy, cx + (j + 1) * 34, cy + 72, facing=-1 if k else 1, n=6, seed=400 + 10 * k + j, rules=False)
+ for j in range(4):
+ tp.part(None, None, paths=[np.array([[cx + j * 34, cy], [cx + j * 34, cy + 72]])], width=1.4, layer='text')
+
+# ---------------------------------------------------------------- paint it, pot by pot
+tp.sketch()
+tp.stage('sketch')
+tp.ground('#d9bf86')
+tp.stage('ground')
+tp.colour(['skin', 'skin_f', 'red', 'brown', 'ochre'])
+tp.stage('reds')
+tp.colour(['linen', 'white', 'yellow'])
+tp.stage('whites')
+tp.colour(['blue', 'lblue', 'green', 'lgreen', 'dkgreen'])
+tp.stage('blues')
+tp.colour()
+tp.ink()
+tp.stage('outlines')
+tp.colour(layer='text')
+tp.ink(layer='text')
+tp.stage('text')
+tp.age(losses=[(1902, 560, 40, 92), (250, 1052, 80, 26), (1250, 30, 48, 24), (18, 330, 24, 62), (1560, 620, 26, 18)],
+ zones=[(176, 868, 34), (958, 296, 22), (1338, 512, 18), (742, 610, 16)], cracks=9, seed=2)
+tp.save(out, stages_dir=stages)
+print('saved', out)
diff --git a/lib/artdeco.py b/lib/artdeco.py
new file mode 100644
index 0000000..1482f9c
--- /dev/null
+++ b/lib/artdeco.py
@@ -0,0 +1,1047 @@
+"""artdeco — a 1930s Art Deco / Streamline travel poster: airbrush and frisket on illustration board, printed by
+offset lithography (numpy + Pillow only).
+
+Model: the poster artist never draws a line. Every shape is a *frisket* -- a sheet of masking film cut with a knife
+and laid on the board -- and the colour is sprayed over it with an airbrush, so each shape has a perfectly crisp
+edge and an inside that is one smooth gradient. Form comes only from light and dark: a tower is a flat cut-out
+whose face is sprayed darker on one side and lighter on the other, a cylinder gets a hot highlight streak along
+one shoulder and a band of reflected light under its belly, a sky is one long fade.
+ spray `spray(mask, colour, density)` is one pass of the airbrush over a frisket. Density 0..1 per pixel is
+ how much paint lands. Airbrush paint arrives as a fog of tiny droplets, so wherever the coat is thin
+ (the tail of a fade) it is speckled -- the stipple is a fixed per-board noise multiplied by d(1 - d),
+ zero where the coat is solid or absent. Gradients are built from passes: `fade()` (linear, between two
+ points, through colour stops) and `glow()` (radial).
+ sky `sky()` fades top to bottom; `burst()` is the Deco sunburst: alternating light and dark wedges
+ around a centre, sprayed through a fan-shaped frisket, strongest near the centre and fading outward,
+ with a soft radial glow; `moon()` a disc with an off-centre radial fade (a sphere) and a halo;
+ `searchlight()` a long wedge of light whose density falls along its length.
+ city `tower(x, base, tiers)` is a stepped skyscraper in elevation: each set-back tier is its own frisket,
+ sprayed as a slightly cylindrical face (dark on the shadow side, bright on the lit side) with vertical
+ fluting, a rim of light along each ledge, rows of lit and dark windows (`windows`) or lit slit strips
+ (`slits`); `spire`, `crown` (stepped fan of arches) and `clock(...)` sit on top. `far=` pushes a tower
+ into the haze: lighter, bluer, flatter.
+ water `water(horizon)` sprays the river and then mirrors whatever is already above the horizon into it,
+ broken into horizontal ripple dashes that get longer and sparser toward the viewer.
+ machines `camera()` + `express()` render a streamlined train on an arched viaduct from a little 3D scene
+ (signed distance fields, sphere-traced in numpy, rows above the train skipped, only edge pixels
+ supersampled). The renderer does not light it like a photograph: each material has a poster ramp
+ (shadow -> mid -> light colour) indexed by a half-Lambert term, plus an airbrushed highlight streak,
+ moon rim light and a band of reflected light underneath -- the way an illustrator models a
+ cylinder. The result comes back as layers so it can be laid in like the artist does: `frisket(r)`
+ (flat base colours), `model(r)` (form sprays), `lights(r)` (lit windows, headlamp, beam, bloom and
+ their reflections in the river).
+ type `lettering(s, ...)` sets a geometric Deco display alphabet built here from rectangles, diagonals and
+ elliptical bowls: thick stems and down-strokes, hairline cross-strokes, a high waist; filled with a
+ sprayed metallic fade and an optional cast block shadow. `caption()` is wide-tracked geometric sans
+ (Futura, else the system sans). `border()` is a double gold rule with stepped corners.
+ print `finish()` lays the lithographic print over everything: paper tone and tooth, a whisper of grain, a
+ faint warm cast, very slight edge vignette.
+Coordinates are pixels, y down; angles are degrees counter-clockwise from 3 o'clock. World units of the 3D scene
+are metres (y up).
+
+ from artdeco import ArtDeco
+ a = ArtDeco(1920, 1080, seed=3)
+ a.sky([(0, '#0a1530'), (1, '#3f8f8a')], bottom=690)
+ a.burst(1250, 430, rays=44)
+ a.moon(1250, 430, 110)
+ a.tower(1500, 690, [(160, 220), (120, 120), (70, 80)], spire=120)
+ a.water(690)
+ a.camera(f=1500, cx=960, horizon=690, height=12.5)
+ r = a.express(nose=(-7.4, 21), vp_x=1450)
+ a.frisket(r); a.model(r); a.lights(r)
+ a.lettering('NIGHT EXPRESS', 110, 300, 150)
+ a.finish(); a.save('out.jpg')
+"""
+import os
+import numpy as np
+from PIL import Image, ImageDraw
+from core import blur, noise2d, smoothstep, load_font, polygon_mask
+
+NAVY, MIDNIGHT, TEAL, JADE = '#0e1d3a', '#08112a', '#2f6f78', '#5fa39a'
+GOLD, BRASS, IVORY, CREAM = '#d9ac55', '#a9772f', '#f6ead0', '#efdcb2'
+MAROON, CRIMSON, WARM = '#5a1424', '#a82a33', '#ffd585'
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+def _c(c):
+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)
+
+
+def ramp(t, stops):
+ """t (any shape) through colour stops [(pos, colour), ...] -> (..., 3)"""
+ t = np.asarray(t, np.float32)
+ pos = np.array([p for p, _ in stops], np.float32)
+ col = np.stack([_c(c) for _, c in stops])
+ out = np.empty(t.shape + (3,), np.float32)
+ for k in range(3):
+ out[..., k] = np.interp(t, pos, col[:, k])
+ return out
+
+
+# ---------------------------------------------------------------- the Deco display alphabet
+# unit glyphs: cap height 1, y up from the baseline. Thick stems and down-strokes (T), hairline cross-strokes (t),
+# a high waist for E F H B P R. Each glyph = (advance width, [polygons]).
+_T, _t, _WAIST = 0.2, 0.055, 0.6
+
+
+def _rect(x0, y0, x1, y1):
+ return [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
+
+
+def _diag(xb, xt, w, yb=0.0, yt=1.0):
+ """slanted stroke of horizontal thickness w; left edge at xb (bottom) and xt (top)"""
+ return [(xb, yb), (xb + w, yb), (xt + w, yt), (xt, yt)]
+
+
+def _ring(cx, cy, rx, ry, a0=0, a1=360, tl=_T, tr=_T, tb=_t, tt=_t, n=96):
+ """elliptical bowl between angles a0..a1 (degrees ccw); side thicknesses left/right/bottom/top"""
+ a = np.radians(np.linspace(a0, a1, n))
+ icx, icy = cx + (tl - tr) / 2, cy + (tb - tt) / 2
+ irx, iry = rx - (tl + tr) / 2, ry - (tb + tt) / 2
+ outer = [(cx + rx * np.cos(t), cy + ry * np.sin(t)) for t in a]
+ inner = [(icx + irx * np.cos(t), icy + iry * np.sin(t)) for t in a[::-1]]
+ if a1 - a0 >= 360:
+ return [outer, inner] # drawn as outer filled, inner cut (see _glyph_mask)
+ return [outer + inner]
+
+
+def _bowl_right(xs, xc, yb, yt, rx, tx=_T):
+ """D/P/B bowl: arms from the stem at x=xs out to xc, then a half ring bulging right"""
+ cy, ry = (yb + yt) / 2, (yt - yb) / 2
+ return [_rect(xs - 0.01, yt - _t, xc + 0.005, yt), _rect(xs - 0.01, yb, xc + 0.005, yb + _t)] + \
+ _ring(xc, cy, rx, ry, -90, 90, tl=tx, tr=tx, tb=_t, tt=_t)
+
+
+def _glyph(ch):
+ T, t, W = _T, _t, _WAIST
+ if ch == 'A':
+ wd, ax = 0.9, 0.45
+ right = _diag(wd - T * 1.15, ax - T / 2, T * 1.15)
+ left = _diag(0.0, ax - T / 2, t * 1.25)
+ yb, yt = 0.27, 0.27 + t
+ xl = lambda y: t * 1.25 + (ax - T / 2) * y
+ xr = lambda y: (wd - T * 1.15) + (ax - T / 2 - (wd - T * 1.15)) * y
+ bar = [(xl(yb) - 0.01, yb), (xr(yb) + 0.01, yb), (xr(yt) + 0.01, yt), (xl(yt) - 0.01, yt)]
+ return wd, [right, left, bar]
+ if ch == 'B':
+ return 0.7, [_rect(0, 0, T, 1)] + _bowl_right(T, 0.37, W - t / 2, 1.0, 0.26, T * 0.85) + \
+ _bowl_right(T, 0.40, 0.0, W + t / 2, 0.30)
+ if ch == 'C':
+ return 0.84, _ring(0.42, 0.5, 0.42, 0.5, 42, 318)
+ if ch == 'D':
+ return 0.78, [_rect(0, 0, T, 1)] + _bowl_right(T, 0.32, 0, 1, 0.46)
+ if ch == 'E':
+ return 0.6, [_rect(0, 0, T, 1), _rect(T - 0.01, 1 - t, 0.6, 1), _rect(T - 0.01, W - t / 2, 0.5, W + t / 2),
+ _rect(T - 0.01, 0, 0.6, t)]
+ if ch == 'F':
+ return 0.58, [_rect(0, 0, T, 1), _rect(T - 0.01, 1 - t, 0.58, 1), _rect(T - 0.01, W - t / 2, 0.48, W + t / 2)]
+ if ch == 'G':
+ return 0.86, _ring(0.43, 0.5, 0.43, 0.5, 42, 360) + [_rect(0.47, 0.5 - t, 0.86, 0.5),
+ _rect(0.86 - T, 0.12, 0.86, 0.5)]
+ if ch == 'H':
+ return 0.78, [_rect(0, 0, T, 1), _rect(0.78 - T, 0, 0.78, 1), _rect(T - 0.01, W - t / 2, 0.79 - T, W + t / 2)]
+ if ch == 'I':
+ return T, [_rect(0, 0, T, 1)]
+ if ch == 'J':
+ return 0.56, [_rect(0.56 - T, 0.28, 0.56, 1)] + _ring(0.28, 0.28, 0.28, 0.28, 180, 360, tl=t * 1.4, tr=T)
+ if ch == 'K':
+ return 0.78, [_rect(0, 0, T, 1), _diag(T - 0.03, 0.78 - t * 1.4, t * 1.4, 0.36, 1.0),
+ _diag(0.78 - T * 1.1, T - 0.04, T * 1.1, 0.0, 0.62)]
+ if ch == 'L':
+ return 0.58, [_rect(0, 0, T, 1), _rect(T - 0.01, 0, 0.58, t)]
+ if ch == 'M':
+ wd = 1.02
+ return wd, [_rect(0, 0, t * 1.4, 1), _diag(wd / 2 - T * 0.55, 0.0, T * 1.1),
+ _diag(wd / 2 - t * 0.7, wd - T - t * 0.4, t * 1.4), _rect(wd - T, 0, wd, 1)]
+ if ch == 'N':
+ wd = 0.8
+ return wd, [_rect(0, 0, t * 1.4, 1), _diag(wd - T * 1.1, 0.0, T * 1.1), _rect(wd - t * 1.4, 0, wd, 1)]
+ if ch == 'O':
+ return 0.94, _ring(0.47, 0.5, 0.47, 0.5)
+ if ch == 'P':
+ return 0.66, [_rect(0, 0, T, 1)] + _bowl_right(T, 0.37, W - t / 2 - 0.03, 1.0, 0.29, T * 0.95)
+ if ch == 'Q':
+ return 0.96, _ring(0.47, 0.5, 0.47, 0.5) + [_diag(0.80, 0.52, T * 0.8, -0.08, 0.3)]
+ if ch == 'R':
+ return 0.74, [_rect(0, 0, T, 1)] + _bowl_right(T, 0.35, W - t / 2 - 0.03, 1.0, 0.29, T * 0.95) + \
+ [_diag(0.74 - T * 1.1, 0.25, T * 1.1, 0.0, W - 0.02)]
+ if ch == 'S':
+ wd = 0.68
+ return wd, _ring(wd / 2, 0.75 - t / 4, wd / 2 - 0.02, 0.25 + t / 4, 25, 270, tl=T * 0.95, tr=t * 1.4) + \
+ _ring(wd / 2, 0.25 + t / 4, wd / 2, 0.25 + t / 4, -155, 90, tl=t * 1.4, tr=T)
+ if ch == 'T':
+ return 0.72, [_rect(0, 1 - t * 1.5, 0.72, 1), _rect(0.36 - T / 2, 0, 0.36 + T / 2, 1)]
+ if ch == 'U':
+ return 0.78, [_rect(0, 0.32, T, 1), _rect(0.78 - t * 1.4, 0.32, 0.78, 1)] + \
+ _ring(0.39, 0.32, 0.39, 0.32, 180, 360, tl=T, tr=t * 1.4)
+ if ch == 'V':
+ wd = 0.86
+ return wd, [_diag(wd / 2 - T * 0.55, 0.0, T * 1.1), _diag(wd / 2 - t * 0.7, wd - t * 1.4, t * 1.4)]
+ if ch == 'W':
+ wd = 1.26
+ return wd, [_diag(0.3 - T * 0.5, 0.0, T * 1.0), _diag(0.3 - t * 0.7, 0.63 - t * 0.7, t * 1.4),
+ _diag(0.96 - T * 0.5, 0.63 - T * 0.5, T * 1.0), _diag(0.96 - t * 0.7, wd - t * 1.4, t * 1.4)]
+ if ch == 'X':
+ wd = 0.82
+ return wd, [_diag(wd - T * 1.1, 0.0, T * 1.1), _diag(0.0, wd - t * 1.4, t * 1.4)]
+ if ch == 'Y':
+ wd = 0.82
+ return wd, [_diag(wd / 2 - T / 2, 0.0, T, 0.46, 1.0), _diag(wd / 2 - t * 0.7, wd - t * 1.4, t * 1.4, 0.46, 1.0),
+ _rect(wd / 2 - T / 2, 0, wd / 2 + T / 2, 0.47)]
+ if ch == 'Z':
+ wd = 0.72
+ return wd, [_rect(0, 1 - t, wd, 1), _rect(0, 0, wd, t), _diag(0.0, wd - T * 1.1, T * 1.1, t * 0.5, 1 - t * 0.5)]
+ if ch == '-':
+ return 0.42, [_rect(0.04, 0.46, 0.38, 0.46 + t * 1.2)]
+ if ch in '·.':
+ return 0.3, [[(0.15, 0.4), (0.25, 0.5), (0.15, 0.6), (0.05, 0.5)]] if ch == '·' else [_rect(0.05, 0, 0.05 + T * 0.8, T * 0.8)]
+ if ch == ' ':
+ return 0.42, []
+ return None
+
+
+# ---------------------------------------------------------------- signed distance helpers for the 3D scene
+def _rbox2(x, y, bx, by, r):
+ qx = np.abs(x) - bx + r
+ qy = np.abs(y) - by + r
+ return np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) + np.minimum(np.maximum(qx, qy), 0) - r
+
+
+def _ext(d2, du):
+ """combine a 2D section distance with a distance along the extrusion axis"""
+ return np.hypot(np.maximum(d2, 0), np.maximum(du, 0)) + np.minimum(np.maximum(d2, du), 0)
+
+
+class _Render:
+ """layers of an `express()` render, all full-canvas: alpha, base, shaded, emissive, depth"""
+ pass
+
+
+class ArtDeco:
+ def __init__(self, W=1920, H=1080, seed=0, grain=1.0):
+ self.W, self.H, self.seed = W, H, seed
+ self.rng = np.random.default_rng(seed)
+ self.img = np.zeros((H, W, 3), np.float32)
+ self.speck = self.rng.standard_normal((H, W)).astype(np.float32) * grain # the airbrush's droplet fog
+ self.stages = []
+ self.yy, self.xx = np.mgrid[0:H, 0:W].astype(np.float32)
+ self.cam = None
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ # ------------------------------------------------------------ airbrush
+ def spray(self, mask, colour, density=1.0, grain=1.0, blend='paint'):
+ """one pass of the airbrush through a frisket: mask * density = paint coverage per pixel.
+ colour may be one colour or a (H, W, 3) field. Thin coats are speckled (droplets)."""
+ d = np.clip(np.asarray(mask, np.float32) * density, 0, 1)
+ if grain:
+ d = np.clip(d + self.speck * (0.2 * grain) * d * (1 - d), 0, 1)
+ col = _c(colour) if isinstance(colour, str) or np.ndim(colour) == 1 else colour
+ if blend == 'screen':
+ self.img = 1 - (1 - self.img) * (1 - d[..., None] * col)
+ elif blend == 'add':
+ self.img = np.minimum(self.img + d[..., None] * col, 1.5)
+ else:
+ self.img = self.img * (1 - d[..., None]) + col * d[..., None]
+
+ def fade(self, mask, stops, p0, p1, grain=1.0):
+ """linear gradient through colour stops from point p0 (pos 0) to p1 (pos 1), sprayed over mask"""
+ dx, dy = p1[0] - p0[0], p1[1] - p0[1]
+ L2 = dx * dx + dy * dy + 1e-6
+ t = ((self.xx - p0[0]) * dx + (self.yy - p0[1]) * dy) / L2
+ t = np.clip(t + self.speck * 0.006 * grain, 0, 1)
+ self.spray(mask, ramp(t, stops), grain=grain)
+
+ def glow(self, cx, cy, r, colour, strength=1.0, power=2.0, mask=1.0, blend='screen'):
+ """radial airbrush glow: soft disc of light falling off to zero at radius r"""
+ d = np.hypot(self.xx - cx, self.yy - cy) / r
+ a = np.clip(1 - d, 0, 1) ** power * strength
+ self.spray(a * mask, colour, grain=0.6, blend=blend)
+
+ def rect(self, x0, y0, x1, y1):
+ """anti-aliased rectangle frisket (fractional edges)"""
+ cx = np.clip(np.minimum(self.xx + 1 - x0, x1 - self.xx), 0, 1)
+ cy = np.clip(np.minimum(self.yy + 1 - y0, y1 - self.yy), 0, 1)
+ return (cx * cy).astype(np.float32)
+
+ def poly(self, pts):
+ return polygon_mask(self.H, self.W, pts, ss=4)
+
+ def disc(self, cx, cy, r):
+ return np.clip(r - np.hypot(self.xx + 0.5 - cx, self.yy + 0.5 - cy) + 0.5, 0, 1).astype(np.float32)
+
+ # ------------------------------------------------------------ sky
+ def sky(self, stops, top=0, bottom=None):
+ """the long airbrushed fade of the night sky, top -> bottom"""
+ bottom = self.H if bottom is None else bottom
+ self.fade(1.0, stops, (0, top), (0, bottom))
+
+ def burst(self, cx, cy, rays=44, contrast=0.16, reach=1500, colour='#bfe3d6', dark='#06102a', glow=0.5,
+ phase=0.0, taper=0.35, bottom=None):
+ """Deco sunburst: alternating light and dark wedges around (cx, cy). The light wedges are sprayed through
+ a fan-shaped frisket and are a little wider near the centre (taper), contrast falls off with distance.
+ bottom: row where the frisket stops (the horizon)."""
+ dx, dy = self.xx - cx, self.yy - cy
+ r = np.hypot(dx, dy) + 1e-3
+ th = np.arctan2(dy, dx) + np.radians(phase)
+ n = rays / 2
+ s = np.sin(n * th)
+ w = n / r * 1.2 # d(sin)/dpx -> 1 px anti-aliasing at any radius
+ bias = taper * np.exp(-r / (reach * 0.25)) # light wedges widen toward the centre
+ on = np.clip(0.5 + (s + bias) / (2 * w), 0, 1)
+ fall = np.exp(-r / reach) * smoothstep(0, 60, r)
+ clip = 1.0 if bottom is None else np.clip(bottom - self.yy, 0, 1)
+ self.spray(on * fall * contrast * 2.2 * clip, colour, grain=0.45, blend='screen')
+ self.spray((1 - on) * fall * contrast * 1.4 * clip, dark, grain=0.45)
+ if glow:
+ self.glow(cx, cy, reach * 0.55, colour, strength=glow * 0.55, power=2.2, mask=clip)
+
+ def moon(self, cx, cy, r, stops=((0, '#fff8e2'), (0.55, '#f3dfa6'), (1, '#c99b4f')), halo='#f6e6b0',
+ halo_r=2.6, halo_strength=0.55, light=(-0.35, -0.4)):
+ """a full moon: disc frisket, radial fade off-centre toward the light (reads as a sphere), soft halo,
+ and two or three faint airbrushed maria"""
+ self.glow(cx, cy, r * halo_r, halo, strength=halo_strength, power=2.4)
+ m = self.disc(cx, cy, r)
+ lx, ly = cx + light[0] * r, cy + light[1] * r
+ t = np.clip(np.hypot(self.xx - lx, self.yy - ly) / (r * 1.6), 0, 1)
+ limb = smoothstep(0.75, 1.0, np.hypot(self.xx - cx, self.yy - cy) / r)
+ self.spray(m, ramp(np.clip(t * 0.85 + limb * 0.25, 0, 1), stops), grain=0.6)
+ rr = np.random.default_rng(self._seed())
+ for k in range(5): # maria: soft, low-contrast sprays
+ a, d = rr.uniform(0, 2 * np.pi), rr.uniform(0.1, 0.55) * r
+ mx, my, mr = cx + np.cos(a) * d, cy + np.sin(a) * d, rr.uniform(0.2, 0.36) * r
+ blob = np.clip(1 - np.hypot(self.xx - mx, (self.yy - my) * 1.25) / mr, 0, 1)
+ self.spray(m * smoothstep(0, 1, blob) * 0.13, '#c49a5a', grain=0.25)
+
+ def searchlight(self, x, y, angle, length, spread=2.2, colour='#d9f0e4', strength=0.32):
+ """a searchlight beam: wedge from (x, y) at `angle`, half-angle `spread`, fading along its length"""
+ a = np.radians(angle)
+ ux, uy = np.cos(a), -np.sin(a)
+ dx, dy = self.xx - x, self.yy - y
+ along = dx * ux + dy * uy
+ across = np.abs(-dx * uy + dy * ux)
+ half = np.tan(np.radians(spread)) * np.maximum(along, 0) + 2.5
+ edge = np.clip(half - across + 0.5, 0, 1) * (along > 0)
+ core = np.clip(1 - across / (half + 1e-3), 0, 1) ** 0.6
+ fall = np.clip(1 - along / length, 0, 1) ** 1.3
+ self.spray(edge * (0.55 + 0.45 * core) * fall * strength, colour, grain=1.2, blend='screen')
+
+ # ------------------------------------------------------------ city
+ def tower(self, x, base, tiers, body=('#0b1a33', '#183554', '#2f5c78'), rim='#e2be6a', light=1,
+ flutes=0, windows=0.0, slits=0, win=WARM, far=0.0, haze='#4f8f8c', spire=0, spire_w=None,
+ ledge=3.0, seed=None, mast=0, top_windows=True):
+ """a stepped skyscraper in elevation. tiers = [(width, height), ...] bottom -> top, centred on x.
+ Each tier is a frisket sprayed as a slightly round face (shadow side -> lit side, `light` = +1 lit from the
+ right), with `flutes` vertical pilasters, a rim of light on each ledge, lit windows (`windows` = share
+ of windows lit) or `slits` continuous lit strips. far 0..1 mixes everything toward the haze colour.
+ Returns the top centre (x, y) of the top tier."""
+ rr = np.random.default_rng(self._seed() if seed is None else seed)
+ hz = _c(haze)
+ cols = [(1 - far) * _c(c) + far * hz for c in body]
+ rimc = (1 - far * 0.8) * _c(rim) + far * 0.8 * hz
+ winc = (1 - far * 0.6) * _c(win) + far * 0.6 * hz
+ y = float(base)
+ for i, (w, h) in enumerate(tiers):
+ x0, x1, y0, y1 = x - w / 2, x + w / 2, y - h, y
+ m = self.rect(x0, y0, x1, y1)
+ u = np.clip((self.xx - x0) / max(w, 1), 0, 1)
+ if light < 0: u = 1 - u
+ sh = 0.12 + 0.88 * u ** 1.4 # round face: dark side -> lit side
+ if flutes:
+ fu = (u * flutes) % 1.0
+ sh = sh * (0.84 + 0.16 * np.clip(fu * 1.6, 0, 1)) + 0.05 * smoothstep(0.75, 1.0, fu)
+ sh = sh * (0.9 + 0.1 * np.clip((self.yy - y0) / max(h, 1), 0, 1)) # city glow from below
+ st = [(0, cols[0]), (0.55, cols[1]), (1, cols[2])]
+ self.spray(m, ramp(np.clip(sh, 0, 1), st), grain=0.8)
+ # windows
+ lit_here = top_windows or i < len(tiers) - 1
+ if windows > 0 and w > 18 and lit_here:
+ cw = max(6.0, w / max(3, int(w / 13)))
+ rh = cw * 1.25
+ nx, ny = int(w / cw), int((h - rh * 0.6) / rh)
+ ox = x0 + (w - nx * cw) / 2
+ lit = np.zeros((self.H, self.W), np.float32)
+ for jx in range(nx):
+ for jy in range(ny):
+ if rr.random() > windows: continue
+ wx0 = ox + jx * cw + cw * 0.3
+ wy0 = y0 + rh * 0.5 + jy * rh
+ a = rr.uniform(0.55, 1.0)
+ lit += self.rect(wx0, wy0, wx0 + cw * 0.42, wy0 + rh * 0.42) * a
+ self.spray(np.clip(lit, 0, 1) * m, winc, grain=0.5)
+ if slits and w > 18 and lit_here:
+ for k in range(slits):
+ sx = x0 + w * (k + 0.5) / slits
+ sm = self.rect(sx - 1.6, y0 + h * 0.08, sx + 1.6, y1 - h * 0.06)
+ gy = np.clip((self.yy - y0) / max(h, 1), 0, 1)
+ self.spray(sm * (0.35 + 0.65 * gy) * rr.uniform(0.6, 1.0), winc, grain=0.6)
+ # ledge catching the light (top surface of the set-back)
+ if ledge:
+ lm = self.rect(x0, y0, x1, y0 + ledge) * (0.45 + 0.55 * u)
+ self.spray(lm * (1 - far * 0.6), rimc, grain=0.6)
+ y = y0
+ top = (x, y)
+ if spire:
+ sw = spire_w or tiers[-1][0] * 0.28
+ m = self.poly([(x - sw / 2, y + 1), (x + sw / 2, y + 1), (x, y - spire)])
+ u = np.clip((self.xx - (x - sw / 2)) / sw, 0, 1)
+ if light < 0: u = 1 - u
+ st = [(0, cols[0]), (0.5, cols[2]), (1, rimc)]
+ self.spray(m, ramp(u ** 1.2, st), grain=0.8)
+ top = (x, y - spire)
+ if mast:
+ self.spray(self.rect(x - 1.2, top[1] - mast, x + 1.2, top[1] + 2), cols[2], grain=0)
+ self.glow(x, top[1] - mast, 9, '#ff5a4a', strength=0.9, power=1.5)
+ self.spray(self.disc(x, top[1] - mast, 2.2), '#ff8a70', grain=0)
+ return top
+
+ def crown(self, x, y, w, steps=3, body=('#0b1a33', '#183554', '#2f5c78'), rim='#e2be6a', win=WARM, light=1,
+ far=0.0, haze='#4f8f8c'):
+ """stepped fan crown: `steps` nested half-discs rising from y, each with radial lit slits (sunburst
+ windows) and a rim of light. Returns the apex y."""
+ hz = _c(haze)
+ cols = [(1 - far) * _c(c) + far * hz for c in body]
+ rimc = (1 - far * 0.8) * _c(rim) + far * 0.8 * hz
+ r0 = w / 2
+ for k in range(steps):
+ r = r0 * (1 - k / (steps + 0.6))
+ cy = y - k * r0 * 0.34
+ m = self.disc(x, cy, r) * (self.yy <= cy)
+ u = np.clip((self.xx - (x - r)) / (2 * r), 0, 1)
+ if light < 0: u = 1 - u
+ self.spray(m, ramp(0.15 + 0.85 * u ** 1.3, [(0, cols[0]), (0.55, cols[1]), (1, cols[2])]), grain=0.8)
+ ring = np.clip(r - np.hypot(self.xx - x, self.yy - cy), 0, 1) * np.clip(np.hypot(self.xx - x, self.yy - cy) - (r - 3.0), 0, 1)
+ self.spray(ring * (self.yy <= cy) * (0.4 + 0.6 * u), rimc, grain=0.5)
+ th = np.arctan2(-(self.yy - cy), self.xx - x)
+ n = 9 + 2 * k
+ sl = np.clip(0.5 + (np.cos(th * n * 2) - 0.72) * r / 6, 0, 1)
+ rad = np.hypot(self.xx - x, self.yy - cy)
+ band = ((rad > r * 0.55) & (rad < r * 0.86)).astype(np.float32)
+ self.spray(m * sl * band * (1 - far * 0.5) * 0.9, (1 - far * 0.5) * _c(win) + far * 0.5 * hz, grain=0.6)
+ return y - (steps - 1) * r0 * 0.34 - r0 * (1 - (steps - 1) / (steps + 0.6))
+
+ def clock(self, cx, cy, r, hour, minute, face='#f3e2b3', hands='#1a1f2e', rim=GOLD):
+ """a tower clock: gilt rim, ivory face sprayed as a shallow dome, twelve bar markers, two hands"""
+ self.glow(cx, cy, r * 2.2, '#f6deb0', strength=0.35, power=2)
+ self.spray(self.disc(cx, cy, r + max(2, r * 0.12)), rim, grain=0.4)
+ t = np.clip(np.hypot(self.xx - cx + r * 0.3, self.yy - cy + r * 0.3) / (r * 1.8), 0, 1)
+ self.spray(self.disc(cx, cy, r), ramp(t, [(0, '#fffaf0'), (1, '#d9c08a')]), grain=0.4)
+ hc = _c(hands)
+ for k in range(12):
+ a = np.radians(90 - k * 30)
+ p0 = (cx + np.cos(a) * r * 0.72, cy - np.sin(a) * r * 0.72)
+ p1 = (cx + np.cos(a) * r * 0.9, cy - np.sin(a) * r * 0.9)
+ self.spray(self._bar(p0, p1, r * (0.09 if k % 3 == 0 else 0.05)), hc, grain=0)
+ am = np.radians(90 - minute * 6)
+ ah = np.radians(90 - (hour % 12 + minute / 60) * 30)
+ self.spray(self._bar((cx, cy), (cx + np.cos(ah) * r * 0.5, cy - np.sin(ah) * r * 0.5), r * 0.1), hc, grain=0)
+ self.spray(self._bar((cx, cy), (cx + np.cos(am) * r * 0.8, cy - np.sin(am) * r * 0.8), r * 0.065), hc, grain=0)
+ self.spray(self.disc(cx, cy, r * 0.09), rim, grain=0)
+
+ def _bar(self, p0, p1, w):
+ dx, dy = p1[0] - p0[0], p1[1] - p0[1]
+ L = np.hypot(dx, dy) + 1e-6
+ nx, ny = -dy / L * w / 2, dx / L * w / 2
+ return self.poly([(p0[0] + nx, p0[1] + ny), (p1[0] + nx, p1[1] + ny), (p1[0] - nx, p1[1] - ny), (p0[0] - nx, p0[1] - ny)])
+
+ # ------------------------------------------------------------ river
+ def water(self, horizon, stops=((0, '#1d4a5a'), (1, '#060d22')), reflect=0.6, dash=(70, 2.2), seed=None):
+ """the river: sprayed fade from the horizon down, then the scene above the horizon mirrored into it,
+ broken into horizontal ripple dashes (longer and sparser toward the viewer)"""
+ H, W = self.H, self.W
+ h = int(horizon)
+ rows = np.arange(h, H)
+ rho = (rows - h).astype(np.float32)
+ src = np.clip(h - 1 - rho * 1.0, 0, h - 1).astype(int)
+ mir = self.img[src] # (rows, W, 3)
+ rr = np.random.default_rng(self._seed() if seed is None else seed)
+ # horizontal ripple displacement per row, growing toward the viewer
+ amp = 1.5 + rho * 0.035
+ off = (np.sin(rho * 0.9 + rr.uniform(0, 6)) * 0.6 + rr.standard_normal(len(rows)) * 0.7) * amp
+ xs = np.clip((np.arange(W)[None, :] + off[:, None]).astype(int), 0, W - 1)
+ mir = np.take_along_axis(mir, xs[..., None].repeat(3, 2), axis=1)
+ # ripple dashes: elongated noise, threshold rising toward the viewer
+ brk = self._ripples(len(rows), W, 0.42)
+ wt = np.clip(1 - rho / (H - h) * 0.5, 0, 1)[:, None]
+ base = ramp((rho / max(1, H - h))[:, None].repeat(W, 1), stops)
+ lum = mir @ np.float32([0.3, 0.55, 0.15])
+ boost = 0.45 + 1.3 * smoothstep(0.35, 0.85, lum)
+ out = base + (mir - base * 0.6) * (reflect * brk * wt * boost)[..., None] * 0.9
+ mask = np.zeros((H, W), np.float32)
+ mask[h:] = 1
+ full = self.img.copy()
+ full[h:] = out
+ self.spray(mask, full, grain=0.7)
+ self.horizon = h
+
+ def _ripples(self, n_rows, W, level):
+ """0..1 mask of horizontal ripple dashes for n_rows of river below the horizon: thin and dense at the
+ horizon, longer, thicker and sparser toward the viewer"""
+ rho = np.arange(n_rows, dtype=np.float32)
+ # rows grow with perspective: index the noise by a compressed depth coordinate
+ depth = np.sqrt(rho + 4.0) * 9.0
+ nr = int(depth[-1]) + 2
+ z = noise2d(nr, W // 90 + 2, 2.5, 2, self._seed())
+ z = np.asarray(Image.fromarray(z).resize((W, nr), Image.BICUBIC), np.float32)
+ lo = np.floor(depth).astype(int); fr = (depth - lo)[:, None]
+ zz = z[lo] * (1 - fr) + z[np.minimum(lo + 1, nr - 1)] * fr
+ thr = level + 0.12 * (rho / max(1, n_rows))[:, None]
+ return smoothstep(thr - 0.04, thr + 0.04, zz).astype(np.float32)
+
+ # ------------------------------------------------------------ 3D: camera and the streamliner on its viaduct
+ def camera(self, f=1500.0, cx=None, horizon=None, height=12.5):
+ """pin-hole camera at (0, height, 0) looking along +Z, level (the horizon is the row `horizon`)"""
+ self.cam = dict(f=float(f), cx=float(self.W / 2 if cx is None else cx),
+ cy=float(self.H / 2 if horizon is None else horizon), h=float(height))
+
+ def project(self, X, Y, Z):
+ c = self.cam
+ return c['cx'] + c['f'] * X / Z, c['cy'] - c['f'] * (Y - c['h']) / Z
+
+ def express(self, nose=(-7.4, 21.0), vp_x=1450, deck=10.0, cars=9, loco=19.0, car=23.0, gap=1.1,
+ nose_len=3.6, rake=2.2, light=(-0.55, 0.62, -0.56), moon=None, top=None, edge_ss=3, max_steps=150):
+ """render the streamlined train on an arched viaduct over the river. nose = (X, Z) of the locomotive's
+ nose tip on the rails (deck height `deck` above the water); the track runs away toward the vanishing
+ point at column vp_x on the horizon. Returns a _Render with alpha/base/shade/emit layers."""
+ c = self.cam
+ f, cx, cy = c['f'], c['cx'], c['cy']
+ d = np.array([(vp_x - cx) / f, 0, 1], np.float32)
+ d /= np.linalg.norm(d)
+ s = np.array([d[2], 0, -d[0]], np.float32) # lateral axis, toward the camera side
+ N = np.array([nose[0], deck, nose[1]], np.float32)
+ P = dict(d=d, s=s, N=N, deck=deck, cars=cars, loco=loco, car=car, gap=gap, Ln=nose_len,
+ bw=1.55, yb=0.75, yt=2.6, ycut=0.45, yk=1.32, rake=rake)
+ P['end'] = loco + gap + cars * (car + gap)
+ self._P = P
+ P['tip'] = -nose_len * 4 # provisional, for the livery mapping
+
+ def surface_a(h):
+ # where the nose surface crosses height h on the centre line
+ lo, hi = -nose_len * 4 - 10, rake + 1.0
+ for _ in range(48):
+ mid = (lo + hi) / 2
+ dd = self._sd_train(np.float32([mid]), np.float32([0.0]), np.float32([h]))[0][0]
+ lo, hi = (mid, hi) if dd > 0 else (lo, mid)
+ return hi
+ P['tip'] = surface_a(1.6)
+ # headlamp: on the nose surface at height 2.35 on the centre line, set just inside it
+ P['lamp'] = np.float32([surface_a(2.35) + 0.2, 0.0, 2.35])
+ L = np.array(light, np.float32); L /= np.linalg.norm(L)
+ if moon is None:
+ M = np.array([0.35, 0.45, 0.82], np.float32)
+ else:
+ M = np.array([(moon[0] - cx) / f, -(moon[1] - cy) / f, 1], np.float32)
+ M /= np.linalg.norm(M)
+ P['L'], P['M'] = L, M
+ # which rows can contain geometry: everything from just above the locomotive roof down
+ y_top = int(max(0, (top if top is not None else self.project(N[0], deck + 4.6, N[2])[1] - 30)))
+ H, W = self.H, self.W
+ ys, xs = np.mgrid[y_top:H, 0:W]
+ xs = xs.ravel().astype(np.float32) + 0.5
+ ys = ys.ravel().astype(np.float32) + 0.5
+ col, alpha, emit, depth, mat = self._shade_px(xs, ys, max_steps)
+ # supersample only where the 1x result has an edge
+ hh = H - y_top
+ colg = col.reshape(hh, W, 3)
+ ag = alpha.reshape(hh, W)
+ lum = colg @ np.float32([0.3, 0.5, 0.2]) * ag + emit.reshape(hh, W, 3).sum(-1) * 0.3
+ e = np.zeros((hh, W), bool)
+ gx = np.abs(np.diff(lum, axis=1)) > 0.035
+ gy = np.abs(np.diff(lum, axis=0)) > 0.035
+ e[:, 1:] |= gx; e[:, :-1] |= gx; e[1:] |= gy; e[:-1] |= gy
+ ax = np.abs(np.diff(ag, axis=1)) > 0.01
+ ay = np.abs(np.diff(ag, axis=0)) > 0.01
+ e[:, 1:] |= ax; e[:, :-1] |= ax; e[1:] |= ay; e[:-1] |= ay
+ ei = np.flatnonzero(e.ravel())
+ if edge_ss > 1 and ei.size:
+ k = edge_ss
+ offs = [((i + 0.5) / k - 0.5, (j + 0.5) / k - 0.5) for i in range(k) for j in range(k)]
+ acc_c = np.zeros((ei.size, 3), np.float32); acc_a = np.zeros(ei.size, np.float32)
+ acc_e = np.zeros((ei.size, 3), np.float32)
+ for ox, oy in offs:
+ c2, a2, e2, _, _ = self._shade_px(xs[ei] + ox, ys[ei] + oy, max_steps)
+ acc_c += c2 * a2[:, None]; acc_a += a2; acc_e += e2
+ n = len(offs)
+ alpha[ei] = acc_a / n
+ col[ei] = acc_c / np.maximum(acc_a, 1e-4)[:, None]
+ emit[ei] = acc_e / n
+ R = _Render()
+ R.y_top = y_top
+
+ def full(a, ch_=None):
+ if ch_:
+ out = np.zeros((H, W, ch_), np.float32); out[y_top:] = a.reshape(hh, W, ch_)
+ else:
+ out = np.zeros((H, W), np.float32); out[y_top:] = a.reshape(hh, W)
+ return out
+ R.alpha = full(alpha)
+ R.shade = full(col, 3)
+ R.emit = full(emit, 3)
+ R.depth = full(np.where(mat > 0, depth, 1e9).astype(np.float32))
+ R.mat = full(mat.astype(np.float32))
+ R.base = self._base_colours(R.mat)
+ R.under = None
+ return R
+
+ # ---- the scene as signed distances (local frame: a = metres behind the nose, v = lateral, y = above rails)
+ def _local(self, x, y, z):
+ P = self._P
+ qx, qz = x - P['N'][0], z - P['N'][2]
+ a = qx * P['d'][0] + qz * P['d'][2]
+ v = qx * P['s'][0] + qz * P['s'][2]
+ return a, v, y - P['deck']
+
+ def _sd_train(self, a, v, y):
+ """distance to the train + texture coordinates. The body is a flat *core* in the vertical plane v = 0
+ -- in the (a, y) plane a strip yb..yt running back from a raked front edge -- dilated by R = half the body
+ width and cut flat at the bottom: straight sides, a round roof, a raked prow. In front of the core's
+ front edge the a axis is stretched by nose_len / R, which turns the round prow into a long bullet nose
+ (stretching only under-estimates distance, so the sphere tracer stays safe). Livery coordinate ys: on
+ the nose the heights are squeezed toward yk, so the stripes converge on the prow."""
+ P = self._P
+ Ln, R, yb, yt, ycut, yk, rake = P['Ln'], P['bw'], P['yb'], P['yt'], P['ycut'], P['yk'], P['rake']
+ m = rake / (yt - yb)
+ a1 = rake
+ yc_ = np.clip(y, yb, yt)
+ front = m * (yc_ - yb)
+ e = a - front
+ a_s = front + np.where(e < 0, e * (R / Ln), e)
+ # distance in the (a, y) plane to the core: bottom ray, top ray, raked front edge
+ d_bot = np.where(a_s >= 0, np.abs(y - yb), np.hypot(a_s, y - yb))
+ d_top = np.where(a_s >= a1, np.abs(y - yt), np.hypot(a_s - a1, y - yt))
+ L2 = a1 * a1 + (yt - yb) ** 2
+ tt = np.clip((a_s * a1 + (y - yb) * (yt - yb)) / L2, 0, 1)
+ d_fr = np.hypot(a_s - tt * a1, y - yb - tt * (yt - yb))
+ inside = (y >= yb) & (y <= yt) & (a_s >= front)
+ dC = np.where(inside, 0.0, np.minimum(np.minimum(d_bot, d_top), d_fr))
+ d_loco = np.maximum(np.sqrt(v * v + dC * dC) - R, np.maximum(ycut - y, a - P['loco']))
+ dy = y - yc_
+ sec = np.sqrt(v * v + dy * dy) - R
+ a0 = a - P['loco'] - P['gap']
+ k = np.clip(np.round((a0 - P['car'] / 2) / (P['car'] + P['gap'])), 0, P['cars'] - 1)
+ w = a0 - k * (P['car'] + P['gap'])
+ du = np.abs(w - P['car'] / 2) - P['car'] / 2
+ d_car = np.maximum(_ext(sec + 0.18, du + 0.18) - 0.18, ycut - y)
+ dyd = y - np.clip(y, yb + 0.1, yt - 0.1)
+ d_dia = np.maximum(np.sqrt(v * v + dyd * dyd) - R * 0.9,
+ np.maximum(ycut + 0.05 - y, np.maximum(P['loco'] - 0.5 - a, a - P['end'])))
+ d = np.minimum(np.minimum(d_loco, d_car), d_dia)
+ an = np.clip((a1 + 1.0 - a) / (a1 + 1.0 - P['tip']), 0, 1) # 0 behind the nose .. 1 at the tip
+ sc = np.sqrt(np.clip(1 - an ** 2, 0.0025, 1))
+ ys = yk + (y - yk) / sc
+ return d, v, ys, k, w
+
+ def _sd_viaduct(self, a, v, y):
+ P = self._P
+ dk = P['deck']
+ deck = _rbox2(v, y + 0.7, 3.95, 0.55, 0.05) # slab y -1.25 .. -0.15
+ par = _rbox2(np.abs(v) - 3.62, y - 0.03, 0.3, 0.23, 0.04) # low parapets
+ wall_v = np.abs(v) - 3.3
+ wall_y = np.maximum(y + 1.2, -dk - 1 - y) # from below the water up to under the deck
+ wall = np.maximum(wall_v, wall_y)
+ Pp, R = 15.0, 5.3
+ am = np.mod(a, Pp) - Pp / 2
+ yac = -2.7 - R
+ circ = np.hypot(am, y - yac) - R
+ qx, qy = np.abs(am) - R, y - yac
+ rect = np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) + np.minimum(np.maximum(qx, qy), 0)
+ hole = np.minimum(circ, rect)
+ wall = np.maximum(wall, -hole)
+ ap = np.mod(a + Pp / 2, Pp) - Pp / 2 # pilasters between the arches + plinths
+ p1 = np.maximum(np.maximum(np.abs(ap) - 1.25, np.abs(v) - 3.62), np.maximum(y + 1.25, -dk - 1 - y))
+ p2 = np.maximum(np.maximum(np.abs(ap) - 1.75, np.abs(v) - 3.85), np.maximum(y + dk - 1.6, -dk - 1 - y))
+ pier = np.minimum(p1, p2)
+ rails = _rbox2(np.abs(v) - 0.72, y + 0.08, 0.05, 0.08, 0.0)
+ via = np.minimum(np.minimum(deck, par), np.minimum(wall, pier))
+ return via, rails
+
+ def _sd_lamp(self, a, v, y):
+ lp = self._P['lamp']
+ return np.sqrt((a - lp[0]) ** 2 + (v - lp[1]) ** 2 + (y - lp[2]) ** 2) - 0.3
+
+ def _sdf(self, x, y, z):
+ a, v, yl = self._local(x, y, z)
+ dt = self._sd_train(a, v, yl)[0]
+ dv, drl = self._sd_viaduct(a, v, yl)
+ return np.minimum(np.minimum(dt, self._sd_lamp(a, v, yl)), np.minimum(dv, drl))
+
+ def _shade_px(self, px, py, max_steps):
+ c = self.cam
+ f, cx, cy, ch = c['f'], c['cx'], c['cy'], c['h']
+ dx = (px - cx) / f; dy = -(py - cy) / f; dz = np.ones_like(px)
+ nl = np.sqrt(dx * dx + dy * dy + 1)
+ dx /= nl; dy /= nl; dz /= nl
+ # rays stop at the water plane (y = 0) or far away
+ tw = np.where(dy < -1e-5, ch / np.maximum(-dy, 1e-5), 3000.0).astype(np.float32)
+ tmax = np.minimum(tw, 2500.0)
+ n = px.size
+ t = np.full(n, 0.3, np.float32)
+ hit = np.zeros(n, bool)
+ alive = np.arange(n)
+ pix = 1.0 / f
+ for _ in range(max_steps):
+ if alive.size == 0: break
+ ta = t[alive]
+ d = self._sdf(dx[alive] * ta, ch + dy[alive] * ta, dz[alive] * ta)
+ h = d < ta * pix * 0.35 + 1e-4
+ hit[alive[h]] = True
+ tn = ta + d * 0.82
+ t[alive] = tn
+ keep = (~h) & (tn < tmax[alive])
+ alive = alive[keep]
+ col = np.zeros((n, 3), np.float32)
+ emit = np.zeros((n, 3), np.float32)
+ alpha = hit.astype(np.float32)
+ mat = np.zeros(n, np.int8)
+ hi = np.flatnonzero(hit)
+ if hi.size:
+ th = t[hi]
+ X, Y, Z = dx[hi] * th, ch + dy[hi] * th, dz[hi] * th
+ V = -np.stack([dx[hi], dy[hi], dz[hi]], 1)
+ cc, ee, mm = self._surface(X, Y, Z, V, th)
+ col[hi] = cc; emit[hi] = ee; mat[hi] = mm
+ return col, alpha, emit, t, mat
+
+ def _normal(self, X, Y, Z, th):
+ e = np.maximum(0.004, th * 0.0006).astype(np.float32)
+ k = ((1, -1, -1), (-1, -1, 1), (-1, 1, -1), (1, 1, 1))
+ n = np.zeros((X.size, 3), np.float32)
+ for kx, ky, kz in k:
+ dd = self._sdf(X + kx * e, Y + ky * e, Z + kz * e)
+ n[:, 0] += kx * dd; n[:, 1] += ky * dd; n[:, 2] += kz * dd
+ return n / (np.linalg.norm(n, axis=1, keepdims=True) + 1e-9)
+
+ def _surface(self, X, Y, Z, V, th):
+ P = self._P
+ n = self._normal(X, Y, Z, th)
+ a, v, y = self._local(X, Y, Z)
+ dt, vs, ys, kcar, wcar = self._sd_train(a, v, y)
+ dv, drl = self._sd_viaduct(a, v, y)
+ dl = self._sd_lamp(a, v, y)
+ ds = np.stack([dt, dl, dv, drl], 1)
+ which = np.argmin(ds, 1) # 0 train, 1 lamp, 2 viaduct, 3 rails
+ L, M = P['L'], P['M']
+ ndl = n @ L
+ ndm = n @ M
+ ndv = np.clip(np.sum(n * V, 1), 0, 1)
+ k = 0.5 + 0.5 * ndl # half-Lambert: the airbrush modelling term
+ Hh = L[None, :] + V
+ Hh /= np.linalg.norm(Hh, axis=1, keepdims=True)
+ spec = smoothstep(0.90, 0.985, np.sum(n * Hh, 1))
+ rim = (1 - ndv) ** 2.2 * np.clip(ndm + 0.25, 0, 1)
+ bounce = np.clip(-n[:, 1], 0, 1)
+ col = np.zeros((X.size, 3), np.float32)
+ emit = np.zeros((X.size, 3), np.float32)
+ mat = np.zeros(X.size, np.int8)
+ # ---- train
+ it = which == 0
+ if it.any():
+ ktr = k[it]; yy = ys[it]; aa = a[it]
+ side = np.abs(n[it] @ P['s']) > 0.55
+ t = np.clip(0.08 + 0.92 * ktr ** 1.25, 0, 1)
+ body = ramp(t, [(0, '#16070d'), (0.35, '#4a101d'), (0.62, '#8b2030'), (0.84, '#c4473f'), (1, '#f1a172')])
+ skirt = ramp(t, [(0, '#07090f'), (0.5, '#1d2232'), (0.85, '#4b5368'), (1, '#8a93a6')])
+ gold = ramp(t, [(0, '#2a1a08'), (0.4, '#7b5519'), (0.7, '#cf9f45'), (0.9, '#f3d58b'), (1, '#fff3cf')])
+ cream = ramp(t, [(0, '#3a2a1c'), (0.35, '#8c6f4c'), (0.62, '#d8bf93'), (0.84, '#f3e3c0'), (1, '#fff8e8')])
+ cc = body.copy()
+ is_skirt = yy < 1.0
+ cc[is_skirt] = skirt[is_skirt]
+ cap = aa < P['tip'] * 0.86 + P['rake'] * 0.14 # nose cap: plain enamel, stripes end before it
+ band = (yy > 1.95) & (yy < 3.15) & ~cap
+ cc[band] = cream[band]
+ stripe = (((yy > 1.7) & (yy < 1.84)) | ((yy > 3.26) & (yy < 3.36)) | ((yy > 1.12) & (yy < 1.2))) & ~cap
+ cc[stripe] = gold[stripe]
+ m = np.full(it.sum(), 1, np.int8)
+ m[is_skirt] = 4; m[band] = 8; m[stripe] = 5
+ # car windows (sleeping cars: some blinds drawn) and the cab glass
+ kk = kcar[it]; ww = wcar[it]
+ on_car = (aa > P['loco'] + P['gap']) & (aa < P['end'])
+ wpos = (ww - 1.6) / 2.05
+ wi = np.floor(wpos)
+ wf = wpos - wi
+ in_win = on_car & side & (ww > 1.6) & (ww < P['car'] - 1.6) & (wf > 0.16) & (wf < 0.84) & (yy > 2.05) & (yy < 3.05)
+ hsh = np.mod(np.sin(kk * 12.9898 + wi * 78.233) * 43758.5453, 1.0)
+ blind = 2.05 + np.where(hsh < 0.3, 0.55, np.where(hsh < 0.45, 0.9, 1.0)) * 1.0
+ dark = hsh > 0.86
+ lit = in_win & ~dark
+ glass = ramp(t, [(0, '#05070d'), (0.6, '#14203a'), (1, '#3a5578')])
+ cc[in_win] = glass[in_win]
+ ev = np.zeros((it.sum(), 3), np.float32)
+ gy = np.clip((yy - 2.05) / 1.0, 0, 1)
+ warm = ramp(gy, [(0, '#fff0b8'), (1, '#f7b553')])
+ blinded = lit & (yy > blind)
+ ev[lit] = warm[lit] * 1.05
+ ev[blinded] = _c('#d9802f') * 0.62
+ m[in_win] = 6
+ # cab: a rounded side window in the cream band just behind the nose, glass reflecting the sky
+ cu = (aa - 1.55) / 1.05; cv = (yy - 2.6) / 0.36
+ cab = side & (np.abs(cu) ** 3 + np.abs(cv) ** 3 < 1)
+ sky = ramp(np.clip(0.5 - cv * 0.5, 0, 1), [(0, '#08101e'), (0.55, '#1c3d50'), (1, '#6aa9a2')])
+ cc[cab] = sky[cab]
+ ev[cab] = _c('#ffcf7a') * 0.08
+ m[cab] = 6
+ # lamp bezel (chrome ring round the headlamp)
+ lp = P['lamp']
+ rl = np.sqrt((aa - lp[0]) ** 2 + (v[it] - lp[1]) ** 2 + (y[it] - lp[2]) ** 2)
+ bez = rl < 0.47
+ chrome = ramp(t, [(0, '#1a1d26'), (0.5, '#6f7787'), (0.85, '#d9dde3'), (1, '#ffffff')])
+ cc[bez] = chrome[bez]
+ ny = n[it, 1]
+ streak = np.exp(-((ny - 0.62) / 0.09) ** 2) * 0.55 + np.exp(-((ny + 0.42) / 0.07) ** 2) * 0.12
+ cc = cc + streak[:, None] * np.where(m[:, None] == 8, _c('#fff3dc') * 0.35, _c('#ffb08a') * 0.6) * (1 - is_skirt[:, None] * 0.6)
+ sp = spec[it][:, None]
+ spcol = np.where(m[:, None] == 5, _c('#fff6dc'), _c('#ffd9b8'))
+ cc = cc + sp * spcol * np.where(m[:, None] == 6, 0.7, 0.55)
+ cc = cc + rim[it][:, None] * _c('#8fd0c8') * 0.55
+ cc = cc + bounce[it][:, None] * _c('#2b6a74') * 0.22
+ col[it] = cc; emit[it] = ev; mat[it] = m
+ il = which == 1
+ if il.any():
+ col[il] = _c('#fffbe8')
+ emit[il] = _c('#fff4cf') * 0.85
+ mat[il] = 7
+ # the headlamp lights the deck and rails ahead of the train (a cone along -a, tipped slightly down)
+ lp = P['lamp']
+ qa, qv, qy = a - lp[0], v - lp[1], y - lp[2]
+ ql = np.sqrt(qa * qa + qv * qv + qy * qy) + 1e-4
+ ax_ = np.float32([-0.995, 0.0, -0.1]); ax_ /= np.linalg.norm(ax_)
+ cosang = (qa * ax_[0] + qv * ax_[1] + qy * ax_[2]) / ql
+ nl_a, nl_v = n @ P['d'], n @ P['s']
+ lam = np.clip(-(nl_a * qa + nl_v * qv + n[:, 1] * qy) / ql, 0, 1)
+ spill = smoothstep(np.cos(np.radians(15)), np.cos(np.radians(4)), cosang) * np.clip(lam * 5, 0, 1) * \
+ np.clip(1 - ql / 70, 0, 1) ** 1.2
+ iv = which == 2
+ if iv.any():
+ t = np.clip(0.06 + 0.94 * k[iv] ** 1.1, 0, 1)
+ cc = ramp(t, [(0, '#050b18'), (0.45, '#11243a'), (0.75, '#24465c'), (1, '#4f7d86')])
+ up = np.clip(n[iv, 1], 0, 1)
+ cc = cc + up[:, None] * _c('#2c5560') * 0.25 + rim[iv][:, None] * _c('#6fb8b0') * 0.35
+ cc = cc + spill[iv][:, None] * _c('#d9b06a') * 0.55
+ col[iv] = cc; mat[iv] = 2
+ ir = which == 3
+ if ir.any():
+ col[ir] = ramp(np.clip(k[ir] + spec[ir], 0, 1), [(0, '#0b0e16'), (0.6, '#5a6274'), (1, '#e9eef2')])
+ col[ir] += spill[ir][:, None] * _c('#ffe2a8') * 1.1
+ mat[ir] = 3
+ # air between us and far objects: fade toward the glow of the city at the horizon
+ fog = (1 - np.exp(-th / 260.0)) ** 1.2
+ fogc = _c('#3f7d82')
+ col = col * (1 - fog[:, None] * 0.85) + fogc * fog[:, None] * 0.85
+ emit = emit * (1 - fog[:, None] * 0.45)
+ return col, emit, mat
+
+ def _base_colours(self, mat):
+ """flat base coat per material (what the first spray through each frisket looks like)"""
+ out = np.zeros(mat.shape + (3,), np.float32)
+ for m, cc in ((1, '#7a1c2b'), (2, '#1c3449'), (3, '#4a5262'), (4, '#2a2f3d'), (5, '#b88a3c'),
+ (6, '#141d30'), (7, '#e8dcc0'), (8, '#cdb58a')):
+ out[mat == m] = _c(cc)
+ return out
+
+ def frisket(self, R):
+ """first pass: every machine shape cut and sprayed flat in its base colour"""
+ R.under = self.img.copy()
+ self.img = R.under * (1 - R.alpha[..., None]) + R.base * R.alpha[..., None]
+
+ def model(self, R):
+ """second pass: form shading (ramps, highlight streaks, rim and reflected light)"""
+ if R.under is None: R.under = self.img.copy()
+ sh = R.shade.copy()
+ sh = np.clip(sh + self.speck[..., None] * 0.006, 0, 1.2)
+ self.img = R.under * (1 - R.alpha[..., None]) + sh * R.alpha[..., None]
+
+ def lights(self, R, beam=True, beam_len=900, bloom=1.0, reflect=True):
+ """third pass: lit windows and headlamp, headlamp beam, bloom, the lights' reflections in the river"""
+ e = R.emit
+ lum = e.max(-1)
+ self.img = self.img * (1 - np.clip(lum, 0, 1)[..., None]) + e
+ P = self._P
+ lp = P['lamp']
+ # lamp in world coordinates
+ wpos = P['N'] + P['d'] * lp[0] + P['s'] * lp[1] + np.array([0, lp[2], 0], np.float32)
+ lx, ly = self.project(*wpos)
+ if beam:
+ tip = wpos - P['d'] * min(60.0, 0.6 * wpos[2] / P['d'][2])
+ bx, by = self.project(*tip)
+ ang = np.degrees(np.arctan2(-(by - ly), bx - lx))
+ self.searchlight(lx, ly, ang, beam_len, spread=8.5, colour='#fff1c8', strength=0.42)
+ self.searchlight(lx, ly, ang, beam_len * 0.7, spread=3.6, colour='#fff6dc', strength=0.4)
+ if bloom:
+ g = blur(lum, 3) * 0.6 + blur(lum, 14) * 0.5 + blur(lum, 40) * 0.35
+ self.spray(np.clip(g * bloom, 0, 1), '#ffd58a', grain=0.4, blend='screen')
+ self.glow(lx, ly, 80, '#fff3d0', strength=0.45, power=2.6)
+ self.glow(lx, ly, 10, '#ffffff', strength=0.8, power=1.4)
+ # four-point glint on the lamp
+ for ang in (0, 90):
+ aa = np.radians(ang)
+ ux, uy = np.cos(aa), np.sin(aa)
+ dx, dy = self.xx - lx, self.yy - ly
+ al = np.abs(dx * ux + dy * uy); ac = np.abs(-dx * uy + dy * ux)
+ self.spray(np.clip(1 - al / 110, 0, 1) ** 2 * np.clip(1 - ac / 1.6, 0, 1), '#fff6e0', grain=0, blend='screen')
+ if reflect and hasattr(self, 'horizon'):
+ # the lit windows mirrored in the river: mirror each emissive hit point under the water plane
+ c = self.cam
+ ys_, xs_ = np.nonzero(lum > 0.25)
+ if ys_.size:
+ dx = (xs_ + 0.5 - c['cx']) / c['f']; dy = -(ys_ + 0.5 - c['cy']) / c['f']
+ t = R.depth[ys_, xs_]
+ nl = np.sqrt(dx * dx + dy * dy + 1)
+ X, Y, Z = dx / nl * t, c['h'] + dy / nl * t, t / nl
+ mx, my = self.project(X, -Y, Z)
+ ok = (mx >= 0) & (mx < self.W) & (my >= self.horizon) & (my < self.H)
+ mxi, myi = mx[ok].astype(int), my[ok].astype(int)
+ dist = np.sqrt(X[ok] ** 2 + (Y[ok] + c['h']) ** 2 + Z[ok] ** 2)
+ vis = R.depth[myi, mxi] > dist * 0.98
+ buf = np.zeros((self.H, self.W, 3), np.float32)
+ np.add.at(buf, (myi[vis], mxi[vis]), e[ys_[ok][vis], xs_[ok][vis]] * 0.5)
+ # stretch down into ripple streaks and break into dashes
+ k = 46
+ h0 = self.horizon
+ acc = buf[h0:].copy()
+ b = buf[h0:]
+ for j in range(1, k):
+ acc[j:] += b[:-j] * (1 - j / k) ** 1.5
+ acc = np.stack([blur(acc[..., q], 1.6) for q in range(3)], -1)
+ dash = self._ripples(self.H - h0, self.W, 0.5)
+ self.img[h0:] = self.img[h0:] + acc * dash[..., None] * (1 - R.alpha[h0:, :, None]) * 0.9
+
+ # ------------------------------------------------------------ type
+ def _glyph_mask(self, s, cap, track=0.12, ss=4):
+ """render a string in the Deco display alphabet -> (mask array, width px, ascent px)"""
+ gl = []
+ x = 0.0
+ for ch in s.upper():
+ g = _glyph(ch)
+ if g is None:
+ g = _glyph(' ')
+ gl.append((x, g))
+ x += g[0] + track
+ width = x - track
+ pad = 0.12
+ Wm = int((width + 2 * pad) * cap * ss) + 4
+ Hm = int((1 + 2 * pad) * cap * ss) + 4
+ im = Image.new('L', (Wm, Hm), 0)
+ dr = ImageDraw.Draw(im)
+ S = cap * ss
+ for x0, (wd, polys) in gl:
+ k = 0
+ while k < len(polys):
+ p = polys[k]
+ pts = [((x0 + pad + px) * S, (1 + pad - py) * S) for px, py in p]
+ # a closed full ring arrives as [outer, inner]: fill outer, cut inner
+ if k + 1 < len(polys) and len(p) == 96 and len(polys[k + 1]) == 96 and \
+ abs(p[0][0] - p[-1][0]) < 1e-6 and abs(p[0][1] - p[-1][1]) < 1e-6:
+ dr.polygon(pts, fill=255)
+ q = polys[k + 1]
+ dr.polygon([((x0 + pad + px) * S, (1 + pad - py) * S) for px, py in q], fill=0)
+ k += 2
+ continue
+ dr.polygon(pts, fill=255)
+ k += 1
+ im = im.resize((Wm // ss, Hm // ss), Image.LANCZOS)
+ return np.asarray(im, np.float32) / 255, width * cap, pad * cap
+
+ def deco_width(self, s, cap, track=0.12):
+ x = 0.0
+ for ch in s.upper():
+ g = _glyph(ch) or _glyph(' ')
+ x += g[0] + track
+ return (x - track) * cap
+
+ def lettering(self, s, x, base, cap, fill=((0, '#fff7e4'), (0.5, '#f2d79a'), (0.52, '#c9963f'), (1, '#f0cf87')),
+ track=0.12, shadow=(5, 5), shadow_colour='#050a1c', anchor='l'):
+ """Deco display letters: thick down-strokes, hairline cross-strokes, high waist. `fill` is sprayed top to
+ bottom through the letter friskets (default: a gilt fade with a hard horizon at the middle, the way
+ sign painters faked metal), `shadow` a cast block shadow (dx, dy) in a dark ink."""
+ m, wpx, pad = self._glyph_mask(s, cap, track)
+ if anchor == 'm': x = x - wpx / 2
+ elif anchor == 'r': x = x - wpx
+ ox, oy = int(round(x - pad)), int(round(base - cap - pad))
+ full = np.zeros((self.H, self.W), np.float32)
+ h, w = m.shape
+ y0, x0 = max(0, oy), max(0, ox)
+ y1, x1 = min(self.H, oy + h), min(self.W, ox + w)
+ full[y0:y1, x0:x1] = m[y0 - oy:y1 - oy, x0 - ox:x1 - ox]
+ if shadow:
+ sh = np.zeros_like(full)
+ n = int(max(abs(shadow[0]), abs(shadow[1])))
+ for j in range(1, n + 1):
+ dx, dy = int(round(shadow[0] * j / n)), int(round(shadow[1] * j / n))
+ sh = np.maximum(sh, np.roll(np.roll(full, dy, 0), dx, 1))
+ self.spray(sh * (1 - full), shadow_colour, density=0.9, grain=0.6)
+ self.fade(full, list(fill), (0, base - cap), (0, base))
+ return wpx
+
+ def caption(self, s, x, y, size, colour=IVORY, track=0.32, anchor='ls', font='geometric', alpha=1.0):
+ """wide-tracked geometric sans (Futura / system sans) for the small print"""
+ f = load_font(font, size)
+ im = Image.new('L', (self.W, self.H), 0)
+ d = ImageDraw.Draw(im)
+ adv = [f.getlength(ch) + track * size for ch in s]
+ total = sum(adv) - track * size
+ x0 = x - total * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor[0]]
+ for ch, a in zip(s, adv):
+ d.text((x0, y), ch, font=f, fill=255, anchor='l' + anchor[1])
+ x0 += a
+ m = np.asarray(im, np.float32) / 255
+ self.spray(m * alpha, colour, grain=0.3)
+ return total
+
+ def rule(self, x0, x1, y, width=2.0, colour=GOLD):
+ self.spray(self.rect(x0, y - width / 2, x1, y + width / 2), colour, grain=0.3)
+
+ def border(self, inset=26, gap=9, width=2.2, colour=GOLD, step=34):
+ """double gilt rule round the sheet with stepped (ziggurat) corners"""
+ W, H = self.W, self.H
+ m = np.zeros((H, W), np.float32)
+ for k, ins in enumerate((inset, inset + gap)):
+ st = step - k * gap * 0.0
+ x0, y0, x1, y1 = ins, ins, W - ins, H - ins
+ pts = [(x0 + st, y0), (x1 - st, y0), (x1 - st, y0 + st * 0.5), (x1 - st * 0.5, y0 + st * 0.5),
+ (x1 - st * 0.5, y0 + st), (x1, y0 + st), (x1, y1 - st), (x1 - st * 0.5, y1 - st),
+ (x1 - st * 0.5, y1 - st * 0.5), (x1 - st, y1 - st * 0.5), (x1 - st, y1), (x0 + st, y1),
+ (x0 + st, y1 - st * 0.5), (x0 + st * 0.5, y1 - st * 0.5), (x0 + st * 0.5, y1 - st), (x0, y1 - st),
+ (x0, y0 + st), (x0 + st * 0.5, y0 + st), (x0 + st * 0.5, y0 + st * 0.5), (x0 + st, y0 + st * 0.5)]
+ im = Image.new('L', (W * 2, H * 2), 0)
+ ImageDraw.Draw(im).line([(px * 2, py * 2) for px, py in pts + [pts[0]]], fill=255,
+ width=int(round(width * 2)), joint='curve')
+ m = np.maximum(m, np.asarray(im.resize((W, H), Image.LANCZOS), np.float32) / 255)
+ self.fade(m, [(0, '#f3d892'), (0.5, colour), (1, '#9c6e2c')], (0, 0), (W, H), grain=0.3)
+
+ # ------------------------------------------------------------ print
+ def finish(self, paper='#efe4cc', tooth=0.035, warm=0.04, vignette=0.12):
+ """lithographic print: paper tooth, a whisper of grain, warm cast, soft vignette"""
+ H, W = self.H, self.W
+ n = noise2d(H, W, 3, 2, self._seed()) - 0.5
+ fib = noise2d(H, W // 6 + 1, 2, 2, self._seed())
+ fib = np.asarray(Image.fromarray(fib).resize((W, H), Image.BICUBIC), np.float32) - 0.5
+ g = 1 + tooth * (n * 0.8 + fib * 0.4)
+ img = self.img * g[..., None]
+ img = img * (1 - warm) + warm * _c(paper) * (0.35 + 0.65 * img)
+ r = np.hypot((self.xx - W / 2) / (W / 2), (self.yy - H / 2) / (H / 2))
+ img = img * (1 - vignette * smoothstep(0.65, 1.45, r))[..., None]
+ self.img = img
+
+ def stage(self, name):
+ self.stages.append((name, self.composite()))
+
+ def composite(self):
+ return Image.fromarray((np.clip(self.img, 0, 1) * 255 + 0.5).astype(np.uint8))
+
+ 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
diff --git a/lib/codex.py b/lib/codex.py
new file mode 100644
index 0000000..3d344db
--- /dev/null
+++ b/lib/codex.py
@@ -0,0 +1,1091 @@
+"""codex — a Renaissance engineer's notebook page in the manner of Leonardo's codices: iron-gall ink from a quill
+on laid rag paper, left-handed hatching, red chalk, stylus and compass construction, exploded machine parts and
+mirror writing (numpy + Pillow only).
+
+Model:
+ sheet laid rag paper on a museum mount. The ground is a warm buff with fibre mottling, the faint wire marks
+ of the paper mould (fine horizontal laid lines, wavy vertical chain lines every ~170 px), and a
+ `tooth` field that red chalk catches on. Time is baked into the sheet: browned and slightly ragged
+ edges, one lost corner, large soft clouds where the sizing yellowed unevenly, rust-coloured foxing
+ specks (crisp cores, small clusters), a water stain whose tide line is darker than its inside, an
+ optional old vertical fold (bright on one lip, dark on the other, grimy along the crease), handling
+ grime near the lower corners, and writing from the back of the leaf showing through -- reversed, so
+ it reads left to right (`show_through`).
+ ink iron-gall ink is a density field `ink`. A quill stroke is a polyline smoothed, resampled to ~1.3 px
+ and wobbled by the hand; its width follows the broad nib (wider where the line runs across the nib's
+ edge, cut at ~35 deg), a heavier touch-down and a tapering lift-off. The pen carries a load: every px
+ drawn uses ink, so strokes grow paler until the pen is re-dipped, and a fresh dip can pool a small
+ dark bead where the next stroke starts. Composite is a multiply: thin ink is warm amber-brown, thick
+ ink dark umber, overlaps darken (crossings in hatching), a faint halo bleeds into the fibres, and the
+ paper's fibre texture breaks the ink up a little.
+ hatching Leonardo was left-handed, so his parallel hatching runs '\\' (top left to bottom right) almost
+ everywhere, whatever the form. Tone is density: a shade field (0 lit .. 1 dark) is cut into levels;
+ the first level is spaced hatching, the next interleaves between those lines, the darkest adds a
+ second direction (cross-hatching). A hand hatches in bands -- a row of parallel strokes of about one
+ length, then the next row -- so long runs are cut where staggered band edges fall, never chained
+ stroke after stroke (that reads as wavy fur). Strokes are all bowed the same way (a pivoting wrist),
+ start a little heavier and over- or undershoot the contour by a pixel or two. `between()` gives the
+ 0..1 field across a panel from one rib to the next, the usual way to make a membrane billow.
+ chalk red chalk (sanguine) deposits only where it touches the paper tooth: light pressure grazes the tops
+ of the grain, heavy pressure fills the valleys; `rub` smears it into a soft tone.
+ stylus construction lines pressed with a stylus or a compass leg have no colour: they are a height field
+ lit by raking light (the wall facing the light is bright, the other dark); compass centres leave
+ prick holes. `lead` is a faint grey leadpoint underdrawing with searching lines.
+ writing mirror writing in a chancery cursive (Apple Chancery / URW Chancery, else any script face), flipped:
+ every line starts at the right margin and is ragged on the left; letters jitter in size and
+ baseline, the baseline drifts, the pen fades and is re-dipped mid-line. `prose()` makes
+ pseudo-Italian; letters such as a, b, c label points of the drawings.
+ solids machine parts (spur gears, lantern pinions, crown wheels, cranks, axles, beams, pulleys) are small
+ meshes drawn by a pen renderer: an orthographic camera, a z-buffer, every face shaded by how far it
+ turns from the light, each surface group hatched with that tone, the ink of whatever is behind the
+ solid erased (a draughtsman simply does not draw hidden lines), and only feature edges -- silhouette,
+ creases sharper than ~30 deg, open borders -- chained into long quill strokes; hidden parts of an
+ edge are dropped by depth test. Exploded views are the same parts slid apart along a dot-dash axis.
+ objects things Leonardo drew again and again: `cane` (a rod as two converging pen lines with cord lashings,
+ returns its outline for masking), `feather` (curved rachis, narrow leading vane, broad trailing vane,
+ rounded tip; `overlapped=True` draws only what shows in a fanned wing), `bird` (a little bird seen from
+ behind at any phase of the wing-beat: bent wrist, spread primaries, body and tail).
+ accidents ink blots with a darker tide rim and satellite drops, spatter, struck-out sketches, contours searched
+ two or three times before the final line (pentimenti).
+Angles are screen degrees, clockwise (y points down): 55 is the left-hander's '\\', -40 is '/'.
+
+ from codex import Codex, Camera, gear, merge
+ c = Codex(1920, 1080, seed=3)
+ c.sheet()
+ c.compass(960, 540, 200) # blind compass circle + prick hole
+ c.quill(Codex.arc(960, 540, 200, 0, 360), width=2.2) # inked over
+ c.hatch(c.disc_mask(960, 540, 200), shade=c.radial_shade(960, 540, 200))
+ cam = Camera(1400, 700, azim=-30, elev=35)
+ c.solid(gear(80, 16, 12, 30), cam)
+ c.write(c.prose(40), x=700, y=200, width=420, size=21) # mirror-written paragraph
+ c.save('page.jpg')
+"""
+import os
+import glob
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+from core import blur, fbm1d, spline, noise2d, smoothstep, polygon_mask, blob_pts, shift, load_font
+
+INK_DARK = np.array([0.19, 0.105, 0.045], np.float32) # thick iron-gall ink, aged to umber
+INK_LIGHT = np.array([0.60, 0.40, 0.18], np.float32) # thin ink, warm amber-brown
+INK_HALO = np.array([0.80, 0.64, 0.42], np.float32) # what migrates into the fibres
+SANGUINE = '#a9482c'
+LEADPOINT = '#6a6762'
+PAPER = '#e9d7ae'
+MOUNT = '#6b5f52'
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+def _c(c):
+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)
+
+
+def _resample(P, step):
+ P = np.asarray(P, np.float32)
+ if len(P) < 2: return P
+ seg = np.hypot(*np.diff(P, axis=0).T)
+ s = np.concatenate([[0], np.cumsum(seg)])
+ if s[-1] < 1e-3: return P[:1]
+ n = max(2, int(np.ceil(s[-1] / step)) + 1)
+ ss = np.linspace(0, s[-1], n)
+ return np.stack([np.interp(ss, s, P[:, 0]), np.interp(ss, s, P[:, 1])], 1).astype(np.float32)
+
+
+# ------------------------------------------------------------------------------------------- pseudo-Italian
+_SYL = ['la', 'le', 'li', 'lo', 'ra', 're', 'ri', 'ro', 'ta', 'te', 'ti', 'to', 'na', 'ne', 'ni', 'no', 'ma', 'me',
+ 'mo', 'pa', 'pe', 'po', 'sa', 'se', 'so', 'ca', 'che', 'chi', 'co', 'da', 'de', 'di', 'do', 'va', 've', 'vo',
+ 'gli', 'gna', 'gno', 'zza', 'zzo', 'qua', 'que', 'stra', 'ssi', 'tte', 'lla', 'nte', 'nto', 'rri', 'ppo', 'ffe']
+_SMALL = ['e', 'la', 'il', 'che', 'di', 'del', 'della', 'per', 'con', 'non', 'se', 'al', 'nel', 'quando', 'come',
+ 'piu', 'sua', 'suo', 'essa', 'tal', 'ogni', 'cosi', 'ma', 'o', 'a', 'in', 'da', 'lo', 'le']
+_TERMS = ['ala', 'penna', 'moto', 'vento', 'aria', 'peso', 'leva', 'rota', 'corda', 'polo', 'perno', 'forza',
+ 'canna', 'tela', 'nodo', 'braccio', 'volo', 'batte', 'sotto', 'sopra']
+
+
+# ------------------------------------------------------------------------------------------- solids
+class Camera:
+ """orthographic camera. World: x right, y forward (away), z up. azim turns the object about z, elev tilts the
+ view down from above; `scale` px per unit; (cx, cy) is where the world origin lands on the page."""
+
+ def __init__(self, cx, cy, scale=1.0, azim=-30.0, elev=30.0):
+ self.cx, self.cy, self.s = cx, cy, scale
+ a, e = np.deg2rad(azim), np.deg2rad(elev)
+ Rz = np.array([[np.cos(a), -np.sin(a), 0], [np.sin(a), np.cos(a), 0], [0, 0, 1]], np.float32)
+ right = np.array([1, 0, 0], np.float32)
+ toward = np.array([0, -np.cos(e), np.sin(e)], np.float32) # from the scene to the eye
+ up = np.array([0, np.sin(e), np.cos(e)], np.float32)
+ self.B = np.stack([right, toward, up]) @ Rz # rows: right, toward, up in world coords
+
+ def cam(self, P):
+ return np.asarray(P, np.float32) @ self.B.T # (right, toward, up)
+
+ def project(self, P):
+ C = self.cam(P)
+ xy = np.stack([self.cx + C[:, 0] * self.s, self.cy - C[:, 2] * self.s], 1)
+ return xy.astype(np.float32), (-C[:, 1] * self.s).astype(np.float32) # depth: larger is farther
+
+
+class Mesh:
+ """vertices (N, 3), faces (lists of vertex indices, counter-clockwise seen from outside) and a surface group
+ name per face (each group is hatched as one surface)"""
+
+ def __init__(self, V=None, F=None, G=None):
+ self.V = np.zeros((0, 3), np.float32) if V is None else np.asarray(V, np.float32)
+ self.F = [] if F is None else [list(f) for f in F]
+ self.G = [] if G is None else list(G)
+
+ def place(self, origin=(0, 0, 0), axis=(0, 0, 1), spin=0.0):
+ """local z -> `axis`, then move to `origin`; spin turns the part about its own axis first (degrees)"""
+ z = np.asarray(axis, np.float32); z /= np.linalg.norm(z)
+ ref = np.array([0, 0, 1], np.float32) if abs(z[2]) < 0.9 else np.array([1, 0, 0], np.float32)
+ x = np.cross(ref, z); x /= np.linalg.norm(x); y = np.cross(z, x)
+ sp = np.deg2rad(spin)
+ Vl = self.V.copy()
+ Vl[:, 0], Vl[:, 1] = self.V[:, 0] * np.cos(sp) - self.V[:, 1] * np.sin(sp), self.V[:, 0] * np.sin(sp) + self.V[:, 1] * np.cos(sp)
+ V = Vl[:, :1] * x + Vl[:, 1:2] * y + Vl[:, 2:3] * z + np.asarray(origin, np.float32)
+ return Mesh(V, self.F, self.G)
+
+ def named(self, prefix):
+ return Mesh(self.V, self.F, [prefix + '.' + g for g in self.G])
+
+
+def merge(*meshes):
+ V, F, G, off = [], [], [], 0
+ for m in meshes:
+ V.append(m.V); F += [[i + off for i in f] for f in m.F]; G += m.G; off += len(m.V)
+ return Mesh(np.concatenate(V) if V else None, F, G)
+
+
+def extrude(outline, h, cap='cap', side='side', z0=0.0):
+ """prism: a counter-clockwise 2D outline from z0 to z0 + h"""
+ P = np.asarray(outline, np.float32)
+ M = len(P)
+ V = np.concatenate([np.c_[P, np.full(M, z0)], np.c_[P, np.full(M, z0 + h)]]).astype(np.float32)
+ F = [list(range(M - 1, -1, -1)), list(range(M, 2 * M))]
+ G = [cap + '_bottom', cap]
+ for i in range(M):
+ j = (i + 1) % M
+ F.append([i, j, M + j, M + i]); G.append(side)
+ return Mesh(V, F, G)
+
+
+def circle_outline(r, n=48):
+ t = np.linspace(0, 2 * np.pi, n, endpoint=False)
+ return np.stack([np.cos(t) * r, np.sin(t) * r], 1)
+
+
+def cylinder(r, h, n=40, cap='cap', side='side', z0=0.0):
+ return extrude(circle_outline(r, n), h, cap, side, z0)
+
+
+def box(sx, sy, sz):
+ """a beam centred on the origin"""
+ m = extrude([(-sx / 2, -sy / 2), (sx / 2, -sy / 2), (sx / 2, sy / 2), (-sx / 2, sy / 2)], sz, 'end', 'face', -sz / 2)
+ for i, f in enumerate(m.F[2:]): # name the four long faces separately: crisp creases
+ m.G[2 + i] = 'face%d' % i
+ return m
+
+
+def gear(r, teeth, depth, h, hub=None):
+ """spur gear of radius r (tip), `teeth` trapezoid teeth `depth` deep, thickness h; optional hub boss"""
+ pts = []
+ for k in range(teeth):
+ a0 = 2 * np.pi * k / teeth
+ da = 2 * np.pi / teeth
+ for f, rr in [(0.0, r - depth), (0.18, r - depth), (0.30, r), (0.62, r), (0.74, r - depth)]:
+ pts.append((np.cos(a0 + f * da) * rr, np.sin(a0 + f * da) * rr))
+ m = extrude(pts, h, 'face', 'teeth')
+ if hub:
+ m = merge(m, cylinder(hub[0], hub[1], 28, 'hub_face', 'hub', h))
+ return m
+
+
+def lantern(r, h, staves=8, stave_r=None, disc_h=None):
+ """lantern pinion: two thin discs joined by round staves (the pins the crown wheel's teeth push)"""
+ stave_r = stave_r or r * 0.09
+ disc_h = disc_h or r * 0.16
+ parts = [cylinder(r, disc_h, 44, 'disc_low', 'rim_low'), cylinder(r, disc_h, 44, 'disc', 'rim', h - disc_h)]
+ for k in range(staves):
+ a = 2 * np.pi * k / staves
+ s = cylinder(stave_r, h - 2 * disc_h, 10, 'stave_end', 'stave', disc_h)
+ s.V[:, 0] += np.cos(a) * r * 0.74; s.V[:, 1] += np.sin(a) * r * 0.74
+ parts.append(s)
+ return merge(*parts)
+
+
+def crown(r, h, teeth=16, tooth_h=None, tooth_w=None):
+ """crown wheel: a disc with square pegs standing up round its rim (meshes with a lantern pinion at 90 deg)"""
+ tooth_h = tooth_h or r * 0.22
+ tooth_w = tooth_w or r * 0.11
+ parts = [cylinder(r, h, 64, 'face', 'rim')]
+ for k in range(teeth):
+ a = 2 * np.pi * k / teeth
+ t = box(tooth_w, tooth_w, tooth_h)
+ t.V[:, 2] += h + tooth_h / 2
+ ca, sa = np.cos(a), np.sin(a)
+ x, y = t.V[:, 0].copy(), t.V[:, 1].copy()
+ t.V[:, 0] = (x + r - tooth_w * 0.75) * ca - y * sa
+ t.V[:, 1] = (x + r - tooth_w * 0.75) * sa + y * ca
+ t.G = ['peg_top' if g == 'end' else ('peg_bottom' if g == 'end_bottom' else 'peg') for g in t.G]
+ parts.append(t)
+ return merge(*parts)
+
+
+def crank(arm, r_axle, handle_len, handle_r, throw_w=None):
+ """bent crank: a flat iron arm along +x from the axle end (z=0), a round wooden handle standing at its tip"""
+ throw_w = throw_w or r_axle * 1.6
+ a = box(arm + throw_w, throw_w, throw_w * 0.6)
+ a.V[:, 0] += arm / 2
+ a.G = ['arm_' + g for g in a.G]
+ boss = cylinder(r_axle * 1.9, throw_w * 1.1, 20, 'boss_end', 'boss', -throw_w * 1.1) # socket for the shaft
+ hnd = cylinder(handle_r, handle_len, 18, 'handle_end', 'handle', throw_w * 0.3)
+ hnd.V[:, 0] += arm
+ return merge(a, boss, hnd)
+
+
+def pulley(r, h, groove=0.25):
+ """grooved sheave: two flanges with a narrower waist (the cord runs in the groove)"""
+ q = h / 4
+ return merge(cylinder(r, q, 36, 'flange_low', 'rim_low'), cylinder(r * (1 - groove), 2 * q, 36, 'waist_cap', 'groove', q),
+ cylinder(r, q, 36, 'flange', 'rim', 3 * q))
+
+
+# ------------------------------------------------------------------------------------------- the page
+class Codex:
+ def __init__(self, W=1920, H=1080, seed=0, ss=3, nib=35.0):
+ self.W, self.H, self.ss = W, H, ss
+ self.rng = np.random.default_rng(seed)
+ self.nib = np.deg2rad(nib)
+ self.ink = np.zeros((H, W), np.float32)
+ self.chalk = np.zeros((H, W), np.float32)
+ self.lead = np.zeros((H, W), np.float32)
+ self.groove = np.zeros((H, W), np.float32)
+ self.load = 1.0
+ self.use = 1.0 / 2600.0 # load used per px of 2 px line
+ self.fresh = False
+ self.base = None
+ self.mask = np.ones((H, W), np.float32)
+ self.tooth = None
+ self._fonts = {}
+ self.stages = []
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ def _box(self, x0, y0, x1, y1):
+ x0, y0 = max(0, int(np.floor(x0))), max(0, int(np.floor(y0)))
+ x1, y1 = min(self.W, int(np.ceil(x1))), min(self.H, int(np.ceil(y1)))
+ if x1 <= x0 or y1 <= y0: return None
+ return (slice(y0, y1), slice(x0, x1))
+
+ # ------------------------------------------------------------ paper
+ def sheet(self, tone=PAPER, mount=MOUNT, margin=(30, 26), laid=5.6, chain=172, lost_corner='br', fold=None,
+ stains=None, foxing=1.0, edges=1.0, age=1.0):
+ """the leaf on its mount. stains: [(cx, cy, r)] water stains; fold: x of an old vertical fold"""
+ W, H, r = self.W, self.H, self.rng
+ YY, XX = np.mgrid[0:H, 0:W].astype(np.float32)
+ mx, my = margin
+ # ragged sheet outline
+ e = lambda n, sc, s: fbm1d(n, sc, 4, s) * 3.0 * edges
+ top = my + e(W, 90, self._seed()); bot = H - my + e(W, 90, self._seed())
+ lef = mx + e(H, 90, self._seed()); rig = W - mx + e(H, 90, self._seed())
+ inside = (YY >= top[None, :]) & (YY <= bot[None, :]) & (XX >= lef[:, None]) & (XX <= rig[:, None])
+ m = inside.astype(np.float32)
+ for _ in range(int(7 * edges)): # small chips out of the edges
+ side = r.integers(4)
+ if side == 0: cx, cy = r.uniform(mx, W - mx), my
+ elif side == 1: cx, cy = r.uniform(mx, W - mx), H - my
+ elif side == 2: cx, cy = mx, r.uniform(my, H - my)
+ else: cx, cy = W - mx, r.uniform(my, H - my)
+ m *= 1 - polygon_mask(H, W, blob_pts(cx, cy, r.uniform(4, 11), r.uniform(3, 7), 0.4, 24, self._seed(), r.uniform(0, 3)))
+ if lost_corner:
+ cx = W - mx if 'r' in lost_corner else mx
+ cy = H - my if 'b' in lost_corner else my
+ sx, sy = (-1 if 'r' in lost_corner else 1), (-1 if 'b' in lost_corner else 1)
+ n = 30
+ t = np.linspace(0, 1, n)
+ tear = np.stack([cx + sx * (1 - t) * 74, cy + sy * t * 52], 1) + fbm1d(n, 8, 3, self._seed())[:, None] * 6
+ poly = np.vstack([[cx + sx * 90, cy - sy * 20], tear, [cx - sx * 20, cy + sy * 70], [cx - sx * 20, cy - sy * 20]])
+ m *= 1 - polygon_mask(H, W, poly, 2)
+ m = blur(m, 0.7)
+ self.mask = m
+ # paper body
+ col = _c(tone)
+ mott = noise2d(H, W, 260, 4, self._seed()) - 0.5
+ cloud = noise2d(H, W, 60, 3, self._seed()) - 0.5
+ g = r.random((H, W)).astype(np.float32)
+ fib = blur(g, 0.6) - 0.5
+ streak = np.asarray(Image.fromarray(r.random((H // 3, W // 22)).astype(np.float32)).resize((W, H), Image.BILINEAR)) - 0.5
+ self.fib = np.clip(0.5 + 2.2 * fib + 0.8 * streak, 0, 1).astype(np.float32)
+ self.tooth = np.clip(0.5 + 2.6 * fib + 0.9 * cloud + 0.4 * streak, 0, 1).astype(np.float32)
+ laidl = np.cos(2 * np.pi * (YY + 1.4 * fbm1d(W, 300, 3, self._seed())[None, :]) / laid)
+ laidl *= 0.5 + 0.5 * noise2d(H, W, 120, 2, self._seed())
+ ch = np.zeros((H, W), np.float32)
+ x = mx + r.uniform(30, 90)
+ while x < W - mx:
+ wav = x + 3 * fbm1d(H, 200, 3, self._seed())
+ d = XX - wav[:, None]
+ ch += np.exp(-d ** 2 / 3.0) - 0.45 * np.exp(-d ** 2 / 40.0)
+ x += chain * r.uniform(0.96, 1.04)
+ lum = 1 + 0.045 * mott + 0.02 * cloud + 0.016 * fib + 0.008 * streak + 0.006 * laidl + 0.012 * ch
+ paper = col[None, None, :] * lum[..., None]
+ # age: large soft brownish clouds where the sizing has yellowed unevenly
+ ag = smoothstep(0.5, 0.86, noise2d(H, W, 210, 4, self._seed())) * (0.55 + 0.45 * noise2d(H, W, 46, 3, self._seed()))
+ a_ = (0.115 * ag * age)[..., None]
+ paper = paper * (1 - a_ * (1 - np.array([0.74, 0.56, 0.36], np.float32)))
+ # browning toward the edges (oxidised), with a warmer, darker band right at the edge
+ dist = blur(m, 34)
+ brown = np.clip(1 - dist * 1.35, 0, 1) ** 1.3 * (0.7 + 0.6 * noise2d(H, W, 90, 3, self._seed()))
+ rim = np.clip(1 - blur(m, 5) * 1.25, 0, 1) * m
+ tan = np.array([0.66, 0.47, 0.27], np.float32)
+ k = np.clip(0.55 * brown + 0.5 * rim, 0, 0.9)[..., None]
+ paper = paper * (1 - k) + paper * tan * 1.05 * k
+ # foxing: rust specks in loose clusters
+ spots = np.zeros((H, W), np.float32)
+ for _ in range(int(26 * foxing)):
+ cx, cy = r.uniform(mx, W - mx), r.uniform(my, H - my)
+ for _ in range(int(r.integers(2, 14))):
+ sx, sy = cx + r.normal(0, 22), cy + r.normal(0, 16)
+ rad = r.uniform(0.5, 2.4) if r.random() < 0.88 else r.uniform(3, 6)
+ ext = rad * 7 + 3
+ sl = self._box(sx - ext, sy - ext, sx + ext + 1, sy + ext + 1)
+ if sl is None: continue
+ d2 = (XX[sl] - sx) ** 2 + (YY[sl] - sy) ** 2
+ core_ = np.clip((rad - np.sqrt(d2)) / 1.2 + 0.5, 0, 1) * r.uniform(0.35, 0.9)
+ spots[sl] += core_ * (0.8 + 0.4 * self.rng.random(d2.shape)) + 0.07 * np.exp(-d2 / (2 * (rad * 1.9) ** 2))
+ rust = np.array([0.56, 0.33, 0.16], np.float32)
+ sp = blur(np.clip(spots, 0, 1), 0.6)[..., None] * 0.5
+ paper = paper * (1 - sp) + paper * rust * sp
+ # water stains: slightly darker inside, a crisp darker tide line at the edge where the water stopped
+ for (cx, cy, rad) in (stains or []):
+ st = polygon_mask(H, W, blob_pts(cx, cy, rad, rad * r.uniform(0.6, 0.85), 0.22, 160, self._seed(), r.uniform(0, 3)), 2)
+ st = blur(st, 1.0)
+ tide = np.clip(np.clip(st - blur(st, 6), 0, 1) * 2.2 + np.clip(st - blur(st, 2.0), 0, 1) * 1.2, 0, 1)
+ tide *= 0.6 + 0.8 * noise2d(H, W, 40, 2, self._seed())
+ a = (0.05 * blur(st, 14) + 0.16 * tide)[..., None]
+ paper = paper * (1 - a * (1 - np.array([0.74, 0.56, 0.34], np.float32)))
+ # an old fold: one lip catches the light, the other is in shadow, grime in the crease
+ if fold is not None:
+ fx = fold + 2.0 * fbm1d(H, 260, 3, self._seed())
+ d = XX - fx[:, None]
+ crease = 0.05 * np.exp(-(d + 2.2) ** 2 / 5.0) - 0.07 * np.exp(-(d - 1.6) ** 2 / 4.0) - 0.035 * np.exp(-d ** 2 / 70.0)
+ paper *= (1 + crease * (0.7 + 0.6 * noise2d(H, W, 50, 2, self._seed())))[..., None]
+ # handling grime near the lower corners (where the leaf was turned)
+ for gx, gy in [(W - mx - 150, H - my - 130), (mx + 120, H - my - 100)]:
+ gr = np.exp(-(((XX - gx) / 210) ** 2 + ((YY - gy) / 150) ** 2)) * (0.5 + noise2d(H, W, 40, 3, self._seed()))
+ paper *= (1 - 0.06 * gr)[..., None]
+ # the mount (card) and the sheet's shadow on it
+ mc = _c(mount)
+ card = mc[None, None, :] * (1 + 0.04 * (noise2d(H, W, 30, 3, self._seed()) - 0.5) + 0.02 * fib)[..., None]
+ sh = blur(shift(m, 3, 5), 7) * 0.45
+ card *= (1 - sh)[..., None]
+ self.base = (card * (1 - m[..., None]) + paper * m[..., None]).astype(np.float32)
+ return self
+
+ def show_through(self, x, y, width, lines=8, size=20, strength=0.06):
+ """writing on the back of the leaf, seen through it: reversed (so it reads left to right), soft, faint"""
+ save, self.ink = self.ink, np.zeros_like(self.ink)
+ load = self.load
+ self.write(self.prose(lines * 9), x, y, width=width, size=size, mirror=False, max_lines=lines)
+ ghost = blur(self.ink, 1.6) * strength
+ self.ink, self.load = save, load
+ self.base *= (1 - np.clip(ghost, 0, 0.3)[..., None] * (1 - INK_LIGHT * 0.9))
+
+ # ------------------------------------------------------------ stroke engine
+ def _prep(self, pts, width, ink, smooth=True, jitter=0.5, taper=(6, 18), step=1.3, nib=True, load=True):
+ """resample a hand stroke, wobble it, give it nib width, pressure and an ink load -> (P, widths, values)"""
+ P = np.asarray(pts, np.float32)
+ if smooth and len(P) > 2: P = spline(P, 8)
+ P = _resample(P, step)
+ n = len(P)
+ if n < 2:
+ return P, np.array([width], np.float32), np.array([ink], np.float32)
+ tg = np.gradient(P, axis=0)
+ tg /= np.linalg.norm(tg, axis=1, keepdims=True) + 1e-6
+ nrm = np.stack([-tg[:, 1], tg[:, 0]], 1)
+ s = self._seed()
+ if jitter:
+ wob = fbm1d(n, max(4, 120 / step), 3, s) * jitter + fbm1d(n, max(2, 8 / step), 2, s + 1) * jitter * 0.18
+ P = P + nrm * wob[:, None]
+ sa = np.arange(n, dtype=np.float32) * step
+ L = sa[-1]
+ nibf = (0.66 + 0.42 * np.abs(np.sin(np.arctan2(tg[:, 1], tg[:, 0]) - self.nib))) if nib else 1.0
+ env = smoothstep(0, max(1.0, min(taper[0], L * 0.3)), sa) * smoothstep(0, max(1.0, min(taper[1], L * 0.4)), L - sa)
+ press = (0.42 + 0.58 * env) * (1 + 0.10 * fbm1d(n, max(4, 60 / step), 2, s + 2))
+ w = (width * nibf * press).astype(np.float32)
+ v = np.full(n, ink, np.float32)
+ if load:
+ v0 = self.load
+ used = sa * self.use * max(width, 0.8) / 2.0
+ v = ink * np.clip(v0 - used, 0.42, 1.0) * (0.92 + 0.1 * env)
+ if self.fresh: # just dipped: a small pool where the nib lands
+ v = v * (1 + 0.45 * np.exp(-sa / 4.0)); w = w * (1 + 0.35 * np.exp(-sa / 3.0))
+ self.fresh = False
+ self.load = v0 - float(used[-1])
+ if self.load < 0.58:
+ self.load = self.rng.uniform(0.95, 1.05); self.fresh = self.rng.random() < 0.35
+ return P, w, v.astype(np.float32)
+
+ def _raster(self, strokes, ss=None):
+ """strokes [(P, w, v)] -> (coverage, slices); drawn at ss x and box-filtered. Strokes of one call overwrite
+ each other (no double density where a stroke meets itself); separate calls add up."""
+ ss = ss or self.ss
+ strokes = [s for s in strokes if len(s[0])]
+ if not strokes: return None, None
+ allp = np.concatenate([s[0] for s in strokes])
+ pad = max(float(s[1].max()) for s in strokes) + 3
+ sl = self._box(allp[:, 0].min() - pad, allp[:, 1].min() - pad, allp[:, 0].max() + pad, allp[:, 1].max() + pad)
+ if sl is None: return None, None
+ x0, y0 = sl[1].start, sl[0].start
+ bw, bh = sl[1].stop - x0, sl[0].stop - y0
+ im = Image.new('L', (bw * ss, bh * ss), 0)
+ d = ImageDraw.Draw(im)
+ off = np.array([x0, y0], np.float32)
+ for P, w, v in strokes:
+ Q = (P - off) * ss
+ n = len(Q)
+ if n == 1:
+ r_ = w[0] * ss / 2
+ d.ellipse([Q[0, 0] - r_, Q[0, 1] - r_, Q[0, 0] + r_, Q[0, 1] + r_], fill=int(255 * min(1, v[0])))
+ continue
+ for i in range(0, n - 1, 2):
+ j = min(n - 1, i + 2)
+ ww = float(w[i:j + 1].mean()) * ss
+ vv = int(round(255 * float(np.clip(v[i:j + 1].mean(), 0, 1))))
+ r_ = ww / 2
+ d.ellipse([Q[i, 0] - r_, Q[i, 1] - r_, Q[i, 0] + r_, Q[i, 1] + r_], fill=vv)
+ d.line([(float(q[0]), float(q[1])) for q in Q[i:j + 1]], fill=vv, width=max(1, int(round(ww))))
+ r_ = w[-1] * ss / 2
+ d.ellipse([Q[-1, 0] - r_, Q[-1, 1] - r_, Q[-1, 0] + r_, Q[-1, 1] + r_], fill=int(255 * np.clip(v[-1], 0, 1)))
+ m = np.asarray(im.resize((bw, bh), Image.BOX), np.float32) / 255
+ return m, sl
+
+ def _deposit(self, strokes, medium='ink', strength=1.0):
+ m, sl = self._raster(strokes)
+ if sl is None: return
+ if medium == 'ink':
+ self.ink[sl] += m * strength
+ elif medium == 'chalk':
+ t = self.tooth[sl]
+ thr = 1.0 - 1.35 * m
+ dep = smoothstep(thr - 0.2, thr + 0.2, t)
+ a = np.clip(m * 1.5, 0, 1) * (0.25 + 0.75 * dep) * strength
+ self.chalk[sl] = 1 - (1 - self.chalk[sl]) * (1 - a)
+ elif medium == 'lead':
+ self.lead[sl] = np.maximum(self.lead[sl], m * strength)
+ elif medium == 'stylus':
+ self.groove[sl] = np.maximum(self.groove[sl], m * strength)
+
+ # ------------------------------------------------------------ the quill
+ def quill(self, pts, width=2.2, ink=1.0, smooth=True, jitter=0.5, taper=(6, 18)):
+ """one pen stroke through pts"""
+ self._deposit([self._prep(pts, width, ink, smooth, jitter, taper)])
+
+ def quills(self, strokes, width=2.2, ink=1.0, smooth=True, jitter=0.5, taper=(6, 18)):
+ """many pen strokes in one pass (they do not double up where they touch)"""
+ self._deposit([self._prep(p, width, ink, smooth, jitter, taper) for p in strokes if len(p) > 1])
+
+ def contour(self, pts, width=2.3, ink=1.0, searching=2, spread=2.2, smooth=True, closed=False):
+ """a contour found the way Leonardo found it: `searching` light, slightly-off passes, then the line"""
+ P = np.asarray(pts, np.float32)
+ if closed: P = np.vstack([P, P[:2]])
+ for k in range(searching):
+ off = self.rng.normal(0, spread, 2)
+ Q = P + off * np.linspace(0.4, 1.0, len(P))[:, None]
+ Q = Q + fbm1d(len(P), max(3, len(P) / 3), 2, self._seed())[:, None] * spread * 0.8
+ self.quill(Q, width * 0.55, ink * 0.42, smooth, 0.7)
+ self.quill(P, width, ink, smooth)
+
+ def ruled(self, p0, p1, width=1.7, ink=0.9, overshoot=4.0, medium='ink'):
+ """a line drawn along a straight-edge: straight, ends not exactly on target"""
+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)
+ d = p1 - p0; d /= np.linalg.norm(d) + 1e-6
+ a = p0 - d * self.rng.uniform(-overshoot * 0.5, overshoot)
+ b = p1 + d * self.rng.uniform(-overshoot * 0.5, overshoot)
+ self._deposit([self._prep([a, b], width, ink, False, 0.15, (3, 6), load=(medium == 'ink'))], medium)
+
+ def dotted(self, pts, dash=7.0, gap=6.0, width=1.5, ink=0.8, dot_dash=False, smooth=True):
+ """dashed (or dot-dash, for an axis) pen line along pts"""
+ P = np.asarray(pts, np.float32)
+ if smooth and len(P) > 2: P = spline(P, 8)
+ P = _resample(P, 1.0)
+ n = len(P)
+ strokes, i, k = [], 0, 0
+ while i < n - 1:
+ ln = dash if (not dot_dash or k % 2 == 0) else 1.5
+ j = min(n - 1, i + max(1, int(ln * self.rng.uniform(0.8, 1.2))))
+ strokes.append(P[i:j + 1] if j > i else P[i:i + 1])
+ i = j + int(gap * self.rng.uniform(0.8, 1.25)); k += 1
+ self._deposit([self._prep(s, width, ink, False, 0.2, (1.5, 2.5)) for s in strokes])
+
+ def arrow(self, pts, width=1.8, ink=0.95, head=11.0, smooth=True):
+ """a pen arrow along pts (head at the last point)"""
+ P = np.asarray(pts, np.float32)
+ if smooth and len(P) > 2: P = spline(P, 10)
+ self.quill(P, width, ink, False)
+ d = P[-1] - P[-4 if len(P) > 4 else 0]; d /= np.linalg.norm(d) + 1e-6
+ for sgn in (1, -1):
+ a = np.deg2rad(150 * sgn)
+ v = np.array([d[0] * np.cos(a) - d[1] * np.sin(a), d[0] * np.sin(a) + d[1] * np.cos(a)])
+ self.quill([P[-1], P[-1] + v * head * 0.55, P[-1] + v * head], width * 0.9, ink, True, 0.2, (2, 6))
+
+ # ------------------------------------------------------------ hatching
+ def hatch(self, mask, shade=1.0, angle=55.0, spacing=5.2, levels=(0.2, 0.48), cross=0.76, cross_angle=-38.0,
+ width=1.1, ink=0.72, length=(22, 46), bow=0.035, over=1.6, jitter=0.1, noise=0.08, origin=(0, 0),
+ medium='ink'):
+ """parallel hatching inside `mask` (0..1); shade (array like mask, or a number) 0 lit .. 1 dark.
+ Lines at `angle` (55 = the left-hander's '\\'); each entry of `levels` interleaves another set of lines
+ where shade exceeds it; above `cross` a second set at `cross_angle` crosses them.
+ A hand hatches in bands: a row of parallel strokes of about one length, then the next row, so long
+ runs are cut where the band edges fall (staggered a little from line to line, small gaps/overlaps)."""
+ M = np.asarray(mask, np.float32)
+ ys, xs = np.nonzero(M > 0.5)
+ if len(xs) < 4: return
+ S = np.broadcast_to(np.asarray(shade, np.float32), M.shape) if np.ndim(shade) == 0 else np.asarray(shade, np.float32)
+ by0, by1, bx0, bx1 = max(0, ys.min() - 2), min(M.shape[0], ys.max() + 3), max(0, xs.min() - 2), min(M.shape[1], xs.max() + 3)
+ M, S = M[by0:by1, bx0:bx1], S[by0:by1, bx0:bx1]
+ ox, oy = origin[0] + bx0, origin[1] + by0
+ xs, ys = xs - bx0, ys - by0
+ h, w = M.shape
+ N = noise2d(h, w, 22, 2, self._seed()) - 0.5 if h > 2 and w > 2 else np.zeros_like(M)
+ cx, cy = xs.mean(), ys.mean()
+ corners = np.array([[xs.min(), ys.min()], [xs.max(), ys.min()], [xs.min(), ys.max()], [xs.max(), ys.max()]], np.float32) - [cx, cy]
+ r = self.rng
+ layers = [(angle, lev, k / max(1, len(levels)), spacing) for k, lev in enumerate(levels)]
+ if cross is not None: layers.append((cross_angle, cross, 0.0, spacing * 1.05))
+ for ang, lev, phase, sp in layers:
+ a = np.deg2rad(ang)
+ d = np.array([np.cos(a), np.sin(a)], np.float32)
+ nv = np.array([-np.sin(a), np.cos(a)], np.float32)
+ on, od = corners @ nv, corners @ d
+ ts = np.arange(od.min() - 3, od.max() + 3, 1.0, dtype=np.float32)
+ Lb = r.uniform(*length)
+ cut0 = od.min() - 3 + r.uniform(0, Lb)
+ wph = r.uniform(0, 2 * np.pi)
+ strokes = []
+ o = on.min() + phase * sp
+ while o < on.max():
+ px = cx + nv[0] * o + d[0] * ts; py = cy + nv[1] * o + d[1] * ts
+ ix, iy = np.round(px).astype(int), np.round(py).astype(int)
+ ok = (ix >= 0) & (iy >= 0) & (ix < w) & (iy < h)
+ inside = np.zeros(len(ts), bool)
+ ii, jj = iy[ok], ix[ok]
+ inside[ok] = (M[ii, jj] > 0.5) & (S[ii, jj] + noise * 2 * N[ii, jj] > lev)
+ edges = np.diff(np.concatenate([[0], inside.astype(np.int8), [0]]))
+ cb = cut0 + 0.2 * Lb * np.sin(o / 19.0 + wph) + r.normal(0, 1.2)
+ for s0, s1 in zip(np.nonzero(edges == 1)[0], np.nonzero(edges == -1)[0]):
+ if s1 - s0 < 3: continue
+ t0 = ts[s0] - r.uniform(-over * 0.6, over)
+ t1 = ts[s1 - 1] + r.uniform(-over * 0.8, over)
+ k0 = int(np.ceil((t0 - cb) / Lb))
+ cuts = [cb + Lb * k for k in range(k0, k0 + int((t1 - t0) / Lb) + 2) if t0 + Lb * 0.4 < cb + Lb * k < t1 - Lb * 0.4]
+ knots = [t0] + cuts + [t1]
+ for i in range(len(knots) - 1):
+ p_ = knots[i] + (r.uniform(0.3, 1.8) if i > 0 else 0)
+ e_ = knots[i + 1] - (r.uniform(-0.6, 1.2) if i < len(knots) - 2 else 0)
+ if e_ - p_ < 2.5: continue
+ p0 = np.array([cx, cy]) + nv * o + d * p_
+ p1 = np.array([cx, cy]) + nv * o + d * e_
+ mid = (p0 + p1) / 2 + nv * (e_ - p_) * bow * r.uniform(0.7, 1.3)
+ strokes.append(np.array([p0, mid, p1], np.float32) + [ox, oy])
+ o += sp * r.uniform(0.88, 1.12)
+ if not strokes: continue
+ if medium == 'ink':
+ self._deposit([self._prep(s, width, ink, True, jitter, (3, 7)) for s in strokes])
+ else:
+ self._deposit([self._prep(s, width, ink, True, jitter, (4, 8), nib=False, load=False) for s in strokes], medium)
+
+ # ------------------------------------------------------------ red chalk, leadpoint, stylus
+ def sanguine(self, pts, width=3.4, pressure=0.7, smooth=True, jitter=0.6):
+ """one red-chalk stroke (pressure decides how deep into the grain it goes)"""
+ self._deposit([self._prep(pts, width, pressure, smooth, jitter, (8, 16), nib=False, load=False)], 'chalk')
+
+ def sanguines(self, strokes, width=3.4, pressure=0.7, smooth=True, jitter=0.6):
+ self._deposit([self._prep(p, width, pressure, smooth, jitter, (8, 16), nib=False, load=False) for p in strokes if len(p) > 1], 'chalk')
+
+ def rub(self, mask, amount=0.25, soften=4.0, origin=(0, 0)):
+ """a finger rubbed over the chalk: a soft tone inside mask, the chalk lines blurred into it"""
+ M = np.asarray(mask, np.float32)
+ h, w = M.shape
+ sl = self._box(origin[0], origin[1], origin[0] + w, origin[1] + h)
+ if sl is None: return
+ M = M[:sl[0].stop - sl[0].start, :sl[1].stop - sl[1].start]
+ sm = blur(self.chalk[sl], soften)
+ tone = blur(M, soften) * amount * (0.7 + 0.6 * self.tooth[sl])
+ self.chalk[sl] = np.clip(np.maximum(self.chalk[sl] * (1 - 0.35 * M) + sm * 0.35 * M, tone), 0, 1)
+
+ def leadpoint(self, pts, width=1.1, strength=0.5, smooth=True, jitter=0.8):
+ """faint grey underdrawing (searching lines under the ink)"""
+ self._deposit([self._prep(pts, width, strength, smooth, jitter, (6, 10), nib=False, load=False)], 'lead')
+
+ def incise(self, pts, depth=1.0, width=1.5, smooth=True):
+ """a blind line pressed with a stylus: no colour, only a groove that catches the raking light"""
+ self._deposit([self._prep(pts, width, depth, smooth, 0.15, (4, 6), nib=False, load=False)], 'stylus')
+
+ def prick(self, x, y, r=1.6):
+ """the hole a compass point leaves at a centre"""
+ sl = self._box(x - 6, y - 6, x + 7, y + 7)
+ if sl is None: return
+ yy, xx = np.mgrid[sl[0], sl[1]].astype(np.float32)
+ d2 = (xx - x) ** 2 + (yy - y) ** 2
+ self.groove[sl] = np.maximum(self.groove[sl], 2.6 * np.exp(-d2 / (2 * r * r)))
+ self.ink[sl] += 0.5 * np.exp(-d2 / (2 * (r * 0.6) ** 2))
+
+ def compass(self, cx, cy, r, a0=0.0, a1=360.0, depth=0.9, prick=True):
+ """a circle (or arc) scored with the compass, centre pricked"""
+ self.incise(self.arc(cx, cy, r, a0, a1), depth, 1.4, smooth=False)
+ if prick: self.prick(cx, cy)
+
+ # ------------------------------------------------------------ shapes and shade fields
+ @staticmethod
+ def arc(cx, cy, rx, a0=0.0, a1=360.0, ry=None, rot=0.0, step=None):
+ """points on an (elliptic) arc, screen degrees (clockwise from +x)"""
+ ry = rx if ry is None else ry
+ n = max(8, int(abs(a1 - a0) / 360 * 2 * np.pi * max(rx, ry) / (step or 3.0)))
+ t = np.deg2rad(np.linspace(a0, a1, n))
+ x, y = np.cos(t) * rx, np.sin(t) * ry
+ c, s = np.cos(np.deg2rad(rot)), np.sin(np.deg2rad(rot))
+ return np.stack([cx + x * c - y * s, cy + x * s + y * c], 1).astype(np.float32)
+
+ def _grid(self):
+ if not hasattr(self, '_yx'):
+ self._yx = np.mgrid[0:self.H, 0:self.W].astype(np.float32)
+ return self._yx[0], self._yx[1]
+
+ def poly_mask(self, pts, ss=2):
+ return polygon_mask(self.H, self.W, pts, ss)
+
+ def disc_mask(self, cx, cy, r):
+ sl = self._box(cx - r - 2, cy - r - 2, cx + r + 3, cy + r + 3)
+ m = np.zeros((self.H, self.W), np.float32)
+ yy, xx = np.mgrid[sl[0], sl[1]].astype(np.float32)
+ m[sl] = np.clip(r + 0.5 - np.hypot(xx - cx, yy - cy), 0, 1)
+ return m
+
+ def radial_shade(self, cx, cy, r, light=(-0.55, -0.6)):
+ """shade of a sphere/disc lit from `light` (screen direction): 0 lit .. 1 dark"""
+ YY, XX = self._grid()
+ ux, uy = (XX - cx) / r, (YY - cy) / r
+ l = np.asarray(light, np.float32) / np.linalg.norm(light)
+ return np.clip(0.42 + 0.5 * (ux * -l[0] + uy * -l[1]) + 0.22 * (ux * ux + uy * uy), 0, 1)
+
+ def between(self, a0, a1, b0, b1):
+ """0 on the line a0-a1 .. 1 on the line b0-b1 (e.g. across a membrane panel from one rib to the next)"""
+ YY, XX = self._grid()
+
+ def dist(p, q):
+ p, q = np.asarray(p, np.float32), np.asarray(q, np.float32)
+ d = q - p; d /= np.linalg.norm(d) + 1e-6
+ return np.abs((XX - p[0]) * d[1] - (YY - p[1]) * d[0])
+ da, db = dist(a0, a1), dist(b0, b1)
+ return da / (da + db + 1e-6)
+
+ # ------------------------------------------------------------ objects Leonardo drew again and again
+ def cane(self, p0, p1, w0=6.0, w1=3.0, bend=0.0, lashings=(), width=1.7, ink=1.0, cap=True):
+ """a cane / wooden rod seen from the side: two converging pen lines (w0 at p0, w1 at p1), optional
+ bend (px, sideways), cord lashings at fractions along it. Returns its outline (for masking hatching)."""
+ from core import curve
+ C = curve(p0, p1, bend, 40)
+ tg = np.gradient(C, axis=0); tg /= np.linalg.norm(tg, axis=1, keepdims=True) + 1e-6
+ nv = np.stack([-tg[:, 1], tg[:, 0]], 1)
+ t = np.linspace(0, 1, len(C))[:, None]
+ hw = (w0 + (w1 - w0) * t) / 2
+ A, B = C + nv * hw, C - nv * hw
+ self.quills([A, B], width, ink, True, 0.35, (5, 12))
+ if cap:
+ self.quill(self.arc(C[0, 0], C[0, 1], w0 / 2, 0, 360, step=1.0)[::-1], width * 0.8, ink * 0.9, False, 0.2, (2, 3))
+ for f in lashings:
+ i = int(np.clip(f, 0, 1) * (len(C) - 1))
+ for k in range(3):
+ q = C[min(len(C) - 1, i + k * 2)] + tg[i] * k * 0.5
+ h_ = hw[i, 0] + 1.6
+ self.quill([q + nv[i] * h_ - tg[i] * 1.5, q - nv[i] * h_ + tg[i] * 1.5], width * 0.7, ink * 0.9, False, 0.1, (1, 2))
+ return np.vstack([A, B[::-1]])
+
+ def feather(self, base, angle, length, width, medium='chalk', curl=0.06, lead=0.42, pressure=0.75, rachis=True,
+ line=None, side=1, overlapped=False):
+ """a flight feather: curved rachis, narrow leading vane, broad trailing vane, rounded tip.
+ medium 'chalk' (red chalk) or 'ink'; side=+1/-1 puts the broad vane on the left/right of the rachis (as seen
+ walking from base to tip); overlapped=True draws only what shows in a fanned wing (the broad vane's edge,
+ the tip and the end of the narrow vane). Returns (outline polygon, rachis, edge of the broad vane)."""
+ from core import curve
+ a = np.deg2rad(angle)
+ tip = (base[0] + np.cos(a) * length, base[1] + np.sin(a) * length)
+ C = curve(base, tip, length * curl, 48)
+ tg = np.gradient(C, axis=0); tg /= np.linalg.norm(tg, axis=1, keepdims=True) + 1e-6
+ nv = np.stack([-tg[:, 1], tg[:, 0]], 1) * side
+ t = np.linspace(0, 1, len(C))
+ rise = np.clip(t / 0.2, 0, 1) ** 0.55 # widens quickly from the bare quill
+ tipr = np.where(t > 0.7, np.sqrt(np.clip(1 - ((t - 0.7) / 0.3) ** 2, 0, 1)), 1.0) # rounded end
+ prof = width * rise * tipr * (1 - 0.18 * t)
+ trail = C + nv * prof[:, None]
+ lead_ = C - nv * (prof * lead)[:, None]
+ poly = np.vstack([trail, lead_[::-1]])
+ if overlapped:
+ outline = [np.vstack([trail[int(len(C) * 0.18):], lead_[::-1][:int(len(C) * 0.4)]])]
+ else:
+ outline = [trail[3:], lead_[3:]]
+ if medium == 'chalk':
+ lw = line or 2.4
+ self.sanguines(outline, lw, pressure, True, 0.5)
+ if rachis: self.sanguine(C[:-4], lw * 0.8, pressure * 0.8, True, 0.3)
+ else:
+ lw = line or 1.5
+ self.quills(outline, lw, 0.9, True, 0.35)
+ if rachis: self.quill(C[:-4], lw * 0.75, 0.75, True, 0.25)
+ return poly, C, trail
+
+ def bird(self, x, y, size=24.0, phase=0.0, ink=0.85, width=1.6):
+ """one of Leonardo's little birds seen from behind, a few quick strokes: phase 0 wings level, pi/2 fully
+ up, -pi/2 fully down; the wing bends at the wrist and its tip trails behind the beat"""
+ up = np.sin(phase)
+ lag = np.cos(phase)
+ s_ = size
+ strokes = []
+ for sgn in (-1, 1):
+ root = (x + sgn * s_ * 0.07, y - s_ * 0.02)
+ wrist = (x + sgn * s_ * 0.48, y - up * s_ * 0.42 - lag * s_ * 0.10)
+ tip = (x + sgn * s_ * 1.0, y - up * s_ * 0.66 + lag * s_ * 0.08 * (1 if up >= 0 else -1))
+ strokes.append([root, wrist, tip])
+ fk = (tip[0] - sgn * s_ * 0.16, tip[1] + s_ * 0.12) # primaries spread at the tip
+ strokes.append([fk, (tip[0] - sgn * s_ * 0.05, tip[1] + s_ * 0.05), tip])
+ self.quills(strokes, width, ink, True, 0.15, (2, 5))
+ self.quill([(x, y - s_ * 0.14), (x + s_ * 0.01, y + s_ * 0.06), (x, y + s_ * 0.24)], width * 2.0, ink, True, 0.05, (3, 4))
+ self.quills([[(x, y + s_ * 0.2), (x - s_ * 0.1, y + s_ * 0.36)], [(x, y + s_ * 0.2), (x + s_ * 0.1, y + s_ * 0.36)],
+ [(x, y + s_ * 0.2), (x, y + s_ * 0.38)]], width * 0.8, ink * 0.9, False, 0.05, (1, 2))
+
+ # ------------------------------------------------------------ writing
+ def _hand(self, size):
+ size = int(round(size))
+ if size in self._fonts: return self._fonts[size]
+ env = os.environ.get('INKPAINT_FONT_CHANCERY')
+ cands = ([(env, 0)] if env else []) + [('/System/Library/Fonts/Supplemental/Apple Chancery.ttf', 0),
+ ('/usr/share/fonts/**/z003*.[ot]tf', 0), ('/usr/share/fonts/**/URWChancery*.[ot]tf', 0),
+ ('C:/Windows/Fonts/segoesc.ttf', 0), ('/System/Library/Fonts/Supplemental/SnellRoundhand.ttc', 0)]
+ f = None
+ for pat, idx in cands:
+ hits = glob.glob(pat, recursive=True) if pat else []
+ if hits:
+ try:
+ f = ImageFont.truetype(hits[0], size, index=idx); break
+ except OSError:
+ pass
+ if f is None: f = load_font('script', size)
+ self._fonts[size] = f
+ return f
+
+ def prose(self, n=30, terms=0.18, capital=True):
+ """n pseudo-Italian words: real little words, invented ones, a few engineering terms"""
+ r = self.rng
+ out = []
+ for i in range(n):
+ u = r.random()
+ if u < 0.34: w = _SMALL[r.integers(len(_SMALL))]
+ elif u < 0.34 + terms: w = _TERMS[r.integers(len(_TERMS))]
+ else: w = ''.join(_SYL[r.integers(len(_SYL))] for _ in range(int(r.integers(2, 4))))
+ out.append(w)
+ if capital and out: out[0] = out[0][:1].upper() + out[0][1:]
+ return ' '.join(out)
+
+ def _line_mask(self, s, size):
+ """one handwritten line (left to right) -> (mask, baseline y in mask)"""
+ r = self.rng
+ f = self._hand(size)
+ est = int(f.getlength(s) * 1.12 + size * 2)
+ h = int(size * 2.4)
+ base = int(size * 1.5)
+ im = Image.new('L', (est, h), 0)
+ d = ImageDraw.Draw(im)
+ x = size * 0.5
+ drift = fbm1d(max(len(s), 2), 9, 2, self._seed()) * size * 0.07
+ slope = r.normal(0, 0.006)
+ for i, ch in enumerate(s):
+ fs = self._hand(size * r.uniform(0.93, 1.07)) if ch != ' ' else f
+ y = base + drift[i] + slope * x + r.normal(0, 0.35)
+ d.text((x, y), ch, font=fs, fill=255, anchor='ls')
+ x += fs.getlength(ch) * r.uniform(0.96, 1.05) + (r.uniform(0.0, 2.2) if ch == ' ' else 0)
+ x = int(min(est, x + size * 0.3))
+ return np.asarray(im, np.float32)[:, :x] / 255, base, x
+
+ def write(self, text, x, y, width=420, size=20, leading=1.32, mirror=True, ink=0.9, max_lines=None, indent=None):
+ """a block of handwriting. mirror=True: Leonardo's right-to-left mirror writing, x is the RIGHT margin
+ where every line starts (lines end ragged on the left); mirror=False: normal, x is the left margin.
+ `indent(i)` may return extra px to keep line i clear of a drawing. Returns the y below the block."""
+ words = text.split() if isinstance(text, str) else None
+ lines = []
+ if words is not None:
+ f = self._hand(size)
+ cur = ''
+ k = 0
+ while words:
+ lim = width - (indent(len(lines)) if indent else 0)
+ t = (cur + ' ' + words[0]).strip()
+ if f.getlength(t) * 1.03 <= lim or not cur:
+ cur = t; words.pop(0)
+ else:
+ lines.append(cur); cur = ''
+ if max_lines and len(lines) >= max_lines: break
+ if cur and not (max_lines and len(lines) >= max_lines): lines.append(cur)
+ else:
+ lines = list(text)
+ yy = y
+ for i, s in enumerate(lines):
+ m, base, wl = self._line_mask(s, size)
+ # the pen's load along the line (in writing order), re-dipped when it runs low
+ n = m.shape[1]
+ prof = np.empty(n, np.float32)
+ for j in range(n):
+ prof[j] = self.load
+ self.load -= self.use * 0.55
+ if self.load < 0.6: self.load = self.rng.uniform(0.95, 1.05)
+ dens = m * (ink * (0.55 + 0.45 * np.clip(prof, 0, 1)))[None, :]
+ ind = indent(i) if indent else 0
+ if mirror:
+ dens = dens[:, ::-1]
+ x0 = int(round(x - ind - n + self.rng.normal(0, 1.5)))
+ else:
+ x0 = int(round(x + ind + self.rng.normal(0, 1.5)))
+ y0 = int(round(yy - base))
+ sl = self._box(x0, y0, x0 + n, y0 + dens.shape[0])
+ if sl is not None:
+ dy, dx = sl[0].start - y0, sl[1].start - x0
+ self.ink[sl] += dens[dy:dy + sl[0].stop - sl[0].start, dx:dx + sl[1].stop - sl[1].start]
+ yy += size * leading
+ return yy
+
+ def label(self, s, x, y, size=22, ink=0.95, mirror=True):
+ """a short label (a point letter, a number) centred on x, baseline y"""
+ m, base, n = self._line_mask(s, size)
+ dens = m * ink * (0.85 + 0.15 * self.load)
+ if mirror: dens = dens[:, ::-1]
+ x0, y0 = int(round(x - n / 2)), int(round(y - base))
+ sl = self._box(x0, y0, x0 + n, y0 + dens.shape[0])
+ if sl is not None:
+ dy, dx = sl[0].start - y0, sl[1].start - x0
+ self.ink[sl] += dens[dy:dy + sl[0].stop - sl[0].start, dx:dx + sl[1].stop - sl[1].start]
+
+ # ------------------------------------------------------------ accidents
+ def blot(self, x, y, r=6.0, ink=1.4, drops=5):
+ """an ink drop: irregular, a darker tide rim where it dried, a few satellite drops"""
+ sl = self._box(x - r * 4 - 4, y - r * 4 - 4, x + r * 4 + 5, y + r * 4 + 5)
+ if sl is None: return
+ h, w = sl[0].stop - sl[0].start, sl[1].stop - sl[1].start
+ ox, oy = sl[1].start, sl[0].start
+ pts = blob_pts(x - ox, y - oy, r, r * self.rng.uniform(0.7, 1.0), 0.22, 60, self._seed(), self.rng.uniform(0, 3))
+ m = polygon_mask(h, w, pts, 3)
+ for _ in range(drops):
+ a, d = self.rng.uniform(0, 2 * np.pi), r * self.rng.uniform(1.3, 3.4)
+ rr = self.rng.uniform(0.5, max(0.8, r * 0.22))
+ m = np.maximum(m, polygon_mask(h, w, blob_pts(x - ox + np.cos(a) * d, y - oy + np.sin(a) * d, rr, rr, 0.2, 14, self._seed()), 3))
+ rim = np.clip(m - blur(m, max(0.8, r * 0.16)), 0, 1)
+ self.ink[sl] += (blur(m, 0.5) * 0.85 + rim * 1.1) * ink
+
+ def spatter(self, x, y, n=12, spread=30.0, ink=1.0):
+ r = self.rng
+ for _ in range(n):
+ px, py = x + r.normal(0, spread), y + r.normal(0, spread * 0.7)
+ rr = r.uniform(0.5, 1.6)
+ sl = self._box(px - 4, py - 4, px + 5, py + 5)
+ if sl is None: continue
+ yy, xx = np.mgrid[sl[0], sl[1]].astype(np.float32)
+ self.ink[sl] += ink * np.clip(rr + 0.5 - np.hypot(xx - px, yy - py), 0, 1)
+
+ def strike(self, x0, y0, x1, y1, n=5, width=2.0, ink=1.0):
+ """strike a rejected sketch out: a few fast diagonal strokes across it, then a cross"""
+ r = self.rng
+ strokes = []
+ for k in range(n):
+ t = (k + 0.5) / n
+ a = (x0 + (x1 - x0) * (t - 0.35), y0 - 4)
+ b = (x0 + (x1 - x0) * (t + 0.35), y1 + 4)
+ mid = ((a[0] + b[0]) / 2 + r.normal(0, 3), (a[1] + b[1]) / 2)
+ strokes.append([a, mid, b])
+ strokes.append([(x0, y0), ((x0 + x1) / 2 + 3, (y0 + y1) / 2 - 2), (x1, y1)])
+ strokes.append([(x1, y0), ((x0 + x1) / 2 - 2, (y0 + y1) / 2 + 3), (x0, y1)])
+ for s in strokes: self.quill(s, width, ink, True, 0.6, (3, 12))
+
+ # ------------------------------------------------------------ machine parts (pen renderer)
+ def solid(self, mesh, cam, width=2.1, ink=1.0, crease=30.0, light=(-0.55, 0.45, 0.70), hatch=None, erase=True,
+ hatch_groups=None, edge_ink=None):
+ """draw a mesh the way a draughtsman would: hidden lines dropped, feature edges inked, faces hatched by tone.
+ hatch: dict of hatch() keyword overrides (applies to every group); hatch_groups: {group prefix: dict}
+ for per-surface overrides (angle, levels, ...; None to leave a surface white)."""
+ V = mesh.V
+ S2, Z = cam.project(V)
+ F = mesh.F
+ nf = len(F)
+ Lc = np.asarray(light, np.float32); Lc /= np.linalg.norm(Lc)
+ # face normals (Newell) in camera space: (right, toward, up)
+ Nw = np.zeros((nf, 3), np.float32)
+ for i, f in enumerate(F):
+ P = V[f]; Q = np.roll(P, -1, 0)
+ Nw[i] = [np.sum((P[:, 1] - Q[:, 1]) * (P[:, 2] + Q[:, 2])), np.sum((P[:, 2] - Q[:, 2]) * (P[:, 0] + Q[:, 0])),
+ np.sum((P[:, 0] - Q[:, 0]) * (P[:, 1] + Q[:, 1]))]
+ Nw /= np.linalg.norm(Nw, axis=1, keepdims=True) + 1e-9
+ Nc = cam.cam(Nw)
+ front = Nc[:, 1] > 1e-3
+ lam = np.clip(Nc @ Lc, 0, 1)
+ shade_f = np.clip(1.0 - lam * 1.12, 0, 1) ** 0.9
+ pad = 8
+ sl = self._box(S2[:, 0].min() - pad, S2[:, 1].min() - pad, S2[:, 0].max() + pad, S2[:, 1].max() + pad)
+ if sl is None: return
+ x0, y0 = sl[1].start, sl[0].start
+ h, w = sl[0].stop - y0, sl[1].stop - x0
+ zb = np.full((h, w), np.inf, np.float32)
+ fid = np.full((h, w), -1, np.int32)
+ cov = Image.new('L', (w * 2, h * 2), 0)
+ dc = ImageDraw.Draw(cov)
+ for i in np.nonzero(front)[0]:
+ P2 = S2[F[i]] - [x0, y0]
+ bx0, by0 = max(0, int(P2[:, 0].min()) - 1), max(0, int(P2[:, 1].min()) - 1)
+ bx1, by1 = min(w, int(P2[:, 0].max()) + 2), min(h, int(P2[:, 1].max()) + 2)
+ if bx1 <= bx0 or by1 <= by0: continue
+ im = Image.new('L', (bx1 - bx0, by1 - by0), 0)
+ ImageDraw.Draw(im).polygon([(float(p[0] - bx0 - 0.5), float(p[1] - by0 - 0.5)) for p in P2], fill=1, outline=1)
+ m = np.asarray(im, bool)
+ dc.polygon([(float(p[0] * 2), float(p[1] * 2)) for p in P2], fill=255)
+ if not m.any(): continue
+ A = np.c_[P2, np.ones(len(P2))]
+ coef, *_ = np.linalg.lstsq(A, Z[F[i]], rcond=None)
+ yy, xx = np.mgrid[by0:by1, bx0:bx1].astype(np.float32)
+ dep = coef[0] * xx + coef[1] * yy + coef[2]
+ sub_z = zb[by0:by1, bx0:bx1]; sub_f = fid[by0:by1, bx0:bx1]
+ upd = m & (dep < sub_z)
+ sub_z[upd] = dep[upd]; sub_f[upd] = i
+ sil = np.asarray(cov.resize((w, h), Image.BOX), np.float32) / 255
+ if erase:
+ self.ink[sl] *= 1 - sil
+ self.lead[sl] *= 1 - sil
+ # hatch each surface group with its own tone field (smoothed inside the group)
+ groups = {}
+ for i, g in enumerate(mesh.G): groups.setdefault(g, []).append(i)
+ base_h = dict(angle=55.0, spacing=4.6, levels=(0.22, 0.5), cross=0.76, width=1.05, ink=0.7, length=(10, 40))
+ if hatch: base_h.update(hatch)
+ for g, idx in groups.items():
+ kw = dict(base_h)
+ skip = False
+ if hatch_groups:
+ for pre, o in hatch_groups.items():
+ if g.startswith(pre) or g.split('.')[-1].startswith(pre):
+ if o is None: skip = True
+ else: kw.update(o)
+ if skip: continue
+ reg = np.isin(fid, idx)
+ if reg.sum() < 12: continue
+ sh = np.zeros((h, w), np.float32)
+ lut = np.zeros(nf + 1, np.float32); lut[:nf] = shade_f
+ sh[reg] = lut[fid[reg]]
+ regf = reg.astype(np.float32)
+ num = blur(sh * regf, 2.0); den = blur(regf, 2.0) + 1e-4
+ shs = np.where(reg, num / den, 0)
+ self.hatch(regf, shs, origin=(x0, y0), **kw)
+ # feature edges
+ emap = {}
+ for i, f in enumerate(F):
+ for k in range(len(f)):
+ a, b = f[k], f[(k + 1) % len(f)]
+ emap.setdefault((min(a, b), max(a, b)), []).append(i)
+ cosc = np.cos(np.deg2rad(crease))
+ draw = {}
+ for (a, b), own in emap.items():
+ vis = [o for o in own if front[o]]
+ if not vis: continue
+ if len(own) == 1: kind = 1.0
+ elif len(vis) < len(own): kind = 1.0 # silhouette
+ elif float(np.dot(Nw[own[0]], Nw[own[1]])) < cosc: kind = 0.72 # crease
+ else: continue
+ draw[(a, b)] = kind
+ # chain edges into long polylines (degree-2 vertices of the same kind are joined)
+ adj = {}
+ for (a, b), k in draw.items():
+ adj.setdefault(a, []).append((b, k)); adj.setdefault(b, []).append((a, k))
+ used = set()
+ chains = []
+ for (a, b), k in draw.items():
+ if (a, b) in used: continue
+ used.add((a, b))
+ path = [a, b]
+ for end in (1, 0):
+ while True:
+ v = path[-1] if end else path[0]
+ prev = path[-2] if end else path[1]
+ nxt = [(u, kk) for u, kk in adj[v] if (min(u, v), max(u, v)) not in used and kk == k]
+ if len(adj[v]) != 2 or not nxt: break
+ u = nxt[0][0]
+ used.add((min(u, v), max(u, v)))
+ if end: path.append(u)
+ else: path.insert(0, u)
+ if u == path[0 if end else -1]: break
+ chains.append((path, k))
+ zmax = zb.copy()
+ zmax[~np.isfinite(zmax)] = 1e9
+ zmax = np.maximum.reduce([shift(zmax, dx, dy) for dx in (-1, 0, 1) for dy in (-1, 0, 1)])
+ tol = 1.5
+ strokes_hi, strokes_lo = [], []
+ for path, k in chains:
+ P = S2[path]; Zp = Z[path]
+ seg = np.hypot(*np.diff(P, axis=0).T)
+ sacc = np.concatenate([[0], np.cumsum(seg)])
+ if sacc[-1] < 1.5: continue
+ n = int(sacc[-1]) + 2
+ t = np.linspace(0, sacc[-1], n)
+ px = np.interp(t, sacc, P[:, 0]); py = np.interp(t, sacc, P[:, 1]); pz = np.interp(t, sacc, Zp)
+ ix = np.clip(np.round(px - x0).astype(int), 0, w - 1); iy = np.clip(np.round(py - y0).astype(int), 0, h - 1)
+ vis = pz <= zmax[iy, ix] + tol
+ e = np.diff(np.concatenate([[0], vis.astype(np.int8), [0]]))
+ for s0, s1 in zip(np.nonzero(e == 1)[0], np.nonzero(e == -1)[0]):
+ if s1 - s0 < 3: continue
+ run = np.stack([px[s0:s1], py[s0:s1]], 1)
+ # long runs are drawn as several pen strokes, as a hand would
+ L = s1 - s0
+ cut = [0]
+ while cut[-1] < L - 1:
+ cut.append(min(L - 1, cut[-1] + int(self.rng.uniform(90, 220))))
+ for c0, c1 in zip(cut[:-1], cut[1:]):
+ (strokes_hi if k >= 1 else strokes_lo).append(run[max(0, c0 - 2):c1 + 1])
+ ei = ink if edge_ink is None else edge_ink
+ self._deposit([self._prep(s, width, ei, False, 0.35, (4, 8)) for s in strokes_hi])
+ self._deposit([self._prep(s, width * 0.72, ei * 0.85, False, 0.35, (4, 8)) for s in strokes_lo])
+
+ # ------------------------------------------------------------ output
+ def composite(self):
+ img = self.base.copy()
+ m = self.mask
+ if self.groove.any(): # raking light on the stylus grooves
+ g = blur(self.groove, 0.7)
+ gy, gx = np.gradient(g)
+ lit = (gx * -0.6 + gy * -0.7)
+ img *= (1 + np.clip(lit * 0.55, -0.12, 0.12) * m - 0.03 * np.clip(g, 0, 1) * m)[..., None]
+ if self.lead.any():
+ a = np.clip(self.lead * 0.5, 0, 0.55) * m
+ img *= 1 - a[..., None] * (1 - _c(LEADPOINT))
+ if self.chalk.any():
+ a = np.clip(self.chalk, 0, 1) * 0.9 * m
+ img *= 1 - a[..., None] * (1 - _c(SANGUINE))
+ D = self.ink * (0.8 + 0.4 * self.fib) * m
+ halo = np.clip(blur(D, 1.8), 0, 1.5)
+ img *= 1 - (0.11 * halo)[..., None] * (1 - INK_HALO)
+ a = 1 - np.exp(-1.75 * D)
+ k = smoothstep(0.25, 0.97, a)[..., None]
+ col = INK_LIGHT * (1 - k) + INK_DARK * k
+ img *= 1 - a[..., None] * (1 - col)
+ 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):
+ img = self.composite()
+ if path.lower().endswith(('.jpg', '.jpeg')):
+ img.save(path, quality=88, 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
diff --git a/lib/comic.py b/lib/comic.py
new file mode 100644
index 0000000..602f969
--- /dev/null
+++ b/lib/comic.py
@@ -0,0 +1,1088 @@
+"""comic — a golden-age comic-book cover of about 1940: brush-inked key lines on the black plate, flat process
+colours separated by hand into Ben-Day tints, four plates printed a little out of register on cheap newsprint that
+has since browned (numpy + Pillow only).
+
+Model: the cover is made the way the shop made it, then printed the way a web press printed it.
+ newsprint groundwood pulp: cream gone tan, cloudy formation, short brown fibres and bark flecks, a fine tooth
+ with pits that never take ink. Ink soaks in instead of sitting on top, so every print is a little
+ fuzzy and a little flat, and the paper colour tints every ink printed on it.
+ key plate the inker's black: brush lines that land thin, swell and lift off to a point and run heavier on the
+ side away from the light (`brush`, `outline`, `edge`), thin pen lines (`pen`), spotted blacks (`ink`),
+ feathering -- rows of tapered strokes coming in from a shadow edge (`feather`), hatching, speed lines
+ and hand lettering. Things in front hide what is behind them: every `part` first erases the key and
+ the colour under itself, then gets its own outline.
+ colour guide the colourist marks every area with a mix of the three process inks taken from a short list of
+ Ben-Day tints -- 0, 20, 40, 70, 100 % -- so a whole cover has only a few dozen colours: skin is
+ 20 % red + 40 % yellow, sky blue 40 % blue, red is 100 % red + 100 % yellow ... (`flat`). The colour
+ runs under the black lines. A graded sky is a stack of bands, because the separator cut a new
+ piece of tint film for each step, along a hand-cut wavy edge (`graded`, `rings`). Grey is a black tint.
+ separation every plate is screened on its own: a tint becomes Ben-Day dots on a regular grid at that plate's
+ angle (round dots that grow, touch at 50 % and turn into holes near 70 %); 100 % prints solid. Overlap
+ two tints and the dot grids beat into rosettes. Separations were painted by hand, so each plate's
+ flats wander a pixel or two off the line art.
+ press every plate lands a little off (`register`): the red slips out from under the black outline on one
+ side and leaves a sliver of paper on the other. Newsprint drinks ink: dots spread and lose their round
+ edge, small dots drop out, solids mottle and let paper pits and fibres through, the black is never
+ quite black. Inks are transparent and multiply (yellow + red = red-orange, red + blue = purple).
+ afterlife the cover browned from the edges (`brown_edges`), the spine cracked into little white stress ticks
+ and two staples rusted (`spine`), a corner got rubbed and dog-eared (`corner`), a crease broke the
+ colour (`crease`), foxing spots (`foxing`).
+Stages: `stage(name, plates='CMYK')` keeps the plates as they are now and proofs only the listed ones, so a
+drawing animation can show the key line art first and then the progressive proofs (yellow, + red, + blue) the way
+an engraver pulled them. Coordinates are pixels, y down; angles in degrees counter-clockwise (0 = 3 o'clock).
+
+ from comic import ComicCover, YELLOW, RED, BLUE, SKY
+ c = ComicCover(1920, 1080, seed=3)
+ c.paper()
+ c.graded(None, [BLUE, SKY, YELLOW], (0, 0), (0, 1080)) # banded sky, whole sheet
+ c.part(c.ellipse_pts(960, 540, 200, 120), RED, width=7) # a red shape in front, inked round
+ c.feather(*c.edge_normals(c.ellipse_pts(960, 540, 200, 120)), length=40)
+ c.balloon('HELLO THERE!', 1300, 300, 40, tail=(1100, 470))
+ c.logo('THRILL', [(200, 60), (900, 40), (900, 230), (200, 210)], vp=(560, 2600))
+ c.stage('key', plates='K'); c.stage('colour')
+ c.spine(); c.brown_edges(); c.foxing()
+ c.save('out.jpg', stages_dir='stages')
+"""
+import glob
+import os
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+from core import blur, fbm1d, spline, noise2d, smoothstep, shift, latin_font
+
+# ---------------------------------------------------------------- inks and colours
+# printed solid on bright paper; on newsprint they multiply with the paper colour
+INK = {'C': np.array([0.15, 0.55, 0.83], np.float32), # process blue of the period (greener than today's cyan)
+ 'M': np.array([0.91, 0.21, 0.39], np.float32), # process red (warm magenta)
+ 'Y': np.array([0.99, 0.84, 0.13], np.float32),
+ 'K': np.array([0.13, 0.11, 0.11], np.float32)}
+NEWS = (0.935, 0.872, 0.715) # newsprint, already toned
+# colour guide values: (blue, red, yellow, black) Ben-Day tints, 0..1 -- the colourist's chart
+WHITE = (0, 0, 0, 0)
+CREAM = (0, 0, .2, 0)
+PALE = (0, 0, .4, 0)
+YELLOW = (0, 0, 1, 0)
+GOLD = (0, .2, 1, 0)
+ORANGE = (0, .4, 1, 0)
+DEEP_ORANGE = (0, .7, 1, 0)
+RED = (0, 1, 1, 0)
+CRIMSON = (0, 1, .7, 0)
+PINK = (0, .4, .2, 0)
+SKIN = (0, .2, .4, 0)
+TAN = (0, .4, .7, 0)
+BROWN = (0, .7, 1, .4) # no blue in browns: C+M+Y rosettes read green
+DARK_BROWN = (0, .7, 1, .7)
+SKY = (.4, 0, 0, 0)
+LIGHT_BLUE = (.2, 0, 0, 0)
+BLUE = (1, .4, 0, 0)
+NAVY = (1, .7, 0, .2)
+VIOLET = (.7, .7, 0, 0)
+MAUVE = (.4, .4, .2, 0)
+LILAC = (.2, .2, 0, 0)
+GREEN = (1, 0, 1, 0)
+LIME = (.4, 0, 1, 0)
+GREY = (0, 0, 0, .4)
+LIGHT_GREY = (0, 0, 0, .2)
+SILVER = (.2, 0, 0, .2)
+SCREEN_ANGLE = {'C': 15.0, 'M': 75.0, 'Y': 0.0, 'K': 45.0}
+LIGHT = (-0.6, -0.8) # light from the upper left: outlines swell lower right
+
+_S = '/System/Library/Fonts/Supplemental/'
+_FACES = { # (glob, face index); first hit wins -- macOS, then Linux / Windows look-alikes; generic core style last
+ 'letter': [(_S + 'ChalkboardSE.ttc', 2), (_S + 'Comic Sans MS Bold.ttf', 0), ('/System/Library/Fonts/MarkerFelt.ttc', 1),
+ ('/usr/share/fonts/**/*ComicNeue*Bold*.[ot]tf', 0), ('/usr/share/fonts/**/*Kalam*Bold*.ttf', 0),
+ ('C:/Windows/Fonts/comicbd.ttf', 0), 'hand'],
+ 'logo': [(_S + 'Futura.ttc', 4), (_S + 'Impact.ttf', 0), ('/usr/share/fonts/**/*Oswald*Bold*.ttf', 0),
+ ('/usr/share/fonts/**/DejaVuSansCondensed-Bold.ttf', 0), ('C:/Windows/Fonts/impact.ttf', 0), 'condensed'],
+ 'bold': [(_S + 'Futura.ttc', 2), (_S + 'Arial Black.ttf', 0), ('/usr/share/fonts/**/DejaVuSans-Bold.ttf', 0),
+ ('C:/Windows/Fonts/ariblk.ttf', 0), 'sans_bold'],
+ 'slab': [(_S + 'Rockwell.ttc', 2), (_S + 'SuperClarendon.ttc', 7), ('/usr/share/fonts/**/DejaVuSerif-Bold.ttf', 0),
+ ('C:/Windows/Fonts/ROCKB.TTF', 0), 'serif'],
+ 'heavy': [(_S + 'SuperClarendon.ttc', 7), (_S + 'Rockwell.ttc', 2), ('/usr/share/fonts/**/DejaVuSerif-Bold.ttf', 0),
+ ('C:/Windows/Fonts/ROCKEB.TTF', 0), 'serif'],
+}
+_FONT_CACHE = {}
+
+
+def _font(face, size):
+ key = (face, int(size))
+ if key in _FONT_CACHE: return _FONT_CACHE[key]
+ env = os.environ.get('INKPAINT_FONT_' + face.upper())
+ cands = ([(env, 0)] if env and os.path.exists(env) else []) + _FACES.get(face, [face])
+ f = None
+ for c in cands:
+ if isinstance(c, str):
+ hit = latin_font(c)
+ if not hit: continue
+ path, idx = hit
+ else:
+ fs = glob.glob(c[0], recursive=True)
+ if not fs: continue
+ path, idx = fs[0], c[1]
+ try:
+ f = ImageFont.truetype(path, int(size), index=idx); break
+ except OSError:
+ continue
+ if f is None: f = ImageFont.load_default(int(size))
+ _FONT_CACHE[key] = f
+ return f
+
+
+# ---------------------------------------------------------------- geometry helpers
+def _resample(P, step, closed=False):
+ P = np.asarray(P, np.float32)
+ if closed: P = np.vstack([P, P[:1]])
+ seg = np.hypot(*np.diff(P, axis=0).T)
+ s = np.concatenate([[0], np.cumsum(seg)])
+ if s[-1] < 1e-3: return P[:1]
+ n = max(2, int(s[-1] / step) + 1)
+ ss = np.linspace(0, s[-1], n, endpoint=not closed)
+ return np.stack([np.interp(ss, s, P[:, 0]), np.interp(ss, s, P[:, 1])], 1).astype(np.float32)
+
+
+def _closed_spline(pts, per=10):
+ """periodic Catmull-Rom through control points"""
+ P = np.asarray(pts, np.float32)
+ n = len(P)
+ t = np.linspace(0, 1, per, endpoint=False)[:, None]
+ t2, t3 = t * t, t * t * t
+ out = []
+ for i in range(n):
+ p0, p1, p2, p3 = P[(i - 1) % n], P[i], P[(i + 1) % n], P[(i + 2) % n]
+ out.append(0.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 + (-p0 + 3 * p1 - 3 * p2 + p3) * t3))
+ return np.vstack(out).astype(np.float32)
+
+
+def _normals(P):
+ T = np.gradient(P, axis=0)
+ T /= np.linalg.norm(T, axis=1, keepdims=True) + 1e-6
+ return T, np.stack([-T[:, 1], T[:, 0]], 1)
+
+
+def _outward(P):
+ """unit outward normals of a closed polygon (either winding)"""
+ _, N = _normals(np.vstack([P[-1:], P, P[:1]]))
+ N = N[1:-1]
+ area = 0.5 * np.sum(P[:, 0] * np.roll(P[:, 1], -1) - np.roll(P[:, 0], -1) * P[:, 1])
+ return N if area < 0 else -N
+
+
+def _persp(dst, src):
+ """coefficients for Image.transform(PERSPECTIVE): output (dst) points -> input (src) points"""
+ A, b = [], []
+ for (x, y), (u, v) in zip(dst, src):
+ A.append([x, y, 1, 0, 0, 0, -u * x, -u * y]); b.append(u)
+ A.append([0, 0, 0, x, y, 1, -v * x, -v * y]); b.append(v)
+ return tuple(np.linalg.solve(np.array(A, np.float64), np.array(b, np.float64)))
+
+
+def _norm_noise(rng, H, W, sigma):
+ n = blur(rng.standard_normal((H, W)).astype(np.float32), sigma)
+ return (n / (n.std() + 1e-6)).astype(np.float32)
+
+
+class ComicCover:
+ def __init__(self, W=1920, H=1080, seed=0, screen=11.0, misreg=4.0, slop=1.6, light=LIGHT):
+ self.W, self.H = W, H
+ self.rng = np.random.default_rng(seed)
+ self.seed = seed
+ self.pitch = float(screen)
+ self.slop = float(slop)
+ l = np.asarray(light, np.float32)
+ self.light = l / np.linalg.norm(l)
+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)
+ self.g = {p: np.zeros((H, W), np.float32) for p in 'CMYk'} # colour guide; 'k' = black tints
+ self.key = np.zeros((H, W), np.float32) # line art (solid black)
+ a = self.rng.uniform(0, 2 * np.pi, 3)
+ self.reg = {'K': (0.0, 0.0, 0.0)}
+ for p, ang, k in zip('MCY', a, (1.0, 0.85, 0.6)):
+ self.reg[p] = (float(np.cos(ang) * misreg * k), float(np.sin(ang) * misreg * k), float(self.rng.normal(0, 0.03)))
+ self.paper_rgb = np.ones((H, W, 3), np.float32) * np.array(NEWS, np.float32)
+ self.tooth = np.full((H, W), 0.5, np.float32)
+ self.wear_ops = []
+ self.stages = []
+ self._press_cache = None
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ def register(self, plate, dx, dy, rot=0.0):
+ """where plate C, M, Y or K lands relative to the sheet (px, px, degrees)"""
+ self.reg[plate] = (float(dx), float(dy), float(rot))
+
+ # ------------------------------------------------------------ newsprint
+ def paper(self, colour=NEWS, tone=1.0, fibres=3200, flecks=420):
+ """groundwood newsprint: cloudy formation, warm age patches, short fibres, bark flecks, pitted tooth"""
+ H, W = self.H, self.W
+ r = np.random.default_rng(self._seed())
+ col = np.asarray(colour, np.float32)
+ form = noise2d(H, W, 26, 3, self._seed()) - 0.5 # pulp flocs
+ cloud = noise2d(H, W, 260, 3, self._seed()) - 0.5
+ warm = noise2d(H, W, 420, 3, self._seed())
+ img = col[None, None, :] * (1 + 0.035 * form + 0.05 * cloud * tone)[..., None]
+ img = img * (1 - 0.07 * tone * (warm ** 2)[..., None] * np.array([0.25, 0.55, 1.0], np.float32))
+ im = Image.new('L', (W, H), 0)
+ lt = Image.new('L', (W, H), 0)
+ d, dl = ImageDraw.Draw(im), ImageDraw.Draw(lt)
+ for i in range(fibres):
+ x, y = r.uniform(0, W), r.uniform(0, H)
+ L, a = r.uniform(3, 16), r.uniform(0, np.pi)
+ k = r.uniform(-0.25, 0.25)
+ pts = [(x + np.cos(a + k * t) * L * t, y + np.sin(a + k * t) * L * t) for t in np.linspace(-0.5, 0.5, 5)]
+ if r.random() < 0.72:
+ d.line(pts, fill=int(r.uniform(60, 200)), width=1)
+ else:
+ dl.line(pts, fill=int(r.uniform(80, 220)), width=1)
+ for i in range(flecks):
+ x, y, rr = r.uniform(0, W), r.uniform(0, H), r.uniform(0.5, 1.6)
+ d.ellipse([x - rr, y - rr * r.uniform(0.6, 1.2), x + rr, y + rr], fill=int(r.uniform(150, 255)))
+ fib = blur(np.asarray(im, np.float32) / 255, 0.45)
+ lfb = blur(np.asarray(lt, np.float32) / 255, 0.45)
+ brown = np.array([0.45, 0.32, 0.18], np.float32)
+ img = img * (1 - 0.30 * fib[..., None] * (1 - brown)) + 0.05 * lfb[..., None]
+ self.tooth = np.clip(0.5 + 0.16 * _norm_noise(r, H, W, 0.6) + 0.10 * form, 0, 1).astype(np.float32)
+ img = img * (1 + 0.02 * (self.tooth - 0.5))[..., None]
+ self.paper_rgb = np.clip(img, 0, 1).astype(np.float32)
+ self._press_cache = None
+
+ # ------------------------------------------------------------ shapes
+ @staticmethod
+ def ellipse_pts(cx, cy, rx, ry, rot=0.0, a0=0.0, a1=360.0, n=None):
+ n = n or max(24, int(np.pi * (rx + ry) / 3))
+ t = np.deg2rad(np.linspace(a0, a1, n, endpoint=(a1 - a0) % 360 != 0))
+ c, s = np.cos(np.deg2rad(rot)), np.sin(np.deg2rad(rot))
+ x, y = np.cos(t) * rx, -np.sin(t) * ry
+ return np.stack([cx + x * c + y * s, cy - x * s + y * c], 1).astype(np.float32)
+
+ @staticmethod
+ def smooth(pts, per=10, closed=True):
+ """Catmull-Rom through control points (closed by default)"""
+ return _closed_spline(pts, per) if closed else spline(pts, per)
+
+ @staticmethod
+ def tube_pts(path, widths, per=10, caps=True):
+ """outline of a limb / rope / flame tongue: a spline centreline with widths along it, round caps"""
+ path = np.asarray(path, np.float32)
+ P = spline(path, per) if len(path) > 2 else np.linspace(path[0], path[1], 16).astype(np.float32)
+ P = _resample(P, 2.0)
+ w = np.interp(np.linspace(0, 1, len(P)), np.linspace(0, 1, len(widths)), np.asarray(widths, np.float32))
+ T, N = _normals(P)
+ A = P + N * (w / 2)[:, None]
+ B = P - N * (w / 2)[:, None]
+ if not caps:
+ return np.vstack([A, B[::-1]]).astype(np.float32)
+ arc = np.linspace(0, np.pi, 12)[1:-1]
+
+ def cap(i, angs):
+ c, rr = P[i], w[i] / 2
+ return np.stack([c[0] + np.cos(angs) * rr, c[1] + np.sin(angs) * rr], 1)
+ b1 = np.arctan2(N[-1, 1], N[-1, 0])
+ b0 = np.arctan2(N[0, 1], N[0, 0])
+ return np.vstack([A, cap(-1, b1 - arc), B[::-1], cap(0, b0 + np.pi - arc)]).astype(np.float32)
+
+ @staticmethod
+ def burst_pts(cx, cy, rx, ry, spikes=14, depth=0.3, seed=0, rot=0.0):
+ """a starburst: alternating points and notches with uneven spike lengths"""
+ r = np.random.default_rng(seed)
+ n = spikes * 2
+ t = np.linspace(0, 2 * np.pi, n, endpoint=False) + np.deg2rad(rot) + r.uniform(-0.08, 0.08, n)
+ k = np.where(np.arange(n) % 2 == 0, 1 + r.uniform(-0.08, 0.12, n), 1 - depth + r.uniform(-0.05, 0.05, n))
+ return np.stack([cx + np.cos(t) * rx * k, cy + np.sin(t) * ry * k], 1).astype(np.float32)
+
+ def mask(self, pts, smooth=False, per=10, ss=3):
+ """closed polygon (or control points if smooth) -> anti-aliased full-sheet mask"""
+ P = np.asarray(pts, np.float32)
+ if smooth: P = _closed_spline(P, per)
+ m = np.zeros((self.H, self.W), np.float32)
+ x0, y0 = int(max(0, np.floor(P[:, 0].min()) - 2)), int(max(0, np.floor(P[:, 1].min()) - 2))
+ x1, y1 = int(min(self.W, np.ceil(P[:, 0].max()) + 3)), int(min(self.H, np.ceil(P[:, 1].max()) + 3))
+ if x1 <= x0 or y1 <= y0: return m
+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0)
+ ImageDraw.Draw(im).polygon([((x - x0) * ss, (y - y0) * ss) for x, y in P.tolist()], fill=255)
+ m[y0:y1, x0:x1] = np.asarray(im.resize((x1 - x0, y1 - y0), Image.BOX), np.float32) / 255
+ return m
+
+ def circle(self, cx, cy, r):
+ return np.clip(r + 0.5 - np.hypot(self.XX - cx, self.YY - cy), 0, 1)
+
+ def _m(self, shape, smooth=False):
+ if shape is None: return np.ones((self.H, self.W), np.float32)
+ if isinstance(shape, np.ndarray) and shape.shape == (self.H, self.W): return shape
+ return self.mask(shape, smooth)
+
+ @staticmethod
+ def _bbox(m, pad=0):
+ ys, xs = np.nonzero(m > 0.003)
+ if len(xs) == 0: return None
+ H, W = m.shape
+ return (slice(max(0, ys.min() - pad), min(H, ys.max() + pad + 1)), slice(max(0, xs.min() - pad), min(W, xs.max() + pad + 1)))
+
+ def grow(self, m, r):
+ """dilate a soft mask by about r px (round, anti-aliased)"""
+ if r <= 0: return m
+ sg = max(0.5, r * 0.6)
+ q = 0.0478 # Phi(-1/0.6): a straight edge moves out by r
+ dd = 0.05 / sg
+ return smoothstep(q - dd, q + dd, blur(m, sg))
+
+ def shrink(self, m, r):
+ return 1 - self.grow(1 - m, r)
+
+ # ------------------------------------------------------------ colour guide (the colourist's flats)
+ def _set(self, a, colour, sl=None):
+ c = [float(v) for v in colour] + [0.0] * (4 - len(colour))
+ for p, v in zip('CMYk', c):
+ g = self.g[p] if sl is None else self.g[p][sl]
+ g *= 1 - a
+ if v: g += a * v
+
+ def flat(self, shape, colour, smooth=False):
+ """paint an area of the colour guide with one Ben-Day mix (replaces what was there)"""
+ a = self._m(shape, smooth)
+ self._set(a, colour)
+ return a
+
+ def graded(self, shape, colours, p0, p1, edges=None, wave=7.0, scale=180.0, smooth=False):
+ """stepped bands from p0 to p1, one Ben-Day colour per band, split along hand-cut wavy edges.
+ edges: the inner band edges as fractions 0..1 (default: equal bands)"""
+ a = self._m(shape, smooth)
+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)
+ d = p1 - p0
+ L = float(np.linalg.norm(d)) + 1e-6
+ t = ((self.XX - p0[0]) * d[0] + (self.YY - p0[1]) * d[1]) / (L * L)
+ t = t + (noise2d(self.H, self.W, scale, 2, self._seed()) - 0.5) * 2 * wave / L
+ n = len(colours)
+ e = np.asarray(edges if edges is not None else np.arange(1, n) / n, np.float32)
+ band = np.searchsorted(e, t.ravel()).reshape(t.shape)
+ for i, col in enumerate(colours):
+ self._set(a * (band == i), col)
+ return a
+
+ def rings(self, shape, cx, cy, colours, radii, wave=4.0, smooth=False):
+ """concentric bands (a halo): colours[i] inside radii[i]; outermost first is not needed"""
+ a = self._m(shape, smooth)
+ rr = np.hypot(self.XX - cx, self.YY - cy) + (noise2d(self.H, self.W, 90, 2, self._seed()) - 0.5) * 2 * wave
+ for col, rad in sorted(zip(colours, radii), key=lambda z: -z[1]):
+ self._set(a * np.clip(rad + 0.5 - rr, 0, 1), col)
+ return a
+
+ def knock(self, shape, key=True, smooth=False):
+ """white: no ink on any plate (stars, highlights, balloons)"""
+ a = self._m(shape, smooth)
+ self._set(a, WHITE)
+ if key: self.key *= 1 - a
+ return a
+
+ # ------------------------------------------------------------ key plate (brush and pen)
+ def _dense(self, pts, smooth=True, closed=False, step=1.5):
+ P = np.asarray(pts, np.float32)
+ if smooth and 3 <= len(P) < 80:
+ P = _closed_spline(P, 10) if closed else spline(P, per=10)
+ P = _resample(P, step, closed)
+ return P if len(P) >= 2 else np.vstack([P, P + 0.5])
+
+ def _ribbon(self, P, w, ss=3):
+ """variable-width centreline -> (slices, alpha) at 1x, drawn at ss x with round joins"""
+ r = float(w.max()) / 2 + 3
+ x0, y0 = int(max(0, P[:, 0].min() - r)), int(max(0, P[:, 1].min() - r))
+ x1, y1 = int(min(self.W, P[:, 0].max() + r + 1)), int(min(self.H, P[:, 1].max() + r + 1))
+ if x1 - x0 < 1 or y1 - y0 < 1: return None, None
+ bw, bh = x1 - x0, y1 - y0
+ im = Image.new('L', (bw * ss, bh * ss), 0)
+ d = ImageDraw.Draw(im)
+ Q = (P - np.array([x0, y0], np.float32)) * ss
+ R = np.maximum(w * ss / 2, 0.55)
+ _, N = _normals(Q)
+ A = (Q + N * R[:, None]).tolist(); B = (Q - N * R[:, None]).tolist()
+ for i in range(len(Q) - 1):
+ d.polygon(A[i] + A[i + 1] + B[i + 1] + B[i], fill=255)
+ seg = np.diff(Q, axis=0)
+ seg /= np.linalg.norm(seg, axis=1, keepdims=True) + 1e-6
+ turn = np.concatenate([[1.0], np.sum(seg[1:] * seg[:-1], 1), [1.0]])
+ idx = set(np.flatnonzero(turn < 0.97).tolist()) | set(range(0, len(Q), 3)) | {0, len(Q) - 1}
+ Ql, Rl = Q.tolist(), R.tolist()
+ for i in idx:
+ (x, y), rr = Ql[i], Rl[i]
+ d.ellipse([x - rr, y - rr, x + rr, y + rr], fill=255)
+ return (slice(y0, y1), slice(x0, x1)), np.asarray(im.resize((bw, bh), Image.BOX), np.float32) / 255
+
+ def _put_key(self, sl, a, clip=None):
+ if sl is None: return
+ if clip is not None: a = a * clip[sl]
+ np.maximum(self.key[sl], a, out=self.key[sl])
+
+ def _profile(self, P, width, taper, swell, jitter):
+ n = len(P)
+ s = np.concatenate([[0], np.cumsum(np.hypot(*np.diff(P, axis=0).T))])
+ L = max(float(s[-1]), 1e-3)
+ _, N = _normals(P)
+ if jitter:
+ P = P + N * (fbm1d(n, max(4, 60), 3, self._seed()) * jitter)[:, None]
+ t0 = max(1e-3, min(taper[0] * L, 70.0)) if taper[0] else 1e-3
+ t1 = max(1e-3, min(taper[1] * L, 90.0)) if taper[1] else 1e-3
+ w = width * (1 + swell * np.sin(np.pi * s / L)) * (1 + 0.10 * fbm1d(n, max(4, 40), 3, self._seed()))
+ if taper[0]: w = w * (0.12 + 0.88 * smoothstep(0, t0, s))
+ if taper[1]: w = w * (0.04 + 0.96 * smoothstep(0, t1, L - s))
+ return P.astype(np.float32), w.astype(np.float32)
+
+ def brush(self, pts, width=6.0, taper=(0.25, 0.4), swell=0.2, smooth=True, jitter=0.5, clip=None):
+ """an open brush stroke: lands thin, swells, lifts off to a point"""
+ P, w = self._profile(self._dense(pts, smooth), width, taper, swell, jitter)
+ sl, a = self._ribbon(P, w)
+ self._put_key(sl, a, clip)
+ return P
+
+ def pen(self, pts, width=2.2, smooth=True, taper=(0.08, 0.12), clip=None):
+ """a thin, even crow-quill line for small detail"""
+ P, w = self._profile(self._dense(pts, smooth), width, taper, 0.0, 0.25)
+ sl, a = self._ribbon(P, w)
+ self._put_key(sl, a, clip)
+
+ def dot(self, x, y, r=2.5):
+ self.key = np.maximum(self.key, self.circle(x, y, r))
+
+ def outline(self, pts, width=5.0, heavy=0.9, smooth=None, overlap=0.06, closed=True, taper=(0.03, 0.05), clip=None):
+ """ink round a closed shape in one stroke: heavier on the side away from the light, the two ends
+ overlapping where the brush came back round"""
+ P = np.asarray(pts, np.float32)
+ smooth = (len(P) < 80) if smooth is None else smooth
+ if not closed:
+ return self.edge(P, width, heavy, smooth=smooth, clip=clip)
+ C = self._dense(P, smooth, closed=True)
+ n = len(C)
+ out = _outward(C)
+ i0 = int(self.rng.integers(n))
+ idx = (i0 + np.arange(int(n * (1 + overlap)))) % n
+ Pp, O = C[idx], out[idx]
+ Pr, w = self._profile(Pp, width, taper, 0.0, 0.45)
+ w = w * (1 + heavy * np.clip(-(O @ self.light), -0.6, 1))
+ sl, a = self._ribbon(Pr, w)
+ self._put_key(sl, a, clip)
+ return C
+
+ def edge(self, pts, width=5.0, heavy=0.9, side=None, smooth=True, taper=(0.15, 0.25), clip=None):
+ """an open contour line that also swells where it faces away from the light.
+ side=+1/-1 picks which normal counts as 'outside' (default: the one facing away from the light)"""
+ P = self._dense(pts, smooth)
+ _, N = _normals(P)
+ if side is None:
+ side = 1.0 if float(np.mean(-(N @ self.light))) >= 0 else -1.0
+ Pr, w = self._profile(P, width, taper, 0.1, 0.45)
+ w = w * (1 + heavy * np.clip(-(side * N) @ self.light, -0.6, 1))
+ sl, a = self._ribbon(Pr, w)
+ self._put_key(sl, a, clip)
+ return P
+
+ def ink(self, shape, smooth=False):
+ """spotted black: a solid area of key"""
+ a = self._m(shape, smooth)
+ np.maximum(self.key, a, out=self.key)
+ return a
+
+ def erase(self, shape, smooth=False):
+ """white-out on the key (what a front object hides)"""
+ a = self._m(shape, smooth)
+ self.key *= 1 - a
+ return a
+
+ def mask_outline(self, m, width=5.0, heavy=4.0, clip=None, sl=None):
+ """outline any soft mask (unions of circles, text): an even ring plus a crescent on the shadow side.
+ sl: m is already the crop of the sheet at sl (with room for the line around it)"""
+ if sl is None:
+ sl = self._bbox(m, int(width + heavy + 6))
+ if sl is None: return
+ mm = m[sl]
+ else:
+ mm = m
+ ring = np.clip(self.grow(mm, width * 0.5) - self.shrink(mm, width * 0.5), 0, 1)
+ if heavy:
+ dx, dy = -self.light * heavy
+ cres = np.clip(shift(mm, dx, dy) - mm, 0, 1)
+ cres = smoothstep(0.35, 0.65, blur(cres, 0.8 + heavy * 0.15))
+ ring = np.maximum(ring, cres * self.grow(mm, width * 0.5 + heavy))
+ if clip is not None: ring = ring * clip[sl]
+ np.maximum(self.key[sl], ring, out=self.key[sl])
+
+ def part(self, pts, colour=None, width=5.0, heavy=0.9, smooth=False, line=True, per=10):
+ """a thing in front: erase key and colour under it, paint its flat, ink its outline. Returns its mask"""
+ P = np.asarray(pts, np.float32)
+ C = _closed_spline(P, per) if smooth else P
+ a = self.mask(C)
+ self.key *= 1 - a
+ if colour is not None: self._set(a, colour)
+ if line and width > 0: self.outline(C, width, heavy, smooth=False)
+ return a
+
+ @staticmethod
+ def edge_normals(pts, smooth=False, step=4.0):
+ """points along a closed outline and their outward normals (for feather)"""
+ P = np.asarray(pts, np.float32)
+ if smooth: P = _closed_spline(P, 10)
+ P = _resample(P, step, closed=True)
+ return P, _outward(P)
+
+ def feather(self, P, N, length=40.0, width=3.4, spacing=8.0, thresh=0.1, clip=None, along=None,
+ curl=0.15, toward=None, jitter=1.0):
+ """golden-age feathering: tapered strokes that grow out of a shadow edge into the form -- long in the core
+ of the shadow, shorter toward the light, their lengths drifting in waves rather than ticking like a ruler,
+ each one a little curved and a little off parallel.
+ P, N: edge points and outward normals (see edge_normals). Strokes are made only where the edge faces
+ away from the light (or toward `toward`, a unit vector); `along` forces one direction for all strokes;
+ clip (the shape's own mask) keeps them inside."""
+ P = np.asarray(P, np.float32)
+ N = np.asarray(N, np.float32)
+ s = np.concatenate([[0], np.cumsum(np.hypot(*np.diff(P, axis=0).T))])
+ face = -(N @ self.light) if toward is None else N @ np.asarray(toward, np.float32)
+ face = np.convolve(np.pad(face, 3, mode='edge'), np.ones(7) / 7, mode='valid') # smooth over a few points
+ n = len(P)
+ wav = np.interp(s, np.linspace(0, s[-1] + 1e-3, 64), fbm1d(64, 9, 3, self._seed())) # slow swell
+ chop = np.interp(s, np.linspace(0, s[-1] + 1e-3, 256), fbm1d(256, 6, 2, self._seed())) # quick unevenness
+ r = self.rng
+ last = -1e9
+ for i in range(n):
+ if s[i] - last < spacing * r.uniform(0.7, 1.3): continue
+ f = (face[i] - thresh) / (1 - thresh)
+ if f <= 0.05: continue
+ last = s[i]
+ Ln = length * f ** 0.7 * np.clip(0.62 + 0.38 * wav[i] + 0.3 * chop[i] * jitter, 0.25, 1.15)
+ if Ln < 4: continue
+ dirv = -N[i] if along is None else np.asarray(along, np.float32)
+ tilt = r.normal(0, 0.07 * jitter)
+ ct, st = np.cos(tilt), np.sin(tilt)
+ dirv = np.array([dirv[0] * ct - dirv[1] * st, dirv[0] * st + dirv[1] * ct], np.float32)
+ side = np.array([-dirv[1], dirv[0]], np.float32)
+ cu = curl * r.uniform(0.6, 1.4)
+ p0 = P[i] + N[i] * 1.5
+ mid = p0 + dirv * Ln * 0.5 + side * Ln * cu * 0.3
+ end = p0 + dirv * Ln + side * Ln * cu
+ Pd = _resample(spline(np.array([p0, mid, end], np.float32), 6), 1.2)
+ sd = np.linspace(0, 1, len(Pd))
+ w = width * (0.75 + 0.25 * f) * (1 - sd) ** 1.15 * r.uniform(0.85, 1.15) + 0.2
+ sl, a = self._ribbon(Pd, w.astype(np.float32))
+ self._put_key(sl, a, clip)
+
+ def hatch(self, shape, angle=-30, spacing=9.0, width=2.2, taper=0.3, clip=None, jitter=0.3, smooth=False):
+ """parallel brush hatching clipped to a shape (ground shadows, cast shadows)"""
+ m = self._m(shape, smooth)
+ sl = self._bbox(m, 2)
+ if sl is None: return
+ y0, x0 = sl[0].start, sl[1].start
+ M = m[sl]
+ h, w = M.shape
+ a = np.deg2rad(angle)
+ d = np.array([np.cos(a), -np.sin(a)], np.float32)
+ p = np.array([-d[1], d[0]], np.float32)
+ corners = np.array([[0, 0], [w, 0], [0, h], [w, h]], np.float32)
+ pr, dr = corners @ p, corners @ d
+ ts = np.arange(dr.min(), dr.max(), 1.5, dtype=np.float32)
+ for o in np.arange(pr.min() + spacing * 0.5, pr.max(), spacing):
+ o = o + self.rng.uniform(-0.12, 0.12) * spacing
+ pts = o * p + ts[:, None] * d
+ ix, iy = np.round(pts[:, 0]).astype(int), np.round(pts[:, 1]).astype(int)
+ ok = (ix >= 0) & (iy >= 0) & (ix < w) & (iy < h)
+ inside = np.zeros(len(ts), bool)
+ inside[ok] = M[iy[ok], ix[ok]] > 0.5
+ edges = np.flatnonzero(np.diff(np.concatenate([[0], inside.astype(np.int8), [0]])))
+ for s0, s1 in zip(edges[::2], edges[1::2]):
+ if s1 - s0 < 4: continue
+ seg = pts[s0:s1] + np.array([x0, y0], np.float32)
+ self.brush(seg, width, taper=(taper * 0.5, taper), swell=0.1, smooth=False, jitter=jitter, clip=clip)
+
+ def speed(self, origin, direction, n=7, length=300.0, spread=120.0, width=4.0, gap=0.0, seed=None):
+ """speed lines: a bundle of tapered strokes trailing behind a moving thing (direction = where it came from)"""
+ r = np.random.default_rng(self._seed() if seed is None else seed)
+ d = np.asarray(direction, np.float32); d = d / np.linalg.norm(d)
+ p = np.array([-d[1], d[0]], np.float32)
+ o = np.asarray(origin, np.float32)
+ for i in range(n):
+ off = (i / max(n - 1, 1) - 0.5) * spread + r.normal(0, spread * 0.04)
+ start = o + p * off + d * (gap + r.uniform(0, length * 0.25))
+ L = length * r.uniform(0.45, 1.0)
+ self.brush([start, start + d * L * 0.5, start + d * L], width * r.uniform(0.7, 1.15), taper=(0.05, 0.85),
+ swell=0.0, jitter=0.2)
+
+ # ------------------------------------------------------------ lettering
+ def text_mask(self, text, x, y, size, face='letter', align='centre', leading=1.18, jitter=1.0, rot=0.0,
+ anchor='mm', tracking=0.0):
+ """hand lettering -> (full mask, (x0, y0, x1, y1)). Every glyph is placed by hand: a hair off the
+ baseline and a hair rotated. anchor: 'mm' centres the block on (x, y), 'lt' puts its top-left there."""
+ f = _font(face, size)
+ lines = text.split('\n')
+ r = self.rng
+ asc = f.getbbox('H')[1]
+ cap = f.getbbox('H')[3] - asc
+ lh = size * leading
+ widths = [sum(f.getlength(ch) + tracking * size for ch in ln) - tracking * size for ln in lines]
+ bw = max(widths) if widths else 0
+ bh = cap + lh * (len(lines) - 1)
+ ox = x - bw / 2 if anchor[0] == 'm' else (x - bw if anchor[0] == 'r' else x)
+ oy = y - bh / 2 if anchor[1] == 'm' else (y - bh if anchor[1] == 'b' else y)
+ pad = int(size * 0.6) + 4
+ cw, ch = int(bw + 2 * pad), int(bh + 2 * pad)
+ buf = Image.new('L', (cw * 2, ch * 2), 0)
+ for li, ln in enumerate(lines):
+ lx = (bw - widths[li]) / 2 if align == 'centre' else (bw - widths[li] if align == 'right' else 0)
+ cx = pad + lx
+ by = pad + li * lh
+ for chh in ln:
+ adv = f.getlength(chh) + tracking * size
+ if chh.strip():
+ gsz = int(size * 1.8) + 8
+ g = Image.new('L', (gsz * 2, gsz * 2), 0)
+ f2 = _font(face, size * 2)
+ ImageDraw.Draw(g).text((gsz * 0.5, gsz * 0.5 - asc * 2), chh, font=f2, fill=255)
+ if jitter:
+ g = g.rotate(r.normal(0, 2.2 * jitter), resample=Image.BICUBIC, center=(gsz * 0.5 + f2.getlength(chh) / 2, gsz * 0.5 + cap))
+ dy = r.normal(0, 0.035 * size * jitter)
+ px, py = int(round((cx - gsz * 0.25) * 2)), int(round((by + dy - gsz * 0.25) * 2))
+ reg = buf.crop((px, py, px + gsz * 2, py + gsz * 2))
+ buf.paste(Image.fromarray(np.maximum(np.asarray(reg), np.asarray(g))), (px, py))
+ cx += adv
+ sm = buf.resize((cw, ch), Image.BOX)
+ if rot:
+ sm = sm.rotate(rot, resample=Image.BICUBIC, expand=True)
+ a = np.asarray(sm, np.float32) / 255
+ m = np.zeros((self.H, self.W), np.float32)
+ hh, ww = a.shape
+ X0 = int(round(ox - pad - (ww - cw) / 2)); Y0 = int(round(oy - pad - (hh - ch) / 2))
+ sx0, sy0 = max(0, -X0), max(0, -Y0)
+ dx0, dy0 = max(0, X0), max(0, Y0)
+ dx1, dy1 = min(self.W, X0 + ww), min(self.H, Y0 + hh)
+ if dx1 > dx0 and dy1 > dy0:
+ m[dy0:dy1, dx0:dx1] = a[sy0:sy0 + dy1 - dy0, sx0:sx0 + dx1 - dx0]
+ return m, (ox, oy, ox + bw, oy + bh)
+
+ def letter(self, text, x, y, size=34, face='letter', align='centre', colour=None, **kw):
+ """hand lettering in black (or in a colour on the colour plates). Returns the text block's box"""
+ m, box = self.text_mask(text, x, y, size, face, align, **kw)
+ if colour is None:
+ np.maximum(self.key, m, out=self.key)
+ else:
+ self._set(m, colour)
+ return box
+
+ def balloon(self, text, x, y, size=36, tail=None, kind='speech', pad=(34, 24), width=4.2, face='letter',
+ colour=WHITE, seed=None):
+ """a speech balloon (kind='speech'), a shout ('yell': a jagged burst) or a thought ('thought'), lettered.
+ tail: the point the tail aims at (the speaker's mouth). Returns the balloon mask"""
+ m, (x0, y0, x1, y1) = self.text_mask(text, x, y, size, face, 'centre')
+ cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
+ rx, ry = (x1 - x0) / 2 * 1.16 + pad[0], (y1 - y0) / 2 * 1.30 + pad[1]
+ r = np.random.default_rng(self._seed() if seed is None else seed)
+ if kind == 'yell':
+ spikes = max(10, int((rx + ry) / 22))
+ P = self.burst_pts(cx, cy, rx * 1.12, ry * 1.22, spikes, 0.2, int(r.integers(1 << 30)))
+ elif kind == 'thought': # a cloud: scallops all the way round
+ k = max(9, int((rx + ry) / 16))
+ t = np.linspace(0, 2 * np.pi, k * 16, endpoint=False)
+ bump = np.abs(np.sin(t * k / 2 + r.uniform(0, 3))) ** 0.6
+ P = np.stack([cx + np.cos(t) * rx * (0.96 + 0.12 * bump), cy + np.sin(t) * ry * (0.94 + 0.16 * bump)], 1).astype(np.float32)
+ else:
+ t = np.linspace(0, 2 * np.pi, 120, endpoint=False)
+ wob = 1 + 0.025 * np.sin(3 * t + r.uniform(0, 6)) + 0.015 * np.sin(5 * t + r.uniform(0, 6))
+ P = np.stack([cx + np.cos(t) * rx * wob, cy + np.sin(t) * ry * wob], 1).astype(np.float32)
+ B = self.mask(P)
+ if tail is not None and kind != 'thought':
+ tx, ty = tail
+ ang = np.arctan2((ty - cy) / ry, (tx - cx) / rx)
+ base = []
+ for da in (-0.20, 0.20):
+ base.append((cx + np.cos(ang + da) * rx * 0.86, cy + np.sin(ang + da) * ry * 0.86))
+ mid = ((base[0][0] + base[1][0]) / 2, (base[0][1] + base[1][1]) / 2)
+ bend = np.array([-(ty - mid[1]), tx - mid[0]], np.float32) * 0.12
+ ctrl = (mid[0] + (tx - mid[0]) * 0.5 + bend[0], mid[1] + (ty - mid[1]) * 0.5 + bend[1])
+ T = np.vstack([spline([base[0], ((base[0][0] + ctrl[0]) / 2, (base[0][1] + ctrl[1]) / 2), (tx, ty)], 10),
+ spline([(tx, ty), ((base[1][0] + ctrl[0]) / 2, (base[1][1] + ctrl[1]) / 2), base[1]], 10)])
+ B = np.maximum(B, self.mask(T))
+ if kind == 'thought' and tail is not None: # a trail of shrinking bubbles toward the thinker
+ tx, ty = tail
+ ang = np.arctan2((ty - cy) / ry, (tx - cx) / rx)
+ ex, ey = cx + np.cos(ang) * rx * 1.08, cy + np.sin(ang) * ry * 1.08
+ for k, f in enumerate((0.22, 0.55, 0.85)):
+ bx, by = ex + (tx - ex) * f, ey + (ty - ey) * f
+ B = np.maximum(B, self.circle(bx, by, max(4.0, size * (0.42 - 0.12 * k))))
+ self.key *= 1 - B
+ self._set(B, colour)
+ self.mask_outline(B, width, heavy=width * 0.5)
+ np.maximum(self.key, m, out=self.key)
+ return B
+
+ def caption(self, x0, y0, x1, y1, text, size=30, colour=YELLOW, width=4.0, face='letter', align='left', pad=18):
+ """a caption box: a hand-ruled rectangle of flat colour with lettering"""
+ r = self.rng
+ j = lambda: r.normal(0, 1.2)
+ P = np.array([(x0 + j(), y0 + j()), (x1 + j(), y0 + j()), (x1 + j(), y1 + j()), (x0 + j(), y1 + j())], np.float32)
+ a = self.part(P, colour, width=0, line=False)
+ for i in range(4):
+ p, q = P[i], P[(i + 1) % 4]
+ v = (q - p) / np.linalg.norm(q - p)
+ self.brush([p - v * 2, (p + q) / 2, q + v * 2], width, taper=(0.02, 0.03), swell=0.0, jitter=0.3)
+ if align == 'left':
+ self.letter(text, x0 + pad, y0 + pad, size, face, 'left', anchor='lt')
+ else:
+ self.letter(text, (x0 + x1) / 2, (y0 + y1) / 2, size, face, 'centre')
+ return a
+
+ def sfx(self, text, x, y, size=120, colour=YELLOW, rot=0.0, width=6.0, shade=RED, shade_off=(7, 7), face='logo',
+ tracking=0.04, bounce=0.06):
+ """a sound effect: fat letters, each bounced a little, a colour face, a coloured drop shade, black outline"""
+ f = _font(face, size)
+ widths = [f.getlength(ch) + tracking * size for ch in text]
+ total = sum(widths) - tracking * size
+ a = np.deg2rad(rot)
+ u = np.array([np.cos(a), -np.sin(a)], np.float32)
+ v = np.array([np.sin(a), np.cos(a)], np.float32)
+ M = np.zeros((self.H, self.W), np.float32)
+ s = -total / 2
+ for i, ch in enumerate(text):
+ cxy = np.array([x, y], np.float32) + u * (s + widths[i] / 2)
+ sz = size * (1 + bounce * np.sin(i * 1.7 + 0.5))
+ m, _ = self.text_mask(ch, float(cxy[0]), float(cxy[1] + self.rng.normal(0, size * 0.03)), sz, face,
+ jitter=0, rot=rot + self.rng.normal(0, 4))
+ M = np.maximum(M, m)
+ s += widths[i]
+ if shade is not None:
+ S = np.clip(shift(M, *shade_off) - M, 0, 1)
+ self.key *= 1 - np.maximum(M, S)
+ self._set(S, shade)
+ self.mask_outline(np.maximum(M, shift(M, *shade_off)), width, heavy=0)
+ else:
+ self.key *= 1 - M
+ self._set(M, colour)
+ self.mask_outline(M, width * 0.6, heavy=0)
+ return M
+
+ def logo(self, text, quad, vp=None, depth=28.0, colours=(YELLOW, GOLD, ORANGE), shade=RED, shadow=BLUE,
+ shadow_off=(10, 12), outline=8.0, inner=3.2, face='logo', tracking=0.02, glints=0):
+ """a cover logo: block letters drawn in perspective onto `quad` (top-left, top-right, bottom-right,
+ bottom-left), extruded `depth` px toward the vanishing point `vp`, a face banded light to dark from the top,
+ a coloured extrusion, a drop shadow and a fat black outline round the whole block. Returns the face mask"""
+ f = _font(face, 400)
+ widths = [f.getlength(ch) for ch in text]
+ tw = int(sum(widths) + tracking * 400 * (len(text) - 1)) + 40
+ top = f.getbbox('H')[1]
+ cap = f.getbbox('H')[3] - top
+ src = Image.new('L', (tw, cap + 40), 0)
+ d = ImageDraw.Draw(src)
+ xx = 20
+ for ch, wv in zip(text, widths):
+ d.text((xx, 20 - top), ch, font=f, fill=255)
+ xx += wv + tracking * 400
+ bb = src.getbbox()
+ src = src.crop(bb)
+ sw, sh = src.size
+ Q = np.asarray(quad, np.float32)
+ pad = int(depth + max(abs(shadow_off[0]), abs(shadow_off[1])) + outline + inner + 14)
+ x0, y0 = int(max(0, Q[:, 0].min() - pad)), int(max(0, Q[:, 1].min() - pad))
+ x1, y1 = int(min(self.W, Q[:, 0].max() + pad)), int(min(self.H, Q[:, 1].max() + pad))
+ sl = (slice(y0, y1), slice(x0, x1))
+ w, h = x1 - x0, y1 - y0
+ ss = 2
+ co = _persp([((qx - x0) * ss, (qy - y0) * ss) for qx, qy in Q.tolist()], [(0, 0), (sw, 0), (sw, sh), (0, sh)])
+ face_im = src.transform((w * ss, h * ss), Image.PERSPECTIVE, co, Image.BICUBIC).resize((w, h), Image.BOX)
+ ramp = Image.fromarray(np.tile(np.linspace(0, 255, sh)[:, None], (1, sw)).astype(np.uint8))
+ vmap_im = ramp.transform((w * ss, h * ss), Image.PERSPECTIVE, co, Image.BILINEAR).resize((w, h), Image.BOX)
+ F = np.asarray(face_im, np.float32) / 255
+ V = np.asarray(vmap_im, np.float32) / 255
+ U = F.copy()
+ if vp is not None and depth > 0: # extrude: the face shrunk step by step toward vp
+ Fi = Image.fromarray((F * 255).astype(np.uint8))
+ vx, vy = vp
+ dist = float(np.hypot(Q[:, 0].mean() - vx, Q[:, 1].mean() - vy)) + 1e-3
+ for k in np.linspace(0, 1, max(8, int(depth * 1.2)))[1:]:
+ sc = 1 - depth / dist * k
+ coef = (1 / sc, 0, (x0 - vx) / sc + vx - x0, 0, 1 / sc, (y0 - vy) / sc + vy - y0)
+ np.maximum(U, np.asarray(Fi.transform((w, h), Image.AFFINE, coef, Image.BILINEAR), np.float32) / 255, out=U)
+ E = np.clip(U - F, 0, 1)
+ Sd = np.clip(shift(U, *shadow_off) - U, 0, 1) if shadow is not None else None
+ self.key[sl] *= 1 - (U if Sd is None else np.maximum(U, Sd))
+ if Sd is not None: self._set(Sd, shadow, sl)
+ self._set(E, shade, sl)
+ n = len(colours)
+ band = np.clip((V * n).astype(np.int32), 0, n - 1)
+ for i, col in enumerate(colours):
+ self._set(F * (band == i), col, sl)
+ if glints:
+ r = self.rng
+ for _ in range(glints):
+ gx = r.uniform(Q[0, 0] + 30, Q[1, 0] - 30)
+ gy = np.interp(gx, [Q[0, 0], Q[1, 0]], [Q[0, 1], Q[1, 1]])
+ hgt = np.interp(gx, [Q[3, 0], Q[2, 0]], [Q[3, 1], Q[2, 1]]) - gy
+ p0 = (gx, gy + hgt * 0.12); p1 = (gx + hgt * 0.10, gy + hgt * 0.36)
+ g = self.mask(self.tube_pts([p0, p1], [hgt * 0.035, hgt * 0.05]))[sl]
+ self._set(g * F, WHITE, sl)
+ self.mask_outline(U, outline, heavy=outline * 0.4, sl=sl)
+ if inner:
+ ring = np.clip(self.grow(F, inner * 0.5) - self.shrink(F, inner * 0.5), 0, 1)
+ np.maximum(self.key[sl], ring * self.grow(U, 1), out=self.key[sl])
+ out = np.zeros((self.H, self.W), np.float32)
+ out[sl] = F
+ return out
+
+ # ------------------------------------------------------------ press
+ STRIP = 180 # the press works in bands of rows (keeps the memory small)
+
+ def _rows(self):
+ for y0 in range(0, self.H, self.STRIP):
+ yield y0, min(self.H, y0 + self.STRIP)
+
+ def _screen_maps(self):
+ """per plate: the Ben-Day spot function, its anti-aliasing width, ink density, ragged-edge noise and paper
+ pits (kept as float16), plus each colour separation's hand-painted wander"""
+ if self._press_cache is not None: return self._press_cache
+ H, W = self.H, self.W
+ r = np.random.default_rng(self.seed + 4242)
+ g = np.linspace(0, 1, 257)[:-1]
+ uu, vv = np.meshgrid(g, g)
+ sref = np.sort((0.5 - 0.25 * (np.cos(2 * np.pi * uu) + np.cos(2 * np.pi * vv))).ravel())
+ cache = {'cdf': (np.linspace(0, 1, len(sref)).astype(np.float32), sref.astype(np.float32))}
+ for p in 'CMYK':
+ ang = np.deg2rad(SCREEN_ANGLE[p])
+ ph = r.uniform(0, 1, 2)
+ n1 = _norm_noise(r, H, W, 0.9)
+ n2 = noise2d(H, W, self.pitch * 1.2, 1, int(r.integers(1 << 30)))
+ S16, F16 = np.empty((H, W), np.float16), np.empty((H, W), np.float16)
+ for y0, y1 in self._rows():
+ X, Y = self.XX[y0:y1], self.YY[y0:y1]
+ u = 2 * np.pi * ((X * np.cos(ang) + Y * np.sin(ang)) / self.pitch + ph[0])
+ v = 2 * np.pi * ((-X * np.sin(ang) + Y * np.cos(ang)) / self.pitch + ph[1])
+ su, sv = np.sin(u), np.sin(v)
+ S16[y0:y1] = 0.5 - 0.25 * (np.cos(u) + np.cos(v)) + 0.022 * n1[y0:y1] + 0.03 * (n2[y0:y1] - 0.5)
+ F16[y0:y1] = np.maximum(0.25 * 2 * np.pi / self.pitch * np.sqrt(su * su + sv * sv), 0.03)
+ del n1, n2
+ dens = (0.86 if p != 'K' else 0.94) + (0.16 if p != 'K' else 0.06) * noise2d(H, W, 70, 3, int(r.integers(1 << 30)))
+ dens *= 1 - 0.10 * (noise2d(H, W, 6, 2, int(r.integers(1 << 30))) - 0.5)
+ rag = (_norm_noise(r, H, W, 0.75) * 0.11).astype(np.float16)
+ pits = smoothstep(0.80, 0.93, self.tooth + 0.08 * _norm_noise(r, H, W, 0.5)).astype(np.float16)
+ cache[p] = (S16, F16, dens.astype(np.float16), rag, pits)
+ if self.slop:
+ cache['slop'] = {p: ((noise2d(H, W, 140, 2, int(r.integers(1 << 30))) - 0.5).astype(np.float16),
+ (noise2d(H, W, 140, 2, int(r.integers(1 << 30))) - 0.5).astype(np.float16)) for p in 'CMY'}
+ self._press_cache = cache
+ return cache
+
+ def _warp(self, a, p, a0, a1, slop=None):
+ """rows a0..a1 of a plate as it actually lands: misregistration (+ the separation's hand-painted wander)"""
+ dx, dy, rot = self.reg.get(p, (0, 0, 0))
+ if not dx and not dy and not rot and slop is None: return a[a0:a1]
+ th = np.deg2rad(rot)
+ cx, cy = self.W / 2, self.H / 2
+ XX, YY = self.XX[a0:a1] - cx - dx, self.YY[a0:a1] - cy - dy
+ X = cx + XX * np.cos(th) - YY * np.sin(th)
+ Y = cy + XX * np.sin(th) + YY * np.cos(th)
+ if slop is not None:
+ X += slop[0][a0:a1] * (2 * self.slop)
+ Y += slop[1][a0:a1] * (2 * self.slop)
+ X = np.clip(X, 0, self.W - 1.001); Y = np.clip(Y, 0, self.H - 1.001)
+ x0 = X.astype(np.int32); y0 = Y.astype(np.int32)
+ fx = X - x0; fy = Y - y0
+ return (a[y0, x0] * (1 - fx) + a[y0, x0 + 1] * fx) * (1 - fy) + (a[y0 + 1, x0] * (1 - fx) + a[y0 + 1, x0 + 1] * fx) * fy
+
+ def _screen(self, t, p, cache, a0, a1, gain=0.06):
+ """tint -> Ben-Day dots: a threshold on the plate's spot function (with dot gain); 100 % prints solid"""
+ s, fw = cache[p][0][a0:a1].astype(np.float32), cache[p][1][a0:a1].astype(np.float32)
+ cdf_t, sref = cache['cdf']
+ t = np.clip(t, 0, 1)
+ t2 = np.clip(t + gain * 4 * t * (1 - t), 0, 1) # dot gain peaks at mid tones
+ tau = np.interp(t2, cdf_t, sref).astype(np.float32)
+ tau = np.where(t2 > 0.985, 1.5, tau)
+ ink = np.clip((tau - s) / fw + 0.5, 0, 1)
+ return ink * smoothstep(0.015, 0.05, t)
+
+ def _soak(self, cov, p, cache, a0, a1):
+ """newsprint drinks the ink: edges spread and go ragged, tiny dots drop out, pits stay bare"""
+ rag, pits = cache[p][3][a0:a1], cache[p][4][a0:a1]
+ b = blur(cov, 0.7)
+ out = smoothstep(0.2, 0.8, b + rag)
+ return out * (1 - (0.55 if p != 'K' else 0.35) * pits * smoothstep(0.6, 1.0, b))
+
+ def _print(self, snap, plates, nwear):
+ cache = self._screen_maps()
+ img = self.paper_rgb.copy()
+ pad = 6
+ for y0, y1 in self._rows():
+ a0, a1 = max(0, y0 - pad), min(self.H, y1 + pad)
+ for p in 'YMCK':
+ if p not in plates: continue
+ if p == 'K':
+ t = self._warp(snap['k'], 'K', a0, a1)
+ cov = np.maximum(self._screen(t, 'K', cache, a0, a1), self._warp(snap['key'], 'K', a0, a1))
+ else:
+ t = self._warp(snap[p], p, a0, a1, cache['slop'][p] if self.slop else None)
+ cov = self._screen(t, p, cache, a0, a1)
+ cov = self._soak(cov, p, cache, a0, a1)[y0 - a0:y1 - a0]
+ a = cov * cache[p][2][y0:y1]
+ img[y0:y1] *= 1 - a[..., None] * (1 - INK[p])[None, None, :]
+ for op in self.wear_ops[:nwear]:
+ img = op(img)
+ return np.clip(img, 0, 1)
+
+ def _snap(self):
+ q = lambda a: (np.clip(a, 0, 1) * 255 + 0.5).astype(np.uint8)
+ return {'C': q(self.g['C']), 'M': q(self.g['M']), 'Y': q(self.g['Y']), 'k': q(self.g['k']), 'key': q(self.key)}
+
+ @staticmethod
+ def _unsnap(s):
+ return {k: v.astype(np.float32) / 255 for k, v in s.items()}
+
+ # ------------------------------------------------------------ afterlife (wear)
+ # every wear op is kept as a closure and applied after printing, only inside its own region
+
+ def brown_edges(self, width=60.0, amount=1.0, colour=(0.80, 0.64, 0.42)):
+ """the cover browned from the edges inward, unevenly"""
+ H, W = self.H, self.W
+ nz = noise2d(H, W, 150, 3, self._seed()).astype(np.float16)
+ col = 1 - np.asarray(colour, np.float32)
+
+ def op(img):
+ for y0, y1 in self._rows():
+ X, Y = self.XX[y0:y1], self.YY[y0:y1]
+ d = np.minimum(np.minimum(X, W - 1 - X), np.minimum(Y, H - 1 - Y))
+ f = np.clip(np.exp(-d / (width * (0.6 + 0.8 * nz[y0:y1]))) * amount, 0, 1)
+ img[y0:y1] *= 1 - f[..., None] * col
+ return img
+ self.wear_ops.append(op)
+
+ def spine(self, x=0.0, ticks=70, staples=(0.27, 0.73), reach=46.0):
+ """the left edge is the spine fold: a soft roll, white stress ticks where the ink cracked, two staples
+ with rust halos"""
+ H = self.H
+ RW = int(x + reach + 30)
+ r = np.random.default_rng(self._seed())
+ im = Image.new('L', (RW, H), 0)
+ d = ImageDraw.Draw(im)
+ for i in range(ticks):
+ y = r.uniform(10, H - 10)
+ L = reach * r.uniform(0.15, 1.0) ** 1.6
+ a = r.normal(0, 0.12)
+ n = max(3, int(L / 3))
+ xs = x + 2 + np.linspace(0, L, n)
+ ys = y + np.sin(a) * np.linspace(0, L, n) + r.normal(0, 0.7, n)
+ wv = r.uniform(1.0, 2.4)
+ for k in range(n - 1):
+ d.line([(xs[k], ys[k]), (xs[k + 1], ys[k + 1])], fill=255, width=max(1, int(round(wv * (1 - k / n) + 0.3))))
+ tick = blur(np.asarray(im, np.float32) / 255, 0.5)[..., None]
+ X, Y = self.XX[:, :RW], self.YY[:, :RW]
+ rust = 1 - np.array([0.62, 0.40, 0.22], np.float32)
+ rust2 = 1 - np.array([0.55, 0.32, 0.15], np.float32)
+
+ def op(img):
+ sub = img[:, :RW]
+ sub *= 1 - 0.10 * np.exp(-((X - x - 9) / 5.0) ** 2)[..., None]
+ sub += 0.04 * np.exp(-((X - x - 15) / 4.0) ** 2)[..., None]
+ sub *= 1 - tick
+ sub += np.clip(self.paper_rgb[:, :RW] * 1.04, 0, 1) * tick
+ for f in staples:
+ yc = H * f
+ y0, y1 = int(max(0, yc - 90)), int(min(H, yc + 90))
+ s2, Xs, Ys = sub[y0:y1], X[y0:y1], Y[y0:y1]
+ halo = np.exp(-(((Xs - x - 12) / 9.0) ** 2 + ((Ys - yc) / 44.0) ** 4))
+ s2 *= 1 - 0.30 * halo[..., None] * rust
+ bar = (np.clip(2.2 - np.abs(Xs - x - 12), 0, 1) * np.clip(31 - np.abs(Ys - yc), 0, 1))[..., None]
+ sheen = 0.52 + 0.32 * np.clip(1 - np.abs(Xs - x - 11.3) / 1.6, 0, 1) - 0.12 * ((Ys - yc) / 31) ** 2
+ metal = sheen[..., None] * np.array([0.97, 0.95, 0.92], np.float32)
+ s2 *= 1 - bar
+ s2 += metal * bar
+ for end in (-1, 1):
+ ex = np.exp(-(((Xs - x - 12) / 3.0) ** 2 + ((Ys - yc - end * 31) / 3.5) ** 2))
+ s2 *= 1 - 0.35 * ex[..., None] * rust2
+ return img
+ self.wear_ops.append(op)
+
+ def corner(self, which='br', radius=70.0, fold=True):
+ """a rubbed, dog-eared corner: ink scuffed off toward the tip, a small diagonal crease"""
+ H, W = self.H, self.W
+ cx = W - 1 if which[1] == 'r' else 0
+ cy = H - 1 if which[0] == 'b' else 0
+ R = int(radius + 4)
+ ys = slice(max(0, cy - R), cy + 1) if cy else slice(0, R)
+ xs = slice(max(0, cx - R), cx + 1) if cx else slice(0, R)
+ X, Y = self.XX[ys, xs], self.YY[ys, xs]
+ h, w = X.shape
+ nz = noise2d(h, w, 9, 3, self._seed())
+ fib = _norm_noise(np.random.default_rng(self._seed()), h, w, 0.7)
+ rub = np.clip(1 - np.hypot(X - cx, Y - cy) / radius, 0, 1) ** 1.5
+ rub = (smoothstep(0.25, 0.75, rub + 0.45 * (nz - 0.5) + 0.12 * fib) * 0.85)[..., None]
+
+ def op(img):
+ img[ys, xs] = img[ys, xs] * (1 - rub) + self.paper_rgb[ys, xs] * 0.98 * rub
+ return img
+ self.wear_ops.append(op)
+ if fold:
+ sx = -1 if which[1] == 'r' else 1
+ sy = -1 if which[0] == 'b' else 1
+ self.crease((cx + sx * radius * 0.95, cy + sy * 2), (cx + sx * 2, cy + sy * radius * 0.85), 1.0)
+
+ def crease(self, p0, p1, strength=1.0):
+ """a colour-breaking crease from p0 to p1: a cracked white line with a soft roll beside it"""
+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)
+ pad = 12
+ ys = slice(int(max(0, min(p0[1], p1[1]) - pad)), int(min(self.H, max(p0[1], p1[1]) + pad + 1)))
+ xs = slice(int(max(0, min(p0[0], p1[0]) - pad)), int(min(self.W, max(p0[0], p1[0]) + pad + 1)))
+ X, Y = self.XX[ys, xs], self.YY[ys, xs]
+ d = p1 - p0
+ L = float(np.linalg.norm(d)) + 1e-6
+ u = d / L
+ n = np.array([-u[1], u[0]], np.float32)
+ t = ((X - p0[0]) * u[0] + (Y - p0[1]) * u[1]) / L
+ off = (X - p0[0]) * n[0] + (Y - p0[1]) * n[1]
+ o = off - np.interp(t, np.linspace(0, 1, 64), fbm1d(64, 10, 3, self._seed()) * 2.0)
+ inside = smoothstep(-0.02, 0.03, t) * smoothstep(-0.02, 0.03, 1 - t)
+ h, w = X.shape
+ crack = (np.exp(-(o / 0.9) ** 2) * inside * smoothstep(0.35, 0.6, noise2d(h, w, 7, 2, self._seed())) * strength)[..., None]
+ shade = (0.10 * strength * np.exp(-((o - 4) / 4.0) ** 2) * inside)[..., None]
+ lift = (0.05 * strength * np.exp(-((o + 3) / 3.0) ** 2) * inside)[..., None]
+
+ def op(img):
+ sub = img[ys, xs] * (1 - shade) + lift
+ img[ys, xs] = sub * (1 - crack) + self.paper_rgb[ys, xs] * 1.03 * crack
+ return img
+ self.wear_ops.append(op)
+
+ def foxing(self, n=40, colour=(0.66, 0.46, 0.24)):
+ """small rusty-brown age spots"""
+ r = np.random.default_rng(self._seed())
+ col = 1 - np.asarray(colour, np.float32)
+ spots = []
+ for i in range(n):
+ x, y = r.uniform(0, self.W), r.uniform(0, self.H)
+ if r.random() < 0.5:
+ x = r.choice([r.uniform(0, 160), r.uniform(self.W - 160, self.W)])
+ rr = r.uniform(1.5, 7) * (1 + 2 * (r.random() < 0.1))
+ k = int(rr * 2 + 6)
+ x0, y0 = int(max(0, x - k)), int(max(0, y - k))
+ x1, y1 = int(min(self.W, x + k + 1)), int(min(self.H, y + k + 1))
+ if x1 <= x0 or y1 <= y0: continue
+ im = Image.new('L', (x1 - x0, y1 - y0), 0)
+ ImageDraw.Draw(im).ellipse([x - rr - x0, y - rr - y0, x + rr - x0, y + rr - y0], fill=int(r.uniform(40, 105)))
+ spots.append((slice(y0, y1), slice(x0, x1), blur(np.asarray(im, np.float32) / 255, 1.6)[..., None]))
+
+ def op(img):
+ for ys, xs, f in spots:
+ img[ys, xs] *= 1 - f * col
+ return img
+ self.wear_ops.append(op)
+
+ # ------------------------------------------------------------ output
+ def stage(self, name, plates='CMYK'):
+ """keep the plates as they are now; on save they are proofed with only `plates` printed"""
+ self.stages.append((name, plates, self._snap(), len(self.wear_ops)))
+
+ def render(self, plates='CMYK'):
+ snap = {k: v for k, v in self.g.items()}
+ snap['key'] = self.key
+ img = self._print(snap, plates, len(self.wear_ops))
+ return Image.fromarray((img * 255 + 0.5).astype(np.uint8))
+
+ def save(self, path, stages_dir=None, quality=88):
+ img = self.render()
+ 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, plates, snap, nw) in enumerate(self.stages):
+ im = self._print(self._unsnap(snap), plates, nw)
+ Image.fromarray((im * 255 + 0.5).astype(np.uint8)).save(f"{stages_dir}/{i:02d}_{name}.png")
+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")
+ return img
diff --git a/lib/constructivism.py b/lib/constructivism.py
new file mode 100644
index 0000000..4e50e8f
--- /dev/null
+++ b/lib/constructivism.py
@@ -0,0 +1,892 @@
+"""constructivism -- a Soviet constructivist poster of the 1920s, printed in two inks (numpy + Pillow only).
+
+A red disc, a black diagonal, a wedge, slabs of heavy condensed Cyrillic, and photographs cut out with scissors and
+screened into a coarse 45-degree halftone: the photomontage poster as it came off a two-colour press onto cheap,
+cream paper, and as it looks a century later.
+
+Model: the poster is one sheet and two printing plates.
+ plates everything red is on the red plate, everything black (solids, type, every halftone dot of every
+ photograph) is on the black plate. A plate is a coverage map 0..1. Drawing is "ink this mask on that
+ plate" or "knock this mask out of these plates" (the paper shows). The plates are only put on paper
+ in composite(), each with its own registration error -- one small shift plus a hair of rotation for the
+ whole plate -- so all red moves together against all black: wherever the designer made red and black
+ meet, a sliver of bare paper opens on one side and a dark overprint on the other.
+ inks printing ink is a transparent filter, so the ink colours multiply with the paper and with each other:
+ black over red prints a deep warm black, red over the paper picks up the paper's yellow. The ink film
+ is never quite even: big soft blotches of more and less ink, a fine mottle, a few voids where a fibre
+ or a speck of dust kept the plate from touching, an edge that is ragged at the scale of the paper's
+ fibres, and a slightly heavier squeeze of ink along the edge of every solid (letterpress halo).
+ photo a "photograph" is really rendered: `Photo` is a tiny z-buffer rasteriser for triangle meshes (cylinders,
+ lathes, swept tubes, boxes, hyperboloid lattices) in a perspective camera, shaded like a studio or
+ outdoor photo (key + fill + sky light, Blinn highlights, an environment for metal, haze with distance,
+ a slightly soft lens and film grain), giving a grey-tone image and a silhouette.
+ montage the photomontage step: a photo is scaled, rotated and placed on the poster, then -- like the whole
+ paste-up being re-photographed for the plate -- screened in poster space into an AM halftone on the
+ black plate: round dots on a 45-degree screen that grow, touch in a chequerboard at 50 % and leave only
+ white holes in the shadows, with dot gain and fibre-ragged dot edges. `cut=` cuts the print out along
+ its silhouette with a margin (scissors: a slightly wandering offset path), and the cut piece covers
+ whatever was printed under it, so it shows as a pale paper outline with the faint highlight dots of
+ the photographic backdrop; without `cut` the photo is retouched out of its background and the dots
+ print straight over the red.
+ type heavy condensed grotesque (Helvetica Neue Condensed Black, else Impact / DejaVu Sans Condensed Bold)
+ for the slabs, a squarer condensed face (DIN Condensed, else Arial Narrow / PT Sans Narrow) for labels,
+ Futura Bold for small geometric captions; any font missing a Cyrillic glyph is skipped for the next.
+ Big lettering can be given a hand-drawn `wobble` (a sub-pixel low-frequency warp of the outline).
+ paper cheap uncoated poster paper: cream, cloudy pulp, short fibres and dark flecks, a little cockle,
+ yellowing and greying toward the edges.
+ age a hundred years later: the folds it was posted in (a lit ridge and a dark valley, a band of grime,
+ the ink cracked off in a broken line along the crease), foxing, a faint water-stain tide line,
+ rubbed corners, drawing-pin holes.
+Coordinates are pixels, y down. Angles are degrees counter-clockwise from 3 o'clock; `rot` of text and photos is
+counter-clockwise too (so a line of type rising to the right has a positive rot).
+
+ from constructivism import Constructivism, Photo
+ c = Constructivism(1920, 1080, seed=3)
+ c.paper()
+ c.ink(c.circle(420, 260, 200), 'red')
+ c.ink(c.wedge((420, 260), -25, 8, 1700), 'red')
+ c.waves(420, 260, 180, 1500, 64, 14, -36, -14, plates=('black',))
+ c.ink(c.bar(560, 1000, 1920, 560, 96), 'black', knock=c.text_mask('СЛУШАЙТЕ', 760, 935, 70, anchor='lm', rot=18))
+ p = Photo(600, 900, eye=(-40, -60, 2), target=(0, 0, 40), fov=60)
+ steel = p.material(albedo=0.12)
+ p.hyperboloid(0, 25, 20, 15, 16, 67.5, steel, member=0.5); p.hyperboloid(25, 50, 15, 11, 12, 90, steel, member=0.4)
+ c.montage(p, 420, 620, cell=5.5) # retouched, printed over the red
+ c.montage(other_photo, 1500, 600, rot=10, cut=13, close=16) # cut out with scissors, covers what is under
+ c.text('РАДИО', 1860, 330, 330, 'black', anchor='rs')
+ c.age(folds=(1, 1))
+ c.save('out.jpg')
+"""
+import glob
+import os
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+from core import blur, noise2d, smoothstep, fbm1d
+
+RED, BLACK = '#c9302a', '#1d1b1a'
+PAPER, AGED = '#ebe0c6', '#d6c08f'
+PLATES = ('red', 'black')
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+def _c(c):
+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)
+
+
+# ---------------------------------------------------------------- fonts (kept inside this module)
+_CHAINS = {
+ 'grotesk': [('/System/Library/Fonts/HelveticaNeue.ttc', ('Condensed Black',)),
+ ('/System/Library/Fonts/Supplemental/Impact.ttf', None),
+ ('/usr/share/fonts/**/DejaVuSansCondensed-Bold.ttf', None),
+ ('C:/Windows/Fonts/impact.ttf', None)],
+ 'din': [('/System/Library/Fonts/Supplemental/DIN Condensed Bold.ttf', None),
+ ('/System/Library/Fonts/Supplemental/Arial Narrow Bold.ttf', None),
+ ('/System/Library/Fonts/PTSans.ttc', ('Narrow', 'Bold')),
+ ('/usr/share/fonts/**/DejaVuSansCondensed-Bold.ttf', None),
+ ('C:/Windows/Fonts/ARIALNB.TTF', None)],
+ 'narrow': [('/System/Library/Fonts/HelveticaNeue.ttc', ('Condensed Bold',)),
+ ('/System/Library/Fonts/Supplemental/Arial Narrow Bold.ttf', None),
+ ('/usr/share/fonts/**/DejaVuSansCondensed-Bold.ttf', None),
+ ('C:/Windows/Fonts/ARIALNB.TTF', None)],
+ 'futura': [('/System/Library/Fonts/Supplemental/Futura.ttc', ('Bold',)),
+ ('/System/Library/Fonts/Avenir Next.ttc', ('Bold',)),
+ ('/usr/share/fonts/**/DejaVuSans-Bold.ttf', None),
+ ('C:/Windows/Fonts/arialbd.ttf', None)],
+}
+_FACES, _FONTS, _HAS = {}, {}, {}
+
+
+def _faces(style):
+ """all usable (path, index) faces for a style, best first; $INKPAINT_FONT_<STYLE> goes in front"""
+ if style in _FACES: return _FACES[style]
+ out = []
+ env = os.environ.get('INKPAINT_FONT_' + style.upper())
+ if env and os.path.exists(env): out.append((env, 0))
+ for pat, want in _CHAINS.get(style, _CHAINS['grotesk']):
+ for path in glob.glob(pat, recursive=True)[:1]:
+ if want is None:
+ out.append((path, 0)); continue
+ for i in range(40):
+ try:
+ f = ImageFont.truetype(path, 20, index=i)
+ except (OSError, ValueError):
+ break
+ name = ' '.join(f.getname())
+ if all(w in name for w in want) and 'Italic' not in name and 'Oblique' not in name:
+ out.append((path, i)); break
+ _FACES[style] = out
+ return out
+
+
+def _font_of(face, size):
+ k = (face, int(round(size)))
+ if k not in _FONTS:
+ _FONTS[k] = ImageFont.truetype(face[0], max(4, int(round(size))), index=face[1])
+ return _FONTS[k]
+
+
+def _has(face, ch):
+ k = (face, ch)
+ if k not in _HAS:
+ f = _font_of(face, 48)
+ a, b = f.getmask(ch), f.getmask('\U0010fffd')
+ _HAS[k] = ch.isspace() or (a.getbbox() is not None and not (a.size == b.size and bytes(a) == bytes(b)))
+ return _HAS[k]
+
+
+def font(style, size, s=''):
+ """PIL font for `style` ('grotesk', 'din', 'narrow', 'futura') whose face has every glyph of `s`"""
+ faces = _faces(style) or _faces('grotesk')
+ for face in faces:
+ if all(_has(face, ch) for ch in s):
+ return _font_of(face, size)
+ if faces: return _font_of(faces[0], size)
+ from core import load_font
+ return load_font('sans_bold', size)
+
+
+# ---------------------------------------------------------------- small helpers
+def _rotate(a, deg, center=None, expand=False):
+ im = Image.fromarray(a.astype(np.float32), 'F')
+ return np.asarray(im.rotate(deg, resample=Image.BILINEAR, center=center, expand=expand), np.float32)
+
+
+def _warp(a, dx, dy):
+ """sample a at (x + dx, y + dy), bilinear, clamped"""
+ h, w = a.shape
+ Y, X = np.mgrid[0:h, 0:w].astype(np.float32)
+ x = np.clip(X + dx, 0, w - 1.001); y = np.clip(Y + dy, 0, h - 1.001)
+ x0, y0 = x.astype(np.int32), y.astype(np.int32)
+ fx, fy = x - x0, y - y0
+ return ((a[y0, x0] * (1 - fx) + a[y0, x0 + 1] * fx) * (1 - fy)
+ + (a[y0 + 1, x0] * (1 - fx) + a[y0 + 1, x0 + 1] * fx) * fy)
+
+
+def _dilate(m, r):
+ """dilate a 0..1 mask by a disc of radius r px (max over shifted copies, done in 2-px steps)"""
+ out = m.copy()
+ offs = [(dx, dy) for dx in range(-2, 3) for dy in range(-2, 3) if dx * dx + dy * dy <= 5]
+ steps, rest = int(r // 2), r - 2 * int(r // 2)
+ for _ in range(steps):
+ p = np.pad(out, 2)
+ h, w = out.shape
+ out = np.max([p[2 + dy:2 + dy + h, 2 + dx:2 + dx + w] for dx, dy in offs], axis=0)
+ if rest > 0.3:
+ p = np.pad(out, 1)
+ h, w = out.shape
+ out = np.max([p[1 + dy:1 + dy + h, 1 + dx:1 + dx + w] for dx in (-1, 0, 1) for dy in (-1, 0, 1)
+ if dx * dx + dy * dy <= 1], axis=0)
+ return out
+
+
+def _fill_holes(m):
+ """binary mask -> the same with every enclosed hole filled (flood the outside from a padded corner)"""
+ im = Image.fromarray(np.pad((m > 0.5).astype(np.uint8) * 255, 1)).copy() # copy: floodfill needs a writable image
+ ImageDraw.floodfill(im, (0, 0), 128)
+ return (np.asarray(im)[1:-1, 1:-1] != 128).astype(np.float32)
+
+
+def halftone(dark, X, Y, cell=7.0, angle=45.0, rough=None, gain=0.55, soften=0.3):
+ """AM halftone: darkness 0..1 -> ink coverage 0..1, evaluated at poster coordinates X, Y (so every photo on the
+ sheet shares one screen). Round dots that grow with darkness, touch in a chequerboard at 50 % and leave white
+ holes in the shadows. rough: a fibre-noise field that roughens the dot edges; gain: dot gain blur (px)."""
+ d = blur(dark, cell * soften) if soften else dark
+ a = np.deg2rad(angle)
+ u = (X * np.cos(a) + Y * np.sin(a)) / cell
+ v = (-X * np.sin(a) + Y * np.cos(a)) / cell
+ su, sv = np.sin(2 * np.pi * u), np.sin(2 * np.pi * v)
+ spot = 0.5 - 0.25 * (np.cos(2 * np.pi * u) + np.cos(2 * np.pi * v))
+ grad = (np.pi / (2 * cell)) * np.sqrt(su * su + sv * sv) + 0.04
+ if rough is not None:
+ spot = spot + rough
+ ink = np.clip((d - spot) / grad + 0.5, 0, 1) * smoothstep(0.0, 0.035, d)
+ ink = np.maximum(ink, smoothstep(0.94, 1.0, d))
+ if gain:
+ ink = np.clip(blur(ink, gain) * 1.1, 0, 1)
+ return ink.astype(np.float32)
+
+
+# ---------------------------------------------------------------- the photograph
+class Photo:
+ """A tiny perspective z-buffer rasteriser that 'photographs' simple meshes in grey tones.
+ World units are metres, Z is up. Build with cylinder / lathe / sweep / box / hyperboloid, then render()
+ (once: rendering frees the buffers and caches the result)."""
+
+ def __init__(self, w, h, eye, target, up=(0, 0, 1), fov=40.0, ss=2, seed=0, key=(-0.55, -0.65, 0.55),
+ fill=(0.75, -0.25, 0.15), key_k=1.0, fill_k=0.3, amb=0.32, exposure=1.0, haze=0.0,
+ haze_tone=0.9, grain=0.025, lens=0.6, shift=(0.0, 0.0)):
+ """shift: lens shift (fraction of the frame) -- moves the picture without tilting the camera"""
+ self.w, self.h, self.ss = w, h, ss
+ self.E = np.array(eye, np.float64)
+ f = np.array(target, np.float64) - self.E; f /= np.linalg.norm(f)
+ r = np.cross(f, np.array(up, np.float64)); r /= np.linalg.norm(r)
+ u = np.cross(r, f)
+ self.R = np.stack([r, u, f])
+ self.focal = 0.5 * w / np.tan(np.deg2rad(fov) / 2)
+ self.cx, self.cy = w / 2 + shift[0] * w, h / 2 + shift[1] * h
+ H, W = h * ss, w * ss
+ self.z = np.full((H, W), np.inf, np.float32)
+ self.n = np.zeros((H, W, 3), np.float32)
+ self.pos = np.zeros((H, W, 3), np.float32)
+ self.mat = np.full((H, W), -1, np.int16)
+ self.mats = []
+ self.rng = np.random.default_rng(seed)
+ self.key = np.array(key, np.float32) / np.linalg.norm(key)
+ self.fill = np.array(fill, np.float32) / np.linalg.norm(fill)
+ self.key_k, self.fill_k, self.amb, self.exposure = key_k, fill_k, amb, exposure
+ self.haze, self.haze_tone, self.grain, self.lens = haze, haze_tone, grain, lens
+ self._out = None
+
+ def material(self, albedo=0.5, gloss=0.15, shine=20.0, metal=0.0, tex=None, interior=0.3, haze=True):
+ """returns a material id. tex(pos (k,3), normal (k,3)) -> albedo multiplier (k,) for procedural texture.
+ interior: how dark the inside (back faces) of an open shape looks"""
+ self.mats.append(dict(albedo=albedo, gloss=gloss, shine=shine, metal=metal, tex=tex, interior=interior,
+ haze=haze))
+ return len(self.mats) - 1
+
+ def project(self, P):
+ """world points (n, 3) -> screen x, y (output pixels) and depth"""
+ p = (np.asarray(P, np.float64) - self.E) @ self.R.T
+ z = p[:, 2]
+ return self.cx + self.focal * p[:, 0] / z, self.cy - self.focal * p[:, 1] / z, z
+
+ # ------------------------------------------------------------ rasteriser
+ def mesh(self, V, N, F, mid):
+ """triangles F (m, 3) over vertices V (n, 3) with vertex normals N (n, 3)"""
+ if self.z is None:
+ raise RuntimeError('this Photo has already been rendered; build a new one to add more objects')
+ V = np.asarray(V, np.float64); N = np.asarray(N, np.float32); F = np.asarray(F, np.int64)
+ sx, sy, z = self.project(V)
+ ss = self.ss
+ sx, sy = sx * ss, sy * ss
+ H, W = self.z.shape
+ for tri in F:
+ i, j, k = tri
+ z0, z1, z2 = z[i], z[j], z[k]
+ if min(z0, z1, z2) < 0.05: continue
+ x0, x1, x2 = sx[i], sx[j], sx[k]
+ y0, y1, y2 = sy[i], sy[j], sy[k]
+ area = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)
+ if abs(area) < 1e-7: continue
+ bx0 = max(int(np.floor(min(x0, x1, x2))), 0); bx1 = min(int(np.ceil(max(x0, x1, x2))) + 1, W)
+ by0 = max(int(np.floor(min(y0, y1, y2))), 0); by1 = min(int(np.ceil(max(y0, y1, y2))) + 1, H)
+ if bx1 <= bx0 or by1 <= by0: continue
+ py, px = np.mgrid[by0:by1, bx0:bx1].astype(np.float64)
+ px += 0.5; py += 0.5
+ w0 = ((x1 - px) * (y2 - py) - (x2 - px) * (y1 - py)) / area
+ w1 = ((x2 - px) * (y0 - py) - (x0 - px) * (y2 - py)) / area
+ w2 = 1 - w0 - w1
+ ins = (w0 >= -1e-9) & (w1 >= -1e-9) & (w2 >= -1e-9)
+ if not ins.any(): continue
+ zz = (w0 * z0 + w1 * z1 + w2 * z2).astype(np.float32)
+ sub = self.z[by0:by1, bx0:bx1]
+ upd = ins & (zz < sub)
+ if not upd.any(): continue
+ sub[upd] = zz[upd]
+ a, b, c = w0[upd][:, None], w1[upd][:, None], w2[upd][:, None]
+ self.n[by0:by1, bx0:bx1][upd] = a * N[i] + b * N[j] + c * N[k]
+ self.pos[by0:by1, bx0:bx1][upd] = a * V[i] + b * V[j] + c * V[k]
+ self.mat[by0:by1, bx0:bx1][upd] = mid
+
+ @staticmethod
+ def _frame(axis):
+ a = np.asarray(axis, np.float64); a = a / np.linalg.norm(a)
+ t = np.array([0, 0, 1.0]) if abs(a[2]) < 0.9 else np.array([1.0, 0, 0])
+ u = np.cross(a, t); u /= np.linalg.norm(u)
+ return a, u, np.cross(a, u)
+
+ def _surface(self, rings, normals, mid, closed=True):
+ """grid of vertex rings (k, s, 3) -> triangles"""
+ k, s = rings.shape[:2]
+ V = rings.reshape(-1, 3); N = normals.reshape(-1, 3)
+ F = []
+ cols = s if closed else s - 1
+ for a in range(k - 1):
+ for b in range(cols):
+ b2 = (b + 1) % s
+ p, q, r_, t = a * s + b, a * s + b2, (a + 1) * s + b2, (a + 1) * s + b
+ F.append((p, q, r_)); F.append((p, r_, t))
+ self.mesh(V, N, F, mid)
+
+ def lathe(self, base, axis, profile, mid, sides=32, cap=True):
+ """surface of revolution: profile = [(t, r), ...] along `axis` from `base` (metres)"""
+ a, u, v = self._frame(axis)
+ prof = np.asarray(profile, np.float64)
+ th = np.linspace(0, 2 * np.pi, sides, endpoint=False)
+ ring = np.cos(th)[:, None] * u + np.sin(th)[:, None] * v # (s, 3) radial dirs
+ t, r = prof[:, 0], prof[:, 1]
+ dt, dr = np.gradient(t), np.gradient(r)
+ P = np.asarray(base, np.float64) + t[:, None, None] * a + r[:, None, None] * ring[None]
+ nrm = ring[None] * dt[:, None, None] - a * dr[:, None, None]
+ nrm /= np.linalg.norm(nrm, axis=-1, keepdims=True) + 1e-12
+ self._surface(P, nrm, mid)
+ if cap and r[-1] > 1e-4: # flat end cap
+ c = np.asarray(base) + t[-1] * a
+ V = np.vstack([c[None], P[-1]]); N = np.tile(a, (sides + 1, 1))
+ self.mesh(V, N, [(0, 1 + i, 1 + (i + 1) % sides) for i in range(sides)], mid)
+ if cap and r[0] > 1e-4:
+ c = np.asarray(base) + t[0] * a
+ V = np.vstack([c[None], P[0]]); N = np.tile(-a, (sides + 1, 1))
+ self.mesh(V, N, [(0, 1 + i, 1 + (i + 1) % sides) for i in range(sides)], mid)
+
+ def cylinder(self, p0, p1, r, mid, sides=8, segs=1, r1=None, cap=False):
+ """a straight tube (steel member, rod, wire) from p0 to p1; r1 tapers it"""
+ p0, p1 = np.asarray(p0, np.float64), np.asarray(p1, np.float64)
+ L = np.linalg.norm(p1 - p0)
+ if L < 1e-9: return
+ r1 = r if r1 is None else r1
+ t = np.linspace(0, L, segs + 1)
+ self.lathe(p0, p1 - p0, np.stack([t, r + (r1 - r) * t / L], 1), mid, sides, cap)
+
+ def sweep(self, path, radii, mid, sides=20):
+ """a tube of varying radius along a 3-D path (gooseneck, horn, cable); parallel-transport frames"""
+ P = np.asarray(path, np.float64); rad = np.asarray(radii, np.float64)
+ T = np.gradient(P, axis=0); T /= np.linalg.norm(T, axis=1, keepdims=True)
+ _, u, _ = self._frame(T[0])
+ us = [u]
+ for i in range(1, len(P)):
+ u = us[-1] - T[i] * np.dot(us[-1], T[i]); u /= np.linalg.norm(u)
+ us.append(u)
+ U = np.array(us); Vv = np.cross(T, U)
+ th = np.linspace(0, 2 * np.pi, sides, endpoint=False)
+ ring = np.cos(th)[None, :, None] * U[:, None] + np.sin(th)[None, :, None] * Vv[:, None]
+ s = np.concatenate([[0], np.cumsum(np.linalg.norm(np.diff(P, axis=0), axis=1))])
+ drds = np.gradient(rad, s)
+ pts = P[:, None] + rad[:, None, None] * ring
+ nrm = ring - drds[:, None, None] * T[:, None]
+ nrm /= np.linalg.norm(nrm, axis=-1, keepdims=True)
+ self._surface(pts, nrm, mid)
+
+ def box(self, lo, hi, mid):
+ """axis-aligned box from corner lo to corner hi (flat-shaded faces)"""
+ x0, y0, z0 = lo; x1, y1, z1 = hi
+ faces = [((x0, y0, z0), (x1, y0, z0), (x1, y0, z1), (x0, y0, z1), (0, -1, 0)),
+ ((x1, y1, z0), (x0, y1, z0), (x0, y1, z1), (x1, y1, z1), (0, 1, 0)),
+ ((x0, y1, z0), (x0, y0, z0), (x0, y0, z1), (x0, y1, z1), (-1, 0, 0)),
+ ((x1, y0, z0), (x1, y1, z0), (x1, y1, z1), (x1, y0, z1), (1, 0, 0)),
+ ((x0, y0, z1), (x1, y0, z1), (x1, y1, z1), (x0, y1, z1), (0, 0, 1)),
+ ((x0, y1, z0), (x1, y1, z0), (x1, y0, z0), (x0, y0, z0), (0, 0, -1))]
+ for a, b, c, d, n in faces:
+ self.mesh([a, b, c, d], [n] * 4, [(0, 1, 2), (0, 2, 3)], mid)
+
+ def hyperboloid(self, z0, z1, r0, r1, n, twist, mid, member=0.25, rings=4, ring_member=None, phase=0.0, sides=6,
+ segs=4):
+ """one section of a ruled-surface lattice (a hyperboloid tower section): n straight members leaning one
+ way and n the other, from a ring of radius r0 at height z0 to a ring of radius r1 at z1, each joining
+ angle th to th +- twist (degrees); plus `rings` horizontal hoops that follow the waist."""
+ tw = np.deg2rad(twist)
+ th = np.deg2rad(phase) + np.linspace(0, 2 * np.pi, n, endpoint=False)
+ for sgn in (1, -1):
+ for t in th:
+ p0 = (r0 * np.cos(t), r0 * np.sin(t), z0)
+ p1 = (r1 * np.cos(t + sgn * tw), r1 * np.sin(t + sgn * tw), z1)
+ self.cylinder(p0, p1, member, mid, sides, segs)
+ rm = ring_member or member * 0.8
+ for k in range(rings + 1):
+ f = k / rings
+ a0 = np.array([r0, 0.0]); a1 = np.array([r1 * np.cos(tw), r1 * np.sin(tw)])
+ rr = np.linalg.norm(a0 * (1 - f) + a1 * f) # waist radius here
+ zz = z0 + (z1 - z0) * f
+ m = max(24, n * 2)
+ ang = np.linspace(0, 2 * np.pi, m + 1)
+ for a, b in zip(ang[:-1], ang[1:]):
+ self.cylinder((rr * np.cos(a), rr * np.sin(a), zz), (rr * np.cos(b), rr * np.sin(b), zz), rm, mid, 5)
+
+ # ------------------------------------------------------------ shading
+ def render(self, backdrop=None):
+ """-> (tone, alpha), both (h, w) float32. tone 1 = paper white, 0 = full black.
+ backdrop: None (transparent) or a tone (float) / (h, w) array behind the objects"""
+ if self._out is not None: return self._out
+ ss = self.ss
+ hit = self.mat >= 0
+ idx = np.flatnonzero(hit) # shade only the covered pixels
+ mat = self.mat.reshape(-1)[idx]
+ pos = self.pos.reshape(-1, 3)[idx]
+ n = self.n.reshape(-1, 3)[idx]
+ n /= np.linalg.norm(n, axis=-1, keepdims=True) + 1e-9
+ V = self.E[None, :].astype(np.float32) - pos
+ dist = np.linalg.norm(V, axis=-1)
+ V /= dist[:, None] + 1e-9
+ ndv = (n * V).sum(-1)
+ back = ndv < 0
+ n[back] *= -1
+ ndv = np.abs(ndv)
+ k = len(idx)
+ alb = np.zeros(k, np.float32); gloss = np.zeros_like(alb); shine = np.ones_like(alb)
+ metal = np.zeros_like(alb); inter = np.ones_like(alb); hz = np.zeros_like(alb)
+ for mid, m in enumerate(self.mats):
+ sel = mat == mid
+ if not sel.any(): continue
+ a = np.full(int(sel.sum()), m['albedo'], np.float32)
+ if m['tex'] is not None:
+ a = a * np.asarray(m['tex'](pos[sel], n[sel]), np.float32)
+ alb[sel] = a; gloss[sel] = m['gloss']; shine[sel] = m['shine']; metal[sel] = m['metal']
+ inter[sel & back] = m['interior']; hz[sel] = 1.0 if m['haze'] else 0.0
+ L1, L2 = self.key, self.fill
+ d1 = np.clip(n @ L1, 0, 1); d2 = np.clip(n @ L2, 0, 1)
+ hemi = 0.55 + 0.45 * n[:, 2]
+ H1 = L1[None] + V; H1 /= np.linalg.norm(H1, axis=-1, keepdims=True) + 1e-9
+ spec = np.clip((n * H1).sum(-1), 0, 1) ** shine
+ Rz = 2 * ndv * n[:, 2] - V[:, 2] # reflected ray, z part
+ env = 0.12 + 0.88 * smoothstep(-0.15, 0.55, Rz) # bright sky, dark ground
+ fres = 0.04 + 0.5 * (1 - ndv) ** 4
+ diff = alb * (self.key_k * d1 + self.fill_k * d2 + self.amb * hemi)
+ col = diff * (1 - metal) + metal * alb * (0.25 + 0.95 * env) + gloss * (1.4 * spec + fres * env)
+ col = col * inter
+ if self.haze:
+ kh = 1 - np.exp(-dist / self.haze)
+ col = col * (1 - kh * hz) + self.haze_tone * kh * hz
+ t = 1 - np.exp(-col * 2.2 * self.exposure) # soft film shoulder
+ tone = np.zeros(self.z.size, np.float32)
+ tone[idx] = np.clip(t / (1 - np.exp(-2.2 * self.exposure)), 0, 1)
+ tone = tone.reshape(self.z.shape)
+ # downsample with coverage
+ cov = hit.astype(np.float32)
+ h, w = self.h, self.w
+ cs = cov.reshape(h, ss, w, ss).mean((1, 3))
+ ts = (tone * cov).reshape(h, ss, w, ss).mean((1, 3)) / np.maximum(cs, 1e-6)
+ if self.lens:
+ wsum = blur(cs, self.lens)
+ ts = blur(ts * cs, self.lens) / np.maximum(wsum, 1e-6)
+ cs = np.clip(wsum * 1.0, 0, 1)
+ if self.grain:
+ g = blur(self.rng.random((h, w)).astype(np.float32), 0.8)
+ ts = ts + self.grain * (g - g.mean()) / (g.std() + 1e-6)
+ ts = np.clip(ts, 0, 1)
+ if backdrop is not None:
+ ts = ts * cs + np.asarray(backdrop, np.float32) * (1 - cs)
+ self._out = (ts.astype(np.float32), cs.astype(np.float32))
+ self.z = self.n = self.pos = self.mat = None # the negative is developed: free the buffers
+ return self._out
+
+
+# ---------------------------------------------------------------- the poster
+class Constructivism:
+ def __init__(self, W=1920, H=1080, seed=0, misreg=2.4, red=RED, black=BLACK):
+ """misreg: typical registration error between the two plates, px"""
+ self.W, self.H = W, H
+ self.rng = np.random.default_rng(seed)
+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)
+ self.cov = {p: np.zeros((H, W), np.float32) for p in PLATES}
+ self.inks = {'red': _c(red), 'black': _c(black)}
+ self.paper_rgb = np.ones((H, W, 3), np.float32) * _c(PAPER)
+ self.light = np.ones((H, W), np.float32)
+ self.fibre = np.ones((H, W), np.float32)
+ self.tooth = np.zeros((H, W), np.float32)
+ self.stages = []
+ self.aged = None
+ r = self.rng
+ self.reg = {}
+ for p in PLATES: # each plate's registration error
+ a = r.uniform(0, 2 * np.pi)
+ mag = misreg * r.uniform(0.6, 1.0) * (1.0 if p == 'red' else 0.35)
+ self.reg[p] = (np.cos(a) * mag, np.sin(a) * mag, r.normal(0, 0.02)) # dx, dy, degrees
+ self._ink_fields()
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ def _ink_fields(self):
+ H, W, r = self.H, self.W, self.rng
+ self.film = {}
+ for p in PLATES:
+ blot = noise2d(H, W, 260, 3, self._seed())
+ mott = noise2d(H, W, 22, 2, self._seed())
+ fine = blur(r.random((H, W)).astype(np.float32), 0.7)
+ fine = (fine - fine.mean()) / (fine.std() + 1e-6)
+ # voids: dust and fibres that kept the plate off the paper
+ vim = Image.new('L', (W, H), 0)
+ d = ImageDraw.Draw(vim)
+ for _ in range(int(W * H / 5200)):
+ x, y = r.uniform(0, W), r.uniform(0, H)
+ if r.random() < 0.7:
+ rr = r.uniform(0.4, 1.3)
+ d.ellipse((x - rr, y - rr, x + rr, y + rr), fill=int(r.uniform(90, 255)))
+ else:
+ a, L = r.uniform(0, np.pi), r.uniform(3, 11)
+ d.line((x, y, x + np.cos(a) * L, y + np.sin(a) * L), fill=int(r.uniform(80, 200)), width=1)
+ voids = blur(np.asarray(vim, np.float32) / 255, 0.45)
+ film = 1.0 - 0.07 * (blot - 0.5) - 0.05 * (mott - 0.5) - 0.018 * fine
+ self.film[p] = dict(film=film.astype(np.float32), voids=voids.astype(np.float32),
+ edge=(blur(r.random((H, W)).astype(np.float32), 0.9) - 0.5).astype(np.float32))
+
+ # ------------------------------------------------------------ the sheet
+ def paper(self, colour=PAPER, aged=AGED, yellow=1.0):
+ """cheap cream poster paper: cloudy pulp, fibres, dark flecks, a little cockle, yellowing at the edges"""
+ H, W, r = self.H, self.W, self.rng
+ base = _c(colour)
+ cloud = noise2d(H, W, 300, 4, self._seed())
+ t = smoothstep(0.3, 0.95, cloud)[..., None] * 0.18
+ img = base * (1 - t) + _c(aged) * t
+ # yellowing / greying toward the edges (light and air got at the margins, the middle was folded inside)
+ ex = np.minimum(self.XX, W - 1 - self.XX) / W
+ ey = np.minimum(self.YY, H - 1 - self.YY) / H
+ e = np.minimum(ex * 1.7, ey * 1.0)
+ wob = noise2d(H, W, 160, 3, self._seed())
+ edge = (1 - smoothstep(0.0, 0.16 + 0.08 * wob, e)) * yellow
+ img = img * (1 - 0.45 * edge[..., None]) + _c(aged) * 0.92 * 0.45 * edge[..., None]
+ img = img * (1 - 0.05 * edge[..., None] * (1 - wob[..., None]))
+ img = img * (1 + 0.014 * (noise2d(H, W, 50, 3, self._seed()) - 0.5))[..., None]
+ # fibres
+ fim = Image.new('L', (W, H), 128)
+ d = ImageDraw.Draw(fim)
+ for _ in range(int(W * H / 650)):
+ x, y = r.uniform(0, W), r.uniform(0, H)
+ a, L = r.uniform(0, np.pi), r.uniform(4, 20)
+ bend = r.normal(0, 0.3)
+ pts = [(x + np.cos(a + bend * s) * L * s, y + np.sin(a + bend * s) * L * s) for s in np.linspace(-0.5, 0.5, 5)]
+ d.line(pts, fill=int(128 + r.choice([-1, 1]) * r.uniform(8, 26)), width=1)
+ fib = blur((np.asarray(fim, np.float32) - 128) / 128, 0.55)
+ fine = blur(r.random((H, W)).astype(np.float32), 0.6)
+ self.tooth = ((fine - fine.mean()) / (fine.std() + 1e-6)).astype(np.float32)
+ self.fibre = (1 + 0.045 * fib + 0.008 * self.tooth).astype(np.float32)
+ # flecks in the pulp
+ fl = Image.new('L', (W * 2, H * 2), 0)
+ d = ImageDraw.Draw(fl)
+ for _ in range(int(W * H / 5000)):
+ x, y = r.uniform(0, W * 2), r.uniform(0, H * 2)
+ rr = r.uniform(0.6, 2.2) * (3 if r.random() < 0.03 else 1)
+ d.ellipse((x - rr, y - rr * r.uniform(0.4, 1), x + rr, y + rr * r.uniform(0.4, 1)), fill=int(r.uniform(60, 190)))
+ fl = np.asarray(fl.resize((W, H), Image.BOX), np.float32) / 255
+ img = img * (1 - fl[..., None] * (1 - _c('#5d4b36')))
+ self.paper_rgb = img.astype(np.float32)
+ cockle = noise2d(H, W, 480, 2, self._seed()) - 0.5
+ grad = 1 + 0.025 * (0.5 - (self.XX / W * 0.6 + self.YY / H * 0.4))
+ self.light = (grad + 0.02 * cockle).astype(np.float32)
+
+ # ------------------------------------------------------------ masks (full canvas, anti-aliased, 0..1)
+ def circle(self, cx, cy, r):
+ return np.clip(r - np.hypot(self.XX - cx, self.YY - cy) + 0.5, 0, 1)
+
+ def ring(self, cx, cy, r, width):
+ return np.clip(width / 2 - np.abs(np.hypot(self.XX - cx, self.YY - cy) - r) + 0.5, 0, 1)
+
+ def _between(self, cx, cy, a0, a1):
+ """0..1: inside the angular sector a0 -> a1 (ccw degrees, span <= 180) seen from (cx, cy)"""
+ dx, dy = self.XX - cx, -(self.YY - cy)
+ t0, t1 = np.deg2rad(a0), np.deg2rad(a1)
+ h0 = np.cos(t0) * dy - np.sin(t0) * dx # left of ray a0
+ h1 = -np.cos(t1) * dy + np.sin(t1) * dx # right of ray a1
+ return np.clip(np.minimum(h0, h1) + 0.5, 0, 1)
+
+ def arc(self, cx, cy, r, a0, a1, width):
+ """a band of radius r from angle a0 to a1 (ccw), square-cut along the radii"""
+ return np.minimum(self.ring(cx, cy, r, width), self._between(cx, cy, a0, a1))
+
+ def sector(self, cx, cy, r, a0, a1):
+ return np.minimum(self.circle(cx, cy, r), self._between(cx, cy, a0, a1))
+
+ def poly(self, pts, ss=4):
+ P = np.asarray(pts, np.float64)
+ x0, y0 = int(np.floor(P[:, 0].min())) - 2, int(np.floor(P[:, 1].min())) - 2
+ x1, y1 = int(np.ceil(P[:, 0].max())) + 2, int(np.ceil(P[:, 1].max())) + 2
+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0)
+ ImageDraw.Draw(im).polygon([((x - x0) * ss, (y - y0) * ss) for x, y in P], fill=255)
+ a = np.asarray(im.resize((x1 - x0, y1 - y0), Image.BOX), np.float32) / 255
+ return self._place(a, x0, y0)
+
+ def _place(self, a, x0, y0):
+ out = np.zeros((self.H, self.W), np.float32)
+ h, w = a.shape
+ ys, xs = max(0, y0), max(0, x0)
+ ye, xe = min(self.H, y0 + h), min(self.W, x0 + w)
+ if ye > ys and xe > xs:
+ out[ys:ye, xs:xe] = a[ys - y0:ye - y0, xs - x0:xe - x0]
+ return out
+
+ def rect(self, x0, y0, x1, y1, rot=0.0):
+ """rectangle; rot (ccw degrees) turns it about its centre"""
+ cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
+ t = np.deg2rad(rot)
+ c, s = np.cos(t), np.sin(t)
+ return self.poly([(cx + u * c + v * s, cy - u * s + v * c) for u, v in
+ [(x0 - cx, y0 - cy), (x1 - cx, y0 - cy), (x1 - cx, y1 - cy), (x0 - cx, y1 - cy)]])
+
+ def bar(self, x0, y0, x1, y1, width, cap='butt'):
+ """a straight bar from (x0, y0) to (x1, y1) -- a diagonal slab, or a rule when thin"""
+ dx, dy = x1 - x0, y1 - y0
+ L = float(np.hypot(dx, dy)) + 1e-6
+ ux, uy = dx / L, dy / L
+ u = (self.XX - x0) * ux + (self.YY - y0) * uy
+ v = -(self.XX - x0) * uy + (self.YY - y0) * ux
+ ext = width / 2 if cap == 'square' else 0
+ return np.clip(np.minimum(width / 2 - np.abs(v), np.minimum(u + ext, L + ext - u)) + 0.5, 0, 1)
+
+ def wedge(self, apex, angle, half, length):
+ """a sharp triangle (the 'wedge') from `apex` pointing along `angle` (ccw degrees), opening by +-half"""
+ ax, ay = apex
+ pts = [(ax, ay)]
+ for a in (angle - half, angle + half):
+ t = np.deg2rad(a)
+ pts.append((ax + np.cos(t) * length, ay - np.sin(t) * length))
+ return self.poly(pts)
+
+ def along(self, p, angle, d, side=0.0):
+ """the point `d` px from p along `angle` (ccw degrees) and `side` px to its left"""
+ t = np.deg2rad(angle)
+ return p[0] + np.cos(t) * d - np.sin(t) * side, p[1] - np.sin(t) * d - np.cos(t) * side
+
+ # ------------------------------------------------------------ type
+ def text_mask(self, s, x, y, size, font_style='grotesk', anchor='ls', spacing=0.0, rot=0.0, wobble=0.0,
+ scale_x=1.0, ss=2):
+ """lettering -> full-canvas mask. anchor as in Pillow ('ls' left-baseline, 'mm' centre, 'rs', 'lt' ...).
+ spacing: extra px per letter. rot: ccw degrees about (x, y). wobble: hand-drawn warp of the outline, px.
+ scale_x: squeeze (<1) or stretch the letters horizontally."""
+ f = font(font_style, size * ss, s)
+ adv = [f.getlength(ch) + spacing * ss for ch in s]
+ total = sum(adv) - (spacing * ss if s else 0)
+ asc, desc = f.getmetrics()
+ pad = int(size * 0.4 + 8) * ss
+ bw, bh = int(total + 2 * pad), int(asc + desc + 2 * pad)
+ im = Image.new('L', (bw, bh), 0)
+ d = ImageDraw.Draw(im)
+ base = pad + asc
+ if spacing:
+ cx = pad
+ for ch, a in zip(s, adv):
+ d.text((cx, base), ch, font=f, fill=255, anchor='ls')
+ cx += a
+ else:
+ d.text((pad, base), s, font=f, fill=255, anchor='ls')
+ bb = f.getbbox('H', anchor='ls')
+ capH = -bb[1]
+ ax = pad + total * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor[0]]
+ ay = base - {'s': 0, 'm': capH / 2, 't': capH, 'a': capH, 'b': -desc, 'd': -desc}[anchor[1]]
+ if scale_x != 1.0:
+ nw = max(1, int(round(bw * scale_x)))
+ im = im.resize((nw, bh), Image.LANCZOS)
+ ax *= scale_x
+ a = np.asarray(im.resize((im.width // ss, im.height // ss), Image.BOX), np.float32) / 255
+ ax, ay = ax / ss, ay / ss
+ if wobble:
+ h, w = a.shape
+ g = np.random.default_rng(self._seed())
+ dx = (noise2d(h, w, max(6.0, size * 0.35), 2, int(g.integers(1 << 30))) - 0.5) * 2 * wobble
+ dy = (noise2d(h, w, max(6.0, size * 0.35), 2, int(g.integers(1 << 30))) - 0.5) * 2 * wobble
+ a = _warp(a, dx, dy)
+ if rot:
+ h, w = a.shape
+ R = int(np.hypot(h, w)) + 4
+ big = np.zeros((2 * R, 2 * R), np.float32)
+ ox, oy = int(round(R - ax)), int(round(R - ay))
+ big[oy:oy + h, ox:ox + w] = a
+ big = _rotate(big, rot, center=(R, R))
+ return self._place(big, int(round(x)) - R, int(round(y)) - R)
+ return self._place(a, int(round(x - ax)), int(round(y - ay)))
+
+ def text_width(self, s, size, font_style='grotesk', spacing=0.0):
+ f = font(font_style, size, s)
+ return sum(f.getlength(ch) + spacing for ch in s) - (spacing if s else 0)
+
+ def text(self, s, x, y, size, plate='black', font_style='grotesk', anchor='ls', spacing=0.0, rot=0.0,
+ wobble=0.0, scale_x=1.0, knock=None):
+ """print lettering on a plate (and optionally knock the same letters out of other plates)"""
+ m = self.text_mask(s, x, y, size, font_style, anchor, spacing, rot, wobble, scale_x)
+ self.ink(m, plate)
+ if knock:
+ self.knock(m, knock)
+ return m
+
+ # ------------------------------------------------------------ inking
+ def ink(self, mask, plate='black', knock=None, density=1.0):
+ """ink a mask on a plate. knock: a mask cut out of this same solid (type reversed out of a bar)"""
+ m = np.clip(mask if knock is None else mask - knock, 0, 1) * density
+ c = self.cov[plate]
+ np.maximum(c, m, out=c)
+
+ def knock(self, mask, plates=PLATES):
+ """knock a mask out of plates: nothing is printed there (the paper shows)"""
+ for p in ((plates,) if isinstance(plates, str) else plates):
+ self.cov[p] *= (1 - np.clip(mask, 0, 1))
+
+ def tint(self, mask, plate='black', level=0.3, cell=7.0, angle=45.0):
+ """a flat halftone tint (a screen of dots at one percentage) inside mask"""
+ rows, cols = np.flatnonzero(mask.max(1) > 0.002), np.flatnonzero(mask.max(0) > 0.002)
+ if not len(rows): return
+ sl = (slice(rows[0], rows[-1] + 1), slice(cols[0], cols[-1] + 1))
+ rough = self._rough(sl)
+ ht = halftone(np.full(mask[sl].shape, level, np.float32), self.XX[sl], self.YY[sl], cell, angle, rough,
+ soften=0)
+ sub = self.cov[plate][sl]
+ np.maximum(sub, ht * mask[sl], out=sub)
+
+ def _rough(self, sl):
+ return 0.07 * self.film['black']['edge'][sl] / 0.12
+
+ def waves(self, cx, cy, r0, r1, step, width, a0, a1, plates=('black', 'red'), grow=0.0):
+ """concentric wave fronts radiating from (cx, cy) inside the angles a0 -> a1, cycling through `plates`.
+ grow: change of width per 100 px of radius, as a fraction (+ fatten, - thin out as they spread)"""
+ k = 0
+ r = r0
+ while r <= r1:
+ w = max(2.0, width * (1 + grow * (r - r0) / 100))
+ self.ink(self.arc(cx, cy, r, a0, a1, w), plates[k % len(plates)])
+ r += step; k += 1
+
+ # ------------------------------------------------------------ photomontage
+ def montage(self, photo, cx, cy, rot=0.0, scale=1.0, plate='black', cut=None, backdrop=0.94, cell=7.0,
+ angle=45.0, contrast=1.0, gamma=1.0, gain=0.55, cut_wander=0.35, close=0, soften=0.3):
+ """paste a photograph (a Photo or (tone, alpha)) centred at (cx, cy), turned rot degrees ccw and scaled,
+ then screen it into the halftone on `plate`. cut: scissor margin in px (the cut piece covers what is
+ under it); None: retouched out of its background and overprinted. backdrop: tone of the photo's own
+ background inside the cut. close: px of closing applied to the silhouette before cutting (bridges the
+ gaps of a lattice so the scissors go round the outside). soften: blur before screening, in cells (lower keeps
+ thin members and narrow gaps open, higher gives rounder, calmer dots)."""
+ tone, alpha = photo.render() if hasattr(photo, 'render') else photo
+ tone = np.clip(0.5 + (tone - 0.5) * contrast, 0, 1) ** gamma
+ dark = alpha * (1 - tone)
+ h, w = tone.shape
+ if scale != 1.0:
+ nw, nh = int(round(w * scale)), int(round(h * scale))
+ dark = np.asarray(Image.fromarray(dark, 'F').resize((nw, nh), Image.BILINEAR), np.float32)
+ alpha = np.asarray(Image.fromarray(alpha, 'F').resize((nw, nh), Image.BILINEAR), np.float32)
+ h, w = nh, nw
+ pad = int((cut or 0) + 30)
+ dark = np.pad(dark, pad); alpha = np.pad(alpha, pad)
+ if rot:
+ dark = _rotate(dark, rot, expand=True); alpha = _rotate(alpha, rot, expand=True)
+ h, w = dark.shape
+ x0, y0 = int(round(cx - w / 2)), int(round(cy - h / 2))
+ D = self._place(dark, x0, y0); A = self._place(alpha, x0, y0)
+ ys, xs = max(0, y0), max(0, x0)
+ ye, xe = min(self.H, y0 + h), min(self.W, x0 + w)
+ sl = (slice(ys, ye), slice(xs, xe))
+ piece = None
+ if cut:
+ a = A[sl]
+ if close:
+ a = 1 - _dilate(1 - _dilate((a > 0.3).astype(np.float32), close), close)
+ a = np.maximum(a, A[sl])
+ m = _fill_holes(_dilate((a > 0.25).astype(np.float32), cut)) # scissors go round, never in
+ n = noise2d(m.shape[0], m.shape[1], 90, 3, self._seed()) - 0.5
+ m = blur(m, 2.2 + cut * 0.12)
+ m = smoothstep(0.42 + cut_wander * n * 0.5, 0.58 + cut_wander * n * 0.5, m)
+ piece = np.zeros((self.H, self.W), np.float32)
+ piece[sl] = np.maximum(m, A[sl])
+ D[sl] = D[sl] + (1 - A[sl]) * (1 - backdrop) * piece[sl]
+ self.knock(piece)
+ ht = halftone(D[sl], self.XX[sl], self.YY[sl], cell, angle, self._rough(sl), gain, soften)
+ if piece is not None:
+ ht *= piece[sl]
+ sub = self.cov[plate][sl]
+ np.maximum(sub, ht, out=sub)
+ return piece if piece is not None else A
+
+ # ------------------------------------------------------------ a century later
+ def age(self, folds=(1, 1), foxing=1.0, stain=True, pins=True, crack=1.0, grime=1.0):
+ """folds: (vertical, horizontal) fold lines -- the sheet folded into equal panels; ink cracks off along
+ them. foxing: brown spots. stain: a faint water tide line. pins: drawing-pin holes in the corners."""
+ H, W, r = self.H, self.W, self.rng
+ light = np.ones((H, W), np.float32); dirt = np.zeros((H, W), np.float32)
+ crackm = np.zeros((H, W), np.float32); wear = np.zeros((H, W), np.float32)
+ lines = [('v', W * (i + 1) / (folds[0] + 1)) for i in range(folds[0])]
+ lines += [('h', H * (i + 1) / (folds[1] + 1)) for i in range(folds[1])]
+ for kind, pos in lines:
+ n = W if kind == 'h' else H
+ wav = fbm1d(n, 300, 4, self._seed()) * 2.0 + pos
+ coord = self.XX if kind == 'v' else self.YY
+ along = self.YY if kind == 'v' else self.XX
+ off = wav[along.astype(np.int32)]
+ d = coord - off
+ sgn = r.choice([-1, 1])
+ light *= 1 + sgn * 0.035 * np.exp(-(d - 1.6) ** 2 / 3.0) - sgn * 0.045 * np.exp(-(d + 1.6) ** 2 / 3.0)
+ light *= 1 - 0.035 * np.exp(-d ** 2 / 0.8)
+ dirt = np.maximum(dirt, np.exp(-d ** 2 / (2 * 9.0 ** 2)) * (0.5 + 0.5 * noise2d(H, W, 40, 2, self._seed())))
+ gate = smoothstep(0.22, 0.6, noise2d(H, W, 16, 2, self._seed()))
+ jit = blur(r.random((H, W)).astype(np.float32), 0.6)
+ crackm = np.maximum(crackm, np.clip(1.6 - np.abs(d) / 1.2, 0, 1) * gate * smoothstep(0.3, 0.55, jit) * crack)
+ rough = noise2d(H, W, 6, 2, self._seed())
+ wear = np.maximum(wear, np.exp(-d ** 2 / (2 * 3.2 ** 2)) * (0.35 + 0.65 * rough) * crack)
+ # foxing
+ fox = np.zeros((H, W), np.float32)
+ for _ in range(int(40 * foxing)):
+ x, y = r.uniform(0, W), r.uniform(0, H)
+ rad = r.lognormal(1.2, 0.6)
+ fox = np.maximum(fox, np.exp(-((self.XX - x) ** 2 + (self.YY - y) ** 2) / (2 * rad ** 2)) * r.uniform(0.25, 0.8))
+ # tide line of an old water stain (lower-right corner area)
+ tide = np.zeros((H, W), np.float32)
+ if stain:
+ sx, sy, sr = W * r.uniform(0.86, 0.95), H * r.uniform(0.84, 0.95), r.uniform(150, 230)
+ ang = np.arctan2(self.YY - sy, self.XX - sx)
+ rr = np.hypot(self.XX - sx, self.YY - sy) / sr
+ wob = 1 + 0.12 * np.sin(3 * ang + 1) + 0.07 * np.sin(7 * ang + 2)
+ q = rr / wob
+ tide = np.exp(-(q - 1) ** 2 / (2 * 0.012 ** 2)) * 0.6 + smoothstep(1.0, 0.2, q) * 0.12
+ # rubbed corners
+ cx = np.minimum(self.XX, W - 1 - self.XX); cy = np.minimum(self.YY, H - 1 - self.YY)
+ rub = np.exp(-(cx ** 2 + cy ** 2) / (2 * 55.0 ** 2)) * noise2d(H, W, 12, 2, self._seed())
+ holes = np.zeros((H, W), np.float32); halo = np.zeros((H, W), np.float32)
+ if pins:
+ for (px, py) in [(22, 22), (W - 24, 20), (21, H - 23), (W - 22, H - 21)]:
+ px += r.uniform(-5, 5); py += r.uniform(-5, 5)
+ d = np.hypot(self.XX - px, self.YY - py)
+ holes = np.maximum(holes, np.clip(2.6 - d, 0, 1))
+ halo = np.maximum(halo, np.exp(-d ** 2 / (2 * 6.0 ** 2)) * (0.6 + 0.4 * np.cos(np.arctan2(self.YY - py, self.XX - px) - r.uniform(0, 6.3))))
+ self.aged = dict(light=light, dirt=dirt * 0.06 * grime, crack=crackm, wear=wear, fox=fox, tide=tide,
+ rub=rub, holes=holes, halo=halo)
+
+ # ------------------------------------------------------------ output
+ def _plate(self, p):
+ dx, dy, rot = self.reg[p]
+ c = self.cov[p]
+ if dx or dy or rot:
+ P = 8 # the sheet was trimmed after printing: no bare edge
+ im = Image.fromarray(np.pad(c, P, mode='edge'), 'F')
+ t = np.deg2rad(rot)
+ cs, sn = np.cos(t), np.sin(t)
+ cx, cy = self.W / 2, self.H / 2
+ # output -> input: rotate by -rot about the centre, then subtract the shift
+ a, b = cs, -sn
+ d_, e = sn, cs
+ c0 = cx - a * (cx + dx) - b * (cy + dy) + P
+ f0 = cy - d_ * (cx + dx) - e * (cy + dy) + P
+ c = np.asarray(im.transform((self.W, self.H), Image.AFFINE, (a, b, c0, d_, e, f0), resample=Image.BILINEAR),
+ np.float32)
+ F = self.film[p]
+ # ragged edge at the scale of the fibres, a heavier squeeze of ink at the edge of solids
+ e = c + F['edge'] * 0.55 * (c * (1 - c) * 4)
+ e = smoothstep(0.2, 0.8, e)
+ rim = np.clip(e - blur(e, 2.0), 0, 1)
+ dens = e * np.clip(F['film'] + 0.06 * rim, 0, 1.08) * (1 - 0.85 * F['voids'])
+ return np.clip(dens, 0, 1)
+
+ def composite(self):
+ img = self.paper_rgb.copy()
+ ag = self.aged
+ if ag is not None:
+ img *= (1 - ag['fox'][..., None] * 0.2 * (1 - _c('#a77a45')))
+ img *= (1 - ag['tide'][..., None] * 0.12 * (1 - _c('#9c7a4c')))
+ for p in PLATES:
+ dns = self._plate(p)
+ if ag is not None:
+ dns = dns * (1 - ag['crack']) * (1 - 0.22 * ag['wear']) * (1 - 0.25 * ag['rub'])
+ ink = self.inks[p]
+ filt = np.clip(ink / np.array([0.93, 0.89, 0.80], np.float32), 0, 1) # ink as a filter
+ img = img * (1 - dns[..., None] + dns[..., None] * filt)
+ L = self.light * self.fibre
+ if ag is not None:
+ L = L * ag['light']
+ img = img * (1 - ag['dirt'][..., None]) * (1 - 0.3 * ag['halo'][..., None] * (1 - _c('#8a5a2b')))
+ img = img * (1 - ag['holes'][..., None]) + ag['holes'][..., None] * _c('#2a2118')
+ img = img * (1 - 0.06 * ag['rub'][..., None]) + 0.06 * ag['rub'][..., None] * _c('#e6dcc4')
+ img = img * L[..., 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
diff --git a/lib/illuminated.py b/lib/illuminated.py
new file mode 100644
index 0000000..ef1c04d
--- /dev/null
+++ b/lib/illuminated.py
@@ -0,0 +1,1670 @@
+"""illuminated — an opening of a late-medieval illuminated manuscript (c. 1400): vellum, textura written with a broad-
+edged quill in iron-gall ink, vermilion rubrics, raised and burnished gold leaf, tempera initials with white-lead
+tracery, an ivy-spray border and compass-drawn diagrams (numpy + Pillow only).
+
+Model -- the page is made the way a scriptorium made it, one craft after another, and every craft is a method:
+ codex an open book seen from above on a dark desk: leather boards, a stack of page edges at the fore-edge,
+ two leaves of vellum that darken and dip into the gutter (the page edges near the gutter bow inward).
+ vellum calf skin, scraped and pounced: warm cream with cloudy thicker (warmer) and thinner (cooler, more
+ translucent) zones, a few faint veins, the hair-follicle speckle of the hair side, a fine scraped nap,
+ and a low cockle -- the skin never lies flat, so the room light rolls across it.
+ rule prickings down the outer margin, pale plummet ruling at every line and the bounding verticals.
+ scribe textura quadrata from a simulated broad-edged quill. The nib is a short line segment held at a fixed
+ angle (about 40 degrees); a stroke is the area that segment sweeps, so the width follows the direction
+ of travel -- full on the diamond heads and feet, a hairline on the joins. Every letter is a handful of
+ pen strokes (minims with diamond heads and feet, broken bows) with a little per-letter wobble. Iron-gall
+ ink is nearly black where the quill was freshly dipped and browner as it runs dry (the scribe re-dips
+ every few words), and darker along the stroke edges where it pooled. Long s inside words, round s at the
+ end, '7' is the Tironian et, 'ꝑ' is p-with-a-bar for "per".
+ rubricate vermilion for titles and reserved words, capitals touched in red, paragraph marks alternating red and
+ blue, and a pen line filler on short last lines.
+ gild gold leaf on a raised gesso cushion over red bole, burnished with a stone: a mirror, so its colour is
+ the room it reflects. Every gold pixel takes its normal from the gesso dome (plus punched tooling, leaf
+ seams and burnishing streaks), reflects the camera ray (a camera at finite height, so the angle changes
+ across the page) and looks up a studio with a big soft window at the upper left. Flat gold reads gold,
+ the cushion edges flare pale on the side facing the window and fall to dark olive on the other, and the
+ punched dots glitter. Shell gold (powdered gold in gum) is matte and grainy instead.
+ paint tempera inside the outlines: granular azurite, rose, verdigris, vermilion, lead white; pigment pools a
+ little at the edges and the paint has body (it catches the light). Then white-lead tracery, and a black
+ pen outline round everything gilded or painted.
+ penwork ivy sprays: hairline tendrils grown recursively from a gold-and-colour bar border, ending in curls, gold
+ ivy leaves, blue and rose flowers and gold bezants; red filigree round blue penwork initials.
+ diagrams compass-and-rule figures: an astrolabe whose plate is a real stereographic projection (tropics, equator,
+ almucantars for a chosen latitude, horizon), with a shell-gold rete and a rule with sight vanes; a
+ roundel of the planetary spheres with the names written round the rings.
+ age six hundred years: the writing on the other side of the leaf showing through, foxing, thumb soil on the
+ lower outer corners, an iron-gall halo, flakes of gold lost down to the red bole, chips in the azurite.
+
+Each large ornament is an object whose methods follow the workshop order, so a draw-on animation shows the page
+being made: ink lines -> gold -> colours -> pen.
+
+ from illuminated import Illuminated
+ il = Illuminated(1920, 1080, seed=5)
+ il.desk(); left, right = il.codex(200, 40, 1720, 1040) # two page rects
+ il.rule(350, 885, [122 + 50 * i for i in range(17)], prick_x=214) # a ruled line at every x-height
+ blk = il.column('*incipit liber.* | uoniam stelle circa terram mouentur ... ^prima est luna ... |',
+ 350, 885, 140, 18, 50, indent=[(1, 350), (5, 596)]) # 5 lines wrap round the initial
+ q = il.initial('Q', 350, 172, 232)
+ il.scribe(blk); il.rubricate(blk) # black text, then the red
+ q.gild(); q.paint(); q.pen() # gold first, then colour, then pen
+ il.age(); il.save('out.jpg')
+"""
+import os
+import numpy as np
+from PIL import Image, ImageDraw
+from core import blur, noise2d, smoothstep, fbm1d
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+def _c(c):
+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)
+
+
+# ---------------------------------------------------------------- materials
+VELLUM = '#eddcb6'
+INK, INK_THIN = '#21160e', '#6b4a2d' # iron-gall: fresh / running dry
+RED, RED_DARK, RED_THIN = '#c03a22', '#8e2312', '#d4643f'
+AZURE, AZURE_DARK, AZURE_LIGHT = '#2f53a3', '#1b2f6e', '#5a7cc4'
+ROSE, ROSE_DARK = '#c86576', '#8a3446'
+GREEN, GREEN_DARK = '#4a8457', '#2b5636'
+OCHRE = '#c79a4c'
+WHITE = '#f5efe2'
+SILVER = '#d9d6cc'
+LEAD = '#5c5d62'
+BOLE = '#9b4429'
+RULE = '#a98a66'
+DESK = '#2b1b11'
+LEATHER = '#4c2918'
+
+# burnished gold: brightness of the reflected room -> colour (dark olive .. gold .. pale highlight)
+_GOLD_E = np.array([0.0, 0.2, 0.4, 0.58, 0.8, 1.1], np.float32)
+_GOLD_C = np.array([[0.14, 0.08, 0.03], [0.36, 0.24, 0.08], [0.62, 0.44, 0.15], [0.85, 0.65, 0.26],
+ [0.98, 0.85, 0.50], [1.0, 0.97, 0.82]], np.float32)
+
+
+def _gold_ramp(E):
+ return np.stack([np.interp(E, _GOLD_E, _GOLD_C[:, k]) for k in range(3)], -1).astype(np.float32)
+
+
+def _bbox(a, pad=0, thr=0.002):
+ rows = np.flatnonzero((a > thr).any(1))
+ if not len(rows): return None
+ cols = np.flatnonzero((a > thr).any(0))
+ H, W = a.shape
+ return (slice(max(rows[0] - pad, 0), min(rows[-1] + 1 + pad, H)),
+ slice(max(cols[0] - pad, 0), min(cols[-1] + 1 + pad, W)))
+
+
+# ---------------------------------------------------------------- textura: every letter is a few broad-pen strokes
+# units: x-height = 1, y down, y = 0 is the x-height line, y = 1 the baseline; ascenders reach -0.46, descenders 1.42.
+P, D, DY = 0.40, 0.09, 0.11 # minim pitch, diamond reach (x), diamond drop (y)
+
+
+def _post(x, t=0.0, b=1.0, head=True, foot=True):
+ s = [(x - D, t), (x, t + DY)] if head else [(x, t)]
+ s += [(x, b - DY), (x + D, b)] if foot else [(x, b)]
+ return s
+
+
+def _arch(x0, x1, b=1.0, foot=True):
+ """hairline from the post at x0 up into a new post at x1"""
+ s = [(x0, 0.17), (x1 - D, 0.0), (x1, DY)]
+ s += [(x1, b - DY), (x1 + D, b)] if foot else [(x1, b)]
+ return s
+
+
+_O_L = [(0.17, -0.01), (0.0, 0.13), (0.0, 0.87), (0.15, 1.01)]
+GLYPHS = {
+ 'a': ([[(0.02, 0.10), (0.16, -0.01), (0.36, 0.11), (0.36, 1 - DY), (0.36 + D, 1.0)],
+ [(0.36, 0.42), (0.05, 0.53), (0.0, 0.63), (0.0, 0.88), (0.12, 1.0), (0.36, 0.86)]], 0.36 + P),
+ 'b': ([[(-D, -0.46), (0.0, -0.35), (0.0, 0.88), (0.14, 1.01), (0.37, 0.88), (0.37, 0.12), (0.22, -0.01), (0.0, 0.17)]],
+ 0.37 + P),
+ 'c': ([[(0.15, 0.0), (0.0, 0.13), (0.0, 1 - DY), (0.11, 1.0), (0.32, 0.88)], [(0.06, 0.0), (0.31, 0.12)]], 0.31 + 0.34),
+ 'd': ([[(0.27, -0.03), (0.0, 0.13), (0.0, 0.87), (0.15, 1.01)], [(-0.05, -0.42), (0.37, 0.12), (0.37, 0.88), (0.22, 1.01)]],
+ 0.37 + P),
+ 'e': ([[(0.15, 0.0), (0.0, 0.13), (0.0, 1 - DY), (0.11, 1.0), (0.33, 0.88)],
+ [(0.06, 0.0), (0.32, 0.12), (0.32, 0.36), (0.0, 0.52)]], 0.33 + 0.36),
+ 'f': ([[(0.0, 1.0), (0.0, -0.28), (0.14, -0.44), (0.31, -0.35)], [(-0.12, 0.03), (0.22, 0.03)]], 0.52),
+ 'ſ': ([[(0.0, 1.0), (0.0, -0.28), (0.14, -0.44), (0.31, -0.35)]], 0.48),
+ 'g': ([[(0.17, -0.01), (0.0, 0.13), (0.0, 0.80), (0.14, 0.94), (0.37, 0.84)],
+ [(0.15, -0.01), (0.37, 0.12), (0.37, 1.24), (0.22, 1.40), (-0.02, 1.32)], [(0.37, 0.03), (0.50, -0.04)]], 0.37 + P),
+ 'h': ([[(-D, -0.46), (0.0, -0.35), (0.0, 1 - DY), (D, 1.0)], [(0.0, 0.17), (P - D, 0.0), (P, DY), (P, 1.14), (P - 0.15, 1.34)]],
+ 2 * P),
+ 'i': ([_post(0.0), [(-0.04, -0.34), (0.05, -0.24)]], P),
+ 'j': ([[(-D, 0.0), (0.0, DY), (0.0, 1.2), (-0.13, 1.37)], [(-0.04, -0.34), (0.05, -0.24)]], P),
+ 'l': ([[(-D, -0.46), (0.0, -0.35), (0.0, 1 - DY), (0.12, 1.0)]], P + 0.04),
+ 'm': ([_post(0.0), _arch(0.0, P), _arch(P, 2 * P)], 3 * P),
+ 'n': ([_post(0.0), _arch(0.0, P)], 2 * P),
+ 'o': ([_O_L, [(0.15, -0.01), (0.38, 0.12), (0.38, 0.88), (0.22, 1.01)]], 0.38 + P),
+ 'p': ([[(-D, 0.0), (0.0, DY), (0.0, 1.42)], [(0.0, 0.17), (0.24, -0.01), (0.38, 0.12), (0.38, 0.88), (0.24, 1.01), (0.0, 0.88)],
+ [(-0.12, 1.42), (0.12, 1.42)]], 0.38 + P),
+ 'ꝑ': ([[(-D, 0.0), (0.0, DY), (0.0, 1.42)], [(0.0, 0.17), (0.24, -0.01), (0.38, 0.12), (0.38, 0.88), (0.24, 1.01), (0.0, 0.88)],
+ [(-0.12, 1.42), (0.12, 1.42)], [(-0.2, 1.2), (0.2, 1.2)]], 0.38 + P),
+ 'q': ([[(0.16, -0.01), (0.0, 0.13), (0.0, 0.87), (0.14, 1.01), (0.38, 0.86)], [(0.14, -0.02), (0.38, 0.12), (0.38, 1.42)],
+ [(0.26, 1.42), (0.50, 1.42)]], 0.38 + P),
+ 'r': ([_post(0.0), [(0.0, 0.17), (0.14, 0.0), (0.27, 0.1)]], P + 0.22),
+ 's': ([[(0.32, 0.10), (0.18, -0.01), (0.02, 0.10), (0.02, 0.34), (0.30, 0.64), (0.30, 0.88), (0.16, 1.01), (-0.01, 0.92)]],
+ 0.32 + 0.38),
+ 't': ([[(0.0, -0.24), (0.0, 1 - DY), (0.12, 1.0)], [(-0.12, 0.03), (0.24, 0.03)]], P + 0.14),
+ 'u': ([[(-D, 0.0), (0.0, DY), (0.0, 1 - DY), (D, 1.0), (P, 0.83)], _post(P)], 2 * P),
+ 'v': ([[(-D, 0.0), (0.0, DY), (0.0, 0.72), (0.2, 1.0)], [(P - D, 0.0), (P, DY), (P, 0.6), (0.2, 1.0)]], 2 * P),
+ 'x': ([[(-0.06, 0.0), (0.04, 0.1), (0.32, 0.9), (0.42, 1.0)], [(0.36, 0.02), (0.0, 1.0)]], 0.42 + 0.32),
+ 'y': ([[(-D, 0.0), (0.0, DY), (0.0, 0.86), (0.1, 0.98), (P, 0.84)], [(P - D, 0.0), (P, DY), (P, 1.24), (P - 0.15, 1.40), (-0.04, 1.32)]],
+ 2 * P),
+ 'z': ([[(-0.04, 0.0), (0.06, 0.08), (0.34, 0.06), (0.02, 0.92), (0.32, 0.92), (0.42, 1.0)]], 0.38 + 0.32),
+ '7': ([[(-0.08, 0.02), (0.28, 0.02), (0.14, 0.45), (0.14, 1.28)]], 0.30 + 0.32),
+ '.': ([[(-0.03, 0.86), (0.06, 0.97)]], 0.30),
+ '·': ([[(-0.03, 0.43), (0.06, 0.54)]], 0.30),
+ ':': ([[(-0.03, 0.34), (0.06, 0.45)], [(-0.03, 0.86), (0.06, 0.97)]], 0.30),
+ ',': ([[(-0.02, 0.86), (0.06, 0.96), (-0.04, 1.18)]], 0.28),
+ ';': ([[(-0.03, 0.38), (0.06, 0.49)], [(-0.02, 0.86), (0.06, 0.96), (-0.04, 1.18)]], 0.30),
+ '/': ([[(0.22, -0.05), (-0.02, 1.05)]], 0.34),
+ '-': ([[(0.0, 0.50), (0.22, 0.36)], [(0.0, 0.66), (0.22, 0.52)]], 0.34),
+ ' ': ([], 0.42),
+}
+GLYPHS = {k: ([np.array(s, np.float32) for s in v[0]], v[1]) for k, v in GLYPHS.items()}
+
+
+def scribal(word):
+ """modern spelling -> what the scribe writes: long s inside the word, round s at the end"""
+ w = word.lower()
+ out = []
+ for i, ch in enumerate(w):
+ nxt = w[i + 1] if i + 1 < len(w) else ''
+ out.append('ſ' if ch == 's' and nxt.isalpha() else ch)
+ return ''.join(out)
+
+
+def word_width(word, xh):
+ return sum(GLYPHS.get(ch, GLYPHS[' '])[1] for ch in word) * xh
+
+
+def _hyphenate(tok, room, xh):
+ """split a word token at a rough Latin syllable break so the first part plus a hyphen fits in `room` px"""
+ w = tok['text']
+ vow = set('aeiouy')
+ core = w.rstrip('.,;:·')
+ best = None
+ for i in range(2, len(core) - 2):
+ a, b = w[:i], w[i:]
+ if not (set(b) & vow) or not (set(a) & vow): continue
+ if not ((a[-1] in vow and b[0] not in vow) or (a[-1] not in vow and b[0] not in vow and a[-2] in vow)): continue
+ if word_width(a + '-', xh) <= room: best = i
+ if best is None or room < 3 * xh: return None
+ a, b = w[:best] + '-', w[best:]
+ return dict(tok, text=a, w=word_width(a, xh)), dict(tok, text=b, w=word_width(b, xh), touch=False)
+
+
+class Block:
+ """a laid-out column of text. words: list of dicts (text, x, y, xh, red, touch, kind); fillers: (x0, x1, y, xh)"""
+ def __init__(self, words, fillers, lines, xh):
+ self.words, self.fillers, self.lines, self.xh = words, fillers, lines, xh
+
+ @property
+ def bottom(self):
+ return self.lines[-1] if self.lines else None
+
+
+class Illuminated:
+ def __init__(self, W=1920, H=1080, seed=0, ss=3, nib_angle=40.0):
+ self.W, self.H, self.ss, self.nib_angle = W, H, ss, nib_angle
+ self.rng = np.random.default_rng(seed)
+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)
+ self.img = np.ones((H, W, 3), np.float32) * hexc(DESK)
+ self.hmap = np.zeros((H, W), np.float32) # relief seen by the room light (cockle, paint body)
+ self.gold = np.zeros((H, W), np.float32) # burnished leaf coverage
+ self.gesso = np.zeros((H, W), np.float32) # gilding cushion height + tooling, px
+ self.shell = np.zeros((H, W), np.float32) # shell-gold coverage
+ self.inkm = np.zeros((H, W), np.float32) # iron-gall coverage (for the halo)
+ self.azm = np.zeros((H, W), np.float32) # azurite coverage (it flakes)
+ self.light = np.ones((H, W), np.float32)
+ self.pagem = np.zeros((H, W), np.float32)
+ self.t_fine = noise2d(H, W, 3, 2, self._seed())
+ self.t_mid = noise2d(H, W, 18, 3, self._seed())
+ self.t_big = noise2d(H, W, 260, 3, self._seed())
+ self.t_wave = noise2d(H, W, 60, 2, self._seed())
+ self.grain = self.rng.random((H, W)).astype(np.float32)
+ self.gx, self.book, self.dip = W / 2, (0, 0, W, H), 0.0
+ self._streak = None
+ self.stages = []
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ # ------------------------------------------------------------ rasterising (local box, ss x supersampled)
+ def _raster(self, polys=(), lines=(), dots=(), pad=3, holes=()):
+ """polys: [(N, 2)]; lines: [((N, 2), width)]; dots: [(x, y, r)]; holes: polys cut back out.
+ Returns (mask, x0, y0) or None."""
+ groups = [np.asarray(p, np.float32).reshape(-1, 2) for p in polys]
+ groups += [np.asarray(l[0], np.float32).reshape(-1, 2) for l in lines]
+ groups += [np.array([[x - r, y - r], [x + r, y + r]], np.float32) for x, y, r in dots]
+ if not groups: return None
+ allp = np.concatenate(groups)
+ mw = max([0.0] + [float(l[1]) for l in lines])
+ x0 = int(np.floor(allp[:, 0].min() - mw - pad)); y0 = int(np.floor(allp[:, 1].min() - mw - pad))
+ x1 = int(np.ceil(allp[:, 0].max() + mw + pad)); y1 = int(np.ceil(allp[:, 1].max() + mw + pad))
+ x0, y0, x1, y1 = max(x0, 0), max(y0, 0), min(x1, self.W), min(y1, self.H)
+ if x1 <= x0 or y1 <= y0: return None
+ ss = self.ss
+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0)
+ d = ImageDraw.Draw(im)
+ off = np.array([x0, y0], np.float32)
+ for p in polys:
+ q = (np.asarray(p, np.float32).reshape(-1, 2) - off) * ss
+ if len(q) >= 3: d.polygon(q.ravel().tolist(), fill=255)
+ for p, w in lines:
+ q = (np.asarray(p, np.float32).reshape(-1, 2) - off) * ss
+ ww = max(1, int(round(w * ss)))
+ if len(q) >= 2: d.line(q.ravel().tolist(), fill=255, width=ww, joint='curve')
+ r = ww / 2
+ for e in (q[0], q[-1]): d.ellipse((e[0] - r, e[1] - r, e[0] + r, e[1] + r), fill=255)
+ for x, y, r in dots:
+ cx, cy, rr = (x - x0) * ss, (y - y0) * ss, r * ss
+ d.ellipse((cx - rr, cy - rr, cx + rr, cy + rr), fill=255)
+ for p in holes:
+ q = (np.asarray(p, np.float32).reshape(-1, 2) - off) * ss
+ if len(q) >= 3: d.polygon(q.ravel().tolist(), fill=0)
+ return np.asarray(im.reduce(ss), np.float32) / 255, x0, y0
+
+ def mask(self, polys=(), lines=(), dots=(), holes=()):
+ """full-canvas anti-aliased mask of polygons, round-pen lines and dots (minus holes)"""
+ out = np.zeros((self.H, self.W), np.float32)
+ r = self._raster(polys, lines, dots, holes=holes)
+ if r is not None:
+ m, x0, y0 = r
+ out[y0:y0 + m.shape[0], x0:x0 + m.shape[1]] = m
+ return out
+
+ def circle(self, cx, cy, r):
+ return np.clip(r - np.hypot(self.XX - cx, self.YY - cy) + 0.5, 0, 1)
+
+ def ring(self, cx, cy, r0, r1):
+ d = np.hypot(self.XX - cx, self.YY - cy)
+ return np.clip(np.minimum(r1 - d, d - r0) + 0.5, 0, 1)
+
+ def ellipse(self, cx, cy, rx, ry, rot=0.0):
+ c, s = np.cos(np.radians(rot)), np.sin(np.radians(rot))
+ u = (self.XX - cx) * c + (self.YY - cy) * s
+ v = -(self.XX - cx) * s + (self.YY - cy) * c
+ q = np.sqrt((u / rx) ** 2 + (v / ry) ** 2)
+ return np.clip((1 - q) * min(rx, ry) + 0.5, 0, 1)
+
+ # ------------------------------------------------------------ the desk and the book
+ def desk(self, colour=DESK):
+ """dark walnut: long grain along the boards, open pores, a lamp pool toward the book"""
+ H, W, r = self.H, self.W, self.rng
+ streak = np.asarray(Image.fromarray(r.random((H // 3, W // 40)).astype(np.float32)).resize((W, H), Image.BICUBIC))
+ warp = noise2d(H, W, 300, 3, self._seed())
+ band = 0.5 + 0.5 * np.sin(self.YY * 0.045 + warp * 18 + 3 * streak)
+ fine = np.asarray(Image.fromarray(r.random((H, W // 12)).astype(np.float32)).resize((W, H), Image.BILINEAR))
+ g = 0.72 + 0.22 * band + 0.10 * (fine - 0.5) + 0.12 * (streak - 0.5)
+ pores = (r.random((H, W)) > 0.996).astype(np.float32)
+ pores = blur(np.asarray(Image.fromarray(pores).resize((W, H))), 0.6) * 3
+ g = g * (1 - 0.35 * np.clip(pores, 0, 1))
+ col = _c(colour)[None, None] * g[..., None]
+ col = col * (1 + 0.12 * (hexc('#5a3018') - _c(colour))[None, None] * (band[..., None] - 0.5))
+ self.img = col.astype(np.float32)
+ lamp = np.exp(-(((self.XX - W * 0.45) / (W * 0.62)) ** 2 + ((self.YY - H * 0.42) / (H * 0.85)) ** 2))
+ self.light *= (0.55 + 0.55 * lamp).astype(np.float32)
+
+ def codex(self, x0, y0, x1, y1, cover=LEATHER, squares=15, stack=7, dip=24):
+ """an open book: boards, page stack, two vellum pages meeting at the gutter. Returns the two page rects."""
+ gx = (x0 + x1) / 2
+ self.gx, self.book, self.dip = gx, (x0, y0, x1, y1), dip
+ # the book's shadow on the desk
+ foot = self.mask([[(x0 - squares, y0 - squares), (x1 + squares, y0 - squares), (x1 + squares, y1 + squares),
+ (x0 - squares, y1 + squares)]])
+ sh = blur(np.roll(np.roll(foot, 14, 0), 10, 1), 16)
+ self.img *= (1 - 0.6 * sh * (1 - foot))[..., None]
+ # leather boards (worn lighter at the edges)
+ bx0, by0, bx1, by1 = x0 - squares, y0 - squares, x1 + squares, y1 + squares
+ board = foot
+ edge = np.minimum.reduce([self.XX - bx0, bx1 - self.XX, self.YY - by0, by1 - self.YY])
+ wear = smoothstep(6, 0, edge) * (0.5 + 0.5 * self.t_mid)
+ lc = _c(cover)[None, None] * (0.8 + 0.3 * self.t_mid[..., None] + 0.08 * (self.t_fine[..., None] - 0.5))
+ lc = lc * (1 + 0.5 * wear[..., None]) + 0.05 * wear[..., None]
+ self.img = self.img * (1 - board[..., None]) + lc * board[..., None]
+ inner = self.mask([[(x0, y0), (x1, y0), (x1, y1), (x0, y1)]])
+ self.hmap += board * (1 - inner) * 0.8 * (self.t_fine - 0.5)
+ # stack of page edges under the open leaves: outer edges fan out a little
+ pages = [(x0, y0, gx, y1), (gx, y0, x1, y1)]
+ vel = hexc(VELLUM)
+ for k in range(stack, 0, -1):
+ o = k * 1.6
+ for (px0, py0, px1, py1), side in zip(pages, (-1, 1)):
+ ox0 = px0 - o if side < 0 else px0
+ ox1 = px1 + o if side > 0 else px1
+ m = self.mask([[(ox0, py0 - o * 0.55), (ox1, py0 - o * 0.55), (ox1, py1 + o * 0.7), (ox0, py1 + o * 0.7)]])
+ tone = (0.70 + 0.05 * (k % 2) - 0.02 * k) * vel
+ self.img = self.img * (1 - m[..., None]) + tone * m[..., None]
+ # the two open leaves
+ for i, (px0, py0, px1, py1) in enumerate(pages):
+ m = self.mask([self._page_outline(px0, py0, px1, py1, i)])
+ self._vellum(m, i)
+ self.pagem = np.maximum(self.pagem, m)
+ # the leaves curl down into the gutter
+ d = np.abs(self.XX - gx)
+ inside = (self.YY > y0 - 30) & (self.YY < y1 + 30) & (self.XX > x0 - 30) & (self.XX < x1 + 30)
+ g = 1 - 0.5 * np.exp(-d / 11) - 0.2 * np.exp(-d / 46) + 0.035 * np.exp(-((d - 120) / 55) ** 2)
+ self.light *= np.where(inside, g, 1).astype(np.float32)
+ return pages
+
+ def _page_outline(self, px0, py0, px1, py1, i):
+ n = 48
+ w = lambda: 1.3 * fbm1d(n, 10, 3, self._seed())
+ xs = np.linspace(px0, px1, n); ys = np.linspace(py0, py1, n)
+ top = np.stack([xs, py0 + w()], 1)
+ bot = np.stack([xs[::-1], py1 + w()], 1)
+ if i == 0: # left leaf: outer edge on the left, gutter straight
+ right = np.array([[px1, py0], [px1, py1]], np.float32)
+ left = np.stack([px0 + w(), ys[::-1]], 1)
+ return np.concatenate([top, right, bot, left])
+ left = np.array([[px0, py1], [px0, py0]], np.float32)
+ right = np.stack([px1 + w(), ys], 1)
+ return np.concatenate([top, right, bot, left])
+
+ def _vellum(self, m, idx):
+ """calf vellum inside mask m"""
+ sl = _bbox(m, 2)
+ h, w = m[sl].shape
+ r = self.rng
+ mm = m[sl][..., None]
+ base = hexc(VELLUM)
+ big = self.t_big[sl]
+ warm = smoothstep(0.45, 0.85, noise2d(h, w, 150, 3, self._seed()))
+ thin = smoothstep(0.62, 0.86, noise2d(h, w, 110, 3, self._seed()))
+ col = base[None, None] * (1 + 0.07 * (big[..., None] - 0.5) + 0.025 * (self.t_wave[sl][..., None] - 0.5))
+ col = col * (1 - 0.42 * warm[..., None]) + hexc('#dcc28e')[None, None] * 0.42 * warm[..., None]
+ col = col * (1 - 0.22 * thin[..., None]) + hexc('#f3ead6')[None, None] * 0.22 * thin[..., None]
+ # fine scraped nap
+ nap = np.asarray(Image.fromarray(r.random((h // 2 + 1, w // 9 + 1)).astype(np.float32)).resize((w, h), Image.BICUBIC))
+ col *= (1 + 0.016 * (nap - 0.5) + 0.010 * (self.t_fine[sl] - 0.5))[..., None]
+ # hair-side follicles: tiny clusters of dark dots
+ fol = Image.new('L', (w * 2, h * 2), 0)
+ d = ImageDraw.Draw(fol)
+ for _ in range(int(w * h / 900)):
+ x, y = r.uniform(0, w * 2), r.uniform(0, h * 2)
+ for k in range(r.integers(1, 4)):
+ xx, yy, rr = x + r.normal(0, 2.4), y + r.normal(0, 2.4), r.uniform(0.6, 1.3)
+ d.ellipse((xx - rr, yy - rr, xx + rr, yy + rr), fill=int(r.uniform(60, 170)))
+ fol = np.asarray(fol.resize((w, h), Image.BOX), np.float32) / 255
+ col *= (1 - 0.32 * fol[..., None] * (1 - hexc('#8a7058'))[None, None])
+ # faint veins
+ vim = Image.new('L', (w, h), 0)
+ d = ImageDraw.Draw(vim)
+ for _ in range(3):
+ x, y = r.uniform(0, w), r.uniform(0, h)
+ a = r.uniform(0, np.pi)
+ n = 60
+ wob = fbm1d(n, 14, 3, self._seed())
+ pts = []
+ for k in range(n):
+ a += 0.05 * wob[k]
+ x += 6 * np.cos(a); y += 6 * np.sin(a)
+ pts.append((x, y))
+ d.line(pts, fill=255, width=int(r.integers(2, 4)), joint='curve')
+ vein = blur(np.asarray(vim, np.float32) / 255, 2.0)
+ col *= (1 - 0.05 * vein[..., None] * (1 - hexc('#9a6a5a'))[None, None] * 3)
+ # darker, grubbier toward the edges of the leaf
+ ed = blur(m[sl], 14)
+ col *= (1 - 0.08 * (1 - smoothstep(0.55, 0.98, ed)))[..., None]
+ self.img[sl] = self.img[sl] * (1 - mm) + col * mm
+ # cockle: the skin is never flat, more so toward the free edges
+ ck = noise2d(h, w, 240, 2, self._seed()) - 0.5
+ self.hmap[sl] += m[sl] * (6.0 * ck + 6.0 * (1 - smoothstep(0.5, 0.95, blur(m[sl], 40))) * ck)
+
+ def flaw(self, cx, cy, rx, ry, rot=0.0):
+ """a natural hole in the skin (the scribe wrote round it): you see the next leaf through it, with a shadow"""
+ hole = self.ellipse(cx, cy, rx, ry, rot)
+ lip = self.ellipse(cx, cy, rx + 2.2, ry + 2.2, rot) - hole
+ under = hexc(VELLUM) * 0.78
+ sh = np.clip(hole - np.roll(np.roll(hole, 3, 0), 2, 1), 0, 1)
+ col = under[None, None] * (1 - 0.35 * sh[..., None])
+ self.img = self.img * (1 - hole[..., None]) + col * hole[..., None]
+ self.img *= (1 - 0.10 * lip)[..., None]
+ self.hmap += lip * 1.5
+
+ # ------------------------------------------------------------ ruling
+ def rule(self, x0, x1, ys, prick_x=None, colour=RULE, opacity=0.3, top=None, bottom=None):
+ """plummet ruling: a line at every y (x-height line of each text line), bounding verticals at x0/x1 running
+ the height of the leaf, prickings at prick_x"""
+ r = self.rng
+ lines = []
+ for y in ys:
+ wob = r.normal(0, 0.25)
+ lines.append(([(x0 - 4, y + wob), (x1 + 4, y + wob + r.normal(0, 0.4))], 0.7))
+ bx0, by0, bx1, by1 = self.book
+ t = top if top is not None else by0 + 6
+ b = bottom if bottom is not None else by1 - 6
+ for x in (x0, x1):
+ lines.append(([(x + r.normal(0, 0.3), t), (x + r.normal(0, 0.6), b)], 0.7))
+ res = self._raster(lines=lines)
+ m, mx, my = res
+ sl = (slice(my, my + m.shape[0]), slice(mx, mx + m.shape[1]))
+ a = m * opacity * (0.7 + 0.6 * self.t_mid[sl])
+ self.img[sl] = self.img[sl] * (1 - a[..., None]) + _c(colour) * a[..., None]
+ if prick_x is not None:
+ pm = self.mask(dots=[(prick_x + r.normal(0, 0.6), y + r.normal(0, 0.5), 1.1) for y in ys])
+ self.img *= (1 - 0.65 * pm)[..., None]
+ self.hmap -= pm * 1.2
+
+ # ------------------------------------------------------------ the scribe's pen
+ def _glyph_polys(self, ch, x, y, xh, rot=0.0, nib=0.2, jitter=1.0):
+ g = GLYPHS.get(ch, GLYPHS[' '])
+ strokes, adv = g
+ r = self.rng
+ dx, dy = r.normal(0, 0.012 * xh) * jitter, r.normal(0, 0.012 * xh) * jitter
+ sc = 1 + r.normal(0, 0.012) * jitter
+ th = np.radians(rot + r.normal(0, 0.6) * jitter)
+ c, s = np.cos(th), np.sin(th)
+ a = np.radians(self.nib_angle + rot + r.normal(0, 1.5) * jitter)
+ nv = 0.5 * nib * xh * sc * np.array([np.cos(a), -np.sin(a)], np.float32)
+ quads, hairs = [], []
+ for st in strokes:
+ u = st[:, 0] * xh * sc
+ v = (st[:, 1] - 1.0) * xh * sc
+ pts = np.stack([x + dx + u * c + v * s, y + dy - u * s + v * c], 1)
+ for i in range(len(pts) - 1):
+ p, q = pts[i], pts[i + 1]
+ quads.append(np.array([p - nv, p + nv, q + nv, q - nv]))
+ hairs.append(pts)
+ return quads, hairs, adv * xh * sc
+
+ def _pen_glyphs(self, items, kind='iron', nib=0.2, opacity=0.95, jitter=1.0):
+ """items: (ch, x, y, xh, rot, load). Each glyph is its pen strokes; load (0..1) is how full the quill was."""
+ if not items: return
+ G = []
+ for ch, x, y, xh, rot, load in items:
+ q, h, _ = self._glyph_polys(ch, x, y, xh, rot, nib, jitter)
+ if q: G.append((q, h, max(0.55, 0.045 * xh), load))
+ if not G: return
+ allp = np.concatenate([np.concatenate(g[0]) for g in G])
+ pad = 4
+ x0 = max(int(allp[:, 0].min()) - pad, 0); y0 = max(int(allp[:, 1].min()) - pad, 0)
+ x1 = min(int(allp[:, 0].max()) + pad + 1, self.W); y1 = min(int(allp[:, 1].max()) + pad + 1, self.H)
+ if x1 <= x0 or y1 <= y0: return
+ ss = self.ss
+ cim = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0)
+ lim = Image.new('L', cim.size, 0)
+ dc, dl = ImageDraw.Draw(cim), ImageDraw.Draw(lim)
+ off = np.array([x0, y0], np.float32)
+ for quads, hairs, hw, load in G:
+ f = int(30 + 225 * np.clip(load, 0, 1))
+ for q in quads:
+ qq = ((q - off) * ss).ravel().tolist()
+ dc.polygon(qq, fill=255); dl.polygon(qq, fill=f)
+ for hl in hairs:
+ qq = ((hl - off) * ss).ravel().tolist()
+ ww = max(1, int(round(hw * ss)))
+ dc.line(qq, fill=255, width=ww); dl.line(qq, fill=f, width=ww)
+ cov = np.asarray(cim.reduce(ss), np.float32) / 255
+ ld = np.asarray(lim.reduce(ss), np.float32) / 255
+ self._ink(cov, ld / np.maximum(cov, 1e-3), x0, y0, kind, opacity)
+
+ def _ink(self, cov, load, x0, y0, kind='iron', opacity=0.95):
+ h, w = cov.shape
+ sl = (slice(y0, y0 + h), slice(x0, x0 + w))
+ load = np.clip(load, 0, 1)
+ rim = np.clip((cov - blur(cov, 0.9)) * 2.2, 0, 1)
+ tex = self.t_fine[sl] - 0.5
+ if kind == 'iron':
+ k = np.clip(0.30 + 0.62 * load + 0.55 * rim + 0.25 * tex, 0, 1)[..., None]
+ col = hexc(INK_THIN) * (1 - k) + hexc(INK) * k
+ a = cov * opacity * (0.80 + 0.20 * load)
+ self.inkm[sl] = np.maximum(self.inkm[sl], a)
+ elif kind == 'red':
+ k = np.clip(0.25 + 0.35 * load + 0.7 * rim + 0.3 * tex, 0, 1)[..., None]
+ col = np.where(k < 0.5, hexc(RED_THIN) * (1 - 2 * k) + hexc(RED) * 2 * k, hexc(RED) * (2 - 2 * k) + hexc(RED_DARK) * (2 * k - 1))
+ a = cov * opacity * (0.82 + 0.18 * load)
+ elif kind == 'blue':
+ k = np.clip(0.3 + 0.4 * load + 0.6 * rim + 0.3 * tex, 0, 1)[..., None]
+ col = hexc(AZURE_LIGHT) * (1 - k) + hexc(AZURE_DARK) * k
+ a = cov * opacity
+ elif kind == 'white':
+ col = np.broadcast_to(hexc(WHITE), cov.shape + (3,)) * (1 - 0.04 * rim[..., None])
+ a = cov * opacity * (0.75 + 0.25 * load)
+ elif kind == 'diagram': # thin compass ink: browner, a little faded
+ k = np.clip(0.35 + 0.3 * load + 0.5 * rim + 0.3 * tex, 0, 1)[..., None]
+ col = hexc('#7a5536') * (1 - k) + hexc('#2e1f14') * k
+ a = cov * opacity
+ self.inkm[sl] = np.maximum(self.inkm[sl], a * 0.6)
+ else:
+ col = np.broadcast_to(_c(kind), cov.shape + (3,))
+ a = cov * opacity
+ a3 = a[..., None]
+ self.img[sl] = self.img[sl] * (1 - a3) + col * a3
+ self.gold[sl] *= 1 - a
+ self.shell[sl] *= 1 - a
+ self.hmap[sl] += a * 0.3
+
+ def pen(self, paths, width=1.0, kind='iron', opacity=0.95, closed=False, dash=None):
+ """round-nib pen lines (diagrams, hairline tendrils, outlines). paths: list of (N, 2); dash=(on, off) px"""
+ lines = []
+ for p in paths:
+ p = np.asarray(p, np.float32)
+ if closed: p = np.vstack([p, p[:1]])
+ if dash:
+ seg = np.linalg.norm(np.diff(p, axis=0), axis=1)
+ s = np.concatenate([[0], np.cumsum(seg)])
+ on, off = dash
+ t = 0.0
+ while t < s[-1]:
+ tt = np.linspace(t, min(t + on, s[-1]), 4)
+ lines.append((np.stack([np.interp(tt, s, p[:, 0]), np.interp(tt, s, p[:, 1])], 1), width))
+ t += on + off
+ else:
+ lines.append((p, width))
+ r = self._raster(lines=lines)
+ if r is None: return
+ m, x0, y0 = r
+ self._ink(m, np.ones_like(m), x0, y0, kind, opacity)
+
+ def outline(self, mask, width=1.4, kind='iron', opacity=0.92):
+ """pen outline round a gilded or painted shape (centred on its edge)"""
+ mb = blur(mask, max(0.45, width * 0.42))
+ band = smoothstep(0.02, 0.32, mb) * smoothstep(0.98, 0.68, mb)
+ sl = _bbox(band, 1)
+ if sl is None: return
+ b = np.clip(band[sl] * 1.25, 0, 1)
+ y0, x0 = sl[0].start, sl[1].start
+ self._ink(b, np.ones_like(b), x0, y0, kind, opacity)
+
+ # ------------------------------------------------------------ writing
+ def write(self, s, x, y, xh, kind='iron', rot=0.0, load=None, nib=0.2, spacing=0.0):
+ """write a line of textura starting at baseline point (x, y). Returns the end x."""
+ items = []
+ cx = x
+ c, sn = np.cos(np.radians(rot)), np.sin(np.radians(rot))
+ lv = 1.0 if load is None else load
+ for word in s.split(' '):
+ for ch in scribal(word):
+ items.append((ch, x + (cx - x) * c, y - (cx - x) * sn, xh, rot, lv))
+ cx += (GLYPHS.get(ch, GLYPHS[' '])[1] + spacing) * xh
+ if load is None: lv = max(0.4, lv - 0.025)
+ cx += GLYPHS[' '][1] * xh
+ self._pen_glyphs(items, kind, nib)
+ return cx - GLYPHS[' '][1] * xh
+
+ def text_width(self, s, xh, spacing=0.0):
+ words = [scribal(w) for w in s.split(' ')]
+ return sum(word_width(w, xh) + spacing * xh * len(w) for w in words) + GLYPHS[' '][1] * xh * (len(words) - 1)
+
+ def arc_text(self, s, cx, cy, r, at=90.0, xh=10, kind='iron', nib=0.2, inside=False):
+ """text round a circle, centred at angle `at` (degrees, counter-clockwise from 3 o'clock); baseline on radius r.
+ Reads clockwise along the top (inside=False)."""
+ chars = scribal(s.replace(' ', ' '))
+ widths = [GLYPHS.get(ch, GLYPHS[' '])[1] * xh for ch in chars]
+ L = sum(widths)
+ sgn = 1 if not inside else -1
+ pos = -L / 2
+ items = []
+ for ch, w in zip(chars, widths):
+ th = np.radians(at) - sgn * pos / r
+ tc = np.radians(at) - sgn * (pos + w / 2) / r
+ rot = np.degrees(tc) - 90 if not inside else np.degrees(tc) + 90
+ px, py = cx + r * np.cos(th), cy - r * np.sin(th)
+ items.append((ch, px, py, xh, rot, 1.0))
+ pos += w
+ self._pen_glyphs(items, kind, nib, jitter=0.6)
+
+ def column(self, text, x0, x1, y, xh, leading, indent=(), align='justify', filler=True):
+ """lay text out in a column, first baseline at y. indent: [(n_lines, left_x)] to wrap round an initial.
+ Markup: *red words* (reserved for the rubricator), ^word = capital touched in red, ¶ = paragraph mark,
+ | = paragraph end. Returns a Block for scribe() and rubricate()."""
+ toks = []
+ red = False
+ for t in text.split():
+ if t == '|':
+ toks.append({'kind': 'break'}); continue
+ if t == '¶':
+ toks.append({'kind': 'para', 'w': 0.75 * xh}); continue
+ touch = t.startswith('^')
+ t = t.lstrip('^')
+ start = t.startswith('*'); end = t.endswith('*')
+ t = t.strip('*')
+ if start: red = True
+ w = scribal(t)
+ toks.append({'kind': 'word', 'text': w, 'w': word_width(w, xh), 'red': red, 'touch': touch})
+ if end: red = False
+ sp = GLYPHS[' '][1] * xh
+ lefts = []
+ for n, lx in indent: lefts += [lx] * n
+ words, fillers, lines = [], [], []
+ i, li = 0, 0
+ while i < len(toks):
+ lx = lefts[li] if li < len(lefts) else x0
+ avail = x1 - lx
+ line, wsum = [], 0.0
+ while i < len(toks):
+ t = toks[i]
+ if t['kind'] == 'break':
+ i += 1; break
+ need = t['w'] + (sp if line else 0)
+ if line and wsum + need > avail:
+ cut = _hyphenate(t, avail - wsum - sp, xh) if t['kind'] == 'word' else None
+ if cut: # the scribe splits the word with a hairline hyphen
+ a, b = cut
+ line.append(a); wsum += sp + a['w']
+ toks[i] = b
+ break
+ line.append(t); wsum += need; i += 1
+ last = i >= len(toks) or toks[i - 1]['kind'] == 'break'
+ by = y + li * leading
+ gaps = len(line) - 1
+ extra = avail - wsum
+ stretch = extra / gaps if (align == 'justify' and gaps and not last and extra < 2.2 * sp * gaps) else 0.0
+ cx = lx
+ for t in line:
+ words.append(dict(t, x=cx, y=by, xh=xh))
+ cx += t['w'] + sp + stretch
+ end = cx - sp - stretch
+ if filler and last and x1 - end > 2.0 * xh:
+ fillers.append((end + 0.5 * xh, x1, by, xh))
+ lines.append(by)
+ li += 1
+ return Block(words, fillers, lines, xh)
+
+ def scribe(self, blk, dip=(16, 30)):
+ """the scribe writes every black word, re-dipping the quill every dip glyphs (ink load 1 -> ~0.4)"""
+ r = self.rng
+ items, left, load = [], 0, 1.0
+ for w in blk.words:
+ if w['kind'] != 'word' or w['red']: continue
+ cx = w['x']
+ for ch in w['text']:
+ if left <= 0:
+ left = int(r.integers(*dip)); n0 = left; load = 1.0
+ items.append((ch, cx, w['y'], w['xh'], 0.0, 0.42 + 0.58 * left / n0))
+ cx += GLYPHS.get(ch, GLYPHS[' '])[1] * w['xh']
+ left -= 1
+ self._pen_glyphs(items, 'iron', 0.2)
+
+ def rubricate(self, blk, blue_first=False):
+ """red words, capitals touched in red, alternating red / blue paragraph marks, line fillers"""
+ items = []
+ for w in blk.words:
+ if w['kind'] == 'word' and w['red']:
+ cx = w['x']
+ for ch in w['text']:
+ items.append((ch, cx, w['y'], w['xh'], 0.0, 0.9))
+ cx += GLYPHS.get(ch, GLYPHS[' '])[1] * w['xh']
+ self._pen_glyphs(items, 'red', 0.2)
+ # capitals touched in red: a translucent stroke of red wash down the first letter
+ polys = []
+ for w in blk.words:
+ if w['kind'] == 'word' and w['touch']:
+ x, y, xh = w['x'], w['y'], w['xh']
+ polys.append([(x - 0.08 * xh, y - 1.05 * xh), (x + 0.10 * xh, y - 1.05 * xh), (x + 0.12 * xh, y - 0.02 * xh), (x - 0.06 * xh, y - 0.02 * xh)])
+ if polys:
+ r = self._raster(polys)
+ m, x0, y0 = r
+ self._ink(blur(m, 0.5), np.ones_like(m), x0, y0, 'red', 0.62)
+ # paragraph marks
+ k = 1 if blue_first else 0
+ for w in blk.words:
+ if w['kind'] == 'para':
+ self.paraph(w['x'] + 0.05 * w['xh'], w['y'], w['xh'], 'blue' if k % 2 else 'red')
+ k += 1
+ for f in blk.fillers:
+ self.line_filler(*f)
+
+ def paraph(self, x, y, xh, kind='red'):
+ """a paragraph mark: a solid bowl and a double stem, written with a wide pen"""
+ u = lambda pts: [(x + a * xh, y + (b - 1) * xh) for a, b in pts]
+ bowl = self.mask([u([(0.42, -0.02), (0.18, -0.04), (0.02, 0.08), (-0.02, 0.32), (0.06, 0.52), (0.24, 0.62), (0.42, 0.60)])])
+ stems = self.mask(lines=[(u([(0.40, -0.04), (0.40, 1.15)]), 0.13 * xh), (u([(0.58, -0.04), (0.58, 1.15)]), 0.09 * xh),
+ (u([(0.30, -0.05), (0.66, -0.05)]), 0.09 * xh)])
+ m = np.maximum(bowl, stems)
+ sl = _bbox(m, 2)
+ self._ink(m[sl], np.ones_like(m[sl]), sl[1].start, sl[0].start, kind, 0.96)
+
+ def line_filler(self, x0, x1, y, xh):
+ """the rubricator closes a short last line: a red zigzag with blue dots in the valleys"""
+ n = max(2, int((x1 - x0) / (0.5 * xh)))
+ xs = np.linspace(x0, x1, n * 2 + 1)
+ ys = y - 0.5 * xh + 0.22 * xh * np.where(np.arange(len(xs)) % 2, -1, 1)
+ self.pen([np.stack([xs, ys], 1)], max(0.9, 0.07 * xh), 'red')
+ dots = [(xs[i], y - 0.5 * xh + 0.42 * xh * (1 if i % 4 == 1 else -1), 0.11 * xh) for i in range(1, len(xs), 2)]
+ m = self.mask(dots=dots)
+ sl = _bbox(m, 2)
+ self._ink(m[sl], np.ones_like(m[sl]), sl[1].start, sl[0].start, 'blue', 0.95)
+
+ # ------------------------------------------------------------ gold
+ def gild(self, mask, cushion=4.0):
+ """lay burnished gold leaf on a raised gesso cushion (over red bole) inside mask"""
+ sl = _bbox(mask, 6)
+ if sl is None: return
+ m = mask[sl]
+ d = blur(m, 2.2)
+ dome = np.clip((d - 0.2) / 0.8, 0, 1) ** 0.6
+ self.gold[sl] = np.maximum(self.gold[sl], m)
+ h = (cushion + 4.5 * (self.t_wave[sl] - 0.5)) * dome * m # the burnisher never leaves it quite flat
+ self.gesso[sl] = np.maximum(self.gesso[sl], h)
+ self.img[sl] = self.img[sl] * (1 - m[..., None]) + hexc(BOLE) * m[..., None]
+
+ def punch(self, pts, r=1.4, depth=1.4):
+ """tooling: a punch pressed into the burnished gold leaves a small dimple that glitters"""
+ m = blur(self.mask(dots=[(x, y, r) for x, y in pts]), 0.6)
+ self.gesso -= depth * m * self.gold
+
+ def shell_gold(self, mask, body=0.5):
+ """shell gold: powdered gold in gum, painted on -- matte and grainy, no cushion"""
+ sl = _bbox(mask, 2)
+ if sl is None: return
+ m = mask[sl]
+ self.shell[sl] = np.maximum(self.shell[sl], m)
+ self.img[sl] = self.img[sl] * (1 - m[..., None]) + hexc('#8c6a2c') * m[..., None]
+ self.hmap[sl] += m * body
+
+ # ------------------------------------------------------------ paint
+ def paint(self, mask, colour, mix=None, texture=1.0, pool=1.0, opacity=0.97, body=0.7, granular=0.0):
+ """tempera inside mask. mix=(colour2, field) blends toward colour2 by a 0..1 field (full canvas).
+ granular: coarse pigment specks (azurite ~1)."""
+ sl = _bbox(mask, 3)
+ if sl is None: return
+ m = mask[sl]
+ col = np.broadcast_to(_c(colour), m.shape + (3,)).astype(np.float32)
+ if mix is not None:
+ c2, f = mix
+ f = np.clip(f[sl], 0, 1)[..., None]
+ col = col * (1 - f) + _c(c2) * f
+ tex = 1 + texture * (0.07 * (self.t_mid[sl] - 0.5) + 0.06 * (self.t_fine[sl] - 0.5))
+ if granular:
+ g = self.grain[sl]
+ tex = tex * (1 - granular * 0.28 * (g > 0.93)) * (1 + granular * 0.16 * (g < 0.04))
+ col = col * tex[..., None]
+ rim = np.clip((m - blur(m, 1.8)) * 2.0, 0, 1)
+ col = col * (1 - 0.22 * pool * rim)[..., None]
+ a = m * opacity
+ self.img[sl] = self.img[sl] * (1 - a[..., None]) + col * a[..., None]
+ self.gold[sl] *= 1 - a
+ self.shell[sl] *= 1 - a
+ self.hmap[sl] += m * body
+ if _c(colour)[2] > 0.5 and _c(colour)[0] < 0.3:
+ self.azm[sl] = np.maximum(self.azm[sl], m)
+
+ def wash(self, mask, colour, opacity=0.25):
+ """a thin transparent wash (multiplies, keeps the vellum showing)"""
+ sl = _bbox(mask, 2)
+ if sl is None: return
+ a = (mask[sl] * opacity * (0.85 + 0.3 * self.t_mid[sl]))[..., None]
+ self.img[sl] = self.img[sl] * (1 - a + a * _c(colour) / max(hexc(VELLUM).max(), 1e-3))
+
+ # ------------------------------------------------------------ ornament objects
+ def initial(self, letter, x0, y0, size, body=ROSE, scene='night'):
+ return Initial(self, letter, x0, y0, size, body, scene)
+
+ def border(self, path, width=10, avoid=(), bounds=None, seed=0, every=78, reach=1.0):
+ return Border(self, path, width, avoid, bounds, seed, every, reach)
+
+ def versal(self, letter, x, y, size, colour=AZURE, flourish=RED, reach=(160, 160)):
+ return Versal(self, letter, x, y, size, colour, flourish, reach)
+
+ def astrolabe(self, cx, cy, R, **kw):
+ return Astrolabe(self, cx, cy, R, **kw)
+
+ def spheres(self, cx, cy, R, **kw):
+ return Spheres(self, cx, cy, R, **kw)
+
+ def star(self, cx, cy, r, points=8, inner=0.42, rot=0.0):
+ a = np.radians(rot) + np.arange(points * 2) * np.pi / points
+ rr = np.where(np.arange(points * 2) % 2, r * inner, r)
+ return np.stack([cx + rr * np.sin(a), cy - rr * np.cos(a)], 1)
+
+ # ------------------------------------------------------------ time
+ def show_through(self, x0, x1, ys, xh, avoid=(), opacity=0.06):
+ """the writing on the other side of the leaf, mirrored and soft, showing through the skin"""
+ r = self.rng
+ vocab = 'et in de per ad cum est sunt quod circa terra motus orbis caelum gradus linea medium semper autem ' \
+ 'superior inferior numerus tempus annus dies hora signum umbra lumen quantitas distantia'.split()
+ items = []
+ for y in ys:
+ x = x0 + r.uniform(0, 2) * xh
+ while x < x1 - 2 * xh:
+ w = scribal(vocab[r.integers(len(vocab))])
+ ww = word_width(w, xh)
+ if x + ww > x1: break
+ if not any(a[0] - 4 < x < a[2] + 4 and a[1] - 4 < y < a[3] + 4 for a in avoid):
+ cx = x
+ for ch in w:
+ items.append((ch, x0 + x1 - cx, y, xh, 0.0, 1.0)) # mirrored position (letter flipped below)
+ cx += GLYPHS[ch][1] * xh
+ x += ww + GLYPHS[' '][1] * xh * r.uniform(1, 1.6)
+ polys = []
+ for ch, x, y, xh_, rot, ld in items:
+ q, h, _ = self._glyph_polys(ch, x, y, xh_, 0.0, 0.2, 1.0)
+ for quad in q:
+ quad = quad.copy(); quad[:, 0] = 2 * x - quad[:, 0] # flip the letter itself
+ polys.append(quad)
+ res = self._raster(polys)
+ if res is None: return
+ m, mx, my = res
+ m = blur(m, 1.6)
+ sl = (slice(my, my + m.shape[0]), slice(mx, mx + m.shape[1]))
+ a = (m * opacity * self.pagem[sl])[..., None]
+ self.img[sl] = self.img[sl] * (1 - a) + hexc('#5a4632') * a
+
+ def age(self, foxing=40, soil=1.0, flakes=1.0, halo=1.0):
+ """six centuries: iron-gall halo, foxing, thumb soil, gold flaking to the bole, chipped azurite"""
+ r = self.rng
+ H, W = self.H, self.W
+ # iron-gall halo (the ink browns the skin around it)
+ hl = np.clip(blur(self.inkm, 2.4) - self.inkm, 0, 1) * halo
+ self.img *= (1 - 0.10 * hl[..., None] * (1 - hexc('#8a6238'))[None, None] * 2.2)
+ # foxing
+ bx0, by0, bx1, by1 = self.book
+ dots = [(r.uniform(bx0, bx1), r.uniform(by0, by1), r.uniform(1.0, 4.5)) for _ in range(foxing)]
+ fx = blur(self.mask(dots=dots), 2.0) * self.pagem
+ self.img *= (1 - 0.18 * fx[..., None] * (1 - hexc('#a0703e'))[None, None] * 1.6)
+ # thumb soil on the lower outer corners (where the leaves are turned)
+ for cx in (bx0, bx1):
+ d = np.hypot((self.XX - cx) / 1.1, self.YY - by1)
+ s = np.exp(-(d / 150) ** 2) * (0.6 + 0.6 * self.t_mid) * soil * self.pagem
+ self.img *= (1 - 0.16 * s[..., None] * (1 - hexc('#8f7a5c'))[None, None] * 2.4)
+ # gold flakes: small irregular losses, mostly toward the cushion edges, show the red bole
+ if flakes:
+ n = noise2d(H, W, 5, 2, self._seed())
+ edge = 1 - smoothstep(0.5, 0.95, blur(self.gold, 2.5))
+ lost = (n > 0.82 - 0.10 * edge * flakes) & (self.gold > 0.5) & (self.t_mid > 0.55)
+ lost = blur(lost.astype(np.float32), 0.6) * self.gold
+ self.gold *= 1 - lost
+ deep = lost * (self.grain > 0.7)
+ self.img = self.img * (1 - 0.5 * deep[..., None]) + hexc('#e8dcc4') * 0.5 * deep[..., None]
+ # azurite chips (it is the first pigment to flake)
+ n2 = noise2d(H, W, 4, 2, self._seed())
+ chip = blur(((n2 > 0.86) & (self.azm > 0.5) & (self.t_big > 0.45)).astype(np.float32), 0.5) * self.azm
+ self.img = self.img * (1 - chip[..., None]) + hexc('#d9c9a6') * chip[..., None]
+ self.hmap -= chip * 0.6
+
+ # ------------------------------------------------------------ light and output
+ def _streaks(self):
+ if self._streak is None:
+ H, W, r = self.H, self.W, self.rng
+ s = np.asarray(Image.fromarray(r.random((H // 2, W // 14)).astype(np.float32)).resize((W, H), Image.BICUBIC))
+ s2 = np.asarray(Image.fromarray(r.random((H // 14, W // 2)).astype(np.float32)).resize((W, H), Image.BICUBIC))
+ # gold leaf comes in squares: faint raised seams where two leaves overlap
+ seam = np.zeros((H, W), np.float32)
+ size = 64
+ for row in range(H // size + 1):
+ off = r.uniform(0, size)
+ ys = slice(row * size, min((row + 1) * size, H))
+ xx = (self.XX[ys] + off) % size
+ seam[ys] = np.maximum(seam[ys], np.exp(-(np.minimum(xx, size - xx) / 0.9) ** 2))
+ yy = self.YY % size
+ seam = np.maximum(seam, np.exp(-(np.minimum(yy, size - yy) / 0.9) ** 2))
+ self._streak = (0.04 * (s - 0.5) + 0.03 * (s2 - 0.5) + 0.12 * seam).astype(np.float32)
+ return self._streak
+
+ def composite(self):
+ H, W = self.H, self.W
+ img = self.img.copy()
+ L = np.array([-0.48, -0.56, 0.68], np.float32); L /= np.linalg.norm(L)
+ gy, gx = np.gradient(self.hmap)
+ nz = 1 / np.sqrt(gx * gx + gy * gy + 1)
+ shade = (-gx * L[0] - gy * L[1] + L[2]) * nz / L[2]
+ img *= np.clip(shade, 0.72, 1.22)[..., None]
+ # shell gold: matte, grainy, follows the relief a little
+ sl = _bbox(self.shell, 1)
+ if sl is not None:
+ g = self.grain[sl]
+ E = 0.50 + 0.55 * (shade[sl] - 1) + 0.10 * (self.t_fine[sl] - 0.5) + 0.06 * (self.t_mid[sl] - 0.5)
+ E = E + 0.35 * (g > 0.985)
+ col = _gold_ramp(E * 0.96) * np.array([1.0, 0.97, 0.9], np.float32)
+ a = self.shell[sl][..., None]
+ img[sl] = img[sl] * (1 - a) + col * a
+ # burnished gold: a mirror of the room
+ sl = _bbox(self.gold, 2)
+ if sl is not None:
+ h = self.gesso[sl] + self._streaks()[sl] * (self.gold[sl] > 0)
+ h = blur(h, 0.6)
+ hy, hx = np.gradient(h)
+ n = np.stack([-hx, -hy, np.ones_like(hx)], -1)
+ n /= np.linalg.norm(n, axis=-1, keepdims=True)
+ cam = np.array([W * 0.5, H * 0.45, 6000.0], np.float32)
+ v = np.stack([cam[0] - self.XX[sl], cam[1] - self.YY[sl], np.full(hx.shape, cam[2], np.float32)], -1)
+ v /= np.linalg.norm(v, axis=-1, keepdims=True)
+ nv = (n * v).sum(-1, keepdims=True)
+ rf = 2 * nv * n - v
+ Lw = np.array([-0.40, -0.45, 0.80], np.float32); Lw /= np.linalg.norm(Lw)
+ dd = (rf * Lw).sum(-1)
+ E = 0.06 + 0.9 * smoothstep(0.55, 1.0, dd) ** 1.4 + 0.3 * smoothstep(0.975, 0.997, dd)
+ E = E + 0.04 * (self.t_mid[sl] - 0.5)
+ col = _gold_ramp(E)
+ a = self.gold[sl][..., None]
+ img[sl] = img[sl] * (1 - a) + col * a
+ # the leaves bow down into the gutter: their top and bottom edges dip inward near the spine
+ if self.dip:
+ gxp = self.gx
+ x0 = max(int(gxp - 110), 0); x1 = min(int(gxp + 110), W)
+ bx0, by0, bx1, by1 = self.book
+ cy = (by0 + by1) / 2
+ hh = (by1 - by0) / 2
+ xs = np.arange(x0, x1, dtype=np.float32)
+ s = self.dip * np.exp(-np.abs(xs - gxp) / 26)
+ yy = np.arange(H, dtype=np.float32)[:, None]
+ src = cy + (yy - cy) * (1 + s[None, :] / hh)
+ src = np.clip(src, 0, H - 1.001)
+ i0 = np.floor(src).astype(np.int32); f = (src - i0)[..., None]
+ slab = img[:, x0:x1]
+ cols = np.arange(x1 - x0)[None, :]
+ img[:, x0:x1] = slab[i0, cols] * (1 - f) + slab[i0 + 1, cols] * f
+ img *= self.light[..., 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
+
+
+# ====================================================================== ornaments
+def _lombard(il, cx, cy, R, letter='O', squash=0.94):
+ """a Lombardic capital: body mask, counter mask. The bowl swells on the left and right (thin at top and bottom),
+ with small pearls jutting into the counter; Q adds a sweeping tail."""
+ X, Y = il.XX - cx, (il.YY - cy) / squash
+ q = (np.abs(X / R) ** 2.3 + np.abs(Y / R) ** 2.3) ** (1 / 2.3)
+ outer = np.clip((1 - q) * R + 0.5, 0, 1)
+ rx, ry = 0.50 * R, 0.74 * R
+ qi = np.sqrt((X / rx) ** 2 + (Y / ry) ** 2)
+ counter = np.clip((1 - qi) * rx + 0.5, 0, 1)
+ # pearls: small pointed bumps on the inside of the thick sides
+ for sx in (-1, 1):
+ pearl = il.ellipse(cx + sx * rx * 0.98, cy, 0.13 * R, 0.07 * R)
+ counter = np.clip(counter - pearl, 0, 1)
+ body = np.clip(outer - counter, 0, 1)
+ if letter == 'Q':
+ t = np.linspace(0, 1, 40)
+ p0 = np.array([cx + 0.40 * R, cy + 0.80 * R]); p1 = np.array([cx + 0.95 * R, cy + 1.10 * R])
+ p2 = np.array([cx + 1.18 * R, cy + 1.02 * R])
+ c = ((1 - t) ** 2)[:, None] * p0 + (2 * t * (1 - t))[:, None] * p1 + (t ** 2)[:, None] * p2
+ tan = np.gradient(c, axis=0); tan /= np.linalg.norm(tan, axis=1, keepdims=True) + 1e-6
+ nrm = np.stack([-tan[:, 1], tan[:, 0]], 1)
+ w = 0.17 * R * (1 - t) ** 0.9 + 0.8
+ tail = il.mask([np.concatenate([c + nrm * w[:, None], (c - nrm * w[:, None])[::-1]])])
+ body = np.maximum(body, tail * (1 - counter))
+ return body, counter
+
+
+class Initial:
+ """a historiated initial: a Lombardic letter in tempera with white tracery on a burnished, tooled gold panel;
+ the counter holds a small night scene (sky, crescent moon, gold stars, a hill with an observatory tower)"""
+
+ def __init__(self, il, letter, x0, y0, size, body=ROSE, scene='night'):
+ self.il, self.letter, self.size, self.body_col, self.scene = il, letter, size, body, scene
+ self.x0, self.y0, self.x1, self.y1 = x0, y0, x0 + size, y0 + size
+ self.cx, self.cy, self.R = x0 + size * 0.46, y0 + size * 0.45, size * 0.385
+ self.panel = il.mask([[(x0, y0), (x0 + size, y0), (x0 + size, y0 + size), (x0, y0 + size)]])
+ self.body, self.counter = _lombard(il, self.cx, self.cy, self.R, letter)
+ self.ground = np.clip(self.panel - self.body - self.counter, 0, 1)
+ R, cx, cy = self.R, self.cx, self.cy
+ # the scene inside the counter
+ rx, ry = 0.50 * R, 0.74 * R
+ hx = np.linspace(cx - rx * 1.2, cx + rx * 1.2, 30)
+ hy = cy + ry * 0.42 - 0.20 * ry * np.exp(-((hx - cx + 0.15 * rx) / (0.55 * rx)) ** 2) + 3 * fbm1d(30, 8, 2, 3)
+ self.hill = il.mask([np.concatenate([np.stack([hx, hy], 1), [(cx + rx * 1.2, cy + ry * 1.2), (cx - rx * 1.2, cy + ry * 1.2)]])]) * self.counter
+ tw, th = 0.20 * rx, 0.55 * ry
+ tx, ty = cx + 0.12 * rx, cy + ry * 0.24
+ self.tower_pts = [(tx - tw, ty), (tx - tw, ty - th), (tx - tw * 1.25, ty - th), (tx - tw * 1.25, ty - th - 0.12 * ry),
+ (tx - tw * 0.4, ty - th - 0.12 * ry), (tx - tw * 0.4, ty - th - 0.05 * ry), (tx + tw * 0.4, ty - th - 0.05 * ry),
+ (tx + tw * 0.4, ty - th - 0.12 * ry), (tx + tw * 1.25, ty - th - 0.12 * ry), (tx + tw * 1.25, ty - th),
+ (tx + tw, ty - th), (tx + tw, ty)]
+ self.tower = il.mask([self.tower_pts]) * self.counter
+ self.door = il.mask([[(tx - tw * 0.35, ty), (tx - tw * 0.35, ty - th * 0.28), (tx, ty - th * 0.36),
+ (tx + tw * 0.35, ty - th * 0.28), (tx + tw * 0.35, ty)]])
+ self.window = il.mask([[(tx - tw * 0.18, ty - th * 0.62), (tx - tw * 0.18, ty - th * 0.78), (tx, ty - th * 0.84),
+ (tx + tw * 0.18, ty - th * 0.78), (tx + tw * 0.18, ty - th * 0.62)]])
+ mx, my, mr = cx - 0.22 * rx, cy - 0.48 * ry, 0.30 * rx
+ self.moon = np.clip(il.circle(mx, my, mr) - il.circle(mx + 0.42 * mr, my - 0.20 * mr, mr * 0.86), 0, 1)
+ self.stars = [(cx + 0.38 * rx, cy - 0.55 * ry, 4.2), (cx + 0.05 * rx, cy - 0.20 * ry, 3.2), (cx - 0.55 * rx, cy - 0.05 * ry, 3.0),
+ (cx + 0.55 * rx, cy - 0.12 * ry, 2.6), (cx + 0.22 * rx, cy - 0.80 * ry, 2.6), (cx - 0.30 * rx, cy + 0.10 * ry, 2.2),
+ (cx + 0.62 * rx, cy - 0.36 * ry, 2.0), (cx - 0.05 * rx, cy - 0.66 * ry, 2.0)]
+
+ def gild(self):
+ il = self.il
+ il.gild(self.ground, cushion=5.0)
+ sm = il.mask([il.star(x, y, r * 1.5, 6, 0.45) for x, y, r in self.stars]) * self.counter
+ il.gild(sm, cushion=1.5)
+ # tooling: a row of punched dots inside the panel edge and rosettes in the open gold
+ x0, y0, x1, y1, m = self.x0, self.y0, self.x1, self.y1, 9
+ pts = []
+ for t in np.arange(0, 1, 1 / 46):
+ pts += [(x0 + m + (x1 - x0 - 2 * m) * t, y0 + m), (x1 - m, y0 + m + (y1 - y0 - 2 * m) * t),
+ (x1 - m - (x1 - x0 - 2 * m) * t, y1 - m), (x0 + m, y1 - m - (y1 - y0 - 2 * m) * t)]
+ pts = [p for p in pts if self.ground[int(p[1]), int(p[0])] > 0.9]
+ ros = []
+ for gx in np.arange(x0 + 26, x1 - 10, 30):
+ for gy in np.arange(y0 + 26, y1 - 10, 30):
+ if all(self.ground[int(gy + dy), int(gx + dx)] > 0.9 for dx in (-8, 0, 8) for dy in (-8, 0, 8)):
+ ros += [(gx + 4 * np.cos(a), gy + 4 * np.sin(a)) for a in np.arange(6) * np.pi / 3] + [(gx, gy)]
+ il.punch(pts, 1.3, 1.6)
+ il.punch(ros, 1.0, 1.2)
+
+ def paint(self):
+ il = self.il
+ R, cx, cy = self.R, self.cx, self.cy
+ sky = smoothstep(cy - 0.8 * R, cy + 0.5 * R, il.YY)
+ il.paint(np.clip(self.counter - self.hill - self.tower, 0, 1), '#1c2f6c', mix=(AZURE, sky), granular=1.0)
+ il.paint(self.hill, GREEN, mix=(GREEN_DARK, smoothstep(cy + 0.25 * R, cy + 0.8 * R, il.YY)))
+ il.paint(self.tower, '#d8c7a6', mix=('#a8916c', smoothstep(cx - 0.05 * R, cx + 0.1 * R, il.XX)))
+ il.paint(self.door * self.tower, '#3a2a1e')
+ il.paint(self.window * self.tower, '#f0c860')
+ il.paint(self.moon, SILVER, mix=('#9a988f', smoothstep(cx - 0.35 * R, cx - 0.05 * R, il.XX)))
+ # letter body: rose, darker toward the counter and on the lower right
+ inner = blur(self.counter, R * 0.12)
+ f = np.clip(1.6 * inner + 0.35 * smoothstep(-R, R, (il.XX - cx) + (il.YY - cy)), 0, 1)
+ il.paint(self.body, self.body_col, mix=(ROSE_DARK, f))
+ d = np.hypot(il.XX - cx, (il.YY - cy) / 0.94)
+ lift = smoothstep(0.80 * R, 0.97 * R, d) * smoothstep(0.2 * R, -0.6 * R, (il.XX - cx) + (il.YY - cy))
+ il.paint(self.body * lift, '#efc3c3', opacity=0.55, body=0.1)
+
+ def pen(self):
+ il = self.il
+ R, cx, cy = self.R, self.cx, self.cy
+ # white-lead tracery on the letter body: a line down the thick sides, dot triplets, short highlights
+ rm = 0.75 * R
+ paths = []
+ for a0, a1 in ((110, 250), (-62, 62)):
+ a = np.radians(np.linspace(a0, a1, 60))
+ rr = np.where(np.cos(a) < 0, 0.765, 0.77) * R
+ paths.append(np.stack([cx + rr * np.cos(a), cy - rr * np.sin(a) * 0.94], 1))
+ il.pen(paths, 1.1, 'white', 0.9)
+ dots = []
+ for a in np.radians(np.arange(120, 245, 21)):
+ px, py = cx + 0.885 * R * np.cos(a), cy - 0.885 * R * np.sin(a) * 0.94
+ dots += [(px, py, 1.3), (px + 2.6 * np.cos(a + 1.57), py - 2.6 * np.sin(a + 1.57), 1.0),
+ (px - 2.6 * np.cos(a + 1.57), py + 2.6 * np.sin(a + 1.57), 1.0)]
+ for a in np.radians(np.arange(-50, 55, 21)):
+ dots.append((cx + 0.885 * R * np.cos(a), cy - 0.885 * R * np.sin(a) * 0.94, 1.2))
+ m = il.mask(dots=dots)
+ sl = _bbox(m, 2)
+ il._ink(m[sl], np.ones_like(m[sl]), sl[1].start, sl[0].start, 'white', 0.92)
+ # moon glow line and tower masonry
+ il.outline(self.moon, 1.0)
+ tx = [p[0] for p in self.tower_pts]; ty = [p[1] for p in self.tower_pts]
+ courses = [[(min(tx) + 2, y), (max(tx) - 2, y)] for y in np.arange(max(ty) - 6, min(ty) + 8, -6.5)]
+ il.pen(courses, 0.6, 'diagram', 0.5)
+ il.outline(self.tower, 1.1)
+ il.outline(self.door * self.tower, 0.8)
+ il.outline(self.hill, 1.0)
+ il.outline(il.mask([il.star(x, y, r * 1.5, 6, 0.45) for x, y, r in self.stars]) * self.counter, 0.7, opacity=0.7)
+ il.outline(self.body, 1.6)
+ il.outline(self.panel, 2.0)
+
+
+class Border:
+ """a bar border (segments of burnished gold, azure and rose with white tracery) along `path`, sprouting
+ hairline ivy sprays: tendrils grown recursively, with gold ivy leaves, flowers, gold bezants and curls"""
+
+ def __init__(self, il, path, width=10, avoid=(), bounds=None, seed=0, every=78, reach=1.0):
+ self.il, self.width = il, width
+ r = np.random.default_rng(seed)
+ self.r = r
+ p = np.asarray(path, np.float32)
+ seg = np.linalg.norm(np.diff(p, axis=0), axis=1)
+ s = np.concatenate([[0], np.cumsum(seg)])
+ n = int(s[-1] / 2) + 2
+ ss = np.linspace(0, s[-1], n)
+ self.path = np.stack([np.interp(ss, s, p[:, 0]), np.interp(ss, s, p[:, 1])], 1)
+ self.length = s[-1]
+ # bar segments
+ cuts = [0.0]
+ while cuts[-1] < s[-1]:
+ cuts.append(cuts[-1] + r.uniform(38, 62))
+ cuts[-1] = s[-1]
+ kinds = ['gold', AZURE, 'gold', ROSE]
+ self.segments = []
+ for i in range(len(cuts) - 1):
+ k = (ss >= cuts[i]) & (ss <= cuts[i + 1])
+ self.segments.append((kinds[i % 4], self.path[k]))
+ self.knots = [self.path[min(int(c / s[-1] * (n - 1)), n - 1)] for c in cuts[1:-1]]
+ # sprays
+ self.avoid = [tuple(a) for a in avoid]
+ self.bounds = bounds or (0, 0, il.W, il.H)
+ self.lines, self.leaves, self.flowers, self.balls = [], [], [], []
+ tan = np.gradient(self.path, axis=0)
+ tan /= np.linalg.norm(tan, axis=1, keepdims=True) + 1e-6
+ for k, t in enumerate(np.arange(r.uniform(20, 40), s[-1] - 10, every)):
+ i = int(t / s[-1] * (n - 1))
+ base = self.path[i]
+ a_t = np.arctan2(tan[i, 1], tan[i, 0])
+ for side in (-1, 1):
+ if r.random() < 0.15: continue
+ a = a_t + side * (np.pi / 2) + r.normal(0, 0.35)
+ start = base + np.array([np.cos(a), np.sin(a)]) * (width / 2 + 1)
+ self._spray(start, a, r.uniform(80, 130) * reach, 2, side)
+ # finials at the ends of the bar: a long tendril continuing the bar's direction
+ for end, sgn in ((0, -1), (n - 1, 1)):
+ a = np.arctan2(tan[end, 1], tan[end, 0]) * 1.0 + (np.pi if sgn < 0 else 0)
+ self._spray(self.path[end] + np.array([np.cos(a), np.sin(a)]) * 3, a, 120 * reach, 2, 1)
+
+ def _bar_dist(self, p):
+ return float(np.min(np.hypot(self.path[:, 0] - p[0], self.path[:, 1] - p[1])))
+
+ def _ok(self, p, margin=7, bar=0.0):
+ if bar and self._bar_dist(p) < self.width / 2 + bar: return False
+ x0, y0, x1, y1 = self.bounds
+ if not (x0 + margin < p[0] < x1 - margin and y0 + margin < p[1] < y1 - margin): return False
+ for a in self.avoid:
+ if a[0] - margin < p[0] < a[2] + margin and a[1] - margin < p[1] < a[3] + margin: return False
+ return True
+
+ def _spray(self, start, ang, length, depth, side):
+ r = self.r
+ step = 2.4
+ n = int(length / step)
+ turn = side if r.random() < 0.7 else -side
+ k0 = r.uniform(0.004, 0.012) * turn
+ pts = [np.asarray(start, np.float32)]
+ a = ang
+ wav = fbm1d(max(n, 4), 20, 2, int(r.integers(1 << 30)))
+ for i in range(n):
+ t = i / max(n, 1)
+ a += (k0 + 0.010 * wav[i] + 0.045 * turn * t ** 4) * step
+ q = pts[-1] + step * np.array([np.cos(a), np.sin(a)], np.float32)
+ if not self._ok(q, bar=2.0 if i > 3 else 0.0): break
+ pts.append(q)
+ if len(pts) < 5: return
+ pts = np.array(pts)
+ self.lines.append(pts)
+ m = len(pts)
+ # leaves on short stalks along the stem, alternating sides
+ for j in range(int(m * step / 42)):
+ idx = int(m * r.uniform(0.2, 0.85))
+ tg = pts[min(idx + 1, m - 1)] - pts[max(idx - 1, 0)]
+ ta = np.arctan2(tg[1], tg[0])
+ sd = 1 if j % 2 else -1
+ la = ta + sd * r.uniform(0.7, 1.2)
+ stalk_end = pts[idx] + 6 * np.array([np.cos(la), np.sin(la)])
+ ls = r.uniform(11, 15)
+ if self._ok(stalk_end, 9, ls + 3) and self._ok(stalk_end + ls * np.array([np.cos(la), np.sin(la)]), 9, 3) \
+ and self._ok(stalk_end + 0.6 * ls * np.array([np.cos(la + 1.1), np.sin(la + 1.1)]), 9) \
+ and self._ok(stalk_end + 0.6 * ls * np.array([np.cos(la - 1.1), np.sin(la - 1.1)]), 9):
+ self.lines.append(np.array([pts[idx], stalk_end]))
+ self.leaves.append((stalk_end, la, ls))
+ if depth > 0:
+ for j in range(int(r.integers(1, 3))):
+ idx = int(m * r.uniform(0.3, 0.7))
+ tg = pts[min(idx + 1, m - 1)] - pts[max(idx - 1, 0)]
+ sd = 1 if (j + depth) % 2 else -1
+ a2 = np.arctan2(tg[1], tg[0]) + sd * r.uniform(0.6, 1.0)
+ self._spray(pts[idx], a2, length * r.uniform(0.4, 0.62), depth - 1, sd)
+ # terminal
+ end = pts[-1]
+ tg = pts[-1] - pts[-3]
+ ea = np.arctan2(tg[1], tg[0])
+ u = r.random()
+ ls = r.uniform(13, 17)
+ if u < 0.42 and self._ok(end + (4 + ls) * np.array([np.cos(ea), np.sin(ea)]), 9, 3) and self._ok(end, 9, ls + 3):
+ self.leaves.append((end + 4 * np.array([np.cos(ea), np.sin(ea)]), ea, ls))
+ elif u < 0.62:
+ fp, fr = end + 5 * np.array([np.cos(ea), np.sin(ea)]), r.uniform(5.5, 7.0)
+ if self._ok(fp, fr + 8, fr + 4):
+ self.flowers.append((fp, AZURE if r.random() < 0.55 else ROSE, fr))
+ else:
+ # curl and a gold bezant with three little hairs
+ cur = [end]
+ a, rad = ea, 5.0
+ for i in range(26):
+ a += 0.32 * turn
+ rad *= 0.94
+ cur.append(cur[-1] + rad * 0.32 * np.array([np.cos(a), np.sin(a)]))
+ self.lines.append(np.array(cur))
+ bp = pts[int(m * 0.6)] + 9 * np.array([np.cos(ea - turn * 1.3), np.sin(ea - turn * 1.3)])
+ if self._ok(bp, 8, 8): self.balls.append((bp, r.uniform(3.4, 4.4)))
+
+ @staticmethod
+ def leaf_pts(p, a, s):
+ u = np.array([(0.0, 0.0), (0.0, -0.18), (0.08, -0.42), (0.22, -0.66), (0.30, -0.40), (0.42, -0.22), (0.70, -0.20),
+ (1.12, 0.0), (0.70, 0.20), (0.42, 0.22), (0.30, 0.40), (0.22, 0.66), (0.08, 0.42), (0.0, 0.18)],
+ np.float32) * s
+ c, sn = np.cos(a), np.sin(a)
+ return np.stack([p[0] + u[:, 0] * c - u[:, 1] * sn, p[1] + u[:, 0] * sn + u[:, 1] * c], 1)
+
+ def _seg_mask(self, which):
+ lines = [(pts, self.width) for k, pts in self.segments if (k == which) and len(pts) > 1]
+ return self.il.mask(lines=lines) if lines else None
+
+ def gild(self):
+ il = self.il
+ m = self._seg_mask('gold')
+ if m is not None: il.gild(m, cushion=3.5)
+ lm = il.mask([self.leaf_pts(p, a, s) for p, a, s in self.leaves])
+ il.gild(lm, cushion=2.2)
+ il.gild(il.mask(dots=[(p[0], p[1], rr) for p, rr in self.balls]), cushion=2.0)
+
+ def paint(self):
+ il = self.il
+ for col, dark in ((AZURE, AZURE_DARK), (ROSE, ROSE_DARK)):
+ m = self._seg_mask(col)
+ if m is None: continue
+ il.paint(m, col, mix=(dark, blur(m, 2) * 0 + smoothstep(0.0, 1.0, il.t_mid)), granular=1.0 if col == AZURE else 0.0)
+ # flowers: five petals round a centre
+ for col in (AZURE, ROSE):
+ dots = []
+ for p, c, rr in self.flowers:
+ if c != col: continue
+ for k in range(5):
+ a = k * 2 * np.pi / 5 + 0.3
+ dots.append((p[0] + rr * 0.75 * np.cos(a), p[1] + rr * 0.75 * np.sin(a), rr * 0.55))
+ if dots:
+ il.paint(il.mask(dots=dots), col, granular=1.0 if col == AZURE else 0)
+
+ def pen(self):
+ il = self.il
+ # white tracery on the coloured bar segments: a wave with dots
+ waves = []
+ for k, pts in self.segments:
+ if k == 'gold' or len(pts) < 6: continue
+ tg = np.gradient(pts, axis=0); tg /= np.linalg.norm(tg, axis=1, keepdims=True) + 1e-6
+ nrm = np.stack([-tg[:, 1], tg[:, 0]], 1)
+ s = np.arange(len(pts)) * 2.0
+ waves.append(pts[2:-2] + nrm[2:-2] * (self.width * 0.22) * np.sin(s[2:-2] / 5.5)[:, None])
+ il.pen(waves, 0.8, 'white', 0.9)
+ bar = il.mask(lines=[(self.path, self.width)])
+ il.outline(bar, 1.3)
+ # bands across the bar where segments meet
+ tan = np.gradient(self.path, axis=0); tan /= np.linalg.norm(tan, axis=1, keepdims=True) + 1e-6
+ bands = []
+ for kp in self.knots:
+ i = int(np.argmin(np.linalg.norm(self.path - kp, axis=1)))
+ nrm = np.array([-tan[i, 1], tan[i, 0]])
+ for o in (-1.6, 1.6):
+ c = kp + tan[i] * o
+ bands.append([c - nrm * self.width * 0.5, c + nrm * self.width * 0.5])
+ il.pen(bands, 1.0)
+ # hairline tendrils, leaves, flowers, bezants
+ il.pen(self.lines, 0.85)
+ lm = il.mask([self.leaf_pts(p, a, s) for p, a, s in self.leaves])
+ il.outline(lm, 1.0)
+ veins = [[p, p + 0.75 * s * np.array([np.cos(a), np.sin(a)])] for p, a, s in self.leaves]
+ il.pen(veins, 0.6, opacity=0.8)
+ fm = il.mask(dots=[(p[0], p[1], rr * 1.15) for p, c, rr in self.flowers])
+ il.outline(fm, 0.8, opacity=0.8)
+ cen = il.mask(dots=[(p[0], p[1], 1.4) for p, c, rr in self.flowers])
+ sl = _bbox(cen, 2)
+ if sl is not None:
+ il._ink(cen[sl], np.ones_like(cen[sl]), sl[1].start, sl[0].start, 'white', 0.95)
+ bm = il.mask(dots=[(p[0], p[1], rr) for p, rr in self.balls])
+ il.outline(bm, 0.9)
+ hairs = []
+ for p, rr in self.balls:
+ for k in range(3):
+ a = self.r.uniform(0, 2 * np.pi)
+ c0 = p + (rr + 1) * np.array([np.cos(a), np.sin(a)])
+ hairs.append([c0, c0 + 4 * np.array([np.cos(a + 0.4), np.sin(a + 0.4)]), c0 + 7 * np.array([np.cos(a - 0.1), np.sin(a - 0.1)])])
+ il.pen(hairs, 0.6, opacity=0.85)
+
+
+class Versal:
+ """a two-line penwork initial: a split Lombardic letter in azurite, flourished with red filigree that runs up and
+ down the margin"""
+
+ def __init__(self, il, letter, x, y, size, colour, flourish, reach):
+ self.il, self.colour, self.flourish, self.reach = il, colour, flourish, reach
+ self.x, self.y, self.size = x, y, size
+ self.cx, self.cy, self.R = x + size * 0.5, y + size * 0.5, size * 0.5
+ self.body, self.counter = _lombard(il, self.cx, self.cy, self.R, letter)
+ # the split: a reserved hairline of bare vellum down the thick sides
+ a = np.radians(np.linspace(-55, 55, 30))
+ R = self.R
+ self.split = il.mask(lines=[(np.stack([self.cx + 0.76 * R * np.cos(a), self.cy - 0.76 * R * np.sin(a) * 0.94], 1), 1.6),
+ (np.stack([self.cx - 0.76 * R * np.cos(a), self.cy - 0.76 * R * np.sin(a) * 0.94], 1), 1.6)])
+
+ def paint(self):
+ il = self.il
+ il.paint(np.clip(self.body - self.split, 0, 1), self.colour, granular=1.0)
+
+ def pen(self):
+ il, R, cx, cy = self.il, self.R, self.cx, self.cy
+ r = np.random.default_rng(7)
+ kind = 'red' if self.flourish == RED else 'blue'
+ paths = []
+ # echo lines round the bowl
+ for o in (5, 9):
+ a = np.linspace(0, 2 * np.pi, 160)
+ paths.append(np.stack([cx + (R + o) * np.cos(a), cy + (R + o) * 0.94 * np.sin(a)], 1))
+ # infill of the counter: concentric ovals and little circles
+ a = np.linspace(0, 2 * np.pi, 120)
+ paths.append(np.stack([cx + 0.36 * R * np.cos(a), cy + 0.58 * R * np.sin(a)], 1))
+ circles = [np.stack([cx + 0.36 * R * np.cos(t) + 2.0 * np.cos(np.linspace(0, 2 * np.pi, 14)),
+ cy + 0.58 * R * np.sin(t) + 2.0 * np.sin(np.linspace(0, 2 * np.pi, 14))], 1)
+ for t in np.linspace(0, 2 * np.pi, 8, endpoint=False)]
+ # tendrils up and down the margin, with feathered barbs and a curl at the end
+ up, down = self.reach
+ for sgn, L in ((-1, up), (1, down)):
+ x0 = cx - R - 16
+ ys = np.linspace(cy + sgn * R * 0.4, cy + sgn * (R + L), 80)
+ xs = x0 + 2.5 * np.sin((ys - cy) / 14)
+ paths.append(np.stack([xs, ys], 1))
+ for j, k in enumerate(range(6, 80, 9)):
+ bx, by = xs[k], ys[k]
+ t = np.linspace(0, 1, 16)
+ L = 12 if j % 2 else 8 # long and short hooks, each ending in a curl
+ hx = bx - L * t - 2.2 * np.sin(t * np.pi * 1.6) * t
+ hy = by + sgn * (-5 * np.sin(t * np.pi * 0.8) + 3.5 * t ** 3)
+ paths.append(np.stack([hx, hy], 1))
+ a, rad, cur = -np.pi / 2 * sgn, 7.0, [np.array([xs[-1], ys[-1]])]
+ for i in range(30):
+ a += 0.3; rad *= 0.95
+ cur.append(cur[-1] + rad * 0.3 * np.array([np.cos(a), np.sin(a)]))
+ paths.append(np.array(cur))
+ il.pen(paths, 0.8, kind, 0.9)
+ il.pen(circles, 0.7, kind, 0.9)
+ dots = [(cx, cy, 2.0)] + [(cx - R - 24, cy + s * (R + 8 + 14 * k), 1.6) for s in (-1, 1) for k in range(1, 3)]
+ m = il.mask(dots=dots)
+ sl = _bbox(m, 2)
+ il._ink(m[sl], np.ones_like(m[sl]), sl[1].start, sl[0].start, kind, 0.95)
+
+
+class Astrolabe:
+ """an astrolabe drawn with compass and rule. The plate is a real stereographic projection from the south pole:
+ tropic of Capricorn at the plate edge, equator, tropic of Cancer, almucantars (circles of equal altitude) for
+ latitude `lat`, the horizon; a shell-gold rete (ecliptic ring, star pointers) turned by `rete`; the rule with sight
+ vanes at `rule` degrees above the horizon, and its line of sight continued (dotted) to `star`."""
+
+ def __init__(self, il, cx, cy, R, lat=48.0, rete=24.0, rule=40.0, star=None, seed=3):
+ self.il, self.cx, self.cy, self.R = il, cx, cy, R
+ self.lat, self.rete_rot, self.rule_deg, self.star_xy = lat, rete, rule, star
+ self.rp = 0.84 * R # plate = tropic of Capricorn
+ eps = np.radians(23.44)
+ self.req = self.rp / np.tan((np.pi / 2 + eps) / 2)
+ self.rcan = self.req * np.tan((np.pi / 2 - eps) / 2)
+ phi = np.radians(lat)
+ self.alm = []
+ for a in range(0, 90, 10):
+ al = np.radians(a)
+ yc = cy - self.req * np.cos(phi) / (np.sin(phi) + np.sin(al))
+ rr = self.req * np.cos(al) / (np.sin(phi) + np.sin(al))
+ self.alm.append((a, yc, rr))
+ self.zenith = (cx, cy - self.req * np.cos(phi) / (np.sin(phi) + 1))
+ r = np.random.default_rng(seed)
+ # rete geometry
+ th = np.radians(rete)
+ e = (self.rp - self.rcan) / 2
+ self.ecl = (cx + e * np.sin(th), cy - e * np.cos(th), (self.rp + self.rcan) / 2)
+ self.pointers = []
+ for rf, ang in ((0.92, 200), (0.72, 140), (0.55, 250), (0.88, 320), (0.40, 30), (0.80, 75), (0.30, 160), (0.66, 290), (0.95, 110)):
+ a = np.radians(ang + rete)
+ self.pointers.append((cx + rf * self.rp * np.cos(a), cy - rf * self.rp * np.sin(a), a))
+
+ def _circle(self, cx, cy, r, n=None):
+ n = n or max(48, int(r * 1.2))
+ t = np.linspace(0, 2 * np.pi, n)
+ return np.stack([cx + r * np.cos(t), cy + r * np.sin(t)], 1)
+
+ def _clip(self, pts, r):
+ """split a polyline into the runs that lie inside the plate"""
+ ins = np.hypot(pts[:, 0] - self.cx, pts[:, 1] - self.cy) <= r
+ runs, cur = [], []
+ for p, k in zip(pts, ins):
+ if k: cur.append(p)
+ elif cur:
+ if len(cur) > 1: runs.append(np.array(cur))
+ cur = []
+ if len(cur) > 1: runs.append(np.array(cur))
+ return runs
+
+ def _rete_mask(self):
+ il, cx, cy, R, rp = self.il, self.cx, self.cy, self.R, self.rp
+ ex, ey, er = self.ecl
+ m = il.ring(ex, ey, er - 0.06 * R, er) # ecliptic ring with its zodiac band
+ m = np.maximum(m, il.ring(cx, cy, rp - 0.022 * R, rp)) # outer rim of the rete
+ th = np.radians(self.rete_rot)
+ lines = []
+ u = np.array([np.cos(th), np.sin(th)]); v = np.array([-np.sin(th), np.cos(th)])
+ c = np.array([cx, cy])
+ lines.append((np.array([c - u * rp, c + u * rp]), 0.017 * R)) # equinoctial bar
+ lines.append((np.array([c + v * self.rcan * 0.5, c + v * rp]), 0.017 * R))
+ # tracery: two little loops on the lower bar and a trefoil round the hub
+ for f in (0.66, 0.84):
+ p = c + v * rp * f
+ t = np.linspace(0, 2 * np.pi, 40)
+ lines.append((np.stack([p[0] + 0.045 * R * np.cos(t), p[1] + 0.045 * R * np.sin(t)], 1), 0.010 * R))
+ m = np.maximum(m, il.mask(lines=lines))
+ m = np.maximum(m, il.circle(cx, cy, 0.05 * R))
+ # star pointers: flame-shaped blades from the framework to each star
+ polys = []
+ for px, py, a in self.pointers:
+ d = np.array([px - cx, py - cy]); L = np.linalg.norm(d); d /= L + 1e-6
+ nrm = np.array([-d[1], d[0]])
+ base = np.array([px, py]) - d * 0.13 * R
+ w = 0.024 * R
+ polys.append([(px, py), base + nrm * w, base - d * 0.05 * R, base - nrm * w * 0.6])
+ m = np.maximum(m, il.mask(polys))
+ m = np.maximum(m, il.mask(dots=[(px, py, 0.012 * R) for px, py, a in self.pointers]))
+ return np.clip(m, 0, 1) * il.circle(cx, cy, rp)
+
+ def _throne(self):
+ il, cx, cy, R = self.il, self.cx, self.cy, self.R
+ top = cy - R
+ t = np.linspace(0, 1, 30)
+ left = np.stack([cx - 0.30 * R + 0.18 * R * t ** 1.6, top + 0.06 * R - 0.20 * R * np.sin(t * np.pi / 2)], 1)
+ lobe = lambda x, y, r: self._circle(x, y, r, 30)
+ th = il.mask([np.concatenate([left, [(cx, top - 0.21 * R)], (left * [-1, 1] + [2 * cx, 0])[::-1]])])
+ th = np.maximum(th, il.mask([lobe(cx - 0.11 * R, top - 0.10 * R, 0.07 * R), lobe(cx + 0.11 * R, top - 0.10 * R, 0.07 * R),
+ lobe(cx, top - 0.19 * R, 0.07 * R)]))
+ holes = il.circle(cx, top - 0.19 * R, 0.025 * R)
+ ring = il.ring(cx, top - 0.36 * R, 0.085 * R, 0.115 * R)
+ shackle = il.ring(cx, top - 0.26 * R, 0.035 * R, 0.055 * R)
+ return np.clip(th - holes, 0, 1) * (1 - il.circle(cx, cy, R * 0.99)), np.maximum(ring, shackle)
+
+ def _rule(self):
+ il, cx, cy, R = self.il, self.cx, self.cy, self.R
+ a = np.radians(self.rule_deg)
+ u = np.array([np.cos(a), -np.sin(a)]); v = np.array([np.sin(a), np.cos(a)])
+ c = np.array([cx, cy])
+ L, w = 0.97 * R, 0.022 * R
+ bar = il.mask([[c - u * L + v * w * 0.3, c - u * (L - 0.1 * R) + v * w, c + u * (L - 0.1 * R) + v * w, c + u * L + v * w * 0.3,
+ c + u * L - v * w * 0.3, c + u * (L - 0.1 * R) - v * w, c - u * (L - 0.1 * R) - v * w, c - u * L - v * w * 0.3]])
+ vanes = []
+ holes = []
+ for s in (-1, 1):
+ p = c + u * s * 0.70 * R
+ vanes.append([p - u * 0.018 * R + v * 0.06 * R, p + u * 0.018 * R + v * 0.06 * R, p + u * 0.018 * R - v * 0.06 * R,
+ p - u * 0.018 * R - v * 0.06 * R])
+ holes.append((p[0], p[1], 0.009 * R))
+ return np.maximum(bar, il.mask(vanes)), il.mask(dots=holes)
+
+ def draw(self):
+ """the draftsman's compass work in brown ink"""
+ il, cx, cy, R, rp = self.il, self.cx, self.cy, self.R, self.rp
+ paths = [self._circle(cx, cy, R), self._circle(cx, cy, 0.88 * R), self._circle(cx, cy, rp),
+ self._circle(cx, cy, self.req), self._circle(cx, cy, self.rcan)]
+ il.pen(paths, 1.1, 'diagram', 0.9)
+ thin = [[(cx - rp, cy), (cx + rp, cy)], [(cx, cy - rp), (cx, cy + rp)]]
+ for a, yc, rr in self.alm:
+ for run in self._clip(self._circle(cx, yc, rr, 400), rp):
+ (paths if a == 0 else thin).append(run)
+ # azimuths: circles through the zenith and nadir, drawn above the horizon only
+ phi = np.radians(self.lat)
+ yz = cy - self.req * np.cos(phi) / (1 + np.sin(phi))
+ yn = cy + self.req * np.cos(phi) / (1 - np.sin(phi))
+ hh, ym = (yn - yz) / 2, (yn + yz) / 2
+ a0, hy, hr = self.alm[0]
+ for A in range(15, 180, 15):
+ dx = hh / np.tan(np.radians(A))
+ circ = self._circle(cx + dx, ym, np.hypot(dx, hh), 900)
+ keep = np.hypot(circ[:, 0] - cx, circ[:, 1] - hy) <= hr
+ circ = np.where(keep[:, None], circ, 1e5)
+ thin += self._clip(circ, rp)
+ il.pen(thin, 0.75, 'diagram', 0.85)
+ hor = [run for run in self._clip(self._circle(cx, self.alm[0][1], self.alm[0][2], 600), rp)]
+ il.pen(hor, 1.3, 'diagram', 0.95)
+ # degree ticks on the limb
+ ticks = []
+ for d in range(0, 360, 5):
+ a = np.radians(d)
+ r1 = 0.88 * R + (0.08 if d % 15 == 0 else 0.045) * R
+ ticks.append([(cx + 0.88 * R * np.cos(a), cy - 0.88 * R * np.sin(a)), (cx + r1 * np.cos(a), cy - r1 * np.sin(a))])
+ il.pen(ticks, 0.8, 'diagram', 0.85)
+ th, ring = self._throne()
+ il.outline(np.maximum(th, ring), 1.1, 'diagram')
+ rete = self._rete_mask()
+ il.outline(rete, 0.9, 'diagram', 0.8)
+
+ def gild(self, star=True):
+ il, cx, cy, R = self.il, self.cx, self.cy, self.R
+ il.shell_gold(il.ring(cx, cy, 0.88 * R, R))
+ th, ring = self._throne()
+ il.shell_gold(np.maximum(th, ring))
+ il.shell_gold(self._rete_mask())
+ if star and self.star_xy is not None:
+ sx, sy = self.star_xy
+ il.gild(il.mask([il.star(sx, sy, 0.13 * R, 8, 0.34, 11)]), cushion=4.5)
+
+ def paint(self):
+ """light washes: the sky above the horizon, the earth below"""
+ il, cx, cy, rp = self.il, self.cx, self.cy, self.rp
+ a0, yc, rr = self.alm[0]
+ above = il.circle(cx, yc, rr) * il.circle(cx, cy, rp - 1)
+ il.wash(above * (1 - self._rete_mask()), '#7c9ad6', 0.45)
+ il.wash(il.circle(cx, cy, rp - 1) * (1 - il.circle(cx, yc, rr)) * (1 - self._rete_mask()), '#c9a46a', 0.25)
+
+ def pen(self, labels=(), xh=13):
+ """ink over the gold: ticks, the rule with its sight vanes, the line of sight to the star, labels in red"""
+ il, cx, cy, R = self.il, self.cx, self.cy, self.R
+ ticks = []
+ for d in range(0, 360, 5):
+ a = np.radians(d)
+ r1 = 0.88 * R + (0.10 if d % 15 == 0 else 0.05) * R
+ ticks.append([(cx + 0.885 * R * np.cos(a), cy - 0.885 * R * np.sin(a)), (cx + r1 * np.cos(a), cy - r1 * np.sin(a))])
+ il.pen(ticks, 0.8, 'iron', 0.85)
+ il.outline(il.ring(cx, cy, 0.88 * R, R), 1.3)
+ th, ring = self._throne()
+ il.outline(np.maximum(th, ring), 1.2)
+ rete = self._rete_mask()
+ il.outline(rete, 1.1)
+ # zodiac divisions on the ecliptic ring
+ ex, ey, er = self.ecl
+ zt = []
+ for k in range(36):
+ a = np.radians(k * 10 + self.rete_rot)
+ r0 = er - (0.075 if k % 3 == 0 else 0.03) * R
+ zt.append([(ex + r0 * np.cos(a), ey - r0 * np.sin(a)), (ex + er * np.cos(a), ey - er * np.sin(a))])
+ il.pen(zt, 0.7, 'iron', 0.8)
+ # the rule and its vanes
+ bar, holes = self._rule()
+ il.shell_gold(bar)
+ il.outline(bar, 1.2)
+ il.paint(holes, '#2a1d14', texture=0)
+ il.outline(il.circle(cx, cy, 0.03 * R), 1.0)
+ # line of sight and the angle of altitude
+ a = np.radians(self.rule_deg)
+ if self.star_xy is not None:
+ sx, sy = self.star_xy
+ p0 = (cx + 1.0 * R * np.cos(a), cy - 1.0 * R * np.sin(a))
+ il.pen([[p0, (sx - 0.15 * R * np.cos(a), sy + 0.15 * R * np.sin(a))]], 1.1, 'red', 0.9, dash=(5, 5))
+ il.outline(il.mask([il.star(sx, sy, 0.13 * R, 8, 0.34, 11)]), 1.0)
+ il.pen([[(cx + 0.05 * R, cy), (cx + 1.32 * R, cy)]], 1.0, 'red', 0.85, dash=(9, 5))
+ arc_r = 1.12 * R
+ t = np.linspace(0, a, 30)
+ il.pen([np.stack([cx + arc_r * np.cos(t), cy - arc_r * np.sin(t)], 1)], 1.2, 'red', 0.9)
+ # labels with leader lines: (text, (x, y) of the label baseline start, (x, y) pointed at)
+ leads = []
+ for s, (lx, ly), (tx, ty) in labels:
+ w = il.text_width(s, xh)
+ il.write(s, lx, ly, xh, 'red', load=0.9)
+ sx0 = lx + w + 4 if tx > lx + w else lx - 4
+ leads.append([(sx0, ly - 0.5 * xh), (tx, ty)])
+ il.pen(leads, 0.7, 'red', 0.8)
+
+
+class Spheres:
+ """the order of the planets: the earth (a T-O map) at the centre, the seven planetary spheres, the sphere of the
+ fixed stars, a burnished gold frame; planet discs round a spiral, names written round the rings"""
+
+ NAMES = ('luna', 'mercurius', 'uenus', 'sol', 'mars', 'iupiter', 'saturnus')
+ COLS = (SILVER, '#8a93a0', '#e8e4c8', 'gold', '#c8452a', '#c9b98e', LEAD)
+
+ def __init__(self, il, cx, cy, R, angles=(196, 222, 248, 274, 300, 326, 352), label_at=(150, 131, 112, 93, 74, 55, 36)):
+ self.il, self.cx, self.cy, self.R = il, cx, cy, R
+ self.rt = 0.20 * R
+ self.rb = np.linspace(0.23 * R, 0.84 * R, 8) # 7 planetary rings
+ self.rf = (0.84 * R, 0.95 * R) # fixed stars
+ self.angles, self.label_at = angles, label_at
+ self.discs = []
+ for k, ang in enumerate(angles):
+ rm = (self.rb[k] + self.rb[k + 1]) / 2
+ a = np.radians(ang)
+ self.discs.append((cx + rm * np.cos(a), cy - rm * np.sin(a), (self.rb[1] - self.rb[0]) * 0.52))
+ rng = np.random.default_rng(11)
+ self.fstars = []
+ for a in np.linspace(0, 2 * np.pi, 22, endpoint=False) + rng.normal(0, 0.06, 22):
+ if abs(np.degrees(a) % 360 - 90) < 24: continue # leave room for the name
+ rr = rng.uniform(0.865, 0.925) * R
+ self.fstars.append((cx + rr * np.cos(a), cy - rr * np.sin(a), rng.uniform(4.6, 6.4)))
+
+ def _c(self, r, n=None):
+ n = n or max(60, int(r * 1.3))
+ t = np.linspace(0, 2 * np.pi, n)
+ return np.stack([self.cx + r * np.cos(t), self.cy + r * np.sin(t)], 1)
+
+ def draw(self):
+ il, R = self.il, self.R
+ il.pen([self._c(r) for r in list(self.rb) + [self.rt, self.rf[1], R]], 1.0, 'diagram', 0.9)
+
+ def gild(self):
+ il, cx, cy, R = self.il, self.cx, self.cy, self.R
+ il.gild(il.ring(cx, cy, self.rf[1], R), cushion=3.5)
+ x, y, r = self.discs[3]
+ il.gild(np.maximum(il.circle(x, y, r * 1.1), il.mask([il.star(x, y, r * 1.9, 12, 0.6)])), cushion=2.2)
+ il.gild(il.mask([il.star(x_, y_, r_, 6, 0.45) for x_, y_, r_ in self.fstars]) * il.ring(cx, cy, *self.rf), cushion=1.2)
+
+ def paint(self):
+ il, cx, cy, R = self.il, self.cx, self.cy, self.R
+ # ring tints, alternating
+ for k in range(7):
+ if k % 2 == 0:
+ il.wash(il.ring(cx, cy, self.rb[k], self.rb[k + 1]), '#d9c49a', 0.45)
+ # fixed stars: azurite, painted round the gilded stars
+ stars = il.mask([il.star(x_, y_, r_ + 1.2, 6, 0.45) for x_, y_, r_ in self.fstars])
+ il.paint(il.ring(cx, cy, *self.rf) * (1 - stars), AZURE, mix=(AZURE_DARK, smoothstep(cy - R, cy + R, il.YY)), granular=1.0)
+ # the earth: a T-O map -- ocean round, the T of waters, three parts of the land
+ rt = self.rt
+ il.paint(il.circle(cx, cy, rt), AZURE_LIGHT, granular=0.6)
+ land = il.circle(cx, cy, rt * 0.8)
+ il.paint(land * (il.YY < cy), GREEN)
+ il.paint(land * (il.YY >= cy) * (il.XX < cx), '#b9944c')
+ il.paint(land * (il.YY >= cy) * (il.XX >= cx), '#a7713f')
+ t = il.mask(lines=[([(cx - rt * 0.8, cy), (cx + rt * 0.8, cy)], 2.6), ([(cx, cy), (cx, cy + rt * 0.8)], 2.6)])
+ il.paint(t * land, AZURE_LIGHT, texture=0.4)
+ # planet discs
+ for k, ((x, y, r), col) in enumerate(zip(self.discs, self.COLS)):
+ if col == 'gold': continue
+ m = il.circle(x, y, r)
+ if k == 0: # the moon: a crescent
+ m = np.clip(m - il.circle(x + r * 0.45, y - r * 0.2, r * 0.85), 0, 1)
+ il.paint(m, col, mix=('#3a3a3a', smoothstep(x - r, x + r * 1.4, il.XX) * 0.35))
+
+ def pen(self, xh=9.0):
+ il, cx, cy, R = self.il, self.cx, self.cy, self.R
+ il.outline(il.ring(cx, cy, self.rf[1], R), 1.3)
+ il.pen([self._c(r) for r in list(self.rb) + [self.rt, self.rf[0]]], 0.9, 'iron', 0.85)
+ x, y, r = self.discs[3]
+ il.outline(np.maximum(il.circle(x, y, r * 1.1), il.mask([il.star(x, y, r * 1.9, 12, 0.6)])), 0.9)
+ for k, (x, y, r) in enumerate(self.discs):
+ if k == 3: continue
+ m = il.circle(x, y, r)
+ if k == 0: m = np.clip(m - il.circle(x + r * 0.45, y - r * 0.2, r * 0.85), 0, 1)
+ il.outline(m, 0.9)
+ il.outline(il.circle(cx, cy, self.rt), 1.1)
+ # names round the rings, alternating red and black
+ for k, name in enumerate(self.NAMES):
+ rm = (self.rb[k] + self.rb[k + 1]) / 2 - xh * 0.5
+ il.arc_text(name, cx, cy, rm, self.label_at[k], xh, 'red' if k % 2 == 0 else 'iron', 0.2)
+ il.arc_text('firmamentum', cx, cy, (self.rf[0] + self.rf[1]) / 2 - xh * 0.5 - 0.5, 90, xh * 0.95, 'white', 0.2)
diff --git a/lib/letterpress.py b/lib/letterpress.py
new file mode 100644
index 0000000..b1f6d58
--- /dev/null
+++ b/lib/letterpress.py
@@ -0,0 +1,1024 @@
+"""letterpress — a two-colour letterpress poster of the 1890s playbill kind: wood-type lines set to full measure,
+a woodcut picture split into a red tint block and a black key block, both printed a hair out of register on
+cheap toned stock that has since been folded, tacked to a wall and left to foxing (numpy + Pillow only).
+
+Model: a sheet goes through the press once per ink. Everything that will print in one ink is first locked up on
+that ink's forme (`plates[ink]`), then `press(ink)` prints the forme in one impression.
+ stock cheap machine-finished paper, already toned: a cloudy cream with warmer patches, short fibres, dark
+ flecks in the pulp and a per-pixel "tooth" (the hills and pits that decide where ink takes).
+ forme one per ink. A forme carries wood type, metal type, brass rules, ornaments and the woodcut block for
+ that colour. On press the sheet lands a little differently for every pass, so each forme prints with
+ its own small shift and a hair of rotation (`register`): red and black never sit exactly on each
+ other -- the red tint creeps out from under the black key on one side and leaves a sliver of paper on
+ the other. A forme can be locked in named parts (`with lp.layer('key'):`) and proofed part by part
+ (`press(ink, only=['key'])`), which is how the drawing stages show key lines before hatching.
+ wood type every letter is its own block of end-grain maple. A line is set to the full measure, the way a
+ jobbing printer filled a poster: the face is condensed or extended (a different font of wood type)
+ and letter-spaced until the line is flush on both sides. Each block inks a little differently: wood
+ grain prints as faint streaks, the block is never exactly type-high so one end prints lighter, old
+ blocks have nicked edges, dents (pale soft spots) and now and then a split along the grain. Shaded
+ letters (`shade=`) carry a drop shade on the other forme; inline letters (`inline=`) have a white line
+ cut down the middle of the stroke.
+ ink a stiff, nearly opaque oil ink rolled on thin. On big solids the roller starves: the film goes
+ mottled and the deepest pits of the tooth stay bare (a "salty" print), while the edge of every
+ solid squeezes a little extra ink into a darker rim. Dust on the forme leaves round dropouts.
+ Black over red prints darker still.
+ impression the forme bites into the soft sheet: printed areas sit in a shallow dent that catches the light
+ along one edge (very low, it is thin stock).
+ woodcut drawn the way a cutter leaves wood standing: a key line around every shape that thickens on the side
+ away from the light, swelling parallel hatching whose line width follows a tone (`hatch`), solid
+ blacks, carved highlights (`clear`), stipple, and a red tint block (`tint`) cut separately and loosely
+ from the key, so its edges wander off the black lines.
+ afterlife the bill was folded in thirds to post (`fold`: a crease with cracked ink, dirt and a light/shade
+ roll), a date strip printed on its own little press was pasted on (`strip(..., draw=fn)`: whiter slip,
+ glue stain round it), it was tacked up (`tack`: torn hole, rust halo), browned from the edges
+ (`tone_edges`), foxed (`foxing`), water-stained (`stain`) and nicked (`nicks`).
+Coordinates are pixels, y down. Angles are degrees counter-clockwise (0 = 3 o'clock) unless noted. Shapes are
+full-sheet float masks (`shape`, `poly`, `tube`, `ellipse`, `rect`) that can be added, multiplied and subtracted.
+
+ from letterpress import Letterpress, RED, BLACK
+ lp = Letterpress(1920, 1080, seed=7)
+ lp.paper()
+ lp.type_line('CIRCUS', 90, 840, 360, 190, face='clarendon', ink=RED, shade=(9, 7, BLACK, 4))
+ body = lp.shape([(1200, 600), (1500, 560), (1600, 700), (1300, 760)])
+ lp.tint(body) # red block
+ lp.clear(body); lp.key(body); lp.hatch(body, angle=30)
+ lp.press(RED); lp.press(BLACK)
+ lp.fold('v', 640); lp.tone_edges(); lp.foxing()
+ lp.save('out.jpg')
+"""
+import glob
+import os
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont, ImageFilter
+from core import blur, noise2d, smoothstep, shift, spline, latin_font, fbm1d
+
+RED, BLACK = '#c0392b', '#1d1a17'
+PAPER, AGED, RUST, WALL = '#ecdfbd', '#c9a66b', '#8a4a22', '#3a2f26'
+OPACITY = {RED: 0.82, BLACK: 0.95}
+LIGHT = (-0.55, -0.83) # where the light comes from (screen direction, unit-ish)
+SS = 2 # supersampling for type and shapes
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+def _c(c):
+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)
+
+
+# ---------------------------------------------------------------- faces of type (kept inside this module)
+_S = '/System/Library/Fonts/Supplemental/'
+_FACES = { # (glob, index); first hit wins -- macOS, then Linux / Windows look-alikes; generic core style last
+ 'clarendon': [(_S + 'SuperClarendon.ttc', 7), (_S + 'Rockwell.ttc', 2), ('/usr/share/fonts/**/DejaVuSerif-Bold.ttf', 0),
+ ('C:/Windows/Fonts/ROCKEB.TTF', 0), ('C:/Windows/Fonts/georgiab.ttf', 0)],
+ 'antique': [(_S + 'Rockwell.ttc', 2), (_S + 'SuperClarendon.ttc', 5), ('/usr/share/fonts/**/DejaVuSerif-Bold.ttf', 0),
+ ('C:/Windows/Fonts/ROCKB.TTF', 0), ('C:/Windows/Fonts/georgiab.ttf', 0)],
+ 'gothic': [(_S + 'Impact.ttf', 0), (_S + 'DIN Condensed Bold.ttf', 0), ('/usr/share/fonts/**/DejaVuSansCondensed-Bold.ttf', 0),
+ ('C:/Windows/Fonts/impact.ttf', 0)],
+ 'fatface': [(_S + 'Bodoni 72.ttc', 2), (_S + 'Didot.ttc', 2), ('/usr/share/fonts/**/DejaVuSerif-Bold.ttf', 0),
+ ('C:/Windows/Fonts/BOD_B.TTF', 0), ('C:/Windows/Fonts/georgiab.ttf', 0)],
+ 'roman': [(_S + 'Hoefler Text.ttc', 0), (_S + 'PTSerif.ttc', 0), (_S + 'Times New Roman.ttf', 0),
+ ('/usr/share/fonts/**/DejaVuSerif.ttf', 0), ('C:/Windows/Fonts/times.ttf', 0)],
+ 'roman_bold': [(_S + 'Hoefler Text.ttc', 1), (_S + 'PTSerif.ttc', 3), (_S + 'Times New Roman Bold.ttf', 0),
+ ('/usr/share/fonts/**/DejaVuSerif-Bold.ttf', 0), ('C:/Windows/Fonts/timesbd.ttf', 0)],
+ 'italic': [(_S + 'Hoefler Text.ttc', 2), (_S + 'PTSerif.ttc', 1), (_S + 'Times New Roman Italic.ttf', 0),
+ ('/usr/share/fonts/**/DejaVuSerif-Italic.ttf', 0), ('C:/Windows/Fonts/timesi.ttf', 0)],
+ 'cjk': [(_S + 'Songti.ttc', 0), ('/System/Library/Fonts/STHeiti Medium.ttc', 1),
+ ('/usr/share/fonts/**/NotoSerifCJK*Black*.tt[cf]', 0), ('/usr/share/fonts/**/NotoSerifCJK*Bold*.tt[cf]', 0),
+ ('/usr/share/fonts/**/NotoSansCJK*Bold*.tt[cf]', 0), ('C:/Windows/Fonts/simsun.ttc', 0)],
+ 'cjk_book': [(_S + 'Songti.ttc', 6), ('/System/Library/Fonts/STHeiti Medium.ttc', 1),
+ ('/usr/share/fonts/**/NotoSerifCJK*Regular*.tt[cf]', 0), ('C:/Windows/Fonts/simsun.ttc', 0)],
+ 'ornament': [(_S + 'Bodoni Ornaments.ttf', 0)],
+}
+_GENERIC = {'clarendon': 'serif', 'antique': 'serif', 'gothic': 'condensed', 'fatface': 'serif', 'roman': 'serif',
+ 'roman_bold': 'serif', 'italic': 'serif', 'cjk': 'cjk', 'cjk_book': 'cjk', 'ornament': 'sans'}
+_HITS, _FONTS, _CAP = {}, {}, {}
+
+
+def _face(face):
+ if face in _HITS: return _HITS[face]
+ env = os.environ.get('INKPAINT_FONT_' + face.upper())
+ hit = (env, 0) if env and os.path.exists(env) else None
+ for pat, idx in ([] if hit else _FACES.get(face, [])):
+ fs = glob.glob(pat, recursive=True)
+ if fs:
+ hit = (fs[0], idx); break
+ if hit is None and face != 'ornament':
+ hit = latin_font(_GENERIC.get(face, 'sans')) or latin_font('sans')
+ _HITS[face] = hit
+ return hit
+
+
+def font(face, size):
+ """PIL font for a face of type: clarendon, antique, gothic, fatface, roman, roman_bold, italic, cjk, cjk_book"""
+ k = (face, int(round(size)))
+ if k not in _FONTS:
+ hit = _face(face)
+ size = max(4, int(round(size)))
+ _FONTS[k] = ImageFont.truetype(hit[0], size, index=hit[1]) if hit else ImageFont.load_default(size)
+ return _FONTS[k]
+
+
+def cap_ratio(face):
+ """cap height / font size for a face (the height of H, or of 国 for Chinese)"""
+ if face not in _CAP:
+ f = font(face, 200)
+ ch = '国' if face.startswith('cjk') else 'H'
+ b = f.getbbox(ch, anchor='ls')
+ _CAP[face] = max(0.3, -b[1] / 200)
+ return _CAP[face]
+
+
+# ---------------------------------------------------------------- small array helpers
+def _paste(dst, a, x, y):
+ """paste array a into dst with its top-left at (x, y), clipped"""
+ h, w = a.shape[:2]
+ H, W = dst.shape[:2]
+ ys, xs, ye, xe = max(0, y), max(0, x), min(H, y + h), min(W, x + w)
+ if ye > ys and xe > xs:
+ dst[ys:ye, xs:xe] = a[ys - y:ye - y, xs - x:xe - x]
+
+
+def _box3(a):
+ p = np.pad(a, 1, mode='edge')
+ h, w = a.shape
+ return sum(p[i:i + h, j:j + w] for i in range(3) for j in range(3)) / 9
+
+
+def _erode(a, r):
+ if r <= 0: return a
+ im = Image.fromarray((np.clip(a, 0, 1) * 255).astype(np.uint8))
+ return np.asarray(im.filter(ImageFilter.MinFilter(2 * int(r) + 1)), np.float32) / 255
+
+
+def _dilate(a, r):
+ if r <= 0: return a
+ im = Image.fromarray((np.clip(a, 0, 1) * 255).astype(np.uint8))
+ return np.asarray(im.filter(ImageFilter.MaxFilter(2 * int(r) + 1)), np.float32) / 255
+
+
+def _phi_table():
+ z = np.linspace(0, 4.5, 400)
+ # Abramowitz & Stegun 7.1.26 erf
+ x = z / np.sqrt(2)
+ t = 1 / (1 + 0.3275911 * x)
+ erf = 1 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * np.exp(-x * x)
+ return 0.5 * (1 + erf), z
+
+
+_PHI, _Z = _phi_table()
+
+
+def _inner_dist(mask, sigma):
+ """approximate distance (px) from each inside pixel to the shape's edge, valid up to ~3 sigma"""
+ b = blur(mask, sigma)
+ return (np.interp(np.clip(b, 0.5, 0.99999), _PHI, _Z) * sigma).astype(np.float32)
+
+
+def _closed_spline(pts, per=10):
+ P = np.asarray(pts, np.float32)
+ n = len(P)
+ ext = np.vstack([P[-1:], P, P[:2]])
+ out = []
+ for i in range(1, n + 1):
+ p0, p1, p2, p3 = ext[i - 1], ext[i], ext[i + 1], ext[i + 2]
+ for t in np.linspace(0, 1, per, endpoint=False):
+ t2, t3 = t * t, t * t * t
+ out.append(0.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 + (-p0 + 3 * p1 - 3 * p2 + p3) * t3))
+ return np.array(out, np.float32)
+
+
+def _hash(i, seed):
+ """per-integer pseudo-random in [-1, 1] (for per-line jitter of hatching)"""
+ x = (np.asarray(i, np.int64) * 374761393 + seed * 668265263) & 0xFFFFFFFF
+ x = ((x ^ (x >> 13)) * 1274126177) & 0xFFFFFFFF
+ return ((x & 0xFFFF) / 32767.5 - 1).astype(np.float32)
+
+
+class Letterpress:
+ def __init__(self, W=1920, H=1080, seed=0, misreg=3.2):
+ """misreg: typical registration error between the formes, px (one pass of the sheet per ink)"""
+ self.W, self.H = W, H
+ self.seed = seed
+ self.rng = np.random.default_rng(seed)
+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)
+ self.misreg = misreg
+ self.salt = 1.0 # how much bare tooth shows in solids
+ self.paper_col = _c(PAPER)
+ self.img = np.ones((H, W, 3), np.float32) * self.paper_col
+ self.stock = self.img.copy() # bare paper, for ink that cracks off
+ self.fibre = np.ones((H, W), np.float32)
+ self.light = np.ones((H, W), np.float32)
+ self.impress = np.zeros((H, W), np.float32)
+ self.tooth = np.full((H, W), 0.5, np.float32)
+ self.plates = {}
+ self._layer = 'main'
+ self.stages = []
+ self.wob = (noise2d(H // 4, W // 4, 18, 3, self._seed()) - 0.5) # hand wobble of cut lines
+ self.wob = np.asarray(Image.fromarray(self.wob).resize((W, H), Image.BICUBIC), np.float32)
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ # ------------------------------------------------------------ the stock
+ def paper(self, colour=PAPER, warm=AGED, tone=0.5):
+ """cheap toned poster stock: cloudy cream with warmer patches, fibres, flecks, tooth, a sheet that is not
+ quite flat. tone: how far it has already yellowed (0 fresh .. 1 brown)"""
+ H, W, r = self.H, self.W, self.rng
+ self.paper_col = _c(colour)
+ cloud = noise2d(H, W, 300, 4, self._seed())
+ t = (smoothstep(0.3, 0.95, cloud) * (0.18 + 0.25 * tone))[..., None]
+ base = self.paper_col * (1 - t) + _c(warm) * t
+ base = base * (1 + 0.02 * (noise2d(H, W, 40, 3, self._seed()) - 0.5))[..., None]
+ self.img = base.astype(np.float32)
+ fim = Image.new('L', (W, H), 128)
+ d = ImageDraw.Draw(fim)
+ for _ in range(int(W * H / 520)):
+ x, y = r.uniform(0, W), r.uniform(0, H)
+ a, L = r.uniform(0, np.pi), r.uniform(4, 22)
+ bend = r.normal(0, 0.3)
+ pts = [(x + np.cos(a + bend * s) * L * s, y + np.sin(a + bend * s) * L * s) for s in np.linspace(-0.5, 0.5, 5)]
+ d.line(pts, fill=int(128 + r.choice([-1, 1], p=[0.6, 0.4]) * r.uniform(10, 34)), width=1)
+ fib = blur((np.asarray(fim, np.float32) - 128) / 128, 0.55)
+ fine = blur(r.random((H, W)).astype(np.float32), 0.6)
+ fine = (fine - fine.mean()) / (fine.std() + 1e-6)
+ self.fibre = (1 + 0.06 * fib + 0.008 * fine).astype(np.float32)
+ fl = Image.new('L', (W * 2, H * 2), 0)
+ d = ImageDraw.Draw(fl)
+ for _ in range(int(W * H / 5000)):
+ x, y = r.uniform(0, W * 2), r.uniform(0, H * 2)
+ rr = r.uniform(0.6, 2.4) * (3 if r.random() < 0.05 else 1)
+ d.ellipse((x - rr, y - rr * r.uniform(0.4, 1), x + rr, y + rr * r.uniform(0.4, 1)), fill=int(r.uniform(60, 190)))
+ fl = np.asarray(fl.resize((W, H), Image.BOX), np.float32) / 255
+ self.img *= (1 - fl[..., None] * (1 - _c('#5e4630')))
+ g = r.random((H, W)).astype(np.float32)
+ c = noise2d(H, W, 5.0, 2, self._seed())
+ tt = 0.85 * (g - 0.5) / 0.29 + 0.6 * (c - c.mean()) / (c.std() + 1e-6)
+ self.tooth = np.clip(0.5 + tt / 4.0, 0, 1).astype(np.float32) # 1 = the deepest pits
+ cockle = noise2d(H, W, 420, 2, self._seed()) - 0.5
+ grad = 1 + 0.03 * (0.5 - (self.XX / W * 0.6 + self.YY / H * 0.4))
+ self.light = (grad + 0.03 * cockle).astype(np.float32)
+ self.stock = self.img.copy()
+
+ # ------------------------------------------------------------ formes
+ def _plate(self, ink):
+ if ink in self.plates: return self.plates[ink]
+ r = self.rng
+ n = len(self.plates)
+ a = r.uniform(0, 2 * np.pi)
+ mag = 0.0 if n == 0 and ink == BLACK else self.misreg * r.uniform(0.7, 1.0)
+ P = dict(layers={}, film=np.ones((self.H, self.W), np.float32),
+ off=(float(np.cos(a) * mag), float(np.sin(a) * mag)), rot=float(r.normal(0, 0.05)),
+ seed=self._seed())
+ self.plates[ink] = P
+ return P
+
+ def register(self, ink, dx, dy, rot=0.0):
+ """set a forme's registration error by hand: shift (px) and rotation (degrees ccw)"""
+ P = self._plate(ink)
+ P['off'], P['rot'] = (float(dx), float(dy)), float(rot)
+
+ def layer(self, name):
+ """with lp.layer('hatch'): ... -- what is locked inside goes into a named part of each forme, so a stage
+ can press the key lines before the hatching (press(ink, only=[...])). clear() cuts through every part."""
+ lp = self
+
+ class _L:
+ def __enter__(s):
+ s.prev = lp._layer
+ lp._layer = name
+
+ def __exit__(s, *a):
+ lp._layer = s.prev
+ return _L()
+
+ def _mask(self, ink, name=None):
+ P = self._plate(ink)
+ name = name or self._layer
+ if name not in P['layers']:
+ P['layers'][name] = np.zeros((self.H, self.W), np.float32)
+ return P['layers'][name]
+
+ def lock(self, mask, ink=BLACK, film=None):
+ """lock any mask into a forme (it prints at the next press of that ink); film scales the ink locally"""
+ P = self._plate(ink)
+ M = self._mask(ink)
+ np.maximum(M, mask, out=M)
+ if film is not None:
+ sel = mask > 0.02
+ P['film'][sel] = np.minimum(P['film'][sel], film[sel] if np.ndim(film) else film)
+
+ def clear(self, mask, ink=BLACK, keep=0.0):
+ """cut away: whatever is on the forme under `mask` no longer prints (woodcut highlights, overlaps)"""
+ P = self._plate(ink)
+ for M in P['layers'].values():
+ M *= 1 - np.clip(mask, 0, 1) * (1 - keep)
+
+ def _affine(self, a, P):
+ dx, dy = P['off']
+ t = np.deg2rad(P['rot'])
+ c, s = np.cos(t), np.sin(t)
+ cx, cy = self.W / 2, self.H / 2
+ # output (x, y) samples input at R^-1 (x - c - d) + c
+ A, B = c, -s
+ D, E = s, c
+ C = cx - A * (cx + dx) - B * (cy + dy)
+ F = cy - D * (cx + dx) - E * (cy + dy)
+ im = Image.fromarray(a.astype(np.float32), 'F')
+ return np.asarray(im.transform((self.W, self.H), Image.AFFINE, (A, B, C, D, E, F), resample=Image.BILINEAR),
+ np.float32)
+
+ def press(self, ink, density=1.0, only=None):
+ """one impression: print everything locked on the `ink` forme since its last press, then clear the forme.
+ only=[layer names] prints just those parts of the forme (and keeps the rest locked).
+ Stiff oil ink: ragged edge at the scale of the paper tooth, a squeezed darker rim, starved mottled solids
+ with bare pits (salt), dust dropouts; nearly opaque, multiplies a little with what is under it."""
+ P = self._plate(ink)
+ names = [k for k in P['layers'] if only is None or k in only]
+ if not names: return
+ m = np.maximum.reduce([P['layers'][k] for k in names]) if len(names) > 1 else P['layers'][names[0]]
+ rows, cols = np.flatnonzero(m.max(1) > 0.002), np.flatnonzero(m.max(0) > 0.002)
+ if not len(rows): return
+ r = np.random.default_rng(P['seed'] + 17 * len(self.stages))
+ mm = np.clip(self._affine(m, P), 0, 1)
+ film = self._affine(P['film'] - 1, P) + 1 if P['film'].min() < 1 else 1.0
+ pad = int(self.misreg * 2 + 14)
+ y0, y1 = max(0, rows[0] - pad), min(self.H, rows[-1] + pad + 1)
+ x0, x1 = max(0, cols[0] - pad), min(self.W, cols[-1] + pad + 1)
+ sl = (slice(y0, y1), slice(x0, x1))
+ mm = mm[sl]
+ h, w = mm.shape
+ if not np.isscalar(film): film = film[sl]
+ fine = blur(r.random((h, w)).astype(np.float32), 0.9)
+ fine = np.clip(0.5 + (fine - fine.mean()) / (fine.std() + 1e-6) * 0.2, 0, 1)
+ mott = noise2d(h, w, 26, 3, int(r.integers(1 << 30))) # the roller's mottle ...
+ roller = noise2d(h, w, 380, 2, int(r.integers(1 << 30))) # ... and its uneven charge
+ # dust on the forme: round dropouts
+ dim = Image.new('L', (w * 2, h * 2), 0)
+ d = ImageDraw.Draw(dim)
+ for _ in range(int(w * h / 9000 * density)):
+ x, y, rr = r.uniform(0, w * 2), r.uniform(0, h * 2), r.uniform(0.9, 3.4) * (2.4 if r.random() < 0.06 else 1)
+ d.ellipse((x - rr, y - rr * r.uniform(0.6, 1), x + rr, y + rr), fill=int(r.uniform(150, 255)))
+ dust = np.asarray(dim.resize((w, h), Image.BOX), np.float32) / 255
+ del dim
+ col = _c(ink)[None, None, :]
+ mul = np.clip(col / self.paper_col, 0, 1.2)
+ op = OPACITY.get(ink, 0.85)
+ B, M = 240, 24 # row bands keep the memory down
+ for b0 in range(0, h, B):
+ b1 = min(h, b0 + B)
+ a0, a1 = max(0, b0 - M), min(h, b1 + M)
+ k0, k1 = b0 - a0, b1 - a0
+ mmb = mm[a0:a1]
+ mb = _box3(mmb)
+ e = mb + (fine[a0:a1] - 0.5) * 0.28 + 0.04 # ink squeezes a hair past the edge
+ rag = smoothstep(0.32, 0.68, e) * np.clip(mb * 3, 0, 1)
+ thick = smoothstep(0.5, 0.85, blur(mmb, 2.0)) # hairlines keep their own edge
+ m2 = mmb * (1 - thick) + rag * thick
+ # the roller: big solids starve, mottle, show salt; the edge of a solid squeezes a darker rim
+ interior = smoothstep(0.86, 0.995, blur(mmb, 5.0))
+ mo = mott[a0:a1]
+ thin = 0.10 * interior * (mo - 0.35) + 0.07 * (roller[a0:a1] - 0.5)
+ salt = (smoothstep(0.975, 1.03, self.tooth[y0 + a0:y0 + a1, x0:x1] + interior * 0.07 * mo * mo)
+ * (0.35 + 0.65 * interior) * self.salt)
+ rim = np.clip(m2 - blur(m2, 1.6), 0, 1)
+ fb = film if np.isscalar(film) else np.clip(film[a0:a1], 0, 1)
+ cov = m2 * fb * density * (1 - thin) * (1 - salt) * (1 - dust[a0:a1] * 0.95)
+ cov = np.clip(cov * (1 + 0.12 * rim), 0, 1)[k0:k1, :, None]
+ rows_ = slice(y0 + b0, y0 + b1)
+ cur = self.img[rows_, x0:x1]
+ T = cur * (1 - cov + cov * mul) # the transparent part multiplies
+ O = cur * (1 - cov) + cov * col # the pigment part covers
+ self.img[rows_, x0:x1] = T * (1 - op) + O * op
+ np.maximum(self.impress[rows_, x0:x1], m2[k0:k1], out=self.impress[rows_, x0:x1])
+ for k in names:
+ del P['layers'][k]
+ if not P['layers']:
+ P['film'][:] = 1
+
+ # ------------------------------------------------------------ wood type
+ def type_line(self, s, x0, x1, base, cap, face='clarendon', ink=BLACK, align='justify', stretch=None,
+ track=0.0, shade=None, inline=None, wear=0.35, grain=0.5, limits=(0.62, 1.7)):
+ """set one line of wood type with its baseline at `base` and capitals `cap` px tall.
+ align='justify' fills x0..x1 exactly: the face is condensed / extended (within `limits`) and the rest is
+ letter-spacing. stretch fixes the width factor; track adds px between letters.
+ shade=(dx, dy, ink, gap): a drop shade on another forme, offset (dx, dy), with a gap of white.
+ inline=(inset, width): a white line cut down the middle of each stroke.
+ wear: nicks, dents and splits of old blocks (0..1). grain: how much the wood grain prints.
+ Returns dict(x0, x1, top, base, boxes=[(x0, y0, x1, y1) per letter])."""
+ size = cap / cap_ratio(face)
+ f = font(face, size * SS)
+ chars = list(s)
+ n = len(chars)
+ adv = [f.getlength(ch) / SS for ch in chars]
+ ink_l = [(f.getbbox(ch, anchor='ls') if not ch.isspace() else (0, 0, f.getlength(ch), 0)) for ch in chars]
+ lb = ink_l[0][0] / SS
+ rb = adv[-1] - ink_l[-1][2] / SS
+ nat = sum(adv) - lb - rb
+ meas = x1 - x0
+ if align == 'justify':
+ k = stretch or float(np.clip((meas - track * (n - 1)) / max(nat, 1), *limits))
+ gap = (meas - nat * k) / max(n - 1, 1)
+ pen = x0 - lb * k
+ else:
+ k = stretch or 1.0
+ gap = track
+ total = nat * k + gap * (n - 1)
+ start = {'left': x0, 'center': (x0 + x1 - total) / 2, 'right': x1 - total}[align]
+ pen = start - lb * k
+ r = self.rng
+ P = self._plate(ink)
+ pad = int(cap * 0.3 + 6)
+ top = int(base - cap * 1.35) - pad
+ hl = int(cap * 1.75) + 2 * pad
+ lx0 = int(pen) - pad
+ lw = int(sum(adv) * k + gap * n + 2 * pad + 8)
+ G = np.zeros((hl, lw), np.float32)
+ FILM = np.ones((hl, lw), np.float32)
+ INL = np.zeros((hl, lw), np.float32)
+ boxes = []
+ for i, ch in enumerate(chars):
+ if ch.isspace():
+ pen += adv[i] * k + gap
+ continue
+ bb = ink_l[i]
+ gw = int(np.ceil((bb[2] - bb[0]) + 8 * SS))
+ gh = int(np.ceil((bb[3] - bb[1]) + 8 * SS))
+ im = Image.new('L', (gw, gh), 0)
+ ImageDraw.Draw(im).text((4 * SS - bb[0], 4 * SS - bb[1]), ch, font=f, fill=255, anchor='ls')
+ tw, th = max(1, int(round(gw * k / SS))), max(1, int(round(gh / SS)))
+ g = np.asarray(im.resize((tw, th), Image.LANCZOS), np.float32) / 255
+ g = np.clip(g, 0, 1)
+ # where the glyph lands: its ink box starts at pen + bb[0]/SS*k
+ gx = pen + (bb[0] / SS - 4) * k
+ jit = r.normal(0, 0.35 + cap * 0.004)
+ gy = base + bb[1] / SS - 4 + jit
+ ix, iy = int(round(gx)) - lx0, int(round(gy)) - top
+ g, film, inl = self._block(g, cap, wear, grain, inline, r)
+ ys, xs = max(0, iy), max(0, ix)
+ ye, xe = min(hl, iy + th), min(lw, ix + tw)
+ if ye > ys and xe > xs:
+ sub = (slice(ys, ye), slice(xs, xe))
+ gg = g[ys - iy:ye - iy, xs - ix:xe - ix]
+ np.maximum(G[sub], gg, out=G[sub])
+ FILM[sub] = np.where(gg > 0.02, np.minimum(FILM[sub], film[ys - iy:ye - iy, xs - ix:xe - ix]), FILM[sub])
+ if inl is not None:
+ np.maximum(INL[sub], inl[ys - iy:ye - iy, xs - ix:xe - ix], out=INL[sub])
+ boxes.append((lx0 + ix, top + iy, lx0 + ix + tw, top + iy + th))
+ pen += adv[i] * k + gap
+ Gp = np.clip(G - INL, 0, 1)
+ full = self._place(Gp, lx0, top)
+ fullf = self._place(FILM, lx0, top, fill=1.0)
+ self.lock(full, ink, fullf)
+ if shade:
+ dx, dy, sink, sgap = shade
+ steps = int(max(abs(dx), abs(dy)))
+ S = np.zeros_like(G)
+ for t in range(1, steps + 1):
+ np.maximum(S, shift(G, dx * t / steps, dy * t / steps), out=S)
+ S = np.clip(S - _dilate(G, sgap), 0, 1)
+ self.lock(self._place(S, lx0, top), sink)
+ return dict(x0=x0, x1=x1, top=base - cap, base=base, boxes=boxes, stretch=k)
+
+ def _block(self, g, cap, wear, grain, inline, r):
+ """one piece of wood type: grain streaks, an end that prints light, dents, nicks, a rare split"""
+ h, w = g.shape
+ film = np.full((h, w), r.uniform(0.9, 1.0), np.float32)
+ if grain > 0 and h > 8 and w > 8:
+ gh, gw = max(2, h // 3), max(2, int(w / max(20, cap * 0.9)) + 2)
+ st = np.asarray(Image.fromarray(r.random((gh, gw)).astype(np.float32)).resize((w, h), Image.BICUBIC), np.float32)
+ fine = np.asarray(Image.fromarray(r.random((max(2, h // 2), max(2, w // 30) + 2)).astype(np.float32))
+ .resize((w, h), Image.BICUBIC), np.float32)
+ streak = smoothstep(0.55, 0.85, st) * 0.6 + smoothstep(0.6, 0.9, fine) * 0.4
+ film *= 1 - grain * 0.16 * streak
+ a = r.uniform(0, 2 * np.pi)
+ yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
+ ramp = ((xx - w / 2) * np.cos(a) + (yy - h / 2) * np.sin(a)) / (max(w, h) / 2 + 1)
+ film *= 1 - r.uniform(0.0, 0.10) * np.clip(ramp, 0, 1) # not quite type-high at one end
+ if wear > 0 and cap > 40:
+ for _ in range(r.poisson(wear * 2.2)): # dents: soft pale spots
+ cx, cy, rr = r.uniform(0, w), r.uniform(0, h), r.uniform(0.03, 0.09) * cap
+ film *= 1 - r.uniform(0.15, 0.35) * np.exp(-((xx - cx) ** 2 + (yy - cy) ** 2) / (2 * rr * rr))
+ inl = None
+ if inline:
+ inset, width = inline
+ e1 = _erode(g, inset)
+ e2 = _erode(g, inset + width)
+ inl = np.clip(e1 - e2, 0, 1)
+ if wear > 0:
+ edge = (g > 0.5) & (_erode(g, 1) < 0.5)
+ ey, ex = np.nonzero(edge)
+ if len(ey):
+ n = r.poisson(wear * (2 + len(ey) / 220))
+ im = Image.fromarray((g * 255).astype(np.uint8))
+ d = ImageDraw.Draw(im)
+ for _ in range(n):
+ j = int(r.integers(len(ey)))
+ rr = r.uniform(0.8, 1.6 + cap * 0.012)
+ d.ellipse((ex[j] - rr, ey[j] - rr * r.uniform(0.6, 1), ex[j] + rr, ey[j] + rr), fill=0)
+ if cap > 60 and r.random() < wear * 0.22: # a split along the grain
+ y = r.uniform(h * 0.2, h * 0.8)
+ pts = [(x, y + r.normal(0, 0.8) + (x - w / 2) * r.normal(0, 0.03)) for x in np.linspace(0, w, 7)]
+ d.line(pts, fill=0, width=max(1, int(round(cap * 0.012))))
+ g = np.asarray(im, np.float32) / 255
+ return g, film, inl
+
+ def type_width(self, s, cap, face='clarendon', stretch=1.0, track=0.0):
+ """natural width of a line of wood type (ink edges, no justification)"""
+ f = font(face, cap / cap_ratio(face) * SS)
+ b0 = f.getbbox(s[0], anchor='ls')[0] / SS
+ rb = f.getlength(s[-1]) / SS - f.getbbox(s[-1], anchor='ls')[2] / SS
+ return (f.getlength(s) / SS - b0 - rb) * stretch + track * (len(s) - 1)
+
+ # ------------------------------------------------------------ metal type, rules, ornaments
+ def text_mask(self, s, x, y, size, face='roman', anchor='ls', spacing=0.0, rot=0.0, stretch=1.0):
+ """small metal type -> full-canvas mask. anchor as in Pillow (l/m/r + a/t/m/s/b); size is the font size"""
+ f = font(face, size * SS)
+ adv = [f.getlength(ch) + spacing * SS for ch in s]
+ total = (sum(adv) - spacing * SS) / SS * stretch
+ asc, desc = f.getmetrics()
+ W2 = int(total * SS / stretch + size * SS * 1.2 + 8)
+ H2 = int((asc + desc) * 1.4 + 8)
+ im = Image.new('L', (W2, H2), 0)
+ d = ImageDraw.Draw(im)
+ ox, oy = int(size * SS * 0.6), int(asc * 1.2)
+ cx = ox
+ for ch, a in zip(s, adv):
+ d.text((cx, oy), ch, font=f, fill=255, anchor='ls')
+ cx += a
+ tw = max(1, int(round(W2 / SS * stretch)))
+ a = np.asarray(im.resize((tw, max(1, H2 // SS)), Image.LANCZOS), np.float32) / 255
+ capH = -f.getbbox('H', anchor='ls')[1] / SS
+ dy = {'s': 0, 'a': -asc / SS, 't': capH, 'm': capH / 2, 'b': -desc / SS, 'd': -desc / SS}[anchor[1]]
+ px = x - total * {'l': 0, 'm': 0.5, 'r': 1}[anchor[0]] - ox / SS * stretch
+ py = y + dy - oy / SS
+ if rot:
+ R = int(np.hypot(*a.shape) + abs(px - x) + abs(py - y)) + 4
+ ox, oy = int(round(x)) - R, int(round(y)) - R
+ big = np.zeros((2 * R, 2 * R), np.float32)
+ _paste(big, a, int(round(px)) - ox, int(round(py)) - oy)
+ bim = Image.fromarray(big, 'F').rotate(rot, resample=Image.BICUBIC, center=(x - ox, y - oy))
+ return self._place(np.clip(np.asarray(bim, np.float32), 0, 1), ox, oy)
+ return self._place(a, int(round(px)), int(round(py)))
+
+ def text(self, s, x, y, size, face='roman', ink=BLACK, anchor='ls', spacing=0.0, rot=0.0, stretch=1.0):
+ """set a line of small metal type (cleaner than wood type) and lock it on the forme; returns its width"""
+ m = self.text_mask(s, x, y, size, face, anchor, spacing, rot, stretch)
+ self.lock(m, ink)
+ return self.text_width(s, size, face, spacing) * stretch
+
+ def text_width(self, s, size, face='roman', spacing=0.0):
+ f = font(face, size * SS)
+ return (sum(f.getlength(ch) for ch in s) / SS + spacing * (len(s) - 1))
+
+ def rule(self, x0, x1, y, kind='single', ink=BLACK, weight=3.0, joints=260):
+ """brass rule from x0 to x1 at y. kind: single | double | thick_thin | thin_thick | dotted.
+ Long rules are made of several pieces of brass: tiny gaps and 1 px steps at the joints."""
+ r = self.rng
+ parts = {'single': [(0, weight)], 'double': [(-weight * 1.1, weight * 0.6), (weight * 1.1, weight * 0.6)],
+ 'thick_thin': [(-weight * 0.9, weight * 1.5), (weight * 1.35, weight * 0.45)],
+ 'thin_thick': [(-weight * 1.35, weight * 0.45), (weight * 0.9, weight * 1.5)]}
+ m = np.zeros((self.H, self.W), np.float32)
+ if kind == 'dotted':
+ n = int((x1 - x0) / (weight * 3.2))
+ for xx in np.linspace(x0, x1, n):
+ m = np.maximum(m, self._disc(xx, y, weight * 0.62))
+ self.lock(m, ink)
+ return m
+ cuts = [x0]
+ while cuts[-1] + joints < x1 - joints * 0.4:
+ cuts.append(cuts[-1] + joints * r.uniform(0.8, 1.2))
+ cuts.append(x1)
+ for (a, b) in zip(cuts[:-1], cuts[1:]):
+ step = r.choice([-0.6, 0, 0, 0.6])
+ for off, wdt in parts[kind]:
+ yy = y + off + step
+ g = 0.8 if b < x1 else 0
+ m = np.maximum(m, np.clip(np.minimum(self.XX - a, b - g - self.XX) + 0.5, 0, 1)
+ * np.clip(wdt / 2 - np.abs(self.YY - yy) + 0.5, 0, 1))
+ self.lock(m, ink)
+ return m
+
+ def leaders(self, x0, x1, y, size=4.0, gap=14.0, ink=BLACK):
+ """a row of leader dots between a name and its detail"""
+ n = max(1, int((x1 - x0) / gap))
+ m = np.zeros((self.H, self.W), np.float32)
+ for xx in np.linspace(x0, x1, n + 1):
+ m = np.maximum(m, self._disc(xx, y, size / 2))
+ self.lock(m, ink)
+
+ def star(self, cx, cy, r, ink=RED, points=5, inner=0.4, rot=90.0):
+ """a printer's star (metal ornament)"""
+ t = np.deg2rad(rot) + np.arange(points * 2) * np.pi / points
+ rr = np.where(np.arange(points * 2) % 2 == 0, r, r * inner)
+ pts = np.stack([cx + np.cos(t) * rr, cy - np.sin(t) * rr], 1)
+ m = self.poly(pts)
+ self.lock(m, ink)
+ return m
+
+ def ornament(self, ch, cx, cy, size, ink=BLACK, rot=0.0):
+ """a printer's flower from the ornament font (Bodoni Ornaments on macOS); a star where it is missing"""
+ if _face('ornament') is None:
+ return self.star(cx, cy, size * 0.4, ink)
+ m = self.text_mask(ch, cx, cy, size, 'ornament', anchor='mm', rot=rot)
+ self.lock(m, ink)
+ return m
+
+ def border(self, x0, y0, x1, y1, ink=BLACK, weight=4.0, corners=True):
+ """a thick-and-thin rule box with square corner pieces, the frame of a bill"""
+ for (yy, flip) in [(y0, False), (y1, True)]:
+ self.rule(x0, x1, yy, 'thin_thick' if flip else 'thick_thin', ink, weight)
+ m = np.zeros((self.H, self.W), np.float32)
+ for xx, flip in [(x0, False), (x1, True)]:
+ o1, o2 = (-weight * 0.9, weight * 1.35) if not flip else (weight * 0.9, -weight * 1.35)
+ for off, wdt in [(o1, weight * 1.5), (o2, weight * 0.45)]:
+ m = np.maximum(m, np.clip(wdt / 2 - np.abs(self.XX - (xx + off)) + 0.5, 0, 1)
+ * np.clip(np.minimum(self.YY - y0, y1 - self.YY) + 0.5, 0, 1))
+ self.lock(m, ink)
+ if corners:
+ s = weight * 4.2
+ for (cx, cy) in [(x0, y0), (x1, y0), (x0, y1), (x1, y1)]:
+ sq = self.rect(cx - s, cy - s, cx + s, cy + s)
+ self.clear(sq, ink)
+ self.lock(np.clip(sq - self.rect(cx - s + weight, cy - s + weight, cx + s - weight, cy + s - weight), 0, 1)
+ + self._disc(cx, cy, s * 0.42), ink)
+
+ # ------------------------------------------------------------ shapes (full-canvas masks, 0..1)
+ def _place(self, a, x0, y0, fill=0.0):
+ out = np.full((self.H, self.W), fill, np.float32)
+ h, w = a.shape
+ ys, xs = max(0, y0), max(0, x0)
+ ye, xe = min(self.H, y0 + h), min(self.W, x0 + w)
+ if ye > ys and xe > xs:
+ out[ys:ye, xs:xe] = a[ys - y0:ye - y0, xs - x0:xe - x0]
+ return out
+
+ def _disc(self, cx, cy, r):
+ x0, y0 = int(cx - r - 2), int(cy - r - 2)
+ n = int(2 * r + 5)
+ yy, xx = np.mgrid[y0:y0 + n, x0:x0 + n].astype(np.float32)
+ return self._place(np.clip(r - np.hypot(xx - cx, yy - cy) + 0.5, 0, 1), x0, y0)
+
+ def poly(self, pts, ss=3):
+ """filled polygon mask (supersampled)"""
+ P = np.asarray(pts, np.float64)
+ x0, y0 = int(np.floor(P[:, 0].min())) - 2, int(np.floor(P[:, 1].min())) - 2
+ x1, y1 = int(np.ceil(P[:, 0].max())) + 2, int(np.ceil(P[:, 1].max())) + 2
+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0)
+ ImageDraw.Draw(im).polygon([((x - x0) * ss, (y - y0) * ss) for x, y in P], fill=255)
+ a = np.asarray(im.resize((x1 - x0, y1 - y0), Image.BOX), np.float32) / 255
+ return self._place(a, x0, y0)
+
+ def shape(self, pts, per=10):
+ """closed smooth shape through control points (Catmull-Rom) -> mask"""
+ return self.poly(_closed_spline(pts, per))
+
+ def rect(self, x0, y0, x1, y1):
+ return (np.clip(np.minimum(self.XX - x0, x1 - self.XX) + 0.5, 0, 1)
+ * np.clip(np.minimum(self.YY - y0, y1 - self.YY) + 0.5, 0, 1))
+
+ def ellipse(self, cx, cy, rx, ry, rot=0.0, a0=0.0, a1=360.0, n=120):
+ """ellipse (or a pie slice from a0 to a1, degrees ccw) as a mask"""
+ t = np.deg2rad(np.linspace(a0, a1, n))
+ c, s = np.cos(np.deg2rad(rot)), np.sin(np.deg2rad(rot))
+ x, y = np.cos(t) * rx, -np.sin(t) * ry
+ pts = np.stack([cx + x * c + y * s, cy - x * s + y * c], 1)
+ if a1 - a0 < 360: pts = np.vstack([[cx, cy], pts])
+ return self.poly(pts)
+
+ @staticmethod
+ def outline_pts(path, widths, cap=True):
+ """polygon around a centre-line `path` (N x 2) with per-point widths (N,) -- limbs, trunks, ropes"""
+ P = np.asarray(path, np.float32)
+ wd = np.asarray(widths, np.float32)
+ d = np.gradient(P, axis=0)
+ d /= np.linalg.norm(d, axis=1, keepdims=True) + 1e-6
+ nrm = np.stack([-d[:, 1], d[:, 0]], 1)
+ L = P + nrm * wd[:, None] / 2
+ R = P - nrm * wd[:, None] / 2
+ pts = [L]
+ if cap:
+ a0 = np.arctan2(nrm[-1, 1], nrm[-1, 0])
+ t = np.linspace(0, -np.pi, 9)[1:-1] + a0
+ pts.append(P[-1] + np.stack([np.cos(t), np.sin(t)], 1) * wd[-1] / 2)
+ pts.append(R[::-1])
+ if cap:
+ a0 = np.arctan2(-nrm[0, 1], -nrm[0, 0])
+ t = np.linspace(0, -np.pi, 9)[1:-1] + a0
+ pts.append(P[0] + np.stack([np.cos(t), np.sin(t)], 1) * wd[0] / 2)
+ return np.vstack(pts)
+
+ def tube(self, pts, w0=8.0, w1=None, per=12, widths=None):
+ """a tapered tube along a smooth path (legs, trunk, tail, rope): width w0 at the start, w1 at the end"""
+ path = spline(pts, per) if len(pts) > 2 else np.linspace(pts[0], pts[1], per * 2).astype(np.float32)
+ if widths is None:
+ widths = np.linspace(w0, w0 if w1 is None else w1, len(path))
+ else:
+ widths = np.interp(np.linspace(0, 1, len(path)), np.linspace(0, 1, len(widths)), widths)
+ return self.poly(self.outline_pts(path, widths))
+
+ # ------------------------------------------------------------ the woodcut
+ def ramp(self, p0, p1):
+ """a linear tone field: 0 at point p0, 1 at point p1 (and beyond), for darkening one side of a form"""
+ dx, dy = p1[0] - p0[0], p1[1] - p0[1]
+ t = ((self.XX - p0[0]) * dx + (self.YY - p0[1]) * dy) / (dx * dx + dy * dy + 1e-6)
+ return np.clip(t, 0, 1).astype(np.float32)
+
+ def cast(self, mask, dx, dy, onto, soft=2.0):
+ """the shadow `mask` casts on `onto` when the light comes from the opposite of (dx, dy)"""
+ return np.clip(blur(shift(mask, dx, dy), soft) - mask, 0, 1) * onto
+
+ def form_tone(self, mask, soft=None, light=LIGHT, ambient=0.12, lift=1.0):
+ """tone 0 (lit) .. 1 (dark) of a rounded volume filling `mask`: a blurred mask as a pillow height map,
+ lit from `light`. soft: how round (px, default ~ a sixth of the shape's size)"""
+ rows, cols = np.flatnonzero(mask.max(1) > 0.01), np.flatnonzero(mask.max(0) > 0.01)
+ if not len(rows): return np.zeros_like(mask)
+ if soft is None:
+ soft = max(4.0, min(rows[-1] - rows[0], cols[-1] - cols[0]) / 6)
+ pad = int(soft * 3)
+ y0, y1 = max(0, rows[0] - pad), min(self.H, rows[-1] + pad + 1)
+ x0, x1 = max(0, cols[0] - pad), min(self.W, cols[-1] + pad + 1)
+ m = mask[y0:y1, x0:x1]
+ h = blur(m, soft) * soft * 2.2 * lift
+ gy, gx = np.gradient(h)
+ L = np.array([light[0], light[1], 0.75], np.float32)
+ L /= np.linalg.norm(L)
+ nz = 1.0
+ nl = (-gx * L[0] - gy * L[1] + nz * L[2]) / np.sqrt(gx * gx + gy * gy + nz * nz)
+ t = np.clip(1 - (nl - ambient) / (1 - ambient), 0, 1) * m
+ out = np.zeros_like(mask)
+ out[y0:y1, x0:x1] = t
+ return out
+
+ def key(self, mask, width=3.5, heavy=7.5, light=LIGHT, ink=BLACK):
+ """the key line: a cut outline just inside the shape, thicker on the side turned from the light"""
+ sig = max(width, heavy) * 0.75
+ rows, cols = np.flatnonzero(mask.max(1) > 0.01), np.flatnonzero(mask.max(0) > 0.01)
+ if not len(rows): return mask * 0
+ pad = int(sig * 4 + 4)
+ y0, y1 = max(0, rows[0] - pad), min(self.H, rows[-1] + pad + 1)
+ x0, x1 = max(0, cols[0] - pad), min(self.W, cols[-1] + pad + 1)
+ m = mask[y0:y1, x0:x1]
+ d = _inner_dist(m, sig)
+ b = blur(m, 2.5)
+ gy, gx = np.gradient(b)
+ gl = np.sqrt(gx * gx + gy * gy) + 1e-6
+ L = np.array(light, np.float32) / np.hypot(*light)
+ facing = (-gx * L[0] - gy * L[1]) / gl # +1 the edge faces the light
+ shadow = smoothstep(-0.2, 0.9, -facing)
+ w = width + (heavy - width) * shadow
+ w = w * (1 + 0.18 * self.wob[y0:y1, x0:x1] * 4)
+ line = np.clip(w - d + 0.5, 0, 1) * m
+ out = self._place(line, x0, y0)
+ self.lock(out, ink)
+ return out
+
+ def hatch(self, mask, angle=0.0, spacing=9.0, tone=None, centre=None, aspect=1.0, lo=0.12, gain=1.0,
+ wobble=1.0, ink=BLACK, solid=0.92):
+ """swelling parallel hatching cut into `mask`. The lines run at `angle` (degrees ccw), or as arcs around
+ `centre` (cross-contour lines on a round body; aspect squashes them). Each line's width follows `tone`
+ (0..1, default form_tone(mask)): thin where it is light, fattening into solid black above `solid`,
+ and petering out below `lo`, so every line ends in a hand-cut taper."""
+ if tone is None: tone = self.form_tone(mask)
+ rows, cols = np.flatnonzero(mask.max(1) > 0.01), np.flatnonzero(mask.max(0) > 0.01)
+ if not len(rows): return mask * 0
+ y0, y1, x0, x1 = rows[0], rows[-1] + 1, cols[0], cols[-1] + 1
+ X, Y = self.XX[y0:y1, x0:x1], self.YY[y0:y1, x0:x1]
+ if centre is None:
+ t = np.deg2rad(angle)
+ v = X * np.sin(t) + Y * np.cos(t)
+ else:
+ v = np.sqrt((X - centre[0]) ** 2 + ((Y - centre[1]) * aspect) ** 2)
+ v = v + self.wob[y0:y1, x0:x1] * spacing * 1.3 * wobble
+ i = np.floor(v / spacing + 0.5)
+ dist = np.abs(v - i * spacing)
+ j = _hash(i.astype(np.int64), self.seed)
+ tt = tone[y0:y1, x0:x1] * gain + 0.07 * j
+ hw = spacing * 0.5 * np.clip((tt - lo) / max(solid - lo, 1e-3), 0, 1.05) ** 0.85
+ line = np.clip(hw - dist + 0.5, 0, 1) * (hw > 0.35) * mask[y0:y1, x0:x1]
+ out = self._place(line.astype(np.float32), x0, y0)
+ self.lock(out, ink)
+ return out
+
+ def line(self, pts, width=3.0, taper=(0.25, 0.25), ink=BLACK, per=12):
+ """a cut line along a smooth path: swells to `width`, tapers at both ends (wrinkles, folds, ropes)"""
+ path = spline(pts, per) if len(pts) > 2 else np.linspace(pts[0], pts[1], per * 2).astype(np.float32)
+ n = len(path)
+ t = np.linspace(0, 1, n)
+ prof = np.clip(np.minimum(t / max(taper[0], 1e-3), (1 - t) / max(taper[1], 1e-3)), 0, 1) ** 0.7
+ w = np.maximum(width * (0.15 + 0.85 * prof), 0.6)
+ m = self.poly(self.outline_pts(path, w, cap=False))
+ self.lock(m, ink)
+ return m
+
+ def solid(self, mask, ink=BLACK):
+ """leave the wood standing: a solid black (or red) area"""
+ self.lock(np.clip(mask, 0, 1), ink)
+ return mask
+
+ def stipple(self, mask, density=0.004, size=(0.8, 2.2), ink=BLACK, tone=None):
+ """dots picked out with a point (sawdust, sand, texture); density = dots per px of mask"""
+ r = self.rng
+ rows, cols = np.flatnonzero(mask.max(1) > 0.01), np.flatnonzero(mask.max(0) > 0.01)
+ if not len(rows): return
+ y0, y1, x0, x1 = rows[0], rows[-1] + 1, cols[0], cols[-1] + 1
+ h, w = y1 - y0, x1 - x0
+ n = int(mask[y0:y1, x0:x1].sum() * density)
+ im = Image.new('L', (w * 2, h * 2), 0)
+ d = ImageDraw.Draw(im)
+ for _ in range(n):
+ x, y = r.uniform(0, w), r.uniform(0, h)
+ p = mask[y0 + int(y), x0 + int(x)] * (1 if tone is None else tone[y0 + int(y), x0 + int(x)])
+ if r.random() > p: continue
+ rr = r.uniform(*size)
+ d.ellipse(((x - rr) * 2, (y - rr * r.uniform(0.6, 1)) * 2, (x + rr) * 2, (y + rr) * 2), fill=255)
+ a = np.asarray(im.resize((w, h), Image.BOX), np.float32) / 255
+ self.lock(self._place(a, x0, y0), ink)
+
+ def tint(self, mask, ink=RED, loose=2.2, grow=1.0):
+ """the colour block, cut separately and a little loosely: its edge wanders off the key by ~`loose` px
+ and it is cut a hair fat (`grow` px) so it runs under the black lines"""
+ rows, cols = np.flatnonzero(mask.max(1) > 0.01), np.flatnonzero(mask.max(0) > 0.01)
+ if not len(rows): return
+ pad = int(loose * 3 + grow + 6)
+ y0, y1 = max(0, rows[0] - pad), min(self.H, rows[-1] + pad + 1)
+ x0, x1 = max(0, cols[0] - pad), min(self.W, cols[-1] + pad + 1)
+ m = mask[y0:y1, x0:x1]
+ h, w = m.shape
+ dxn = noise2d(h, w, 60, 2, self._seed()) - 0.5
+ dyn = noise2d(h, w, 60, 2, self._seed()) - 0.5
+ yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
+ sx = np.clip(xx + dxn * loose * 4, 0, w - 1).astype(np.int32)
+ sy = np.clip(yy + dyn * loose * 4, 0, h - 1).astype(np.int32)
+ mw = m[sy, sx]
+ if grow >= 1:
+ mw = _dilate(mw, int(round(grow)))
+ mw = blur(mw, 0.6)
+ self.lock(self._place(np.clip(mw, 0, 1), x0, y0), ink)
+
+ # ------------------------------------------------------------ after printing: the life of the bill
+ def fold(self, axis, pos, depth=1.0, crack=0.8):
+ """a crease from folding the bill: axis 'v' (vertical line at x=pos) or 'h' (horizontal at y=pos).
+ The ink cracks off along the crease, dirt settles in it, and the two faces roll the light differently."""
+ r = self.rng
+ d = (self.XX - pos) if axis == 'v' else (self.YY - pos)
+ along = self.YY if axis == 'v' else self.XX
+ n = self.H if axis == 'v' else self.W
+ wig = np.interp(along, np.arange(n), fbm1d(n, 120, 3, self._seed()) * 1.6)
+ d = d + wig
+ sgn = r.choice([-1, 1])
+ self.light *= (1 + depth * 0.05 * sgn * np.tanh(d / 3.0) * np.exp(-np.abs(d) / 55.0)
+ - depth * 0.05 * np.exp(-(d / 2.2) ** 2))
+ # ink cracked off the ridge
+ nz = noise2d(self.H, self.W, 7, 2, self._seed())
+ band = np.exp(-(d / 1.6) ** 2) * smoothstep(0.42, 0.62, nz) * crack
+ printed = np.clip(self.impress, 0, 1)
+ loss = (band * printed)[..., None]
+ self.img = self.img * (1 - loss * 0.85) + self.stock * loss * 0.85
+ dirt = np.exp(-(d / 1.3) ** 2) * (0.5 + 0.5 * nz) * 0.16 * depth
+ self.img *= (1 - dirt[..., None] * (1 - _c('#6b5236')))
+
+ def tone_edges(self, amount=1.0, width=70.0, colour='#a87c45'):
+ """paper browns from the edges in (light and air), and a little everywhere in uneven patches"""
+ e = np.minimum(np.minimum(self.XX, self.W - 1 - self.XX), np.minimum(self.YY, self.H - 1 - self.YY))
+ nz = noise2d(self.H, self.W, 90, 3, self._seed())
+ e = e + (nz - 0.5) * width * 0.9
+ t = np.clip(np.exp(-np.maximum(e, 0) / width) * 0.55 + smoothstep(0.55, 0.95, noise2d(self.H, self.W, 260, 3, self._seed())) * 0.16, 0, 1)
+ t = (t * amount)[..., None]
+ self.img = self.img * (1 - t * (1 - _c(colour) / np.maximum(self.paper_col, 1e-3) * 0.95))
+ self.stock = self.stock * (1 - t * (1 - _c(colour) / np.maximum(self.paper_col, 1e-3) * 0.95))
+
+ def foxing(self, n=160, colour='#9a6436', clusters=6):
+ """foxing: rust-brown spots in the paper, in loose clusters, the larger ones with a darker tide-line ring"""
+ r = self.rng
+ W, H = self.W, self.H
+ im = Image.new('L', (W, H), 0)
+ d = ImageDraw.Draw(im)
+ cs = [(r.uniform(0, W), r.uniform(0, H), r.uniform(60, 240)) for _ in range(clusters)]
+ for k in range(n):
+ if r.random() < 0.7:
+ cx, cy, s = cs[int(r.integers(len(cs)))]
+ x, y = cx + r.normal(0, s), cy + r.normal(0, s * 0.7)
+ else:
+ x, y = r.uniform(0, W), r.uniform(0, H)
+ rr = r.uniform(0.8, 3.0) * (r.uniform(2, 4.5) if r.random() < 0.12 else 1)
+ a = int(r.uniform(50, 150))
+ d.ellipse((x - rr, y - rr * r.uniform(0.6, 1), x + rr, y + rr), fill=a)
+ if rr > 4:
+ d.ellipse((x - rr, y - rr, x + rr, y + rr), outline=min(255, a + 60), width=1)
+ f = blur(np.asarray(im, np.float32) / 255, 0.9)[..., None]
+ self.img = self.img * (1 - f * (1 - _c(colour)))
+
+ def stain(self, cx, cy, rx, ry, strength=0.10, colour='#a07a48'):
+ """a water stain: a faint browned patch with a darker, wandering tide line"""
+ t = np.linspace(0, 2 * np.pi, 140, endpoint=False)
+ wob = 1 + 0.18 * fbm1d(140, 25, 4, self._seed())
+ pts = np.stack([cx + np.cos(t) * rx * wob, cy + np.sin(t) * ry * wob], 1)
+ m = blur(self.poly(pts), 6)
+ ring = np.clip(m * (1 - m) * 4, 0, 1) ** 2
+ a = (m * 0.35 + ring * 0.9)[..., None] * strength
+ self.img = self.img * (1 - a * (1 - _c(colour)))
+
+ def tack(self, x, y, r=4.0):
+ """a tack hole: the bill was nailed up -- a torn hole showing the wall, rust bled into the paper"""
+ g = self.rng
+ halo = self._disc(x, y, r * 4.5)
+ halo = blur(halo, r * 1.6) * (0.6 + 0.4 * noise2d(self.H, self.W, 12, 2, self._seed()))
+ self.img *= (1 - (halo * 0.5)[..., None] * (1 - _c(RUST)))
+ pts = [(x + np.cos(a) * r * g.uniform(0.6, 1.3), y + np.sin(a) * r * g.uniform(0.6, 1.3))
+ for a in np.linspace(0, 2 * np.pi, 9, endpoint=False)]
+ hole = self.poly(pts)
+ for _ in range(3): # little radial tears
+ a = g.uniform(0, 2 * np.pi)
+ L = g.uniform(1.2, 2.6) * r
+ hole = np.maximum(hole, self.poly(self.outline_pts(np.array([[x, y], [x + np.cos(a) * L, y + np.sin(a) * L]]),
+ np.array([1.6, 0.4]), cap=False)))
+ lip = np.clip(_dilate(hole, 2) - hole, 0, 1) * 0.35
+ self.img = self.img * (1 - lip[..., None] * 0.5)
+ self.img = self.img * (1 - hole[..., None]) + _c(WALL) * hole[..., None]
+
+ def nicks(self, n=8, size=(4, 14)):
+ """small bites out of the sheet's edges (the wall shows through)"""
+ g = self.rng
+ m = np.zeros((self.H, self.W), np.float32)
+ for _ in range(n):
+ side = g.integers(4)
+ s = g.uniform(*size)
+ if side == 0: x, y = g.uniform(0, self.W), 0
+ elif side == 1: x, y = g.uniform(0, self.W), self.H
+ elif side == 2: x, y = 0, g.uniform(0, self.H)
+ else: x, y = self.W, g.uniform(0, self.H)
+ pts = [(x + np.cos(a) * s * g.uniform(0.5, 1.2), y + np.sin(a) * s * g.uniform(0.4, 1.0))
+ for a in np.linspace(0, 2 * np.pi, 11, endpoint=False)]
+ m = np.maximum(m, self.poly(pts))
+ lip = np.clip(_dilate(m, 2) - m, 0, 1) * 0.25
+ self.img *= (1 - lip[..., None])
+ self.img = self.img * (1 - m[..., None]) + _c(WALL) * m[..., None]
+
+ def strip(self, x0, y0, x1, y1, rot=0.0, colour='#efe3c6', draw=None, ink=BLACK, misreg=(1.5, -1.0)):
+ """paste a date strip over the bill: a separate slip of whiter stock printed on its own forme.
+ draw(s) gets the strip as a small Letterpress (origin at the strip's top-left + 20 px margin, so the strip
+ spans 20..20+w, 20..20+h) to set type on; it is pressed, rotated by `rot` and pasted. The glue darkens
+ the bill around the strip, and the damp slip dries with a few wrinkles."""
+ r = self.rng
+ w, h = int(x1 - x0), int(y1 - y0)
+ sub = Letterpress(w + 40, h + 40, seed=self._seed(), misreg=0)
+ sub.paper(colour, warm='#e2cfa2', tone=0.25)
+ sub.register(ink, *misreg)
+ if draw is not None:
+ draw(sub)
+ for k in list(sub.plates):
+ sub.press(k)
+ sheet = sub.img * (sub.fibre * sub.light)[..., None]
+ mask = np.zeros((h + 40, w + 40), np.float32)
+ mask[20:20 + h, 20:20 + w] = 1
+ # paper edge: slightly ragged guillotine cut
+ mask = np.clip(_box3(mask) + (np.asarray(Image.fromarray(r.random((h + 40, w + 40)).astype(np.float32)), np.float32) - 0.5) * 0.15, 0, 1)
+ wr = noise2d(h + 40, w + 40, 30, 2, self._seed())
+ sheet = sheet * (1 + 0.035 * (wr - 0.5))[..., None]
+ rgba = np.dstack([np.clip(sheet, 0, 1), mask])
+ cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
+ ims = [Image.fromarray(rgba[..., k].astype(np.float32), 'F').rotate(rot, resample=Image.BICUBIC, expand=True)
+ for k in range(4)]
+ arr = np.stack([np.asarray(i, np.float32) for i in ims], -1)
+ hh, ww = arr.shape[:2]
+ px, py = int(round(cx - ww / 2)), int(round(cy - hh / 2))
+ a = self._place(arr[..., 3], px, py)
+ glue = np.clip(_dilate(a, 3) * 1.0 - a, 0, 1)
+ glue = blur(glue, 2.0) * 0.6
+ self.img *= (1 - (glue * 0.35)[..., None] * (1 - _c('#8a6a3c')))
+ sh = np.clip(shift(blur(a, 1.4), 1, 2) - a, 0, 1) * 0.25
+ self.img *= (1 - sh[..., None])
+ for k in range(3):
+ ch = self._place(arr[..., k], px, py)
+ self.img[..., k] = self.img[..., k] * (1 - a) + ch * a
+ self.impress *= (1 - a)
+ self.stock = self.stock * (1 - a[..., None]) + self.img * a[..., None]
+ return a
+
+ # ------------------------------------------------------------ output
+ def composite(self):
+ imp = blur(self.impress, 1.2)
+ gy, gx = np.gradient(imp)
+ relief = 1 + 0.10 * (gx * LIGHT[0] + gy * LIGHT[1]) # the dent's far wall catches the light
+ img = self.img * (self.fibre * self.light * relief)[..., 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
diff --git a/lib/lineprinter.py b/lib/lineprinter.py
new file mode 100644
index 0000000..9a5edd1
--- /dev/null
+++ b/lib/lineprinter.py
@@ -0,0 +1,918 @@
+"""lineprinter — ASCII art from a 1970s impact line printer on greenbar continuous paper (numpy + Pillow only).
+
+Model:
+ form : continuous fanfold "greenbar" paper, 14 7/8 x 11 in, printed at 10 characters per inch and 6 lines
+ per inch (132 columns, 66 lines a page). Pale green bands 1/2 in tall (exactly 3 print lines) are
+ flexo-printed across the form; a tractor strip on each side carries 5/32 in feed holes every 1/2 in and
+ is split off by a line of micro-perforations; a cross perforation and a fanfold crease mark each page
+ break (11 in deep by default; `page_in=8.5` with a smaller `ppi` puts a whole sheet, tear line to tear
+ line, on the desk). Holes look through to the desk, with the paper's own shadow inside them.
+ picture : nothing is painted on the paper. The scene is painted into a hidden *role map* at sub-cell
+ resolution (6 x 10 samples per character cell), in painter's order:
+ fill(mask, role, tone) a region: which glyph vocabulary (role) and how much ink it wants (tone);
+ stroke(points) a drawn line (tower struts, outlines, antennae);
+ text(s, col, row) literal characters (headers, log lines, a printer plot).
+ Shading helpers give tones the way light would: `sphere_tone` (smoke puffs), `cylinder_tone`
+ (a turned body), `billow` (a cloud of puffs that shadow each other and can be lit from below).
+ glyphs : `compose()` decides every cell:
+ line cells -> by the stroke's direction measured in real pixels (cells are tall) and where it sits in
+ the cell: | / \\ for steep, _ - . ' for flat and shallow (so curves come out as _.-'),
+ X and + where two strokes cross; a stroke smeared over two cells keeps the stronger one;
+ edge cells -> where a silhouette turns, the same rule on the boundary between two regions; 'round'
+ roles use ( ) for upright sides, a flat top edge high in its cell moves up a row as '_';
+ fill cells -> the role's ramp, light to dark, chosen by tone with error diffusion inside the role (so
+ % @ # blend into each other instead of forming hard contour bands);
+ darkest -> overstrikes: ramp entries like '#@' are printed on top of each other in extra passes.
+ printing : a drum printer: one hammer per column fires through an inked fabric ribbon against a spinning type
+ drum. Each impression is the type slug: ragged edge and grain from the ribbon weave and paper tooth;
+ a weak impression gets thinner and breaks up instead of turning grey. Drum timing makes each character
+ sit a little high or low (same character, same error), every hammer has its own force (a weak hammer
+ leaves a pale column down the page), the ribbon fades as the job runs and wears across its width, some
+ lines are printed with the ribbon riding low (character tops starve), overstrike passes land a fraction
+ of a pixel off, worn slugs print the same nick every time; ink wicks into the paper and the hammer
+ leaves a faint emboss.
+ after : someone reads the printout with a ballpoint: `pen`, `ring`, `tick`, `pen_text`.
+
+ from lineprinter import LinePrinter
+ lp = LinePrinter(1920, 1080, seed=3)
+ lp.form()
+ lp.role('smoke', ['', '.', ':', '+', '%', '@', '#', '#@'])
+ puffs = [(40, 30, 6), (50, 28, 7), (58, 31, 5)] # (col, row, radius in columns)
+ lp.billow(puffs, 'smoke')
+ lp.stroke([(20, 10), (20, 30)]) # a vertical line -> '|' cells
+ lp.text('T+00:03 LIFTOFF', 96, 5, strike=2) # bold by double strike
+ lp.print_rows(0, lp.rows)
+ lp.save('out.jpg')
+"""
+import os
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+from core import blur, fbm1d, spline, noise2d, smoothstep, polygon_mask, blob_pts, shift, load_font
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+def _c(c):
+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)
+
+
+def gauss(a, sigma):
+ """separable gaussian blur (edge padded), fine for small sigmas on big arrays"""
+ if sigma <= 0.05: return a.astype(np.float32)
+ r = max(1, int(np.ceil(sigma * 3)))
+ k = np.exp(-0.5 * (np.arange(-r, r + 1) / sigma) ** 2).astype(np.float32); k /= k.sum()
+ out = a.astype(np.float32)
+ for ax in (0, 1):
+ pad = [(0, 0), (0, 0)]; pad[ax] = (r, r)
+ p = np.pad(out, pad, mode='edge')
+ n = out.shape[ax]
+ acc = np.zeros_like(out)
+ for i, w in enumerate(k):
+ acc += w * (p[i:i + n] if ax == 0 else p[:, i:i + n])
+ out = acc
+ return out
+
+
+_MONO = [('/System/Library/Fonts/Menlo.ttc', 1), ('/usr/share/fonts/**/DejaVuSansMono-Bold.ttf', 0),
+ ('/usr/share/fonts/**/LiberationMono-Bold.ttf', 0), ('C:/Windows/Fonts/consolab.ttf', 0),
+ ('C:/Windows/Fonts/courbd.ttf', 0), ('/System/Library/Fonts/Supplemental/Courier New Bold.ttf', 0)]
+
+
+def mono_font(size, weight='regular'):
+ """the print-chain face: a monospaced sans (ink spread makes it heavier). $INKPAINT_FONT_LINEPRINTER overrides"""
+ import glob
+ env = os.environ.get('INKPAINT_FONT_LINEPRINTER')
+ if env and os.path.exists(env): return ImageFont.truetype(env, int(size))
+ cands = _MONO if weight == 'bold' else [('/System/Library/Fonts/Menlo.ttc', 0), ('/usr/share/fonts/**/DejaVuSansMono.ttf', 0),
+ ('/usr/share/fonts/**/LiberationMono-Regular.ttf', 0), ('C:/Windows/Fonts/consola.ttf', 0),
+ ('C:/Windows/Fonts/cour.ttf', 0)] + _MONO
+ for pat, idx in cands:
+ for f in glob.glob(pat, recursive=True):
+ try:
+ return ImageFont.truetype(f, int(size), index=idx)
+ except OSError:
+ pass
+ return load_font('typewriter', size)
+
+
+# how a line or a silhouette edge becomes a character, by its direction and where it sits in the cell
+OUTLINES = {
+ 'straight': dict(v='|', h='-', low='_', dot='.', tick="'", up='/', down='\\', x='X', plus='+', left='|', right='|',
+ top='_'),
+ 'round': dict(v='|', h='-', low='_', dot='.', tick="'", up='/', down='\\', x='X', plus='+', left='(', right=')',
+ top=None),
+}
+
+
+def _style(st):
+ if isinstance(st, dict): return dict(OUTLINES['straight'], **st)
+ return OUTLINES[st or 'straight']
+
+
+INK = '#22222c' # black nylon ribbon, slightly blue as it ages
+
+
+class LinePrinter:
+ def __init__(self, W=1920, H=1080, seed=0, cols=132, top=40.0, cpi=10, lpi=6, form_in=14.875, ss=2,
+ ink=INK, sub=(6, 10), weight='bold', ppi=None, page_in=11.0):
+ """ppi=None fits the form's width to the picture; a smaller ppi shows the desk on both sides.
+ page_in: form depth (11 in = 66 lines; 8.5 in = 51 lines shows a whole page between two tear lines)"""
+ self.W, self.H, self.ss = W, H, ss
+ self.rng = np.random.default_rng(seed)
+ self.ppi = ppi or W / form_in
+ self.cw, self.ch = self.ppi / cpi, self.ppi / lpi # character cell in px
+ self.px0 = (W - form_in * self.ppi) / 2 # paper edges
+ self.px1 = self.px0 + form_in * self.ppi
+ self.page_rows = int(round(page_in * lpi)) # lines from one tear line to the next
+ self.cols = cols
+ self.xl = (W - cols * self.cw) / 2 # left edge of column 0
+ self.top = float(top) # page break (row 0 starts here)
+ self.rows = int(np.ceil((H - top) / self.ch))
+ self.sx, self.sy = sub
+ SY, SX = self.rows * self.sy, cols * self.sx
+ self.inst = np.zeros((SY, SX), np.int32) # painter's-order instance id (0 = bare paper)
+ self.rmap = np.zeros((SY, SX), np.int16) # role id
+ self.tone = np.zeros((SY, SX), np.float32) # ink wanted 0..1
+ self.line = np.zeros((SY, SX), np.float32) # stroke coverage
+ self.lset = np.zeros((SY, SX), np.int16) # which glyph set a stroke uses
+ self._n = 0
+ self.Y, self.X = (np.mgrid[0:SY, 0:SX].astype(np.float32) + 0.5) / np.array([self.sy, self.sx], np.float32)[:, None, None]
+ self.roles = {'paper': dict(id=0, ramp=[''], edge=None, outline=_style('straight'), dither=0.0, noise=0.0,
+ group='paper', inner_max=1.0)}
+ self._role_by_id = ['paper']
+ self.line_sets = [_style('straight')]
+ self.fixed = {}
+ self.grid = None
+ self.ink_col = _c(ink)
+ self.inkbuf = np.zeros((H * ss, W * ss), np.float32)
+ self.emb = np.zeros((H * ss, W * ss), np.float32)
+ self.pens = {}
+ self.stages = []
+ self.paper_rgb = None
+ self.printed = set()
+ self._jobpos = 0
+ # ---- the machine: drum timing per character, hammers per column, ribbon, paper feed
+ fs = self.ch * 0.86 * ss # cap height ~ 0.105 in
+ self.font = mono_font(fs, weight)
+ self.base = int(round(4 + self.ch * ss * 0.74)) # baseline inside a stamp
+ self._stamps, self._protos = {}, {}
+ self.drum = {}
+ r = self.rng
+ self.h_force = np.clip(r.normal(1.0, 0.045, cols), 0.86, 1.1)
+ for c in r.choice(cols, 2, replace=False): self.h_force[c] = r.uniform(0.66, 0.76) # weak hammers
+ self.h_dx = r.normal(0, 0.22, cols)
+ self.h_dy = r.normal(0, 0.18, cols)
+ self.feed = r.normal(0, 0.3, self.rows + 4)
+ self.skew = np.tan(np.radians(r.uniform(-0.06, 0.06)))
+ self.low_rows = set(int(i) for i in np.nonzero(r.random(self.rows) < 0.06)[0])
+ self.line_ink = np.clip(r.normal(1.0, 0.035, self.rows + 4), 0.88, 1.08)
+ self.wear = 1 - 0.08 * (0.5 + 0.5 * np.sin(np.arange(cols) / cols * 2 * np.pi * 1.3 + r.uniform(0, 6)))
+ self.fade = 0.28
+ self._weave = self._make_weave()
+ self._tooth = None
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ # ================================================================ geometry
+ def xy(self, col, row):
+ """pixel position (1x) of a point given in cell coordinates (col, row); (c, r) is a cell's top-left"""
+ return self.xl + col * self.cw, self.top + row * self.ch
+
+ def centre(self, col, row):
+ """pixel centre (1x) of cell (col, row)'s x-height area"""
+ return self.xl + (col + 0.5) * self.cw, self.top + (row + 0.55) * self.ch
+
+ # ================================================================ the form
+ def form(self, white='#f6f4eb', green='#d2e7cc', desk='#3b3834', band=3, first_green=False, holes=True):
+ """continuous greenbar form at ss x: bands every `band` lines from the page break, tractor strips,
+ feed holes, micro-perforations, the cross perforation and the fanfold crease at `top`"""
+ ss, W, H = self.ss, self.W * self.ss, self.H * self.ss
+ y = (np.arange(H, dtype=np.float32) + 0.5) / ss
+ x = (np.arange(W, dtype=np.float32) + 0.5) / ss
+ strip = self.ppi * 0.5
+ L0, L1 = self.px0 + strip, self.px1 - strip # the perforations
+ p = (y - self.top) / self.ch / band # band coordinate
+ k = np.floor(p)
+ g = ((k.astype(int) % 2) == (0 if first_green else 1)).astype(np.float32)
+ fr = p - k # band edges soft over ~1.5 px
+ d_edge = np.minimum(fr, 1 - fr) * self.ch * band
+ soft = smoothstep(-0.7, 0.7, d_edge)
+ gband = g * soft + (1 - g) * (1 - soft)
+ inside = ((x > L0 + 1.5) & (x < L1 - 1.5)).astype(np.float32)
+ gmask = gband[:, None] * inside[None, :]
+ # flexo green: a little mottled
+ mott = noise2d(H // 4, W // 4, 18, 3, self._seed())
+ mott = np.asarray(Image.fromarray(mott).resize((W, H), Image.BILINEAR), np.float32)
+ wc, gc = _c(white), _c(green)
+ dens = gmask * (0.9 + 0.14 * mott)
+ del gmask, mott
+ img = np.empty((H, W, 3), np.float32) # built channel by channel (memory)
+ for k_ in range(3):
+ img[..., k_] = wc[k_] + (gc[k_] - wc[k_]) * dens
+ del dens
+ # paper formation (cloudy) and tooth (fine)
+ cloud = noise2d(H // 8, W // 8, 40, 4, self._seed())
+ cloud = np.asarray(Image.fromarray(cloud).resize((W, H), Image.BILINEAR), np.float32)
+ tooth = self.rng.random((H, W), dtype=np.float32)
+ tooth = gauss(tooth, 0.7 * ss / 2)
+ tooth = (tooth - tooth.mean()) / (tooth.std() + 1e-6)
+ self._tooth = np.clip(0.5 + 0.18 * tooth, 0, 1)
+ fac = 0.975 + 0.035 * cloud + 0.012 * tooth
+ del cloud, tooth
+ for k_ in range(3): img[..., k_] *= fac
+ del fac
+ # short fibres
+ f = np.zeros((H, W), np.float32)
+ for _ in range(int(W * H / 9000)):
+ x0, y0 = self.rng.uniform(0, W), self.rng.uniform(0, H)
+ a = self.rng.uniform(0, np.pi); L = self.rng.uniform(4, 16) * ss
+ n = int(L)
+ xs = (x0 + np.cos(a) * np.arange(n)).astype(int); ys = (y0 + np.sin(a) * np.arange(n) + np.sin(np.arange(n) / 5) * 1.5).astype(int)
+ ok = (xs >= 0) & (xs < W) & (ys >= 0) & (ys < H)
+ f[ys[ok], xs[ok]] = self.rng.uniform(0.3, 1)
+ f = 1 - 0.05 * gauss(f, 0.6 * ss / 2)
+ for k_ in range(3): img[..., k_] *= f
+ del f
+ # micro-perforations: tiny slits with a torn, lighter lip
+ def perf_v(x0):
+ xi = int(round(x0 * ss))
+ per = 3.4 * ss
+ on = ((np.arange(H) % per) < per * 0.62).astype(np.float32)
+ on *= (self.rng.random(H) > 0.04)
+ for dx, k_ in ((0, 0.16), (-1, 0.06), (1, 0.06)):
+ img[:, xi + dx] *= (1 - k_ * on)[:, None]
+ img[:, xi + ss + 1] = np.minimum(1, img[:, xi + ss + 1] * (1 + 0.03 * on)[:, None])
+
+ def perf_h(y0):
+ yi = int(round(y0 * ss))
+ if not (2 <= yi < H - 3): return
+ per = 3.4 * ss
+ on = ((np.arange(W) % per) < per * 0.62).astype(np.float32)
+ on *= (self.rng.random(W) > 0.04)
+ for dy, k_ in ((0, 0.3), (-1, 0.12), (1, 0.1), (2, 0.04)): # slits, torn lip
+ img[yi + dy, :] *= (1 - k_ * on)[:, None]
+ img[yi - 2, :] *= (1 + 0.04 * on)[:, None]
+ if holes:
+ perf_v(L0); perf_v(L1)
+ # page breaks (cross perforation + fanfold crease: shade on one side, sheen on the other)
+ page = self.page_rows * self.ch
+ for yb in np.arange(self.top - page * 2, self.H + page, page):
+ if -40 < yb < self.H + 40:
+ perf_h(yb)
+ dy = (y - yb)
+ crease = -0.06 * np.exp(-np.maximum(-dy, 0) / 14) * (dy < 0) + 0.03 * np.exp(-np.maximum(dy, 0) / 9) * (dy >= 0)
+ crease += -0.04 * np.exp(-(dy / 1.5) ** 2)
+ img *= (1 + crease)[:, None, None]
+ # feed holes
+ if holes:
+ dc = _c(desk)
+ pitch = self.ppi * 0.5
+ rad = self.ppi * 5 / 64
+ ys0 = self.top + pitch / 2 - pitch * np.ceil((self.top + pitch) / pitch)
+ centres = [(cx, cy) for cx in (self.px0 + strip / 2, self.px1 - strip / 2)
+ for cy in np.arange(ys0, self.H + pitch, pitch)]
+ torn = set(self.rng.choice(len(centres), 2, replace=False).tolist())
+ R = int((rad + 8) * ss)
+ yy, xx = np.mgrid[-R:R + 1, -R:R + 1].astype(np.float32) / ss
+ for i, (cx, cy) in enumerate(centres):
+ ang = np.arctan2(yy, xx)
+ wob = 1 + 0.025 * np.sin(ang * 7 + i) + 0.015 * np.sin(ang * 13 + 2 * i)
+ ry = rad * (1.22 if i in torn else 1.0)
+ dd = np.sqrt((xx / rad) ** 2 + (np.where(yy > 0, yy / ry, yy / rad)) ** 2) / wob
+ hole = smoothstep(1.0 + 0.6 / rad, 1.0 - 0.6 / rad, dd)
+ # desk seen through the hole: the hole's rim shadows the upper-left part of it
+ lit = smoothstep(1.0 + 0.9 / rad, 1.0 - 1.4 / rad,
+ np.sqrt(((xx - 2.6) / rad) ** 2 + ((yy - 3.2) / ry) ** 2))
+ col = dc[None, None, :] * (0.55 + 0.6 * lit[..., None])
+ rim = np.exp(-((dd - 1.0) * rad / 1.1) ** 2) * (dd > 1)
+ x0, y0 = int(round(cx * ss)) - R, int(round(cy * ss)) - R
+ xa, ya = max(x0, 0), max(y0, 0)
+ xb, yb = min(x0 + 2 * R + 1, W), min(y0 + 2 * R + 1, H)
+ if xa >= xb or ya >= yb: continue
+ sl = (slice(ya, yb), slice(xa, xb))
+ ls = (slice(ya - y0, yb - y0), slice(xa - x0, xb - x0))
+ reg = img[sl]
+ reg *= (1 - 0.07 * rim[ls])[..., None]
+ img[sl] = reg * (1 - hole[ls][..., None]) + col[ls] * hole[ls][..., None]
+ # the desk beside the form, with the paper's soft shadow (light from the upper left)
+ if self.px0 > 0.5:
+ pm = smoothstep(self.px0 - 0.6, self.px0 + 0.6, x) * (1 - smoothstep(self.px1 - 0.6, self.px1 + 0.6, x))
+ dist = np.maximum(self.px0 - x, x - self.px1)
+ sh = 1 - np.where(x > self.px1, 0.55 * np.exp(-np.maximum(dist, 0) / 9),
+ 0.3 * np.exp(-np.maximum(dist, 0) / 4))
+ grain = noise2d(H // 4, W // 4, 30, 3, self._seed())
+ grain = np.asarray(Image.fromarray(grain).resize((W, H), Image.BILINEAR), np.float32)
+ dc = _c(desk)
+ for k_ in range(3):
+ d_ = dc[k_] * (0.9 + 0.16 * grain) * sh[None, :]
+ img[..., k_] = img[..., k_] * pm[None, :] + d_ * (1 - pm[None, :])
+ del grain
+ edge = np.exp(-((x - self.px0) / 0.8) ** 2) + np.exp(-((x - self.px1) / 0.8) ** 2)
+ img *= (1 - 0.12 * edge)[None, :, None]
+ np.clip(img, 0, 1, out=img)
+ self.paper_rgb = img
+ return self
+
+ # ================================================================ roles and masks
+ def role(self, name, ramp, edge='outer', outline='straight', dither=0.5, noise=0.02, group=None, inner_max=1.0):
+ """a glyph vocabulary. ramp: light -> dark list of strings ('' blank, '#@' = '#' overstruck with '@').
+ edge: 'outer' outline against other roles, 'all' also between pieces of the same role, None no outline.
+ outline: 'straight' (| for upright sides), 'round' (( and ) for upright sides, for puffs and bellies) or a
+ dict overriding any of v h low dot tick up down x plus left right top.
+ group: roles in the same group (a body and the paint on it) are not outlined against each other.
+ inner_max: with edge='all', outlines between pieces only where the upper piece is lighter than this tone
+ (lit tops of puffs get a rim; inside the shadows the tone alone carries the form)"""
+ if name not in self.roles:
+ self.roles[name] = dict(id=len(self._role_by_id)); self._role_by_id.append(name)
+ self.roles[name].update(ramp=list(ramp), edge=edge, outline=_style(outline), dither=dither, noise=noise,
+ group=group or name, inner_max=inner_max)
+ return name
+
+ def line_set(self, glyphs):
+ """register how a stroke becomes characters: a style name / dict, or one character that is forced"""
+ st = glyphs if (isinstance(glyphs, str) and len(glyphs) == 1) else _style(glyphs)
+ if st in self.line_sets: return self.line_sets.index(st)
+ self.line_sets.append(st); return len(self.line_sets) - 1
+
+ def _aa(self, d):
+ """signed distance in sub-pixels (positive inside) -> coverage"""
+ return np.clip(d + 0.5, 0, 1)
+
+ def ellipse(self, c, r, rx, ry, rot=0.0):
+ """mask of an ellipse; c, r centre in cells, rx in columns, ry in rows, rot radians"""
+ u, v = self.X - c, self.Y - r
+ if rot:
+ # rotate in physical space (columns are narrower than rows)
+ k = self.ch / self.cw
+ uu, vv = u, v * k
+ cs, sn = np.cos(rot), np.sin(rot)
+ u, v = (uu * cs + vv * sn), (-uu * sn + vv * cs) / k
+ d = np.sqrt((u / rx) ** 2 + (v / ry) ** 2)
+ return self._aa((1 - d) * min(rx * self.sx, ry * self.sy))
+
+ def circle(self, c, r, radius):
+ """round in the printed picture: radius in columns, the row radius is corrected for the cell shape"""
+ return self.ellipse(c, r, radius, radius * self.cw / self.ch)
+
+ def poly(self, pts):
+ P = [(float(c) * self.sx, float(r) * self.sy) for c, r in pts]
+ return polygon_mask(self.rows * self.sy, self.cols * self.sx, P, ss=3)
+
+ def shape(self, pts, per=10):
+ """smooth closed outline through control points (cells)"""
+ P = np.asarray(pts, np.float32)
+ P = np.vstack([P, P[:3]])
+ S = spline(P, per)[per:-per * 1]
+ return self.poly(S)
+
+ def rect(self, c0, r0, c1, r1):
+ return self.poly([(c0, r0), (c1, r0), (c1, r1), (c0, r1)])
+
+ def blob(self, c, r, rx, ry, rough=0.1, seed=None):
+ pts = blob_pts(c, r, rx, ry, rough, 120, self._seed() if seed is None else seed)
+ return self.poly(pts)
+
+ # ================================================================ tones (light on things)
+ def sphere_tone(self, c, r, radius, light=(-0.55, -0.7, 0.45), amb=0.12, soft=0.0):
+ """ink wanted on a sphere seen in the picture (0 lit .. 1 dark), radius in columns"""
+ L = np.asarray(light, np.float32); L /= np.linalg.norm(L)
+ u = (self.X - c) / radius
+ v = (self.Y - r) * (self.ch / self.cw) / radius
+ q = np.clip(1 - u * u - v * v, 0, 1)
+ n = np.stack([u, v, np.sqrt(q)])
+ dif = np.clip((n * L[:, None, None]).sum(0), 0, 1)
+ if soft: dif = dif * (1 - soft) + soft * (0.5 + 0.5 * (n * L[:, None, None]).sum(0))
+ return np.clip(1 - (amb + (1 - amb) * dif), 0, 1)
+
+ def cylinder_tone(self, c0, c1, light=(-0.8, 0.0, 0.6), amb=0.1, spec=0.0):
+ """ink wanted across a vertical cylinder between columns c0 and c1"""
+ L = np.asarray(light, np.float32); L /= np.linalg.norm(L)
+ u = np.clip((self.X - (c0 + c1) / 2) / ((c1 - c0) / 2), -1, 1)
+ nz = np.sqrt(np.clip(1 - u * u, 0, 1))
+ dif = np.clip(u * L[0] + nz * L[2], 0, 1)
+ t = 1 - (amb + (1 - amb) * dif)
+ if spec: t -= spec * np.clip(u * L[0] + nz * L[2], 0, 1) ** 24
+ return np.clip(t, 0, 1)
+
+ def ramp_tone(self, p0, p1, t0, t1):
+ """linear tone from cell point p0 (tone t0) to p1 (tone t1)"""
+ d = np.array(p1, np.float32) - np.array(p0, np.float32)
+ s = ((self.X - p0[0]) * d[0] + (self.Y - p0[1]) * d[1]) / (d @ d + 1e-6)
+ return t0 + (t1 - t0) * np.clip(s, 0, 1)
+
+ # ================================================================ painting the role map
+ def fill(self, mask, role, tone=0.5):
+ """paint a region into the role map (covers whatever was there, strokes included)"""
+ m = mask > 0.5
+ if not m.any(): return m
+ self._n += 1
+ rid = self.roles[role]['id']
+ self.inst[m] = self._n
+ self.rmap[m] = rid
+ self.tone[m] = tone[m] if isinstance(tone, np.ndarray) else tone
+ self.line[m] = 0
+ return m
+
+ def erase(self, mask):
+ """back to bare paper (knock-outs)"""
+ m = mask > 0.5
+ self._n += 1
+ self.inst[m] = self._n; self.rmap[m] = 0; self.tone[m] = 0; self.line[m] = 0
+ return m
+
+ def stroke(self, pts, width=1.15, glyphs=None, smooth=False, closed=False):
+ """a drawn line in cell coordinates; its cells get characters by direction and position
+ (glyphs: None / 'straight' / 'round' / dict, or one character to force, e.g. '=' for a platform)"""
+ P = np.asarray(pts, np.float32)
+ if closed: P = np.vstack([P, P[:1]])
+ if smooth and len(P) > 2: P = spline(P, 12)
+ sid = self.line_set(glyphs)
+ Pp = P * np.array([self.sx, self.sy], np.float32)
+ hw = width / 2
+ SY, SX = self.line.shape
+ for a, b in zip(Pp[:-1], Pp[1:]):
+ x0, x1 = int(max(min(a[0], b[0]) - width - 2, 0)), int(min(max(a[0], b[0]) + width + 3, SX))
+ y0, y1 = int(max(min(a[1], b[1]) - width - 2, 0)), int(min(max(a[1], b[1]) + width + 3, SY))
+ if x0 >= x1 or y0 >= y1: continue
+ yy, xx = np.mgrid[y0:y1, x0:x1].astype(np.float32) + 0.5
+ d = b - a; L2 = float(d @ d) + 1e-6
+ t = np.clip(((xx - a[0]) * d[0] + (yy - a[1]) * d[1]) / L2, 0, 1)
+ dist = np.hypot(xx - a[0] - t * d[0], yy - a[1] - t * d[1])
+ cov = np.clip(hw + 0.5 - dist, 0, 1)
+ sl = self.line[y0:y1, x0:x1]
+ np.maximum(sl, cov, out=sl)
+ self.lset[y0:y1, x0:x1][cov > 0.3] = sid
+ self.grid = None
+
+ def text(self, s, col, row, strike=1, opaque=False):
+ """literal characters from (col, row); strike=2 prints each twice (bold by overstrike);
+ opaque=True makes spaces blank out the picture under them"""
+ for i, ch in enumerate(s):
+ if ch == ' ' and not opaque: continue
+ cc = col + i
+ if 0 <= cc < self.cols and 0 <= row < self.rows:
+ self.fixed[(row, cc)] = '' if ch == ' ' else ch * strike
+ self.grid = None
+
+ def text_v(self, s, col, row, strike=1):
+ """literal characters downwards from (col, row), one per line (lettering painted on an upright body)"""
+ for i, ch in enumerate(s):
+ if ch != ' ' and 0 <= row + i < self.rows and 0 <= col < self.cols:
+ self.fixed[(row + i, col)] = ch * strike
+ self.grid = None
+
+ def plot(self, col, row, w, h, xlim, ylim, series, xticks, yticks, ylab_w=5, xfmt='{:g}', yfmt='{:g}'):
+ """a printer plot: y axis of 'I' with '+' ticks and labels, x axis of '-' with '+' ticks, points as glyphs.
+ series: [(xs, ys, glyph), ...] later series overwrite earlier ones. Returns cell(x, y) -> (col, row)"""
+ ax = col + ylab_w + 1 # axis column
+ x0 = ax + 1
+ def cell(xv, yv):
+ cc = x0 + (xv - xlim[0]) / (xlim[1] - xlim[0]) * (w - 1)
+ rr = row + (ylim[1] - yv) / (ylim[1] - ylim[0]) * (h - 1)
+ return cc, rr
+ for r in range(row, row + h): self.text('I', ax, r)
+ for yv in yticks:
+ _, rr = cell(xlim[0], yv); rr = int(round(rr))
+ self.text('+', ax, rr)
+ lab = yfmt.format(yv)
+ self.text(lab.rjust(ylab_w), col, rr)
+ xr = row + h
+ self.text('+' + '-' * w, ax, xr)
+ for xv in xticks:
+ cc, _ = cell(xv, ylim[0]); cc = int(round(cc))
+ self.text('+', cc, xr)
+ lab = xfmt.format(xv)
+ self.text(lab, cc - len(lab) // 2, xr + 1)
+ for xs, ys, g in series:
+ for xv, yv in zip(xs, ys):
+ cc, rr = cell(xv, yv)
+ cc, rr = int(round(cc)), int(round(rr))
+ if x0 <= cc < x0 + w and row <= rr < row + h:
+ self.fixed[(rr, cc)] = g
+ self.grid = None
+ return cell
+
+ def billow(self, puffs, role, light=(-0.55, -0.75, 0.4), amb=0.12, shadow=0.35, glow=None, lift=None):
+ """a cloud of round puffs [(col, row, radius), ...] painted back to front. Each puff is lit as a sphere,
+ casts a soft contact shadow on the puffs behind it, and `glow=(col, row, radius_cols, strength)` lights the
+ cloud from inside (a flame); `lift` is an optional extra tone field added everywhere. Returns the mask."""
+ union = np.zeros(self.line.shape, np.float32)
+ first = self._n + 1
+ L = np.asarray(light, np.float32); L /= np.linalg.norm(L)
+ sh = np.zeros_like(union)
+ for (c, r, R) in puffs:
+ m = self.circle(c, r, R)
+ t = self.sphere_tone(c, r, R, light, amb)
+ mm = self.fill(m, role, t)
+ # this puff shades what is behind it on the side away from the light
+ ring = np.clip(self.circle(c - L[0] * R * 0.35, r - L[1] * R * 0.35 * self.cw / self.ch, R * 1.08) - m, 0, 1)
+ sh = np.maximum(sh * (1 - m), ring)
+ union = np.maximum(union, m)
+ own = (self.inst >= first) & (union > 0.5)
+ sh = blur(sh, 2.0)
+ tone = self.tone.copy()
+ tone[own] = np.clip(tone[own] + shadow * sh[own], 0, 1)
+ if glow is not None:
+ gc, gr, gR, gs = glow
+ d2 = ((self.X - gc) / gR) ** 2 + ((self.Y - gr) * self.ch / self.cw / gR) ** 2
+ tone[own] = np.clip(tone[own] - gs * np.exp(-d2[own] * 1.5), 0, 1)
+ if lift is not None:
+ tone[own] = np.clip(tone[own] + lift[own], 0, 1)
+ self.tone = tone
+ return union
+
+ # ================================================================ choosing the glyphs
+ def _stamp(self, ch):
+ """the type slug for one character at ss x: (mask float32 Hs x Ws), pad 4 px"""
+ if ch in self._stamps: return self._stamps[ch]
+ ss = self.ss
+ Ws, Hs = int(np.ceil(self.cw * ss)) + 8, int(np.ceil(self.ch * ss)) + 8
+ im = Image.new('L', (Ws, Hs), 0)
+ ImageDraw.Draw(im).text((Ws / 2, self.base), ch, font=self.font, fill=255, anchor='ms')
+ m = np.asarray(im, np.float32) / 255
+ if self.rng.random() < 0.3 and m.sum() > 20: # a worn slug: the same nick every time
+ ys, xs = np.nonzero(m > 0.6)
+ i = self.rng.integers(len(ys))
+ yy, xx = np.mgrid[0:Hs, 0:Ws]
+ rr = self.rng.uniform(1.2, 2.2) * ss / 2
+ m = m * (1 - 0.8 * np.exp(-((yy - ys[i]) ** 2 + (xx - xs[i]) ** 2) / (2 * rr * rr)))
+ self._stamps[ch] = m
+ self.drum[ch] = self.rng.normal(0, 0.42)
+ return m
+
+ def _proto(self, ch):
+ """the character's shape on the role-map grid (sy x sx), blurred, unit length"""
+ if ch in self._protos: return self._protos[ch]
+ m = self._stamp(ch)
+ ss = self.ss
+ crop = m[4:4 + int(round(self.ch * ss)), 4:4 + int(round(self.cw * ss))]
+ p = np.asarray(Image.fromarray(crop).resize((self.sx, self.sy), Image.BOX), np.float32)
+ p = gauss(p, 0.7)
+ self._protos[ch] = p
+ return p
+
+ def _pick(self, P, st, inside=None):
+ """the character for a line pattern P (sy x sx): by its direction (measured in real pixels, cells are
+ tall) and where it sits in the cell. Returns (glyph, family) with family in h / diag / v / x"""
+ sy, sx = P.shape
+ w = P.ravel().astype(np.float64); W = w.sum() + 1e-9
+ X = np.tile((np.arange(sx) + 0.5) / sx * self.cw, sy)
+ Y = np.repeat((np.arange(sy) + 0.5) / sy * self.ch, sx)
+ mx, my = (w * X).sum() / W, (w * Y).sum() / W
+ dx, dy = X - mx, Y - my
+ Sxx, Syy, Sxy = (w * dx * dx).sum() / W, (w * dy * dy).sum() / W, (w * dx * dy).sum() / W
+ th = 0.5 * np.arctan2(2 * Sxy, Sxx - Syy)
+ coh = 2 * np.sqrt(((Sxx - Syy) / 2) ** 2 + Sxy ** 2) / (Sxx + Syy + 1e-9)
+ a = np.degrees(abs(th))
+ cy = my / self.ch
+ Xn, Yn = X / self.cw, Y / self.ch # crossing test in cell units
+ mxn, myn = (w * Xn).sum() / W, (w * Yn).sum() / W
+ a_, b_, c_ = (w * (Xn - mxn) ** 2).sum() / W, (w * (Yn - myn) ** 2).sum() / W, (w * (Xn - mxn) * (Yn - myn)).sum() / W
+ cohn = 2 * np.sqrt(((a_ - b_) / 2) ** 2 + c_ ** 2) / (a_ + b_ + 1e-9)
+ if min(coh, cohn) < 0.3 and W > 1.45 * sy: # two strokes crossing
+ pr = {g: self._proto(g).ravel() for g in '/\\|-'}
+ pn = w / (np.linalg.norm(w) + 1e-9)
+ k = {g: float(pn @ (v / (np.linalg.norm(v) + 1e-9))) for g, v in pr.items()}
+ return (st['x'] if k['/'] + k['\\'] > k['|'] + k['-'] else st['plus']), 'x'
+ if a < 14:
+ return (st['h'] if cy < 0.62 else st['low']), 'h'
+ if a < 40:
+ return (st['tick'] if cy < 0.33 else st['h'] if cy < 0.6 else st['dot'] if cy < 0.8 else st['low']), 'h'
+ if a < 72:
+ return (st['up'] if th < 0 else st['down']), 'diag'
+ if inside is not None and abs(inside[0]) > 0.05:
+ return (st['left'] if inside[0] > 0 else st['right']), 'v'
+ return st['v'], 'v'
+
+ @staticmethod
+ def _thin(fam, grid, kind):
+ """non-maximum suppression: an upright or slanted outline keeps one cell per row, a flat one one per column"""
+ drop = []
+ for (r, c), (f, iid, e) in fam.items():
+ if f in ('v', 'diag'): nb = [(r, c - 1), (r, c + 1)]
+ elif f == 'h': nb = [(r - 1, c), (r + 1, c)]
+ else: continue
+ for q in nb:
+ o = fam.get(q)
+ if (o and o[0] == f and o[1] == iid and (f != 'diag' or grid[q[0]][q[1]] == grid[r][c])
+ and (o[2] > e or (o[2] == e and q < (r, c)))):
+ drop.append((r, c)); break
+ for (r, c) in drop:
+ grid[r][c] = ''; kind[r, c] = 0
+
+ def compose(self):
+ """decide every cell's characters from the role map; returns the grid (list of rows of strings)"""
+ R, C, sy, sx = self.rows, self.cols, self.sy, self.sx
+ blk = lambda a: a.reshape(R, sy, C, sx).transpose(0, 2, 1, 3)
+ rm = blk(self.rmap)
+ nroles = len(self._role_by_id)
+ cnt = np.stack([(rm == k).sum((2, 3)) for k in range(nroles)])
+ dom = cnt.argmax(0)
+ tone_b = blk(self.tone)
+ own = (rm == dom[..., None, None])
+ ctone = (tone_b * own).sum((2, 3)) / np.maximum(own.sum((2, 3)), 1)
+ # strokes
+ Lb = blk(self.line)
+ lenergy = Lb.sum((2, 3)) / sy
+ lsb = blk(self.lset)
+ # silhouette edges: boundary sub-pixels on the side of the upper (later) region
+ inst, rmap = self.inst, self.rmap
+ ids_out = [self.roles[n]['id'] for n in self._role_by_id if self.roles[n]['edge'] in ('outer', 'all')]
+ ids_all = [self.roles[n]['id'] for n in self._role_by_id if self.roles[n]['edge'] == 'all']
+ mine = np.isin(rmap, ids_out); all_ = np.isin(rmap, ids_all)
+ gnames = sorted(set(self.roles[n]['group'] for n in self._role_by_id))
+ gid = np.array([gnames.index(self.roles[n]['group']) for n in self._role_by_id], np.int16)
+ gmap = gid[rmap]
+ imax = np.array([self.roles[n]['inner_max'] for n in self._role_by_id], np.float32)[rmap]
+ lit_enough = self.tone < imax
+ B = np.zeros(inst.shape, np.float32)
+ Bown = np.zeros(inst.shape, np.int16)
+ Binst = np.zeros(inst.shape, np.int32)
+ for dy, dx in ((0, 1), (1, 0), (0, -1), (-1, 0)):
+ o_inst = shift(inst, dx, dy); o_role = shift(rmap, dx, dy); o_g = shift(gmap, dx, dy)
+ valid = np.ones(inst.shape, bool)
+ if dx == 1: valid[:, 0] = False
+ if dx == -1: valid[:, -1] = False
+ if dy == 1: valid[0, :] = False
+ if dy == -1: valid[-1, :] = False
+ diff_role = rmap != o_role
+ diff_g = gmap != o_g
+ e = (inst > o_inst) & valid & (rmap != 0) & ((mine & diff_g) | (all_ & ~diff_role & lit_enough))
+ B[e] = 1; Bown[e] = rmap[e]; Binst[e] = inst[e]
+ Bb = blk(B)
+ benergy = Bb.sum((2, 3)) / sy
+ Bo, Bi, Ib = blk(Bown), blk(Binst), blk(inst)
+ grid = [[''] * C for _ in range(R)]
+ kind = np.zeros((R, C), np.int8) # 0 open, 1 fixed, 2 line, 3 edge, 4 fill
+ for (r, c) in self.fixed: kind[r, c] = 1
+ # ---- line cells; a slanted or upright line that smears over two neighbouring cells keeps the stronger one
+ fam = {}
+ for (r, c) in np.argwhere((lenergy > 0.5) & (kind == 0)):
+ ids, ns = np.unique(lsb[r, c][Lb[r, c] > 0.3], return_counts=True)
+ st = self.line_sets[int(ids[ns.argmax()]) if len(ids) else 0]
+ if isinstance(st, str):
+ grid[r][c] = st; fam[(r, c)] = ('forced', 0, lenergy[r, c])
+ else:
+ g, f = self._pick(Lb[r, c], st)
+ grid[r][c] = g; fam[(r, c)] = (f, 0, lenergy[r, c])
+ kind[r, c] = 2
+ self._thin(fam, grid, kind)
+ # ---- edge cells, top to bottom; a region's flat top edge high in its cell moves up as '_'
+ fam = {}
+ for (r, c) in np.argwhere((benergy > 0.32) & (kind == 0)):
+ if kind[r, c]: continue
+ ids, ns = np.unique(Bo[r, c][Bb[r, c] > 0], return_counts=True)
+ rid = int(ids[ns.argmax()])
+ iid = np.bincount(Bi[r, c][Bb[r, c] > 0].ravel()).argmax()
+ P = Bb[r, c] * (Bi[r, c] == iid)
+ if P.sum() < 0.3 * sy: continue
+ st = self.roles[self._role_by_id[rid]]['outline']
+ yy, xx = np.mgrid[0:sy, 0:sx]
+ # which side the region lies on: its pixels in this cell and the two beside it
+ c0, c1 = max(c - 1, 0), min(c + 2, C)
+ inn = (inst[r * sy:(r + 1) * sy, c0 * sx:c1 * sx] == iid)
+ xw = np.mgrid[0:sy, 0:(c1 - c0) * sx][1] - (c - c0) * sx
+ inside = None
+ if inn.sum() > P.sum():
+ inside = (((xw * inn).sum() / inn.sum() - (xx * P).sum() / P.sum()) / sx,
+ ((np.mgrid[0:sy, 0:(c1 - c0) * sx][0] * inn).sum() / inn.sum() - (yy * P).sum() / P.sum()) / sy)
+ g, f = self._pick(P, st, inside)
+ cy = (yy * P).sum() / P.sum() / sy
+ flat = f == 'h' and g in (st['h'], st['low'])
+ if flat and st['top'] and inside is not None and inside[1] > 0 and cy < 0.42:
+ if r > 0 and kind[r - 1, c] == 0 and dom[r - 1, c] != rid:
+ grid[r - 1][c] = st['top']; kind[r - 1, c] = 3
+ continue # this cell is filled normally
+ if flat and inside is not None and inside[1] < 0:
+ g = st['low'] if cy > 0.45 else st['h']
+ grid[r][c] = g; kind[r, c] = 3; fam[(r, c)] = (f, iid, P.sum())
+ self._thin(fam, grid, kind)
+ # ---- fill cells: ramp with error diffusion inside each role
+ err = np.zeros((R, C + 2), np.float32)
+ noise = self.rng.normal(0, 1, (R, C)).astype(np.float32)
+ for r in range(R):
+ for c in range(C):
+ if kind[r, c]: continue
+ rid = int(dom[r, c])
+ if rid == 0 or cnt[rid, r, c] < sy * sx * 0.45: continue
+ ro = self.roles[self._role_by_id[rid]]
+ ramp = ro['ramp']; n = len(ramp) - 1
+ v = ctone[r, c] * n + ro['noise'] * n * noise[r, c] + err[r, c + 1] * ro['dither']
+ q = int(np.clip(np.round(v), 0, n))
+ e = (v - q) if 0 < v < n else 0.0
+ e = float(np.clip(e, -0.6, 0.6))
+ if c + 1 < C and dom[r, c + 1] == rid: err[r, c + 2] += e * 7 / 16
+ if r + 1 < R:
+ if c > 0 and dom[r + 1, c - 1] == rid: err[r + 1, c] += e * 3 / 16
+ if dom[r + 1, c] == rid: err[r + 1, c + 1] += e * 5 / 16
+ if c + 1 < C and dom[r + 1, c + 1] == rid: err[r + 1, c + 2] += e * 1 / 16
+ grid[r][c] = ramp[q]; kind[r, c] = 4
+ for (r, c), s_ in self.fixed.items():
+ if 0 <= r < R and 0 <= c < C: grid[r][c] = s_
+ self.grid = grid
+ self.kind = kind
+ return grid
+
+ def listing(self, path=None):
+ """the page as plain text (first strike of every cell), for a terminal or a .txt"""
+ if self.grid is None: self.compose()
+ lines = [''.join((s[:1] or ' ') for s in row).rstrip() for row in self.grid]
+ txt = '\n'.join(lines) + '\n'
+ if path: open(path, 'w').write(txt)
+ return txt
+
+ # ================================================================ the printer
+ def _make_weave(self):
+ """ribbon: a fabric weave whose threads carry uneven ink, plus clumps; a 256 px tile at ss, sampled at a
+ random offset for every impression (the ribbon has moved on between strikes)"""
+ n = 256
+ yy, xx = np.mgrid[0:n, 0:n].astype(np.float32)
+ p = 2.2 * self.ss # ~2.2 px thread pitch at 1x
+ wv = 0.5 + 0.22 * np.sin(2 * np.pi * (xx + yy) / p) * np.sin(2 * np.pi * (xx - yy) / (p * 1.09))
+ clump = self.rng.random((n, n)).astype(np.float32)
+ clump = gauss(clump, 0.9 * self.ss / 2)
+ clump = (clump - clump.mean()) / (clump.std() + 1e-6)
+ wv += 0.16 * clump
+ return np.clip(wv, 0, 1).astype(np.float32)
+
+ def _soft(self, ch):
+ """the slug's ink footprint: the glyph pushed a little into the paper (spread)"""
+ key = ('soft', ch)
+ if key not in self._stamps:
+ self._stamps[key] = gauss(self._stamp(ch), 0.95 * self.ss / 2)
+ return self._stamps[key]
+
+ def _strike(self, ch, r, c, p, dxp, dyp, ribbon):
+ m = self._soft(ch)
+ ss = self.ss
+ Hs, Ws = m.shape
+ x = self.xl + c * self.cw + self.h_dx[c] + dxp + self.rng.normal(0, 0.12)
+ y = (self.top + r * self.ch + self.feed[r] + self.drum[ch] + self.h_dy[c] + dyp + self.rng.normal(0, 0.15)
+ + (c - self.cols / 2) * self.cw * self.skew)
+ X0, Y0 = int(round(x * ss)) - 4, int(round(y * ss)) - 4
+ xa, ya = max(X0, 0), max(Y0, 0)
+ xb, yb = min(X0 + Ws, self.W * ss), min(Y0 + Hs, self.H * ss)
+ if xa >= xb or ya >= yb: return
+ mm = m[ya - Y0:yb - Y0, xa - X0:xb - X0]
+ e = float(np.clip(self.h_force[c] * self.rng.normal(1, 0.06) * ribbon, 0.25, 1.2))
+ if r in self.low_rows: # ribbon rode low: tops starve
+ e_v = e * (0.55 + 0.45 * smoothstep(0.25, 0.62, (np.arange(Hs) / Hs)))[ya - Y0:yb - Y0, None]
+ else:
+ e_v = e
+ oy, ox = self.rng.integers(0, 256 - Hs), self.rng.integers(0, 256 - Ws)
+ wv = self._weave[oy:oy + (yb - ya), ox:ox + (xb - xa)]
+ tooth = self._tooth[ya:yb, xa:xb] if self._tooth is not None else 0.5
+ tex = 0.55 * wv + 0.45 * tooth - 0.5 # about -0.2 .. 0.2
+ # ink reaches the paper where the slug presses hard enough through the ribbon: strong strikes fill the
+ # whole footprint, weak ones break up on the weave and the paper tooth instead of turning grey
+ v = mm * (1.05 + 0.25 * e_v) + 1.1 * tex - 0.32 * (1 - e_v)
+ cov = smoothstep(0.42, 0.66, v)
+ dens = cov * (0.58 + 0.36 * np.minimum(e_v, 1.05)) * (0.9 + 0.9 * tex)
+ sl = self.inkbuf[ya:yb, xa:xb]
+ sl[...] = 1 - (1 - sl) * (1 - np.clip(dens, 0, 0.97))
+ self.emb[ya:yb, xa:xb] += mm * e
+
+ def print_rows(self, r0=0, r1=None):
+ """impact-print rows r0..r1-1 (all overstrike passes of each line before the paper advances)"""
+ if self.grid is None: self.compose()
+ r1 = self.rows if r1 is None else r1
+ for r in range(r0, min(r1, self.rows)):
+ if r in self.printed: continue
+ row = self.grid[r]
+ npass = max((len(s) for s in row), default=0)
+ self._jobpos += 1
+ job = self._jobpos / max(self.rows, 1)
+ for p in range(npass):
+ dxp = 0.0 if p == 0 else self.rng.normal(0, 0.3)
+ dyp = 0.0 if p == 0 else self.rng.normal(0, 0.42)
+ for c, s in enumerate(row):
+ if len(s) > p and s[p] != ' ':
+ ribbon = (1 - self.fade * job) * self.wear[c] * self.line_ink[r]
+ self._strike(s[p], r, c, p, dxp, dyp, ribbon)
+ self.printed.add(r)
+
+ # ================================================================ ballpoint
+ def _pen_layer(self, colour):
+ key = tuple(np.round(_c(colour), 4))
+ if key not in self.pens:
+ self.pens[key] = np.zeros((self.H * self.ss, self.W * self.ss), np.float32)
+ return self.pens[key]
+
+ def pen(self, pts, colour='#b8322a', width=1.5, smooth=True, density=0.85, skip=0.1):
+ """a ballpoint line through pixel points (1x): starts and ends blot a little, fast parts run pale,
+ the ball skips on the paper tooth"""
+ P = np.asarray(pts, np.float32)
+ if smooth and len(P) > 2: P = spline(P, 10)
+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1)
+ Ltot = float(seg.sum())
+ if Ltot < 1: return
+ s = np.concatenate([[0], np.cumsum(seg)])
+ n = max(8, int(Ltot / 1.2))
+ ss_ = np.linspace(0, Ltot, n)
+ px, py = np.interp(ss_, s, P[:, 0]), np.interp(ss_, s, P[:, 1])
+ t = ss_ / Ltot
+ S = 2 * self.ss # draw at 2 x the layer, then reduce
+ x0, y0 = int(px.min() - 6), int(py.min() - 6)
+ x1, y1 = int(px.max() + 7), int(py.max() + 7)
+ w, h = (x1 - x0) * S, (y1 - y0) * S
+ im = Image.new('L', (w, h), 0)
+ d = ImageDraw.Draw(im)
+ wob = fbm1d(n, 30, 3, self._seed())
+ inten = density * (0.78 + 0.22 * wob) * (1 + 0.25 * np.exp(-t / 0.03) + 0.2 * np.exp(-(1 - t) / 0.03))
+ gate = fbm1d(n, 12, 3, self._seed())
+ inten = inten * np.where(gate < np.quantile(gate, skip), 0.3, 1.0)
+ for i in range(n - 1):
+ ww = max(1, int(round(width * S * (0.85 + 0.15 * wob[i]))))
+ d.line([((px[i] - x0) * S, (py[i] - y0) * S), ((px[i + 1] - x0) * S, (py[i + 1] - y0) * S)],
+ fill=int(np.clip(inten[i], 0, 1) * 255), width=ww, joint='curve')
+ a = np.asarray(im.resize(((x1 - x0) * self.ss, (y1 - y0) * self.ss), Image.BOX), np.float32) / 255
+ self._pen_add(a, x0, y0, colour)
+
+ def _pen_add(self, a, x0, y0, colour):
+ lay = self._pen_layer(colour)
+ X0, Y0 = x0 * self.ss, y0 * self.ss
+ Hh, Ww = a.shape
+ xa, ya = max(X0, 0), max(Y0, 0)
+ xb, yb = min(X0 + Ww, lay.shape[1]), min(Y0 + Hh, lay.shape[0])
+ if xa >= xb or ya >= yb: return
+ aa = a[ya - Y0:yb - Y0, xa - X0:xb - X0]
+ if self._tooth is not None:
+ aa = aa * (0.8 + 0.4 * self._tooth[ya:yb, xa:xb])
+ sl = lay[ya:yb, xa:xb]
+ np.maximum(sl, np.clip(aa, 0, 1), out=sl)
+
+ def ring(self, cx, cy, rx, ry, colour='#b8322a', turns=1.12, width=1.5, tilt=-0.15):
+ """the quick loop drawn around something worth noticing: an ellipse that overshoots its start"""
+ n = 60
+ a0 = self.rng.uniform(-2.6, -2.0)
+ t = np.linspace(a0, a0 + 2 * np.pi * turns, n)
+ grow = 1 + 0.1 * (t - a0) / (2 * np.pi)
+ wob = 1 + 0.04 * fbm1d(n, 20, 3, self._seed())
+ x, y = np.cos(t) * rx * grow * wob, np.sin(t) * ry * grow * wob
+ cs, sn = np.cos(tilt), np.sin(tilt)
+ self.pen(np.stack([cx + x * cs - y * sn, cy + x * sn + y * cs], 1), colour, width)
+
+ def tick(self, x, y, size=14, colour='#b8322a', width=1.5):
+ """a check mark whose foot is at (x, y)"""
+ j = self.rng.normal(0, 0.06, 4) * size
+ pts = [(x - size * 0.45 + j[0], y - size * 0.45), (x - size * 0.12, y - size * 0.1 + j[1]),
+ (x + j[2] * 0.3, y), (x + size * 0.32, y - size * 0.6 + j[3]), (x + size * 0.62, y - size * 1.05)]
+ self.pen(pts, colour, width, smooth=True)
+
+ def pen_text(self, s, x, y, size=26, colour='#b8322a', rot=4.0, style='hand', anchor='ls'):
+ """handwriting with the same ballpoint"""
+ f = load_font(style, size * self.ss)
+ ox, oy = int(size * 0.6), int(size * 1.5) # local origin (1x) of the baseline
+ w, h = int(f.getlength(s) / self.ss + size * 1.4), int(size * 2.3)
+ im = Image.new('L', (w * self.ss, h * self.ss), 0)
+ ImageDraw.Draw(im).text((ox * self.ss, oy * self.ss), s, font=f, fill=230, anchor=anchor)
+ im = im.rotate(rot, resample=Image.BICUBIC, center=(ox * self.ss, oy * self.ss))
+ a = np.asarray(im, np.float32) / 255
+ self._pen_add(a, int(round(x)) - ox, int(round(y)) - oy, colour)
+
+ # ================================================================ output
+ def composite(self, emboss=0.05, wick=0.3, band=480):
+ """ink (multiplied into the paper like a dye), wicking halo, hammer emboss, ballpoint; in horizontal bands
+ to keep memory low; returns a 1x PIL image"""
+ if self.paper_rgb is None: self.form()
+ H2 = self.H * self.ss
+ out8 = np.empty((H2, self.W * self.ss, 3), np.uint8)
+ pad = 12
+ ink_k = (1 - self.ink_col)[None, None, :]
+ for y0 in range(0, H2, band):
+ y1 = min(y0 + band, H2)
+ a0, a1 = max(y0 - pad, 0), min(y1 + pad, H2)
+ A = self.inkbuf[a0:a1]
+ Aw = 1 - (1 - A) * (1 - wick * gauss(A, 1.1 * self.ss / 2))
+ out = self.paper_rgb[a0:a1] * (1 - Aw[..., None] * ink_k)
+ if emboss:
+ h = gauss(self.emb[a0:a1], 1.0 * self.ss / 2)
+ gy, gx = np.gradient(h)
+ out *= np.clip(1 + emboss * (gx * 0.6 + gy * 0.8), 0.9, 1.06)[..., None]
+ for key, a in self.pens.items():
+ col = np.array(key, np.float32)
+ out *= (1 - np.clip(a[a0:a1], 0, 1)[..., None] * (1 - col)[None, None, :])
+ out8[y0:y1] = (np.clip(out[y0 - a0:y0 - a0 + (y1 - y0)], 0, 1) * 255 + 0.5).astype(np.uint8)
+ im = Image.fromarray(out8)
+ if self.ss > 1: im = im.resize((self.W, self.H), Image.LANCZOS)
+ return im
+
+ 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
diff --git a/lib/lowpoly.py b/lib/lowpoly.py
new file mode 100644
index 0000000..4aa02ef
--- /dev/null
+++ b/lib/lowpoly.py
@@ -0,0 +1,1204 @@
+"""lowpoly — a late-90s polygon game frame, drawn by a tiny software rasterizer (numpy + Pillow only).
+
+What makes a frame from a 1999 console / PC game look like one, and how this module does each part:
+ framebuffer everything is drawn into a small framebuffer (default 384 x 216, the 16:9 cousin of 320 x 240)
+ and blown up with nearest-neighbour scaling (x5 -> 1920 x 1080): every pixel stays a hard
+ square and every polygon edge is a staircase. There is no anti-aliasing anywhere.
+ geometry meshes of a few dozen to a few thousand triangles. Vertices go world -> camera -> screen through
+ a pinhole camera; screen positions are snapped to whole pixels (no sub-pixel precision), so
+ thin polygons jag and shimmer.
+ hidden faces back-face culling, then the painter's algorithm: every triangle of the scene goes into one list
+ sorted by mean depth (the console "ordering table") and is drawn far to near; decals carry a depth
+ bias so they land on what they lie on. `zbuffer=True` adds a per-pixel depth test (the N64 way).
+ near plane triangles that cross the near plane are clipped (Sutherland-Hodgman) instead of dropped, so the
+ ground under the camera has no holes.
+ shading flat shading: one colour per triangle from its face normal: a hemisphere ambient (sky above,
+ warm bounce below) + one sun + an optional per-face Blinn glint, so gold, water and glass flash
+ facet by facet like cut stones instead of shining smoothly.
+ textures tiny procedural textures (32-64 texels) sampled nearest-neighbour, interpolated *affinely* across
+ each triangle (no perspective correction): rock strata bend on big polygons near the camera
+ exactly as they did on the original hardware. Texture alpha is a hard cut-out (crossed-quad trees).
+ fog a per-vertex depth cue: each vertex gets a fog amount from its depth, interpolated across the
+ triangle (Gouraud), so the far clip plane dissolves into the horizon colour of the sky.
+ blending the four semi-transparency modes of the era: 'half' (B/2 + F/2), 'add' (B + F), 'sub' (B - F),
+ 'quarter' (B + F/4): propeller discs, blob shadows, glows and lens flares.
+ colour the finished frame is crushed to 15-bit colour (5 bits per channel) through the 4 x 4 ordered
+ dither matrix, so every gradient (sky, fog, lens flare) gets the tell-tale cross-hatch.
+ HUD a bitmap font stamped in framebuffer pixels: chunky italic digits with a banded colour ramp, a 1 px
+ black outline and a drop shadow; icons, a stepped speed bar, a translucent minimap.
+
+World: X right, Y up, Z forward (into the picture), units are metres. Angles in degrees.
+
+ from lowpoly import LowPoly
+ g = LowPoly(1920, 1080, scale=5, seed=1)
+ path = g.path([(0, -40), (0, 60), (25, 160), (40, 260)])
+ plane = g.along(path, 50, u=-1, y=12)
+ g.camera(eye=g.along(path, 40, u=3, y=15), target=plane, fov=52)
+ g.aim(plane, at=(0.35, 0.68)) # compose: the plane on the lower-left third
+ g.sky('#33509e', '#c4bedd'); g.sun(screen=(0.4, 0.1)); g.light(lift=26)
+ g.canyon(path, height=0.75); g.river(path); g.fog(55, 250)
+ g.ring(g.along(path, 70, y=13), g.heading(path, 70))
+ g.aircraft(plane, g.heading(path, 50), roll=30)
+ g.flare()
+ g.counter('HOOPS', '04/09', 8, 6, icon='ring')
+ g.save('out.jpg')
+"""
+import os
+import numpy as np
+from PIL import Image
+from core import noise2d, fbm1d, spline
+
+# the 4x4 ordered-dither offsets of the PlayStation GPU (in 8-bit steps, added before truncating to 5 bits)
+DITHER = np.array([[-4, 0, -3, 1], [2, -2, 3, -1], [-3, 1, -4, 0], [3, -1, 2, -2]], np.float32)
+
+GOLD, WHITE, BLACK = '#ffaa1a', '#f4f1e8', '#000000'
+HUD_YELLOW, HUD_ORANGE, HUD_RED, HUD_GREEN, HUD_CYAN = '#ffe85a', '#ff8a1c', '#e8401c', '#7ee05a', '#7fe6ff'
+
+FONT = { # 5 x 7 bitmap glyphs for the HUD
+ 'A': [' ### ', '# #', '# #', '#####', '# #', '# #', '# #'], 'B': ['#### ', '# #', '# #', '#### ', '# #', '# #', '#### '],
+ 'C': [' ### ', '# #', '# ', '# ', '# ', '# #', ' ### '], 'D': ['#### ', '# #', '# #', '# #', '# #', '# #', '#### '],
+ 'E': ['#####', '# ', '# ', '#### ', '# ', '# ', '#####'], 'F': ['#####', '# ', '# ', '#### ', '# ', '# ', '# '],
+ 'G': [' ### ', '# #', '# ', '# ###', '# #', '# #', ' ####'], 'H': ['# #', '# #', '# #', '#####', '# #', '# #', '# #'],
+ 'I': ['#####', ' # ', ' # ', ' # ', ' # ', ' # ', '#####'], 'J': [' ###', ' # ', ' # ', ' # ', ' # ', '# # ', ' ## '],
+ 'K': ['# #', '# # ', '# # ', '## ', '# # ', '# # ', '# #'], 'L': ['# ', '# ', '# ', '# ', '# ', '# ', '#####'],
+ 'M': ['# #', '## ##', '# # #', '# # #', '# #', '# #', '# #'], 'N': ['# #', '# #', '## #', '# # #', '# ##', '# #', '# #'],
+ 'O': [' ### ', '# #', '# #', '# #', '# #', '# #', ' ### '], 'P': ['#### ', '# #', '# #', '#### ', '# ', '# ', '# '],
+ 'Q': [' ### ', '# #', '# #', '# #', '# # #', '# # ', ' ## #'], 'R': ['#### ', '# #', '# #', '#### ', '# # ', '# # ', '# #'],
+ 'S': [' ####', '# ', '# ', ' ### ', ' #', ' #', '#### '], 'T': ['#####', ' # ', ' # ', ' # ', ' # ', ' # ', ' # '],
+ 'U': ['# #', '# #', '# #', '# #', '# #', '# #', ' ### '], 'V': ['# #', '# #', '# #', '# #', '# #', ' # # ', ' # '],
+ 'W': ['# #', '# #', '# #', '# # #', '# # #', '## ##', '# #'], 'X': ['# #', '# #', ' # # ', ' # ', ' # # ', '# #', '# #'],
+ 'Y': ['# #', '# #', ' # # ', ' # ', ' # ', ' # ', ' # '], 'Z': ['#####', ' #', ' # ', ' # ', ' # ', '# ', '#####'],
+ '0': [' ### ', '# #', '# #', '# #', '# #', '# #', ' ### '], '1': [' # ', ' ## ', '# # ', ' # ', ' # ', ' # ', '#####'],
+ '2': [' ### ', '# #', ' #', ' ## ', ' # ', '# ', '#####'], '3': ['#####', ' # ', ' # ', ' # ', ' #', '# #', ' ### '],
+ '4': [' # ', ' ## ', ' # # ', '# # ', '#####', ' # ', ' # '], '5': ['#####', '# ', '#### ', ' #', ' #', '# #', ' ### '],
+ '6': [' ## ', ' # ', '# ', '#### ', '# #', '# #', ' ### '], '7': ['#####', ' #', ' # ', ' # ', ' # ', ' # ', ' # '],
+ '8': [' ### ', '# #', '# #', ' ### ', '# #', '# #', ' ### '], '9': [' ### ', '# #', '# #', ' ####', ' #', ' # ', ' ## '],
+ ' ': [' '] * 7, '.': [' ', ' ', ' ', ' ', ' ', '#', '#'], ':': [' ', '#', '#', ' ', '#', '#', ' '],
+ "'": ['#', '#', ' ', ' ', ' ', ' ', ' '], '"': ['# #', '# #', ' ', ' ', ' ', ' ', ' '],
+ '/': [' #', ' #', ' # ', ' # ', ' # ', '# ', '# '], '-': [' ', ' ', ' ', '####', ' ', ' ', ' '],
+ '+': [' ', ' # ', ' # ', '#####', ' # ', ' # ', ' '], '!': ['#', '#', '#', '#', '#', ' ', '#'],
+ '>': ['# ', ' # ', ' # ', ' #', ' # ', ' # ', '# '], '<': [' #', ' # ', ' # ', '# ', ' # ', ' # ', ' #'],
+ 'x': [' ', ' ', '# #', ' # # ', ' # ', ' # # ', '# #'], '%': ['## #', '## #', ' # ', ' # ', ' # ', '# ##', '# ##'],
+ '#': [' # # ', '#####', ' # # ', ' # # ', ' # # ', '#####', ' # # '],
+}
+BLEND = {'opaque': 0, 'half': 1, 'add': 2, 'sub': 3, 'quarter': 4}
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+def _c(c):
+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)
+
+
+def _unit(v):
+ v = np.asarray(v, np.float32)
+ return v / (np.linalg.norm(v, axis=-1, keepdims=True) + 1e-9)
+
+
+def _q5(c):
+ """snap a colour to the 15-bit grid (5 bits per channel), as the hardware stores it"""
+ v = np.clip(np.floor(np.asarray(c, np.float32) * 31 + 0.5), 0, 31)
+ return (v * 8 + v // 4) / 255
+
+
+def _basis(fwd, roll=0.0, pitch=0.0):
+ """orthonormal (right, up, fwd) for a heading, then pitch (nose up +) and roll (right wing down +)"""
+ f = _unit(fwd)
+ r = _unit(np.cross([0, 1, 0], f))
+ u = np.cross(f, r)
+ p, q = np.radians(pitch), np.radians(roll)
+ f, u = f * np.cos(p) + u * np.sin(p), u * np.cos(p) - f * np.sin(p)
+ r, u = r * np.cos(q) - u * np.sin(q), u * np.cos(q) + r * np.sin(q)
+ return np.stack([r, u, f]).astype(np.float32)
+
+
+class Path:
+ """a centreline on the ground, sampled every metre of arc length (x, z); `at(s)` -> point, tangent, right"""
+ def __init__(self, pts):
+ P = spline(np.asarray(pts, np.float32), per=32)
+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1)
+ s = np.concatenate([[0], np.cumsum(seg)])
+ self.length = float(s[-1])
+ self.s = np.arange(0, self.length, 1.0, dtype=np.float32)
+ self.x = np.interp(self.s, s, P[:, 0]).astype(np.float32)
+ self.z = np.interp(self.s, s, P[:, 1]).astype(np.float32)
+ tx, tz = np.gradient(self.x), np.gradient(self.z)
+ tl = np.hypot(tx, tz) + 1e-9
+ self.tx, self.tz = tx / tl, tz / tl
+
+ def at(self, s):
+ s = np.clip(np.asarray(s, np.float32), 0, self.s[-1])
+ x, z = np.interp(s, self.s, self.x), np.interp(s, self.s, self.z)
+ tx, tz = np.interp(s, self.s, self.tx), np.interp(s, self.s, self.tz)
+ tl = np.hypot(tx, tz) + 1e-9
+ tx, tz = tx / tl, tz / tl
+ return x, z, tx, tz, tz, -tx # point, tangent, right-hand normal
+
+
+class LowPoly:
+ def __init__(self, W=1920, H=1080, scale=5, seed=0, record=True, zbuffer=False, near=0.6, far=260.0,
+ bits=5, dither=True):
+ self.W, self.H, self.scale = W, H, scale
+ self.w, self.h = W // scale, H // scale
+ self.rng = np.random.default_rng(seed)
+ self.seed = seed
+ self.record, self.zbuffer, self.near, self.far = record, zbuffer, near, far
+ self.bits, self.dither = bits, dither
+ self.meshes, self.post, self.hud = [], [], []
+ self.textures = {}
+ self.stages = []
+ self.camera((0, 2, -10), (0, 2, 0))
+ self.sky('#3a58a8', '#c2bcdc')
+ self.L = self.L_shade = _unit([-0.45, 0.35, 0.8])
+ self.sun_col, self.sky_amb, self.gnd_amb = _c('#ffe2b0') * 1.05, _c('#6f7fb0') * 0.95, _c('#7a5040') * 0.8
+ self.fog_on, self.fog_col, self.fog_near, self.fog_far = False, self.horizon, 60.0, far
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ # ------------------------------------------------------------ camera, sky, sun, fog
+ def camera(self, eye, target=None, fov=52.0, roll=0.0, yaw=0.0, pitch=0.0):
+ """pinhole camera at `eye` looking at `target` (or along yaw / pitch in degrees: yaw 0 looks along +Z,
+ + turns right; pitch + looks up); `fov` is the vertical field of view; roll tilts the horizon (+ clockwise)"""
+ self.eye = np.asarray(eye, np.float32)
+ if target is None:
+ y, p = np.radians(yaw), np.radians(pitch)
+ target = self.eye + np.array([np.sin(y) * np.cos(p), np.sin(p), np.cos(y) * np.cos(p)], np.float32)
+ d = np.asarray(target, np.float32) - self.eye
+ self.yaw = float(np.degrees(np.arctan2(d[0], d[2])))
+ self.pitch = float(np.degrees(np.arctan2(d[1], np.hypot(d[0], d[2]))))
+ self.roll = roll
+ B = _basis(d)
+ q = np.radians(-roll)
+ r, u = B[0] * np.cos(q) - B[1] * np.sin(q), B[1] * np.cos(q) + B[0] * np.sin(q)
+ self.R = np.stack([r, u, B[2]]).astype(np.float32)
+ self.fov = fov
+ self.f = (self.h / 2) / np.tan(np.radians(fov) / 2)
+ self.cx, self.cy = self.w / 2, self.h / 2
+ self.tanx, self.tany = (self.w / 2) / self.f, (self.h / 2) / self.f
+ self._skybuf = None
+
+ def aim(self, point, at=(0.5, 0.5)):
+ """turn the camera (keeping eye, fov and roll) so that world `point` lands at screen fraction `at`:
+ the way to compose a shot ("plane on the lower-left third")"""
+ yaw, pitch = self.yaw, self.pitch
+ for _ in range(40):
+ self.camera(self.eye, None, self.fov, self.roll, yaw, pitch)
+ x, y, z = self.project(point)
+ dx, dy = x - at[0] * self.w, y - at[1] * self.h
+ if abs(dx) < 0.05 and abs(dy) < 0.05: break
+ yaw += np.degrees(np.arctan(dx / self.f)); pitch -= np.degrees(np.arctan(dy / self.f))
+ return self
+
+ def project(self, p):
+ """world point -> (sx, sy, depth) in framebuffer pixels"""
+ c = (np.asarray(p, np.float32) - self.eye) @ self.R.T
+ z = max(float(c[2]), 1e-3)
+ return self.cx + self.f * c[0] / z, self.cy - self.f * c[1] / z, float(c[2])
+
+ def ray(self, sx, sy):
+ """world direction through framebuffer pixel (sx, sy)"""
+ d = np.array([(sx - self.cx) / self.f, -(sy - self.cy) / self.f, 1.0], np.float32)
+ return _unit(d @ self.R)
+
+ def sky(self, zenith='#3a58a8', horizon='#c2bcdc', below=None, glow='#fff0c8', bands=None):
+ """sky gradient by elevation (zenith -> horizon), a warm glow around the sun; below the horizon = horizon"""
+ self.zenith, self.horizon = _c(zenith), _c(horizon)
+ self.below = _c(below) if below is not None else self.horizon
+ self.glow_col = _c(glow)
+ self.bands = bands
+ self._skybuf = None
+
+ def sun(self, direction=None, screen=None, colour='#ffe2b0', strength=1.05, disc=1.7):
+ """set the sun: a world direction toward it, or a framebuffer position as fractions (fx, fy) of the frame.
+ It lights every face, and is drawn in the sky with a glow (call after camera())"""
+ if screen is not None:
+ direction = self.ray(screen[0] * self.w, screen[1] * self.h)
+ self.L = _unit(direction)
+ self.L_shade = self.L
+ self.sun_col = _c(colour) * strength
+ self.sun_disc = disc
+ self._skybuf = None
+
+ def light(self, direction=None, lift=0.0):
+ """the shading light, if it should differ from the sun in the sky (games of the era set them separately):
+ a world direction, or the sun's direction raised by `lift` degrees"""
+ d = _unit(direction) if direction is not None else self.L
+ if lift:
+ h = np.hypot(d[0], d[2]); el = np.arctan2(d[1], h) + np.radians(lift)
+ d = np.array([d[0] / h * np.cos(el), np.sin(el), d[2] / h * np.cos(el)], np.float32)
+ self.L_shade = _unit(d)
+
+ def ambient(self, sky='#6f7fb0', ground='#7a5040', strength=(0.95, 0.8)):
+ self.sky_amb, self.gnd_amb = _c(sky) * strength[0], _c(ground) * strength[1]
+
+ def fog(self, near=60.0, far=None, colour=None):
+ """per-vertex depth fog from `near` (clear) to `far` (all fog); colour defaults to the sky's horizon"""
+ self.fog_on, self.fog_near = True, float(near)
+ self.fog_far = float(far if far is not None else self.far)
+ self.fog_col = _c(colour) if colour is not None else self.horizon
+
+ def _sky(self):
+ if self._skybuf is not None: return self._skybuf
+ yy, xx = np.mgrid[0:self.h, 0:self.w].astype(np.float32) + 0.5
+ d = np.stack([(xx - self.cx) / self.f, -(yy - self.cy) / self.f, np.ones_like(xx)], -1) @ self.R
+ d /= np.linalg.norm(d, axis=-1, keepdims=True)
+ el = np.arcsin(np.clip(d[..., 1], -1, 1))
+ t = np.clip(el / np.radians(38), 0, 1) ** 0.75
+ img = self.horizon * (1 - t[..., None]) + self.zenith * t[..., None]
+ img = np.where((el < 0)[..., None], self.below, img)
+ if self.bands: # thin streak clouds lit from below
+ n = noise2d(self.h, self.w, 40, 3, self.seed + 5)
+ for e0, thick, col, a in self.bands:
+ k = np.exp(-((np.degrees(el) - e0) / thick) ** 2) * np.clip((n - 0.35) * 2.2, 0, 1) * a
+ img = img * (1 - k[..., None]) + _c(col) * k[..., None]
+ cs = np.clip((d * self.L).sum(-1), -1, 1)
+ ang = np.degrees(np.arccos(cs))
+ g = np.exp(-ang / 9.0) * 0.55 + np.exp(-ang / 30.0) * 0.25
+ img = img + (self.glow_col - img) * np.clip(g, 0, 1)[..., None]
+ disc = getattr(self, 'sun_disc', 1.7)
+ core = (ang < disc).astype(np.float32)
+ ring = ((ang >= disc) & (ang < disc * 1.6)).astype(np.float32)
+ img = img * (1 - core[..., None]) + np.array([1.0, 0.99, 0.93]) * core[..., None]
+ img = img * (1 - 0.6 * ring[..., None]) + np.array([1.0, 0.93, 0.7]) * 0.6 * ring[..., None]
+ self._skybuf = np.clip(img, 0, 1).astype(np.float32)
+ return self._skybuf
+
+ # ------------------------------------------------------------ textures
+ def texture(self, name):
+ """tiny procedural textures, RGBA float: strata, ledge, sand, water, rock, juniper, spark, flare"""
+ if name in self.textures: return self.textures[name]
+ r = np.random.default_rng(self.seed * 31 + sum(map(ord, name)))
+ if name == 'strata': # canyon wall: horizontal bands, ledges, desert-varnish streaks
+ th, tw = 64, 32
+ pal = ['#7c3421', '#a8482a', '#c4643a', '#d98a52', '#e6b27a', '#b9573a', '#8e4436', '#efcf98', '#c87a4c', '#9a3d27']
+ rows = np.zeros((th, 3), np.float32)
+ y, k = 0, 0
+ while y < th:
+ t = int(r.integers(2, 8)); col = hexc(pal[(k * 3 + int(r.integers(0, 3))) % len(pal)])
+ rows[y:y + t] = col; y += t; k += 1
+ tex = np.repeat(rows[:, None, :], tw, 1)
+ tex *= (0.9 + 0.2 * r.random((th, tw)))[..., None]
+ edges = np.abs(np.diff(rows.sum(1), prepend=rows[0].sum())) > 0.25
+ tex[edges] *= 0.72 # ledge shadows at band boundaries
+ for _ in range(7): # dark varnish streaks running down
+ x0, y0, L = int(r.integers(0, tw)), int(r.integers(0, th)), int(r.integers(8, 26))
+ for i in range(L):
+ yy = (y0 + i) % th
+ a = 0.45 * (1 - i / L)
+ for dx in (0, 1):
+ tex[yy, (x0 + dx) % tw] *= (1 - a * (0.6 if dx else 1))
+ alpha = np.ones((th, tw, 1), np.float32)
+ elif name == 'ledge': # flat tops: dusty ochre with sage scrub
+ th = tw = 32
+ base = hexc('#c99a62') * (0.88 + 0.22 * r.random((th, tw)))[..., None]
+ n = noise2d(th, tw, 6, 2, int(r.integers(1 << 30)))
+ scrub = (r.random((th, tw)) < 0.12) | (n > 0.78)
+ tex = np.where(scrub[..., None], hexc('#7d8a52') * (0.75 + 0.3 * r.random((th, tw)))[..., None], base)
+ pebble = r.random((th, tw)) < 0.05
+ tex = np.where(pebble[..., None], hexc('#ead2a4'), tex)
+ alpha = np.ones((th, tw, 1), np.float32)
+ elif name == 'sand':
+ th = tw = 32
+ tex = hexc('#d8b48a') * (0.86 + 0.24 * r.random((th, tw)))[..., None]
+ tex = np.where((r.random((th, tw)) < 0.07)[..., None], hexc('#8f7a66'), tex)
+ alpha = np.ones((th, tw, 1), np.float32)
+ elif name == 'water': # teal with lighter ripple dashes running downstream
+ th = tw = 32
+ tex = np.repeat((hexc('#2a6f7c') * (0.92 + 0.12 * r.random((th, 1))))[:, None, :], tw, 1)
+ for _ in range(16):
+ y, x, L = int(r.integers(0, th)), int(r.integers(0, tw)), int(r.integers(3, 8))
+ for i in range(L):
+ tex[(y + i // 3) % th, (x + i) % tw] = hexc('#5fa6a8') if i % 4 else hexc('#9ed2c8')
+ tex *= (0.95 + 0.1 * r.random((th, tw)))[..., None]
+ alpha = np.ones((th, tw, 1), np.float32)
+ elif name == 'rock':
+ th = tw = 16
+ tex = hexc('#8a7468') * (0.8 + 0.35 * r.random((th, tw)))[..., None]
+ alpha = np.ones((th, tw, 1), np.float32)
+ elif name == 'juniper': # a cut-out tree for crossed quads (u across, v up)
+ th, tw = 48, 32
+ yy, xx = np.mgrid[0:th, 0:tw].astype(np.float32)
+ v = 1 - (yy + 0.5) / th; u = (xx + 0.5) / tw - 0.5
+ trunk = (np.abs(u + 0.02 * np.sin(v * 9)) < 0.05) & (v < 0.32)
+ crown = np.zeros((th, tw), bool)
+ for _ in range(9):
+ cy, cx = r.uniform(0.32, 0.9), r.uniform(-0.18, 0.18)
+ ry = r.uniform(0.09, 0.16); rx = ry * (1.4 - (cy - 0.3)) * 1.25
+ crown |= ((u - cx) / rx) ** 2 + ((v - cy) / ry) ** 2 < 1
+ crown &= r.random((th, tw)) > 0.06
+ lit = 0.75 + 0.5 * np.clip(-u * 2 + (v - 0.5), -0.5, 0.6)
+ tex = np.where(crown[..., None], hexc('#5c7e40') * (lit * (0.85 + 0.3 * r.random((th, tw))))[..., None],
+ hexc('#5a3c2a') * np.ones((th, tw, 1)))
+ alpha = (crown | trunk)[..., None].astype(np.float32)
+ elif name == 'spark': # four-point star for additive sprites
+ th = tw = 16
+ yy, xx = np.mgrid[0:th, 0:tw].astype(np.float32) - 7.5
+ a = np.clip(1.2 - (np.abs(xx) * np.abs(yy)) ** 0.5 / 1.6 - np.hypot(xx, yy) / 9, 0, 1)
+ tex = np.ones((th, tw, 3), np.float32); alpha = a[..., None]
+ else:
+ raise ValueError(name)
+ T = np.concatenate([np.clip(tex, 0, 1), alpha], -1).astype(np.float32)
+ self.textures[name] = T
+ return T
+
+ # ------------------------------------------------------------ meshes
+ def mesh(self, V, F, colour, uv=None, tex=None, lit=True, spec=0.0, shine=16.0, blend='opaque', alpha=0.5,
+ two_sided=False, fog=True, bias=0.0, cutout=False, glow=0.0, name=''):
+ """add triangles. V (n, 3) world vertices; F (m, 3) indices; colour one colour or (m, 3) per face;
+ uv (m, 3, 2) per face corner; tex a texture name; blend 'opaque'|'half'|'add'|'sub'|'quarter'; glow lifts the
+ face toward full-bright (pickups). Front faces wind so that their normal points toward the viewer side."""
+ V = np.asarray(V, np.float32); F = np.asarray(F, np.int32)
+ P = V[F]
+ m = len(F)
+ col = np.asarray(colour if not isinstance(colour, str) else hexc(colour), np.float32)
+ col = np.broadcast_to(col, (m, 3)).astype(np.float32)
+ N = _unit(np.cross(P[:, 1] - P[:, 0], P[:, 2] - P[:, 0]))
+ if uv is None: uv = np.zeros((m, 3, 2), np.float32)
+ uv = np.asarray(uv, np.float32)
+ flat = col.copy()
+ if tex is not None: # untextured preview: the texel under the face centre
+ T = self.texture(tex)
+ c = uv.mean(1)
+ iu = (np.floor(c[:, 0] * T.shape[1]).astype(int)) % T.shape[1]
+ iv = (np.floor(c[:, 1] * T.shape[0]).astype(int)) % T.shape[0]
+ flat = col * T[iv, iu, :3]
+ self.meshes.append(dict(P=P, N=N, col=col, flat=flat, uv=uv, tex=tex, lit=lit, spec=spec, shine=shine,
+ blend=BLEND[blend], alpha=alpha, two=two_sided, fog=fog, bias=bias, cutout=cutout,
+ glow=glow, name=name))
+ return self.meshes[-1]
+
+ @staticmethod
+ def _orient(V, F, inside):
+ """flip faces whose normal points toward `inside` (a point, or (m, 3) points one per face)"""
+ V = np.asarray(V, np.float32); F = np.array(F, np.int32)
+ P = V[F]
+ n = np.cross(P[:, 1] - P[:, 0], P[:, 2] - P[:, 0])
+ bad = ((P.mean(1) - np.asarray(inside, np.float32)) * n).sum(-1) < 0
+ F[bad] = F[bad][:, [0, 2, 1]]
+ return F
+
+ # ------------------------------------------------------------ places along a path
+ def path(self, pts):
+ """a centreline through (x, z) control points (Catmull-Rom), sampled by arc length"""
+ return Path(pts)
+
+ def along(self, path, s, u=0.0, y=0.0):
+ """world point `s` metres along the path, `u` metres to its right, `y` metres up"""
+ x, z, tx, tz, nx, nz = path.at(s)
+ return np.array([x + nx * u, y, z + nz * u], np.float32)
+
+ def heading(self, path, s):
+ x, z, tx, tz, nx, nz = path.at(s)
+ return np.array([tx, 0.0, tz], np.float32)
+
+ # ------------------------------------------------------------ terrain
+ CANYON = [ # half cross-section from the centre outward: (u metres, y metres, material of the face beyond)
+ (0.0, -1.2, 'sand'), (6.0, -1.2, 'sand'), (7.4, 0.5, 'sand'), (10.5, 1.4, 'sand'), (13.0, 4.5, 'rock'),
+ (13.6, 15.0, 'ledge'), (18.0, 15.8, 'rock'), (18.8, 26.0, 'ledge'), (22.5, 26.8, 'rock'), (23.4, 37.0, 'ledge'),
+ (34.0, 38.0, 'ledge'), (60.0, 39.5, 'ledge'), (110.0, 41.0, 'ledge')]
+ MATERIALS = {'sand': ('sand', '#ffffff', 'top'), 'rock': ('strata', '#ffffff', 'wall'),
+ 'ledge': ('ledge', '#ffffff', 'top')}
+
+ def canyon(self, path, s0=0.0, s1=None, step=7.0, profile=None, width=0.14, wobble=0.9, height=1.0,
+ strata=40.0, buried=-0.2, seed=None):
+ """a canyon lofted along `path`: every `step` metres a cross-section (river bed, sand banks, talus, stepped
+ cliffs with ledges, rim, plateau) is laid across the path; its width breathes along the way (`width`), every
+ vertex is nudged (`wobble`) so no two facets match; walls take the strata texture by height (`strata`
+ metres per repeat), flat parts a top-down sand / scrub texture"""
+ prof = profile or self.CANYON
+ s1 = path.s[-1] if s1 is None else s1
+ n = int((s1 - s0) / step) + 1
+ ss = np.linspace(s0, s1, n).astype(np.float32)
+ r = np.random.default_rng(self._seed() if seed is None else seed)
+ breathe = {side: 1 + width * fbm1d(n, 6, 3, int(r.integers(1 << 30))) for side in (-1, 1)}
+ K = len(prof)
+ cols = [(-1, k) for k in range(K - 1, 0, -1)] + [(0, 0)] + [(1, k) for k in range(1, K)]
+ nc = len(cols)
+ V = np.zeros((n, nc, 3), np.float32)
+ A = np.zeros((n, nc), np.float32) # arc length of every vertex (texture u on walls)
+ x, z, tx, tz, nx, nz = path.at(ss)
+ for j, (side, k) in enumerate(cols):
+ u, y, _ = prof[k]
+ b = breathe[side if side else 1]
+ uu = side * u * (b if u > 7 else 1.0)
+ big = 1.0 if u >= 11 else 0.4
+ ju = r.normal(0, wobble, n) * big * (k > 0)
+ jy = r.normal(0, wobble, n) * big * (k > 0)
+ js = r.normal(0, step * 0.12, n) * (k > 0)
+ js[0] = js[-1] = 0
+ V[:, j, 0] = x + nx * (uu + ju) + tx * js
+ V[:, j, 1] = y * (height if y > 2 else 1.0) + jy
+ V[:, j, 2] = z + nz * (uu + ju) + tz * js
+ A[:, j] = ss + js
+ idx = np.arange(n * nc).reshape(n, nc)
+ F, mats, inside = [], [], []
+ for i in range(n - 1):
+ for j in range(nc - 1):
+ a, b, c, d = idx[i, j], idx[i, j + 1], idx[i + 1, j], idx[i + 1, j + 1]
+ side = cols[j][0] if cols[j][0] < 0 else cols[j + 1][0]
+ mat = prof[min(cols[j][1], cols[j + 1][1])][2] # material of the face beyond the inner point
+ F += [(a, c, b), (b, c, d)] if (i + j) % 2 else [(a, c, d), (a, d, b)]
+ mats += [mat, mat]
+ # the rock side of every face: deep below the plateau on its own side of the canyon
+ ox, oz = (x[i] + x[i + 1]) / 2 + nx[i] * side * 300, (z[i] + z[i + 1]) / 2 + nz[i] * side * 300
+ inside += [[ox, -80.0, oz]] * 2
+ Vf = V.reshape(-1, 3)
+ F = self._orient(Vf, F, np.array(inside, np.float32))
+ mats = np.array(mats)
+ if buried is not None: # faces wholly under the water are never seen: leave them out
+ keep = Vf[F][:, :, 1].max(1) > buried
+ F, mats = F[keep], mats[keep]
+ self._terrain(Vf[F], mats, strata, along=A.reshape(-1)[F])
+
+ def _terrain(self, P, mats, strata=40.0, along=None):
+ """texture terrain faces by material: walls get strata by height (u along the wall), flat parts top-down"""
+ if along is None:
+ along = P[..., 0] * 0.6 + P[..., 2] * 0.8
+ for mat in np.unique(mats):
+ sel = mats == mat
+ tex, tint, mapping = self.MATERIALS[mat]
+ Q = P[sel]
+ if mapping == 'wall':
+ uv = np.stack([along[sel] / 22.0, -Q[..., 1] / strata], -1)
+ else:
+ uv = np.stack([Q[..., 0] / 15.0, Q[..., 2] / 15.0], -1)
+ V = Q.reshape(-1, 3)
+ self.mesh(V, np.arange(len(V)).reshape(-1, 3), tint, uv=uv, tex=tex, name='terrain')
+
+ def river(self, path, s0=0.0, s1=None, step=7.0, half=7.0, level=0.0, ripple=0.12, colour='#ffffff', spec=0.35):
+ """the water surface between the banks: a strip of slightly uneven facets (each catches the sun on its own),
+ textured with ripples running downstream"""
+ s1 = path.s[-1] if s1 is None else s1
+ n = int((s1 - s0) / step) + 1
+ ss = np.linspace(s0, s1, n).astype(np.float32)
+ x, z, tx, tz, nx, nz = path.at(ss)
+ us = np.array([-half, -half * 0.35, half * 0.35, half], np.float32)
+ r = np.random.default_rng(self._seed())
+ nc = len(us)
+ V = np.zeros((n, nc, 3), np.float32); UV = np.zeros((n, nc, 2), np.float32)
+ for j, u in enumerate(us):
+ V[:, j, 0] = x + nx * u; V[:, j, 2] = z + nz * u
+ V[:, j, 1] = level + r.normal(0, ripple, n) * (0.4 if j in (0, nc - 1) else 1)
+ UV[:, j, 0] = u / 9.0; UV[:, j, 1] = -ss / 9.0
+ idx = np.arange(n * nc).reshape(n, nc)
+ F = []
+ for i in range(n - 1):
+ for j in range(nc - 1):
+ a, b, c, d = idx[i, j], idx[i, j + 1], idx[i + 1, j], idx[i + 1, j + 1]
+ F += [(a, c, b), (b, c, d)] if (i + j) % 2 else [(a, c, d), (a, d, b)]
+ Vf = V.reshape(-1, 3)
+ F = self._orient(Vf, F, Vf.mean(0) - np.array([0, 50, 0]))
+ return self.mesh(Vf, F, colour, uv=UV.reshape(-1, 2)[F], tex='water', spec=spec, shine=30, bias=-2.0,
+ name='water')
+
+ def _prism(self, ring_lo, ring_hi, top=True, bottom=False):
+ """side wall (+ caps) between two closed rings of equal length -> V, F (outward)"""
+ n = len(ring_lo)
+ V = np.vstack([ring_lo, ring_hi]).astype(np.float32)
+ F = []
+ for i in range(n):
+ j = (i + 1) % n
+ F += [(i, j, n + i), (j, n + j, n + i)]
+ c_lo, c_hi = ring_lo.mean(0), ring_hi.mean(0)
+ if top:
+ V = np.vstack([V, c_hi]); k = len(V) - 1
+ F += [(n + i, n + (i + 1) % n, k) for i in range(n)]
+ if bottom:
+ V = np.vstack([V, c_lo]); k = len(V) - 1
+ F += [(i, (i + 1) % n, k) for i in range(n)]
+ F = self._orient(V, np.array(F), (c_lo + c_hi) / 2)
+ return V, F
+
+ def mesa(self, x, z, radius, height, base=0.0, sides=7, taper=0.82, cap=0.06, strata=40.0, seed=None):
+ """a flat-topped butte: an irregular prism with strata walls, a scrub-covered cap rock and a talus skirt"""
+ r = np.random.default_rng(self._seed() if seed is None else seed)
+ a = np.sort(r.uniform(0, 2 * np.pi, sides)) + r.uniform(0, 1)
+ rr = radius * r.uniform(0.75, 1.2, sides)
+ lo = np.stack([x + np.cos(a) * rr * 1.25, np.full(sides, base), z + np.sin(a) * rr * 1.25], 1)
+ mid = np.stack([x + np.cos(a) * rr, np.full(sides, base + height * 0.18), z + np.sin(a) * rr], 1)
+ hi = np.stack([x + np.cos(a) * rr * taper, base + height + r.normal(0, height * cap, sides), z + np.sin(a) * rr * taper], 1)
+ V1, F1 = self._prism(lo, mid, top=False)
+ V2, F2 = self._prism(mid, hi, top=False)
+ Pm = np.concatenate([V1[F1], V2[F2]])
+ ang = np.arctan2(Pm[..., 2] - z, Pm[..., 0] - x)
+ ang = np.where(ang - ang[:, :1] > np.pi, ang - 2 * np.pi, np.where(ang - ang[:, :1] < -np.pi, ang + 2 * np.pi, ang))
+ self._terrain(Pm, np.array(['rock'] * len(Pm)), strata, along=ang * radius)
+ Vt = np.vstack([hi, hi.mean(0) + [0, height * 0.02, 0]])
+ Ft = self._orient(Vt, [(i, (i + 1) % sides, sides) for i in range(sides)], hi.mean(0) - [0, 5, 0])
+ self._terrain(Vt[Ft], np.array(['ledge'] * sides), strata)
+
+ def arch(self, path, s, span=46.0, rise=16.0, base=24.0, thick=4.5, depth=6.0, segs=11, strata=40.0):
+ """a natural stone arch thrown across the canyon at `s`: an irregular rock section swept along a half
+ ellipse whose feet sink into the walls at height `base`; thicker at the feet"""
+ x, z, tx, tz, nx, nz = path.at(s)
+ P0 = np.array([x, 0, z], np.float32)
+ t3, n3 = np.array([tx, 0, tz], np.float32), np.array([nx, 0, nz], np.float32)
+ r = np.random.default_rng(self._seed())
+ sec = 7
+ rings = []
+ for i in range(segs + 1):
+ th = np.pi * i / segs
+ c = P0 + n3 * (-np.cos(th) * span / 2) + np.array([0, base + np.sin(th) * rise, 0])
+ out = _unit(n3 * -np.cos(th) * 0.6 + np.array([0, np.sin(th), 0]) + 1e-3) # away from the arch's axis
+ k = 1 + 0.9 * (1 - np.sin(th)) ** 2
+ a = np.linspace(0, 2 * np.pi, sec, endpoint=False) + 0.3
+ pts = [c + t3 * np.cos(aa) * depth / 2 * k * r.uniform(0.8, 1.15) +
+ out * np.sin(aa) * thick / 2 * k * r.uniform(0.8, 1.15) for aa in a]
+ rings.append(np.array(pts, np.float32))
+ V = np.vstack(rings)
+ F = []
+ for i in range(segs):
+ for j in range(sec):
+ a_, b_ = i * sec + j, i * sec + (j + 1) % sec
+ c_, d_ = a_ + sec, b_ + sec
+ F += [(a_, b_, c_), (b_, d_, c_)]
+ F = np.array(F)
+ cen = np.repeat(np.array([rg.mean(0) for rg in rings[:-1]]) * 0.5 + np.array([rg.mean(0) for rg in rings[1:]]) * 0.5, sec * 2, 0)
+ F = self._orient(V, F, cen)
+ P = V[F]
+ mats = np.where(_unit(np.cross(P[:, 1] - P[:, 0], P[:, 2] - P[:, 0]))[:, 1] > 0.75, 'ledge', 'rock')
+ self._terrain(P, mats, strata)
+
+ def boulder(self, x, y, z, r=1.0, colour='#ffffff', squash=0.7):
+ """a jittered octahedron-sphere rock (half sunk into what it sits on)"""
+ rr = np.random.default_rng(self._seed())
+ ph = np.array([0.0, 0.55, 1.15, 1.75, np.pi])
+ V, F = [], []
+ ring_n = 6
+ V.append([0, 1, 0])
+ for p in ph[1:-1]:
+ for k in range(ring_n):
+ a = 2 * np.pi * k / ring_n + p
+ V.append([np.sin(p) * np.cos(a), np.cos(p), np.sin(p) * np.sin(a)])
+ V.append([0, -1, 0])
+ V = np.array(V, np.float32) * rr.uniform(0.8, 1.15, (len(V), 1))
+ V *= np.array([r, r * squash, r * rr.uniform(0.8, 1.2)])
+ V += [x, y, z]
+ nr = len(ph) - 2
+ for k in range(ring_n):
+ F.append((0, 1 + k, 1 + (k + 1) % ring_n))
+ for i in range(nr - 1):
+ for k in range(ring_n):
+ a, b = 1 + i * ring_n + k, 1 + i * ring_n + (k + 1) % ring_n
+ F += [(a, a + ring_n, b), (b, a + ring_n, b + ring_n)]
+ last = len(V) - 1
+ for k in range(ring_n):
+ F.append((last, 1 + (nr - 1) * ring_n + (k + 1) % ring_n, 1 + (nr - 1) * ring_n + k))
+ F = self._orient(V, F, [x, y, z])
+ P = V[F]
+ uv = np.stack([P[..., 0] / 3 + P[..., 1] / 5, P[..., 2] / 3], -1)
+ return self.mesh(V, F, colour, uv=uv, tex='rock', name='rock')
+
+ def tree(self, x, y, z, height=4.0, colour='#ffffff'):
+ """a juniper as two crossed textured quads with a hard alpha cut-out (the classic billboard tree)"""
+ rr = np.random.default_rng(self._seed())
+ a0 = rr.uniform(0, np.pi)
+ w = height * 0.7
+ for a in (a0, a0 + np.pi / 2):
+ d = np.array([np.cos(a), 0, np.sin(a)], np.float32) * w / 2
+ b = np.array([x, y, z], np.float32)
+ V = np.array([b - d, b + d, b + d + [0, height, 0], b - d + [0, height, 0]], np.float32)
+ F = np.array([(0, 1, 2), (0, 2, 3)])
+ uv = np.array([[(0, 1), (1, 1), (1, 0)], [(0, 1), (1, 0), (0, 0)]], np.float32) * 0.999
+ self.mesh(V, F, colour, uv=uv, tex='juniper', two_sided=True, cutout=True, glow=0.3, name='tree')
+
+ # ------------------------------------------------------------ objects
+ def torus(self, centre, axis, radius, tube, segs=14, sides=6, spin=0.0):
+ """faceted torus around `axis` -> (V, F) outward"""
+ a = _unit(axis)
+ e1 = _unit(np.cross(a, [0, 1, 0]) if abs(a[1]) < 0.9 else np.cross(a, [1, 0, 0]))
+ e2 = np.cross(a, e1)
+ V, C = [], []
+ for i in range(segs):
+ t = 2 * np.pi * i / segs + np.radians(spin)
+ d = e1 * np.cos(t) + e2 * np.sin(t)
+ c = np.asarray(centre, np.float32) + d * radius
+ for k in range(sides):
+ p = 2 * np.pi * k / sides + np.pi / sides
+ V.append(c + (d * np.cos(p) + a * np.sin(p)) * tube)
+ V = np.array(V, np.float32)
+ F, inside = [], []
+ for i in range(segs):
+ for k in range(sides):
+ p0 = i * sides + k; p1 = i * sides + (k + 1) % sides
+ q0 = ((i + 1) % segs) * sides + k; q1 = ((i + 1) % segs) * sides + (k + 1) % sides
+ F += [(p0, q0, p1), (p1, q0, q1)]
+ t = 2 * np.pi * (i + 0.5) / segs + np.radians(spin)
+ c = np.asarray(centre) + (e1 * np.cos(t) + e2 * np.sin(t)) * radius
+ inside += [c, c]
+ return V, self._orient(V, F, np.array(inside, np.float32))
+
+ def ring(self, centre, facing, radius=3.4, tube=0.6, colour=GOLD, segs=12, sides=5, glow=0.28, spin=8.0, shine=4.0,
+ spec=2.0):
+ """a gold hoop to fly through: a faceted torus facing along `facing`; every facet flashes on its own"""
+ V, F = self.torus(centre, facing, radius, tube, segs, sides, spin)
+ return self.mesh(V, F, colour, spec=spec, shine=shine, glow=glow, name="ring")
+
+ def aircraft(self, pos, heading, roll=0.0, pitch=0.0, size=1.0, body=WHITE, trim='#1fa39c', canopy='#1d2c4c',
+ spinner='#f0742a', prop=True):
+ """a small low-wing stunt plane of ~230 triangles: octagonal fuselage, tapered wings with dihedral, tail,
+ bubble canopy, spinner, plus a half-transparent propeller disc with a brighter tip circle and two smeared
+ blades; `roll` + banks to the right"""
+ B = _basis(heading, roll, pitch)
+ O = np.asarray(pos, np.float32)
+ place = lambda v: O + (np.asarray(v, np.float32) * size) @ B
+ parts = [] # (V local, F, colour per face, spec)
+ # fuselage: octagonal sections (z, half-width, half-height, y)
+ st = [(-2.1, 0.06, 0.09, 0.2), (-1.45, 0.17, 0.2, 0.1), (-0.55, 0.33, 0.36, 0.02), (0.4, 0.4, 0.42, 0.0),
+ (1.0, 0.38, 0.38, -0.02), (1.38, 0.29, 0.29, -0.03)]
+ ang = (np.arange(8) + 0.5) * np.pi / 4
+ rings = [np.stack([np.cos(ang) * hw, y + np.sin(ang) * hh, np.full(8, z)], 1) for z, hw, hh, y in st]
+ V = np.vstack(rings); F = []
+ for i in range(len(st) - 1):
+ for k in range(8):
+ a, b = i * 8 + k, i * 8 + (k + 1) % 8
+ F += [(a, b, a + 8), (b, b + 8, a + 8)]
+ V = np.vstack([V, [0, st[0][3], st[0][0] - 0.05], [0, st[-1][3], st[-1][0]]])
+ t0, t1 = len(V) - 2, len(V) - 1
+ F += [(k, (k + 1) % 8, t0) for k in range(8)]
+ F += [((len(st) - 1) * 8 + k, (len(st) - 1) * 8 + (k + 1) % 8, t1) for k in range(8)]
+ F = self._orient(V, F, [0, 0, 0])
+ zc = V[F][:, :, 2].mean(1)
+ yc = V[F][:, :, 1].mean(1)
+ cf = np.where((zc > 0.75)[:, None], hexc(trim), hexc(body))
+ cf = np.where(((zc > -1.2) & (zc < -0.85))[:, None], hexc(trim), cf)
+ cf = np.where(((zc > 0.75) & (yc > 0.25))[:, None], hexc('#22323a'), cf) # anti-glare panel
+ parts.append((V, F, cf, 0.25))
+
+ def wing(x0, x1, z0r, z1r, z0t, z1t, y0, y1, tr, tt, tip_col, split=0.72):
+ """half-wing from x0 (root) to x1 (tip): diamond section (trailing edge, top, leading edge, bottom);
+ the outer segment is painted tip_col"""
+ secs = []
+ for f in (0.0, split, 1.0):
+ x = x0 + (x1 - x0) * f
+ za, zb = z0r + (z0t - z0r) * f, z1r + (z1t - z1r) * f
+ y = y0 + (y1 - y0) * f
+ t = tr + (tt - tr) * f
+ secs.append([(x, y, zb), (x, y + t / 2, za + (zb - za) * 0.3), (x, y, za), (x, y - t / 2, za + (zb - za) * 0.3)])
+ S = np.array(secs, np.float32)
+ V = S.reshape(-1, 3)
+ F, C, I = [], [], []
+ for i in range(2):
+ mid = (S[i].mean(0) + S[i + 1].mean(0)) / 2
+ for k in range(4):
+ a, b = i * 4 + k, i * 4 + (k + 1) % 4
+ F += [(a, b, a + 4), (b, b + 4, a + 4)]
+ C += [tip_col if i == 1 else body] * 2
+ I += [mid, mid]
+ F += [(8, 9, 10), (8, 10, 11), (0, 1, 2), (0, 2, 3)]
+ C += [tip_col] * 2 + [body] * 2
+ I += [(S[1].mean(0) + S[2].mean(0)) / 2] * 2 + [(S[0].mean(0) + S[1].mean(0)) / 2] * 2
+ F = self._orient(V, F, np.array(I, np.float32))
+ return V, F, np.array([hexc(c) for c in C]), 0.3
+
+ for sgn in (1, -1):
+ for (V, F, C, sp) in [wing(0.25, 2.25, 0.85, -0.25, 0.62, 0.12, -0.22, 0.02, 0.16, 0.07, trim),
+ wing(0.1, 0.95, -1.4, -2.05, -1.6, -2.0, 0.12, 0.16, 0.08, 0.05, trim, split=0.6)]:
+ V = V * [sgn, 1, 1]
+ if sgn < 0: F = F[:, [0, 2, 1]]
+ parts.append((V, F, C, sp))
+ # fin
+ fin = [[(0, 0.2, -2.12), (0.05, 0.2, -1.7), (0, 0.2, -1.3), (-0.05, 0.2, -1.7)],
+ [(0, 0.98, -2.12), (0.03, 0.98, -1.95), (0, 0.98, -1.8), (-0.03, 0.98, -1.95)]]
+ V = np.array(fin, np.float32).reshape(-1, 3)
+ Vf, Ff = self._prism(V[:4], V[4:], top=True)
+ parts.append((Vf, Ff, np.tile(hexc(trim), (len(Ff), 1)), 0.3))
+ # canopy: half-octagon bubble
+ cs = [(-0.35, 0.12, 0.05), (-0.05, 0.27, 0.2), (0.35, 0.29, 0.24), (0.62, 0.22, 0.12), (0.78, 0.1, 0.0)]
+ ca = np.linspace(0, np.pi, 5)
+ rings = [np.stack([np.cos(ca) * hw, 0.36 + np.sin(ca) * hh, np.full(5, z)], 1) for z, hw, hh in cs]
+ V = np.vstack(rings); F = []
+ for i in range(len(cs) - 1):
+ for k in range(4):
+ a, b = i * 5 + k, i * 5 + k + 1
+ F += [(a, b, a + 5), (b, b + 5, a + 5)]
+ F = self._orient(V, F, [0, 0.3, 0.2])
+ parts.append((V, F, np.tile(hexc(canopy), (len(F), 1)), 1.4))
+ # spinner
+ sa = np.arange(6) * np.pi / 3
+ base = np.stack([np.cos(sa) * 0.17, -0.03 + np.sin(sa) * 0.17, np.full(6, 1.38)], 1)
+ V = np.vstack([base, [0, -0.03, 1.78]])
+ F = self._orient(V, [(k, (k + 1) % 6, 6) for k in range(6)], [0, -0.03, 1.45])
+ parts.append((V, F, np.tile(hexc(spinner), (len(F), 1)), 0.6))
+ for V, F, C, sp in parts:
+ self.mesh(place(V), F, C, spec=sp, shine=12, name='plane')
+ if prop: # the blur of a spinning propeller: a half-transparent disc
+ pa = np.arange(14) * 2 * np.pi / 14
+ rim = np.stack([np.cos(pa) * 1.0, -0.03 + np.sin(pa) * 1.0, np.full(14, 1.5)], 1)
+ V = np.vstack([rim, [0, -0.03, 1.5]])
+ F = [(k, (k + 1) % 14, 14) for k in range(14)]
+ self.mesh(place(V), F, '#ece8dc', blend='half', alpha=0.36, two_sided=True, lit=False, name='prop')
+ ra = np.arange(14) * 2 * np.pi / 14 # the tip circle, a little brighter
+ outer = np.stack([np.cos(ra) * 1.0, -0.03 + np.sin(ra) * 1.0, np.full(14, 1.49)], 1)
+ inner = np.stack([np.cos(ra) * 0.88, -0.03 + np.sin(ra) * 0.88, np.full(14, 1.49)], 1)
+ V = np.vstack([outer, inner])
+ F = [f for k in range(14) for f in ((k, (k + 1) % 14, 14 + k), ((k + 1) % 14, 14 + (k + 1) % 14, 14 + k))]
+ self.mesh(place(V), F, '#ffffff', blend='half', alpha=0.3, two_sided=True, lit=False, name='prop')
+ for a in (0.5, 0.5 + np.pi): # two smeared blades, a little darker
+ d = np.array([np.cos(a), np.sin(a), 0]); e = np.array([-np.sin(a), np.cos(a), 0])
+ c0 = np.array([0, -0.03, 1.51])
+ V = np.array([c0 + e * 0.07, c0 + d * 0.98 + e * 0.17, c0 + d * 0.98 - e * 0.05, c0 - e * 0.04])
+ self.mesh(place(V), [(0, 1, 2), (0, 2, 3)], '#3a3630', blend='half', alpha=0.4, two_sided=True,
+ lit=False, name='prop')
+ return B
+
+ def shadow(self, x, z, y, radius=1.6, stretch=1.0, heading=(0, 0, 1), strength=0.2, sides=10):
+ """the blob shadow of the era: a dark polygon laid on the ground straight below an object ('sub' blend,
+ drawn after the surface it lies on)"""
+ h = _unit(heading); s = np.cross([0, 1, 0], h)
+ a = np.arange(sides) * 2 * np.pi / sides
+ rim = np.array([x, y, z]) + np.outer(np.cos(a) * radius, s) + np.outer(np.sin(a) * radius * stretch, h)
+ V = np.vstack([rim, [x, y, z]])
+ F = [(k, (k + 1) % sides, sides) for k in range(sides)]
+ return self.mesh(V, F, np.full(3, strength), blend='sub', lit=False, two_sided=True, bias=-6.0, name='shadow')
+
+ def sparkle(self, p, size=1.2, colour='#ffffff', strength=1.0):
+ """an additive four-point star sprite facing the camera"""
+ r, u = self.R[0] * size / 2, self.R[1] * size / 2
+ p = np.asarray(p, np.float32)
+ V = np.array([p - r - u, p + r - u, p + r + u, p - r + u])
+ uv = np.array([[(0, 1), (1, 1), (1, 0)], [(0, 1), (1, 0), (0, 0)]], np.float32) * 0.999
+ return self.mesh(V, [(0, 1, 2), (0, 2, 3)], _c(colour) * strength, uv=uv, tex='spark', blend='add',
+ lit=False, two_sided=True, bias=-3.0, name='fx')
+
+ def flare(self, strength=1.0, elements=None):
+ """a lens flare in screen space from the sun through the centre of the frame (only if the sun is not
+ hidden behind geometry): hexagons, rings and discs in 'add' mode"""
+ els = elements or [(0.0, 12, 'disc', '#fff4d0', 0.35), (0.16, 4, 'hex', '#ffd890', 0.3),
+ (0.3, 2, 'disc', '#ffffff', 0.45), (0.44, 2, 'disc', '#a8f0b0', 0.4),
+ (0.62, 3, 'disc', '#a8c8ff', 0.4), (0.8, 5, 'hex', '#e8b0ff', 0.2),
+ (1.15, 15, 'hex', '#a0d0ff', 0.07), (1.15, 15, 'hexring', '#c8e0ff', 0.2)]
+ self.post.append(('flare', strength, els))
+
+ # ------------------------------------------------------------ rendering
+ def _gather(self, textures):
+ """all meshes as one triangle list. With textures off, surfaces show their flat preview colour (the texel
+ under each face centre); additive sprites keep their texture, they are light, not surface"""
+ M = self.meshes
+ cat = lambda k: np.concatenate([m[k] for m in M])
+ per = lambda k, dt=np.float32: np.concatenate([np.full(len(m['P']), m[k], dt) for m in M])
+ names = sorted({m['tex'] for m in M if m['tex'] is not None})
+ use = [m['tex'] is not None and (textures or m['blend'] == BLEND['add']) for m in M]
+ tid = np.concatenate([np.full(len(m['P']), names.index(m['tex']) if u else -1, np.int32) for m, u in zip(M, use)])
+ col = np.concatenate([m['col'] if (u or m['tex'] is None) else m['flat'] for m, u in zip(M, use)])
+ return dict(P=cat('P'), N=cat('N'), col=col, uv=cat('uv'), tid=tid, texs=[self.textures[t] for t in names],
+ lit=per('lit', bool), spec=per('spec'), shine=per('shine'), blend=per('blend', np.int32),
+ alpha=per('alpha'), two=per('two', bool), fog=per('fog', bool), bias=per('bias'),
+ cut=per('cutout', bool), glow=per('glow'))
+
+ def _render(self, wire=False, fog=True, textures=True):
+ fb = self._sky().copy()
+ self.cov = np.zeros((self.h, self.w), bool)
+ if not self.meshes: return fb
+ G = self._gather(textures)
+ E, R = self.eye, self.R
+ P, N = G['P'], G['N']
+ cen = P.mean(1)
+ front = ((E - cen) * N).sum(-1) > 0
+ keep = front | G['two']
+ N = np.where(front[:, None], N, -N)
+ Pc = (P - E) @ R.T
+ z = Pc[..., 2]
+ keep &= ~(z < self.near).all(1) & ~(z > self.far).all(1)
+ for ax, t in ((0, self.tanx), (1, self.tany)):
+ keep &= ~((Pc[..., ax] - Pc[..., 2] * t * 1.02) > 0).all(1)
+ keep &= ~((Pc[..., ax] + Pc[..., 2] * t * 1.02) < 0).all(1)
+ idx = np.nonzero(keep)[0]
+ # ---- flat shading (one colour per face)
+ n = N[idx]
+ V = _unit(E - cen[idx])
+ Ls = self.L_shade
+ diff = np.clip(n @ Ls, 0, 1)
+ hemi = (0.5 + 0.5 * n[:, 1])[:, None]
+ amb = self.gnd_amb * (1 - hemi) + self.sky_amb * hemi
+ shade = amb + self.sun_col * diff[:, None]
+ H = _unit(V + Ls)
+ spec = G['spec'][idx, None] * np.clip((n * H).sum(-1), 0, 1)[:, None] ** G['shine'][idx, None] * self.sun_col
+ glow = G['glow'][idx, None]
+ shade = shade * (1 - glow) + glow * 1.0
+ lit = G['lit'][idx, None]
+ mul = np.where(lit, G['col'][idx] * shade, G['col'][idx]).astype(np.float32)
+ add = np.where(lit, spec, 0).astype(np.float32)
+ # ---- per-vertex fog, near-plane clipping
+ Pc = Pc[idx]; uv = G['uv'][idx]
+ tri_P, tri_uv, src = [Pc], [uv], [np.arange(len(idx))]
+ cross = (Pc[..., 2] < self.near).any(1)
+ good = ~cross
+ tri_P[0], tri_uv[0], src[0] = Pc[good], uv[good], src[0][good]
+ extra_P, extra_uv, extra_src = [], [], []
+ for k in np.nonzero(cross)[0]:
+ poly = list(zip(Pc[k], uv[k]))
+ out = []
+ for i in range(3):
+ (a, ua), (b, ub) = poly[i], poly[(i + 1) % 3]
+ ina, inb = a[2] >= self.near, b[2] >= self.near
+ if ina: out.append((a, ua))
+ if ina != inb:
+ t = (self.near - a[2]) / (b[2] - a[2])
+ out.append((a + (b - a) * t, ua + (ub - ua) * t))
+ for i in range(1, len(out) - 1):
+ extra_P.append([out[0][0], out[i][0], out[i + 1][0]])
+ extra_uv.append([out[0][1], out[i][1], out[i + 1][1]])
+ extra_src.append(k)
+ if extra_P:
+ tri_P.append(np.array(extra_P, np.float32)); tri_uv.append(np.array(extra_uv, np.float32))
+ src.append(np.array(extra_src))
+ Pc = np.concatenate(tri_P); uv = np.concatenate(tri_uv); src = np.concatenate(src)
+ gi = idx[src]
+ zc = Pc[..., 2]
+ if fog and self.fog_on:
+ fv = np.clip((np.linalg.norm(Pc, axis=-1) - self.fog_near) / (self.fog_far - self.fog_near), 0, 1)
+ fv = fv * G['fog'][gi, None]
+ else:
+ fv = np.zeros_like(zc)
+ sx = np.round(self.cx + self.f * Pc[..., 0] / zc).clip(-30000, 30000).astype(np.int32)
+ sy = np.round(self.cy - self.f * Pc[..., 1] / zc).clip(-30000, 30000).astype(np.int32)
+ key = zc.mean(1) + G['bias'][gi]
+ order = np.argsort(-key, kind='stable')
+ zb = np.full((self.h, self.w), np.inf, np.float32) if self.zbuffer else None
+ fogc = self.fog_col.astype(np.float32)
+ texs = G['texs']; tid = G['tid'][gi]; blend = G['blend'][gi]; alpha = G['alpha'][gi]; cut = G['cut'][gi]
+ mul = mul[src]; add = add[src]
+ Wf, Hf = self.w, self.h
+ wire_fill, wire_line = hexc('#0b1424'), hexc('#9dfcd0')
+ for k in order:
+ X = sx[k]; Y = sy[k]
+ ax, bx, cx = int(X[0]), int(X[1]), int(X[2]); ay, by, cy = int(Y[0]), int(Y[1]), int(Y[2])
+ area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax)
+ if area == 0: continue
+ vi = [0, 1, 2]
+ if area < 0:
+ bx, cx, by, cy = cx, bx, cy, by; vi = [0, 2, 1]; area = -area
+ x0, x1 = max(min(ax, bx, cx), 0), min(max(ax, bx, cx), Wf)
+ y0, y1 = max(min(ay, by, cy), 0), min(max(ay, by, cy), Hf)
+ if x0 >= x1 or y0 >= y1: continue
+ px = np.arange(x0, x1, dtype=np.int64)[None, :] * 2 + 1
+ py = np.arange(y0, y1, dtype=np.int64)[:, None] * 2 + 1
+
+ def edge(Ax, Ay, Bx, By):
+ e = (2 * Bx - 2 * Ax) * (py - 2 * Ay) - (2 * By - 2 * Ay) * (px - 2 * Ax)
+ dx, dy = Bx - Ax, By - Ay
+ return e, (dy < 0) or (dy == 0 and dx > 0)
+ ea, ta = edge(bx, by, cx, cy)
+ eb, tb = edge(cx, cy, ax, ay)
+ ec, tc = edge(ax, ay, bx, by)
+ ins = ((ea > 0) | ((ea == 0) & ta)) & ((eb > 0) | ((eb == 0) & tb)) & ((ec > 0) | ((ec == 0) & tc))
+ yy, xx = np.nonzero(ins)
+ if len(yy) == 0: continue
+ A2 = float(4 * area)
+ wa, wb, wc = ea[yy, xx] / A2, eb[yy, xx] / A2, ec[yy, xx] / A2
+ Yp, Xp = yy + y0, xx + x0
+ f3 = fv[k][vi]
+ fpx = wa * f3[0] + wb * f3[1] + wc * f3[2]
+ if zb is not None:
+ z3 = zc[k][vi]
+ zpx = wa * z3[0] + wb * z3[1] + wc * z3[2]
+ ok = zpx < zb[Yp, Xp]
+ if not ok.any(): continue
+ Yp, Xp, wa, wb, wc, fpx, zpx = Yp[ok], Xp[ok], wa[ok], wb[ok], wc[ok], fpx[ok], zpx[ok]
+ bm = blend[k]
+ if wire:
+ if bm != 0: continue
+ fb[Yp, Xp] = wire_fill * (1 - fpx[:, None]) + fogc * fpx[:, None] * 0.25
+ for (p, q) in ((0, 1), (1, 2), (2, 0)):
+ P0 = (int(X[p]), int(Y[p])); P1 = (int(X[q]), int(Y[q]))
+ m = max(abs(P1[0] - P0[0]), abs(P1[1] - P0[1])) + 1
+ if m > 4000: continue
+ lx = np.round(np.linspace(P0[0], P1[0], m)).astype(int)
+ ly = np.round(np.linspace(P0[1], P1[1], m)).astype(int)
+ okl = (lx >= 0) & (lx < Wf) & (ly >= 0) & (ly < Hf)
+ ff = (fv[k][p] + fv[k][q]) / 2
+ fb[ly[okl], lx[okl]] = wire_line * (1 - ff) + wire_fill * ff
+ self.cov[Yp, Xp] = True
+ continue
+ t = tid[k]
+ src_c = np.broadcast_to(mul[k], (len(Yp), 3))
+ a_px = None
+ if t >= 0:
+ T = texs[t]
+ u3 = uv[k][vi]
+ upx = wa * u3[0, 0] + wb * u3[1, 0] + wc * u3[2, 0]
+ vpx = wa * u3[0, 1] + wb * u3[1, 1] + wc * u3[2, 1]
+ iu = np.floor(upx * T.shape[1]).astype(np.int64) % T.shape[1]
+ iv = np.floor(vpx * T.shape[0]).astype(np.int64) % T.shape[0]
+ texel = T[iv, iu]
+ if cut[k]:
+ ok = texel[:, 3] > 0.5
+ Yp, Xp, fpx, texel = Yp[ok], Xp[ok], fpx[ok], texel[ok]
+ if not len(Yp): continue
+ if zb is not None: zpx = zpx[ok]
+ src_c = texel[:, :3] * mul[k]
+ a_px = texel[:, 3]
+ src_c = src_c + add[k]
+ fp = fpx[:, None]
+ if bm == 0:
+ fb[Yp, Xp] = src_c * (1 - fp) + fogc * fp
+ self.cov[Yp, Xp] = True
+ if zb is not None: zb[Yp, Xp] = zpx
+ elif bm == 1:
+ a = alpha[k] * (a_px[:, None] if a_px is not None else 1)
+ fb[Yp, Xp] = fb[Yp, Xp] * (1 - a) + (src_c * (1 - fp) + fogc * fp) * a
+ elif bm == 2 or bm == 4:
+ a = (a_px[:, None] if a_px is not None else 1) * (1 if bm == 2 else 0.25)
+ fb[Yp, Xp] = fb[Yp, Xp] + src_c * (1 - fp) * a
+ elif bm == 3:
+ fb[Yp, Xp] = fb[Yp, Xp] - src_c * (1 - fp)
+ return np.clip(fb, 0, 1)
+
+ def _post(self, fb, fx=True):
+ for op in self.post:
+ if op[0] == 'flare' and fx:
+ fb = self._flare(fb, op[1], op[2])
+ return fb
+
+ def _flare(self, fb, strength, els):
+ d = (self.L @ self.R.T)
+ if d[2] <= 0.05: return fb
+ sx, sy = self.cx + self.f * d[0] / d[2], self.cy - self.f * d[1] / d[2]
+ if not (0 <= sx < self.w and 0 <= sy < self.h): return fb
+ if self.cov[int(sy), int(sx)]: return fb
+ yy, xx = np.mgrid[0:self.h, 0:self.w].astype(np.float32) + 0.5
+ cxs, cys = self.cx, self.cy
+ for t, rad, kind, col, a in els:
+ px, py = sx + (cxs - sx) * t * 2, sy + (cys - sy) * t * 2
+ dx, dy = xx - px, yy - py
+ if kind in ('hex', 'hexring'):
+ ang = np.arctan2(dy, dx)
+ rr = np.hypot(dx, dy) * np.cos((ang % (np.pi / 3)) - np.pi / 6) / np.cos(np.pi / 6)
+ if kind == 'hex':
+ m = (rr < rad).astype(np.float32) * (0.6 + 0.4 * (rr / rad))
+ else:
+ m = ((rr < rad) & (rr >= rad - 1.2)).astype(np.float32)
+ elif kind == 'ring':
+ rr = np.hypot(dx, dy)
+ m = ((rr < rad) & (rr > rad * 0.78)).astype(np.float32)
+ else:
+ rr = np.hypot(dx, dy)
+ m = np.clip(1 - rr / rad, 0, 1) ** 1.5
+ fb = fb + hexc(col) * (m * a * strength)[..., None]
+ return np.clip(fb, 0, 1)
+
+ def _crush(self, fb):
+ """15-bit colour through the 4x4 ordered dither: 8-bit value + offset, then truncate to 5 bits"""
+ v = fb * 255
+ if self.dither:
+ D = np.tile(DITHER, (self.h // 4 + 1, self.w // 4 + 1))[:self.h, :self.w]
+ v = v + D[..., None]
+ step = 256 >> self.bits
+ q = np.clip(np.floor(v / step), 0, (1 << self.bits) - 1)
+ q = q * step + q // (1 << (self.bits - 3)) if self.bits == 5 else q * step
+ return (q / 255).astype(np.float32)
+
+ def composite(self, wire=False, fog=True, textures=True, fx=True, hud=True):
+ fb = self._render(wire=wire, fog=fog, textures=textures)
+ fb = self._post(fb, fx=fx and not wire)
+ q = self._crush(fb)
+ if hud:
+ for op in self.hud: op(q)
+ img = Image.fromarray((np.clip(q, 0, 1) * 255 + 0.5).astype(np.uint8))
+ return img.resize((self.W, self.H), Image.NEAREST)
+
+ # ------------------------------------------------------------ HUD (framebuffer pixels)
+ def _glyphs(self, s, scale=1, bold=True, italic=0, spacing=1):
+ cols = []
+ for ch in s:
+ g = FONT.get(ch, FONT.get(ch.upper(), FONT[' ']))
+ a = np.array([[c == '#' for c in row] for row in g], bool)
+ if bold:
+ a = np.concatenate([a, np.zeros((7, 1), bool)], 1)
+ a[:, 1:] |= a[:, :-1].copy()
+ cols += [a, np.zeros((7, spacing), bool)]
+ m = np.concatenate(cols[:-1], 1) if cols else np.zeros((7, 1), bool)
+ m = np.kron(m, np.ones((scale, scale), bool))
+ if italic:
+ h = m.shape[0]
+ out = np.zeros((h, m.shape[1] + italic), bool)
+ for r in range(h):
+ o = int(round(italic * (h - 1 - r) / max(h - 1, 1)))
+ out[r, o:o + m.shape[1]] = m[r]
+ m = out
+ return m
+
+ def text_width(self, s, scale=1, bold=True, italic=0, spacing=1):
+ return self._glyphs(s, scale, bold, italic, spacing).shape[1]
+
+ def _stamp(self, q, m, x, y, fill, outline=BLACK, shadow=True):
+ H, W = m.shape
+ pad = 2
+ M = np.zeros((H + 2 * pad, W + 2 * pad), bool)
+ M[pad:pad + H, pad:pad + W] = m
+ O = M.copy()
+ for dy in (-1, 0, 1):
+ for dx in (-1, 0, 1):
+ O |= np.roll(np.roll(M, dy, 0), dx, 1)
+ S = np.roll(np.roll(O, 1, 0), 1, 1) & ~O
+ x0, y0 = int(x) - pad, int(y) - pad
+ ys, xs = np.nonzero(S | O)
+ Y, X = ys + y0, xs + x0
+ ok = (Y >= 0) & (Y < self.h) & (X >= 0) & (X < self.w)
+ if shadow:
+ sel = S[ys, xs] & ok
+ q[Y[sel], X[sel]] = q[Y[sel], X[sel]] * 0.35
+ if outline is not None:
+ sel = O[ys, xs] & ~M[ys, xs] & ok
+ q[Y[sel], X[sel]] = _q5(_c(outline))
+ ys, xs = np.nonzero(M)
+ Y, X = ys + y0, xs + x0
+ ok = (Y >= 0) & (Y < self.h) & (X >= 0) & (X < self.w)
+ if isinstance(fill, (tuple, list)) and not isinstance(fill[0], (int, float)):
+ cols = [_c(c) for c in fill]
+ t = (ys - pad) / max(H - 1, 1)
+ seg = np.clip(t * (len(cols) - 1), 0, len(cols) - 1 - 1e-6)
+ i0 = seg.astype(int); fr = (seg - i0)[:, None]
+ col = np.array(cols)[i0] * (1 - fr) + np.array(cols)[i0 + 1] * fr
+ else:
+ col = np.broadcast_to(_c(fill), (len(ys), 3))
+ q[Y[ok], X[ok]] = _q5(col[ok])
+
+ def text(self, s, x, y, scale=1, fill=WHITE, outline=BLACK, shadow=True, italic=0, anchor='l', bold=True, spacing=1):
+ """bitmap HUD text at framebuffer pixel (x, y) = top-left (anchor 'l'), top-right ('r') or top-centre ('m').
+ fill is a colour or a list of colours for a top-to-bottom ramp"""
+ def op(q):
+ m = self._glyphs(s, scale, bold, italic, spacing)
+ xx = x - (m.shape[1] if anchor == 'r' else m.shape[1] // 2 if anchor == 'm' else 0)
+ self._stamp(q, m, xx, y, fill, outline, shadow)
+ self.hud.append(op)
+
+ def icon(self, kind, x, y, size=1):
+ """HUD icons: 'ring' (a little gold hoop), 'plane' (top view), 'clock'"""
+ pics = {
+ 'ring': [' #### ', ' #....# ', '#. .#', '#. .#', '#. .#', '#. .#', ' #....# ', ' #### '],
+ 'plane': [' # ', ' # ', ' ### ', '#########', ' ####### ', ' # ', ' ### ', ' # '],
+ 'clock': [' #### ', ' #....# ', '#...#..#', '#...#..#', '#...##.#', '#......#', ' #....# ', ' #### '],
+ }
+ cmap = {'ring': {'#': '#ffcc33', '.': '#b06a10'}, 'plane': {'#': '#f4f1e8'},
+ 'clock': {'#': '#f4f1e8', '.': '#5a6a8a'}}[kind]
+ rows = pics[kind]
+
+ def op(q):
+ for ch, col in cmap.items():
+ m = np.array([[c == ch for c in row] for row in rows], bool)
+ m = np.kron(m, np.ones((size, size), bool))
+ self._stamp(q, m, x, y, col, outline=BLACK if ch == '#' else None, shadow=ch == '#')
+ self.hud.append(op)
+
+ def counter(self, label, value, x, y, icon=None, anchor='l', label_fill=HUD_CYAN, fill=(HUD_YELLOW, HUD_ORANGE, '#d0501a'),
+ scale=2, italic=3):
+ """a labelled HUD counter: small label over big italic ramp digits, optional icon on the left"""
+ if icon:
+ self.icon(icon, x, y + 4, size=2)
+ x += 20
+ if anchor == 'r':
+ self.text(label, x, y, 1, label_fill, anchor='r')
+ self.text(value, x, y + 10, scale, list(fill), italic=italic, anchor='r')
+ else:
+ self.text(label, x, y, 1, label_fill)
+ self.text(value, x, y + 10, scale, list(fill), italic=italic)
+
+ def panel(self, x0, y0, x1, y1, colour='#101c3a', alpha=0.55, border='#a8c8ff'):
+ """a translucent HUD box with a 1 px light frame and dark corners cut"""
+ def op(q):
+ q[y0:y1, x0:x1] = q[y0:y1, x0:x1] * (1 - alpha) + _c(colour) * alpha
+ if border is not None:
+ b = _q5(_c(border))
+ q[y0, x0 + 1:x1 - 1] = b; q[y1 - 1, x0 + 1:x1 - 1] = b
+ q[y0 + 1:y1 - 1, x0] = b; q[y0 + 1:y1 - 1, x1 - 1] = b
+ q[...] = self._snap(q)
+ self.hud.append(op)
+
+ @staticmethod
+ def _snap(q):
+ v = np.clip(np.floor(q * 31 + 0.5), 0, 31)
+ return ((v * 8 + v // 4) / 255).astype(np.float32)
+
+ def gauge(self, x, y, value, segments=12, label='SPD', unit='KM/H', number=None, colours=(HUD_GREEN, HUD_YELLOW, HUD_RED)):
+ """a stepped speed bar: segments grow taller left to right, lit up to `value` (0..1), green -> yellow -> red"""
+ def op(q):
+ cols = [_c(c) for c in colours]
+ lit = int(round(value * segments))
+ for i in range(segments):
+ h = 4 + i // 2
+ sx = x + i * 4
+ t = i / max(segments - 1, 1) * (len(cols) - 1)
+ i0 = min(int(t), len(cols) - 2); fr = t - i0
+ c = cols[i0] * (1 - fr) + cols[i0 + 1] * fr
+ if i >= lit: c = np.array([0.18, 0.2, 0.26])
+ q[y + 10 - h - 1:y + 11, sx - 1:sx + 4] = 0
+ q[y + 10 - h:y + 10, sx:sx + 3] = _q5(c)
+ self.hud.append(op)
+ if label: self.text(label, x, y - 9, 1, HUD_CYAN)
+ if number is not None:
+ self.text(number, x + segments * 4 + 6, y - 6, 2, [HUD_YELLOW, HUD_ORANGE, '#d0501a'], italic=3)
+ self.text(unit, x + segments * 4 + 6 + self.text_width(number, 2, italic=3) + 4, y + 2, 1, HUD_CYAN)
+
+ def minimap(self, x0, y0, x1, y1, path, s0, s1, rings, done, plane, heading, finish=None, title=None,
+ band='#c98a52', river='#5fb8c8'):
+ """a translucent top-down course map, turned so the plane heads up: canyon band, river, hoops (passed dim,
+ next bright and boxed, later orange), finish flag, the plane as an arrow"""
+ self.panel(x0, y0, x1, y1)
+ def op(q):
+ h = _unit(np.array([heading[0], heading[2]], np.float32))
+ ss = np.arange(s0, s1, 1.0)
+ x, z, *_ = path.at(ss)
+ pts = np.stack([x, z], 1)
+ rot = np.array([[h[1], -h[0]], [h[0], h[1]]], np.float32) # world xz -> map (right, forward)
+ org = np.array([plane[0], plane[2]], np.float32)
+ Q = (pts - org) @ rot.T
+ lo, hi = Q.min(0), Q.max(0)
+ m = 6
+ sc = min((x1 - x0 - 2 * m) / max(hi[0] - lo[0], 1), (y1 - y0 - 2 * m - (8 if title else 0)) / max(hi[1] - lo[1], 1))
+ mid = (lo + hi) / 2
+ cxm, cym = (x0 + x1) / 2, (y0 + y1) / 2 + (4 if title else 0)
+ tomap = lambda P: np.stack([cxm + (P[..., 0] - mid[0]) * sc, cym - (P[..., 1] - mid[1]) * sc], -1)
+ M = tomap(Q)
+
+ def dots(P, r, col):
+ for px, py in P:
+ xi, yi = int(round(px)), int(round(py))
+ q[max(yi - r, y0 + 1):min(yi + r + 1, y1 - 1), max(xi - r, x0 + 1):min(xi + r + 1, x1 - 1)] = _q5(_c(col))
+ dots(M[::1], 2, band)
+ dots(M[::1], 0, river)
+ for i, rp in enumerate(rings):
+ R2 = tomap((np.array([[rp[0], rp[2]]], np.float32) - org) @ rot.T)
+ if i < done: dots(R2, 1, '#6a6a7a')
+ elif i == done:
+ xi, yi = int(round(R2[0, 0])), int(round(R2[0, 1]))
+ q[yi - 3:yi + 4, xi - 3:xi + 4] = _q5(_c('#000000'))
+ q[yi - 2:yi + 3, xi - 2:xi + 3] = _q5(_c(HUD_YELLOW))
+ q[yi - 1:yi + 2, xi - 1:xi + 2] = _q5(_c('#000000'))
+ else: dots(R2, 1, HUD_ORANGE)
+ if finish is not None:
+ F2 = tomap((np.array([[finish[0], finish[2]]], np.float32) - org) @ rot.T)[0]
+ xi, yi = int(round(F2[0])), int(round(F2[1]))
+ for j in range(-3, 3):
+ for i in range(-3, 3):
+ q[yi + j, xi + i] = _q5(_c('#ffffff' if (i + j) % 2 else '#000000'))
+ P2 = tomap(np.zeros((1, 2), np.float32))[0]
+ xi, yi = int(round(P2[0])), int(round(P2[1]))
+ arrow = [' # ', ' # ', ' ### ', ' ### ', '#####', '## ##']
+ for j, row in enumerate(arrow):
+ for i, c in enumerate(row):
+ if c == '#': q[yi - 3 + j, xi - 2 + i] = _q5(_c('#ffffff'))
+ self.hud.append(op)
+ if title: self.text(title, (x0 + x1) // 2, y0 + 3, 1, HUD_CYAN, anchor='m', shadow=False)
+
+ # ------------------------------------------------------------ output
+ def stage(self, name, wire=False, fog=True, textures=True, fx=True, hud=True):
+ """snapshot for the draw-on GIF; wire=True draws hidden-line wireframe, fog/textures can be held back"""
+ if self.record:
+ self.stages.append((name, self.composite(wire=wire, fog=fog, textures=textures, fx=fx, hud=hud)))
+
+ 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
diff --git a/lib/mosaic.py b/lib/mosaic.py
new file mode 100644
index 0000000..475ef06
--- /dev/null
+++ b/lib/mosaic.py
@@ -0,0 +1,970 @@
+"""mosaic — a Roman floor mosaic: thousands of hand-cut stone and glass tesserae pressed in rows into lime mortar,
+grouted, polished and then two thousand years old (numpy + Pillow only).
+
+Model -- the way a mosaicist actually works:
+ cartoon a hidden full-size colour map (the "cartoon") painted with flat colours and gradients. Nobody ever
+ sees it; every stone that is set looks at the cartoon under itself, takes the mean colour and picks
+ the nearest stone in the box (`STONES`), with a little noise so that tone boundaries are dithered
+ the way a mosaicist mixes two stones. Explicit colours (outlines, letters, eyes) skip the cartoon.
+ sinopia before laying, the design is brushed in red ochre on the wet setting bed; `sinopia()` draws it and
+ it stays visible wherever no stone has been set yet (the first stage of the animation).
+ andamento the *flow* of the rows is what makes a mosaic read as a mosaic. Every laying method traces
+ iso-lines of a scalar field (marching squares on a distance field or on a plain coordinate) and
+ walks along each line cutting it into stones:
+ line one row along a path (letters, fins, rigging, net cords);
+ outline the first row(s) just inside a figure's edge, usually in a dark stone;
+ fill rows that follow the outline inward (opus vermiculatum). With wrap=True they also flow
+ round any stone already set inside the figure (an eye, a gill line), the way a
+ mosaicist rings an eye with concentric rows;
+ halo one or two background rows that follow the outline of everything already set, outside;
+ rows the background in straight (or wavy, any field) rows: opus tessellatum;
+ frame rows parallel to the sides of a rectangle, mitred at the corners, for borders;
+ tuck small filler pieces cut to fit the holes that are left.
+ A row is fitted with a whole number of stones, so stones are a little longer or shorter than
+ average; on a curve each stone becomes a slight wedge (its corners are offset along the local
+ normals). Rows are split at sharp corners. Stones near a figure's spine stop at the ridge of the
+ distance field, so the two sides of a fish meet along its back instead of overlapping.
+ stones every tessera is a small convex polygon: four corners jittered, now and then a corner knocked off,
+ a degree or two of rotation, its own height and a slight tilt, because they are set by hand.
+ A stone that would land mostly on stones already set is rejected; one that overlaps a little is
+ cut to fit (earlier stones win, and keep a grout gap). Materials: limestone (matte, mottled),
+ marble (veins, a little gloss), smalti glass (saturated, glossy, bubbles) and terracotta (porous).
+ light rendered at `ss` x supersampling as a height field: stone tops are domed and their edges worn round
+ (each stone's own signed distance gives the bevel), grout sits lower with sand in it, the bed lower
+ still. One raking light from the upper left: Lambert + Blinn-Phong per material, cast shadows from
+ each stone onto the grout, ambient occlusion in the joints, the per-stone tilt making neighbouring
+ stones of the same colour catch the light differently.
+ time `lacuna()` loses the stones in a patch: the old bed shows, with the sockets of the lost stones
+ still printed in it; `crack()` runs a settling crack through stones and joints; `patina()` puts
+ dirt in the joints and wears the polish.
+
+ from mosaic import Mosaic
+ m = Mosaic(1920, 1080, seed=1, tile=13)
+ fish = m.ellipse(960, 540, 160, 60)
+ m.shade(fish, 'slate', 'white', (960, 480), (960, 600)) # the cartoon: dark back, pale belly
+ m.sinopia(fish); m.stage('sinopia')
+ m.point(1060, 530, 'black', 9, 'round') # the eye first
+ m.outline(fish, 'black', size=9); m.fill(fish, size=9) # vermiculatum, rows ring the eye
+ m.halo(rows=2, stones=['white', 'bone']) # background rows hugging the figure
+ m.rows(m.free(), stones=['white', 'bone', 'cream']) # tessellatum for the rest
+ m.save('out.jpg')
+Coordinates are output pixels, y down; angles in degrees, counter-clockwise; masks are float (H, W) in 0..1.
+"""
+import os
+import numpy as np
+from PIL import Image, ImageDraw
+from core import blur, noise2d, smoothstep, polygon_mask, spline, fbm1d, height_shadow
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+# ---------------------------------------------------------------- the box of stones
+MATERIALS = ('stone', 'marble', 'glass', 'terracotta')
+STONES = {
+ 'white': ('#ece5d4', 'marble'), 'bone': ('#dfd5bd', 'stone'), 'cream': ('#d2c29f', 'stone'),
+ 'buff': ('#bfa980', 'stone'), 'grey': ('#a49e93', 'stone'), 'slate': ('#6c6964', 'stone'),
+ 'black': ('#2a2725', 'stone'), 'umber': ('#53382a', 'stone'), 'brown': ('#7c5437', 'stone'),
+ 'ochre': ('#bf924a', 'stone'), 'yellow': ('#d8b75f', 'stone'), 'red': ('#9c3d2a', 'stone'),
+ 'brick': ('#b45a3b', 'terracotta'), 'pink': ('#cd9780', 'marble'), 'rose': ('#e2bca7', 'marble'),
+ 'green': ('#5e6d4b', 'stone'), 'navy': ('#1c3453', 'glass'), 'blue': ('#2b5a88', 'glass'),
+ 'sky': ('#5a8eba', 'glass'), 'pale': ('#9bbfd3', 'glass'), 'teal': ('#2e7c80', 'glass'),
+ 'scarlet': ('#c02e23', 'glass'), 'flame': ('#dc6326', 'glass'), 'gold': ('#e5b039', 'glass'),
+}
+SINOPIA = '#a9563c'
+# stone marble glass terra
+_GLOSS = np.array([9.0, 28.0, 70.0, 5.0], np.float32)
+_SPEC = np.array([0.035, 0.09, 0.34, 0.02], np.float32)
+_MOTTLE = np.array([0.075, 0.04, 0.03, 0.09], np.float32)
+
+
+def _opp(c):
+ """rgb -> (lightness, red-green, yellow-blue): stones are matched on hue first, so greys stay grey"""
+ c = np.asarray(c, np.float32)
+ return np.stack([c[..., 0] * 0.3 + c[..., 1] * 0.59 + c[..., 2] * 0.11, c[..., 0] - c[..., 1],
+ (c[..., 0] + c[..., 1]) * 0.5 - c[..., 2]], -1)
+
+
+# ---------------------------------------------------------------- distance fields and iso-lines
+def _shift_fill(a, dy, dx, fill):
+ """out[y, x] = a[y + dy, x + dx], `fill` where that falls outside"""
+ H, W = a.shape
+ out = np.full_like(a, fill)
+ if abs(dy) >= H or abs(dx) >= W: return out
+ ys, yd = (slice(dy, H), slice(0, H - dy)) if dy >= 0 else (slice(0, H + dy), slice(-dy, H))
+ xs, xd = (slice(dx, W), slice(0, W - dx)) if dx >= 0 else (slice(0, W + dx), slice(-dx, W))
+ out[yd, xd] = a[ys, xs]
+ return out
+
+
+def edt(seeds, reach=None):
+ """Euclidean distance from every pixel to the nearest True pixel of `seeds` (jump flooding, numpy only).
+ `reach` limits the first jump: distances beyond about 2 x reach may be overestimated (fine for row layout)."""
+ H, W = seeds.shape
+ if not seeds.any():
+ return np.full((H, W), 1e6, np.float32)
+ yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)
+ far = np.float32(-1e5)
+ sy = np.where(seeds, yy, far).astype(np.float32)
+ sx = np.where(seeds, xx, far).astype(np.float32)
+ best = np.where(seeds, 0, 1e12).astype(np.float32)
+ top = max(H, W) if reach is None else min(max(H, W), int(reach))
+ step = 1 << int(np.ceil(np.log2(max(top, 2))))
+ steps = []
+ while step >= 1:
+ steps.append(step); step //= 2
+ for st in steps + [1]:
+ for dy in (-st, 0, st):
+ for dx in (-st, 0, st):
+ if dx == 0 and dy == 0: continue
+ cy = _shift_fill(sy, dy, dx, far); cx = _shift_fill(sx, dy, dx, far)
+ d = (yy - cy) ** 2 + (xx - cx) ** 2
+ bt = d < best
+ sy = np.where(bt, cy, sy); sx = np.where(bt, cx, sx); best = np.where(bt, d, best)
+ return np.sqrt(best)
+
+
+def maxfilt(a, r):
+ """square max filter of radius r (separable, doubling shifts)"""
+ r = int(r)
+ out = a.copy()
+ for ax in (0, 1):
+ cur, span = out, 0
+ while span < r:
+ st = min(span + 1, r - span)
+ dy, dx = (st, 0) if ax == 0 else (0, st)
+ cur = np.maximum(np.maximum(cur, _shift_fill(cur, dy, dx, -np.inf)), _shift_fill(cur, -dy, -dx, -np.inf))
+ span += st
+ out = cur
+ return out
+
+
+def iso_lines(f, step, offset=0.5):
+ """every iso-line f = (k + offset) * step of the field f (NaN = outside), by marching squares.
+ returns [(k, points (n, 2) as x, y in pixel-centre coordinates, closed)]"""
+ h, w = f.shape
+ with np.errstate(invalid='ignore'):
+ q = np.floor(f / step - offset)
+ tl, tr, br, bl = q[:-1, :-1], q[:-1, 1:], q[1:, 1:], q[1:, :-1]
+ qmax = np.maximum(np.maximum(tl, tr), np.maximum(br, bl)) # NaN propagates -> no crossing
+ qmin = np.minimum(np.minimum(tl, tr), np.minimum(br, bl))
+ cross = qmax > qmin
+ ii, jj = np.nonzero(cross)
+ if len(ii) == 0: return []
+ lev = qmax[ii, jj]
+ Lv = ((lev + offset) * step).astype(np.float32)
+ A = f[ii, jj] - Lv; B = f[ii, jj + 1] - Lv; C = f[ii + 1, jj + 1] - Lv; D = f[ii + 1, jj] - Lv
+ sA, sB, sC, sD = A >= 0, B >= 0, C >= 0, D >= 0
+
+ def lerp(u, v):
+ den = u - v
+ return np.clip(np.where(np.abs(den) > 1e-9, u / np.where(np.abs(den) > 1e-9, den, 1), 0.5), 0, 1)
+
+ X = jj.astype(np.float32); Y = ii.astype(np.float32)
+ pts = np.stack([np.stack([X + lerp(A, B), Y], 1), np.stack([X + 1, Y + lerp(B, C)], 1),
+ np.stack([X + lerp(D, C), Y + 1], 1), np.stack([X, Y + lerp(A, D)], 1)], 1) # top right bottom left
+ li = (lev - lev.min()).astype(np.int64); NL = int(li.max()) + 1
+ base = (ii.astype(np.int64) * w + jj)
+ keys = np.stack([2 * base, 2 * (base + 1) + 1, 2 * (base + w), 2 * base + 1], 1) * NL + li[:, None]
+ flags = np.stack([sA != sB, sB != sC, sD != sC, sA != sD], 1)
+ cnt = flags.sum(1)
+ rows = np.nonzero(cnt == 2)[0]
+ e = np.argsort(~flags[rows], axis=1, kind='stable')[:, :2]
+ ka, kb = keys[rows, e[:, 0]], keys[rows, e[:, 1]]
+ pa, pb = pts[rows, e[:, 0]], pts[rows, e[:, 1]]
+ lv = lev[rows]
+ sad = np.nonzero(cnt == 4)[0]
+ if len(sad):
+ cpos = (A[sad] + B[sad] + C[sad] + D[sad]) >= 0
+ cutBD = (sA[sad] & sC[sad] & cpos) | (sB[sad] & sD[sad] & ~cpos)
+ p1 = np.where(cutBD[:, None], np.array([[0, 1]]), np.array([[0, 3]]))
+ p2 = np.where(cutBD[:, None], np.array([[2, 3]]), np.array([[1, 2]]))
+ for pr in (p1, p2):
+ ka = np.concatenate([ka, keys[sad, pr[:, 0]]]); kb = np.concatenate([kb, keys[sad, pr[:, 1]]])
+ pa = np.concatenate([pa, pts[sad, pr[:, 0]]]); pb = np.concatenate([pb, pts[sad, pr[:, 1]]])
+ lv = np.concatenate([lv, lev[sad]])
+ n = len(ka)
+ ends = np.concatenate([ka, kb])
+ order = np.argsort(ends, kind='stable'); sk = ends[order]
+ same = np.nonzero(sk[1:] == sk[:-1])[0]
+ partner = np.full(2 * n, -1, np.int64)
+ partner[order[same]] = order[same + 1]; partner[order[same + 1]] = order[same]
+ partner = partner.tolist(); PA = (pa + 0.5).tolist(); PB = (pb + 0.5).tolist(); LV = lv.tolist()
+ seen = [False] * n
+ out = []
+ for s0 in range(n):
+ if seen[s0]: continue
+ seen[s0] = True
+ fwd, e, closed = [PB[s0]], s0 + n, False
+ while True:
+ p = partner[e]
+ if p < 0: break
+ s = p % n
+ if s == s0: closed = True; break
+ if seen[s]: break
+ seen[s] = True
+ if p < n: fwd.append(PB[s]); e = s + n
+ else: fwd.append(PA[s]); e = s
+ bwd = []
+ if not closed:
+ e = s0
+ while True:
+ p = partner[e]
+ if p < 0: break
+ s = p % n
+ if seen[s]: break
+ seen[s] = True
+ if p < n: bwd.append(PB[s]); e = s + n
+ else: bwd.append(PA[s]); e = s
+ P = np.array(bwd[::-1] + [PA[s0]] + fwd, np.float32)
+ out.append((int(LV[s0]), P, closed))
+ return out
+
+
+# ---------------------------------------------------------------- stroke capitals for inscriptions
+def _arc(cx, cy, rx, ry, a0, a1, n=24):
+ t = np.radians(np.linspace(a0, a1, n))
+ return [(cx + rx * np.cos(x), cy - ry * np.sin(x)) for x in t]
+
+
+LETTERS = { # cap height 1, y down; each letter is a list of strokes; one row of stones per stroke
+ 'A': [[(0, 1), (0.34, 0), (0.68, 1)], [(0.17, 0.6), (0.51, 0.6)]],
+ 'B': [[(0.04, 1), (0.04, 0)], [(0.04, 0), (0.38, 0), (0.54, 0.12), (0.54, 0.36), (0.38, 0.48), (0.04, 0.48)],
+ [(0.38, 0.48), (0.58, 0.6), (0.58, 0.88), (0.42, 1), (0.04, 1)]],
+ 'C': [_arc(0.4, 0.5, 0.4, 0.5, 48, 312)],
+ 'D': [[(0.04, 0), (0.04, 1)], [(0.04, 0), (0.3, 0)] + _arc(0.3, 0.5, 0.36, 0.5, 90, -90, 18)[1:] + [(0.04, 1)]],
+ 'E': [[(0.56, 0), (0.04, 0), (0.04, 1), (0.56, 1)], [(0.04, 0.5), (0.46, 0.5)]],
+ 'F': [[(0.56, 0), (0.04, 0), (0.04, 1)], [(0.04, 0.5), (0.46, 0.5)]],
+ 'G': [_arc(0.4, 0.5, 0.4, 0.5, 48, 330), [(0.8, 0.62), (0.8, 0.95)], [(0.56, 0.6), (0.8, 0.6)]],
+ 'H': [[(0.04, 0), (0.04, 1)], [(0.64, 0), (0.64, 1)], [(0.04, 0.5), (0.64, 0.5)]],
+ 'I': [[(0.04, 0), (0.04, 1)]],
+ 'L': [[(0.04, 0), (0.04, 1), (0.54, 1)]],
+ 'M': [[(0.0, 1), (0.06, 0), (0.4, 0.86), (0.74, 0), (0.8, 1)]],
+ 'N': [[(0.04, 1), (0.04, 0), (0.66, 1), (0.66, 0)]],
+ 'O': [_arc(0.42, 0.5, 0.42, 0.5, 90, 450, 40)],
+ 'P': [[(0.04, 1), (0.04, 0)], [(0.04, 0), (0.38, 0), (0.56, 0.11), (0.6, 0.27), (0.56, 0.42), (0.38, 0.52), (0.04, 0.52)]],
+ 'Q': [_arc(0.42, 0.5, 0.42, 0.5, 90, 450, 40), [(0.46, 0.8), (0.8, 1.08)]],
+ 'R': [[(0.04, 1), (0.04, 0)], [(0.04, 0), (0.38, 0), (0.56, 0.11), (0.6, 0.27), (0.56, 0.42), (0.38, 0.52), (0.04, 0.52)],
+ [(0.3, 0.52), (0.64, 1)]],
+ 'S': [[(0.56, 0.1), (0.4, 0.0), (0.18, 0.02), (0.05, 0.16), (0.08, 0.36), (0.3, 0.48), (0.5, 0.58),
+ (0.6, 0.76), (0.54, 0.94), (0.32, 1.0), (0.1, 0.96), (0.0, 0.86)]],
+ 'T': [[(0, 0), (0.68, 0)], [(0.34, 0), (0.34, 1)]],
+ 'V': [[(0, 0), (0.34, 1), (0.68, 0)]],
+ 'X': [[(0, 0), (0.62, 1)], [(0.62, 0), (0, 1)]],
+ 'Y': [[(0, 0), (0.34, 0.5), (0.68, 0)], [(0.34, 0.5), (0.34, 1)]],
+}
+_CURVED = set('BCDGOPQRS')
+
+
+class Mosaic:
+ def __init__(self, W=1920, H=1080, seed=0, tile=13, gap=1.8, ss=2, light=(-0.52, -0.66, 0.54),
+ bed='#d8cfbb', grout='#b3a892', stones=None):
+ self.W, self.H, self.tile, self.gap, self.ss = W, H, float(tile), float(gap), ss
+ self.rng = np.random.default_rng(seed)
+ self.seed = seed
+ L = np.asarray(light, np.float32); self.L = L / np.linalg.norm(L)
+ self.bed, self.grout = hexc(bed), hexc(grout)
+ self.box = dict(STONES if stones is None else stones)
+ self.cartoon = np.ones((H, W, 3), np.float32) * hexc('#e2dac8')
+ self.sin = np.zeros((H, W), np.float32)
+ self.occ = np.zeros((H, W), bool)
+ self.poly, self.rgb, self.mat, self.ht, self.tilt = [], [], [], [], []
+ self.lost = [] # indices of stones lost to time
+ self.cracks = []
+ self.patina_amt = 0.0
+ self.stages = []
+ self.stage_ss = 1
+ self._names = list(self.box)
+ self._pal = np.stack([hexc(self.box[k][0]) for k in self._names])
+ self._palmat = np.array([MATERIALS.index(self.box[k][1]) for k in self._names])
+ self._opp = _opp(self._pal)
+ self.dither = 0.035
+ self._tex = {}
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ # ------------------------------------------------------------ masks
+ def poly_mask(self, pts):
+ return polygon_mask(self.H, self.W, pts, ss=2)
+
+ def ellipse(self, cx, cy, rx, ry, rot=0.0):
+ t = np.linspace(0, 2 * np.pi, 120, endpoint=False); a = np.radians(rot)
+ x, y = np.cos(t) * rx, np.sin(t) * ry
+ return self.poly_mask(np.stack([cx + x * np.cos(a) + y * np.sin(a), cy - x * np.sin(a) + y * np.cos(a)], 1))
+
+ def rect(self, x0, y0, x1, y1):
+ m = np.zeros((self.H, self.W), np.float32)
+ m[max(int(round(y0)), 0):max(int(round(y1)), 0), max(int(round(x0)), 0):max(int(round(x1)), 0)] = 1
+ return m
+
+ def band(self, pts, w0, w1=None):
+ """a thick (optionally tapering, w0 -> w1) stroke along pts, as a mask: arms, masts, oars, poles"""
+ w1 = w0 if w1 is None else w1
+ P = np.asarray(pts, np.float32)
+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1); s = np.concatenate([[0], np.cumsum(seg)])
+ n = max(2, int(s[-1] / 1.5) + 2); ss = np.linspace(0, s[-1], n)
+ x, y = np.interp(ss, s, P[:, 0]), np.interp(ss, s, P[:, 1]); r = (w0 + (w1 - w0) * ss / max(s[-1], 1)) / 2
+ k = 3
+ bx0 = int(max(np.floor((x - r).min()) - 2, 0)); bx1 = int(min(np.ceil((x + r).max()) + 2, self.W))
+ by0 = int(max(np.floor((y - r).min()) - 2, 0)); by1 = int(min(np.ceil((y + r).max()) + 2, self.H))
+ out = np.zeros((self.H, self.W), np.float32)
+ if bx1 <= bx0 or by1 <= by0: return out
+ im = Image.new('L', ((bx1 - bx0) * k, (by1 - by0) * k), 0); d = ImageDraw.Draw(im)
+ for xi, yi, ri in zip(x - bx0, y - by0, r):
+ d.ellipse(((xi - ri) * k, (yi - ri) * k, (xi + ri) * k, (yi + ri) * k), fill=255)
+ out[by0:by1, bx0:bx1] = np.asarray(im.resize((bx1 - bx0, by1 - by0), Image.BILINEAR), np.float32) / 255
+ return out
+
+ def everything(self):
+ """mask of every stone set so far"""
+ return self.occ.astype(np.float32)
+
+ def free(self, region=None):
+ """region (default whole picture) minus every stone set so far"""
+ m = np.ones((self.H, self.W), np.float32) if region is None else region.copy()
+ return m * (1 - self.occ)
+
+ # ------------------------------------------------------------ the cartoon (hidden colour map) and sinopia
+ def _col(self, c):
+ if isinstance(c, str):
+ return hexc(self.box[c][0]) if c in self.box else hexc(c)
+ return np.asarray(c, np.float32)
+
+ def _bb(self, mask, pad=0):
+ """row/column slices of the part of `mask` that is not zero (whole canvas if empty)"""
+ r = np.nonzero((mask > 1e-4).any(1))[0]; c = np.nonzero((mask > 1e-4).any(0))[0]
+ if len(r) == 0: return slice(0, 0), slice(0, 0)
+ return (slice(max(r[0] - pad, 0), min(r[-1] + pad + 1, self.H)), slice(max(c[0] - pad, 0), min(c[-1] + pad + 1, self.W)))
+
+ def paint(self, mask, colour):
+ ys, xs = self._bb(mask)
+ a = np.clip(mask[ys, xs], 0, 1)[..., None]
+ self.cartoon[ys, xs] = self.cartoon[ys, xs] * (1 - a) + self._col(colour) * a
+
+ def shade(self, mask, c0, c1, p0, p1, gamma=1.0):
+ """linear gradient c0 at p0 -> c1 at p1, inside mask"""
+ ys, xs = self._bb(mask)
+ yy, xx = np.mgrid[ys, xs].astype(np.float32)
+ d = np.array(p1, np.float32) - np.array(p0, np.float32)
+ t = np.clip(((xx - p0[0]) * d[0] + (yy - p0[1]) * d[1]) / (d @ d + 1e-6), 0, 1) ** gamma
+ col = self._col(c0) * (1 - t[..., None]) + self._col(c1) * t[..., None]
+ a = np.clip(mask[ys, xs], 0, 1)[..., None]
+ self.cartoon[ys, xs] = self.cartoon[ys, xs] * (1 - a) + col * a
+
+ def sinopia(self, mask=None, pts=None, width=3.0, strength=0.75):
+ """red-ochre underdrawing on the wet bed: the outline of a mask, or a brushed line through pts"""
+ if mask is None:
+ mask = self.band(spline(pts, 8) if len(pts) > 2 else pts, width)
+ ys, xs = self._bb(mask, 2)
+ line = mask[ys, xs]
+ else:
+ ys, xs = self._bb(mask, 6)
+ b = blur(np.clip(mask[ys, xs], 0, 1), 1.2)
+ gy, gx = np.gradient(b)
+ line = np.clip(np.hypot(gx, gy) * width * 1.6, 0, 1)
+ if not hasattr(self, '_brk'):
+ self._brk = 0.55 + 0.45 * smoothstep(0.3, 0.6, noise2d(self.H, self.W, 60, 3, self._seed()))
+ self.sin[ys, xs] = np.maximum(self.sin[ys, xs], line * self._brk[ys, xs] * strength)
+
+ # ------------------------------------------------------------ stones
+ def _stone(self, colour, material, stones, rgb_sample=None):
+ """pick a stone out of the box: explicit name / hex, or the nearest stone to the cartoon colour"""
+ if colour is not None:
+ if isinstance(colour, str) and colour in self.box:
+ base = hexc(self.box[colour][0]); mat = MATERIALS.index(self.box[colour][1])
+ else:
+ base = self._col(colour)
+ mat = int(self._palmat[np.argmin(((self._pal - base) ** 2).sum(1))])
+ else:
+ idx = np.arange(len(self._names)) if stones is None else np.array([self._names.index(s) for s in stones])
+ c = _opp(rgb_sample) + self.rng.normal(0, 1, 3) * np.array([self.dither, self.dither * 0.3, self.dither * 0.3])
+ dd = ((self._opp[idx] - c) ** 2 * np.array([1.0, 2.6, 2.6])).sum(1)
+ k = idx[int(np.argmin(dd))]
+ base, mat = self._pal[k], int(self._palmat[k])
+ if material is not None: mat = MATERIALS.index(material)
+ rgb = np.clip(base * self.rng.uniform(0.94, 1.05) + self.rng.normal(0, 0.011, 3), 0, 1)
+ return rgb.astype(np.float32), mat
+
+ def _patch(self, P, scale=1.0, H=None, W=None):
+ """bbox and signed distance (px, positive inside) of convex polygon P, at pixel centres"""
+ H = H or self.H; W = W or self.W
+ P = np.asarray(P, np.float32) * scale
+ x0 = max(int(np.floor(P[:, 0].min())) - 1, 0); x1 = min(int(np.ceil(P[:, 0].max())) + 1, W)
+ y0 = max(int(np.floor(P[:, 1].min())) - 1, 0); y1 = min(int(np.ceil(P[:, 1].max())) + 1, H)
+ if x1 <= x0 or y1 <= y0: return None
+ X = np.arange(x0, x1, dtype=np.float32)[None, :] + 0.5
+ Y = np.arange(y0, y1, dtype=np.float32)[:, None] + 0.5
+ Q = np.roll(P, -1, 0); E = Q - P
+ area = float((P[:, 0] * Q[:, 1] - Q[:, 0] * P[:, 1]).sum())
+ sg = 1.0 if area > 0 else -1.0
+ sd = None
+ for k in range(len(P)):
+ ln = float(np.hypot(E[k, 0], E[k, 1]))
+ if ln < 1e-4: continue
+ d = sg * (E[k, 0] * (Y - P[k, 1]) - E[k, 1] * (X - P[k, 0])) / ln
+ sd = d if sd is None else np.minimum(sd, d)
+ if sd is None: return None
+ return y0, x0, sd
+
+ def _set(self, P, colour=None, material=None, stones=None, keep=0.55, height=None):
+ """try to set one stone with outline P; refuse it when it would sit mostly on stones already set"""
+ r = self._patch(P)
+ if r is None: return False
+ y0, x0, sd = r
+ ins = sd > 0
+ cnt = int(ins.sum())
+ if cnt < 3: return False
+ sub = self.occ[y0:y0 + sd.shape[0], x0:x0 + sd.shape[1]]
+ over = int((sub & ins).sum())
+ if over > (1 - keep) * cnt: return False
+ cx, cy = P[:, 0].mean(), P[:, 1].mean()
+ if 0 <= int(cy) < self.H and 0 <= int(cx) < self.W and self.occ[int(cy), int(cx)] and over > 0.12 * cnt:
+ return False
+ sample = None
+ if colour is None:
+ sample = self.cartoon[y0:y0 + sd.shape[0], x0:x0 + sd.shape[1]][ins & ~sub].mean(0) if cnt > over else \
+ self.cartoon[int(np.clip(cy, 0, self.H - 1)), int(np.clip(cx, 0, self.W - 1))]
+ rgb, mat = self._stone(colour, material, stones, sample)
+ sub |= ins
+ self.poly.append(np.asarray(P, np.float32)); self.rgb.append(rgb); self.mat.append(mat)
+ self.ht.append(float(height if height is not None else self.rng.uniform(1.5, 2.0)))
+ self.tilt.append(self.rng.normal(0, 0.06, 2).astype(np.float32))
+ return True
+
+ def _rough(self, Q, size, chip=0.2, jit=0.045):
+ """hand-cut: jitter the corners, sometimes knock one off, turn the stone a hair"""
+ Q = np.asarray(Q, np.float32) + self.rng.normal(0, jit * size, (len(Q), 2)).astype(np.float32)
+ c = Q.mean(0)
+ a = np.radians(self.rng.normal(0, 1.6)); R = np.array([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]], np.float32)
+ Q = (Q - c) @ R.T + c
+ if len(Q) == 4 and self.rng.random() < chip:
+ k = int(self.rng.integers(4)); f = self.rng.uniform(0.1, 0.24)
+ p, a_, b_ = Q[k], Q[k - 1], Q[(k + 1) % 4]
+ Q = np.concatenate([Q[:k], [p + (a_ - p) * f, p + (b_ - p) * f], Q[k + 1:]])
+ return Q
+
+ def _convex_ok(self, Q):
+ Q = np.asarray(Q); R = np.roll(Q, -1, 0); S = np.roll(Q, -2, 0)
+ cr = (R[:, 0] - Q[:, 0]) * (S[:, 1] - R[:, 1]) - (R[:, 1] - Q[:, 1]) * (S[:, 0] - R[:, 0])
+ return bool((cr > -1e-3).all() or (cr < 1e-3).all())
+
+ def _split(self, P, closed, ang=0.75, k=3):
+ """cut a row at its sharp corners (a mosaicist turns a corner with a new stone, not a bent one)"""
+ n = len(P)
+ if n < 2 * k + 3: return [(P, closed)]
+ idx = np.arange(n)
+ if closed:
+ a, b = P[(idx - k) % n], P[(idx + k) % n]
+ else:
+ a, b = P[np.clip(idx - k, 0, n - 1)], P[np.clip(idx + k, 0, n - 1)]
+ v1, v2 = P - a, b - P
+ turn = np.abs(np.arctan2(v1[:, 0] * v2[:, 1] - v1[:, 1] * v2[:, 0], (v1 * v2).sum(1)))
+ if not closed: turn[:k + 1] = 0; turn[-k - 1:] = 0
+ hot = turn > ang
+ if not hot.any(): return [(P, closed)]
+ cuts = []
+ i = 0
+ while i < n:
+ if hot[i]:
+ j = i
+ while j + 1 < n and hot[j + 1]: j += 1
+ cuts.append(i + int(np.argmax(turn[i:j + 1]))); i = j + 1
+ else:
+ i += 1
+ if closed:
+ P = np.concatenate([P[cuts[0]:], P[:cuts[0] + 1]]); cuts = [c - cuts[0] if c >= cuts[0] else c + n - cuts[0] for c in cuts] + [n]
+ return [(P[cuts[i]:cuts[i + 1] + 1], False) for i in range(len(cuts) - 1)]
+ cuts = [0] + cuts + [n - 1]
+ return [(P[cuts[i]:cuts[i + 1] + 1], False) for i in range(len(cuts) - 1)]
+
+ def _row(self, P, closed, size, across=None, colour=None, material=None, stones=None, var=0.2,
+ ridge=None, level=None, keep=0.55, chip=0.2, jit=0.045, height=None):
+ """cut one row (polyline P) into stones and try to set each of them"""
+ across = size if across is None else across
+ if len(P) < 2: return 0
+ for Q, cl in self._split(P, closed):
+ if cl: Q = np.concatenate([Q, Q[:1]])
+ seg = np.linalg.norm(np.diff(Q, axis=0), axis=1)
+ s = np.concatenate([[0], np.cumsum(seg)]); L = float(s[-1])
+ pitch = size + self.gap
+ if L < 0.45 * size: continue
+ n = max(1, int(round(L / pitch)))
+ if not cl and L < 0.8 * pitch: n = 1
+ lens = self.rng.uniform(1 - var, 1 + var, n); lens *= L / lens.sum()
+ b = np.concatenate([[0], np.cumsum(lens)]) + (self.rng.uniform(0, lens[0]) if cl else 0)
+ kk = 2
+ tx = np.gradient(Q[:, 0]); ty = np.gradient(Q[:, 1])
+ if len(Q) > 2 * kk + 1:
+ ker = np.ones(2 * kk + 1) / (2 * kk + 1)
+ tx = np.convolve(np.pad(tx, kk, mode='edge'), ker, 'valid'); ty = np.convolve(np.pad(ty, kk, mode='edge'), ker, 'valid')
+ tl = np.hypot(tx, ty) + 1e-6; tx, ty = tx / tl, ty / tl
+
+ def at(u):
+ u = u % L if cl else np.clip(u, 0, L)
+ return (np.array([np.interp(u, s, Q[:, 0]), np.interp(u, s, Q[:, 1])], np.float32),
+ np.array([-np.interp(u, s, ty), np.interp(u, s, tx)], np.float32))
+
+ for i in range(n):
+ a0, a1 = b[i] + self.gap / 2, b[i + 1] - self.gap / 2
+ if a1 - a0 < 0.3 * size: continue
+ (p0, n0), (p1, n1) = at(a0), at(a1)
+ n0 /= np.linalg.norm(n0) + 1e-6; n1 /= np.linalg.norm(n1) + 1e-6
+ hw = (across / 2) * self.rng.uniform(0.92, 1.03)
+ wi = wo = hw
+ if ridge is not None: # don't cross the figure's spine
+ pm = (p0 + p1) / 2
+ g = ridge(pm)
+ if g is not None:
+ room = g - level - self.gap / 2 # distance to the ridge, inward side
+ nxt = g - (level + size + self.gap) # is there another row inside?
+ if nxt < 0.3 * size:
+ wi = float(np.clip(room, 0.3 * size, 1.15 * size))
+ else:
+ wi = min(hw, max(room, 0.3 * size))
+ # inward = toward higher field: decided by caller via sign of normals (ridge rows: +n is inward)
+ Qd = np.array([p0 + n0 * wi, p1 + n1 * wi, p1 - n1 * wo, p0 - n0 * wo], np.float32)
+ if not self._convex_ok(Qd):
+ m = (Qd[0] + Qd[1]) / 2; Qd = np.array([m, Qd[2], Qd[3]], np.float32)
+ Qd = self._rough(Qd, size, chip=chip, jit=jit)
+ if not self._convex_ok(Qd): continue
+ self._set(Qd, colour, material, stones, keep, height)
+ return 1
+
+ def _obstacle(self, y0, y1, x0, x1):
+ o = self.occ[y0:y1, x0:x1].astype(np.float32)
+ return blur(o, self.gap * 0.5) > 0.12
+
+ def _bbox(self, mask, pad):
+ ys, xs = np.nonzero(mask > 0.5)
+ if len(ys) == 0: return None
+ return (max(ys.min() - pad, 0), min(ys.max() + pad + 1, self.H), max(xs.min() - pad, 0), min(xs.max() + pad + 1, self.W))
+
+ def _ridge_fn(self, din, y0, x0, size):
+ M = maxfilt(np.where(np.isfinite(din), din, 0), int(2 * (size + self.gap)) + 2) # must see past the next row
+
+ def g(p):
+ x, y = int(p[0]) - x0, int(p[1]) - y0
+ if 0 <= y < M.shape[0] and 0 <= x < M.shape[1]: return float(M[y, x])
+ return None
+ return g
+
+ @staticmethod
+ def _orient(P, f):
+ """reverse a row if needed so that its left normal (-ty, tx) points up the field (inward for figures)"""
+ n = len(P)
+ if n < 3: return P
+ idx = np.linspace(1, n - 2, min(9, n - 2)).astype(int)
+ t = P[idx + 1] - P[idx - 1]; t /= np.linalg.norm(t, axis=1, keepdims=True) + 1e-6
+ nrm = np.stack([-t[:, 1], t[:, 0]], 1)
+ H, W = f.shape
+ vote = 0.0
+ for p, q in zip(P[idx], nrm):
+ a, b = p + q * 1.6 - 0.5, p - q * 1.6 - 0.5
+ ia, ib = (int(round(a[1])), int(round(a[0]))), (int(round(b[1])), int(round(b[0])))
+ if 0 <= ia[0] < H and 0 <= ia[1] < W and 0 <= ib[0] < H and 0 <= ib[1] < W:
+ fa, fb = f[ia], f[ib]
+ if np.isfinite(fa) and np.isfinite(fb): vote += np.sign(fa - fb)
+ return P[::-1].copy() if vote < 0 else P
+
+ def _lay_field(self, field, y0, x0, size, levels=None, colour=None, material=None, stones=None, ridge=None,
+ var=0.2, keep=0.55, across=None, chip=0.2, height=None, order=None):
+ """trace the iso-lines of `field` (crop at y0, x0) one stone-pitch apart and lay a row on each"""
+ pitch = size + self.gap
+ lines = iso_lines(field, pitch, 0.5)
+ lines.sort(key=lambda t: t[0])
+ if order == 'random':
+ self.rng.shuffle(lines)
+ for k, P, closed in lines:
+ if levels is not None and not (levels[0] <= k < levels[1]): continue
+ P = self._orient(P, field) + np.array([x0, y0], np.float32)
+ col = colour(k) if callable(colour) else colour
+ self._row(P, closed, size, across, col, material, stones, var, ridge,
+ (k + 0.5) * pitch if ridge is not None else None, keep, chip, height=height)
+
+ # ------------------------------------------------------------ laying methods
+ def point(self, x, y, colour, size=None, shape='square', angle=0.0, material=None):
+ """set one stone by hand: an eye ('round'), a highlight, a stop between words ('tri')"""
+ size = size or self.tile
+ a = np.radians(angle)
+ if shape == 'round':
+ t = np.linspace(0, 2 * np.pi, 9, endpoint=False) + a
+ Q = np.stack([x + np.cos(t) * size / 2, y - np.sin(t) * size / 2], 1)
+ elif shape == 'tri':
+ t = np.radians([90, 210, 330]) + a
+ Q = np.stack([x + np.cos(t) * size * 0.6, y - np.sin(t) * size * 0.6], 1)
+ else:
+ t = np.radians([45, 135, 225, 315]) + a
+ Q = np.stack([x + np.cos(t) * size * 0.7, y - np.sin(t) * size * 0.7], 1)
+ Q = self._rough(Q, size, chip=0.0, jit=0.04)
+ return self._set(Q.astype(np.float32), colour, material, None, keep=0.5)
+
+ def line(self, pts, colour=None, size=None, across=None, smooth=True, material=None, keep=0.5, var=0.15, stones=None):
+ """one row of stones along a path: a contour line, a fin ray, a mast, a net cord, a letter stroke.
+ colour=None takes each stone's colour from the cartoon (a tentacle's spine row)"""
+ size = size or self.tile * 0.8
+ P = np.asarray(pts, np.float32)
+ if smooth and len(P) > 2: P = spline(P, 10)
+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1); s = np.concatenate([[0], np.cumsum(seg)])
+ n = max(2, int(s[-1]) + 1); u = np.linspace(0, s[-1], n)
+ P = np.stack([np.interp(u, s, P[:, 0]), np.interp(u, s, P[:, 1])], 1).astype(np.float32)
+ self._row(P, False, size, across, colour, material, stones, var, keep=keep, chip=0.15)
+
+ def outline(self, mask, colour='black', rows=1, size=None, material=None, stones=None):
+ """the first row(s) of a figure, just inside its edge: the dark contour line of Roman figures"""
+ size = size or self.tile * 0.8
+ pitch = size + self.gap
+ bb = self._bbox(mask, 4)
+ if bb is None: return
+ y0, y1, x0, x1 = bb
+ m = mask[y0:y1, x0:x1] > 0.5
+ din = edt(~m, reach=pitch * (rows + 2)) - 0.5
+ f = np.where(m & ~self._obstacle(y0, y1, x0, x1), din, np.nan).astype(np.float32)
+ f[din > pitch * (rows + 0.9)] = np.nan
+ self._lay_field(f, y0, x0, size, levels=(0, rows), colour=colour, material=material, stones=stones,
+ ridge=self._ridge_fn(np.where(m, din, 0), y0, x0, size))
+
+ def fill(self, mask, size=None, stones=None, material=None, wrap=True, tuck=True, colour=None):
+ """rows that follow the figure's outline inward (opus vermiculatum); colours come from the cartoon"""
+ size = size or self.tile * 0.8
+ pitch = size + self.gap
+ bb = self._bbox(mask, 4)
+ if bb is None: return
+ y0, y1, x0, x1 = bb
+ m = mask[y0:y1, x0:x1] > 0.5
+ din = edt(~m) - 0.5
+ obs = self._obstacle(y0, y1, x0, x1)
+ field = din
+ if wrap and (obs & m).any():
+ dob = edt(obs & m) - 0.5
+ field = np.minimum(din, dob + 0.0)
+ f = np.where(m & ~obs, field, np.nan).astype(np.float32)
+ self._lay_field(f, y0, x0, size, colour=colour, material=material, stones=stones,
+ ridge=self._ridge_fn(np.where(m, field, 0), y0, x0, size))
+ if tuck: self.tuck(mask, size, stones=stones, material=material, colour=colour)
+
+ def figure(self, mask, outline='black', size=None, stones=None, rows=1, wrap=True):
+ if outline is not None: self.outline(mask, outline, rows, size)
+ self.fill(mask, size, stones, wrap=wrap)
+
+ def halo(self, region=None, rows=2, size=None, stones=None, colour=None, around=None):
+ """background rows that hug the outline of what is already set (or of `around`), outside it"""
+ size = size or self.tile
+ pitch = size + self.gap
+ reg = np.ones((self.H, self.W), bool) if region is None else region > 0.5
+ src = self.occ if around is None else (around > 0.5)
+ bb = self._bbox(reg.astype(np.float32), 2)
+ if bb is None: return
+ y0, y1, x0, x1 = bb
+ k = 2 # distance field at half resolution
+ s_ = src[y0:y1, x0:x1]
+ dsmall = edt(s_[::k, ::k], reach=pitch * (rows + 2) / k) * k
+ d = np.asarray(Image.fromarray(dsmall.astype(np.float32)).resize((x1 - x0, y1 - y0), Image.BILINEAR), np.float32)
+ d = np.maximum(d - self.gap * 0.5 - 0.5, 0)
+ obs = self._obstacle(y0, y1, x0, x1)
+ f = np.where(reg[y0:y1, x0:x1] & ~obs & (d < pitch * (rows + 0.6)), d, np.nan).astype(np.float32)
+ self._lay_field(f, y0, x0, size, levels=(0, rows), colour=colour, stones=stones, var=0.18)
+
+ def rows(self, region, size=None, angle=0.0, wobble=0.0, field=None, stones=None, colour=None, tuck=True,
+ var=0.18, material=None):
+ """background in parallel rows (opus tessellatum); `field` (H, W) lays rows along its iso-lines instead"""
+ size = size or self.tile
+ reg = region > 0.5
+ bb = self._bbox(region, 2)
+ if bb is None: return
+ y0, y1, x0, x1 = bb
+ if field is None:
+ yy, xx = np.mgrid[y0:y1, x0:x1].astype(np.float32)
+ a = np.radians(angle)
+ f = -xx * np.sin(a) + yy * np.cos(a)
+ if wobble:
+ f = f + wobble * (noise2d(y1 - y0, x1 - x0, 300, 3, self._seed()) - 0.5) * 2
+ else:
+ f = field[y0:y1, x0:x1].astype(np.float32)
+ obs = self._obstacle(y0, y1, x0, x1)
+ f = np.where(reg[y0:y1, x0:x1] & ~obs, f, np.nan).astype(np.float32)
+ self._lay_field(f, y0, x0, size, colour=colour, stones=stones, var=var, material=material)
+ if tuck: self.tuck(region, size, stones=stones, colour=colour, material=material)
+
+ def frame(self, x0, y0, x1, y1, width, size=None, stones=None, colour=None, tuck=True):
+ """rows running parallel to the four sides of a rectangle band (borders), mitred at the corners"""
+ yy, xx = np.mgrid[0:self.H, 0:self.W].astype(np.float32)
+ d = np.minimum(np.minimum(xx + 0.5 - x0, x1 - xx - 0.5), np.minimum(yy + 0.5 - y0, y1 - yy - 0.5))
+ reg = ((d >= 0) & (d < width)).astype(np.float32)
+ self.rows(reg, size, field=d, stones=stones, colour=colour, tuck=tuck)
+ return reg
+
+ def tuck(self, region, size=None, stones=None, colour=None, material=None, small=0.32):
+ """fill the holes that are left with pieces cut to fit, biggest holes first"""
+ size = size or self.tile
+ bb = self._bbox(region, 2)
+ if bb is None: return
+ y0, y1, x0, x1 = bb
+ free = (region[y0:y1, x0:x1] > 0.5) & ~self._obstacle(y0, y1, x0, x1)
+ if not free.any(): return
+ df = edt(~free, reach=size * 2)
+ st = max(2, int(size * 0.45))
+ gy, gx = np.mgrid[st // 2:y1 - y0:st, st // 2:x1 - x0:st]
+ gy = np.clip(gy + self.rng.integers(-st // 3, st // 3 + 1, gy.shape), 0, y1 - y0 - 1)
+ gx = np.clip(gx + self.rng.integers(-st // 3, st // 3 + 1, gx.shape), 0, x1 - x0 - 1)
+ dv = df[gy, gx]
+ ok = dv > (small * size + self.gap) / 2
+ gy, gx, dv = gy[ok], gx[ok], dv[ok]
+ for i in np.argsort(-dv):
+ y, x = int(gy[i]) + y0, int(gx[i]) + x0
+ if self.occ[y, x]: continue
+ s = float(np.clip(2 * dv[i] - self.gap, small * size, size))
+ a = self.rng.uniform(0, np.pi / 2)
+ t = np.array([0.25, 0.75, 1.25, 1.75]) * np.pi + a
+ Q = np.stack([x + 0.5 + np.cos(t) * s * 0.7, y + 0.5 + np.sin(t) * s * 0.7], 1)
+ Q = self._rough(Q, s, chip=0.2)
+ self._set(Q.astype(np.float32), colour, material, stones, keep=0.7)
+
+ # ------------------------------------------------------------ inscriptions
+ def text_width(self, text, height, spacing=0.32):
+ w = 0.0
+ for ch in text:
+ if ch == ' ': w += 0.5 * height; continue
+ if ch in '·.': w += 0.36 * height; continue
+ st = LETTERS.get(ch.upper())
+ if st is None: continue
+ w += (max(p[0] for s_ in st for p in s_) + spacing) * height
+ return w - spacing * height
+
+ def letters(self, text, x, y, height, colour='black', size=None, spacing=0.32, anchor='m'):
+ """Roman capitals, each stroke one row of stones; '·' is a triangular stop. y is the cap top"""
+ size = size or max(5.0, height / 6.2)
+ w = self.text_width(text, height, spacing)
+ cx = x - w / 2 if anchor == 'm' else x
+ for ch in text:
+ if ch == ' ': cx += 0.5 * height; continue
+ if ch in '·.':
+ self.point(cx + 0.14 * height, y + 0.55 * height, colour, size * 1.05, 'tri', angle=180)
+ cx += 0.36 * height; continue
+ st = LETTERS.get(ch.upper())
+ if st is None: continue
+ for s_ in st:
+ P = [(cx + px * height, y + py * height) for px, py in s_]
+ self.line(P, colour, size, smooth=ch.upper() in _CURVED or len(P) > 6, keep=0.45, var=0.12)
+ cx += (max(p[0] for s_ in st for p in s_) + spacing) * height
+
+ def tabula(self, x0, y0, x1, y1, lines, ear=60, frame=('black', 'red'), ground=('white', 'bone'), size=None):
+ """tabula ansata: a framed plaque with a dovetail handle each side; lines = [(text, height, colour)]"""
+ size = size or self.tile * 0.75
+ cy = (y0 + y1) / 2; hh = (y1 - y0) / 2
+ plaque = self.poly_mask([(x0, y0), (x1, y0), (x1, y1), (x0, y1)])
+ ears = []
+ for sgn, xe in ((-1, x0), (1, x1)):
+ e = [(xe - sgn * 2, cy), (xe + sgn * ear, cy - hh * 0.8), (xe + sgn * ear * 0.78, cy), (xe + sgn * ear, cy + hh * 0.8)]
+ ears.append(self.poly_mask(e))
+ shape = np.clip(plaque + ears[0] + ears[1], 0, 1)
+ total = sum(h for _, h, _ in lines) * 1.0 + (len(lines) - 1) * lines[0][1] * 0.45
+ ty = cy - total / 2
+ for text, h, col in lines:
+ self.letters(text, (x0 + x1) / 2, ty, h, col, size=max(5.6, h / 5.6))
+ ty += h * 1.45
+ self.outline(shape, frame[0], 1, size)
+ if len(frame) > 1: self.outline(shape, frame[1], 2, size)
+ inner = np.clip(plaque - self.everything(), 0, 1)
+ self.rows(inner, size * 1.05, stones=list(ground))
+ for e in ears:
+ em = e * (1 - self.everything())
+ self.fill(em, size, stones=[frame[1] if len(frame) > 1 else frame[0]], tuck=False)
+ self.tuck(em, size, stones=[frame[1] if len(frame) > 1 else frame[0]], small=0.55)
+ return shape
+
+ # ------------------------------------------------------------ time
+ def lacuna(self, mask, ragged=0.5):
+ """the stones in this patch are lost; their sockets stay printed in the old bed"""
+ m = mask > 0.5
+ edge = (blur(mask.astype(np.float32), 6) > 0.12) & ~m
+ for k, P in enumerate(self.poly):
+ cx, cy = P.mean(0)
+ yi, xi = int(np.clip(cy, 0, self.H - 1)), int(np.clip(cx, 0, self.W - 1))
+ if m[yi, xi] or (edge[yi, xi] and self.rng.random() < ragged):
+ self.lost.append(k)
+
+ def crack(self, pts, width=1.3):
+ """a settling crack: a dark hairline through stones and joints, one side sunk a little"""
+ P = np.asarray(pts, np.float32)
+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1); s = np.concatenate([[0], np.cumsum(seg)])
+ n = max(8, int(s[-1] / 3)); u = np.linspace(0, s[-1], n)
+ x, y = np.interp(u, s, P[:, 0]), np.interp(u, s, P[:, 1])
+ d = np.stack([np.gradient(x), np.gradient(y)], 1); d /= np.linalg.norm(d, axis=1, keepdims=True) + 1e-6
+ w = fbm1d(n, 12, 4, self._seed()) * 5 + fbm1d(n, 3, 2, self._seed()) * 1.5
+ Q = np.stack([x - d[:, 1] * w, y + d[:, 0] * w], 1)
+ self.cracks.append((Q, width))
+
+ def patina(self, amount=1.0):
+ self.patina_amt = amount
+
+ # ------------------------------------------------------------ rendering
+ def _textures(self, ss):
+ if ss in self._tex: return self._tex[ss]
+ r = np.random.default_rng(self.seed + 991)
+ N = 256 * ss
+ mott = (noise2d(N, N, 9 * ss, 3, self.seed + 1) - 0.5) * 2
+ mott = mott * 0.7 + (r.random((N, N)).astype(np.float32) - 0.5) * 0.6
+ vy, vx = np.mgrid[0:N, 0:N].astype(np.float32)
+ warp = noise2d(N, N, 40 * ss, 3, self.seed + 2) * 40 * ss
+ vein = np.abs(np.sin((vx * 0.6 + vy * 0.8 + warp) / (11.0 * ss)))
+ vein = 1 - smoothstep(0.0, 0.07, vein)
+ vein *= smoothstep(0.35, 0.7, noise2d(N, N, 60 * ss, 2, self.seed + 3))
+ pits = np.zeros((N, N), np.float32)
+ for _ in range(int(900)):
+ x, y, rr = r.integers(0, N), r.integers(0, N), r.uniform(0.5, 1.6) * ss
+ y0, y1, x0, x1 = max(y - 4 * ss, 0), min(y + 4 * ss, N), max(x - 4 * ss, 0), min(x + 4 * ss, N)
+ pits[y0:y1, x0:x1] = np.maximum(pits[y0:y1, x0:x1], np.exp(-((vy[y0:y1, x0:x1] - y) ** 2 + (vx[y0:y1, x0:x1] - x) ** 2) / (2 * rr * rr)))
+ sand = (r.random((N, N)).astype(np.float32) - 0.5)
+ sand = sand * 0.6 + (noise2d(N, N, 3 * ss, 2, self.seed + 4) - 0.5) * 0.8
+ self._tex[ss] = (mott.astype(np.float32), vein.astype(np.float32), pits.astype(np.float32), sand.astype(np.float32))
+ return self._tex[ss]
+
+ def _render(self, ss, n=None, aged=True):
+ H, W = self.H * ss, self.W * ss
+ n = len(self.poly) if n is None else n
+ lost = set(self.lost) if aged else set()
+ idm = np.zeros((H, W), np.int32)
+ dep = np.zeros((H, W), np.float32)
+ block = np.zeros((H, W), bool)
+ sock = np.zeros((H, W), np.float32)
+ rr = 0.7 * self.gap * ss
+ for k in range(n):
+ r = self._patch(self.poly[k], ss, H, W)
+ if r is None: continue
+ y0, x0, sd = r
+ sl = (slice(y0, y0 + sd.shape[0]), slice(x0, x0 + sd.shape[1]))
+ if k in lost:
+ np.maximum(sock[sl], smoothstep(-0.5 * ss, 1.0 * ss, sd), out=sock[sl])
+ continue
+ ins = (sd > 0) & ~block[sl]
+ idm[sl][ins] = k + 1
+ dep[sl][ins] = sd[ins]
+ block[sl] |= sd > -rr
+ del block
+ N = n + 1
+ RGB = np.zeros((N, 3), np.float32); MAT = np.zeros(N, np.int32); HT = np.zeros(N, np.float32)
+ TL = np.zeros((N, 2), np.float32); OFF = np.zeros((N, 2), np.int32); VEIN = np.zeros(N, np.float32)
+ if n:
+ RGB[1:] = np.array(self.rgb[:n]); MAT[1:] = self.mat[:n]; HT[1:] = self.ht[:n]; TL[1:] = np.array(self.tilt[:n])
+ rr_ = np.random.default_rng(self.seed + 5)
+ OFF[1:] = rr_.integers(0, 256 * ss, (n, 2)); VEIN[1:] = (rr_.random(n) < 0.45) * rr_.uniform(0.3, 1.0, n)
+ mott, vein, pits, sand = self._textures(ss)
+ T = mott.shape[0]
+ # bed / sinopia / crack / weather maps stay at 1x and are enlarged one strip at a time (keeps memory low)
+ crk1 = None
+ if aged and self.cracks:
+ im = Image.new('L', (self.W * 2, self.H * 2), 0); d = ImageDraw.Draw(im)
+ for Q, w in self.cracks:
+ d.line([tuple(p) for p in (Q * 2).tolist()], fill=255, width=max(1, int(round(w * 2))), joint='curve')
+ crk1 = blur(np.asarray(im.resize((self.W, self.H), Image.BILINEAR), np.float32) / 255, 0.35)
+ lowf1 = np.asarray(Image.fromarray(noise2d(self.H // 4, self.W // 4, 30, 4, self.seed + 7)).resize((self.W, self.H), Image.BILINEAR), np.float32)
+
+ def up(a1, ya, yb):
+ c = a1[ya // ss:(yb + ss - 1) // ss]
+ if ss == 1: return c
+ return np.asarray(Image.fromarray(c).resize((W, c.shape[0] * ss), Image.BILINEAR), np.float32)[:yb - ya]
+ out = np.zeros((self.H, self.W, 3), np.float32)
+ strip = 96 * ss; mg = 18 * ss # thin strips keep memory low
+ L = self.L; Hv = L + np.array([0, 0, 1], np.float32); Hv /= np.linalg.norm(Hv)
+ for ys in range(0, H, strip):
+ ya, yb = max(ys - mg, 0), min(ys + strip + mg, H)
+ ids = idm[ya:yb]; tile = ids > 0
+ lf = up(lowf1, ya, yb); sn_ = up(self.sin, ya, yb)
+ ck = up(crk1, ya, yb) if crk1 is not None else None
+ yy, xx = np.mgrid[ya:yb, 0:W].astype(np.int32)
+ # chamfer distance to any id change, so cut-to-fit edges are worn too
+ ch = np.where(tile, 6.0 * ss, 0).astype(np.float32)
+ edge = np.zeros_like(tile)
+ for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
+ edge |= ids != _shift_fill(ids, dy, dx, 0)
+ ch[edge & tile] = 0.5
+ for _ in range(int(3 * ss)):
+ for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
+ ch = np.minimum(ch, _shift_fill(ch, dy, dx, 0) + 1)
+ dd = np.minimum(dep[ya:yb], ch)
+ Rb = 1.7 * ss
+ prof = smoothstep(0, Rb, dd)
+ dome = smoothstep(0, 5 * Rb, dd)
+ ht = HT[ids]
+ gs = sand[yy % T, xx % T]
+ near = blur(tile.astype(np.float32), 1.6 * ss)
+ grouted = near > 0.06
+ sk = sock[ya:yb]
+ oldbed = (blur(sk, 3 * ss) > 0.02) if aged else np.zeros_like(tile)
+ h_grout = 0.35 + 0.3 * near + 0.07 * gs
+ h_bed = 0.7 + 0.06 * gs + 0.5 * (lf - 0.5)
+ h_old = -0.2 + 0.3 * gs - 0.9 * sk
+ hfield = np.where(tile, ht * (0.86 * prof + 0.14 * dome), np.where(oldbed, h_old, np.where(grouted, h_grout, h_bed)))
+ if ck is not None:
+ hfield = hfield - 1.6 * ck
+ gy, gx = np.gradient(hfield)
+ gx *= 1.0; gy *= 1.0
+ tlt = TL[ids] * (prof * 0.9 + 0.1)[..., None] * tile[..., None]
+ nx = -gx * ss + tlt[..., 0]; ny = -gy * ss + tlt[..., 1]; nz = np.ones_like(nx)
+ nl = np.sqrt(nx * nx + ny * ny + 1); nx /= nl; ny /= nl; nz /= nl
+ lam = np.clip(nx * L[0] + ny * L[1] + nz * L[2], 0, 1)
+ shd = 0.45 + 0.55 * lam / L[2]
+ sh = height_shadow(hfield * ss, light=tuple(L), reach=7 * ss, step=max(1.0, 0.75 * ss), soft=0.9 * ss)
+ ao = np.clip((blur(hfield, 1.2 * ss) - hfield) / 1.2, 0, 1) * 0.6 + np.clip((blur(hfield, 3.5 * ss) - hfield) / 2.0, 0, 1) * 0.4
+ # albedo
+ mt = MAT[ids]
+ oy, ox = OFF[ids, 0], OFF[ids, 1]
+ ty_, tx_ = (yy + oy) % T, (xx + ox) % T
+ alb = RGB[ids].copy()
+ mo = mott[ty_, tx_] * _MOTTLE[mt]
+ alb *= (1 + mo)[..., None]
+ vv = vein[ty_, tx_] * VEIN[ids] * (mt == 1)
+ alb *= (1 - 0.22 * vv)[..., None]
+ pp = pits[ty_, tx_] * ((mt == 0) | (mt == 3)) * 0.35 + pits[(ty_ + 97) % T, tx_] * (mt == 2) * 0.5
+ alb *= (1 - 0.3 * pp)[..., None]
+ gcol = self.grout * (1 + 0.16 * gs)[..., None]
+ if aged and self.patina_amt: # dirt settles in patches, not everywhere
+ dirt = smoothstep(0.45, 0.85, lf) * 0.26 * self.patina_amt
+ gcol = gcol * (1 - dirt)[..., None]
+ bcol = self.bed * (1 + 0.07 * gs + 0.06 * (lf - 0.5))[..., None]
+ sn = sn_[..., None]
+ bcol = bcol * (1 - sn * 0.72) + hexc(SINOPIA) * sn * 0.72
+ ocol = hexc('#8b7b63') * (1 + 0.16 * gs + 0.2 * (lf - 0.5))[..., None] * (1 - 0.22 * sk)[..., None]
+ nont = np.where(oldbed[..., None], ocol, np.where(grouted[..., None], gcol, bcol))
+ alb = np.where(tile[..., None], alb, nont)
+ if ck is not None:
+ alb *= (1 - 0.75 * np.clip(ck * 1.4, 0, 1))[..., None]
+ nh = np.clip(nx * Hv[0] + ny * Hv[1] + nz * Hv[2], 0, 1)
+ spec = np.where(tile, _SPEC[mt] * nh ** _GLOSS[mt], 0.01 * nh ** 6)
+ if aged and self.patina_amt:
+ spec *= 1 - 0.5 * self.patina_amt * smoothstep(0.45, 0.85, lf)
+ col = alb * (shd * (1 - 0.32 * ao) * (1 - 0.22 * sh))[..., None] + spec[..., None]
+ a0, a1 = ys - ya, ys - ya + min(strip, H - ys)
+ c = col[a0:a1]
+ h_, w_ = c.shape[0] // ss, c.shape[1] // ss
+ out[ys // ss:ys // ss + h_] = c[:h_ * ss, :w_ * ss].reshape(h_, ss, w_, ss, 3).mean((1, 3))
+ # a photograph of a floor: light falls off from the upper left, a touch of warmth
+ yy, xx = np.mgrid[0:self.H, 0:self.W].astype(np.float32)
+ r2 = ((xx - self.W * 0.35) / self.W) ** 2 + ((yy - self.H * 0.3) / self.H) ** 2
+ out *= (1.05 - 0.2 * r2)[..., None]
+ out = np.clip(out, 0, 1) ** np.array([0.97, 1.0, 1.05], np.float32)
+ return Image.fromarray((np.clip(out, 0, 1) * 255).astype(np.uint8))
+
+ # ------------------------------------------------------------ output
+ def stage(self, name):
+ """remember how far the work has got; rendered (at stage_ss) only when save() gets a stages_dir"""
+ self.stages.append((name, len(self.poly), bool(self.lost or self.cracks or self.patina_amt)))
+
+ def save(self, path, stages_dir=None, quality=88):
+ """the picture at ss x supersampling; with stages_dir also every stage, and the finished floor again, at
+ stage_ss -- all snapshots at one resolution, so the animation's last cross-fade only changes what aged"""
+ img = self._render(self.ss, aged=True)
+ if path.lower().endswith(('.jpg', '.jpeg')):
+ img.save(path, quality=quality, subsampling=0)
+ else:
+ img.save(path)
+ if stages_dir:
+ os.makedirs(stages_dir, exist_ok=True)
+ for i, (name, n, aged) in enumerate(self.stages):
+ self._render(self.stage_ss, n, aged).save(f"{stages_dir}/{i:02d}_{name}.png")
+ last = img if self.stage_ss == self.ss else self._render(self.stage_ss, aged=True)
+ last.save(f"{stages_dir}/{len(self.stages):02d}_final.png")
+ return img
diff --git a/lib/patch.py b/lib/patch.py
new file mode 100644
index 0000000..8b2c085
--- /dev/null
+++ b/lib/patch.py
@@ -0,0 +1,765 @@
+"""patch — machine-embroidered patches sewn onto denim: tatami fill, satin stitch, merrowed and hot-cut edges,
+running / sashiko stitch, French knots, a needle and thread (numpy + Pillow only).
+
+Model:
+ denim 3/1 right-hand twill. Indigo warp yarns float over three white weft picks and dive under one, and the
+ float steps one pick every row, so the blue wales climb to the right and a pale weft fleck shows at every
+ fourth crossing. Warp yarns are ring-dyed and slubby: dye depth and thickness wander along every yarn
+ (faint vertical streaks), and the high points are worn toward the white core. Rendered at 2x, averaged.
+ seam a felled seam: the panel above is folded over the one below and held by two rows of lockstitch in
+ tobacco thread; the folded ridge is worn pale ("roping") and throws a little shadow.
+ thread polyester embroidery thread, lit as a round glossy fibre: a cylinder across the stitch that dives into
+ the cloth at both needle holes (so every needle hole is a small dark dimple), with an anisotropic
+ Kajiya-Kay highlight that depends on the stitch *direction*. The same colour sewn at two angles catches
+ the light differently, which is exactly why a real patch reads as stitched and not printed.
+ digitizer every filled shape is stitched the way an embroidery machine does it: parallel rows at a chosen angle
+ (scan lines through the shape), and each row is cut into stitches.
+ tatami short stitches (`length`, about 3 mm) whose needle holes shift a fraction of a stitch every row ->
+ the fine brick / diagonal texture of a background fill;
+ satin one long float across the whole row -> the smooth glossy columns of letters, peaks, flames.
+ Floats longer than `maxlen` are split (split satin) as a digitizer would.
+ The rows end where the shape ends, so the edge of every fill is made of stitch ends; later fills lie
+ on top of earlier ones and cast a thin shadow; each fill is slightly padded (its edges catch light).
+ edges merrow: an overlock wraps thread round and round the cut edge -> a raised rolled cord of slanted wraps
+ around round, oval and rocker patches. Hot-cut: a wide satin column laid along the outline of a
+ die-cut shape, its stitches square to the edge. Both are evaluated at 4 sub-pixel positions (2-3 px wraps
+ would beat against the pixel grid), and where stitches crowd below ~2 px in a tight corner their ridges
+ fade into a smooth fan instead of aliasing into a starburst.
+ attach `blank()` lays the cut twill blank on the denim (a soft shadow, the patch's thickness); `whip()` sews a
+ merrowed patch on by hand with slanted stitches over the edge; `thread()` and `needle()` leave the
+ needle lying on the cloth with the thread still running back to the last stitch.
+
+ from patch import Patch
+ p = Patch(1920, 1080, seed=1)
+ p.denim()
+ b = p.blank(p.circle_pts(960, 540, 200), '#20294a') # a round twill blank
+ p.fill(p.circle(960, 540, 200), '#20294a', angle=30) # tatami background
+ p.fill(p.poly([(820, 640), (960, 420), (1100, 640)]), '#8aa1c4', angle=60) # a peak
+ p.fill(p.poly([(920, 485), (960, 420), (1000, 485)]), '#f2efe8', angle=-35, kind='satin')
+ p.arc_text('HIGH CAMP', 960, 540, 170, size=40, colour='#f3e6c4')
+ p.merrow(b, '#d79b32') # rolled edge
+ p.save('out.jpg')
+Coordinates are output pixels, y down; angles in degrees, counter-clockwise (0 = stitches run left-right).
+Masks are float arrays (H, W) in 0..1, as in stitch.py: combine them with *, np.maximum, 1 - m.
+"""
+import os
+import numpy as np
+from PIL import Image, ImageDraw, ImageFilter
+from core import blur, noise2d, smoothstep, polygon_mask, shift, load_font, text_mask, spline, fbm1d
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+def _c(c):
+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)
+
+
+def _h01(*keys):
+ """deterministic per-stitch random numbers in [0, 1) from integer keys (row, stitch, salt ...)"""
+ arrs = [np.asarray(k).astype(np.int64).astype(np.uint64) for k in keys]
+ out = np.zeros(np.broadcast(*arrs).shape, np.uint64) + np.uint64(0x9E3779B97F4A7C15)
+ with np.errstate(over='ignore'):
+ for k in arrs:
+ out = out ^ (k + np.uint64(0x9E3779B97F4A7C15) + (out << np.uint64(6)) + (out >> np.uint64(2)))
+ out = out * np.uint64(0xBF58476D1CE4E5B9)
+ out = out ^ (out >> np.uint64(31))
+ return ((out >> np.uint64(40)).astype(np.float64) / float(1 << 24)).astype(np.float32)
+
+
+def _resample(P, step, closed):
+ P = np.asarray(P, np.float32)
+ if closed: P = np.vstack([P, P[:1]])
+ seg = np.hypot(*np.diff(P, axis=0).T)
+ cum = np.concatenate([[0], np.cumsum(seg)])
+ n = max(3, int(cum[-1] / step) + 1)
+ t = np.linspace(0, cum[-1], n, endpoint=not closed)
+ return np.stack([np.interp(t, cum, P[:, 0]), np.interp(t, cum, P[:, 1])], 1).astype(np.float32)
+
+
+def smooth_closed(pts, iters=3):
+ """Chaikin corner cutting on a closed outline: rounds every corner a little (die-cut patches have no sharp corners)"""
+ P = np.asarray(pts, np.float32)
+ for _ in range(iters):
+ Q = np.roll(P, -1, 0)
+ P = np.stack([0.75 * P + 0.25 * Q, 0.25 * P + 0.75 * Q], 1).reshape(-1, 2)
+ return P
+
+
+class Blank:
+ """a cut patch blank: its outline (closed polyline, px) and coverage mask"""
+ def __init__(self, pts, mask, colour):
+ self.pts, self.mask, self.colour = pts, mask, colour
+
+
+class Patch:
+ def __init__(self, W=1920, H=1080, seed=0, light=(-0.5, -0.62, 0.6)):
+ self.W, self.H = W, H
+ self.rng = np.random.default_rng(seed)
+ L = np.asarray(light, np.float32)
+ self.L = L / np.linalg.norm(L)
+ Hv = self.L + np.array([0, 0, 1], np.float32)
+ self.Hv = Hv / np.linalg.norm(Hv)
+ self.img = np.full((H, W, 3), 0.45, np.float32)
+ self.stages = []
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ # ================================================================ masks and outlines
+ def circle(self, cx, cy, r):
+ return polygon_mask(self.H, self.W, self.circle_pts(cx, cy, r), ss=2)
+
+ def ring(self, cx, cy, r0, r1):
+ return self.circle(cx, cy, r1) * (1 - self.circle(cx, cy, r0))
+
+ def poly(self, pts, smooth=0):
+ P = smooth_closed(pts, smooth) if smooth else pts
+ return polygon_mask(self.H, self.W, P, ss=2)
+
+ @staticmethod
+ def circle_pts(cx, cy, r, step=2.0):
+ n = max(24, int(2 * np.pi * r / step))
+ t = np.linspace(0, 2 * np.pi, n, endpoint=False)
+ return np.stack([cx + r * np.cos(t), cy - r * np.sin(t)], 1).astype(np.float32)
+
+ @staticmethod
+ def arch_pts(cx, top, w, h, corner=26.0):
+ """die-cut 'tombstone': a half-circle top on straight sides, rounded bottom corners"""
+ r = w / 2; cyc = top + r; bot = top + h
+ t = np.linspace(0, np.pi, 90)
+ arc = np.stack([cx + r * np.cos(t), cyc - r * np.sin(t)], 1) # right -> left over the top
+ pts = [*arc, (cx - r, bot - corner)]
+ t = np.linspace(np.pi, 1.5 * np.pi, 14)
+ pts += list(np.stack([cx - r + corner + corner * np.cos(t), bot - corner - corner * np.sin(t)], 1))
+ t = np.linspace(1.5 * np.pi, 2 * np.pi, 14)
+ pts += list(np.stack([cx + r - corner + corner * np.cos(t), bot - corner - corner * np.sin(t)], 1))
+ return _resample(np.array(pts, np.float32), 2.0, True)
+
+ @staticmethod
+ def rocker_pts(cx, cy, r0, r1, span=90.0, centre=90.0, corner=2):
+ """a 'rocker': the curved banner patch that sits above (centre=90) or below (270) a round patch"""
+ a0, a1 = np.deg2rad(centre + span / 2), np.deg2rad(centre - span / 2)
+ t = np.linspace(a0, a1, 120)
+ outer = np.stack([cx + r1 * np.cos(t), cy - r1 * np.sin(t)], 1)
+ inner = np.stack([cx + r0 * np.cos(t[::-1]), cy - r0 * np.sin(t[::-1])], 1)
+ P = np.vstack([outer, inner])
+ P = _resample(P, 6.0, True)
+ return _resample(smooth_closed(P, corner), 2.0, True)
+
+ def text_mask(self, s, x, y, size, font='rounded', anchor='mm', spacing=0.0, rot=0.0):
+ return text_mask(self.H, self.W, s, load_font(font, size), (x, y), anchor, spacing, rot)
+
+ # ================================================================ the denim
+ def denim(self, colour='#3b5d96', weft='#b9c2cf', warp_px=1.5, pick_px=2.5, fade=0.6, worn='#a3b9da'):
+ """3/1 right-hand twill, rendered at 2x in bands and averaged down. Warp yarns (indigo) are packed tighter
+ than weft picks (ecru), so the wales climb at about 60 degrees, as on real jeans."""
+ ss = 2
+ cw, ch = warp_px * ss, pick_px * ss
+ W2 = self.W * ss
+ rng = np.random.default_rng(self._seed())
+ ncol = int(W2 / cw) + 3
+ nrow = int(self.H * ss / ch) + 3
+ kn = 7 # slub knots every 7 picks along each warp yarn
+ G1 = rng.random((nrow // kn + 3, ncol)).astype(np.float32)
+ G2 = rng.random((nrow // 2 + 3, ncol)).astype(np.float32)
+ dye = rng.normal(0, 1, ncol).astype(np.float32) # dye depth differs yarn to yarn
+ pick = rng.normal(0, 1, nrow).astype(np.float32) # and weft pick to pick
+ cellr = rng.random((nrow, ncol)).astype(np.float32) # how much of each weft fleck peeks out
+ wear = noise2d(self.H // 4, self.W // 4, 60, 4, self._seed())
+ wear = np.asarray(Image.fromarray(wear).resize((self.W, self.H), Image.BICUBIC), np.float32)
+ fold = noise2d(self.H // 4, self.W // 4, 160, 3, self._seed())
+ fold = np.asarray(Image.fromarray(fold).resize((self.W, self.H), Image.BICUBIC), np.float32)
+ col, wcol, wn = _c(colour), _c(weft), _c(worn)
+ L = self.L
+ out = np.empty((self.H, self.W, 3), np.float32)
+ band = 120
+ for yb in range(0, self.H, band):
+ ye = min(self.H, yb + band)
+ yy, xx = np.mgrid[yb * ss:ye * ss, 0:W2].astype(np.float32)
+ yy += 0.5; xx += 0.5
+ cx = (xx / cw).astype(np.int32); cy = (yy / ch).astype(np.int32)
+ fx = xx / cw - cx; fy = yy / ch - cy
+ k = (cx + cy) % 4
+ isw = k == 0 # weft on top
+ tw = ((k - 1) + fy) / 3.0 # position along the 3-pick warp float
+ across = np.where(isw, (fy - 0.5) * 2, (fx - 0.5) * 2)
+ along = np.where(isw, fx, tw)
+ nzc = np.sqrt(np.clip(1 - 0.8 * across ** 2, 0.05, 1))
+ end = np.clip(np.sin(np.pi * np.clip(along, 0, 1)), 0, 1) ** np.where(isw, 1.2, 0.35)
+ side = np.where(isw, across * L[1], across * L[0]) / np.hypot(L[0], L[1])
+ shade = 0.6 + 0.32 * nzc * end - 0.1 * side
+ # slubs: dye and thickness wander along every warp yarn
+ fyk = yy / (ch * kn); i0 = np.minimum(fyk.astype(np.int32), G1.shape[0] - 2); w = fyk - i0
+ sl1 = G1[i0, cx] * (1 - w) + G1[i0 + 1, cx] * w
+ fyk = yy / (ch * 2); i0 = np.minimum(fyk.astype(np.int32), G2.shape[0] - 2); w = fyk - i0
+ sl2 = G2[i0, cx] * (1 - w) + G2[i0 + 1, cx] * w
+ depth = 1 + 0.06 * dye[cx] + 0.2 * (sl1 - 0.5) + 0.12 * (sl2 - 0.5)
+ twist = 0.05 * np.sin(2 * np.pi * (fy * 1.6 + fx * 1.1))
+ wr = wear[np.minimum(yy.astype(np.int32) // ss, self.H - 1), np.minimum(xx.astype(np.int32) // ss, self.W - 1)]
+ top = np.clip(nzc * end, 0, 1) ** 2
+ ring = np.clip(fade * (0.25 + 0.75 * smoothstep(0.3, 0.9, wr)) * top * np.clip(1.3 - depth, 0, 1) * 0.8, 0, 0.8)
+ warp = col * (depth * (shade + twist))[..., None]
+ warp = warp * (1 - ring[..., None]) + wn * shade[..., None] * ring[..., None]
+ peek = cellr[cy, cx]
+ wv = (0.45 + 0.55 * nzc * end) * (0.55 + 0.6 * peek) * (1 + 0.04 * pick[cy])
+ wf = wcol * wv[..., None]
+ wf = wf * 0.8 + col * 0.2 * shade[..., None]
+ px = np.where(isw[..., None], wf, warp)
+ out[yb:ye] = px.reshape(ye - yb, ss, self.W, ss, 3).mean((1, 3))
+ gy, gx = np.gradient(fold * 40)
+ lightf = 1 + 0.5 * np.clip(-(gx * L[0] + gy * L[1]), -0.2, 0.2)
+ YY, XX = np.mgrid[0:self.H, 0:self.W].astype(np.float32)
+ grad = 1.06 - 0.12 * (XX / self.W * 0.6 + YY / self.H * 0.4)
+ self.img = out * (lightf * grad)[..., None]
+ self.denim_colour = col
+
+ def seam(self, pts, thread='#d49a35', rows=(10.0, 25.0), stitch=9.0, gap=2.6, fold=34.0, wear=0.8):
+ """a felled seam along `pts` (left to right): the panel above is folded over the one below, two rows of
+ lockstitch hold it, and the folded ridge is worn pale"""
+ P = spline(pts, 40)
+ g = self._pparam(P, False, fold + 16)
+ if g is None: return
+ ys, xs, s, d, tx, ty, win = g['ys'], g['xs'], g['s'], g['d'], g['tx'], g['ty'], g['win']
+ y0, y1, x0, x1 = win
+ nx, ny = -ty, tx # d > 0 below the line
+ # height across the seam: fold ridge, double-layer plateau, then the buried edge of the allowance
+ ridge = np.exp(-((d + 1.5) / 3.2) ** 2) * 2.6
+ plate = smoothstep(-2, 1, d) * (1 - smoothstep(fold - 1, fold + 4, d)) * 2.0
+ pull = sum(np.exp(-((d - r) / 2.2) ** 2) for r in rows) * 0.9
+ h = ridge + plate - pull
+ # slope by finite difference of the same profile
+ e = 0.5
+ def prof(dd):
+ return (np.exp(-((dd + 1.5) / 3.2) ** 2) * 2.6 + smoothstep(-2, 1, dd) * (1 - smoothstep(fold - 1, fold + 4, dd)) * 2.0
+ - sum(np.exp(-((dd - r) / 2.2) ** 2) for r in rows) * 0.9)
+ dh = (prof(d + e) - prof(d - e)) / (2 * e)
+ lit = 1 - 0.35 * dh * (nx * self.L[0] + ny * self.L[1]) / np.hypot(self.L[0], self.L[1])
+ groove = 1 - 0.28 * np.exp(-((d - 0.8) / 1.6) ** 2) - 0.12 * np.exp(-((d - fold - 3) / 2.5) ** 2)
+ n1 = fbm1d(int(s.max()) + 64, 60, 4, self._seed())
+ rope = smoothstep(0.05, 0.6, n1[np.clip(s.astype(np.int64), 0, len(n1) - 1)])
+ worn = wear * np.clip(ridge / 2.6, 0, 1) * (0.35 + 0.65 * rope)
+ sub = self.img[y0:y1, x0:x1]
+ cur = sub[ys, xs]
+ cur = cur * (lit * groove)[:, None]
+ cur = cur * (1 - 0.55 * worn[:, None]) + _c('#a9bfdc') * (0.95 * worn)[:, None]
+ sub[ys, xs] = cur
+ # two rows of topstitching
+ tg = np.gradient(P, axis=0); tg /= np.linalg.norm(tg, axis=1, keepdims=True) + 1e-6
+ nrm = np.stack([-tg[:, 1], tg[:, 0]], 1)
+ for i, r in enumerate(rows):
+ self.run(P + nrm * r, thread, stitch=stitch, gap=gap, width=3.1, smooth=False, sheen=0.55,
+ twist=0.6, start=i * 3.0, shadow=0.45)
+
+ # ================================================================ blanks
+ def blank(self, pts, colour='#ece2c9', shadow=0.5):
+ """lay a cut twill blank on the denim; returns a Blank for the edge and whip stitches"""
+ P = np.asarray(pts, np.float32)
+ m = polygon_mask(self.H, self.W, P, ss=2)
+ x0, y0, x1, y1 = self._bbox(m, 16)
+ sub = self.img[y0:y1, x0:x1]; mm = m[y0:y1, x0:x1]
+ sh = blur(shift(mm, 4, 6), 5.0)
+ sub *= (1 - shadow * sh * (1 - mm))[..., None]
+ sub *= (1 - 0.25 * blur(mm, 1.5) * (1 - mm))[..., None]
+ YY, XX = np.mgrid[y0:y1, x0:x1].astype(np.float32)
+ tw = 0.94 + 0.06 * (((XX + YY) // 2) % 2) + 0.03 * np.sin((XX - YY) * 0.9)
+ cut = smoothstep(0.0, 3.0, blur(mm, 1.2) * 6) # the cut edge frays a hair darker
+ face = _c(colour) * (tw * (0.9 + 0.1 * cut))[..., None]
+ sub[:] = sub * (1 - mm[..., None]) + face * mm[..., None]
+ return Blank(P, m, colour)
+
+ # ================================================================ lighting of a thread
+ def _thread_rgb(self, col, v, g, d, p, ao=1.0, rnd=0.0, sheen=1.0, gloss=14.0, twist=0.0, along=None, width=3.0):
+ """colour of a round glossy thread. v: -1..1 across the thread; g: slope dz/ds along it;
+ d / p: unit vectors (x, y) along / across the thread (scalars or arrays)"""
+ L, Hv = self.L, self.Hv
+ nzc = np.sqrt(np.clip(1 - 0.9 * v * v, 0.04, 1))
+ nx = p[0] * v - g * nzc * d[0]
+ ny = p[1] * v - g * nzc * d[1]
+ nz = nzc
+ nn = np.sqrt(nx * nx + ny * ny + nz * nz)
+ nx, ny, nz = nx / nn, ny / nn, nz / nn
+ diff = np.clip(nx * L[0] + ny * L[1] + nz * L[2], 0, 1)
+ tn = np.sqrt(1 + g * g)
+ TH = (d[0] * Hv[0] + d[1] * Hv[1] + g * Hv[2]) / tn
+ aniso = np.sqrt(np.clip(1 - TH * TH, 0, 1)) ** gloss # Kajiya-Kay: sheen depends on stitch direction
+ nh = np.clip(nx * Hv[0] + ny * Hv[1] + nz * Hv[2], 0, 1)
+ spec = sheen * (0.42 * aniso * nh ** 6 + 0.2 * nh ** 40)
+ shade = (0.28 + 0.98 * diff) * ao * (1 + rnd)
+ if twist and along is not None:
+ shade = shade * (1 + 0.07 * twist * np.sin(2 * np.pi * (along + v * width * 0.7) / (width * 1.3)) * nzc)
+ col = _c(col)
+ rgb = col * shade[..., None] + (spec * 0.62)[..., None] * (0.5 + 0.5 * col)
+ return rgb
+
+ def _put(self, win, a, rgb, shadow=0.35, off=(1.4, 1.9), soft=1.3):
+ y0, y1, x0, x1 = win
+ sub = self.img[y0:y1, x0:x1]
+ if shadow:
+ sh = blur(shift(a, off[0], off[1]), soft)
+ sub *= (1 - shadow * sh * (1 - a))[..., None]
+ sub[:] = sub * (1 - a[..., None]) + np.clip(rgb, 0, 1.2) * a[..., None]
+
+ def _bbox(self, m, pad):
+ ys, xs = np.nonzero(m > 0.01)
+ if len(ys) == 0: return None
+ return (max(0, xs.min() - pad), max(0, ys.min() - pad), min(self.W, xs.max() + pad + 1), min(self.H, ys.max() + pad + 1))
+
+ # ================================================================ the digitizer: rows of stitches through a shape
+ def _scan(self, m, x0, y0, angle, pitch, length=None, stagger=0.3, maxlen=None, jitter=0.6, salt=0):
+ h, w = m.shape
+ th = np.deg2rad(angle)
+ dx, dy = float(np.cos(th)), float(-np.sin(th)) # along the stitches
+ px, py = -dy, dx # across the rows
+ yy, xx = np.mgrid[y0:y0 + h, x0:x0 + w].astype(np.float32)
+ A = xx * dx + yy * dy
+ C = xx * px + yy * py
+ rowf = C / pitch
+ rfl = np.floor(rowf)
+ v = (rowf - rfl) * 2 - 1
+ r0 = int(rfl.min()); ri = (rfl - r0).astype(np.int32); nr = int(ri.max()) + 1
+ a0 = float(np.floor(A.min())) - 1; n = int(np.ceil(A.max() - a0)) + 2
+ ks = a0 + np.arange(n, dtype=np.float32)
+ cs = (r0 + np.arange(nr, dtype=np.float32) + 0.5) * pitch
+ SX = ks[None, :] * dx + cs[:, None] * px - x0
+ SY = ks[None, :] * dy + cs[:, None] * py - y0
+ ix = np.rint(SX).astype(np.int32); iy = np.rint(SY).astype(np.int32)
+ ok = (ix >= 0) & (ix < w) & (iy >= 0) & (iy < h)
+ samp = np.zeros((nr, n), bool)
+ samp[ok] = m[iy[ok], ix[ok]] > 0.5
+ prev = np.zeros_like(samp); prev[:, 1:] = samp[:, :-1]
+ nxt = np.zeros_like(samp); nxt[:, :-1] = samp[:, 1:]
+ st = samp & ~prev; en = samp & ~nxt
+ cum = np.cumsum(st.ravel()).reshape(nr, n)
+ nrun = int(cum[-1, -1])
+ if nrun == 0: return None
+ fs = np.flatnonzero(st); fe = np.flatnonzero(en)
+ RS = np.zeros(nrun + 2, np.float32); RE = np.zeros(nrun + 2, np.float32); RR = np.full(nrun + 2, -1, np.int64)
+ RS[1:nrun + 1] = fs % n; RE[1:nrun + 1] = fe % n; RR[1:nrun + 1] = fs // n
+ rows = np.arange(nr)[:, None]; kk = np.arange(n)[None, :]
+ pid = cum; nid = np.minimum(cum + 1, nrun + 1)
+ pok = RR[pid] == rows; nok = RR[nid] == rows
+ dp = np.where(pok, kk - RE[pid], 1e9); dn = np.where(nok, RS[nid] - kk, 1e9)
+ ID = np.where(samp, cum, np.where(dp <= dn, np.where(pok, pid, 0), np.where(nok, nid, 0)))
+ kp = np.clip(np.rint(A - a0).astype(np.int32), 0, n - 1)
+ rid = ID[ri, kp]
+ valid = rid > 0
+ S = a0 + RS[rid] - 0.5 + (_h01(rid, salt, 1) - 0.5) * 2 * jitter
+ E = a0 + RE[rid] + 0.5 + (_h01(rid, salt, 2) - 0.5) * 2 * jitter
+ rowg = ri + r0
+ if length:
+ Ls = float(length)
+ off = (np.mod(rowg * stagger, 1.0) + (_h01(rowg, salt, 5) - 0.5) * 0.12) * Ls # machines drift a little
+ j = np.floor((A + off) / Ls)
+ s0 = np.maximum(j * Ls - off, S); s1 = np.minimum(j * Ls - off + Ls, E)
+ elif maxlen:
+ Lr = np.maximum(E - S, 1.0)
+ m_ = np.maximum(1, np.ceil(Lr / maxlen)); Lg = Lr / m_
+ off = (rowg % 2) * 0.5 * Lg * (m_ > 1)
+ j = np.floor((A - S + off) / Lg)
+ s0 = np.maximum(S + j * Lg - off, S); s1 = np.minimum(S + (j + 1) * Lg - off, E)
+ else:
+ j = np.zeros_like(A); s0, s1 = S, E
+ Lst = np.maximum(s1 - s0, 0.6)
+ t = np.clip((A - s0) / Lst, 0, 1)
+ dout = np.maximum(np.maximum(S - A, A - E), 0)
+ cap = np.where(dout > 0, np.hypot(dout, np.abs(v) * pitch * 0.5), 0)
+ a = np.clip((pitch * 0.5 - cap) / 0.9 + 0.5, 0, 1) * valid
+ de = np.minimum(A - s0, s1 - A)
+ rho = pitch * 0.8
+ u = np.clip(1 - np.maximum(de, 0) / rho, 0, 0.96)
+ hz = np.sqrt(1 - u * u)
+ g = np.clip(u / hz, 0, 3) * np.where(A - s0 < s1 - A, 1.0, -1.0)
+ if not length:
+ hb = np.minimum(Lst * 0.11, 3.2)
+ g = g + hb * np.pi * np.cos(np.pi * t) / Lst
+ rnd = (_h01(rid, j.astype(np.int64), salt) - 0.5) * 2
+ return dict(a=a, v=v, g=g, hz=hz, rnd=rnd, d=(dx, dy), p=(px, py), A=A)
+
+ def fill(self, mask, colour, angle=45.0, kind='tatami', pitch=None, length=None, stagger=0.3, maxlen=None,
+ sheen=1.0, shadow=0.32, jitter=None, pad=1.0):
+ """stitch a shape. kind='tatami': short staggered stitches (backgrounds, big areas);
+ kind='satin': one float per row (letters, narrow shapes; split above `maxlen` px)"""
+ satin = kind == 'satin'
+ pitch = pitch or (2.2 if satin else 2.6)
+ if not satin: length = length or 15.0
+ if satin and maxlen is None: maxlen = 64.0
+ jitter = (0.5 if satin else 0.7) if jitter is None else jitter
+ bb = self._bbox(mask, 8)
+ if bb is None: return
+ x0, y0, x1, y1 = bb
+ m = mask[y0:y1, x0:x1]
+ r = self._scan(m, x0, y0, angle, pitch, None if satin else length, stagger, maxlen if satin else None,
+ jitter, salt=self._seed() % 100000)
+ if r is None: return
+ gro = 0.74 if satin else 0.62
+ ao = (gro + (1 - gro) * np.sqrt(np.clip(1 - 0.9 * r['v'] ** 2, 0, 1)) ** 0.7) * (0.7 + 0.3 * r['hz'])
+ if pad:
+ dome = blur(m, pitch * 1.6)
+ gy, gx = np.gradient(dome)
+ ao = ao * (1 + np.clip(-(gx * self.L[0] + gy * self.L[1]) * 5 * pad, -0.22, 0.22))
+ rgb = self._thread_rgb(colour, r['v'] * (0.7 if satin else 1.0), r['g'], r['d'], r['p'], ao, r['rnd'] * (0.035 if satin else 0.05), sheen,
+ gloss=16 if satin else 12)
+ self._put((y0, y1, x0, x1), r['a'], rgb, shadow)
+
+ # ================================================================ stitches along a path
+ def _pparam(self, P, closed, maxd, inside=None):
+ """for every pixel within maxd of polyline P: arclength s of the nearest point, signed distance d
+ (closed: + outside; open: + on the left-hand normal (-ty, tx)), the unit tangent there"""
+ P = np.asarray(P, np.float32)
+ if closed: P = np.vstack([P, P[:1]])
+ seg = P[1:] - P[:-1]
+ sl = np.hypot(seg[:, 0], seg[:, 1])
+ keep = sl > 1e-3
+ A0, seg, sl = P[:-1][keep], seg[keep], sl[keep]
+ if len(sl) == 0: return None
+ cum = np.concatenate([[0], np.cumsum(sl)]).astype(np.float32)
+ x0 = int(max(0, np.floor(P[:, 0].min() - maxd - 3))); x1 = int(min(self.W, np.ceil(P[:, 0].max() + maxd + 4)))
+ y0 = int(max(0, np.floor(P[:, 1].min() - maxd - 3))); y1 = int(min(self.H, np.ceil(P[:, 1].max() + maxd + 4)))
+ if x1 <= x0 or y1 <= y0: return None
+ im = Image.new('L', (x1 - x0, y1 - y0), 0)
+ ImageDraw.Draw(im).line([(float(x) - x0, float(y) - y0) for x, y in P], fill=255, width=int(2 * maxd + 6), joint='curve')
+ for q in (P[0], P[-1]):
+ ImageDraw.Draw(im).ellipse((q[0] - x0 - maxd - 3, q[1] - y0 - maxd - 3, q[0] - x0 + maxd + 3, q[1] - y0 + maxd + 3), fill=255)
+ im = im.filter(ImageFilter.MaxFilter(5)) # PIL's wide polylines leave pinholes
+ ys, xs = np.nonzero(np.asarray(im) > 0)
+ X = xs.astype(np.float32) + x0; Y = ys.astype(np.float32) + y0
+ N = len(X); M = len(sl)
+ s = np.empty(N, np.float32); dist = np.empty(N, np.float32); tx = np.empty(N, np.float32); ty = np.empty(N, np.float32)
+ side = np.empty(N, np.float32)
+ ch = max(256, 3_000_000 // M)
+ ux, uy = seg[:, 0] / sl, seg[:, 1] / sl
+ for i in range(0, N, ch):
+ wx = X[i:i + ch, None] - A0[None, :, 0]; wy = Y[i:i + ch, None] - A0[None, :, 1]
+ proj = wx * ux[None] + wy * uy[None]
+ tt = np.clip(proj, 0, sl[None])
+ ex = wx - tt * ux[None]; ey = wy - tt * uy[None]
+ dd = ex * ex + ey * ey
+ k = np.argmin(dd, axis=1); rr = np.arange(len(k))
+ pk = proj[rr, k]
+ if not closed: # extend s beyond the two ends
+ pk = np.where(k == 0, np.minimum(pk, sl[0]), pk)
+ pk = np.where(k == M - 1, np.maximum(pk, 0), pk)
+ pk = np.where((k > 0) & (k < M - 1), tt[rr, k], pk)
+ else:
+ pk = tt[rr, k]
+ s[i:i + ch] = cum[k] + pk
+ dist[i:i + ch] = np.sqrt(dd[rr, k])
+ tx[i:i + ch] = ux[k]; ty[i:i + ch] = uy[k]
+ side[i:i + ch] = np.sign(ux[k] * ey[rr, k] - uy[k] * ex[rr, k] + 1e-9)
+ sel = dist <= maxd
+ ys, xs, s, dist, tx, ty, side = ys[sel], xs[sel], s[sel], dist[sel], tx[sel], ty[sel], side[sel]
+ if closed:
+ if inside is None: inside = polygon_mask(self.H, self.W, P, ss=1)
+ ins = inside[ys + y0, xs + x0] > 0.5
+ d = np.where(ins, -dist, dist)
+ nrm = np.where(ins, -side, side) # +1 when the left normal points outward
+ o = np.sign(np.mean(nrm) + 1e-9)
+ nx, ny = -ty * o, tx * o # outward normal
+ else:
+ d = dist * side
+ nx, ny = -ty, tx
+ return dict(ys=ys, xs=xs, s=s, d=d, tx=tx, ty=ty, nx=nx, ny=ny, win=(y0, y1, x0, x1), length=float(cum[-1]))
+
+ def _resolve(self, g, ph, lo=1.2, hi=2.1):
+ """0..1 per band pixel: how well the stitches resolve. Inside tight curves radial stitches crowd below a pixel
+ and would alias into a starburst; there the ridges are faded and the thread reads as a smooth fan."""
+ y0, y1, x0, x1 = g['win']
+ F = np.zeros((y1 - y0, x1 - x0), np.float32); M = np.zeros_like(F)
+ F[g['ys'], g['xs']] = ph; M[g['ys'], g['xs']] = 1
+ gy, gx = np.gradient(F)
+ f = np.hypot(gx, gy)[g['ys'], g['xs']]
+ f = np.where(f > 4.0, 0.0, f) # the closing seam / band edge: ignore
+ return smoothstep(lo, hi, 1.0 / np.maximum(f, 1e-3))
+
+ def _scatter(self, g, a, rgb):
+ y0, y1, x0, x1 = g['win']
+ A = np.zeros((y1 - y0, x1 - x0), np.float32); R = np.zeros((y1 - y0, x1 - x0, 3), np.float32)
+ A[g['ys'], g['xs']] = a; R[g['ys'], g['xs']] = rgb
+ return A, R
+
+ def run(self, pts, colour, stitch=10.0, gap=3.0, width=2.6, smooth=True, sheen=1.0, twist=0.0, shadow=0.4,
+ start=0.0, off=(1.4, 1.9), soft=1.3, clip=None):
+ """running stitch along a path: `stitch` px on top, `gap` px under. gap=0 and a huge stitch = one
+ continuous thread (see thread()). clip: a mask the stitches must stay inside (e.g. a patch)"""
+ P = spline(pts, 12) if smooth and len(pts) > 2 else np.asarray(pts, np.float32)
+ rho = width / 2
+ g = self._pparam(P, False, rho + 2)
+ if g is None: return
+ s, d = g['s'], g['d']
+ Ltot = g['length']
+ per = stitch + gap
+ q = (s - start) / per
+ j = np.floor(q); loc = (q - j) * per
+ ins = loc <= stitch
+ ds = np.where(ins, 0, np.minimum(loc - stitch, per - loc))
+ ds = np.maximum(ds, np.maximum(-s, s - Ltot))
+ rr = np.hypot(ds, d)
+ a = np.clip((rho - rr) / 0.8 + 0.5, 0, 1)
+ v = np.clip(d / rho, -1, 1)
+ e0 = np.minimum(np.where(ins, np.minimum(loc, stitch - loc), 0), np.minimum(s, Ltot - s))
+ rho_e = rho * 1.3
+ u = np.clip(1 - np.maximum(e0, 0) / rho_e, 0, 0.96)
+ hz = np.sqrt(1 - u * u)
+ first = np.where(ins, loc < stitch / 2, loc - stitch > per - loc)
+ first = np.where(s < rho_e, True, np.where(Ltot - s < rho_e, False, first))
+ gz = np.clip(u / hz, 0, 3) * np.where(first, 1.0, -1.0)
+ ao = (0.62 + 0.38 * np.sqrt(np.clip(1 - 0.9 * v * v, 0, 1))) * (0.6 + 0.4 * hz)
+ jj = np.where(ins | (loc - stitch < per - loc), j, j + 1).astype(np.int64)
+ rnd = (_h01(jj, 7) - 0.5) * 0.08
+ rgb = self._thread_rgb(colour, v, gz, (g['tx'], g['ty']), (g['nx'], g['ny']), ao, rnd, sheen,
+ twist=twist, along=s, width=width)
+ if clip is not None:
+ y0, x0 = g['win'][0], g['win'][2]
+ a = a * clip[g['ys'] + y0, g['xs'] + x0]
+ A, R = self._scatter(g, a, rgb)
+ self._put(g['win'], A, R, shadow, off, soft)
+
+ def thread(self, pts, colour, width=2.6, sheen=0.5, twist=1.0, shadow=0.45, lift=1.0):
+ """a loose length of sewing thread lying on the cloth (twisted plies, a shadow that grows with `lift`)"""
+ self.run(pts, colour, stitch=1e7, gap=0.0, width=width, sheen=sheen, twist=twist, shadow=shadow,
+ off=(2.0 * lift + 0.5, 2.6 * lift + 0.6), soft=1.2 + 0.8 * lift)
+
+ def knot(self, x, y, colour, r=4.5, shadow=0.45):
+ """French knot / satin dot: a small bead of wrapped thread (stars, sparks)"""
+ m = int(r + 6)
+ x0, x1, y0, y1 = int(max(0, x - m)), int(min(self.W, x + m + 1)), int(max(0, y - m)), int(min(self.H, y + m + 1))
+ YY, XX = np.mgrid[y0:y1, x0:x1].astype(np.float32)
+ X, Y = XX - x, YY - y
+ dd = np.hypot(X, Y) / r
+ a = np.clip((1 - dd) * r / 0.8 + 0.5, 0, 1)
+ nz = np.sqrt(np.clip(1 - dd ** 2, 0.02, 1)); nx, ny = X / r, Y / r
+ nn = np.sqrt(nx * nx + ny * ny + nz * nz); nx, ny, nz = nx / nn, ny / nn, nz / nn
+ diff = np.clip(nx * self.L[0] + ny * self.L[1] + nz * self.L[2], 0, 1)
+ wrap = np.sin(np.arctan2(Y, X) * 3 + dd * 7)
+ nh = np.clip(nx * self.Hv[0] + ny * self.Hv[1] + nz * self.Hv[2], 0, 1)
+ col = _c(colour)
+ rgb = col * ((0.3 + 0.95 * diff) * (1 + 0.1 * wrap * nz))[..., None] + (0.35 * nh ** 30)[..., None] * (0.6 + 0.4 * col)
+ self._put((y0, y1, x0, x1), a, rgb, shadow)
+
+ def star(self, x, y, r, colour, angle=0.0, inner=0.3, points=4):
+ """a little satin star (each arm its own satin column, stitched along the arm)"""
+ for k in range(points):
+ ph = np.deg2rad(angle + 360.0 * k / points)
+ tip = (x + r * np.cos(ph), y - r * np.sin(ph))
+ w = r * inner
+ l = (x + w * np.cos(ph + np.pi / 2), y - w * np.sin(ph + np.pi / 2))
+ rr = (x + w * np.cos(ph - np.pi / 2), y - w * np.sin(ph - np.pi / 2))
+ self.fill(self.poly([l, tip, rr, (x, y)]), colour, angle=np.rad2deg(ph) + 90, kind='satin', pitch=1.8,
+ shadow=0.25, pad=0.5)
+
+ # ================================================================ edges
+ _SUB = ((-0.25, -0.25), (0.25, -0.25), (-0.25, 0.25), (0.25, 0.25))
+
+ def _supersample(self, g, fn):
+ """evaluate fn(s, d) -> (coverage, rgb) at 4 sub-pixel positions (moved along the local tangent / normal)
+ and average: wraps and stitches 2-3 px apart would otherwise beat against the pixel grid (moire)"""
+ A = 0; C = 0
+ for ox, oy in self._SUB:
+ ds = ox * g['tx'] + oy * g['ty']; dd = ox * g['nx'] + oy * g['ny']
+ a, rgb = fn(g['s'] + ds, g['d'] + dd)
+ A = A + a; C = C + rgb * a[:, None]
+ A = A / len(self._SUB)
+ return A, C / np.maximum(A * len(self._SUB), 1e-6)[:, None]
+
+ def merrow(self, blank, colour, width=18.0, pitch=2.6, slant=0.55, shadow=0.55):
+ """merrowed (overlocked) edge: thread wrapped round and round the cut edge -> a raised rolled cord"""
+ P = blank.pts
+ R = width / 2; c_off = -0.3 * width
+ g = self._pparam(P, True, abs(c_off) + R + 3, inside=blank.mask)
+ if g is None: return
+ tx, ty, nx, ny = g['tx'], g['ty'], g['nx'], g['ny']
+ per = g['length']
+ nw = max(8, int(round(per / pitch))); pit = per / nw
+ si = np.clip(g['s'].astype(np.int64), 0, int(per) + 7)
+ Rr = R * (1 + 0.04 * fbm1d(int(per) + 8, 40, 3, self._seed())[si])
+ jit = fbm1d(int(per) + 8, 24, 2, self._seed())[si] * 0.08
+ res = self._resolve(g, (g['s'] + slant * (g['d'] - c_off)) / pit + jit)
+ L, Hv = self.L, self.Hv
+ col = _c(colour)
+
+ def ev(s, d):
+ dc = d - c_off
+ u = np.clip(dc / Rr, -1, 1)
+ a = np.clip((Rr - np.abs(dc)) / 0.9 + 0.5, 0, 1)
+ ph = (s + slant * dc) / pit + jit
+ w = ((ph - np.floor(ph)) * 2 - 1) * res
+ nzt = np.sqrt(np.clip(1 - u * u, 0.03, 1))
+ wz = np.sqrt(np.clip(1 - 0.85 * w * w, 0.05, 1))
+ Nx = nx * u * wz + tx * w * 0.6; Ny = ny * u * wz + ty * w * 0.6; Nz = nzt * wz
+ nn = np.sqrt(Nx * Nx + Ny * Ny + Nz * Nz); Nx, Ny, Nz = Nx / nn, Ny / nn, Nz / nn
+ Tx = nx * nzt - tx * slant * 0.6; Ty = ny * nzt - ty * slant * 0.6; Tz = -u
+ tn = np.sqrt(Tx * Tx + Ty * Ty + Tz * Tz); Tx, Ty, Tz = Tx / tn, Ty / tn, Tz / tn
+ diff = np.clip(Nx * L[0] + Ny * L[1] + Nz * L[2], 0, 1)
+ TH = Tx * Hv[0] + Ty * Hv[1] + Tz * Hv[2]
+ aniso = np.sqrt(np.clip(1 - TH * TH, 0, 1)) ** 10
+ nh = np.clip(Nx * Hv[0] + Ny * Hv[1] + Nz * Hv[2], 0, 1)
+ spec = 0.42 * aniso * nh ** 5 + 0.18 * nh ** 36
+ rnd = (_h01(np.floor(ph).astype(np.int64), 3) - 0.5) * 0.07
+ ao = (0.6 + 0.4 * wz) * (0.7 + 0.3 * nzt)
+ rgb = col * ((0.28 + 0.98 * diff) * ao * (1 + rnd))[:, None] + (spec * 0.7)[:, None] * (0.5 + 0.5 * col)
+ return a, rgb
+
+ a, rgb = self._supersample(g, ev)
+ A, Rg = self._scatter(g, a, rgb)
+ self._put(g['win'], A, Rg, shadow, off=(2.2, 3.0), soft=2.4)
+
+ def column(self, pts, colour, width=8.0, closed=False, pitch=2.2, smooth=True, inset=None, shadow=0.4, blank=None):
+ """satin column along a path: stitches laid square to the path, side by side (ring separators, logs,
+ tent poles, the hot-cut border). For a closed outline `inset` moves the column inward (0 = centred)."""
+ P = np.asarray(pts, np.float32)
+ if smooth and not closed and len(P) > 2: P = spline(P, 12)
+ hw = width / 2
+ off = 0.0 if inset is None else -inset
+ g = self._pparam(P, closed, abs(off) + hw + 3, inside=None if blank is None else blank.mask)
+ if g is None: return
+ tx, ty, nx, ny = g['tx'], g['ty'], g['nx'], g['ny']
+ per = g['length']
+ n = max(4, int(round(per / pitch))); pit = per / n
+ res = self._resolve(g, g['s'] / pit)
+ col = colour
+
+ def ev(s, d):
+ ph = s / pit; j = np.floor(ph).astype(np.int64)
+ v = ((ph - j) * 2 - 1) * res
+ jj = j % n if closed else j
+ din = off - hw + (_h01(jj, 11) - 0.5) * 0.9
+ dout = off + hw + (_h01(jj, 12) - 0.5) * (0.6 if blank is not None else 1.6)
+ if not closed: # square ends: stitches only between 0..length
+ v = np.where((s < 0) | (s > per), 1.0, v)
+ Lc = dout - din
+ e = np.minimum(d - din, dout - d)
+ a = np.clip(e / 0.8 + 0.5, 0, 1)
+ if not closed:
+ a = a * np.clip((np.minimum(s, per - s) + 0.6) / 0.9, 0, 1)
+ t = np.clip((d - din) / Lc, 0, 1)
+ rho = pitch * 0.9
+ u = np.clip(1 - np.maximum(e, 0) / rho, 0, 0.96); hz = np.sqrt(1 - u * u)
+ gz = np.clip(u / hz, 0, 3) * np.where(d - din < dout - d, 1.0, -1.0)
+ hb = min(1.8, width * 0.12)
+ gz = gz + hb * np.pi * np.cos(np.pi * t) / Lc
+ ao = (0.74 + 0.26 * np.sqrt(np.clip(1 - 0.9 * v * v, 0, 1))) * (0.62 + 0.38 * hz)
+ rnd = (_h01(jj, 13) - 0.5) * 0.035
+ return a, self._thread_rgb(col, v * 0.6, gz, (nx, ny), (tx, ty), ao, rnd, 1.0, gloss=16)
+
+ a, rgb = self._supersample(g, ev)
+ A, R = self._scatter(g, a, rgb)
+ self._put(g['win'], A, R, shadow, off=(1.6, 2.2), soft=1.6)
+
+ def satin_border(self, blank, colour, width=16.0, pitch=2.2, shadow=0.45):
+ """hot-cut border of a die-cut patch: a wide satin column along the outline, stitches square to the edge,
+ reaching a hair past the cut edge (the twill is melted flush underneath)"""
+ self.column(blank.pts, colour, width=width + 1.6, closed=True, pitch=pitch, inset=width / 2 - 0.8,
+ shadow=shadow, blank=blank)
+
+ def whip(self, blank, colour, frm=0.0, to=1.0, spacing=20.0, reach=(5.0, 16.0), lean=6.0, width=2.4):
+ """hand-sew a patch on: slanted whip stitches over the edge from the denim into the patch, for the part of
+ the outline between fractions frm..to of its length. Returns the point where the last stitch went in."""
+ P = _resample(blank.pts, 1.0, True)
+ n = len(P)
+ tg = np.roll(P, -2, 0) - np.roll(P, 2, 0); tg /= np.linalg.norm(tg, axis=1, keepdims=True) + 1e-6
+ nrm = np.stack([tg[:, 1], -tg[:, 0]], 1)
+ cen = P.mean(0)
+ if np.mean(np.sum((P - cen) * nrm, 1)) < 0: nrm = -nrm # outward
+ k0, k1 = int(frm * n), int(to * n)
+ step = max(1, int(spacing))
+ last = None
+ for i, k in enumerate(range(k0, k1, step)):
+ k = k % n; kb = (k + int(lean)) % n
+ jit = (_h01(np.array([i]), 21)[0] - 0.5) * 3
+ pa = P[k] + nrm[k] * (reach[0] + jit * 0.4)
+ pb = P[kb] - nrm[kb] * (reach[1] + jit)
+ self.run([pa, pb], colour, stitch=1e6, gap=0, width=width, smooth=False, sheen=0.4, twist=1.0,
+ shadow=0.4, off=(1.2, 1.6))
+ last = pa
+ return last
+
+ # ================================================================ lettering
+ def text(self, s, x, y, size, colour, font='rounded', angle=55.0, anchor='mm', spacing=0.0, rot=0.0, pitch=1.9):
+ """satin letters (one satin angle for the whole word, slanted across the strokes)"""
+ self.fill(self.text_mask(s, x, y, size, font, anchor, spacing, rot), colour, angle=angle + rot, kind='satin',
+ pitch=pitch, shadow=0.35, pad=0.6)
+
+ def arc_text(self, s, cx, cy, r, size=40, colour='#f3e6c4', centre=90.0, font='rounded', spacing=0.06,
+ bottom=False, angle=55.0, pitch=1.9):
+ """satin letters set on a circle: centre=90 reads along the top (letters stand outward),
+ bottom=True reads along the bottom (letters stand inward)"""
+ f = load_font(font, size)
+ adv = [f.getlength(ch) + spacing * size for ch in s]
+ total = sum(adv) - spacing * size
+ pos = np.cumsum([0] + adv[:-1]) + np.array([f.getlength(ch) / 2 for ch in s])
+ for ch, p_ in zip(s, pos):
+ if ch == ' ': continue
+ off = (total / 2 - p_) / r
+ if not bottom:
+ phi = np.deg2rad(centre) + off; rot = np.rad2deg(phi) - 90
+ else:
+ phi = np.deg2rad(centre) - off; rot = np.rad2deg(phi) - 270
+ x, y = cx + r * np.cos(phi), cy - r * np.sin(phi)
+ m = text_mask(self.H, self.W, ch, f, (x, y), 'mm', 0.0, rot)
+ self.fill(m, colour, angle=rot + angle, kind='satin', pitch=pitch, shadow=0.35, pad=0.6)
+
+ # ================================================================ the needle
+ def needle(self, eye, tip, radius=3.3, colour='#c4c8cf', shadow=0.5):
+ """a steel hand-sewing needle lying on the cloth: eye end at `eye`, point at `tip`. Draw the thread first:
+ it shows through the eye."""
+ P = np.array([eye, tip], np.float32)
+ g = self._pparam(P, False, radius + 3)
+ if g is None: return
+ s, d = g['s'], g['d']; Lt = g['length']
+ taper = 46.0
+ rs = radius * np.where(s > Lt - taper, np.clip((Lt - s) / taper, 0.02, 1) ** 0.75, 1.0)
+ rs = np.where(s < 0, radius, rs)
+ a = np.clip((rs - np.abs(d)) / 0.8 + 0.5, 0, 1) * np.clip((s + 0.5) / 1.0, 0, 1) * np.clip((Lt - s) / 0.8 + 0.3, 0, 1)
+ a = a * np.where(s < radius, np.clip((radius - np.hypot(radius - s, d)) / 0.8 + 0.5, 0, 1), 1)
+ # the eye: an elongated slot near the blunt end
+ es, el, ew = 9.0, 9.0, radius * 0.42
+ eu = (s - (es + el)) / el; ev = d / ew
+ hole = np.clip((1 - np.sqrt(eu * eu + ev * ev)) * 6, 0, 1)
+ rim = np.exp(-((np.sqrt(eu * eu + ev * ev) - 1) / 0.35) ** 2)
+ a = a * (1 - hole)
+ v = np.clip(d / np.maximum(rs, 0.3), -1, 1)
+ nzc = np.sqrt(np.clip(1 - v * v, 0.02, 1))
+ nx, ny, nz = g['nx'] * v, g['ny'] * v, nzc
+ L, Hv = self.L, self.Hv
+ ndl = nx * L[0] + ny * L[1] + nz * L[2]
+ nh = np.clip(nx * Hv[0] + ny * Hv[1] + nz * Hv[2], 0, 1)
+ # polished steel: mostly reflection. A soft room (dark floor at the flanks, bright ceiling on top),
+ # the window as a crisp streak, and the denim's blue picked up on the lower flank
+ room = 0.1 + 0.55 * smoothstep(-0.2, 0.95, ndl) + 0.22 * nzc ** 3
+ streak = 1.3 * nh ** 90 + 0.35 * nh ** 12
+ col = _c(colour)
+ blue = getattr(self, 'denim_colour', col)
+ flank = np.clip(-v * np.sign(g['nx'] * L[0] + g['ny'] * L[1] + 1e-6), 0, 1) ** 2 * 0.5
+ rgb = (col * room[:, None] * (1 - flank[:, None]) + blue * 0.6 * flank[:, None]) * (1 - 0.5 * rim)[:, None] \
+ + streak[:, None]
+ A, R = self._scatter(g, a, rgb)
+ self._put(g['win'], A, R, shadow, off=(3.5, 4.5), soft=2.6)
+
+ # ================================================================ output
+ def composite(self, vignette=0.14, grain=0.012):
+ YY, XX = np.mgrid[0:self.H, 0:self.W].astype(np.float32)
+ r = np.hypot((XX - self.W / 2) / self.W, (YY - self.H / 2) / self.H)
+ img = self.img * (1 - vignette * r ** 2 * 2.4)[..., None]
+ if grain:
+ img = img + np.random.default_rng(7).normal(0, grain, (self.H, self.W, 1)).astype(np.float32)
+ return Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8))
+
+ def stage(self, name):
+ """snapshot for the draw-on animation"""
+ 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
diff --git a/lib/petroglyph.py b/lib/petroglyph.py
new file mode 100644
index 0000000..d0905ca
--- /dev/null
+++ b/lib/petroglyph.py
@@ -0,0 +1,761 @@
+"""petroglyph -- pecked rock art on desert-varnished sandstone (numpy + Pillow only).
+
+A petroglyph is not painted on: it is a picture made by knocking the dark skin off a rock. Everything below is
+height (in px) and colour fields that the actions change, lit at the end by one low sun.
+
+Model:
+ rock a sandstone face is a height field (broad undulations, thin wavy bedding laminae, sand-grain tooth) and
+ an albedo: warm buff-orange stone, cloudy and banded, with scattered dark lithic and pale quartz grains.
+ `ledge()` sets the face below a wavy line back by a step (a lower, sheltered face under an overhang lip).
+ varnish desert varnish is a paper-thin coat of clay with manganese and iron oxides that grows over centuries where
+ rain water runs down the face. It is a thickness field v (0 bare stone .. 1 thick) plus a manganese field:
+ red-brown where iron-rich, blue-black where manganese-rich. Near-uniform and dark, with crisp vertical
+ runoff streaks (each narrows and fades downward, wanders a little, mostly starts near the top), paler
+ streaks where the flow kept it thin, a darker band under the top lip, seep streaks below cracks, and
+ thinner near the ground where blown sand scours it. It adds no height.
+ peck the maker struck the face with a hammerstone. Every blow leaves an irregular pit a few px wide that breaks
+ through the varnish to the paler stone and crushes the grains white. A glyph is rasterised to a mask and
+ hammered out of it with hundreds to thousands of pits: centres are sampled inside the mask with uneven
+ density and a few stray blows past the outline; each pit is a random-polygon sprite with a bowl-shaped
+ depth. Depths add up and saturate, so a densely pecked interior is a shallow granular depression and the
+ outline is ragged at the scale of one pit.
+ abrade grinding / incising with a stone edge: a smooth V-groove along a stroke, fine striations along it, the
+ varnish polished off in the bottom (tally marks, fine lines). Reads smoother and lighter than pecking.
+ age repatination: an old glyph slowly re-varnishes back toward the rock around it and its pits round off.
+ age 0 = struck this season (bright, crisp), 0.5 = centuries, 0.85 = a faint ghost under newer work.
+ Superimposition comes free: a new glyph pecked over an old one is brighter and cuts deeper.
+ fracture a crack: a jagged narrow slot with rounded shoulders and side branches; water seeping out of it lays a
+ darker varnish streak that runs down the face below.
+ spall exfoliation: a flake of the face broke away, taking whatever glyph was on it. The scar is a step down (a
+ sharp lip of small scallops that casts a shadow), conchoidal ripples around the impact point, fresh
+ orange stone with its own iron banding and a pale rind at the lip; age > 0 lets new varnish film it over.
+ lichen crustose lichen rosettes (olive map lichen, orange, grey): lobed rims, areolate (cracked) centres, tiny
+ dark fruiting discs, satellite dots, slightly raised.
+ light a low sun from the upper left (raking light, the way rock art is photographed) plus cool sky light:
+ Lambert shading from the height-field normals, cast shadows marched along the light (each pit is dark on
+ its upper-left wall and lit on the lower-right), ambient occlusion in pits and cracks.
+Order: rock -> ledge -> varnish -> fractures -> old (aged) glyphs -> newer glyphs -> spalls -> lichen.
+Glyphs are drafted first (`Draft`, or the helpers bighorn / hunter / sun_spiral / crescent / concentric / hand /
+hoofprints / meander, which all return a Draft and accept `into=` to collect several figures into one), then
+`peck()`ed; tally marks and fine lines are `abrade()`d. Coordinates are px, y down; angles in degrees,
+counter-clockwise.
+
+ from petroglyph import Petroglyph
+ pg = Petroglyph(1920, 1080, seed=3)
+ pg.rock(); pg.ledge(900, drop=34); pg.varnish()
+ pg.fracture([(900, 0), (860, 300)])
+ pg.peck(pg.meander([(300, 800), (700, 760), (1100, 820)], 14), age=0.8) # an old, re-varnished line
+ pg.peck(pg.bighorn(800, 600, 180)) # a fresh bighorn sheep
+ pg.abrade_tally(200, 150, [10, 10], length=60)
+ pg.spall([(1700, 0), (1920, 0), (1920, 160), (1760, 120)])
+ pg.lichen(1000, 980, 40, 'green')
+ pg.save('out.jpg')
+"""
+import os
+import numpy as np
+from PIL import Image, ImageDraw
+from core import blur, fbm1d, spline, noise2d, smoothstep, height_normals, height_shadow, ambient_occlusion
+
+STONE, STONE_PALE, STONE_RED = '#c3855a', '#d9aa7e', '#b0643e' # sandstone under the varnish
+SCAR = '#d4865a' # fresh stone in a spall scar
+CRUSH = '#ecd3b0' # hammer-crushed grains
+VARNISH_FE, VARNISH_MN = '#4a2517', '#20150e' # iron-rich / manganese-rich varnish
+LICHEN = {'green': ('#9c9f52', '#bdbb72'), 'orange': ('#b8742e', '#d39445'), 'grey': ('#8f9180', '#b0b09c')}
+SUN, SKY = np.array([1.0, 0.92, 0.80], np.float32), np.array([0.62, 0.68, 0.80], np.float32)
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+def _c(c):
+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)
+
+
+def _resample(pts, step):
+ """polyline -> points every `step` px"""
+ P = np.asarray(pts, np.float32)
+ if len(P) < 2: return P
+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1)
+ s = np.concatenate([[0], np.cumsum(seg)])
+ n = max(2, int(s[-1] / step) + 1)
+ t = np.linspace(0, s[-1], n)
+ return np.stack([np.interp(t, s, P[:, 0]), np.interp(t, s, P[:, 1])], 1)
+
+
+# ---------------------------------------------------------------- glyph drafting
+class Draft:
+ """the design a maker would chalk on the rock before hammering: a mask built from strokes, fills and dots
+ (2x supersampled). Strokes wobble a little in path and width, like a hand-laid line."""
+
+ def __init__(self, W, H, ss=2, seed=0):
+ self.W, self.H, self.ss = W, H, ss
+ self.im = Image.new('L', (W * ss, H * ss), 0)
+ self.d = ImageDraw.Draw(self.im)
+ self.rng = np.random.default_rng(seed)
+ self.extra = None
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ def stroke(self, pts, width, end_width=None, wobble=0.12, smooth=True, value=255):
+ """a line of round dabs from width to end_width (taper); wobble = relative wander of path and width"""
+ P = spline(pts, 10) if (smooth and len(pts) > 2) else np.asarray(pts, np.float32)
+ P = _resample(P, max(0.8, width * 0.18))
+ n = len(P)
+ w1 = width if end_width is None else end_width
+ w = np.linspace(width, w1, n) * (1 + wobble * fbm1d(n, max(4, n / 3), 3, self._seed()))
+ if n > 2 and wobble:
+ t = np.gradient(P, axis=0); t /= np.linalg.norm(t, axis=1, keepdims=True) + 1e-6
+ nrm = np.stack([-t[:, 1], t[:, 0]], 1)
+ P = P + nrm * (wobble * width * 0.35 * fbm1d(n, max(4, n / 4), 3, self._seed()))[:, None]
+ s = self.ss
+ for (x, y), ww in zip(P, w):
+ r = max(0.5, ww / 2) * s
+ self.d.ellipse([x * s - r, y * s - r, x * s + r, y * s + r], fill=value)
+ return self
+
+ def fill(self, pts, smooth=True, value=255):
+ """a filled outline (closed spline through the points when smooth)"""
+ P = np.asarray(pts, np.float32)
+ if smooth and len(P) > 3:
+ P = _closed_spline(P)
+ s = self.ss
+ self.d.polygon([(float(x) * s, float(y) * s) for x, y in P], fill=value)
+ return self
+
+ def dot(self, x, y, r, value=255):
+ s = self.ss
+ self.d.ellipse([(x - r) * s, (y - r) * s, (x + r) * s, (y + r) * s], fill=value)
+ return self
+
+ def ring(self, x, y, r, width, wobble=0.08):
+ t = np.linspace(0, 2 * np.pi, max(24, int(r * 0.9)) + 1)
+ rr = r * (1 + 0.03 * fbm1d(len(t), len(t) / 5, 3, self._seed()))
+ return self.stroke(np.stack([x + rr * np.cos(t), y + rr * np.sin(t)], 1), width, wobble=wobble, smooth=False)
+
+ def add(self, mask):
+ """merge a full-frame float mask (0..1)"""
+ self.extra = mask.astype(np.float32) if self.extra is None else np.maximum(self.extra, mask)
+ return self
+
+ def mask(self):
+ m = np.asarray(self.im.resize((self.W, self.H), Image.BILINEAR), np.float32) / 255 if self.ss > 1 else \
+ np.asarray(self.im, np.float32) / 255
+ return m if self.extra is None else np.maximum(m, self.extra)
+
+
+def _closed_spline(P, per=10):
+ """Catmull-Rom through a closed loop of points"""
+ P = np.asarray(P, np.float32)
+ n = len(P)
+ out = []
+ for i in range(n):
+ p0, p1, p2, p3 = P[(i - 1) % n], P[i], P[(i + 1) % n], P[(i + 2) % n]
+ for t in np.linspace(0, 1, per, endpoint=False):
+ t2, t3 = t * t, t * t * t
+ out.append(0.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 + (-p0 + 3 * p1 - 3 * p2 + p3) * t3))
+ return np.array(out, np.float32)
+
+
+# ---------------------------------------------------------------- the rock
+class Petroglyph:
+ def __init__(self, W=1920, H=1080, seed=0, light=(-0.62, -0.50, 0.60)):
+ self.W, self.H = W, H
+ self.rng = np.random.default_rng(seed)
+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)
+ L = np.asarray(light, np.float32)
+ self.L = L / np.linalg.norm(L)
+ self.h = np.zeros((H, W), np.float32) # height, px
+ self.rockc = np.ones((H, W, 3), np.float32) * hexc(STONE)
+ self.v = np.zeros((H, W), np.float32) # varnish thickness
+ self.v0 = None # varnish as it grew (before any pecking)
+ self.mn = np.zeros((H, W), np.float32) # manganese share of the varnish
+ self.crush = np.zeros((H, W), np.float32) # freshly crushed grains (whitening)
+ self.paint = None; self.pa = None # lichen layer
+ self.stages = []
+ self._sprites = {}
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ def draft(self):
+ return Draft(self.W, self.H, seed=self._seed())
+
+ # ------------------------------------------------------------ stone
+ def rock(self, colour=STONE, relief=1.0, bedding=1.0, grain=1.0, bed_angle=-3.0):
+ """the sandstone face: height (broad swells, bedding laminae, grain tooth) and the stone colour beneath"""
+ H, W = self.H, self.W
+ big = noise2d(H, W, 900, 3, self._seed()) - 0.5
+ mid = noise2d(H, W, 170, 3, self._seed()) - 0.5
+ small = noise2d(H, W, 38, 2, self._seed()) - 0.5
+ self.h = ((big * 50 + mid * 14 + small * 1.6) * relief).astype(np.float32)
+ # weathering dimples: shallow solution pockets a few px across
+ for _ in range(int(150 * relief)):
+ x, y = self.rng.uniform(0, W), self.rng.uniform(0, H)
+ r = self.rng.uniform(7, 26); dz = self.rng.uniform(0.5, 1.6)
+ x0, x1, y0, y1 = int(max(0, x - 2 * r)), int(min(W, x + 2 * r + 1)), int(max(0, y - 2 * r)), int(min(H, y + 2 * r + 1))
+ if x1 <= x0 or y1 <= y0: continue
+ dd = ((self.XX[y0:y1, x0:x1] - x) ** 2 + (self.YY[y0:y1, x0:x1] - y) ** 2) / (r * r)
+ self.h[y0:y1, x0:x1] -= dz * np.exp(-dd * 1.6)
+ # bedding: thin laminae, slightly tilted and warped, irregular in spacing
+ a = np.deg2rad(bed_angle)
+ yb = self.YY * np.cos(a) - self.XX * np.sin(a) + (noise2d(H, W, 520, 2, self._seed()) - 0.5) * 70
+ n = H + 2 * W
+ lam1 = fbm1d(n, 9, 3, self._seed()); lam2 = fbm1d(n, 60, 3, self._seed())
+ grid = np.arange(n, dtype=np.float32) - W
+ lam = np.interp(yb, grid, lam1).astype(np.float32)
+ band = np.interp(yb, grid, lam2).astype(np.float32)
+ lam *= 0.4 + 0.6 * noise2d(H, W, 220, 2, self._seed()) # laminae come and go
+ self.h += (0.45 * lam + 1.3 * band) * bedding
+ # grain tooth: sand grains 1-2 px
+ g = self.rng.random((H, W), dtype=np.float32)
+ self.h += (blur(g, 0.6) - 0.5) * 0.95 * grain
+ # stone colour: cloudy patches between paler buff and redder iron-stained stone, banded along the bedding
+ col = _c(colour); pale = hexc(STONE_PALE); red = hexc(STONE_RED)
+ p = noise2d(H, W, 380, 3, self._seed()); q = noise2d(H, W, 140, 3, self._seed())
+ t1 = smoothstep(0.45, 0.85, p)[..., None]; t2 = smoothstep(0.5, 0.9, q)[..., None] * 0.6
+ rc = col * (1 - t1) + pale * t1
+ rc = rc * (1 - t2) + red * t2
+ rc *= (1 + 0.035 * band + 0.012 * lam)[..., None]
+ g2 = self.rng.random((H, W), dtype=np.float32)
+ rc *= (0.94 + 0.12 * blur(g2, 0.5))[..., None]
+ dark = (self.rng.random((H, W), dtype=np.float32) > 0.9965)
+ bright = (self.rng.random((H, W), dtype=np.float32) > 0.997)
+ rc[dark] *= 0.55; rc[bright] = rc[bright] * 0.5 + 0.5
+ self.rockc = rc.astype(np.float32)
+ return self
+
+ def ledge(self, y, drop=16, wander=18, soft=2.0):
+ """set the face below a wavy line back by `drop` px (a lower face under an overhang lip)"""
+ H, W = self.H, self.W
+ k = max(3, W // 70)
+ knots = np.linspace(0, W - 1, k)
+ ang = np.interp(np.arange(W), knots, self.rng.normal(0, 1, k)) * wander * 0.5 # broken, angular lip
+ line = y + wander * fbm1d(W, 300, 3, self._seed()) + ang + 2.5 * fbm1d(W, 14, 2, self._seed())
+ dy = self.YY - line[None, :]
+ below = smoothstep(-soft, soft, dy)
+ bevel = smoothstep(-7, 1, dy) # the lip is rounded off by weathering
+ self.h -= drop * (0.75 * below + 0.25 * bevel)
+ self._ledge = line
+ return self
+
+ def _streaks(self, n, width=(2.9, 0.55), length=(90, 560), top_bias=2.2, reach=0.7):
+ """a field of vertical runoff streaks: crisp-edged, narrowing and fading downward, wandering a little,
+ mostly starting near the top (top_bias), each with its own strength"""
+ H, W = self.H, self.W
+ r = self.rng
+ F = np.zeros((H, W), np.float32)
+ for i in range(int(n)):
+ x = r.uniform(-20, W + 20); w = float(np.clip(np.exp(r.normal(*width)), 5, 110))
+ y0 = H * reach * r.random() ** top_bias - 30; L = r.uniform(*length); a = r.uniform(0.35, 1.0)
+ xs, xe = int(max(0, x - w - 14)), int(min(W, x + w + 15)); ys, ye = int(max(0, y0)), int(min(H, y0 + L))
+ if xe <= xs or ye <= ys: continue
+ X = self.XX[ys:ye, xs:xe] - x; Y = self.YY[ys:ye, xs:xe] - y0
+ X = X - 7 * np.sin(Y / L * np.pi * r.uniform(0.6, 2.2) + r.uniform(0, 6))
+ hw = w / 2 * (1 - 0.55 * Y / L)
+ across = smoothstep(hw + 2.5, hw - 2.5, np.abs(X))
+ along = smoothstep(0, 50, Y) * (1 - smoothstep(L * 0.3, L, Y))
+ F[ys:ye, xs:xe] = np.maximum(F[ys:ye, xs:xe], a * across * along)
+ fine = Image.fromarray(r.random((max(2, H // 50), max(2, W // 2))).astype(np.float32))
+ fine = np.asarray(fine.resize((W, H), Image.BICUBIC), np.float32)
+ return blur(F * (0.75 + 0.35 * fine), 0.7)
+
+ def varnish(self, strength=0.93, streaks=1.0, top=0.14, scour=0.45, patches=1.0):
+ """grow desert varnish over the face: a near-uniform dark coat, crisp blue-black runoff streaks and paler
+ streaks where the flow kept it thin, thicker under the top lip, sand-scoured near the ground"""
+ H, W = self.H, self.W
+ base = noise2d(H, W, 420, 4, self._seed())
+ v = 0.86 + 0.18 * patches * (base - 0.5)
+ zone = np.clip(smoothstep(0.25, 0.7, noise2d(H, W, 450, 3, self._seed())) * 0.7 + 0.5 * smoothstep(H * 0.55, 0, self.YY), 0.15, 1)
+ dark = self._streaks(110 * streaks) * zone
+ pale = self._streaks(26 * patches, width=(3.6, 0.5), length=(160, 700), top_bias=1.2, reach=0.8)
+ v += streaks * 0.20 * dark - 0.24 * patches * pale
+ v += top * smoothstep(H * 0.42, 0, self.YY) * (0.55 + 0.45 * base)
+ v *= 1 - scour * smoothstep(H * 0.72, H * 1.02, self.YY) * (0.55 + 0.45 * noise2d(H, W, 90, 2, self._seed()))
+ if hasattr(self, '_ledge'): # the sheltered lower face carries less varnish
+ under = smoothstep(0, 40, self.YY - self._ledge[None, :])
+ v *= 1 - 0.30 * under
+ self.v = np.clip(v * strength, 0, 0.97).astype(np.float32)
+ self.mn = np.clip(0.35 + 0.5 * (noise2d(H, W, 200, 3, self._seed()) - 0.5) + 0.6 * smoothstep(0.05, 0.6, dark), 0, 1).astype(np.float32)
+ self.v0 = self.v.copy()
+ return self
+
+ def _runoff(self, src, length=220, decay=None):
+ """smear a source mask straight down the face with decay (water running down from it)"""
+ k = decay or np.exp(-1.0 / length)
+ out = np.empty_like(src); acc = np.zeros(src.shape[1], np.float32)
+ for y in range(src.shape[0]):
+ acc = np.maximum(src[y], acc * k)
+ out[y] = acc
+ return out
+
+ def fracture(self, pts, width=3.0, depth=9.0, seep=0.5, branches=2, jag=1.0):
+ """a crack along the rough path `pts`: jagged slot with rounded shoulders, side branches, a seep streak below"""
+ H, W = self.H, self.W
+ d = Draft(W, H, seed=self._seed())
+ P = _resample(spline(pts, 12) if len(pts) > 2 else pts, 3.0)
+ n = len(P)
+ t = np.gradient(P, axis=0); t /= np.linalg.norm(t, axis=1, keepdims=True) + 1e-6
+ nrm = np.stack([-t[:, 1], t[:, 0]], 1)
+ P = P + nrm * (jag * (6 * fbm1d(n, 30, 3, self._seed()) + 1.6 * fbm1d(n, 4, 2, self._seed())))[:, None]
+ wv = width * (0.55 + 0.9 * (0.5 + 0.5 * fbm1d(n, 25, 3, self._seed())))
+ s = d.ss
+ for (x, y), ww in zip(P, wv):
+ rr = ww / 2 * s
+ d.d.ellipse([x * s - rr, y * s - rr, x * s + rr, y * s + rr], fill=255)
+ for _ in range(branches):
+ i = int(self.rng.integers(n // 6, max(n // 6 + 1, n - n // 6)))
+ ang = np.arctan2(t[i, 1], t[i, 0]) + self.rng.choice([-1, 1]) * self.rng.uniform(0.5, 1.0)
+ L = self.rng.uniform(0.12, 0.3) * n * 3.0
+ m = max(4, int(L / 3))
+ q = P[i] + np.stack([np.cos(ang + 0.3 * fbm1d(m, 8, 2, self._seed())), np.sin(ang + 0.3 * fbm1d(m, 8, 2, self._seed()))], 1).cumsum(0) * 3.0
+ for j, (x, y) in enumerate(q):
+ rr = width * 0.45 * (1 - j / m) * s + 0.4
+ d.d.ellipse([x * s - rr, y * s - rr, x * s + rr, y * s + rr], fill=255)
+ m = d.mask()
+ slot = blur(m, 0.5)
+ shoulder = blur(m, width * 1.6)
+ self.h -= depth * slot + 2.2 * np.clip(shoulder * 2.2, 0, 1)
+ self.crush *= (1 - slot)
+ if seep:
+ drip = self._runoff(np.clip(shoulder * 3, 0, 1), 260)
+ coarse = Image.fromarray(self.rng.random((max(2, H // 90), max(2, W // 5))).astype(np.float32))
+ fing = np.asarray(coarse.resize((W, H), Image.BICUBIC), np.float32)
+ drip *= np.clip(0.3 + fing, 0, 1.2)
+ self.v = np.clip(self.v + seep * 0.5 * drip * (1 - self.v), 0, 0.98)
+ self.mn = np.clip(self.mn + seep * 0.6 * drip, 0, 1)
+ if self.v0 is not None: self.v0 = np.maximum(self.v0, self.v)
+ return self
+
+ # ------------------------------------------------------------ hammer, grinder, age
+ def _peck_sprites(self, size):
+ key = round(float(size), 2)
+ if key in self._sprites: return self._sprites[key]
+ r = np.random.default_rng(1234 + int(key * 100))
+ K, S = 48, int(np.ceil(5.2 * size)) * 2 + 1
+ SS = 4
+ c0 = S // 2
+ yy, xx = (np.mgrid[0:S * SS, 0:S * SS].astype(np.float32) + 0.5) / SS - S / 2
+ cov = np.zeros((K, S, S), np.float32); dep = np.zeros((K, S, S), np.float32)
+ for k in range(K):
+ rad = r.uniform(1.9, 4.6) * size
+ m = r.integers(5, 9)
+ ang = np.sort(r.uniform(0, 2 * np.pi, m))
+ rr = rad * r.uniform(0.62, 1.18, m)
+ pts = [(float((S / 2 + rr[i] * np.cos(ang[i])) * SS), float((S / 2 + rr[i] * np.sin(ang[i])) * SS)) for i in range(m)]
+ im = Image.new('L', (S * SS, S * SS), 0)
+ ImageDraw.Draw(im).polygon(pts, fill=255)
+ hi = np.asarray(im, np.float32) / 255
+ rho = np.hypot(xx, yy) / (rad * 1.12)
+ bowl = np.clip(1 - rho ** 2, 0, 1) ** 0.55 * hi
+ cov[k] = hi.reshape(S, SS, S, SS).mean((1, 3))
+ dep[k] = bowl.reshape(S, SS, S, SS).mean((1, 3)) * r.uniform(0.7, 1.3)
+ self._sprites[key] = (cov, dep, c0)
+ return self._sprites[key]
+
+ def _as_mask(self, glyph):
+ return glyph.mask() if isinstance(glyph, Draft) else np.asarray(glyph, np.float32)
+
+ def peck(self, glyph, density=1.0, size=1.0, depth=1.0, age=0.0, scatter=1.0, crush=1.0):
+ """hammer a glyph (Draft or float mask) out of the varnish with irregular pits.
+ density ~1 = solidly pecked, 0.4 = open stipple; size scales the pits; age 0 fresh .. 0.85 ghost"""
+ M = self._as_mask(glyph)
+ cov, dep, c0 = self._peck_sprites(size)
+ K, S = cov.shape[0], cov.shape[1]
+ ys, xs = np.nonzero(M > 0.02)
+ if len(ys) == 0: return self
+ pad = S + int(6 * scatter * size)
+ y0, y1 = max(0, ys.min() - pad), min(self.H, ys.max() + pad + 1)
+ x0, x1 = max(0, xs.min() - pad), min(self.W, xs.max() + pad + 1)
+ sub = M[y0:y1, x0:x1]
+ bh, bw = sub.shape
+ soft = blur(sub, 1.3 * scatter * size)
+ dens = 0.72 + 0.56 * noise2d(bh, bw, 45, 2, self._seed())
+ prob = (smoothstep(0.30, 0.72, soft) + 0.05 * scatter * smoothstep(0.03, 0.3, soft)) * dens
+ area = float(sub.sum())
+ n_want = int(density * 3.4 * area / (np.pi * (3.25 * size) ** 2)) + 1
+ r = self.rng
+ cx, cy = [], []
+ got, tries = 0, 0
+ while got < n_want and tries < 40:
+ m = int((n_want - got) * 2.5) + 16
+ px = r.uniform(0, bw - 1, m); py = r.uniform(0, bh - 1, m)
+ ok = r.random(m) < prob[py.astype(int), px.astype(int)]
+ cx.append(px[ok]); cy.append(py[ok]); got += int(ok.sum()); tries += 1
+ cx = np.concatenate(cx)[:n_want]; cy = np.concatenate(cy)[:n_want]
+ # pits are stamped into a padded local buffer
+ PB = S
+ Hb, Wb = bh + 2 * PB, bw + 2 * PB
+ D = np.zeros((Hb, Wb), np.float32); Sx = np.zeros((Hb, Wb), np.float32)
+ Bs = np.zeros((Hb, Wb), np.float32); Cs = np.zeros((Hb, Wb), np.float32)
+ ix = np.round(cx).astype(np.int64) + PB - c0; iy = np.round(cy).astype(np.int64) + PB - c0
+ kk = r.integers(0, K, len(ix))
+ bright = r.uniform(0.45, 1.0, len(ix)).astype(np.float32)
+ oy, ox = np.mgrid[0:S, 0:S]
+ idx = ((iy[:, None, None] + oy[None]) * Wb + (ix[:, None, None] + ox[None])).ravel()
+ cv = cov[kk]
+ np.add.at(D.ravel(), idx, dep[kk].ravel())
+ np.add.at(Sx.ravel(), idx, (-np.log(1 - 0.93 * cv)).ravel())
+ np.add.at(Bs.ravel(), idx, (cv * bright[:, None, None]).ravel())
+ np.add.at(Cs.ravel(), idx, cv.ravel())
+ crop = (slice(PB, PB + bh), slice(PB, PB + bw))
+ D, Sx, Bs, Cs = D[crop], Sx[crop], Bs[crop], Cs[crop]
+ R = 1 - np.exp(-Sx) # share of varnish knocked off
+ bri = np.clip(Bs / np.maximum(Cs, 1e-3), 0, 1) # coverage-weighted whiteness of the pits
+ dmax = 2.9 * depth * (1 - 0.4 * age)
+ Deff = dmax * (1 - np.exp(-1.35 * D * depth / dmax))
+ if age > 0: # weathering rounds the pits off
+ Deff = blur(Deff, 0.3 + 1.4 * age)
+ R = blur(R, 0.6 * age)
+ sl = (slice(y0, y1), slice(x0, x1))
+ self.h[sl] -= Deff
+ v = self.v[sl]; vref = (self.v0[sl] if self.v0 is not None else v)
+ regrow = np.clip(age, 0, 1) ** 0.8 * 0.92 * vref # old pecks re-varnish toward the rock around them
+ self.v[sl] = v * (1 - R) + R * regrow
+ fresh = R * (0.35 + 0.65 * bri) * crush * (1 - age) ** 1.6
+ self.crush[sl] = np.maximum(self.crush[sl] * (1 - R * 0.5), fresh)
+ return self
+
+ def abrade(self, pts, width=8.0, depth=1.6, age=0.0, polish=1.0, smooth=False):
+ """grind a V-groove along a polyline (incised lines, tally marks): smooth floor, fine striations along it"""
+ P = spline(pts, 10) if (smooth and len(pts) > 2) else np.asarray(pts, np.float32)
+ pad = int(width + 4)
+ X0, X1 = int(max(0, P[:, 0].min() - pad)), int(min(self.W, P[:, 0].max() + pad + 1))
+ Y0, Y1 = int(max(0, P[:, 1].min() - pad)), int(min(self.H, P[:, 1].max() + pad + 1))
+ if X1 <= X0 or Y1 <= Y0: return self
+ box = (slice(Y0, Y1), slice(X0, X1))
+ G = np.zeros((Y1 - Y0, X1 - X0), np.float32); STR = np.zeros_like(G)
+ X = self.XX[box]; Y = self.YY[box]
+ hw = width / 2
+ for a, b in zip(P[:-1], P[1:]):
+ d = b - a; L = float(np.linalg.norm(d))
+ if L < 0.5: continue
+ u = d / L; p = np.array([-u[1], u[0]], np.float32)
+ al = (X - a[0]) * u[0] + (Y - a[1]) * u[1]; pe = (X - a[0]) * p[0] + (Y - a[1]) * p[1]
+ hwv = hw * (1 + 0.12 * np.sin(al * 0.21 + float(self.rng.uniform(0, 6))))
+ ends = smoothstep(-hw * 0.2, hw * 0.9, al) * smoothstep(L + hw * 0.2, L - hw * 0.9, al) if len(P) == 2 else \
+ np.clip(1 - np.maximum(np.maximum(-al, al - L), 0) / hw, 0, 1)
+ prof = np.clip(1 - np.abs(pe) / hwv, 0, 1) ** 0.85 * ends
+ stri = 0.5 + 0.5 * np.sin(pe * 2 * np.pi / 1.4 + 2.5 * np.sin(al * 0.05))
+ G = np.maximum(G, prof)
+ STR = np.maximum(STR, stri * prof)
+ G = blur(G, 0.5)
+ self.h[box] -= depth * (1 - 0.35 * age) * G
+ R = smoothstep(0.04, 0.45, G) * polish
+ vref = (self.v0 if self.v0 is not None else self.v)[box]
+ self.v[box] = self.v[box] * (1 - R) + R * (age ** 0.8 * 0.92 * vref)
+ self.crush[box] = np.maximum(self.crush[box], R * (0.55 + 0.3 * STR) * (1 - age) ** 1.6)
+ return self
+
+ def abrade_tally(self, x, y, counts, gap=24.0, length=60.0, width=8.0, row_gap=None, slant=4.0, age=0.0,
+ strike_every=0, depth=1.6):
+ """rows of ground tally marks (a day count). counts: marks per row; slant: px the tops lean; strike_every=5
+ adds a cross-stroke through each group of five"""
+ row_gap = row_gap or length * 1.45
+ for ri, n in enumerate(counts):
+ yy = y + ri * row_gap
+ for i in range(n):
+ xx = x + i * gap + self.rng.normal(0, 2.2)
+ y_ = yy + self.rng.normal(0, 2.5)
+ ln = length * self.rng.uniform(0.84, 1.1)
+ sk = slant + self.rng.normal(0, 2.6)
+ self.abrade([(xx + sk, y_), (xx - sk * 0.2, y_ + ln)], width * self.rng.uniform(0.82, 1.12),
+ depth * self.rng.uniform(0.8, 1.15), age)
+ if strike_every and (i + 1) % strike_every == 0:
+ self.abrade([(xx - gap * (strike_every - 0.4), yy + ln * 0.62), (xx + gap * 0.45, yy + ln * 0.38)],
+ width * 0.85, depth, age)
+ return self
+
+ # ------------------------------------------------------------ glyph helpers (each returns a Draft)
+ def _frame(self, x, y, size, facing=1, rot=0.0):
+ c, s = np.cos(np.deg2rad(-rot)), np.sin(np.deg2rad(-rot))
+
+ def T(pts):
+ P = np.asarray(pts, np.float32) * size
+ P[:, 0] *= facing
+ return np.stack([x + P[:, 0] * c - P[:, 1] * s, y + P[:, 0] * s + P[:, 1] * c], 1)
+ return T
+
+ def bighorn(self, x, y, size, facing=1, kind='ram', gait=0.0, rot=0.0, into=None):
+ """a bighorn sheep in profile (twisted-perspective horns), centred on its body. size ~ body + head length.
+ kind: 'ram' (great curled horns), 'ewe' (short horns), 'lamb' (none); gait -1..1 swings the legs"""
+ d = into or self.draft()
+ T = self._frame(x, y, size, facing, rot)
+ j = lambda: self.rng.normal(0, 0.012)
+ body = [(-0.36, -0.12), (-0.18, -0.19 + j()), (0.06, -0.20 + j()), (0.24, -0.18), (0.34, -0.10), (0.36, 0.03),
+ (0.27, 0.13), (0.0, 0.15 + j()), (-0.28, 0.13), (-0.40, 0.05), (-0.42, -0.05)]
+ d.fill(T(body))
+ w = 1.0 if kind != 'lamb' else 1.15
+ d.stroke(T([(0.22, -0.12), (0.32, -0.24), (0.40, -0.32)]), 0.15 * size * w, 0.11 * size * w)
+ d.fill(T([(0.34, -0.38), (0.47, -0.41), (0.57, -0.35), (0.635, -0.265), (0.55, -0.225), (0.43, -0.255), (0.33, -0.30)]))
+ if kind == 'ram':
+ d.stroke(T([(0.40, -0.38), (0.35, -0.52), (0.24, -0.59), (0.12, -0.55), (0.07, -0.44), (0.11, -0.35)]), 0.10 * size, 0.05 * size)
+ d.stroke(T([(0.47, -0.40), (0.47, -0.55), (0.39, -0.66), (0.26, -0.70), (0.15, -0.66), (0.11, -0.58)]), 0.08 * size, 0.042 * size)
+ elif kind == 'ewe':
+ d.stroke(T([(0.41, -0.38), (0.38, -0.49), (0.30, -0.53)]), 0.075 * size, 0.04 * size)
+ d.stroke(T([(0.47, -0.40), (0.47, -0.50), (0.40, -0.56)]), 0.06 * size, 0.035 * size)
+ else:
+ d.stroke(T([(0.42, -0.39), (0.38, -0.47)]), 0.06 * size, 0.045 * size)
+ g = gait * 0.06
+ lw = 0.064 * size * (1.15 if kind == 'lamb' else 1.0)
+ ll = 0.46 if kind != 'lamb' else 0.50
+ for (ax, ay), (bx, by) in [((0.27, 0.08), (0.31 + g, ll)), ((0.18, 0.10), (0.13 - g, ll)),
+ ((-0.29, 0.08), (-0.25 + g, ll)), ((-0.37, 0.05), (-0.41 - g, ll))]:
+ d.stroke(T([(ax, ay), ((ax + bx) / 2 + 0.01, (ay + by) / 2), (bx, by)]), lw * 1.1, lw * 0.85)
+ d.stroke(T([(-0.40, -0.08), (-0.47, -0.17)]), 0.055 * size, 0.035 * size)
+ return d
+
+ def hunter(self, x, y, size, facing=1, weapon='bow', rot=0.0, into=None):
+ """a stick-figure hunter, size = height. facing +1 looks right. weapon 'bow' (drawn, arrow nocked) or
+ 'atlatl' (dart raised over the head)"""
+ d = into or self.draft()
+ T = self._frame(x, y, size, facing, rot)
+ d.dot(*T([(0.0, -0.405)])[0], 0.068 * size)
+ d.stroke(T([(-0.005, -0.46), (-0.05, -0.53), (-0.07, -0.58)]), 0.035 * size, 0.022 * size)
+ d.stroke(T([(0.025, -0.46), (0.04, -0.53), (0.03, -0.59)]), 0.035 * size, 0.022 * size)
+ d.stroke(T([(0.0, -0.34), (0.005, -0.15), (0.0, 0.03)]), 0.078 * size, 0.062 * size)
+ d.stroke(T([(0.0, 0.02), (0.09, 0.22), (0.13, 0.44), (0.19, 0.45)]), 0.06 * size, 0.05 * size)
+ d.stroke(T([(0.0, 0.02), (-0.07, 0.22), (-0.15, 0.43), (-0.09, 0.45)]), 0.06 * size, 0.05 * size)
+ if weapon == 'bow':
+ d.stroke(T([(0.0, -0.28), (0.15, -0.265), (0.30, -0.255)]), 0.05 * size, 0.042 * size)
+ d.stroke(T([(0.0, -0.28), (-0.10, -0.22), (-0.03, -0.255)]), 0.048 * size, 0.04 * size)
+ d.stroke(T([(0.23, -0.53), (0.33, -0.40), (0.36, -0.255), (0.33, -0.11), (0.23, 0.02)]), 0.045 * size, 0.04 * size)
+ d.stroke(T([(-0.03, -0.255), (0.50, -0.255)]), 0.034 * size, 0.034 * size, smooth=False)
+ d.fill(T([(0.585, -0.255), (0.48, -0.30), (0.50, -0.255), (0.48, -0.21)]), smooth=False)
+ else:
+ d.stroke(T([(0.0, -0.28), (0.17, -0.20), (0.30, -0.25)]), 0.05 * size, 0.042 * size)
+ d.stroke(T([(0.0, -0.29), (-0.13, -0.40), (-0.12, -0.53)]), 0.05 * size, 0.042 * size)
+ d.stroke(T([(-0.34, -0.50), (0.55, -0.68)]), 0.034 * size, 0.034 * size, smooth=False)
+ d.fill(T([(0.63, -0.70), (0.53, -0.72), (0.545, -0.68), (0.56, -0.64)]), smooth=False)
+ for k in (0, 1):
+ d.stroke(T([(-0.30 + k * 0.06, -0.51 - k * 0.012), (-0.34 + k * 0.06, -0.58 - k * 0.012)]), 0.026 * size, 0.022 * size, smooth=False)
+ d.stroke(T([(-0.30 + k * 0.06, -0.51 - k * 0.012), (-0.36 + k * 0.06, -0.45 - k * 0.012)]), 0.026 * size, 0.022 * size, smooth=False)
+ return d
+
+ def sun_spiral(self, x, y, r, turns=3.0, rays=12, width=None, ray_len=(0.30, 0.46), into=None):
+ """an Archimedean spiral sun ringed by short rays"""
+ d = into or self.draft()
+ w = width or r * 0.11
+ th = np.linspace(1.4, 2 * np.pi * turns, int(70 * turns))
+ rr = r * (0.10 + 0.90 * (th - th[0]) / (th[-1] - th[0]))
+ d.stroke(np.stack([x + rr * np.cos(th), y + rr * np.sin(th)], 1), w * 0.85, w * 1.08, smooth=False)
+ d.dot(x, y, w * 0.55)
+ a0 = self.rng.uniform(0, 2 * np.pi)
+ for i in range(rays):
+ a = a0 + 2 * np.pi * i / rays + self.rng.normal(0, 0.05)
+ r0 = r + w * 1.7; r1 = r0 + r * self.rng.uniform(*ray_len)
+ d.stroke([(x + r0 * np.cos(a), y + r0 * np.sin(a)), (x + r1 * np.cos(a), y + r1 * np.sin(a))], w * 0.95, w * 0.8, smooth=False)
+ return d
+
+ def crescent(self, x, y, r, thick=0.42, rot=0.0, into=None):
+ """a crescent moon, horns pointing away from rot (degrees ccw; 0 = horns to the left)"""
+ d = into or self.draft()
+ t = np.linspace(-np.pi / 2, np.pi / 2, 40)
+ outer = np.stack([r * np.cos(t), r * np.sin(t)], 1)
+ inner = np.stack([r * thick * np.cos(t[::-1]) * 1.0 + 0.0, r * np.sin(t[::-1])], 1)
+ P = np.vstack([outer, inner])
+ c, s = np.cos(np.deg2rad(-rot)), np.sin(np.deg2rad(-rot))
+ P = np.stack([x + P[:, 0] * c - P[:, 1] * s, y + P[:, 0] * s + P[:, 1] * c], 1)
+ d.fill(P, smooth=False)
+ return d
+
+ def concentric(self, x, y, r, rings=3, width=None, dot=True, into=None):
+ """concentric rings (a waterhole / spring), optional centre dot"""
+ d = into or self.draft()
+ w = width or max(7.0, r * 0.16)
+ for i in range(rings):
+ rr = r * (i + 1) / rings
+ if rr > w * 0.9: d.ring(x, y, rr, w)
+ if dot: d.dot(x, y, w * 0.75)
+ return d
+
+ def hand(self, x, y, size, rot=0.0, outline=False, line=None, spread=1.0, into=None):
+ """a hand (palm and five fingers, wrist down), size = wrist-to-fingertip; outline=True pecks only the contour"""
+ d = into or self.draft()
+ T = self._frame(x, y, size, 1, rot)
+ h = Draft(self.W, self.H, seed=self._seed()) if outline else d
+ h.fill(T([(-0.20, 0.15), (-0.21, -0.02), (-0.15, -0.14), (0.0, -0.17), (0.15, -0.14), (0.20, -0.02), (0.18, 0.16), (0.10, 0.27), (-0.10, 0.27)]))
+ h.stroke(T([(-0.08, 0.25), (-0.07, 0.44)]), 0.17 * size, 0.15 * size)
+ h.stroke(T([(0.07, 0.25), (0.06, 0.44)]), 0.17 * size, 0.15 * size)
+ fingers = [((-0.17, 0.08), -62, 0.30, 0.105), ((-0.13, -0.10), -14, 0.37, 0.095), ((-0.03, -0.13), -3, 0.41, 0.095),
+ ((0.07, -0.12), 9, 0.38, 0.09), ((0.15, -0.07), 24, 0.29, 0.082)]
+ for (bx, by), ang, ln, wd in fingers:
+ a = np.deg2rad(ang * spread)
+ ex, ey = bx + np.sin(a) * ln, by - np.cos(a) * ln
+ h.stroke(T([(bx, by), ((bx + ex) / 2 + 0.005, (by + ey) / 2), (ex, ey)]), wd * size, wd * size * 0.85)
+ if outline:
+ m = h.mask()
+ lw = line or size * 0.07
+ inner = smoothstep(0.88, 0.99, blur(m, lw * 0.55))
+ d.add(np.clip(m - inner, 0, 1) * smoothstep(0.1, 0.5, m))
+ return d
+
+ def hoofprints(self, pts, size=16.0, every=34.0, stagger=7.0, into=None):
+ """a trail of cloven hoofprints (two teardrops each) walking along `pts`"""
+ d = into or self.draft()
+ P = _resample(spline(pts, 12) if len(pts) > 2 else pts, every)
+ for i in range(len(P)):
+ a = P[min(i + 1, len(P) - 1)] - P[max(i - 1, 0)]
+ a = a / (np.linalg.norm(a) + 1e-6)
+ nrm = np.array([-a[1], a[0]])
+ c = P[i] + nrm * stagger * (1 if i % 2 else -1) + self.rng.normal(0, 1.2, 2)
+ for side in (-1, 1):
+ heel = c - a * size * 0.36 + nrm * side * size * 0.27
+ mid = c + a * size * 0.02 + nrm * side * size * 0.24
+ tip = c + a * size * 0.42 + nrm * side * size * 0.09
+ d.stroke([heel, mid, tip], size * 0.34, size * 0.14, wobble=0.04)
+ return d
+
+ def meander(self, pts, width, end_width=None, smooth=True, into=None):
+ """any pecked line: a wavy river, a path, a zigzag (smooth=False keeps the corners)"""
+ d = into or self.draft()
+ return d.stroke(pts, width, end_width, smooth=smooth)
+
+ # ------------------------------------------------------------ weathering
+ def _scallops(self, pts, chunk=(14, 40), bow=0.16):
+ """conchoidal edge: the outline is broken into short chunks, each bowing inward as a small scallop"""
+ P = np.asarray(pts, np.float32)
+ Q = np.roll(P, -1, 0)
+ sgn = 1.0 if float((P[:, 0] * Q[:, 1] - Q[:, 0] * P[:, 1]).sum()) > 0 else -1.0
+ out = []
+ for i in range(len(P)):
+ a, b = P[i], P[(i + 1) % len(P)]
+ dd = b - a; L = float(np.linalg.norm(dd)) + 1e-6
+ nrm = sgn * np.array([-dd[1], dd[0]]) / L # inward, whichever way the outline winds
+ cuts = [0.0]
+ while cuts[-1] < L:
+ cuts.append(cuts[-1] + self.rng.uniform(*chunk))
+ cuts = np.array(cuts[:-1] + [L]) / L
+ for t0, t1 in zip(cuts[:-1], cuts[1:]):
+ seg = (t1 - t0) * L
+ t = np.linspace(0, 1, max(3, int(seg / 3)), endpoint=False)
+ b_ = 4 * t * (1 - t) * bow * seg * self.rng.uniform(0.3, 1.3)
+ tt = t0 + (t1 - t0) * t
+ jit = self.rng.normal(0, 1.2)
+ out.append(a + dd * tt[:, None] + nrm * (b_ + jit * (t < 0.01) + self.rng.normal(0, 0.35, len(t)))[:, None])
+ return np.vstack(out)
+
+ def spall(self, pts, depth=7.0, impact=None, stone=SCAR, age=0.0):
+ """a flake of the face has broken off: step-down scar with a scalloped lip, conchoidal ripples, fresh stone.
+ pts: rough outline (either winding); age 0 = fresh orange scar .. 0.6 = partly re-varnished"""
+ H, W = self.H, self.W
+ P = self._scallops(pts)
+ im = Image.new('L', (W * 2, H * 2), 0)
+ ImageDraw.Draw(im).polygon([(float(x) * 2, float(y) * 2) for x, y in P], fill=255)
+ M = np.asarray(im.resize((W, H), Image.BILINEAR), np.float32) / 255
+ M = blur(M, 0.4)
+ ys, xs = np.nonzero(M > 0.01)
+ if len(ys) == 0: return self
+ cx, cy = (impact if impact is not None else (xs.mean(), ys.mean()))
+ dist = np.hypot(self.XX - cx, self.YY - cy)
+ rmax = float(np.percentile(np.hypot(xs - cx, ys - cy), 98)) + 1
+ warp = noise2d(H, W, 70, 2, self._seed())
+ ripple = 1.1 * np.sin(dist / 7.5 + warp * 4) * np.exp(-dist / (rmax * 0.8)) # conchoidal rings
+ bowl = depth * (0.7 + 0.3 * np.clip(1 - dist / rmax, 0, 1)) * (0.85 + 0.3 * noise2d(H, W, 120, 2, self._seed()))
+ base = blur(self.h, 12) - bowl + ripple
+ g = self.rng.random((H, W), dtype=np.float32)
+ base += (blur(g, 0.6) - 0.5) * 0.8 # a fresh break is smoother
+ self.h = self.h * (1 - M) + base * M
+ sc = _c(stone)
+ band = 0.5 + 0.5 * np.sin(dist / 13.0 + 4 * noise2d(H, W, 180, 2, self._seed())) # Liesegang-like iron bands
+ tone = noise2d(H, W, 90, 3, self._seed())
+ sc_map = sc * (0.90 + 0.12 * band + 0.1 * (tone - 0.5))[..., None]
+ rind = np.clip(M - smoothstep(0.6, 0.98, blur(M, 3.5)), 0, 1) # pale weathering rind at the lip
+ sc_map = sc_map * (1 - 0.6 * rind[..., None]) + hexc(STONE_PALE) * 1.08 * 0.6 * rind[..., None]
+ self.rockc = self.rockc * (1 - M[..., None]) + sc_map * M[..., None]
+ film = (0.04 + 0.75 * age) * (self.v0 if self.v0 is not None else self.v) * (0.5 + noise2d(H, W, 40, 2, self._seed()))
+ self.v = self.v * (1 - M) + M * np.clip(film, 0, 0.95)
+ self.crush *= (1 - M)
+ if self.pa is not None: self.pa *= (1 - M)
+ return self
+
+ def lichen(self, x, y, r, kind='green', n=5, raise_=0.5):
+ """a cluster of crustose lichen rosettes around (x, y) within r: lobed rims, areolate (cracked) centres,
+ tiny dark fruiting discs. kind: 'green' (yellow-green map lichen), 'orange', 'grey' or a colour"""
+ H, W = self.H, self.W
+ if self.paint is None:
+ self.paint = np.zeros((H, W, 3), np.float32); self.pa = np.zeros((H, W), np.float32)
+ c0, c1 = (hexc(LICHEN[kind][0]), hexc(LICHEN[kind][1])) if kind in LICHEN else (_c(kind), _c(kind) * 1.15)
+ d = Draft(W, H, seed=self._seed())
+ cents = []
+ for i in range(n):
+ a = self.rng.uniform(0, 2 * np.pi); rr = r * np.sqrt(self.rng.random())
+ px, py = x + rr * np.cos(a), y + rr * np.sin(a)
+ rad = self.rng.uniform(0.14, 0.34) * r
+ cents.append((px, py, rad))
+ t = np.linspace(0, 2 * np.pi, 160, endpoint=False)
+ k = self.rng.integers(9, 16)
+ lobes = 1 + 0.14 * np.abs(np.sin(t * k / 2 + self.rng.uniform(0, 3))) ** 0.6 + 0.3 * fbm1d(160, 40, 3, self._seed())
+ ex, rot_ = self.rng.uniform(0.65, 1.0), self.rng.uniform(0, np.pi)
+ u, w_ = rad * lobes * np.cos(t), rad * lobes * np.sin(t) * ex
+ d.fill(np.stack([px + u * np.cos(rot_) - w_ * np.sin(rot_), py + u * np.sin(rot_) + w_ * np.cos(rot_)], 1), smooth=False)
+ for _ in range(int(self.rng.integers(2, 6))): # young satellite thalli
+ b = self.rng.uniform(0, 2 * np.pi); q = rad * self.rng.uniform(1.1, 1.6)
+ d.dot(px + q * np.cos(b), py + q * np.sin(b), self.rng.uniform(1.2, 0.22 * rad + 1.3))
+ m = d.mask()
+ x0, x1 = int(max(0, x - r * 1.6)), int(min(W, x + r * 1.6 + 1)); y0, y1 = int(max(0, y - r * 1.6)), int(min(H, y + r * 1.6 + 1))
+ sl = (slice(y0, y1), slice(x0, x1))
+ mb = m[sl]; bh, bw = mb.shape
+ rim = np.clip(mb - smoothstep(0.7, 0.98, blur(mb, 2.5)), 0, 1)
+ cell = noise2d(bh, bw, 5, 2, self._seed())
+ cracks = smoothstep(0.035, 0.0, np.abs(cell - 0.5)) * (1 - rim) # areoles
+ speck = noise2d(bh, bw, 3, 1, self._seed())
+ col = c0 * (1 - rim[..., None]) + c1 * rim[..., None]
+ col = col * (0.82 + 0.3 * speck)[..., None] * (1 - 0.55 * cracks)[..., None]
+ for (px, py, rad) in cents: # fruiting discs
+ for _ in range(int(rad * 0.5)):
+ b = self.rng.uniform(0, 2 * np.pi); q = rad * 0.6 * np.sqrt(self.rng.random())
+ fx, fy = px + q * np.cos(b) - x0, py + q * np.sin(b) - y0
+ if 1 <= fx < bw - 2 and 1 <= fy < bh - 2:
+ col[int(fy):int(fy) + 2, int(fx):int(fx) + 2] *= 0.45
+ a = mb * (0.7 + 0.28 * speck)
+ self.paint[sl] = self.paint[sl] * (1 - a[..., None]) + col * a[..., None]
+ self.pa[sl] = np.maximum(self.pa[sl], a)
+ self.h[sl] += raise_ * blur(mb, 1.0) - 0.4 * cracks
+ return self
+
+ # ------------------------------------------------------------ light and output
+ def albedo(self):
+ cr = self.crush[..., None]
+ fresh = self.rockc * (1 - 0.48 * cr) + hexc(CRUSH) * 0.48 * cr
+ vc = hexc(VARNISH_FE) * (1 - self.mn[..., None]) + hexc(VARNISH_MN) * self.mn[..., None]
+ v = self.v[..., None]
+ alb = fresh * (1 - v) + vc * v
+ if self.pa is not None:
+ alb = alb * (1 - self.pa[..., None]) + self.paint * self.pa[..., None]
+ return alb
+
+ def composite(self, sun=1.0, sky=0.42, shadow=0.82, vignette=0.22):
+ h = blur(self.h, 0.55)
+ N = height_normals(h)
+ L = self.L
+ ndl = np.clip(N[..., 0] * L[0] + N[..., 1] * L[1] + N[..., 2] * L[2], 0, 1)
+ del N
+ P = 58 # pad by edge so the frame border casts no shadow
+ sh = height_shadow(np.pad(h, P, mode='edge'), tuple(L), reach=56, step=1.0, soft=0.9)[P:-P, P:-P]
+ ao = ambient_occlusion(h, radii=(2, 6, 18), depth=(2.4, 7.0, 22.0))
+ direct = (ndl / L[2]) * (1 - shadow * sh)
+ light = SKY[None, None, :] * (sky * (1 - 0.6 * ao))[..., None] + SUN[None, None, :] * (sun * 0.66 * direct)[..., None]
+ img = self.albedo() * light
+ r = np.hypot((self.XX - self.W * 0.45) / self.W, (self.YY - self.H * 0.42) / self.H)
+ img *= (1 - vignette * r ** 2 * 2.0)[..., None]
+ img = np.clip(img, 0, 1) ** 0.96
+ return Image.fromarray((img * 255 + 0.5).astype(np.uint8))
+
+ def stage(self, name):
+ self.stages.append((name, self.composite()))
+
+ def save(self, path, stages_dir=None):
+ img = self.composite()
+ if path.lower().endswith(('.jpg', '.jpeg')):
+ img.save(path, quality=88, 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
diff --git a/lib/popart.py b/lib/popart.py
new file mode 100644
index 0000000..d4affc4
--- /dev/null
+++ b/lib/popart.py
@@ -0,0 +1,500 @@
+"""popart — a 1960s pop-art silkscreen painting (the Factory method, after Warhol): one photographic image repeated
+in a grid, every panel hand-painted in loud flat acrylic and then over-printed with the same black photo-stencil,
+which never quite lines up (numpy + Pillow only).
+
+Model (how the real ones were made, and what each step leaves on the canvas):
+ canvas cotton duck primed with white gesso, photographed flat under even light. The plain weave is a height
+ field -- warp and weft crossing over and under, slightly irregular spacing, thicker slubs -- and shows in
+ the bare gesso, faintly through paint, and in the ink wherever the film breaks.
+ grid the panels are masked out with tape on one canvas: straight edges, but paint creeps under the tape in a
+ few feathered spots; the strips between panels stay bare gesso.
+ colour acrylic, painted by hand *before* the black, from a rough tracing of the photo: first each panel's
+ background, then loose flat shapes (face, eyes, nose, collar ...). The shapes are simplified, a little
+ too big or too small, and drift off the photograph -- every panel differently. A paint area is flat but
+ not dead: a few percent of lightness along the brush direction, thin dry drags, a low ridge where the
+ brush stopped, and the weave telegraphing through.
+ key one photographic stencil, made from a high-contrast print of a photo. Only the shadow masses survive:
+ solid where the photo was dark, a coarse halftone where it was mid-grey (`tone=`), open where it was
+ light, with the grainy wandering edge of a photographic threshold and a few dust specks on the film.
+ The key is laid down by hand on every panel: each time a different shift and a hair of rotation against
+ the paint.
+ pull the squeegee drags black ink through the mesh in one stroke (`pull=` gives its direction). Starved of
+ ink, the film breaks: streaks along the stroke, a nick in the blade leaves a thin skipped line, a dry
+ patch where ink has clogged the mesh, the weave valleys left bare -- the colour underneath shows through
+ the black. Flooded, the shapes swell, narrow gaps fill in and blobs squeeze past the stencil edge. Every
+ panel gets its own mix; `ghost=` adds a faint second impression where the screen was set down twice.
+Coordinates: pixels on the canvas; inside a panel you draw in *units* (`Panel.at(u, v)`): the unit origin and size
+are chosen per panel, x to the right, y down. Rotations (`turn`, `rot`, brush `direction`) are degrees
+counter-clockwise on screen; the squeegee `pull` is a travel direction in screen axes (90 = top to bottom).
+
+ from popart import PopSilkscreen, turn, TURQUOISE, LEMON, HOT_PINK
+ ps = PopSilkscreen(1920, 1080, seed=5)
+ ps.canvas()
+ panels = ps.grid(3, 2, gap=12, margin=14, origin=(0.5, 0.53), unit=0.285)
+ p = panels[0]
+ ps.ground(p, TURQUOISE) # background, up to the tape
+ ps.paint(p, p.shape(face_pts), LEMON, drift=(9, -4)) # loose hand-painted shape, off the photo
+ solid = p.shape(shadow_pts); tone = p.soft(p.shape(cheek_pts), 0.08)
+ ps.key(p, solid, tone=tone, shift=(-7, 5), rot=0.6, density=0.94) # the black screen, a bit starved
+ ps.save('out.jpg')
+"""
+import os
+import numpy as np
+from PIL import Image, ImageDraw
+from core import blur, noise2d, smoothstep, spline
+
+# ---------------------------------------------------------------- a loud 1960s acrylic palette
+GESSO, INK = '#f1ede3', '#141312'
+HOT_PINK, PINK, BLUSH = '#ff3d8f', '#ff86bd', '#ffc2d9'
+RED, ORANGE, TANGERINE = '#e8202a', '#ff6a13', '#ff9a1f'
+LEMON, YELLOW, CREAM = '#ffe53b', '#ffc21a', '#fff1d2'
+LIME, GREEN, MINT = '#c4ec2f', '#22c35e', '#7df0b4'
+TURQUOISE, SKY, BLUE = '#14b8c4', '#4fb3ff', '#2253e6'
+ULTRA, VIOLET, LILAC = '#3a2fd0', '#8a3ff0', '#c9a6ff'
+WHITE = '#fbf8f2'
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+def _c(c):
+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)
+
+
+def closed_spline(pts, per=10):
+ """closed Catmull-Rom through control points"""
+ P = np.asarray(pts, np.float32)
+ n = len(P)
+ t = np.linspace(0, 1, per, endpoint=False)[:, None]
+ t2, t3 = t * t, t * t * t
+ out = []
+ for i in range(n):
+ p0, p1, p2, p3 = P[i - 1], P[i], P[(i + 1) % n], P[(i + 2) % n]
+ out.append(0.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2
+ + (-p0 + 3 * p1 - 3 * p2 + p3) * t3))
+ return np.concatenate(out, 0)
+
+
+def turn(pts, deg, about=(0.0, 0.0)):
+ """rotate points counter-clockwise on screen (y down) by `deg` about `about`"""
+ P = np.asarray(pts, np.float32)
+ if not deg: return P
+ a = np.deg2rad(deg)
+ c, s = np.cos(a), np.sin(a)
+ d = P - np.asarray(about, np.float32)
+ return np.stack([about[0] + c * d[:, 0] + s * d[:, 1], about[1] - s * d[:, 0] + c * d[:, 1]], 1)
+
+
+def mirror(pts):
+ """reflect points about the vertical unit axis (u -> -u), keeping their order"""
+ P = np.array(pts, np.float32)
+ P[:, 0] *= -1
+ return P
+
+
+def _sample(a, X, Y):
+ """bilinear sample of a 2D array at float pixel coords (edge-clamped)"""
+ h, w = a.shape
+ X = np.clip(X, 0, w - 1.001); Y = np.clip(Y, 0, h - 1.001)
+ x0, y0 = X.astype(np.int32), Y.astype(np.int32)
+ fx, fy = X - x0, Y - y0
+ return ((a[y0, x0] * (1 - fx) + a[y0, x0 + 1] * fx) * (1 - fy)
+ + (a[y0 + 1, x0] * (1 - fx) + a[y0 + 1, x0 + 1] * fx) * fy)
+
+
+class Panel:
+ """one image of the grid. Canvas rect (x0, y0, x1, y1); masks live in a local window padded by `pad` px on
+ every side (so paint can creep under the tape and the key can wander); units map to local px through
+ `at(u, v)` = origin + (u, v) * scale."""
+
+ def __init__(self, ps, index, x0, y0, x1, y1, pad, origin, unit):
+ self.ps, self.index = ps, index
+ self.x0, self.y0, self.x1, self.y1 = x0, y0, x1, y1
+ self.w, self.h = x1 - x0, y1 - y0
+ self.pad = pad
+ self.lx0, self.ly0 = x0 - pad, y0 - pad # local window on the canvas
+ self.lw, self.lh = self.w + 2 * pad, self.h + 2 * pad
+ self.s = unit * self.h # px per unit
+ self.ox = pad + origin[0] * self.w
+ self.oy = pad + origin[1] * self.h
+ yy, xx = np.mgrid[0:self.lh, 0:self.lw].astype(np.float32)
+ self.XX, self.YY = xx, yy
+ inside = (np.clip(np.minimum(xx - pad, pad + self.w - xx) + 0.5, 0, 1)
+ * np.clip(np.minimum(yy - pad, pad + self.h - yy) + 0.5, 0, 1))
+ self.rect = inside.astype(np.float32) # the taped rectangle
+ self.tape = self.rect # replaced by ground() (with bleed)
+
+ # ------------------------------------------------------------ units
+ def at(self, u, v):
+ return self.ox + u * self.s, self.oy + v * self.s
+
+ def _px(self, pts):
+ P = np.asarray(pts, np.float32)
+ return np.stack([self.ox + P[:, 0] * self.s, self.oy + P[:, 1] * self.s], 1)
+
+ def xy(self, u, v):
+ """unit -> canvas px"""
+ x, y = self.at(u, v)
+ return x + self.lx0, y + self.ly0
+
+ def blank(self):
+ return np.zeros((self.lh, self.lw), np.float32)
+
+ # ------------------------------------------------------------ rasterising (4x supersampled, bbox-cropped)
+ def _raster(self, polys, ellipses=(), ss=4):
+ allp = [p for p in polys if len(p) >= 3]
+ boxes = [p for p in allp] + [np.array([[x - r, y - r], [x + r, y + r]]) for x, y, r, _ in ellipses]
+ if not boxes: return self.blank()
+ B = np.concatenate(boxes, 0)
+ bx0 = int(max(0, np.floor(B[:, 0].min()) - 2)); by0 = int(max(0, np.floor(B[:, 1].min()) - 2))
+ bx1 = int(min(self.lw, np.ceil(B[:, 0].max()) + 3)); by1 = int(min(self.lh, np.ceil(B[:, 1].max()) + 3))
+ out = self.blank()
+ if bx1 <= bx0 or by1 <= by0: return out
+ im = Image.new('L', ((bx1 - bx0) * ss, (by1 - by0) * ss), 0)
+ d = ImageDraw.Draw(im)
+ for p in allp:
+ d.polygon([((x - bx0) * ss, (y - by0) * ss) for x, y in p], fill=255)
+ for x, y, r, ry in ellipses:
+ d.ellipse(((x - r - bx0) * ss, (y - ry - by0) * ss, (x + r - bx0) * ss, (y + ry - by0) * ss), fill=255)
+ out[by0:by1, bx0:bx1] = np.asarray(im.resize((bx1 - bx0, by1 - by0), Image.BOX), np.float32) / 255
+ return out
+
+ # ------------------------------------------------------------ masks (local window, 0..1)
+ def shape(self, pts, smooth=True, per=10):
+ """filled closed outline through unit control points (Catmull-Rom unless smooth=False)"""
+ P = closed_spline(pts, per) if smooth else np.asarray(pts, np.float32)
+ return self._raster([self._px(P)])
+
+ def ellipse(self, u, v, ru, rv=None, rot=0.0):
+ rv = ru if rv is None else rv
+ t = np.linspace(0, 2 * np.pi, 72, endpoint=False)
+ P = np.stack([u + ru * np.cos(t), v + rv * np.sin(t)], 1)
+ return self._raster([self._px(turn(P, rot, (u, v)))])
+
+ def dots(self, spots):
+ """many small discs: [(u, v, r), ...]"""
+ return self._raster([], [(*self.at(u, v), r * self.s, r * self.s) for u, v, r in spots])
+
+ def stroke(self, pts, w0, w1=None, smooth=True, caps=True, profile=None, per=8):
+ """a filled stroke along unit points, width w0 -> w1 (units); `profile(t)` overrides the taper
+ (e.g. lambda t: np.sin(np.pi * t) ** 0.6 for a stripe that swells in the middle)"""
+ P = spline(pts, per) if smooth and len(pts) > 2 else np.asarray(pts, np.float32)
+ if len(P) < 2: return self.blank()
+ P = self._px(P)
+ d = np.gradient(P, axis=0)
+ n = np.stack([-d[:, 1], d[:, 0]], 1) / (np.linalg.norm(d, axis=1, keepdims=True) + 1e-6)
+ seg = np.r_[0, np.cumsum(np.linalg.norm(np.diff(P, axis=0), axis=1))]
+ t = seg / (seg[-1] + 1e-6)
+ w1 = w0 if w1 is None else w1
+ wid = (w0 + (w1 - w0) * t) if profile is None else w0 * profile(t)
+ wid = np.clip(np.nan_to_num(wid), 0, None) # sin(pi)**0.7 can be nan
+ hw = (wid * self.s / 2)[:, None]
+ poly = np.concatenate([P + n * hw, (P - n * hw)[::-1]], 0)
+ ell = []
+ if caps:
+ for i in (0, -1):
+ r = float(hw[i, 0])
+ if r > 0.3: ell.append((P[i, 0], P[i, 1], r, r))
+ return self._raster([poly], ell)
+
+ def soft(self, mask, sigma):
+ """a soft tone field from a mask (sigma in units) -- feed it to key(tone=) for a halftone fringe"""
+ return blur(mask, sigma * self.s)
+
+ def clip(self, mask):
+ """keep a mask inside the taped rectangle"""
+ return mask * self.tape
+
+
+class PopSilkscreen:
+ def __init__(self, W=1920, H=1080, seed=0, light=(-0.55, -0.8)):
+ self.W, self.H = W, H
+ self.rng = np.random.default_rng(seed)
+ self.img = np.ones((H, W, 3), np.float32) * _c(GESSO)
+ self.weave = np.zeros((H, W), np.float32) # thread height, about -1 .. 1
+ self.thick = np.zeros((H, W), np.float32) # paint film, hides the weave
+ self.relief = np.zeros((H, W), np.float32) # ridges at paint edges
+ self.light_dir = np.array(light, np.float32) / (np.linalg.norm(light) + 1e-6)
+ self.room = np.ones((H, W), np.float32)
+ self.panels = []
+ self.stages = []
+ self._grain = None
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ def _win(self, p):
+ """canvas slices and matching local slices for panel p's window (clipped to the canvas)"""
+ cx0, cy0 = max(0, p.lx0), max(0, p.ly0)
+ cx1, cy1 = min(self.W, p.lx0 + p.lw), min(self.H, p.ly0 + p.lh)
+ return ((slice(cy0, cy1), slice(cx0, cx1)),
+ (slice(cy0 - p.ly0, cy1 - p.ly0), slice(cx0 - p.lx0, cx1 - p.lx0)))
+
+ # ------------------------------------------------------------ the support
+ def canvas(self, gesso=GESSO, thread=3.8, slub=0.18):
+ """gessoed cotton duck: plain weave height field (over / under, jittered spacing, slubs), a slightly uneven
+ white ground, and the even light of a studio photograph (a soft falloff toward the corners)"""
+ H, W, r = self.H, self.W, self.rng
+ jx = (noise2d(H, W, 90, 2, self._seed()) - 0.5) * 0.9 # threads wander a little
+ jy = (noise2d(H, W, 90, 2, self._seed()) - 0.5) * 0.9
+ sl_w = np.asarray(Image.fromarray(r.random((H // 26 + 2, W // 4 + 2)).astype(np.float32))
+ .resize((W, H), Image.BICUBIC)) - 0.5 # slubs: thicker stretches of thread
+ sl_h = np.asarray(Image.fromarray(r.random((H // 4 + 2, W // 26 + 2)).astype(np.float32))
+ .resize((W, H), Image.BICUBIC)) - 0.5
+ hgt = np.empty((H, W), np.float32)
+ xx = np.arange(W, dtype=np.float32)[None, :]
+ for a in range(0, H, 180): # in bands: fewer big temporaries
+ b = min(H, a + 180)
+ yy = np.arange(a, b, dtype=np.float32)[:, None]
+ u, v = xx / thread + jx[a:b], yy / thread + jy[a:b]
+ iu, iv = np.floor(u), np.floor(v)
+ pw, pv = np.cos(np.pi * (u - iu - 0.5)), np.cos(np.pi * (v - iv - 0.5)) # 1 on a thread's crown
+ over = ((iu + iv) % 2) == 0
+ hgt[a:b] = np.where(over, pw * (0.62 + 0.38 * pv) * (1 + 2 * slub * sl_w[a:b]),
+ pv * (0.62 + 0.38 * pw) * (1 + 2 * slub * sl_h[a:b]))
+ del jx, jy, sl_w, sl_h
+ hgt = blur(hgt, 0.55)
+ self.weave = ((hgt - hgt.mean()) / (hgt.std() + 1e-6)).astype(np.float32)
+ del hgt
+ base = _c(gesso) * (1 + 0.012 * (noise2d(H, W, 260, 3, self._seed()) - 0.5))[..., None]
+ self.img = base.astype(np.float32)
+ yy, xx = np.arange(H, dtype=np.float32)[:, None], np.arange(W, dtype=np.float32)[None, :]
+ grad = 1 + 0.022 * (0.5 - (xx / W * 0.6 + yy / H * 0.4))
+ vig = 1 - 0.05 * (((xx - W * 0.5) / W) ** 2 + ((yy - H * 0.5) / H) ** 2) * 2
+ self.room = (grad * vig).astype(np.float32)
+ self.thick[:] = 0
+
+ def grid(self, cols, rows, gap=12, margin=14, origin=(0.5, 0.53), unit=0.285, pad=None):
+ """divide the canvas into cols x rows taped panels (row by row); returns the list of Panels.
+ origin: where unit (0, 0) sits in each panel (fractions of its width / height); unit: px per unit as a
+ fraction of the panel height."""
+ pad = int(pad if pad is not None else max(gap, 18))
+ xs = np.linspace(margin, self.W - margin + gap, cols + 1)
+ ys = np.linspace(margin, self.H - margin + gap, rows + 1)
+ self.panels = []
+ for j in range(rows):
+ for i in range(cols):
+ x0, x1 = int(round(xs[i])), int(round(xs[i + 1] - gap))
+ y0, y1 = int(round(ys[j])), int(round(ys[j + 1] - gap))
+ self.panels.append(Panel(self, len(self.panels), x0, y0, x1, y1, pad, origin, unit))
+ return self.panels
+
+ # ------------------------------------------------------------ hand-painted acrylic
+ def _brush(self, h, w, angle, length=140.0, width=7.0):
+ """zero-mean, unit-std streak texture running along `angle` (deg, ccw)"""
+ r = self.rng
+ L = int(np.hypot(h, w)) + 8
+ out = np.zeros((L, L), np.float32)
+ for k, (ln, wd) in enumerate([(length, width), (length * 0.5, width * 3.0)]):
+ a = r.standard_normal((max(2, int(L / wd)), max(2, int(L / ln)))).astype(np.float32)
+ out += np.asarray(Image.fromarray(a).resize((L, L), Image.BICUBIC)) * (1.0 if k == 0 else 0.6)
+ im = Image.fromarray(out).rotate(angle, resample=Image.BILINEAR)
+ a = np.asarray(im)[(L - h) // 2:(L - h) // 2 + h, (L - w) // 2:(L - w) // 2 + w]
+ return ((a - a.mean()) / (a.std() + 1e-6)).astype(np.float32)
+
+ def _wobble(self, p, m, amp, drift, scale=70.0):
+ """re-sample a mask through a low-frequency displacement: a hand-painted edge, `drift` px off the photo"""
+ if amp <= 0 and not any(drift): return m
+ dx = (noise2d(p.lh, p.lw, scale, 2, self._seed()) - 0.5) * 2 * amp
+ dy = (noise2d(p.lh, p.lw, scale, 2, self._seed()) - 0.5) * 2 * amp
+ return _sample(m, p.XX - drift[0] - dx, p.YY - drift[1] - dy)
+
+ def paint(self, p, mask, colour, direction=None, wobble=3.0, drift=(0.0, 0.0), opacity=0.97, dry=0.15,
+ clip=True, streak=0.012):
+ """brush one flat acrylic shape onto panel p. mask: local mask (from Panel.shape / ellipse / stroke ...).
+ wobble: px of hand wander along the edge; drift: (dx, dy) px the painter's tracing is off the photo;
+ direction: brush angle in degrees (random if None); dry: how much the brush drags thin near the edge;
+ streak: lightness variation along the strokes"""
+ m = self._wobble(p, mask, wobble, drift)
+ if clip: m = m * p.tape
+ rows, cols = np.flatnonzero(m.max(1) > 0.004), np.flatnonzero(m.max(0) > 0.004)
+ if not len(rows): return
+ (cs, ls) = self._win(p)
+ y0, y1, x0, x1 = rows[0], rows[-1] + 1, cols[0], cols[-1] + 1
+ y0, y1 = max(y0, ls[0].start), min(y1, ls[0].stop)
+ x0, x1 = max(x0, ls[1].start), min(x1, ls[1].stop)
+ if y1 <= y0 or x1 <= x0: return
+ mm = m[y0:y1, x0:x1]
+ h, w = mm.shape
+ ang = float(self.rng.uniform(-30, 30) if direction is None else direction)
+ tex = self._brush(h, w, ang)
+ # dry drags: where the brush ran thin, mostly within a band along the edge
+ band = np.clip((mm - blur(mm, 6.0)) * 3.0, 0, 1) # only near the edge of the shape
+ drag = smoothstep(1.4, 2.6, -tex) * band * dry
+ cov = np.clip(mm * opacity * (1 - drag), 0, 1)[..., None]
+ col = _c(colour)[None, None, :] * (1 + streak * tex[..., None] + 0.006 * self.rng.standard_normal())
+ gy0, gx0 = p.ly0 + y0, p.lx0 + x0
+ sl = (slice(gy0, gy0 + h), slice(gx0, gx0 + w))
+ self.img[sl] = self.img[sl] * (1 - cov) + col * cov
+ self.thick[sl] = np.maximum(self.thick[sl], mm * (0.75 + 0.15 * tex))
+ rim = np.clip(mm - blur(mm, 1.6), 0, 1) # paint piles up where the brush stops
+ self.relief[sl] += rim * 0.35 + mm * 0.05 * tex
+
+ def ground(self, p, colour, direction=0.0, bleed=1.0, opacity=0.985):
+ """paint panel p's background right up to the tape: straight edges with a few feathered spots where the
+ paint crept underneath"""
+ r = self.rng
+ dist_out = np.maximum(np.maximum(p.pad - p.XX, p.XX - (p.pad + p.w)),
+ np.maximum(p.pad - p.YY, p.YY - (p.pad + p.h)))
+ n = noise2d(p.lh, p.lw, 7.0, 3, self._seed())
+ spots = smoothstep(0.62, 0.9, noise2d(p.lh, p.lw, 46.0, 2, self._seed()))
+ reach = bleed * (0.6 + 4.5 * spots * n)
+ creep = np.clip(reach - dist_out, 0, 1) * (dist_out > 0)
+ tape = np.maximum(p.rect, creep * (0.55 + 0.45 * n))
+ p.tape = tape.astype(np.float32)
+ self.paint(p, p.tape, colour, direction=direction, wobble=0.0, opacity=opacity, dry=0.0, clip=False)
+
+ # ------------------------------------------------------------ the photo-stencil and the pull
+ def _halftone(self, p, tone, cell, angle):
+ a = np.deg2rad(angle)
+ u = (p.XX * np.cos(a) + p.YY * np.sin(a)) / cell
+ v = (-p.XX * np.sin(a) + p.YY * np.cos(a)) / cell
+ d = np.hypot(u - np.floor(u) - 0.5, v - np.floor(v) - 0.5) * cell
+ t = np.clip(tone, 0, 1)
+ rad = cell * np.sqrt(t / np.pi)
+ return np.clip(rad - d + 0.5, 0, 1) * (t > 0.02)
+
+ def _film_grain(self, p):
+ """the stencil film's grain, the same for every panel of one size (it is the same screen)"""
+ key = (p.lh, p.lw)
+ if self._grain is None or self._grain[0] != key:
+ g = np.random.default_rng(7).random((p.lh, p.lw)).astype(np.float32)
+ g = blur(g, 0.7)
+ g = (g - g.mean()) / (g.std() + 1e-6)
+ c = noise2d(p.lh, p.lw, 9.0, 2, 11)
+ c = (c - c.mean()) / (c.std() + 1e-6)
+ self._grain = (key, (0.55 * g + 0.45 * c).astype(np.float32))
+ return self._grain[1]
+
+ def stencil(self, p, solid, tone=None, cell=7.0, angle=45.0, grain=0.22, specks=18):
+ """the photographic key for panel p: solid masses plus a halftone where `tone` is mid-grey, thresholded
+ with film grain (a wandering, slightly granular edge) and a few dust specks"""
+ st = np.clip(solid, 0, 1)
+ if tone is not None:
+ st = np.maximum(st, self._halftone(p, tone, cell, angle))
+ g = self._film_grain(p)
+ e = blur(st, 0.85) + g * grain * 0.5
+ st = smoothstep(0.38, 0.62, e)
+ if specks:
+ r = np.random.default_rng(101) # same specks on every pull
+ near = blur(np.clip(solid, 0, 1), 14) > 0.02
+ ys, xs = np.nonzero(near[::4, ::4])
+ if len(ys):
+ pick = r.choice(len(ys), size=min(specks, len(ys)), replace=False)
+ spots = [(xs[i] * 4 + r.uniform(0, 4), ys[i] * 4 + r.uniform(0, 4),
+ r.uniform(0.7, 2.2) * (2.2 if r.random() < 0.12 else 1), 0) for i in pick]
+ im = Image.new('L', (p.lw * 2, p.lh * 2), 0)
+ d = ImageDraw.Draw(im)
+ for x, y, rr, _ in spots:
+ d.ellipse(((x - rr) * 2, (y - rr * r.uniform(0.6, 1)) * 2, (x + rr) * 2, (y + rr) * 2), fill=255)
+ st = np.maximum(st, np.asarray(im.resize((p.lw, p.lh), Image.BOX), np.float32) / 255)
+ return st.astype(np.float32)
+
+ def _place(self, p, st, rot, sh):
+ """lay the screen down by hand: rotate `rot` deg about the panel centre, then shift `sh` px"""
+ cx, cy = p.pad + p.w / 2, p.pad + p.h / 2
+ a = np.deg2rad(rot)
+ c, s = np.cos(a), np.sin(a)
+ X, Y = p.XX - sh[0] - cx, p.YY - sh[1] - cy # inverse map: canvas -> stencil
+ return _sample(st, cx + c * X - s * Y, cy + s * X + c * Y) if rot else _sample(st, X + cx, Y + cy)
+
+ def _film(self, p, density, pull, starve, nicks):
+ """ink film thickness over the panel window for one stroke of the squeegee"""
+ r = self.rng
+ h, w = p.lh, p.lw
+ vertical = abs(np.sin(np.deg2rad(pull))) > 0.5
+ across_n, along_n = (w, h) if vertical else (h, w)
+ def streaks(scale_across, scale_along):
+ a = r.random((max(2, int(along_n / scale_along)), max(2, int(across_n / scale_across)))).astype(np.float32)
+ im = np.asarray(Image.fromarray(a).resize((across_n, along_n), Image.BICUBIC))
+ return im if vertical else im.T
+ wide, thin = streaks(40, 260) - 0.5, streaks(3.5, 120) - 0.5
+ t = np.deg2rad(pull) # 90: top -> bottom, 0: left -> right
+ along = p.XX * np.cos(t) + p.YY * np.sin(t)
+ along = (along - along.min()) / (along.max() - along.min() + 1e-6) # 0 where the stroke starts
+ blot = noise2d(h, w, 38, 3, self._seed()) - 0.5
+ F = density * (1 + 0.16 * wide + 0.10 * thin + 0.14 * blot - 0.10 * smoothstep(0.3, 1.0, along))
+ if starve > 0: # a patch where ink dried in the mesh
+ clog = smoothstep(0.55, 0.8, noise2d(h, w, 120, 2, self._seed()))
+ F = F - starve * clog * (0.35 + 0.65 * r.random((h, w)).astype(np.float32))
+ for _ in range(nicks): # nicks in the blade -> skipped lines
+ pos = r.uniform(0.15, 0.85) * across_n
+ wid = r.uniform(1.4, 2.8)
+ cross = (p.XX if vertical else p.YY) - pos
+ depth = r.uniform(0.35, 0.6) * (0.5 + 0.5 * noise2d(h, w, 50, 2, self._seed()))
+ F = F - depth * np.exp(-0.5 * (cross / wid) ** 2)
+ return F.astype(np.float32)
+
+ def key(self, p, solid, tone=None, ink=INK, shift=(0.0, 0.0), rot=0.0, density=1.0, flood=0.2, starve=0.0,
+ pull=90.0, nicks=1, ghost=None, cell=7.0, angle=45.0, grain=0.22, opacity=0.97):
+ """pull the black screen through panel p. solid / tone: local masks (see stencil). shift (px), rot (deg):
+ how the screen was laid down against the paint. density: ink film (0.92 starved, 1.0 normal, 1.15 heavy -- below
+ about 0.9 the key falls apart); flood:
+ 0..1, ink squeezed past the stencil (swollen shapes, filled-in gaps, blobs); starve: a dry, clogged
+ patch; pull: squeegee direction; nicks: skipped lines from a nicked blade; ghost: (dx, dy, strength) a
+ faint second impression. Returns the printed coverage (local)."""
+ st = self.stencil(p, solid, tone, cell, angle, grain)
+ st = self._place(p, st, rot, shift) * p.rect
+ F = self._film(p, density, pull, starve, nicks)
+ if flood > 0: # heavy ink: swell, fill in, blobs
+ heavy = np.clip((F - 0.95) * 4, 0, 1)
+ sw = blur(st, 1.2 + 2.2 * flood)
+ thr = 0.5 - 0.32 * flood * (0.4 + 0.6 * heavy)
+ blobs = smoothstep(0.7, 0.92, noise2d(p.lh, p.lw, 16, 2, self._seed())) * flood
+ st = np.maximum(st, smoothstep(thr - 0.06, thr + 0.06, sw + blobs * 0.35 * (sw > 0.05)) * p.rect)
+ rg = np.random.default_rng(self._seed())
+ fine = blur(rg.random((p.lh, p.lw)).astype(np.float32), 0.6)
+ fine = (fine - fine.mean()) / (fine.std() + 1e-6) # pixel-scale speckle, a little clumped
+ clump = noise2d(p.lh, p.lw, 5.0, 2, self._seed()) - 0.5
+ (cs, ls) = self._win(p)
+ wv = self.weave[cs]
+ Fl = F[ls] + 0.035 * wv + 0.05 * fine[ls] + 0.22 * clump[ls] # the weave's valleys get a little less
+ cov = smoothstep(0.66, 0.84, Fl)
+ a = np.clip(st[ls] * cov * opacity, 0, 1)
+ if ghost:
+ gdx, gdy, gs = ghost
+ g2 = self._place(p, st, 0.0, (gdx, gdy)) * p.rect
+ cov2 = smoothstep(0.62, 0.86, F[ls] * 0.82 + 0.05 * wv + 0.08 * fine[ls] + 0.35 * clump[ls])
+ a = 1 - (1 - a) * (1 - np.clip(g2[ls] * cov2 * gs, 0, 1))
+ col = _c(ink)[None, None, :]
+ self.img[cs] = self.img[cs] * (1 - a[..., None]) + col * a[..., None]
+ self.thick[cs] = np.maximum(self.thick[cs], a * 0.35)
+ self.relief[cs] += a * 0.12
+ return a
+
+ # ------------------------------------------------------------ output
+ def composite(self, band=180):
+ """the painting photographed: paint ridges and the weave catch the light (computed in row bands)"""
+ H, W = self.H, self.W
+ out = np.empty((H, W, 3), np.uint8)
+ lx, ly = self.light_dir
+ for a in range(0, H, band):
+ b = min(H, a + band)
+ a0, b0 = max(0, a - 2), min(H, b + 2)
+ rel = np.pad(self.relief[a0:b0], 1, mode='edge')
+ n = rel.shape[0] - 2
+ rel = sum(rel[i:i + n, j:j + W] for i in range(3) for j in range(3)) / 9 # 3x3 smoothing
+ gy, gx = np.gradient(rel)
+ sh = (1 - 0.09 * (lx * gx + ly * gy))[a - a0:a - a0 + (b - a)]
+ vis = 1 - 0.72 * np.clip(self.thick[a:b], 0, 1)
+ sh = sh * (1 + 0.035 * self.weave[a:b] * vis) * self.room[a:b]
+ out[a:b] = (np.clip(self.img[a:b] * sh[..., None], 0, 1) * 255 + 0.5).astype(np.uint8)
+ return Image.fromarray(out)
+
+ 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) # 4:4:4 keeps the colour edges crisp
+ 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
diff --git a/lib/silhouette.py b/lib/silhouette.py
new file mode 100644
index 0000000..0b38412
--- /dev/null
+++ b/lib/silhouette.py
@@ -0,0 +1,808 @@
+"""silhouette — cut-paper silhouette portraits ("shades", c. 1790): black paper cut with small scissors, pasted on
+an ivory card, touched with thin shell gold, glazed in an oval gilt frame and hung on a block-printed wallpaper
+(numpy + Pillow only).
+
+Model:
+ wallpaper hand block-printed paper of the 1790s. A distemper ground brushed on by hand (broad mottling and a
+ faint horizontal brush drag), then each colour printed from its own wooden block: matte and chalky,
+ a little uneven, the colour squeezed into a slightly stronger rim at the edge of every printed shape,
+ dry specks where the block took too little colour, small misregistration between the blocks, and the
+ tiny pin-dots the printer used to line the block up. Lengths are butted at vertical seams where the
+ pattern does not quite match; inside a length the short sheets that made the roll show as faint
+ horizontal joins. Daylight from a window at the upper left falls off across the wall.
+ mouldings picture rail and chair rail: painted wooden mouldings lit from the upper left, throwing a soft
+ shadow down onto the paper; a brass hook over the picture rail for every frame.
+ cord a twisted silk cord from the hook, splitting into an inverted V that runs behind the frame: a lit
+ cylinder with diagonal twist stripes and its own shadow on the wall.
+ frame an oval gilt frame built as a height field from a moulding profile, from the opening outwards:
+ sight-edge bead, cove, a row of pearls, a big torus (optionally twisted like a ribbon), a fillet and
+ an outer roll. Gold is a mirror: every pixel's normal reflects a room (a soft window at the upper
+ left, a dim room, a dark floor), so the gilt reads as the concentric bright and dark rings of a real
+ frame. Gold leaf is laid in squares (faint overlaps); on the most exposed crests it is rubbed through
+ to the red bole underneath; grime and ambient occlusion sit in the hollows. Contact and soft drop
+ shadows on the wall.
+ card ivory card behind the glass: smooth, toned darker toward the edge (two centuries of light), with a
+ few foxing spots.
+ paper the silhouette is black paper cut with scissors. The main outline (`shape`) is glued flat and throws
+ only a hairline shadow; loose snips (`snip`, `line`, `fringe`: hair, lashes, whiskers, plume barbs,
+ ribbon ends, rigging) are cut as separate tapered strips that lift a little and throw a longer
+ shadow. `hole` cuts the paper away so the card shows through (an eye, the gap between legs).
+ Outlines are resampled into tiny straight facets, one closing of the blades each; the black has a
+ faint fibre and sheen, and edges that face the light catch a hairline. Everything is drawn at 4x and
+ box-filtered down, so strands a pixel wide survive.
+ bronze thin shell-gold paint brushed over the black (hair strands, lace, folds, sail seams). Every stroke
+ tapers, has its own brightness (the metal flakes lie at random) and a little grain; paint only stays
+ on the paper.
+ ink captions in iron-gall ink, faded to brown, a little uneven; `pen` for ruled lines and flourishes.
+ glass verre eglomise: a black band with a gold fillet painted on the back of the glass round the opening;
+ the rebate of the frame throws a shadow onto the card from the upper left; after `glaze()` the convex
+ glass picks up a soft sheen and a crisp reflection of the window.
+
+ from silhouette import Silhouette
+ s = Silhouette(1920, 1080, seed=1)
+ s.wallpaper(); s.picture_rail(); s.chair_rail(1000)
+ f = s.frame(960, 540, 220, 280, width=60, hook=True) # opening radii; gilt moulding outside them
+ c = s.sheet(f, at=(960, 560), scale=0.5) # black paper; px = at + 0.5 * design units
+ c.shape(profile_pts); c.snip(hair_pts, 6, 0.5); c.hole(eye_pts)
+ s.paste(c) # glue it onto the card
+ s.bronze(c, [strand_pts, ...], width=2.5) # thin gold over the black
+ s.caption(f, 'Miss A. Lark', 960, 780, 34)
+ s.glaze() # glass reflections on every frame
+ s.save('out.jpg')
+Coordinates are output pixels, y down. Sheet and bronze methods take design units: px = at + scale * (x, y)
+(x mirrored when flip=True); widths are in design units too.
+"""
+import glob
+import os
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+from core import blur, noise2d, smoothstep, shift, load_font, text_mask
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+def _c(c):
+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)
+
+
+# ---------------------------------------------------------------- fonts: copperplate roundhand and a Georgian italic
+_FONTS = {
+ 'roundhand': [('/System/Library/Fonts/Supplemental/SnellRoundhand.ttc', 0), ('/System/Library/Fonts/Supplemental/Apple Chancery.ttf', 0),
+ ('/usr/share/fonts/**/z003*.[ot]tf', 0), ('C:/Windows/Fonts/segoesc.ttf', 0)],
+ 'italic': [('/System/Library/Fonts/Supplemental/Baskerville.ttc', 2), ('/System/Library/Fonts/Supplemental/Hoefler Text.ttc', 2),
+ ('/System/Library/Fonts/Supplemental/Didot.ttc', 1), ('/usr/share/fonts/**/DejaVuSerif-Italic.ttf', 0),
+ ('C:/Windows/Fonts/georgiai.ttf', 0)],
+ 'caps': [('/System/Library/Fonts/Supplemental/Didot.ttc', 0), ('/System/Library/Fonts/Supplemental/Baskerville.ttc', 0),
+ ('/usr/share/fonts/**/DejaVuSerif.ttf', 0), ('C:/Windows/Fonts/georgia.ttf', 0)],
+}
+_FCACHE = {}
+
+
+def sil_font(kind, size):
+ """PIL font: 'roundhand' (copperplate script), 'italic' (Georgian italic) or 'caps' (Didone roman).
+ Override with $INKPAINT_FONT_ROUNDHAND / _ITALIC / _CAPS."""
+ key = (kind, int(size))
+ if key in _FCACHE: return _FCACHE[key]
+ env = os.environ.get('INKPAINT_FONT_' + kind.upper())
+ font = None
+ for pat, idx in ([(env, 0)] if env else []) + _FONTS.get(kind, []):
+ for p in glob.glob(pat, recursive=True):
+ try:
+ font = ImageFont.truetype(p, max(4, int(size)), index=idx); break
+ except OSError:
+ pass
+ if font: break
+ if font is None: font = load_font({'roundhand': 'script', 'italic': 'serif', 'caps': 'serif'}.get(kind, 'serif'), size)
+ _FCACHE[key] = font
+ return font
+
+
+def _box3(a, n=1):
+ """3 x 3 mean, n times (a cheap small blur for full-canvas float32 arrays)"""
+ for _ in range(n):
+ p = np.pad(a, 1, mode='edge')
+ a = (p[:-2, :-2] + p[:-2, 1:-1] + p[:-2, 2:] + p[1:-1, :-2] + p[1:-1, 1:-1] + p[1:-1, 2:] + p[2:, :-2] + p[2:, 1:-1] + p[2:, 2:]) / 9
+ return a
+
+
+def _resample(P, step, closed):
+ """polyline -> points every `step` along its length"""
+ P = np.asarray(P, np.float64)
+ if closed: P = np.vstack([P, P[:1]])
+ seg = np.hypot(*np.diff(P, axis=0).T)
+ s = np.concatenate([[0], np.cumsum(seg)])
+ n = max(3, int(s[-1] / max(step, 1e-3)) + 1)
+ t = np.linspace(0, s[-1], n, endpoint=not closed)
+ return np.stack([np.interp(t, s, P[:, 0]), np.interp(t, s, P[:, 1])], 1)
+
+
+def _strip(C, w0, w1):
+ """outline polygon of a tapered strip along centreline C (N x 2) whose width runs w0 -> w1 (or an array)"""
+ C = np.asarray(C, np.float64)
+ if len(C) < 2: return None
+ d = np.gradient(C, axis=0)
+ d /= np.hypot(d[:, 0], d[:, 1])[:, None] + 1e-9
+ n = np.stack([-d[:, 1], d[:, 0]], 1)
+ w = np.asarray(w0, np.float64) if np.ndim(w0) else np.linspace(w0, w1, len(C))
+ L = C + n * (w[:, None] / 2); R = C - n * (w[:, None] / 2)
+ return np.vstack([L, R[::-1]])
+
+
+def smooth(pts, per=8, closed=True):
+ """Catmull-Rom through control points; closed=True wraps round (outlines), False for open curves"""
+ P = np.asarray(pts, np.float64)
+ if not closed:
+ P = np.vstack([2 * P[0] - P[1], P, 2 * P[-1] - P[-2]])
+ else:
+ P = np.vstack([P[-1:], P, P[:2]])
+ out = []
+ for i in range(1, len(P) - 2):
+ p0, p1, p2, p3 = P[i - 1], P[i], P[i + 1], P[i + 2]
+ for t in np.linspace(0, 1, per, endpoint=False):
+ t2, t3 = t * t, t * t * t
+ out.append(0.5 * (2 * p1 + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 + (-p0 + 3 * p1 - 3 * p2 + p3) * t3))
+ if not closed: out.append(P[-2])
+ return np.array(out)
+
+
+class Frame:
+ """an oval gilt frame on the wall and the card behind its glass (local arrays cover the opening's bbox)"""
+ pass
+
+
+class Sheet:
+ """a sheet of black paper over one frame's card; draws at `ss` x supersampling in design units"""
+
+ def __init__(self, sil, frame, at, scale, flip, ss=4, facet=2.2, warp=None):
+ self.sil, self.f, self.ss, self.warp = sil, frame, ss, warp
+ self.ax, self.ay = at
+ self.k, self.flip, self.facet = scale, flip, facet
+ size = (frame.w * ss, frame.h * ss)
+ self.body = Image.new('L', size, 0)
+ self.loose = Image.new('L', size, 0)
+ self.db, self.dl = ImageDraw.Draw(self.body), ImageDraw.Draw(self.loose)
+ self.mask = None
+ self.rng = np.random.default_rng(sil._seed())
+
+ # ---------------------------------------------------------------- coordinates
+ def px(self, pts):
+ """design units -> canvas pixels"""
+ P = np.asarray(pts, np.float64).reshape(-1, 2)
+ if self.warp is not None: P = np.asarray(self.warp(P), np.float64).reshape(-1, 2)
+ x = -P[:, 0] if self.flip else P[:, 0]
+ return np.stack([self.ax + self.k * x, self.ay + self.k * P[:, 1]], 1)
+
+ def _ss(self, pts):
+ P = self.px(pts)
+ return np.stack([(P[:, 0] - self.f.x0) * self.ss, (P[:, 1] - self.f.y0) * self.ss], 1)
+
+ def _poly(self, draw, P, fill):
+ if P is None or len(P) < 3: return
+ draw.polygon([(float(x), float(y)) for x, y in P], fill=fill)
+
+ # ---------------------------------------------------------------- cutting
+ def shape(self, pts, loose=False):
+ """the main outline, glued flat: closed polygon in design units (spline it first). The edge is
+ re-cut into tiny straight facets with a hair of jitter, like successive closings of the scissors."""
+ P = self._ss(pts)
+ step = self.facet * self.ss
+ Q = _resample(P, step, closed=True)
+ if len(Q) > 6:
+ d = np.roll(Q, -1, 0) - np.roll(Q, 1, 0)
+ n = np.stack([-d[:, 1], d[:, 0]], 1) / (np.hypot(d[:, 0], d[:, 1])[:, None] + 1e-9)
+ Q = Q + n * self.rng.normal(0, 0.12 * self.ss, (len(Q), 1))
+ self._poly(self.dl if loose else self.db, Q, 255)
+
+ def snip(self, pts, w0, w1=0.0, loose=True):
+ """a separately cut tapered strip along a centreline (hair, lash, whisker, ribbon end), width in design
+ units from w0 at the start to w1 at the end (or an array of widths)"""
+ P = self._ss(pts)
+ if len(P) < 2: return
+ C = _resample(P, max(1.0, self.ss * 0.75), closed=False)
+ k = self.k * self.ss
+ w = np.asarray(w0, np.float64) * k if np.ndim(w0) else np.linspace(w0 * k, w1 * k, len(C))
+ if np.ndim(w0): w = np.interp(np.linspace(0, 1, len(C)), np.linspace(0, 1, len(w)), w)
+ w = np.maximum(w, 0.9) # never thinner than ~1/4 px: it would vanish
+ self._poly(self.dl if loose else self.db, _strip(C, w, None), 255)
+
+ def line(self, pts, w, loose=True):
+ """a constant-width strip (rigging, a cord, a stem)"""
+ P = self._ss(pts)
+ C = _resample(P, max(1.0, self.ss * 0.75), closed=False)
+ self._poly(self.dl if loose else self.db, _strip(C, max(0.9, w * self.k * self.ss), max(0.9, w * self.k * self.ss)), 255)
+
+ def disc(self, x, y, r, loose=False):
+ t = np.linspace(0, 2 * np.pi, 40, endpoint=False)
+ self.shape(np.stack([x + r * np.cos(t), y + r * np.sin(t)], 1), loose)
+
+ def hole(self, pts):
+ """cut the paper away: the card shows through"""
+ P = self._ss(pts)
+ self._poly(self.db, P, 0); self._poly(self.dl, P, 0)
+
+ def fringe(self, pts, n, length, angle=40.0, width=3.0, side=(1, -1), bend=0.25, jitter=0.18, tip=0.0, start=0.0):
+ """many loose strands along a curve: plume barbs, fur, frizz. `length` is a number or (at start, at end);
+ `angle` is the strand angle from the curve's direction in degrees (barbs sweep toward the tip); `side`
+ picks which sides get strands (+1 left of travel, -1 right); `bend` curls each strand back toward the
+ curve; `start` skips the first fraction of the curve."""
+ C = _resample(np.asarray(pts, np.float64), 1.0, closed=False)
+ seg = np.hypot(*np.diff(C, axis=0).T); s = np.concatenate([[0], np.cumsum(seg)]); s /= s[-1] + 1e-9
+ d = np.gradient(C, axis=0); d /= np.hypot(d[:, 0], d[:, 1])[:, None] + 1e-9
+ L0, L1 = (length, length) if np.isscalar(length) else length
+ r = self.rng
+ for sd in side:
+ for t in np.linspace(start, 1, n, endpoint=False) + r.uniform(0, (1 - start) / n, n):
+ i = min(len(C) - 1, int(np.searchsorted(s, t)))
+ L = (L0 + (L1 - L0) * t) * r.uniform(1 - jitter, 1 + jitter)
+ a = np.radians(angle * r.uniform(0.85, 1.15)) * sd
+ tx, ty = d[i]
+ ux, uy = tx * np.cos(a) - ty * np.sin(a), tx * np.sin(a) + ty * np.cos(a)
+ nx, ny = -uy * sd, ux * sd # bend back toward the curve's direction
+ u = np.linspace(0, 1, 9)[:, None]
+ P = C[i] + np.stack([ux, uy]) * L * u - np.stack([nx, ny]) * L * bend * u ** 2 * r.uniform(0.6, 1.4)
+ self.snip(P, width * r.uniform(0.8, 1.2), tip)
+
+ def scallop(self, pts, r=(8, 12), step=0.8, loose=False, outset=0.4):
+ """a frizzed or curly edge: small overlapping discs along a curve (r in design units, step in radii,
+ pushed `outset` radii to the left of travel so they bulge out of the shape they trim)"""
+ C = _resample(np.asarray(pts, np.float64), 1.0, closed=False)
+ d = np.gradient(C, axis=0); d /= np.hypot(d[:, 0], d[:, 1])[:, None] + 1e-9
+ r0, r1 = (r, r) if np.isscalar(r) else r
+ s, i = 0.0, 0
+ seg = np.concatenate([[0], np.cumsum(np.hypot(*np.diff(C, axis=0).T))])
+ while s < seg[-1]:
+ i = min(len(C) - 1, int(np.searchsorted(seg, s)))
+ rr = self.rng.uniform(r0, r1)
+ n = np.array([d[i][1], -d[i][0]])
+ c = C[i] + n * rr * outset
+ self.disc(c[0], c[1], rr, loose)
+ s += rr * step * self.rng.uniform(0.8, 1.2)
+
+ def ringlet(self, x, y, length, width=16, turns=5, sway=6, lean=0.0):
+ """a corkscrew curl hanging from (x, y): a wavy strip that swells at every turn and tapers to a point;
+ returns its centreline (for bronzing)"""
+ u = np.linspace(0, 1, 120)
+ cx = x + sway * np.sin(2 * np.pi * turns * u) * (1 - 0.3 * u) + lean * length * u ** 2
+ cy = y + length * u
+ w = width * (0.72 + 0.28 * np.abs(np.cos(np.pi * turns * u))) * (1 - 0.55 * u) * np.clip(u / 0.06, 0.4, 1)
+ w[-12:] *= np.linspace(1, 0.15, 12)
+ C = np.stack([cx, cy], 1)
+ self.snip(C, w, loose=True)
+ return C
+
+ def lace(self, pts, depth=7, step=6, holes=True):
+ """a cut lace frill along a curve: a picot edge sticking out to the left of travel with a row of
+ pierced holes just inside it"""
+ C = _resample(np.asarray(pts, np.float64), 0.5, closed=False)
+ d = np.gradient(C, axis=0); d /= np.hypot(d[:, 0], d[:, 1])[:, None] + 1e-9
+ n = np.stack([d[:, 1], -d[:, 0]], 1)
+ seg = np.concatenate([[0], np.cumsum(np.hypot(*np.diff(C, axis=0).T))])
+ ph = (seg / step) % 1.0
+ out = depth * (0.35 + 0.65 * np.abs(np.sin(np.pi * ph)) ** 0.6)
+ edge = C + n * out[:, None]
+ inner = C - n * depth * 0.8
+ self.shape(np.vstack([edge, inner[::-1]]), loose=True)
+ if holes:
+ for t in np.arange(step * 0.5, seg[-1], step):
+ i = int(np.searchsorted(seg, t)); i = min(i, len(C) - 1)
+ c = C[i] + n[i] * depth * 0.05
+ tt = np.linspace(0, 2 * np.pi, 10, endpoint=False)
+ hr = depth * 0.2
+ self.hole(np.stack([c[0] + hr * np.cos(tt), c[1] + hr * np.sin(tt)], 1))
+
+ # ---------------------------------------------------------------- after cutting
+ def coverage(self):
+ """(body, loose) coverage at 1x in the frame's local box"""
+ b = np.asarray(self.body.reduce(self.ss), np.float32) / 255
+ l = np.asarray(self.loose.reduce(self.ss), np.float32) / 255
+ return b, l
+
+
+class Silhouette:
+ def __init__(self, W=1920, H=1080, seed=0, light=(-0.5, -0.65, 0.58)):
+ self.W, self.H = W, H
+ self.rng = np.random.default_rng(seed)
+ self.L = np.asarray(light, np.float32) / np.linalg.norm(light)
+ self.base = np.ones((H, W, 3), np.float32) * 0.8
+ self.frames = []
+ self.stages = []
+ self.rail_y = None
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ # ================================================================ wall
+ def wallpaper(self, ground='#7e96a1', ink='#ece2c8', tint=None, period=172, repeat=208, length=540, light=0.16):
+ """block-printed striped wallpaper: a brushed distemper ground, a darker stripe band with a row of printed
+ beads between two pinstripes, and a little sprig half-dropped between the bands. Lengths of paper are
+ butted every `length` px; each length has its own small misregistration and pattern drop."""
+ H, W = self.H, self.W
+ g = _c(ground); ink = _c(ink); tint = _c(tint) if tint is not None else g * np.array([0.80, 0.83, 0.86], np.float32)
+ r = self.rng
+ mott = noise2d(H, W, 260, 4, self._seed()) - 0.5
+ drag = np.asarray(Image.fromarray(r.random((H // 3, W // 90)).astype(np.float32)).resize((W, H), Image.BICUBIC), np.float32) - 0.5
+ grain = _box3(r.random((H, W), dtype=np.float32)) - 0.5
+ img = g[None, None, :] * (1 + 0.06 * mott + 0.025 * drag + 0.02 * grain)[..., None]
+
+ SS = 2
+ band = Image.new('L', (W * SS, H * SS), 0); cream = Image.new('L', (W * SS, H * SS), 0)
+ seams = list(range(int(r.uniform(-length * 0.6, -length * 0.2)), W + length, length))
+ P, V = period, repeat
+ for x0 in seams:
+ xa, xb = max(0, x0), min(W, x0 + length)
+ if xb <= xa: continue
+ # every length is its own strip of paper: print it on its own, then butt it against the last one
+ bl, cl = Image.new('L', ((xb - xa) * SS, H * SS), 0), Image.new('L', ((xb - xa) * SS, H * SS), 0)
+ db, dc = ImageDraw.Draw(bl), ImageDraw.Draw(cl)
+ ox = -xa # canvas x -> this strip's x
+ drop = r.uniform(-7, 7) # the pattern match at the seam is off a little
+ mis = r.normal(0, 1.1, 2) # cream block vs band block registration
+ img[:, xa:xb] *= 1 + r.uniform(-0.02, 0.02)
+ for k in range(-1, W // P + 2):
+ bx = k * P + P * 0.5
+ if bx + P < xa or bx - P > xb: continue
+ for j in range(-1, H // V + 2): # the block is printed one repeat at a time
+ y0, y1 = j * V + drop, (j + 1) * V + drop
+ wob = r.normal(0, 0.5)
+ db.rectangle([(bx - 15 + wob + ox) * SS, y0 * SS, (bx + 15 + wob + ox) * SS, y1 * SS + 1], fill=255)
+ cx = bx + mis[0] + r.normal(0, 0.3) + ox
+ for xx in (cx - 19.5, cx + 19.5): # pinstripes
+ dc.rectangle([(xx - 1.6) * SS, (y0 + mis[1]) * SS, (xx + 1.6) * SS, (y1 + mis[1]) * SS + 1], fill=255)
+ for q in range(8): # beads down the middle of the band
+ yy = y0 + mis[1] + (q + 0.5) * V / 8
+ rr = 3.1 if q % 2 == 0 else 1.9
+ dc.ellipse([(cx - rr) * SS, (yy - rr) * SS, (cx + rr) * SS, (yy + rr) * SS], fill=255)
+ sx = bx + P * 0.5 + mis[0] + ox # sprig between bands, half-dropped
+ sy = j * V + drop + (V * 0.5 if k % 2 else 0) + mis[1]
+ self._sprig(dc, sx, sy, SS)
+ dc.ellipse([(sx - 0.9) * SS, (sy - V / 2 - 0.9) * SS, (sx + 0.9) * SS, (sy - V / 2 + 0.9) * SS], fill=255) # pin dot
+ band.paste(bl, (xa * SS, 0)); cream.paste(cl, (xa * SS, 0))
+ mb = self._wander(np.asarray(band.reduce(SS), np.float32) / 255, 0.9)
+ mc = self._wander(np.asarray(cream.reduce(SS), np.float32) / 255, 0.7)
+ img = self._print(img, mb, tint, 0.86)
+ img = self._print(img, mc, ink, 0.66)
+ # seams: butt joins (a dark hairline and the lit edge of the next length) and the faint sheet joins
+ for x0 in seams:
+ if 1 <= x0 < W - 1:
+ img[:, x0] *= 0.84; img[:, x0 + 1] *= 0.95; img[:, x0 - 1] *= 1.04
+ for y in np.arange(r.uniform(150, 450), H, 540):
+ y = int(y)
+ xa, xb = max(0, x0), min(W, x0 + length)
+ if 0 < y < H - 1 and xb > xa:
+ img[y, xa:xb] *= 0.965; img[y - 1, xa:xb] *= 1.02
+ # daylight from the upper left
+ yy, xx = np.arange(H, dtype=np.float32)[:, None] / H, np.arange(W, dtype=np.float32)[None, :] / W
+ lit = 1 + light * (0.55 - 0.75 * xx - 0.45 * yy) - 0.06 * ((xx - 0.45) ** 2 + (yy - 0.4) ** 2)
+ age = noise2d(H, W, 400, 3, self._seed())
+ img = img * (1 - 0.05 * age[..., None]) + np.array([0.06, 0.045, 0.0], np.float32) * age[..., None] # yellowed size
+ self.base = np.clip(img * lit[..., None], 0, 1)
+
+ def _wander(self, m, amp):
+ """the block never comes down perfectly straight: shift every pixel sideways by a slow noise field"""
+ H, W = m.shape
+ dx = (noise2d(H, W, 70, 3, self._seed()) - 0.5) * 2 * amp
+ xs = np.clip(np.arange(W, dtype=np.float32)[None, :] - dx, 0, W - 1.001)
+ i0 = xs.astype(np.int32); fr = xs - i0
+ rows = np.arange(H)[:, None]
+ return m[rows, i0] * (1 - fr) + m[rows, i0 + 1] * fr
+
+ def _sprig(self, d, x, y, SS):
+ """a small block-printed sprig: a four-petal flower on a curved stem with two leaves"""
+ for a in range(4):
+ t = a * np.pi / 2 + np.pi / 4
+ px, py = x + np.cos(t) * 4.2, y - 9 + np.sin(t) * 4.2
+ d.ellipse([(px - 2.6) * SS, (py - 2.6) * SS, (px + 2.6) * SS, (py + 2.6) * SS], fill=255)
+ stem = [(x + 0.8 * np.sin(u * 2.4), y - 4 + u * 16) for u in np.linspace(0, 1, 8)]
+ d.line([(a * SS, b * SS) for a, b in stem], fill=255, width=int(1.6 * SS))
+ for sgn, yy in ((-1, y + 4), (1, y + 8)):
+ leaf = [(x, yy), (x + sgn * 4, yy - 3.5), (x + sgn * 8.5, yy - 2), (x + sgn * 4.5, yy + 1.2)]
+ d.polygon([(a * SS, b * SS) for a, b in leaf], fill=255)
+
+ def _print(self, img, m, col, opacity):
+ """one block of distemper colour: uneven, dry specks, colour squeezed into a rim at the edges"""
+ H, W = m.shape
+ dens = 0.86 + 0.14 * noise2d(H, W, 30, 3, self._seed())
+ dry = smoothstep(0.60, 0.80, _box3(self.rng.random((H, W), dtype=np.float32))) * 0.55
+ rim = np.clip(m - _box3(m, 2), 0, 1) * 1.6
+ a = np.clip(m * (dens - dry) * opacity + rim * 0.25 * m, 0, 1)
+ return img * (1 - a[..., None]) + col[None, None, :] * a[..., None] * (0.97 + 0.06 * dens[..., None])
+
+ def picture_rail(self, y=0, h=42, colour='#e7dfcd'):
+ """painted picture rail along the top of the wall (the frames hang from hooks on it)"""
+ self.rail_y = (y, y + h)
+ self.base = self._moulding(self.base, y, h, _c(colour), [(0.0, 0.18, 'flat'), (0.18, 0.62, 'torus'), (0.62, 0.74, 'fillet'), (0.74, 1.0, 'cove')])
+
+ def chair_rail(self, y, h=26, colour='#e7dfcd', dado='#d9cfb8'):
+ """chair rail at height y with the painted dado below it"""
+ H, W = self.H, self.W
+ dd = _c(dado)
+ y1 = int(y + h)
+ if y1 < H:
+ dn = (noise2d(H - y1, W, 180, 3, self._seed()) - 0.5) * 0.04
+ panel = dd[None, None, :] * (1 + dn[..., None]) * (1 + 0.12 * (0.5 - np.arange(W, dtype=np.float32) / W))[None, :, None]
+ self.base[y1:] = panel
+ self.base = self._moulding(self.base, y, h, _c(colour), [(0.0, 0.25, 'cove'), (0.25, 0.8, 'torus'), (0.8, 1.0, 'fillet')])
+
+ def _moulding(self, img, y0, h, col, parts):
+ H, W = self.H, self.W
+ y0i, y1i = int(round(y0)), int(round(y0 + h))
+ v = (np.arange(y0i, y1i, dtype=np.float32) + 0.5 - y0) / h
+ hh = np.zeros_like(v)
+ for a, b, kind in parts:
+ m = (v >= a) & (v < b)
+ u = (v[m] - a) / (b - a)
+ if kind == 'torus': hh[m] = 0.5 + 0.5 * np.sqrt(np.clip(1 - (2 * u - 1) ** 2, 0, 1))
+ elif kind == 'cove': hh[m] = 0.25 + 0.25 * (1 - np.sqrt(np.clip(1 - (1 - u) ** 2, 0, 1)))
+ elif kind == 'fillet': hh[m] = 0.45
+ else: hh[m] = 0.3
+ gy = np.gradient(hh * h * 0.6)
+ n = np.stack([np.zeros_like(gy), -gy, np.ones_like(gy)], 1); n /= np.linalg.norm(n, axis=1, keepdims=True)
+ shade = 0.62 + 0.5 * np.clip(n @ self.L, 0, 1) + 0.04 * hh
+ grain = 1 + 0.02 * (noise2d(y1i - y0i, W, 40, 2, self._seed()) - 0.5)
+ strip = col[None, None, :] * (shade[:, None, None] * grain[..., None]) * (1 + 0.06 * (0.5 - np.arange(W) / W))[None, :, None]
+ img[y0i:y1i] = np.clip(strip, 0, 1)
+ m = np.zeros((H, 1), np.float32); m[y0i:y1i] = 1 # the shadow only depends on y
+ sh = blur(np.repeat(shift(m, 0, 7), 4, 1), 5)[:, :1] * (1 - m) * 0.42 + blur(np.repeat(shift(m, 0, 2), 4, 1), 1.2)[:, :1] * (1 - m) * 0.25
+ img *= (1 - np.clip(sh, 0, 0.6))[:, :, None]
+ return img
+
+ # ================================================================ frame
+ def frame(self, cx, cy, rx, ry, width=56, pearls=True, twist=0.0, eglomise=True, card='#efe5cd',
+ hook=False, cord='#7a2e2a', spread=34):
+ """an oval gilt frame round an opening of radii (rx, ry); returns a Frame. With hook=True it hangs from
+ the picture rail on a silk cord whose V meets the frame `spread` degrees either side of the top."""
+ f = Frame()
+ f.cx, f.cy, f.rx, f.ry, f.width = cx, cy, rx, ry, width
+ f.x0, f.y0 = int(np.floor(cx - rx - 2)), int(np.floor(cy - ry - 2))
+ f.x1, f.y1 = int(np.ceil(cx + rx + 2)), int(np.ceil(cy + ry + 2))
+ f.w, f.h = f.x1 - f.x0, f.y1 - f.y0
+ f.glazed = False
+ # drop shadows of the whole frame on the wall (computed in a padded box round it)
+ pad = width + 70
+ bx0, by0 = max(0, int(cx - rx - pad)), max(0, int(cy - ry - pad))
+ bx1, by1 = min(self.W, int(cx + rx + pad)), min(self.H, int(cy + ry + pad))
+ yy, xx = np.mgrid[by0:by1, bx0:bx1].astype(np.float32) + 0.5
+ outer = np.clip(width - self._edist(xx - cx, yy - cy, rx, ry) + 0.5, 0, 1)
+ sh = 0.42 * blur(shift(outer, 12, 17), 13) + 0.38 * blur(shift(outer, 2, 3), 2.2)
+ self.base[by0:by1, bx0:bx1] *= (1 - np.clip(sh, 0, 0.75) * (1 - outer))[..., None]
+ del yy, xx, outer, sh
+ if hook and self.rail_y is not None:
+ self._hang(f, cord, spread)
+ self._gild(f, pearls, twist)
+ self._card(f, _c(card), eglomise)
+ self.frames.append(f)
+ return f
+
+ @staticmethod
+ def _edist(x, y, rx, ry):
+ """approximate signed distance (px) outside the ellipse x^2/rx^2 + y^2/ry^2 = 1"""
+ rho = np.sqrt((x / rx) ** 2 + (y / ry) ** 2) + 1e-6
+ g = np.sqrt((x / rx ** 2) ** 2 + (y / ry ** 2) ** 2) / rho + 1e-9
+ return (rho - 1) / g
+
+ @staticmethod
+ def _arclen(theta, a, b):
+ """arc length along the ellipse (a cos t, b sin t) at parameter theta, and the perimeter"""
+ t = np.linspace(-np.pi, np.pi, 4097)
+ sp = np.sqrt((a * np.sin(t)) ** 2 + (b * np.cos(t)) ** 2)
+ s = np.concatenate([[0], np.cumsum((sp[1:] + sp[:-1]) / 2 * np.diff(t))])
+ return np.interp(theta, t, s), s[-1]
+
+ def _gild(self, f, pearls, twist, band=192, margin=24):
+ """render the gilt moulding at 2x in horizontal bands (with overlap for the gradients and blurs),
+ so a big frame never holds more than a band's worth of float arrays"""
+ w, SS = f.width, 2
+ X0c, Y0c = max(0, int(f.cx - f.rx - w - 3)), max(0, int(f.cy - f.ry - w - 3))
+ X1c, Y1c = min(self.W, int(f.cx + f.rx + w + 4)), min(self.H, int(f.cy + f.ry + w + 4))
+ H2, W2 = (Y1c - Y0c) * SS, (X1c - X0c) * SS
+ n_bole = noise2d(H2, W2, 5 * SS, 3, self._seed())
+ n_grime = noise2d(H2, W2, 10 * SS, 2, self._seed())
+ xs = (np.arange(X0c * SS, X1c * SS, dtype=np.float32) + 0.5) / SS - f.cx
+ for r0 in range(0, H2, band):
+ r1 = min(H2, r0 + band)
+ a0, a1 = max(0, r0 - margin), min(H2, r1 + margin)
+ ys = (np.arange(Y0c * SS + a0, Y0c * SS + a1, dtype=np.float32) + 0.5) / SS - f.cy
+ rgb, alpha = self._gilt_band(f, xs, ys, pearls, twist, n_bole[a0:a1], n_grime[a0:a1])
+ k0, k1 = r0 - a0, r1 - a0
+ pre = np.concatenate([rgb[k0:k1] * alpha[k0:k1, :, None], alpha[k0:k1, :, None]], -1)
+ pre = pre.reshape((r1 - r0) // SS, SS, W2 // SS, SS, 4).mean(axis=(1, 3))
+ a1_ = pre[..., 3:4]
+ out = np.clip(pre[..., :3] / np.maximum(a1_, 1e-6), 0, 1)
+ ya, yb = Y0c + r0 // SS, Y0c + r1 // SS
+ reg = self.base[ya:yb, X0c:X1c]
+ self.base[ya:yb, X0c:X1c] = reg * (1 - a1_) + out * a1_
+
+ def _gilt_band(self, f, xs, ys, pearls, twist, n_bole, n_grime):
+ """height field of the moulding profile on one band of 2x pixels, then the gold shading"""
+ w, SS = f.width, 2
+ x, y = np.meshgrid(xs, ys)
+ d = self._edist(x, y, f.rx, f.ry)
+ t = d / w
+ theta = np.arctan2(y / f.ry, x / f.rx)
+ h = np.zeros_like(t)
+ def seg(a, b): return (t >= a) & (t < b)
+ m = t < 0.07; u = (np.clip(t, 0, 0.07) - 0.035) / 0.035
+ h = np.where(m, 0.10 + 0.05 * np.sqrt(np.clip(1 - u ** 2, 0, 1)), h) # sight-edge bead
+ m = seg(0.07, 0.25); u = (t - 0.07) / 0.18
+ h = np.where(m, 0.10 + 0.16 * u ** 2, h) # cove
+ m = seg(0.25, 0.40); h = np.where(m, 0.26, h) # pearl bed
+ m = seg(0.40, 0.84); u = (t - 0.62) / 0.22
+ tor = 0.26 + 0.30 * np.sqrt(np.clip(1 - u ** 2, 0, 1)) # big torus
+ if twist: # ribbon twist
+ s_t, P = self._arclen(theta, f.rx + 0.62 * w, f.ry + 0.62 * w)
+ n_rib = max(12, int(round(P / (0.30 * w))))
+ ph = (s_t / P * n_rib).astype(np.float32) + u * 0.9
+ tor = tor - twist * 0.05 * (0.5 - 0.5 * np.cos(2 * np.pi * ph)) * np.sqrt(np.clip(1 - u ** 2, 0, 1))
+ del s_t, ph
+ h = np.where(m, tor, h); del tor
+ m = seg(0.84, 0.90); h = np.where(m, 0.30, h) # fillet
+ m = seg(0.90, 1.0); u = (t - 0.90) / 0.10
+ h = np.where(m, 0.06 + 0.24 * np.sqrt(np.clip(1 - u ** 2, 0, 1)), h) # outer roll
+ h = (h * w).astype(np.float32)
+ del m, u, t
+ if pearls:
+ db = 0.325 * w; rb = 0.068 * w
+ s_b, P = self._arclen(theta, f.rx + db, f.ry + db)
+ n = max(24, int(round(P / (2.2 * rb))))
+ sp = P / n
+ k = np.round(s_b / sp)
+ a = (s_b - k * sp).astype(np.float32)
+ jit = (1 + 0.05 * np.sin(k * 12.9898) * np.cos(k * 4.1414)).astype(np.float32)
+ del s_b, k
+ c = d - db
+ hb = 0.26 * w + 0.92 * np.sqrt(np.clip((rb * jit) ** 2 - a ** 2 - c ** 2, 0, None))
+ h = np.maximum(h, np.where(np.abs(c) < rb * 1.2, hb, 0)).astype(np.float32)
+ del a, jit, c, hb
+ del theta
+ alpha = ((d > -1.2) & (d < w)).astype(np.float32)
+ del d
+ h = np.where(alpha > 0, h, 0).astype(np.float32)
+ # ---- shading: gold mirrors a room lit by one window at the upper left
+ gy, gx = np.gradient(h)
+ gx *= SS; gy *= SS
+ nz = 1 / np.sqrt(1 + gx * gx + gy * gy); nx, ny = -gx * nz, -gy * nz
+ del gx, gy
+ Lw = self.L
+ rl = 2 * nz * nx * Lw[0] + 2 * nz * ny * Lw[1] + (2 * nz * nz - 1) * Lw[2]
+ room = 0.16 + 0.30 * np.clip(0.5 - 1.2 * nz * ny, 0, 1) + 0.10 * (2 * nz * nz - 1)
+ v = room + 0.50 * np.exp((rl - 1) / 0.35) + 0.85 * np.exp((rl - 1) / 0.03)
+ del nx, ny, nz, rl, room
+ ao = np.clip((blur(h, 3.0 * SS) - h) / (0.07 * w), 0, 1)
+ v = v * (1 - 0.55 * ao)
+ # gold leaf laid in squares: faint tone steps and overlap lines
+ lx, ly = (x + 1000.3) / 26.0, (y + 1000.7) / 26.0
+ cell = np.floor(lx) * 7.13 + np.floor(ly) * 3.71
+ v = v * (1 + 0.035 * np.sin(cell * 12.9898)) * (1 - 0.05 * ((np.abs(lx - np.round(lx)) < 0.025) | (np.abs(ly - np.round(ly)) < 0.025)))
+ del lx, ly, cell, x, y
+ ramp_v = np.array([0.0, 0.30, 0.62, 1.0, 1.5], np.float32)
+ ramp_c = np.array([[0.12, 0.07, 0.025], [0.48, 0.31, 0.10], [0.80, 0.60, 0.26], [0.99, 0.86, 0.55], [1.0, 0.97, 0.84]], np.float32)
+ col = np.stack([np.interp(v, ramp_v, ramp_c[:, i]).astype(np.float32) for i in range(3)], -1)
+ # rubbed through to red bole on the crests; grime in the hollows
+ crest = np.clip((h - blur(h, 2.0 * SS)) / (0.02 * w), 0, 1)
+ bole = (crest * smoothstep(0.66, 0.80, n_bole) * 0.6)[..., None]
+ col = col * (1 - bole) + np.array([0.50, 0.20, 0.10], np.float32) * np.clip(0.4 + 0.8 * v, 0, 1.3)[..., None] * bole
+ grime = (ao * smoothstep(0.3, 0.7, n_grime) * 0.45)[..., None]
+ col = col * (1 - grime) + np.array([0.16, 0.11, 0.06], np.float32) * grime
+ return col, alpha
+
+ def _tube(self, pts, width, col, twist=7.0, shadow=0.32, sh_off=(6, 9), spec=0.35):
+ """a round cord / wire along a polyline: lit cylinder, twist stripes, soft shadow on the wall"""
+ P = _resample(np.asarray(pts, np.float64), 2.0, closed=False)
+ r = width / 2
+ x0, y0 = int(max(0, P[:, 0].min() - width - 30)), int(max(0, P[:, 1].min() - width - 30))
+ x1, y1 = int(min(self.W, P[:, 0].max() + width + 30)), int(min(self.H, P[:, 1].max() + width + 30))
+ yy, xx = np.mgrid[y0:y1, x0:x1].astype(np.float32) + 0.5
+ best = np.full(yy.shape, 1e9, np.float32); along = np.zeros_like(best); acr = np.zeros_like(best)
+ px_ = np.zeros_like(best); py_ = np.zeros_like(best)
+ s0 = 0.0
+ for a, b in zip(P[:-1], P[1:]):
+ ab = b - a; L2 = float(ab @ ab) + 1e-9; L = np.sqrt(L2)
+ tt = np.clip(((xx - a[0]) * ab[0] + (yy - a[1]) * ab[1]) / L2, 0, 1)
+ dx, dy = xx - (a[0] + tt * ab[0]), yy - (a[1] + tt * ab[1])
+ dist = np.sqrt(dx * dx + dy * dy)
+ upd = dist < best
+ sgn = np.sign(ab[0] * dy - ab[1] * dx)
+ best = np.where(upd, dist, best); along = np.where(upd, s0 + tt * L, along); acr = np.where(upd, sgn * dist, acr)
+ px_ = np.where(upd, -ab[1] / L, px_); py_ = np.where(upd, ab[0] / L, py_)
+ s0 += L
+ cov = np.clip(r - best + 0.5, 0, 1)
+ u = np.clip(acr / r, -1, 1)
+ nz = np.sqrt(np.clip(1 - u * u, 0, 1))
+ nx, ny = px_ * u, py_ * u
+ diff = np.clip(nx * self.L[0] + ny * self.L[1] + nz * self.L[2], 0, 1)
+ stripes = np.sin(2 * np.pi * (along + u * r * 1.6) / twist)
+ sh = 0.40 + 0.75 * diff + 0.10 * stripes * nz
+ spc = spec * np.clip(diff, 0, 1) ** 14
+ c = _c(col)
+ rgb = np.clip(c[None, None, :] * sh[..., None] + spc[..., None], 0, 1)
+ reg = self.base[y0:y1, x0:x1]
+ shd = blur(shift(cov, *sh_off), 3.5) * shadow * (1 - cov)
+ reg = reg * (1 - shd[..., None])
+ self.base[y0:y1, x0:x1] = reg * (1 - cov[..., None]) + rgb * cov[..., None]
+
+ def _hang(self, f, cord, spread):
+ top, bot = self.rail_y
+ hx = f.cx
+ # brass hook over the rail and a ring below it
+ self._tube([(hx, top + 3), (hx, bot - 2), (hx + 0.5, bot + 6)], 6, '#b08a3e', twist=1e9, shadow=0.38, sh_off=(3, 4), spec=0.7)
+ t = np.linspace(0, 2 * np.pi, 60)
+ ring = np.stack([hx + 7.5 * np.sin(t), bot + 13 - 7.5 * np.cos(t)], 1)
+ self._tube(ring, 3.2, '#b08a3e', twist=1e9, shadow=0.38, sh_off=(4, 5), spec=0.7)
+ a = np.radians(spread)
+ ow = f.width * 0.55
+ for sgn in (-1, 1):
+ ex = f.cx + sgn * (f.rx + ow) * np.sin(a)
+ ey = f.cy - (f.ry + ow) * np.cos(a)
+ sx, sy = hx + sgn * 3, bot + 20
+ pts = [(sx + (ex - sx) * q, sy + (ey - sy) * q + 3 * np.sin(np.pi * q)) for q in np.linspace(0, 1, 16)]
+ self._tube(pts, 4.6, cord, twist=6.5)
+ # the knot where the two cords leave the ring
+ self._tube([(hx - 3, bot + 19), (hx + 3, bot + 19)], 6.5, cord, twist=4)
+
+ def _card(self, f, col, eglomise):
+ yy, xx = np.mgrid[f.y0:f.y1, f.x0:f.x1].astype(np.float32) + 0.5
+ d = self._edist(xx - f.cx, yy - f.cy, f.rx, f.ry)
+ f.inside = np.clip(-d + 0.5, 0, 1)
+ H, W = d.shape
+ rho = np.clip(1 + d / max(f.rx, f.ry), 0, 1.2)
+ tone = 1 - 0.10 * smoothstep(0.55, 1.0, rho) - 0.02 * (noise2d(H, W, 60, 3, self._seed()) - 0.5)
+ card = col[None, None, :] * tone[..., None]
+ card = card * (1 - np.array([0.0, 0.02, 0.06], np.float32) * smoothstep(0.6, 1.0, rho)[..., None])
+ card *= (1 + 0.012 * (noise2d(H, W, 1.8, 2, self._seed()) - 0.5))[..., None]
+ r = self.rng
+ fox = np.zeros((H, W), np.float32)
+ for _ in range(int(r.integers(6, 12))):
+ cx, cy = r.uniform(0.1, 0.9) * W, r.uniform(0.1, 0.9) * H
+ rr = r.uniform(0.8, 3.2)
+ fox += np.exp(-((xx - f.x0 - cx) ** 2 + (yy - f.y0 - cy) ** 2) / (2 * rr * rr)) * r.uniform(0.25, 0.6)
+ for _ in range(3):
+ cx, cy = r.uniform(0.15, 0.85) * W, r.uniform(0.15, 0.85) * H
+ rr = r.uniform(8, 20)
+ fox += np.exp(-((xx - f.x0 - cx) ** 2 + (yy - f.y0 - cy) ** 2) / (2 * rr * rr)) * 0.06
+ fox = np.clip(fox, 0, 0.7)
+ card = card * (1 - fox[..., None]) + np.array([0.62, 0.42, 0.25], np.float32) * col * fox[..., None]
+ f.card = card.astype(np.float32)
+ f.paper = np.zeros((H, W), np.float32) # where black paper is (for bronze)
+ # verre eglomise: black band with a gold fillet, painted on the back of the glass
+ f.eg_a = np.zeros((H, W), np.float32); f.eg_rgb = np.zeros((H, W, 3), np.float32)
+ if eglomise:
+ bw = max(10, 0.065 * min(f.rx, f.ry))
+ band = np.clip(d + bw + 0.5, 0, 1)
+ fil = np.clip(1.1 - np.abs(d + bw - 3.6), 0, 1)
+ sheen = 0.03 + 0.03 * np.clip(-(xx - f.cx) / f.rx - (yy - f.cy) / f.ry, 0, 1)
+ gold = np.array([0.80, 0.62, 0.30], np.float32) * (0.85 + 0.25 * noise2d(H, W, 12, 2, self._seed()))[..., None]
+ f.eg_rgb = np.ones((H, W, 3), np.float32) * sheen[..., None] * np.array([1.0, 0.95, 0.9], np.float32)
+ f.eg_rgb = f.eg_rgb * (1 - fil[..., None]) + gold * fil[..., None]
+ f.eg_a = np.maximum(band * 0.97, fil)
+ # shadow of the frame's rebate on the card (light from the upper left)
+ out = 1 - f.inside
+ f.lip = 0.38 * blur(shift(out, 5, 7), 4.5) * f.inside + 0.25 * blur(shift(out, 1, 2), 1.2) * f.inside
+ # convex glass: soft sheen and a crisp window reflection (shown after glaze())
+ u, v = (xx - f.cx) / f.rx, (yy - f.cy) / f.ry
+ rr = np.sqrt(u * u + v * v)
+ ang = np.degrees(np.arctan2(v, u))
+ soft = 0.10 * np.exp(-((u + 0.38) ** 2 + (v + 0.45) ** 2) / (2 * 0.32 ** 2))
+ pane = ((rr > 0.70) & (rr < 0.84) & (((ang > -158) & (ang < -134)) | ((ang > -130) & (ang < -112)))).astype(np.float32)
+ pane = blur(pane, 1.0) * (0.75 + 0.25 * np.clip((0.84 - rr) / 0.14, 0, 1))
+ streak = 0.05 * np.exp(-((u * 0.7 + v * 0.7 + 0.15) ** 2) / (2 * 0.05 ** 2)) * np.clip(1 - rr, 0, 1)
+ f.glare = np.clip(1.2 * soft + 0.16 * blur(pane, 1.2) + streak, 0, 0.5)
+
+ # ================================================================ paper, gold, ink
+ def sheet(self, f, at, scale=1.0, flip=False, ss=4, warp=None):
+ """a fresh sheet of black paper over frame f's card. Design unit (0, 0) lands on canvas pixel `at`.
+ warp: optional function (N x 2 design points -> N x 2) applied to everything cut or painted on this sheet,
+ to re-proportion a drawing (a bigger head, a shorter body) without retyping its coordinates."""
+ return Sheet(self, f, at, scale, flip, ss, warp=warp)
+
+ def paste(self, sh, black='#0f0d0c'):
+ """glue a cut sheet onto its card: hairline shadow under the glued body, a longer one under loose snips,
+ black with a faint fibre and sheen, a lit hairline on edges facing the light"""
+ f = sh.f
+ b, l = sh.coverage()
+ P = np.clip(np.maximum(b, l), 0, 1)
+ H, W = P.shape
+ card = f.card
+ sh_b = 0.30 * blur(shift(b, 1, 1), 0.8) + 0.06 * blur(shift(b, 3, 4), 3)
+ sh_l = 0.42 * blur(shift(l, 2, 3), 1.3)
+ card = card * (1 - np.clip(sh_b + sh_l, 0, 0.7) * (1 - P))[..., None]
+ yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)
+ fib = noise2d(H, W, 3.0, 2, self._seed()) - 0.5
+ sheen = 0.6 + 0.4 * np.clip(1 - ((xx / W - 0.3) ** 2 + (yy / H - 0.25) ** 2) * 2, 0, 1)
+ blk = _c(black)[None, None, :] * (1 + 0.18 * fib[..., None]) * (0.85 + 0.3 * sheen[..., None])
+ gy, gx = np.gradient(blur(P, 0.6))
+ lit = np.clip(-(gx * self.L[0] + gy * self.L[1]) * 1.6, 0, 1) * 0.16
+ blk = blk + lit[..., None]
+ f.card = card * (1 - P[..., None]) + blk * P[..., None]
+ f.paper = np.maximum(f.paper, P)
+ sh.mask = P
+
+ def bronze(self, sh, strokes, width=2.0, tip=0.0, bright=1.0, colour='#c9a058'):
+ """thin shell gold painted over the black paper of sheet `sh`. strokes: list of polylines in design units
+ (spline them first); each tapers from `width` (design units) to `tip` and gets its own brightness."""
+ f = sh.f
+ SS = sh.ss
+ cov = Image.new('L', (f.w * SS, f.h * SS), 0); val = Image.new('L', (f.w * SS, f.h * SS), 0)
+ dc, dv = ImageDraw.Draw(cov), ImageDraw.Draw(val)
+ r = self.rng
+ for pts in strokes:
+ P = sh._ss(pts)
+ if len(P) < 2: continue
+ C = _resample(P, max(1.0, SS * 0.75), closed=False)
+ n = len(C)
+ u = np.linspace(0, 1, n)
+ wmax = width * sh.k * SS * r.uniform(0.8, 1.15)
+ w = wmax * np.clip(np.minimum(u / 0.18, 1), 0.25, 1) * (1 - (1 - tip / max(width, 1e-6)) * smoothstep(0.55, 1.0, u))
+ w = np.maximum(w, 0.8)
+ poly = _strip(C, w, None)
+ b = int(np.clip(255 * 0.62 * bright * r.uniform(0.7, 1.15), 0, 255))
+ dc.polygon([tuple(p) for p in poly], fill=255); dv.polygon([tuple(p) for p in poly], fill=b)
+ a = np.asarray(cov.reduce(SS), np.float32) / 255
+ vv = np.asarray(val.reduce(SS), np.float32) / 255 / np.maximum(a, 1e-3) / 0.62
+ H, W = a.shape
+ grain = noise2d(H, W, 1.5, 2, self._seed())
+ gold = _c(colour)[None, None, :] * (vv * (0.85 + 0.3 * grain))[..., None]
+ gold = gold + np.array([0.10, 0.08, 0.04], np.float32) * smoothstep(0.75, 1.0, grain)[..., None] * vv[..., None]
+ a = a * f.paper * 0.95
+ f.card = f.card * (1 - a[..., None]) + np.clip(gold, 0, 1) * a[..., None]
+
+ def caption(self, f, text, x, y, size, style='roundhand', colour='#2f1f14', alpha=0.92, spacing=0.0):
+ """handwritten caption in iron-gall ink on frame f's card, centred on (x, y) baseline"""
+ SS = 2
+ font = sil_font(style, size * SS)
+ m = text_mask(f.h * SS, f.w * SS, text, font, ((x - f.x0) * SS, (y - f.y0) * SS), anchor='ms', spacing=spacing * SS)
+ m = m.reshape(f.h, SS, f.w, SS).mean(axis=(1, 3))
+ self._ink(f, m, colour, alpha)
+
+ def pen(self, f, pts, width=1.2, colour='#3a2618', alpha=0.8):
+ """a pen line in ink on the card (ground line, flourish); canvas pixels"""
+ SS = 4
+ im = Image.new('L', (f.w * SS, f.h * SS), 0)
+ P = np.asarray(pts, np.float64)
+ C = _resample(np.stack([(P[:, 0] - f.x0) * SS, (P[:, 1] - f.y0) * SS], 1), SS * 0.75, closed=False)
+ u = np.linspace(0, 1, len(C))
+ w = width * SS * (0.35 + 0.65 * np.sin(np.pi * u) ** 0.6)
+ ImageDraw.Draw(im).polygon([tuple(p) for p in _strip(C, w, None)], fill=255)
+ self._ink(f, np.asarray(im.reduce(SS), np.float32) / 255, colour, alpha)
+
+ def _ink(self, f, m, colour, alpha):
+ H, W = m.shape
+ dens = 0.8 + 0.2 * noise2d(H, W, 6, 2, self._seed())
+ a = np.clip(m * dens * alpha, 0, 1) * (1 - f.paper)
+ f.card = f.card * (1 - a[..., None]) + _c(colour)[None, None, :] * f.card * 0.25 * a[..., None] + _c(colour)[None, None, :] * 0.75 * a[..., None]
+
+ def glaze(self, frames=None):
+ """put the glass in: soft sheen and window reflection on the convex glass"""
+ for f in (frames or self.frames): f.glazed = True
+
+ # ================================================================ output
+ def composite(self):
+ img = self.base.copy()
+ for f in self.frames:
+ loc = f.card * (1 - f.eg_a[..., None]) + f.eg_rgb * f.eg_a[..., None]
+ loc = loc * (1 - f.lip[..., None])
+ if f.glazed:
+ loc = 1 - (1 - loc) * (1 - f.glare[..., None] * np.array([0.96, 0.98, 1.0], np.float32))
+ a = f.inside[..., None]
+ ya, yb, xa, xb = max(0, f.y0), min(self.H, f.y1), max(0, f.x0), min(self.W, f.x1)
+ sub = (slice(ya - f.y0, yb - f.y0), slice(xa - f.x0, xb - f.x0))
+ img[ya:yb, xa:xb] = img[ya:yb, xa:xb] * (1 - a[sub]) + loc[sub] * a[sub]
+ 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):
+ img = self.composite()
+ if path.lower().endswith(('.jpg', '.jpeg')):
+ img.save(path, quality=88, 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
diff --git a/lib/stainedglass.py b/lib/stainedglass.py
new file mode 100644
index 0000000..4360534
--- /dev/null
+++ b/lib/stainedglass.py
@@ -0,0 +1,1046 @@
+"""stainedglass — a Gothic stained-glass window seen from inside a stone church, lit by daylight from behind
+(numpy + Pillow only).
+
+How a real window is made, and how this module copies it step by step:
+ cartoon the glazier draws the design full size and divides it into pieces. A piece is one colour of glass,
+ and glass cannot be cut into thin strips or deep inward curves, so big areas (sky, ground, a crown of
+ leaves) are split into many irregular pieces. `glass(mask, colour, cell=...)` registers one area of
+ colour; with `cell` it is cut into a jittered Voronoi mosaic (optionally in polar coordinates around a
+ point, so the pieces radiate from a sun). Later areas are cut out of earlier ones, so work back to
+ front like a painter. Slivers too small to cut are merged into a neighbour of the same colour.
+ `cut(pts)` adds an extra cut line (a lead) through a piece, e.g. to split a trunk.
+ glass pot-metal glass is coloured all the way through, and every piece comes from a different part of a
+ hand-blown sheet: its own shade, its own thickness (thicker = darker and more saturated, because the
+ transmission is colour ** thickness), parallel reams / streaks running one way per piece, and seeds
+ (small air bubbles drawn out along the streaks). Flashed ruby carries its colour in a thin layer on
+ clear glass, so it streaks strongly from pink to deep red.
+ paint grisaille is a brown-black vitreous paint fired onto the glass. Paint is never coloured: all the colour
+ is in the glass. `trace()` lays opaque brush lines (features, veins, feathers, twigs too thin to cut);
+ `matt()` / `shade()` lay a semi-opaque stippled wash that models volume; `scratch()` lifts paint off
+ again with a stick so highlights and patterns shine through; `diaper()` is a background pattern
+ scratched out of (or painted on) a light matt; `stain()` is silver stain, which turns white glass lemon
+ to amber and blue glass green; `inscribe()` paints or scratches lettering.
+ lead H-section lead came runs along every boundary between pieces, so the lead falls exactly on the Voronoi
+ bisectors and on the colour edges; a wider came frames the rim of each light; the joints are soldered
+ (slightly wider, lighter tin blobs). `crack()` adds a broken piece mended with a thin strap lead.
+ iron `saddle_bar()` crosses a light on the inside, tied to the leads with copper wire.
+ stone `wall()` is coursed ashlar; `lancet()` cuts a pointed-arch opening with a splayed reveal (radial
+ voussoir joints round the arch), a sloping sill and an optional hood mould; `string_course()` is a
+ moulded band below the sills.
+ light seen from inside, the glass is the light source. `daylight()` turns on the room: the wall stays dim
+ and takes a wash of coloured spill light, the reveals glow near the glass, the sloping sill catches a
+ soft upside-down projection of the lowest glass, and bright glass halates over the dark leads (blue
+ spreads most). `weather()` adds grime along the leads and corrosion pits on some pieces.
+
+ from stainedglass import StainedGlass
+ g = StainedGlass(1920, 1080, seed=1)
+ g.wall()
+ L = g.lancet(960, 80, 940, 360) # a pointed-arch light; L.pt(lx, ly) = local -> image
+ g.glass(L.inner(0), '#1f4fa8', cell=46) # blue sky cut into a Voronoi mosaic
+ g.glass(g.circle(*L.pt(0, 300), 60), '#f2c230') # a yellow sun, one piece
+ g.trace(L.P([(-40, 500), (0, 470), (40, 500)]), 4) # a grisaille line
+ g.lead(); g.saddle_bar(L, 520); g.daylight()
+ g.save('window.jpg')
+"""
+import glob
+import os
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+from core import blur, fbm1d, spline, noise2d, smoothstep, polygon_mask, shift, load_font, text_mask
+
+NANG = 8 # streak directions available to the glass pieces
+PAINT_T = np.array([0.030, 0.022, 0.016], np.float32) # transmission of fully opaque fired grisaille (brown-black)
+STAIN = '#f0b43a' # silver stain at full strength on white glass
+
+# medieval pot-metal glass, as it looks with daylight behind it
+RUBY, BLUE, DEEP_BLUE, SKY = '#b3182c', '#2456b0', '#173c8f', '#5d8fd0'
+GREEN, LEAF, SPRING, OLIVE = '#2f8a3c', '#4fa83f', '#9ccd52', '#7c8a2a'
+GOLD, AMBER, ORANGE, MURREY = '#f2c230', '#e0922a', '#d0601e', '#7a2c5c'
+WHITE, PALE, BROWN, FLESH = '#eeeadb', '#d7e2ea', '#6e4526', '#e9c9a8'
+
+_FONT_FILES = {
+ 'lombardic': ['/System/Library/Fonts/Supplemental/Luminari.ttf', '/System/Library/Fonts/Supplemental/Herculanum.ttf',
+ '/usr/share/fonts/**/*Uncial*.[ot]tf', '/usr/share/fonts/**/*Unifraktur*.[ot]tf',
+ 'C:/Windows/Fonts/OLDENGL.TTF'],
+ 'roman': ['/System/Library/Fonts/Supplemental/Trajan*.[ot]tf', '/System/Library/Fonts/Optima.ttc',
+ '/System/Library/Fonts/Supplemental/Baskerville.ttc', '/usr/share/fonts/**/DejaVuSerif.ttf',
+ 'C:/Windows/Fonts/georgia.ttf'],
+}
+
+
+def glass_font(style, size):
+ """PIL font: 'lombardic' (Luminari / Herculanum / an uncial) or 'roman'; $INKPAINT_FONT_LOMBARDIC overrides;
+ falls back to core.load_font('serif')"""
+ env = os.environ.get('INKPAINT_FONT_' + style.upper())
+ cands = ([env] if env else []) + _FONT_FILES.get(style, [])
+ for pat in cands:
+ for f in glob.glob(pat, recursive=True):
+ try:
+ return ImageFont.truetype(f, int(size))
+ except OSError:
+ pass
+ return load_font('serif', size)
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+def lin(c):
+ """'#rrggbb' or sRGB triple -> linear light"""
+ c = hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)
+ return np.clip(c, 0, 1) ** 2.2
+
+
+def _hash(i, j, seed):
+ h = (i.astype(np.int64) * 73856093) ^ (j.astype(np.int64) * 19349663) ^ np.int64(seed * 83492791)
+ h &= 0xFFFFFFFF
+ h = ((h ^ (h >> 16)) * 0x45d9f3b) & 0xFFFFFFFF
+ h = ((h ^ (h >> 16)) * 0x45d9f3b) & 0xFFFFFFFF
+ return h ^ (h >> 16)
+
+
+class Light:
+ """one pointed-arch light (glass opening). Local coordinates: origin at the apex, x right, y down.
+ sdf(): signed distance inside the glass edge (px, positive inside); inner(b) / band(b0, b1) are AA masks."""
+
+ def __init__(self, g, cx, top, bottom, width, arch, splay, sill):
+ self.g, self.cx, self.top, self.bottom = g, float(cx), float(top), float(bottom)
+ self.a = width / 2.0
+ self.R = max(arch * width, self.a) # arch=1: equilateral (each arc centred on the far springing)
+ self.h = float(np.sqrt(self.R ** 2 - (self.R - self.a) ** 2))
+ self.ys = self.top + self.h # springing line
+ self.splay, self.sill = splay, sill
+ self.width, self.height = width, bottom - top
+ self._sdf = None
+
+ def pt(self, lx, ly):
+ return (self.cx + lx, self.top + ly)
+
+ def P(self, pts):
+ p = np.asarray(pts, np.float32).copy()
+ p[:, 0] += self.cx; p[:, 1] += self.top
+ return p
+
+ def sdf_at(self, X, Y):
+ dx = np.abs(X - self.cx)
+ rect = np.minimum(self.a - dx, self.bottom - Y)
+ cl = self.cx - self.a + self.R # centre of the arc that bounds the left side
+ cr = self.cx + self.a - self.R
+ arch = np.minimum(self.R - np.hypot(X - cl, Y - self.ys), self.R - np.hypot(X - cr, Y - self.ys))
+ arch = np.minimum(arch, self.bottom - Y)
+ return np.where(Y >= self.ys, rect, arch).astype(np.float32)
+
+ def sdf(self):
+ if self._sdf is None:
+ self._sdf = self.sdf_at(self.g.XX, self.g.YY)
+ return self._sdf
+
+ def inner(self, b=0.0):
+ """mask of the glass shrunk by b px (b=0: the whole light)"""
+ return np.clip(self.sdf() - b + 0.5, 0, 1)
+
+ def band(self, b0, b1):
+ """mask of the strip b0 < sdf < b1 (a border band running round the light)"""
+ s = self.sdf()
+ return np.clip(s - b0 + 0.5, 0, 1) * np.clip(b1 - s + 0.5, 0, 1)
+
+ def outline(self, b=0.0, step=20.0):
+ """points (N x 2, image coords) round the outline shrunk by b, every ~step px: bottom, right side,
+ right arc, left arc, left side"""
+ a, R = self.a - b, self.R - b
+ yb, ys, cx = self.bottom - b, self.ys, self.cx
+ cr, cl = self.cx + self.a - self.R, self.cx - self.a + self.R
+ segs = []
+ n = max(2, int(2 * a / step)); segs.append(np.stack([np.linspace(cx - a, cx + a, n), np.full(n, yb)], 1))
+ n = max(2, int((yb - ys) / step)); segs.append(np.stack([np.full(n, cx + a), np.linspace(yb, ys, n)], 1))
+ th1 = -np.arccos(np.clip((cx - cr) / R, -1, 1))
+ n = max(2, int(abs(th1) * R / step)); t = np.linspace(0, th1, n)
+ segs.append(np.stack([cr + R * np.cos(t), ys + R * np.sin(t)], 1))
+ th2 = -np.pi + np.arccos(np.clip((cl - cx) / R, -1, 1))
+ t = np.linspace(th2, -np.pi, n)
+ segs.append(np.stack([cl + R * np.cos(t), ys + R * np.sin(t)], 1))
+ n = max(2, int((yb - ys) / step)); segs.append(np.stack([np.full(n, cx - a), np.linspace(ys, yb, n)], 1))
+ P = np.vstack([sg[1:] if i else sg for i, sg in enumerate(segs)])
+ keep = np.r_[True, np.hypot(*np.diff(P, axis=0).T) > 1e-3]
+ return P[keep].astype(np.float32)
+
+ def half(self, ly, b=0.0):
+ """half-width of the outline shrunk by b at local y"""
+ y = self.top + ly
+ if y >= self.ys: return self.a - b
+ dy = self.ys - y
+ R = self.R - b
+ return max(0.0, float(np.sqrt(max(R * R - dy * dy, 0))) - (self.R - self.a))
+
+
+class StainedGlass:
+ def __init__(self, W=1920, H=1080, seed=0, record=True, ambient=0.05):
+ self.W, self.H = W, H
+ self.rng = np.random.default_rng(seed)
+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)
+ self.record = record
+ self.ambient = ambient
+ z = lambda: np.zeros((H, W), np.float32)
+ # stone
+ self.alb = np.ones((H, W, 3), np.float32) * lin('#8a8073')
+ self.relief = np.ones((H, W), np.float32)
+ self.kind = np.zeros((H, W), np.uint8) # 0 wall face, 1 reveal, 2 sill, 3 moulding
+ self.reveal = z()
+ self.stone_tex = z()
+ self.win = z()
+ self.lights = []
+ # glass
+ self.label = np.full((H, W), -1, np.int32)
+ self.p_col, self.p_thick, self.p_ang, self.p_streak, self.p_region, self.p_off = [], [], [], [], [], []
+ self.regions = []
+ self.cuts = np.zeros((H, W), bool)
+ self.mends = np.zeros((H, W), bool)
+ self.crack_a = z()
+ # paint
+ self.trace_a, self.matt_a, self.scratch_a, self.stain_a = z(), z(), z(), z()
+ self.grain = noise2d(H, W, 1.4, 2, self._seed()) - 0.5
+ # seeds for fields made lazily at render time: fixed now, so stage snapshots never shift the random sequence
+ self._lazy = [int(v) for v in self.rng.integers(1 << 30, size=6)]
+ # lead, iron, light
+ self.lead_a = None; self.lead_rgb = None; self.lead_d = None
+ self.bar_a = z(); self.bar_rgb = np.zeros((H, W, 3), np.float32)
+ self.weather_T = None
+ self.lit = None
+ self.stages = []
+ self._T = None
+ self._sky = None
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ # ================================================================== masks (full frame, anti-aliased)
+ def _local(self, cx, cy, r):
+ b = (slice(max(0, int(cy - r - 2)), min(self.H, int(cy + r + 3))), slice(max(0, int(cx - r - 2)), min(self.W, int(cx + r + 3))))
+ return b, self.XX[b], self.YY[b]
+
+ def circle(self, cx, cy, r):
+ out = np.zeros((self.H, self.W), np.float32)
+ b, X, Y = self._local(cx, cy, r)
+ out[b] = np.clip(r - np.hypot(X - cx, Y - cy) + 0.5, 0, 1)
+ return out
+
+ def ellipse(self, cx, cy, rx, ry, rot=0.0):
+ out = np.zeros((self.H, self.W), np.float32)
+ b, X, Y = self._local(cx, cy, max(rx, ry))
+ c, s = np.cos(rot), np.sin(rot)
+ u = (X - cx) * c + (Y - cy) * s
+ v = -(X - cx) * s + (Y - cy) * c
+ d = np.hypot(u / rx, v / ry)
+ out[b] = np.clip((1 - d) * min(rx, ry) + 0.5, 0, 1)
+ return out
+
+ def poly(self, pts):
+ """filled polygon -> full-frame AA mask (rasterised only inside its bounding box)"""
+ P = np.asarray(pts, np.float32)
+ x0, y0 = max(0, int(P[:, 0].min()) - 2), max(0, int(P[:, 1].min()) - 2)
+ x1, y1 = min(self.W, int(P[:, 0].max()) + 3), min(self.H, int(P[:, 1].max()) + 3)
+ out = np.zeros((self.H, self.W), np.float32)
+ if x1 > x0 and y1 > y0:
+ out[y0:y1, x0:x1] = polygon_mask(y1 - y0, x1 - x0, P - [x0, y0], ss=2)
+ return out
+
+ def blob(self, cx, cy, rx, ry, rough=0.1, seed=None, rot=0.0):
+ from core import blob_pts
+ return self.poly(blob_pts(cx, cy, rx, ry, rough, 90, self._seed() if seed is None else seed, rot))
+
+ def branch(self, pts, w0, w1, smooth=True):
+ """tapered thick polyline mask (boughs, stems): width w0 at the start to w1 at the end"""
+ P = spline(pts, 10) if smooth and len(pts) > 2 else np.asarray(pts, np.float32)
+ w = np.linspace(w0, w1, len(P))
+ y0, x0, m = self._stroke_mask(P, w)
+ out = np.zeros((self.H, self.W), np.float32)
+ self._paste_max(out, y0, x0, m)
+ return out
+
+ # ------------------------------------------------------------------ variable-width polyline rasteriser
+ def _stroke_mask(self, P, widths, ss=3):
+ P = np.asarray(P, np.float32); widths = np.asarray(widths, np.float32)
+ pad = float(widths.max()) / 2 + 3
+ x0, y0 = int(np.floor(P[:, 0].min() - pad)), int(np.floor(P[:, 1].min() - pad))
+ x1, y1 = int(np.ceil(P[:, 0].max() + pad)), int(np.ceil(P[:, 1].max() + pad))
+ w, h = max(1, x1 - x0), max(1, y1 - y0)
+ im = Image.new('L', (w * ss, h * ss), 0)
+ d = ImageDraw.Draw(im)
+ Q = (P - [x0, y0]) * ss
+ for i in range(len(Q)):
+ r = widths[i] * ss / 2
+ d.ellipse([Q[i, 0] - r, Q[i, 1] - r, Q[i, 0] + r, Q[i, 1] + r], fill=255)
+ if i + 1 < len(Q):
+ p, q = Q[i], Q[i + 1]
+ t = q - p; n = np.hypot(*t)
+ if n < 1e-6: continue
+ nx, ny = -t[1] / n, t[0] / n
+ r2 = widths[i + 1] * ss / 2
+ d.polygon([(p[0] + nx * r, p[1] + ny * r), (q[0] + nx * r2, q[1] + ny * r2),
+ (q[0] - nx * r2, q[1] - ny * r2), (p[0] - nx * r, p[1] - ny * r)], fill=255)
+ m = np.asarray(im.resize((w, h), Image.BOX), np.float32) / 255
+ return y0, x0, m
+
+ def _paste_max(self, dst, y0, x0, m, scale=1.0):
+ h, w = m.shape
+ ya, xa = max(0, y0), max(0, x0)
+ yb, xb = min(self.H, y0 + h), min(self.W, x0 + w)
+ if ya >= yb or xa >= xb: return
+ sub = m[ya - y0:yb - y0, xa - x0:xb - x0] * scale
+ np.maximum(dst[ya:yb, xa:xb], sub, out=dst[ya:yb, xa:xb])
+
+ def _crop(self, a, y0, x0, h, w):
+ out = np.zeros((h, w), a.dtype)
+ ya, xa, yb, xb = max(0, y0), max(0, x0), min(self.H, y0 + h), min(self.W, x0 + w)
+ if ya < yb and xa < xb:
+ out[ya - y0:yb - y0, xa - x0:xb - x0] = a[ya:yb, xa:xb]
+ return out
+
+ @staticmethod
+ def _taper(n, taper):
+ t = np.linspace(0, 1, n)
+ a, b = max(taper[0], 1e-3), max(taper[1], 1e-3)
+ return np.clip(np.minimum(t / a, (1 - t) / b), 0, 1) ** 0.6 * 0.75 + 0.25
+
+ # ================================================================== stone
+ def wall(self, colour='#8f8576', mortar='#6f675d', course=(60, 82), block=(110, 240)):
+ """coursed ashlar: blocks of slightly different stone, tooled faces, worn arrises, recessed mortar joints"""
+ H, W = self.H, self.W
+ r = self.rng
+ base, mcol = lin(colour), lin(mortar)
+ mott = noise2d(H, W, 60, 4, self._seed())
+ fine = noise2d(H, W, 3, 2, self._seed())
+ self.stone_tex = (0.65 * mott + 0.35 * fine).astype(np.float32)
+ alb = np.empty((H, W, 3), np.float32)
+ dmin = np.full((H, W), 99, np.float32)
+ tool = np.zeros((H, W), np.float32)
+ top_edge = np.zeros((H, W), np.float32)
+ y = -int(r.integers(10, 40))
+ while y < H:
+ ch = int(r.integers(*course))
+ ya, yb = max(0, y), min(H, y + ch)
+ if yb > ya:
+ xs = [-int(r.integers(0, block[1]))]
+ while xs[-1] < W:
+ xs.append(xs[-1] + int(r.integers(*block)))
+ xs = np.array(xs, np.float32)
+ X = self.XX[ya:yb]; Y = self.YY[ya:yb]
+ k = np.clip(np.searchsorted(xs, X[0], side='right') - 1, 0, len(xs) - 2)
+ left, right = xs[k], xs[k + 1]
+ dx = np.minimum(X - left[None, :], right[None, :] - X)
+ dy = np.minimum(Y - y, y + ch - Y)
+ dmin[ya:yb] = np.minimum(dx, dy)
+ top_edge[ya:yb] = (Y - y) / ch
+ tint = np.stack([np.exp(r.normal(0, 0.10, len(xs))) * np.array([1 + r.normal(0, 0.03), 1, 1 + r.normal(0, 0.04)])[c]
+ for c in range(3)], 1).astype(np.float32)
+ alb[ya:yb] = base * tint[k][None, :, :]
+ ang = r.uniform(0.5, 1.1, len(xs))[k] # every block tooled at its own angle
+ ph = (X * np.cos(ang)[None, :] + Y * np.sin(ang)[None, :])
+ tool[ya:yb] = np.sin(ph * 2 * np.pi / 5.5 + 3 * mott[ya:yb]) * 0.5 + 0.5
+ y += ch
+ wear = (noise2d(H, W, 9, 3, self._seed()) - 0.5) * 3.5 # chipped arrises
+ joint = smoothstep(2.6, 1.0, dmin + wear * 0.5)
+ arris = smoothstep(7, 1.5, dmin + wear)
+ self.alb = alb * (0.80 + 0.32 * self.stone_tex)[..., None]
+ self.alb = self.alb * (1 - joint[..., None]) + mcol * (0.8 + 0.4 * fine)[..., None] * joint[..., None]
+ pits = (noise2d(H, W, 2.2, 1, self._seed()) > 0.84).astype(np.float32) * (1 - joint)
+ self.relief = (1 - 0.05 * tool * (1 - joint) - 0.18 * pits - 0.22 * joint
+ - 0.10 * arris * (top_edge > 0.5) + 0.06 * arris * (top_edge <= 0.5)).astype(np.float32)
+ self.kind[:] = 0
+
+ def lancet(self, cx, top, bottom, width, arch=1.0, splay=30, sill=44, hood=16, voussoir=8.5):
+ """cut a pointed-arch light into the wall: glass opening, splayed reveal (radial voussoir joints round the
+ arch, coursed joints down the sides), a sloping sill below and a roll hood mould over the arch.
+ arch=1 is equilateral; >1 is a sharper lancet. Returns a Light."""
+ L = Light(self, cx, top, bottom, width, arch, splay, sill)
+ self.lights.append(L)
+ m_ = splay + (hood or 0) + 6
+ y0, y1 = max(0, int(top - m_ * 1.3 - 6)), min(self.H, int(bottom + sill + 3))
+ x0, x1 = max(0, int(cx - L.a - m_)), min(self.W, int(cx + L.a + m_ + 1))
+ sl = (slice(y0, y1), slice(x0, x1)) # everything happens inside this box
+ X, Y = self.XX[sl], self.YY[sl]
+ s = L.sdf()[sl]
+ win, rvl, kind, alb, relief = self.win[sl], self.reveal[sl], self.kind[sl], self.alb[sl], self.relief[sl]
+ tex = self.stone_tex[sl]
+ np.maximum(win, np.clip(s + 0.5, 0, 1), out=win)
+ dx = np.abs(X - L.cx)
+ below = Y > L.bottom
+ depth = np.clip((Y - L.bottom) / sill, 0, 1)
+ side_low = below & (Y <= L.bottom + sill) & (dx <= L.a + splay) & (dx > L.a + splay * depth)
+ sill_m = below & (Y <= L.bottom + sill) & (dx <= L.a + splay * depth)
+ rev = (s < 0) & (s >= -splay) & ~below
+ reveal = rev | side_low
+ # reveal position 0 (wall edge) .. 1 (glass edge)
+ rvl[rev] = (1 + s / splay)[rev]
+ rvl[side_low] = (1 - (dx - L.a) / splay)[side_low]
+ rvl[sill_m] = (1 - depth)[sill_m]
+ kind[reveal] = 1
+ kind[sill_m] = 2
+ # joints on the reveal: radial voussoirs round the arch, coursed below the springing
+ cl, cr = L.cx - L.a + L.R, L.cx + L.a - L.R
+ Cx = np.where(X < L.cx, cl, cr)
+ phi = np.arctan2(Y - L.ys, X - Cx)
+ rr = np.hypot(X - Cx, Y - L.ys)
+ step = np.deg2rad(voussoir)
+ jd_arch = np.abs((phi / step) - np.round(phi / step)) * step * rr
+ jd_arch = np.minimum(jd_arch, np.abs(X - L.cx)) # joint at the apex
+ course = 56.0
+ jd_side = np.abs(((Y - L.ys) / course) - np.round((Y - L.ys) / course)) * course
+ jd = np.where(Y < L.ys, jd_arch, jd_side)
+ jd = np.where(sill_m, np.abs(((X - L.cx) / 70) - np.round((X - L.cx) / 70)) * 70 / (0.6 + depth), jd)
+ joint = smoothstep(1.8, 0.6, jd)
+ stone = lin('#9a9081') * (0.80 + 0.34 * tex)[..., None]
+ surf = stone * (1 - joint[..., None]) + lin('#746b60') * joint[..., None]
+ m2 = reveal | sill_m
+ alb[m2] = surf[m2]
+ edge = smoothstep(3.0, 0.0, np.abs(s + splay)) * rev # arris where reveal meets the wall face
+ rel = 1 - 0.2 * joint + 0.18 * edge
+ rel = np.where(sill_m, rel * (1 - 0.15 * smoothstep(0.85, 1.0, depth)), rel)
+ relief[m2] = rel[m2]
+ # hood mould: a roll moulding following the arch, ending in square label stops
+ if hood:
+ t = (-(s + splay)) / hood # 0 inner .. 1 outer
+ stop = (Y > L.ys + 18) & (Y < L.ys + 18 + hood * 1.2)
+ hm = (t >= 0) & (t <= 1) & (Y < L.ys + 18)
+ st = stop & (dx >= L.a + splay - 2) & (dx <= L.a + splay + hood + 4)
+ prof = np.clip(np.sin(np.clip(t, 0, 1) * np.pi), 0, 1) ** 0.7 # a roll: lit crown, darker flanks
+ shade = 0.55 + 0.6 * prof - 0.18 * np.clip(t, 0, 1)
+ hs = hm | st
+ alb[hs] = (lin('#a49a8a') * (0.82 + 0.3 * tex)[..., None])[hs]
+ relief[hm] = shade[hm]
+ relief[st] = (0.95 - 0.25 * ((Y - L.ys - 18) / (hood * 1.2)))[st]
+ kind[hs] = 3
+ self._T = None
+ return L
+
+ def string_course(self, y, h=24, colour='#a1978a'):
+ """a moulded horizontal band across the wall: lit top, shadowed undercut"""
+ m = (self.YY >= y) & (self.YY < y + h)
+ t = (self.YY - y) / h
+ shade = np.where(t < 0.35, 1.15 - 0.2 * t, np.where(t < 0.8, 0.9 - 0.3 * (t - 0.35), 0.45))
+ self.alb = np.where(m[..., None], lin(colour) * (0.82 + 0.3 * self.stone_tex)[..., None], self.alb)
+ self.relief = np.where(m, shade, self.relief).astype(np.float32)
+ self.relief[int(y + h):int(y + h + 6)] *= np.linspace(0.6, 1, 6)[:, None] # shadow under the band
+ self.kind[m] = 3
+
+ # ================================================================== glass
+ def _voronoi(self, X, Y, cell, seed, jitter, around, spokes, aspect, angle):
+ if around is not None:
+ dx, dy = X - around[0], Y - around[1]
+ r = np.hypot(dx, dy)
+ n = int(spokes or max(6, round(2 * np.pi * float(np.median(r)) / cell)))
+ U = r / cell
+ V = (np.arctan2(dy, dx) + np.pi) / (2 * np.pi) * n
+ period = n
+ else:
+ c, s = np.cos(angle), np.sin(angle)
+ U = (X * c + Y * s) / (cell * aspect)
+ V = (-X * s + Y * c) / (cell / aspect)
+ period = None
+ iu, iv = np.floor(U).astype(np.int64), np.floor(V).astype(np.int64)
+ best = np.full(U.shape, np.inf, np.float32)
+ bid = np.zeros(U.shape, np.int64)
+ for di in (-1, 0, 1):
+ for dj in (-1, 0, 1):
+ ci, cj = iu + di, iv + dj
+ cw = np.mod(cj, period) if period else cj
+ h = _hash(ci, cw, seed)
+ su = ci + 0.5 + jitter * ((h & 0xFFFF) / 65535.0 - 0.5)
+ sv = cj + 0.5 + jitter * (((h >> 16) & 0xFFFF) / 65535.0 - 0.5)
+ d = ((U - su) ** 2 + (V - sv) ** 2).astype(np.float32)
+ upd = d < best
+ best = np.where(upd, d, best)
+ bid = np.where(upd, ci * 1000003 + cw, bid)
+ return bid
+
+ def glass(self, mask, colour, cell=None, streak=0.5, seeds=1.0, thick=1.0, vary=1.0, flashed=False,
+ around=None, spokes=None, aspect=1.0, angle=0.0, jitter=0.9, streak_dir=None, sites=None):
+ """lay one area of pot-metal glass of `colour` (its look with daylight behind it).
+ cell: cut it into a Voronoi mosaic of about this piece size (None = one piece);
+ around=(x, y): cut in polar coordinates round a point (pieces radiate; `spokes` sets how many);
+ aspect/angle: stretch the pieces along a direction; streak: strength of the reams; seeds: bubbles;
+ thick: thickness (darker, more saturated); vary: piece-to-piece shade variation; flashed: ruby-style
+ streaky flash layer; streak_dir: fix the ream direction (radians) instead of a random one per piece;
+ sites: explicit cut points (N x 2) -- each piece is the area nearest one site (borders: sites along the band).
+ colour may be a list: Voronoi pieces pick from it at random, site pieces cycle through it.
+ Later glass is cut out of earlier glass. Returns the region id."""
+ m = (np.asarray(mask) > 0.5) & (self.win > 0.02)
+ if not m.any(): return None
+ ys, xs = np.nonzero(m)
+ y0, y1, x0, x1 = ys.min(), ys.max() + 1, xs.min(), xs.max() + 1
+ sub = m[y0:y1, x0:x1]
+ if sites is not None:
+ S = np.asarray(sites, np.float32)
+ py, px = np.nonzero(sub)
+ px = px.astype(np.float32) + x0; py = py.astype(np.float32) + y0
+ inv = np.zeros(len(px), np.int64); best = np.full(len(px), np.inf, np.float32)
+ for i, (sx, sy) in enumerate(S):
+ d = (px - sx) ** 2 + (py - sy) ** 2
+ u = d < best; best[u] = d[u]; inv[u] = i
+ n = len(S)
+ elif cell:
+ bid = self._voronoi(self.XX[y0:y1, x0:x1], self.YY[y0:y1, x0:x1], cell, self._seed(), jitter,
+ around, spokes, aspect, angle)
+ _, inv = np.unique(bid[sub], return_inverse=True)
+ n = int(inv.max()) + 1
+ else:
+ inv = np.zeros(int(sub.sum()), np.int64); n = 1
+ base = len(self.p_col)
+ lab = self.label[y0:y1, x0:x1]
+ lab[sub] = base + inv.reshape(-1).astype(np.int32)
+ rid = len(self.regions)
+ cols = [lin(c) for c in colour] if isinstance(colour, (list, tuple)) and isinstance(colour[0], str) else [lin(colour)]
+ col = cols[0]
+ r = self.rng
+ for i in range(n):
+ ci = cols[i % len(cols)] if sites is not None else cols[int(r.integers(0, len(cols)))]
+ v = np.exp(r.normal(0, 0.11 * vary))
+ c = np.clip(ci * v * np.exp(r.normal(0, 0.05 * vary, 3)), 1e-4, 1)
+ self.p_col.append(c)
+ self.p_thick.append(thick * r.uniform(0.8, 1.3))
+ if streak_dir is None:
+ self.p_ang.append(int(r.integers(0, NANG)))
+ else:
+ self.p_ang.append(int(round((streak_dir % np.pi) / np.pi * NANG)) % NANG)
+ self.p_streak.append(streak * r.uniform(0.5, 1.5) * (2.2 if flashed else 1.0))
+ self.p_region.append(rid)
+ self.p_off.append(float(r.uniform(0, 4000))) # each piece cut from elsewhere in the sheet
+ self.regions.append(dict(colour=col, seeds=seeds, flashed=flashed))
+ self._T = None
+ return rid
+
+ def cut(self, pts, smooth=False):
+ """an extra cut line (lead) through glass, e.g. to divide a trunk or a long border strip"""
+ P = spline(pts, 8) if smooth and len(pts) > 2 else np.asarray(pts, np.float32)
+ im = Image.new('1', (self.W, self.H), 0)
+ ImageDraw.Draw(im).line([tuple(map(float, p)) for p in P], fill=1, width=1)
+ self.cuts |= np.asarray(im, bool) & (self.win > 0.5)
+
+ def crack(self, pts, mend=True):
+ """a crack running through glass; mend=True covers it with a thin strap lead, as restorers did"""
+ P = np.asarray(pts, np.float32)
+ n = max(8, int(np.hypot(*(P[-1] - P[0])) / 6))
+ t = np.linspace(0, 1, n)
+ Q = np.stack([np.interp(t, np.linspace(0, 1, len(P)), P[:, 0]), np.interp(t, np.linspace(0, 1, len(P)), P[:, 1])], 1)
+ Q[1:-1] += self.rng.normal(0, 1.6, (n - 2, 2))
+ y0, x0, m = self._stroke_mask(Q, np.full(n, 1.2))
+ self._paste_max(self.crack_a, y0, x0, m)
+ if mend:
+ im = Image.new('1', (self.W, self.H), 0)
+ ImageDraw.Draw(im).line([tuple(map(float, p)) for p in Q], fill=1, width=1)
+ self.mends |= np.asarray(im, bool)
+
+ def _tidy(self):
+ """merge slivers (too small or too thin to cut) into the neighbour of the same glass they share most edge with"""
+ for _ in range(3):
+ lab = self.label
+ n = len(self.p_col)
+ if n == 0: return
+ reg = np.array(self.p_region + [-1], np.int64)
+ area = np.bincount(lab[lab >= 0], minlength=n)
+ a = np.concatenate([lab[:, :-1].ravel(), lab[:-1, :].ravel()])
+ b = np.concatenate([lab[:, 1:].ravel(), lab[1:, :].ravel()])
+ d = a != b
+ a, b = a[d], b[d]
+ per = np.bincount(a[a >= 0], minlength=n) + np.bincount(b[b >= 0], minlength=n)
+ small = (area > 0) & ((area < 170) | (area < per * 2.6))
+ if not small.any(): return
+ src = np.concatenate([a, b]); dst = np.concatenate([b, a])
+ ok = (src >= 0) & (dst >= 0)
+ src, dst = src[ok], dst[ok]
+ ok = small[src] & ~small[dst] & (reg[src] == reg[dst])
+ src, dst = src[ok], dst[ok]
+ if len(src) == 0: return
+ key, cnt = np.unique(src * n + dst, return_counts=True)
+ s_, d_ = key // n, key % n
+ order = np.lexsort((-cnt, s_))
+ s_, d_ = s_[order], d_[order]
+ first = np.r_[True, s_[1:] != s_[:-1]]
+ mp = np.arange(n + 1, dtype=np.int32); mp[-1] = -1
+ mp[s_[first]] = d_[first]
+ self.label = np.where(lab >= 0, mp[lab], -1).astype(np.int32)
+ self._T = None
+
+ def _glass_T(self):
+ """per-pixel transmission of the bare glass (linear RGB), cached"""
+ if self._T is not None: return self._T
+ H, W = self.H, self.W
+ lab = self.label
+ m = lab >= 0
+ T = np.zeros((H, W, 3), np.float32)
+ if not m.any():
+ self._T = T; return T
+ idx = lab[m]
+ if not hasattr(self, '_thick_n'):
+ self._thick_n = (noise2d(H, W, 80, 3, self._lazy[0]) * 2 - 1).astype(np.float32)
+ self._warp = (noise2d(H, W, 240, 3, self._lazy[1]) - 0.5).astype(np.float32)
+ self._sheen = (noise2d(H, W, 30, 3, self._lazy[2]) * 2 - 1).astype(np.float32)
+ pang = np.array(self.p_ang, np.int64)
+ ang = np.full((H, W), -1, np.int64); ang[m] = pang[idx]
+ off = np.zeros((H, W), np.float32); off[m] = np.array(self.p_off, np.float32)[idx]
+ st = np.zeros((H, W), np.float32)
+ nd = int(np.hypot(W, H)) + 4600
+ for k in range(NANG):
+ sel = ang == k
+ if not sel.any(): continue
+ a = np.pi * k / NANG
+ ys_, xs_ = np.nonzero(sel)
+ dd = xs_ * np.cos(a) + ys_ * np.sin(a) + self._warp[sel] * 40 + H + 200 + off[sel]
+ tab = 0.7 * fbm1d(nd, 4, 4, 1000 + k) + 0.3 * fbm1d(nd, 30, 3, 2000 + k)
+ st[sel] = np.interp(dd, np.arange(nd), tab)
+ st = st / (np.abs(st[m]).max() + 1e-6)
+ pc = np.array(self.p_col, np.float32)[idx]
+ n_p = len(self.p_col)
+ ys_m, xs_m = np.nonzero(m)
+ cnt = np.bincount(idx, minlength=n_p) + 1e-6
+ cxp = np.bincount(idx, xs_m, n_p) / cnt; cyp = np.bincount(idx, ys_m, n_p) / cnt
+ ga = np.random.default_rng(77).uniform(0, 2 * np.pi, n_p)
+ grad = ((xs_m - cxp[idx]) * np.cos(ga[idx]) + (ys_m - cyp[idx]) * np.sin(ga[idx])) / 45.0
+ th = np.array(self.p_thick, np.float32)[idx] * (1 + 0.18 * self._thick_n[m]) * np.clip(1 + 0.22 * grad, 0.6, 1.5)
+ amp = np.array(self.p_streak, np.float32)[idx]
+ th = th * np.clip(1 + 0.55 * amp * st[m], 0.2, 3)
+ Tm = pc ** th[:, None]
+ Tm *= (1 + 0.05 * self._sheen[m])[:, None]
+ T[m] = Tm
+ T *= (1 + self._bubbles(ang))[..., None]
+ self._T = np.clip(T, 0, 1.2).astype(np.float32)
+ return self._T
+
+ def _bubbles(self, ang):
+ """seeds: tiny air bubbles drawn out along the reams -- a bright core in a dark refracting rim"""
+ H, W = self.H, self.W
+ out = np.zeros((H, W), np.float32)
+ lab = self.label
+ ys, xs = np.nonzero(lab >= 0)
+ if len(ys) == 0: return out
+ r = np.random.default_rng(self._lazy[3])
+ n = len(ys) // 520
+ pick = r.integers(0, len(ys), n)
+ seeds = np.array([g['seeds'] for g in self.regions], np.float32)
+ reg = np.array(self.p_region, np.int64)
+ R = 7
+ ky, kx = np.mgrid[-R:R + 1, -R:R + 1].astype(np.float32)
+ for i in pick:
+ y, x = int(ys[i]), int(xs[i])
+ if r.random() > seeds[reg[lab[y, x]]] * 0.6: continue
+ if y < R or x < R or y >= H - R or x >= W - R: continue
+ a = np.pi * ang[y, x] / NANG
+ Lb, wb = r.uniform(1.2, 5.5) * (1.6 if r.random() < 0.15 else 1), r.uniform(0.9, 2.0)
+ u = kx * np.cos(a) + ky * np.sin(a)
+ v = -kx * np.sin(a) + ky * np.cos(a)
+ e = np.sqrt((u / max(Lb, wb)) ** 2 + (v / wb) ** 2)
+ k = 0.55 * np.exp(-e * e * 3) - 0.45 * np.exp(-((e - 1.05) ** 2) / 0.06)
+ out[y - R:y + R + 1, x - R:x + R + 1] += k * r.uniform(0.5, 1.0)
+ return out
+
+ # ================================================================== grisaille paint and silver stain
+ def trace(self, pts, width=3.5, taper=(0.2, 0.3), opacity=0.97, smooth=True, wobble=0.5, clip=None):
+ """an opaque grisaille trace line laid with a long-haired brush: swells and tapers, slightly ragged edge.
+ clip: optional full-frame mask the line is confined to (e.g. only over the sky, not over foliage)"""
+ P = spline(pts, 8) if smooth and len(pts) > 2 else np.asarray(pts, np.float32)
+ if len(P) < 2: return
+ if wobble:
+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1)
+ L = float(seg.sum())
+ if L > 30 and len(P) > 3:
+ t = np.gradient(P, axis=0); t /= np.linalg.norm(t, axis=1, keepdims=True) + 1e-6
+ P = P + np.stack([-t[:, 1], t[:, 0]], 1) * fbm1d(len(P), 12, 2, self._seed())[:, None] * wobble
+ w = width * self._taper(len(P), taper) * (1 + 0.12 * fbm1d(len(P), 10, 2, self._seed()))
+ y0, x0, m = self._stroke_mask(P, w)
+ g = self._crop(self.grain, y0, x0, *m.shape)
+ m = np.clip(m * (1 + 0.5 * g) * 1.1, 0, 1) # paint load: slightly ragged, uneven
+ if clip is not None:
+ m = m * self._crop(np.asarray(clip, np.float32), y0, x0, *m.shape)
+ self._paste_max(self.trace_a, y0, x0, m, opacity)
+
+ def traces(self, strokes, width=3.5, **kw):
+ for p in strokes:
+ self.trace(p, width, **kw)
+
+ def _box(self, mask, pad):
+ """bounding box (slices) of the non-zero part of a full-frame mask, padded; None if empty"""
+ rows, cols = np.nonzero(mask.any(1))[0], np.nonzero(mask.any(0))[0]
+ if len(rows) == 0: return None
+ p = int(pad)
+ return (slice(max(0, rows[0] - p), min(self.H, rows[-1] + p + 1)),
+ slice(max(0, cols[0] - p), min(self.W, cols[-1] + p + 1)))
+
+ def matt(self, mask, strength=0.5, soft=4.0, stipple=0.6):
+ """a semi-opaque wash of paint, badgered smooth and stippled (fine mottled texture)"""
+ mask = np.asarray(mask, np.float32)
+ b = self._box(mask > 1e-3, 3 * soft + 3)
+ if b is None: return
+ m = blur(mask[b], soft) if soft else mask[b]
+ st = np.clip(1 + stipple * self.grain[b] * 2.2, 0, 2)
+ a = np.clip(strength * m * st, 0, 1)
+ self.matt_a[b] = 1 - (1 - self.matt_a[b]) * (1 - a)
+
+ def shade(self, mask, offset=(10, 10), strength=0.55, soft=5.0, clip=None):
+ """model volume with matt on the side away from the light: the shape minus itself moved toward the light"""
+ m = np.asarray(mask, np.float32)
+ b = self._box(m > 1e-3, 3 * soft + max(abs(offset[0]), abs(offset[1])) + 3)
+ if b is None: return
+ mb = m[b]
+ cres = np.clip(mb - shift(mb, -offset[0], -offset[1]), 0, 1)
+ cres = blur(cres, soft) * mb
+ if clip is not None: cres = cres * np.asarray(clip, np.float32)[b]
+ st = np.clip(1 + 0.6 * self.grain[b] * 2.2, 0, 2)
+ a = np.clip(strength * cres * st, 0, 1)
+ self.matt_a[b] = 1 - (1 - self.matt_a[b]) * (1 - a)
+
+ def scratch(self, pts, width=2.0, smooth=True):
+ """scrape paint back off with a stick (sticklighting): highlights, hair, veins, patterns"""
+ P = spline(pts, 8) if smooth and len(pts) > 2 else np.asarray(pts, np.float32)
+ if len(P) < 2: P = np.vstack([P, P + 0.01])
+ w = width * self._taper(len(P), (0.15, 0.15))
+ y0, x0, m = self._stroke_mask(P, w)
+ self._paste_max(self.scratch_a, y0, x0, m)
+
+ def scratch_mask(self, mask):
+ np.maximum(self.scratch_a, np.asarray(mask, np.float32), out=self.scratch_a)
+
+ def stain(self, mask, strength=1.0):
+ """silver stain: fired yellow on white glass (lemon at low strength, amber at high); on blue it makes green"""
+ np.maximum(self.stain_a, np.clip(np.asarray(mask, np.float32) * strength, 0, 1.6), out=self.stain_a)
+
+ def diaper(self, mask, spacing=28, motif='cross', size=5.0, paint=0.3, scratched=True, jitter=0.0,
+ width=1.8, rot=0.0):
+ """a background pattern: a light matt over `mask` with a lattice of small motifs scratched out of it
+ (scratched=False paints the motifs dark instead). motif: cross, dot, ring, flake (six-armed), quatrefoil;
+ jitter > 0 scatters them (falling snow)"""
+ m = np.asarray(mask, np.float32)
+ ys, xs = np.nonzero(m > 0.5)
+ if len(ys) == 0: return
+ y0, y1, x0, x1 = ys.min(), ys.max(), xs.min(), xs.max()
+ if paint: self.matt(m, paint, soft=1.5)
+ r = self.rng
+ strokes = []
+ for j, gy in enumerate(np.arange(y0, y1 + spacing, spacing * 0.866)):
+ for gx in np.arange(x0 + (spacing / 2 if j % 2 else 0), x1 + spacing, spacing):
+ x, y = gx + r.normal(0, jitter * spacing * 0.3), gy + r.normal(0, jitter * spacing * 0.3)
+ xi, yi = int(x), int(y)
+ if not (0 <= xi < self.W and 0 <= yi < self.H) or m[yi, xi] < 0.9: continue
+ s = size * (r.uniform(0.6, 1.2) if jitter else 1)
+ a0 = rot + (r.uniform(0, np.pi) if jitter else 0)
+ if motif == 'cross':
+ for a in (a0, a0 + np.pi / 2):
+ strokes.append(np.array([[x - s * np.cos(a), y - s * np.sin(a)], [x + s * np.cos(a), y + s * np.sin(a)]]))
+ elif motif == 'flake':
+ for k in range(3):
+ a = a0 + k * np.pi / 3
+ strokes.append(np.array([[x - s * np.cos(a), y - s * np.sin(a)], [x + s * np.cos(a), y + s * np.sin(a)]]))
+ elif motif in ('dot', 'ring'):
+ t = np.linspace(0, 2 * np.pi, 14)
+ rr = s * (0.35 if motif == 'dot' else 1)
+ strokes.append(np.stack([x + rr * np.cos(t), y + rr * np.sin(t)], 1))
+ elif motif == 'quatrefoil':
+ for k in range(4):
+ a = a0 + k * np.pi / 2
+ cx, cy = x + s * 0.55 * np.cos(a), y + s * 0.55 * np.sin(a)
+ t = np.linspace(0, 2 * np.pi, 12)
+ strokes.append(np.stack([cx + s * 0.4 * np.cos(t), cy + s * 0.4 * np.sin(t)], 1))
+ tgt = self.scratch_a if scratched else self.trace_a
+ for P in strokes:
+ wv = np.full(len(P), width if motif != 'dot' else size * 0.7)
+ y0_, x0_, mm = self._stroke_mask(P, wv)
+ self._paste_max(tgt, y0_, x0_, mm, 1.0 if scratched else 0.9)
+
+ def inscribe(self, s, x, y, size, font='lombardic', anchor='mm', spacing=0.0, scratched=False, stroke=0):
+ """lettering: painted dark (default) or scratched out of a matt so it shines (scratched=True)"""
+ f = glass_font(font, size)
+ m = text_mask(self.H, self.W, s, f, (x, y), anchor, spacing)
+ if stroke:
+ m = np.clip(blur(m, stroke) * 2.2, 0, 1)
+ if scratched:
+ np.maximum(self.scratch_a, m, out=self.scratch_a)
+ else:
+ np.maximum(self.trace_a, np.clip(m * (1.05 + 0.4 * self.grain), 0, 1) * 0.96, out=self.trace_a)
+
+ # ================================================================== lead, iron, weather, light
+ def _boundary_dist(self, B, R):
+ """distance (px) from every pixel to the nearest True pixel of B, up to R (disk of offsets)"""
+ ys, xs = np.nonzero(B)
+ d = np.full((self.H, self.W), np.inf, np.float32)
+ if len(ys) == 0: return d
+ y0, y1 = max(0, ys.min() - R - 1), min(self.H, ys.max() + R + 2)
+ x0, x1 = max(0, xs.min() - R - 1), min(self.W, xs.max() + R + 2)
+ b = B[y0:y1, x0:x1]
+ dd = np.full(b.shape, np.inf, np.float32)
+ offs = sorted(((ox, oy) for oy in range(-R, R + 1) for ox in range(-R, R + 1) if ox * ox + oy * oy <= R * R),
+ key=lambda o: o[0] ** 2 + o[1] ** 2)
+ for ox, oy in offs:
+ sb = shift(b, ox, oy)
+ new = sb & np.isinf(dd)
+ dd[new] = np.hypot(ox, oy)
+ d[y0:y1, x0:x1] = dd
+ return d
+
+ def lead(self, width=6.0, rim=10.0, solder=True, mend=3.2):
+ """lead the window up: H-section came on every piece boundary, cut line and the rim of each light;
+ soldered joints; thin strap leads over mended cracks"""
+ self._tidy()
+ lab = self.label
+ H, W = self.H, self.W
+ B = np.zeros((H, W), bool)
+ dh = lab[:, 1:] != lab[:, :-1]
+ dv = lab[1:, :] != lab[:-1, :]
+ B[:, 1:] |= dh; B[:, :-1] |= dh
+ B[1:, :] |= dv; B[:-1, :] |= dv
+ B &= (lab >= 0) | np.roll(lab >= 0, 1, 0) | np.roll(lab >= 0, 1, 1)
+ rimzone = np.zeros((H, W), np.float32)
+ for L in self.lights:
+ rimzone = np.maximum(rimzone, smoothstep(rim + 3, rim - 1, L.sdf()) * (L.sdf() > -2))
+ B &= rimzone < 0.5 # the rim came covers the edge itself
+ B |= self.cuts
+ hw = width / 2
+ d = self._boundary_dist(B, int(hw + 4)) + 0.5
+ # solder joints where three or more pieces meet
+ if solder:
+ a, b, c, e = lab[:-1, :-1], lab[:-1, 1:], lab[1:, :-1], lab[1:, 1:]
+ cnt = 1 + (b != a) + ((c != a) & (c != b)) + ((e != a) & (e != b) & (e != c))
+ J = np.zeros((H, W), np.float32); J[:-1, :-1] = (cnt >= 3)
+ J *= (lab >= 0)
+ sol = smoothstep(0.015, 0.09, blur(J, 2.6))
+ sol *= (0.75 + 0.5 * (noise2d(H, W, 6, 2, self._seed())))
+ else:
+ sol = np.zeros((H, W), np.float32)
+ de = d - 2.4 * sol
+ cov_in = smoothstep(hw + 0.75, hw - 0.75, de)
+ h_in = np.sqrt(np.clip(1 - (np.clip(de, 0, None) / (hw + 0.6)) ** 2, 0, 1)) * cov_in
+ # rim came
+ cov_rim = np.zeros((H, W), np.float32); h_rim = np.zeros((H, W), np.float32)
+ for L in self.lights:
+ s = L.sdf()
+ cr = smoothstep(rim + 0.75, rim - 0.75, s) * (s > -3)
+ t = np.clip(s / rim, 0, 1)
+ hr = np.sqrt(np.clip(1 - ((t - 0.45) / 0.62) ** 2, 0, 1)) * cr
+ cov_rim = np.maximum(cov_rim, cr); h_rim = np.maximum(h_rim, hr)
+ # strap leads over mended cracks
+ cov_m = np.zeros((H, W), np.float32); h_m = np.zeros((H, W), np.float32)
+ if self.mends.any():
+ dm = self._boundary_dist(self.mends, int(mend / 2 + 3)) + 0.5
+ cov_m = smoothstep(mend / 2 + 0.7, mend / 2 - 0.7, dm)
+ h_m = np.sqrt(np.clip(1 - (dm / (mend / 2 + 0.5)) ** 2, 0, 1)) * cov_m * 0.7
+ cov = np.maximum(np.maximum(cov_in, cov_rim), cov_m) * (self.win > 0.02)
+ hgt = np.maximum(np.maximum(h_in, h_rim), h_m) * (hw * 0.9) + sol * 1.6
+ hgt = blur(hgt, 0.7)
+ gy, gx = np.gradient(hgt)
+ n = np.stack([-gx, -gy, np.ones_like(gx)], -1)
+ n /= np.linalg.norm(n, axis=-1, keepdims=True)
+ Ld = np.array([-0.35, -0.6, 0.72], np.float32); Ld /= np.linalg.norm(Ld)
+ diff = np.clip(n @ Ld, 0, 1)
+ hv = Ld + np.array([0, 0, 1], np.float32); hv /= np.linalg.norm(hv)
+ spec = np.clip(n @ hv, 0, 1) ** 30
+ pat = noise2d(H, W, 14, 3, self._seed()) # dull white patina (lead carbonate)
+ alb = lin('#2c2d31') * (0.8 + 0.5 * pat)[..., None]
+ alb = alb * (1 - sol[..., None]) + lin('#6d6f72') * sol[..., None] # tin solder is lighter
+ rgb = alb * (0.28 + 0.9 * diff)[..., None] + (0.035 + 0.06 * sol)[..., None] * spec[..., None]
+ self.lead_a = cov.astype(np.float32)
+ self.lead_rgb = rgb.astype(np.float32) * 0.55
+ self.lead_d = np.minimum(de, np.where(cov_rim > 0, 0, 99)).astype(np.float32)
+ for L in self.lights:
+ self.lead_d = np.minimum(self.lead_d, np.clip(L.sdf() - rim, 0, None) + hw)
+ self._T = None
+
+ def saddle_bar(self, light, y, width=9.0, ties=True):
+ """a wrought-iron saddle bar across the light on the inside, ends let into the reveal, wired to the leads"""
+ L = light
+ x0, x1 = L.cx - L.a - L.splay * 0.55, L.cx + L.a + L.splay * 0.55
+ b = (slice(max(0, int(y - width / 2 - 6)), min(self.H, int(y + width / 2 + 7))),
+ slice(max(0, int(x0) - 1), min(self.W, int(x1) + 2)))
+ Y, X = self.YY[b], self.XX[b]
+ t = (Y - (y - width / 2)) / width
+ m = np.clip(np.minimum(Y - (y - width / 2), (y + width / 2) - Y) + 0.5, 0, 1) * \
+ np.clip(np.minimum(X - x0, x1 - X) + 0.5, 0, 1)
+ prof = np.clip(t, 0, 1)
+ shade = 0.35 + 0.9 * np.exp(-((prof - 0.22) / 0.16) ** 2) - 0.25 * smoothstep(0.6, 1, prof)
+ rust = noise2d(Y.shape[0], Y.shape[1], 8, 3, self._seed())
+ col = lin('#2b2622') * (0.7 + 0.6 * rust)[..., None] * shade[..., None] + lin('#5a3a26') * 0.05 * rust[..., None]
+ if ties and self.lead_a is not None:
+ row_a = self.lead_a[int(y - width / 2 - 5)]
+ row_b = self.lead_a[int(y + width / 2 + 5)]
+ xs = np.nonzero((row_a > 0.7) & (row_b > 0.7) & (self.XX[0] > L.cx - L.a + 14) & (self.XX[0] < L.cx + L.a - 14))[0]
+ runs = np.split(xs, np.nonzero(np.diff(xs) > 1)[0] + 1) if len(xs) else []
+ centres = [int(r_.mean()) for r_ in runs if len(r_)]
+ for x in centres[::max(1, len(centres) // 4)][:5]: # a few ties, not one per lead
+ tie = np.clip((1 - np.hypot((X - x) / 1.7, (Y - y) / (width / 2 + 2.6))) * 1.7 + 0.5, 0, 1)
+ m = np.maximum(m, tie)
+ col = np.where((tie > 0.05)[..., None], lin('#5a3a22') * (0.7 + 0.5 * rust)[..., None], col)
+ self.bar_rgb[b] = np.where((m > 0)[..., None], col * 0.6, self.bar_rgb[b])
+ self.bar_a[b] = np.maximum(self.bar_a[b], m)
+
+ def weather(self, grime=0.5, pits=0.5):
+ """age: grime along the leads and toward the bottom of each light; corrosion pits on some pieces"""
+ H, W = self.H, self.W
+ n = noise2d(H, W, 70, 4, self._seed())
+ near = smoothstep(16, 3, self.lead_d) if self.lead_d is not None else 0
+ low = np.zeros((H, W), np.float32)
+ for L in self.lights:
+ low = np.maximum(low, smoothstep(L.top + L.height * 0.4, L.bottom, self.YY) * (L.sdf() > 0))
+ g = grime * np.clip(0.25 * n + 0.45 * near * n + 0.35 * low * n, 0, 1)
+ Tm = 1 - g[..., None] * (1 - lin('#d8c6a2'))[None, None, :] * 1.3
+ # pits: on a few pieces the outside skin has corroded into little dark craters with pale halos
+ out = np.ones((H, W), np.float32)
+ lab = self.label
+ n_p = len(self.p_col)
+ if pits and n_p:
+ r = np.random.default_rng(self._seed())
+ level = np.where(r.random(n_p) < 0.22, r.uniform(0.4, 1.0, n_p), r.uniform(0, 0.12, n_p)) * pits
+ ys, xs = np.nonzero(lab >= 0)
+ pick = r.integers(0, len(ys), len(ys) // 260)
+ R = 4
+ ky, kx = np.mgrid[-R:R + 1, -R:R + 1].astype(np.float32)
+ for i in pick:
+ y, x = int(ys[i]), int(xs[i])
+ if r.random() > level[lab[y, x]] or y < R or x < R or y >= H - R or x >= W - R: continue
+ rr = r.uniform(0.6, 1.9)
+ e = np.hypot(kx, ky) / rr
+ k = 1 - 0.55 * np.exp(-e * e * 1.5) + 0.12 * np.exp(-((e - 1.6) ** 2) / 0.3)
+ out[y - R:y + R + 1, x - R:x + R + 1] *= k
+ self.weather_T = (Tm * out[..., None]).astype(np.float32)
+
+ def daylight(self, strength=1.0, spill=1.0, halation=1.0, sky=('#ffffff', '#e4e9f0')):
+ """turn the room on: sky light behind the glass, coloured spill on the stone, glow on the reveals, a soft
+ projection of the glass on the sill, halation over the leads"""
+ self.lit = dict(strength=strength, spill=spill, halation=halation)
+ self._sky = sky
+
+ # ================================================================== compositing
+ def _backlight(self):
+ H, W = self.H, self.W
+ top, bot = self._sky or ('#ffffff', '#e4e9f0')
+ if not hasattr(self, '_cloud'):
+ self._cloud = noise2d(H, W, 340, 3, self._lazy[4])
+ t = (self.YY / H)[..., None]
+ B = lin(top) * (1 - t) + lin(bot) * t
+ k = (self.lit or {}).get('strength', 1.0)
+ return B * (0.86 + 0.24 * self._cloud)[..., None] * k
+
+ def _cartoon(self):
+ """the glazier's cutline drawing: paper with the cut lines in charcoal"""
+ lab = self.label
+ Bd = np.zeros(lab.shape, np.float32)
+ Bd[:, 1:] += lab[:, 1:] != lab[:, :-1]
+ Bd[1:, :] += lab[1:, :] != lab[:-1, :]
+ Bd = np.clip(blur(np.clip(Bd, 0, 1) + self.cuts, 0.7) * 1.6, 0, 1)
+ paper = lin('#e6dcc6') * (0.92 + 0.08 * self.grain[..., None] * 2)
+ return paper * (1 - 0.8 * Bd[..., None])
+
+ def composite(self, cartoon=False):
+ H, W = self.H, self.W
+ win = self.win[..., None]
+ if cartoon:
+ Eg = self._cartoon() * 0.75
+ light = Eg * 0.5
+ else:
+ Eg = self._glass_T().copy()
+ Eg[self.label < 0] = (0.92, 0.95, 1.0) # still empty: plain daylight
+ P = 1 - (1 - self.trace_a * (1 - self.scratch_a)) * (1 - self.matt_a * (1 - self.scratch_a))
+ Eg *= (1 - P)[..., None] + P[..., None] * PAINT_T
+ del P
+ if self.stain_a.any():
+ S = np.clip(self.stain_a, 0, 1.6)[..., None]
+ Eg *= (1 - np.minimum(S, 1)) + np.minimum(S, 1) * lin(STAIN) ** np.maximum(S, 1)
+ del S
+ if self.crack_a.any():
+ Eg *= (1 - 0.6 * self.crack_a)[..., None]
+ if self.lead_d is not None: # glass just under the came is shaded
+ Eg *= (1 - 0.22 * smoothstep(4.5, 0, self.lead_d - 2.5))[..., None]
+ if self.weather_T is not None:
+ Eg *= self.weather_T
+ Eg *= self._backlight()
+ light = Eg.copy()
+ ba = self.bar_a[..., None]
+ if self.lead_a is not None:
+ la = self.lead_a[..., None]
+ light *= 1 - la
+ Eg *= 1 - la
+ Eg += self.lead_rgb * la
+ light *= (1 - ba) * win
+ # stone lighting: ambient, a wide wash of the window's colours, glowing reveals, the sill's projection.
+ # Until daylight() the room is lit by a fixed neutral spill, so the stone stays identical between stages.
+ q = 4
+ small = light[::q, ::q] if self.lit else self.win[::q, ::q, None] * np.array([0.42, 0.44, 0.48], np.float32)
+ up = lambda a: np.stack([np.asarray(Image.fromarray(np.ascontiguousarray(a[..., c], np.float32)).resize((W, H), Image.BILINEAR))
+ for c in range(a.shape[-1])], -1)
+ wm = blur(self.win[::q, ::q], 40 / q)[..., None] + 1e-3
+ near = np.stack([blur(small[..., c], 40 / q) for c in range(3)], -1)
+ far = np.stack([blur(small[..., c], 150 / q) for c in range(3)], -1)
+ k = (self.lit or {}).get('spill', 0.75)
+ illum = up(k * (0.55 * far + 0.25 * near))
+ illum += (self.ambient * (0.75 + 0.35 * (1 - self.YY / H)))[..., None]
+ avg = up(near / wm) # average colour of the nearby glass
+ del near, far
+ rv = self.reveal
+ f = np.where(self.kind == 1, k * (0.08 + 0.42 * rv ** 1.6), 0) + np.where(self.kind == 2, k * 0.05 * bool(self.lit), 0)
+ illum += avg * f[..., None]
+ del avg, f
+ if self.lit:
+ self._sill_light(light, illum, k)
+ img = self.alb * illum
+ del illum
+ img *= (self.relief * (1 - self.win))[..., None]
+ img += Eg * win
+ del Eg
+ img *= 1 - ba
+ img += self.bar_rgb * ba
+ if self.lit and self.lit.get('halation', 0):
+ h = self.lit['halation']
+ sm = up(np.stack([blur(small[..., c], 24 / q) for c in range(3)], -1))
+ for c in range(3):
+ bl = 0.16 * blur(light[..., c], 1.6) + 0.12 * blur(light[..., c], 6) + 0.09 * sm[..., c]
+ if c == 2: bl *= 1.3 # blue halates most
+ la = self.lead_a if self.lead_a is not None else 0
+ img[..., c] += h * bl * (1 - self.win * (0.74 - 0.08 * la) - 0.4 * self.bar_a)
+ del sm
+ del light
+ # vignette, tone, grain
+ vx = (self.XX / W - 0.5) * 1.6; vy = (self.YY / H - 0.48) * 1.5
+ img *= (1 - 0.42 * smoothstep(0.35, 1.25, np.hypot(vx, vy)))[..., None]
+ hi = img > 0.75
+ img[hi] = 0.75 + 0.25 * (1 - np.exp(-(img[hi] - 0.75) / 0.25))
+ np.clip(img, 0, 1, out=img)
+ img **= 1 / 2.2
+ img += (self.grain * 0.018 * (1 - self.win * 0.6))[..., None]
+ return Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8))
+
+ def _sill_light(self, light, illum, k):
+ """light falling through the lowest glass lands on the sloping sill as a soft, upside-down projection"""
+ H, W = self.H, self.W
+ for L in self.lights:
+ src_h = int(L.height * 0.32)
+ yb = int(L.bottom)
+ x0, x1 = max(0, int(L.cx - L.a - L.splay - 2)), min(W, int(L.cx + L.a + L.splay + 2))
+ src = light[yb - src_h:yb, x0:x1]
+ src = np.stack([blur(src[..., c], 9) for c in range(3)], -1)
+ sh = int(L.sill)
+ xs = np.arange(x1 - x0, dtype=np.float32)
+ c = (x1 - x0) / 2
+ for j in range(sh):
+ y = yb + 1 + j
+ if y >= H: break
+ d = j / sh
+ row = src[int(src_h - 1 - d * (src_h - 1))]
+ xsrc = c + (xs - c) / (1 + 0.18 * d)
+ rr = np.stack([np.interp(xsrc, xs, row[:, kk]) for kk in range(3)], -1) * (1.7 - 0.9 * d)
+ on = self.kind[y, x0:x1] == 2
+ illum[y, x0:x1][on] += k * rr[on]
+
+ def stage(self, name, cartoon=False):
+ if self.record:
+ self.stages.append((name, self.composite(cartoon)))
+
+ 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
diff --git a/lib/stencil.py b/lib/stencil.py
new file mode 100644
index 0000000..277977b
--- /dev/null
+++ b/lib/stencil.py
@@ -0,0 +1,1037 @@
+"""stencil — spray-paint stencil graffiti on a board-marked concrete wall (numpy + Pillow only).
+
+Model: a real wall, real stencils cut from card, and a spray can whose paint is a cloud of droplets.
+ wall board-marked cast concrete, built as an albedo map plus a height map lit by one low sun from the upper
+ left. The formwork was a row of sawn planks, so the wall is banded: each plank-high band has its own
+ tone and a fraction of a pixel of step, the sawn wood grain is pressed into the surface (wavy grain
+ lines flowing round the odd knot), board ends make short vertical joints, and cement paste that
+ squeezed between the boards left a thin broken fin along every seam. Form-tie holes are cone-shaped
+ recesses on a regular grid, some still with the rusted rod end, some plugged with paler mortar. Air
+ bubbles left bug holes (small pits). Weather does the rest: rain streaks hanging from the ties and the
+ seams, rust stains under some ties, a damp splash zone above the pavement with a tide line and a white
+ efflorescence crust, a hairline crack, dust.
+ history the wall was painted before: `buff()` is a council roller patch of not-quite-matching grey laid on in
+ vertical passes (stepped top and bottom edges, dry streaky ends, darker laps) over an old tag whose
+ ghost still shows through; `freehand(..., wash=)` is an old tag half taken off by a pressure washer.
+ stencil `card()` is a sheet of card; you cut openings in it (shapes, letters) and paint goes only through the
+ openings. Any piece of card that the cuts surround completely (the middle of an O, the gap between an
+ arm and a body, the spaces between the spokes of a reel) would fall out, so it must be held by
+ bridges: thin strips of uncut card that show up in the paint as hairlines of bare wall.
+ `bridges()` finds those islands and cuts the shortest bridges automatically; `text()` bridges every
+ counter top and bottom like a stencil typeface. A picture in several tones is several cards, sprayed
+ light to dark; each card goes on a few pixels off, so the lighter layer peeks out along one side.
+ spray the can moves across the card in overlapping sweeps; each sweep deposits a soft cone of paint, so the
+ paint film is the sum of gaussian strokes along the path (heavier where the can slowed or lingered).
+ Through the openings the film reaches the wall: where the card lay flat (near the tape) the edge is
+ knife-crisp, where it lifted the paint creeps under it as a soft fringe; a fine mist drifts further
+ (the overspray halo) and the sweeps that overshoot the card leave a faint straight-edged ghost of the
+ sheet itself. Coverage comes from droplets: a thick film is solid, a thin one is a scatter of dots, so
+ every soft edge is speckled rather than blurred. Paint is opaque or not by pigment (black hides in one
+ coat, white needs more), it does not reach the bottom of pits, it lies on the relief (the wood grain
+ and the seams show through it) and it has a satin sheen. Where the film is too thick at the lower
+ edge of an opening, paint runs: a drip with a neck, a thin tail and a bead at the end, raised and
+ glossy.
+ freehand `freehand()` is the can without a stencil (a skinny cap): a soft line whose width and weight follow the
+ hand's speed, a little spatter, a spit of paint where the nozzle started, drips where it paused.
+Coordinates are pixels on the wall; a card can carry its own design origin and scale (`card(..., origin, scale)`)
+so a figure can be written once in its own units. Angles are degrees counter-clockwise.
+
+ from stencil import Stencil, shade_side, BLACK, WHITE, RED
+ s = Stencil(1920, 1080, seed=7)
+ s.wall(ground=1000); s.pavement()
+ c = s.card(1250, 500, 1650, 1000, origin=(1450, 994)) # the sheet, and where design (0, 0) sits
+ body = np.maximum(c.capsule((0, -60), (0, -300), 60, 45), c.ellipse((0, -360), 40))
+ c.cut(body); c.keep(c.text('HI', 0, -170, 90, anchor='ms', bridge=0)) # knocked-out letters: loose card
+ c.bridges() # ... so hold every island with bridges
+ s.spray(c, BLACK, drips=1.0)
+ s.stage('figure', card=c) # snapshot with the card still taped up
+ s.save('out.jpg')
+"""
+import os
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+from core import blur, noise2d, smoothstep, shift, latin_font, spline, fbm1d, height_normals, height_shadow
+
+CONCRETE = '#a9a398'
+BLACK, WHITE, GREY, RED = '#161616', '#ece8de', '#7b7c79', '#cf2a1f'
+HIDE = {BLACK: 3.4, GREY: 2.8, RED: 2.4, WHITE: 2.0} # hiding power per unit of film
+GLOSS = {BLACK: 0.55, GREY: 0.35, RED: 0.4, WHITE: 0.25} # satin sheen on the relief
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+def _c(c):
+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)
+
+
+def _aniso(h, w, sx, sy, octaves, seed):
+ """value noise in [0, 1] stretched sx by sy px (wood grain, streaks)"""
+ r = np.random.default_rng(seed)
+ out = np.zeros((h, w), np.float32); amp, tot = 1.0, 0.0
+ for o in range(octaves):
+ gh, gw = max(2, int(h / sy * 2 ** o) + 2), max(2, int(w / sx * 2 ** o) + 2)
+ g = Image.fromarray(r.random((gh, gw)).astype(np.float32))
+ out += amp * np.asarray(g.resize((w, h), Image.BICUBIC), np.float32)
+ tot += amp; amp *= 0.5
+ out /= tot
+ return (out - out.min()) / (out.max() - out.min() + 1e-6)
+
+
+def _disc_splat(arr, x, y, r, val, mode='min'):
+ """stamp a soft disc (radius r) into arr at (x, y): mode min/max/add; val scales the profile"""
+ H, W = arr.shape
+ R = int(np.ceil(r + 2))
+ x0, x1, y0, y1 = int(x) - R, int(x) + R + 1, int(y) - R, int(y) + R + 1
+ if x1 <= 0 or y1 <= 0 or x0 >= W or y0 >= H: return
+ xa, ya = max(x0, 0), max(y0, 0)
+ xb, yb = min(x1, W), min(y1, H)
+ yy, xx = np.mgrid[ya:yb, xa:xb].astype(np.float32)
+ d = np.hypot(xx - x, yy - y)
+ prof = np.clip(r + 0.5 - d, 0, 1) if r < 1.5 else np.clip(1 - (d / (r + 0.5)) ** 2, 0, 1)
+ sl = arr[ya:yb, xa:xb]
+ if mode == 'min': np.minimum(sl, val * prof, out=sl)
+ elif mode == 'max': np.maximum(sl, val * prof, out=sl)
+ else: sl += val * prof
+
+
+def _geo_fill(seed, allowed, iters=4000):
+ """geodesic flood: grow `seed` inside `allowed` (both bool) until it stops changing"""
+ cur = seed & allowed
+ for i in range(iters):
+ nxt = cur.copy()
+ nxt[1:] |= cur[:-1]; nxt[:-1] |= cur[1:]
+ nxt[:, 1:] |= cur[:, :-1]; nxt[:, :-1] |= cur[:, 1:]
+ nxt &= allowed
+ if i % 8 == 7 and np.array_equal(nxt, cur): break
+ cur = nxt
+ return cur
+
+
+def shade_side(mask, light=(-1.0, -1.0), depth=20.0, soft=2.0, wobble=0.0, seed=0):
+ """posterised form shadow for a stencil plate: the part of `mask` whose far side (away from `light`) lies
+ within `depth` px -- a crescent along the shadow side, like the dark plate of a two-tone stencil.
+ wobble (0..1) varies the depth along the edge so the shadow reads cut by hand, not offset by machine."""
+ lx, ly = light
+ l = np.hypot(lx, ly) + 1e-6
+ m = blur(mask, soft) if soft else mask
+
+ def far(d):
+ return shift(m, lx / l * d, ly / l * d) # = mask one step of d further away from the light
+
+ if wobble:
+ h, w = mask.shape
+ n = noise2d(h, w, max(10.0, depth * 2.0), 2, seed)
+ f = far(depth * (1 - wobble)) * (1 - n) + far(depth * (1 + wobble)) * n
+ else:
+ f = far(depth)
+ return np.clip(mask * (1 - smoothstep(0.35, 0.65, f)), 0, 1).astype(np.float32)
+
+
+# ====================================================================== the stencil sheet
+class Card:
+ """a sheet of card with openings cut in it. Shapes are made in design units (origin + scale), return local
+ masks (h, w) in [0, 1] that can be combined with numpy, and are cut with `cut()`."""
+
+ def __init__(self, st, x0, y0, x1, y1, origin=None, scale=1.0, tape=None, material='manila', seed=0):
+ self.st = st
+ self.x0, self.y0 = int(np.floor(x0)), int(np.floor(y0))
+ self.x1, self.y1 = int(np.ceil(x1)), int(np.ceil(y1))
+ self.w, self.h = self.x1 - self.x0, self.y1 - self.y0
+ self.ox, self.oy = origin if origin is not None else (self.x0, self.y0)
+ self.k = float(scale)
+ self.rng = np.random.default_rng(seed)
+ self.seed = seed
+ self.open = np.zeros((self.h, self.w), np.float32)
+ yy, xx = np.mgrid[0:self.h, 0:self.w].astype(np.float32)
+ self.YY, self.XX = yy, xx
+ # the sheet itself: a knife-cut rectangle with slightly wandering edges and one clipped corner
+ e = 0.9 * fbm1d(self.w, 120, 3, seed + 1)
+ f = 0.9 * fbm1d(self.h, 120, 3, seed + 2)
+ inside = ((yy > 1.5 + e[None, :]) & (yy < self.h - 2.5 + e[None, :] * 0.7) &
+ (xx > 1.5 + f[:, None]) & (xx < self.w - 2.5 - f[:, None] * 0.7))
+ cc = self.rng.uniform(10, 26)
+ inside &= (xx + yy > cc)
+ self.sheet = blur(inside.astype(np.float32), 0.6)
+ if tape is None: # masking tape at three corners and one edge
+ tape = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 0.55)]
+ self.tape = [(tx * self.w, ty * self.h) for tx, ty in tape]
+ self.material = material
+
+ # ------------------------------------------------------------ design units -> local px
+ def P(self, pts):
+ p = np.asarray(pts, np.float32).reshape(-1, 2)
+ return np.stack([self.ox - self.x0 + p[:, 0] * self.k, self.oy - self.y0 + p[:, 1] * self.k], 1)
+
+ def _poly_mask(self, pts, ss=4):
+ im = Image.new('L', (self.w * ss, self.h * ss), 0)
+ ImageDraw.Draw(im).polygon([(float(x) * ss, float(y) * ss) for x, y in pts], fill=255)
+ im = im.reduce(ss)
+ return np.asarray(im, np.float32) / 255
+
+ # ------------------------------------------------------------ shapes (do not cut yet)
+ def poly(self, pts, smooth=False, per=10, facet=0.0):
+ """closed outline. smooth: Catmull-Rom through the points. facet: px of knife jitter (cut as short straight
+ segments, the way a blade follows a curve)"""
+ P = self.P(pts)
+ if smooth:
+ Q = np.vstack([P, P[:2]])
+ P = spline(Q, per)[: len(P) * per]
+ if facet:
+ seg = np.linalg.norm(np.diff(np.vstack([P, P[:1]]), axis=0), axis=1)
+ L = np.concatenate([[0], np.cumsum(seg)])
+ n = max(8, int(L[-1] / 7))
+ s = np.linspace(0, L[-1], n, endpoint=False)
+ Pc = np.vstack([P, P[:1]])
+ P = np.stack([np.interp(s, L, Pc[:, 0]), np.interp(s, L, Pc[:, 1])], 1)
+ P = P + self.rng.normal(0, facet, P.shape)
+ return self._poly_mask(P)
+
+ def capsule(self, p0, p1, r0, r1=None):
+ """a limb: segment p0-p1 with radius r0 -> r1 (round ends)"""
+ r1 = r0 if r1 is None else r1
+ a, b = self.P([p0])[0], self.P([p1])[0]
+ r0, r1 = r0 * self.k, r1 * self.k
+ X, Y = self.XX, self.YY
+ d = b - a
+ L2 = float(d @ d) + 1e-6
+ t = np.clip(((X - a[0]) * d[0] + (Y - a[1]) * d[1]) / L2, 0, 1)
+ dist = np.hypot(X - a[0] - t * d[0], Y - a[1] - t * d[1])
+ r = r0 + (r1 - r0) * t
+ return np.clip(r - dist + 0.5, 0, 1).astype(np.float32)
+
+ def ellipse(self, c, rx, ry=None, rot=0.0):
+ ry = rx if ry is None else ry
+ cx, cy = self.P([c])[0]
+ rx, ry = rx * self.k, ry * self.k
+ a = np.radians(rot)
+ dx, dy = self.XX - cx, self.YY - cy
+ u = dx * np.cos(a) - dy * np.sin(a)
+ v = dx * np.sin(a) + dy * np.cos(a)
+ q = np.hypot(u / rx, v / ry)
+ return np.clip((1 - q) * min(rx, ry) + 0.5, 0, 1).astype(np.float32)
+
+ def ring(self, c, r_out, r_in):
+ return np.clip(self.ellipse(c, r_out) - self.ellipse(c, r_in), 0, 1)
+
+ def stroke(self, pts, w0, w1=None, smooth=True, per=8):
+ """a tapered band along a path (scarf tail, tail string, a spar): width w0 -> w1"""
+ w1 = w0 if w1 is None else w1
+ P = np.asarray(pts, np.float32)
+ if smooth and len(P) > 2: P = spline(P, per)
+ out = np.zeros((self.h, self.w), np.float32)
+ n = len(P)
+ for i in range(n - 1):
+ t0, t1 = i / max(n - 1, 1), (i + 1) / max(n - 1, 1)
+ np.maximum(out, self.capsule(P[i], P[i + 1], (w0 + (w1 - w0) * t0) / 2, (w0 + (w1 - w0) * t1) / 2), out=out)
+ return out
+
+ def text(self, s, x, y, size, font='stencil', anchor='ls', spacing=0.0, bridge=3.5, rot=0.0):
+ """stencil lettering: the counters of every letter are held by bridges at the top and bottom (or the
+ shortest side, for awkward shapes). x, y, size in design units."""
+ f = stencil_font(font, size * self.k)
+ (px, py), = self.P([(x, y)])
+ im = Image.new('L', (self.w, self.h), 0)
+ d = ImageDraw.Draw(im)
+ if spacing:
+ adv = [f.getlength(ch) + spacing * self.k for ch in s]
+ tot = sum(adv) - spacing * self.k
+ cx = px - tot * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor[0]]
+ for ch, a in zip(s, adv):
+ d.text((cx, py), ch, font=f, fill=255, anchor='l' + anchor[1]); cx += a
+ else:
+ d.text((px, py), s, font=f, fill=255, anchor=anchor)
+ if rot: im = im.rotate(rot, resample=Image.BICUBIC, center=(px, py))
+ m = np.asarray(im, np.float32) / 255
+ if bridge:
+ m = self._bridge_mask(m, bridge * self.k, prefer='v')
+ return m
+
+ # ------------------------------------------------------------ cutting
+ def cut(self, mask):
+ np.maximum(self.open, np.clip(mask, 0, 1), out=self.open)
+ return self
+
+ def keep(self, mask):
+ """leave card here (a deliberate bridge or a detail that stays unpainted)"""
+ self.open *= 1 - np.clip(mask, 0, 1)
+ return self
+
+ def bridge(self, p0, p1, width=3.5):
+ """a hand-placed bridge from p0 to p1 (design units)"""
+ return self.keep(self.capsule(p0, p1, width / 2))
+
+ def bridges(self, width=3.5, min_area=12, two_over=1600, prefer=None):
+ """find every island of card the cuts have isolated and hold each with the shortest bridge (two bridges,
+ on roughly opposite sides, for big islands)"""
+ self.open = self._bridge_mask(self.open, width * self.k, min_area, two_over * self.k ** 2, prefer)
+ return self
+
+ def islands(self):
+ """number of loose pieces of card left (0 means the stencil holds together)"""
+ card = self.open < 0.5
+ outer = np.zeros_like(card); outer[0, :] = outer[-1, :] = outer[:, 0] = outer[:, -1] = True
+ return int(((card & ~_geo_fill(outer, card)).sum()))
+
+ def _bridge_mask(self, m, width, min_area=12, two_over=1600, prefer=None):
+ for _round in range(4):
+ card = m < 0.5
+ h, w = card.shape
+ outer = np.zeros_like(card); outer[0, :] = outer[-1, :] = outer[:, 0] = outer[:, -1] = True
+ reached = _geo_fill(outer, card)
+ isl = card & ~reached
+ if not isl.any(): break
+ todo = isl.copy()
+ cuts = []
+ while todo.any():
+ ys, xs = np.nonzero(todo)
+ seed = np.zeros_like(todo); seed[ys[0], xs[0]] = True
+ comp = _geo_fill(seed, todo)
+ todo &= ~comp
+ area = int(comp.sum())
+ if area < min_area:
+ m = np.where(comp, 1.0, m).astype(np.float32) # a crumb: it just falls out
+ continue
+ cy, cx = np.nonzero(comp)
+ mx, my = cx.mean(), cy.mean()
+ k = np.argmin((cx - mx) ** 2 + (cy - my) ** 2)
+ sx, sy = float(cx[k]), float(cy[k])
+ cands = []
+ angs = np.radians(np.arange(0, 360, 7.5))
+ for a in angs:
+ dx, dy = np.cos(a), np.sin(a)
+ x, y, t = sx, sy, 0.0
+ start = None; ok = False
+ while True:
+ t += 0.75
+ x, y = sx + dx * t, sy + dy * t
+ ix, iy = int(round(x)), int(round(y))
+ if ix < 0 or iy < 0 or ix >= w or iy >= h: break
+ if comp[iy, ix]:
+ start = None; continue
+ if start is None: start = (x, y, t)
+ if card[iy, ix] and not comp[iy, ix]:
+ ok = reached[iy, ix] or isl[iy, ix]
+ end = (x, y)
+ break
+ if ok and start is not None:
+ L = t - start[2]
+ if prefer == 'v': L *= 1.0 + 1.6 * abs(dx) # stencil type: vertical bridges
+ if prefer == 'h': L *= 1.0 + 1.6 * abs(dy)
+ cands.append((L, a, start[:2], end, reached[iy, ix]))
+ if not cands: continue
+ cands.sort(key=lambda c: (not c[4], c[0]))
+ best = cands[0]
+ cuts.append(best)
+ if area > two_over or prefer == 'v':
+ opp = [c for c in cands if abs(((c[1] - best[1] + np.pi) % (2 * np.pi)) - np.pi) > np.radians(120)]
+ if opp: cuts.append(opp[0])
+ for L, a, (x0, y0), (x1, y1), _ in cuts:
+ dx, dy = np.cos(a), np.sin(a)
+ p0 = (x0 - dx * 1.5, y0 - dy * 1.5); p1 = (x1 + dx * 1.5, y1 + dy * 1.5)
+ d = np.array(p1) - np.array(p0)
+ L2 = float(d @ d) + 1e-6
+ tt = np.clip(((self.XX - p0[0]) * d[0] + (self.YY - p0[1]) * d[1]) / L2, 0, 1)
+ dist = np.hypot(self.XX - p0[0] - tt * d[0], self.YY - p0[1] - tt * d[1])
+ m = m * (1 - np.clip(width / 2 - dist + 0.5, 0, 1))
+ return m.astype(np.float32)
+
+
+def stencil_font(style, size):
+ """heavy display faces for stencil lettering: stencil (DIN Condensed Bold / Impact), slab (Rockwell Bold),
+ block (Futura Bold / Arial Black). Override with $INKPAINT_FONT_STENCIL etc."""
+ env = os.environ.get('INKPAINT_FONT_' + style.upper())
+ cands = {'stencil': [('/System/Library/Fonts/Supplemental/DIN Condensed Bold.ttf', 0),
+ ('/System/Library/Fonts/Supplemental/Impact.ttf', 0)],
+ 'slab': [('/System/Library/Fonts/Supplemental/Rockwell.ttc', 1)],
+ 'block': [('/System/Library/Fonts/Supplemental/Arial Black.ttf', 0),
+ ('/System/Library/Fonts/Supplemental/Futura.ttc', 2)]}.get(style, [])
+ if env and os.path.exists(env): cands = [(env, 0)] + cands
+ for p, i in cands:
+ if os.path.exists(p):
+ try:
+ return ImageFont.truetype(p, int(round(size)), index=i)
+ except OSError:
+ pass
+ hit = latin_font('condensed') or latin_font('sans_bold')
+ return ImageFont.truetype(hit[0], int(round(size)), index=hit[1]) if hit else ImageFont.load_default(int(size))
+
+
+# ====================================================================== the wall and the can
+class Stencil:
+ def __init__(self, W=1920, H=1080, seed=0, light=(-0.58, -0.62, 0.53)):
+ self.W, self.H = W, H
+ self.seed = seed
+ self.rng = np.random.default_rng(seed)
+ l = np.array(light, np.float32); self.light = l / np.linalg.norm(l)
+ self.alb = np.ones((H, W, 3), np.float32) * _c(CONCRETE)
+ self.hgt = np.zeros((H, W), np.float32)
+ self.gloss = np.zeros((H, W), np.float32)
+ self.pit = np.zeros((H, W), np.float32) # how deep a pit is: paint does not reach its bottom
+ self.ground_y = H
+ self.gmask = np.zeros((H, W), np.float32) # 1 = pavement (lit from above, not part of the wall)
+ self.stages = []
+ g = self.rng.random((H, W)).astype(np.float32)
+ c = blur(g, 0.9)
+ u = 0.55 * (g - 0.5) / 0.2887 + 0.45 * (c - c.mean()) / (c.std() + 1e-6)
+ order = np.argsort(u, axis=None)
+ U = np.empty(H * W, np.float32); U[order] = (np.arange(H * W, dtype=np.float32) + 0.5) / (H * W)
+ self.U = U.reshape(H, W) # droplet thresholds (uniform, slightly clumped)
+ del g, c, u, order, U
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ # ------------------------------------------------------------ the wall
+ def wall(self, colour=CONCRETE, planks=(86, 118), ties=(380, None), ground=1000, damp=110, crack=True):
+ """board-marked concrete: plank bands, wood grain imprint, board joints, paste fins, tie holes, bug
+ holes, aggregate, weather. ties: (horizontal spacing, list of rows or None for every third seam)"""
+ H, W, r = self.H, self.W, self.rng
+ self.ground_y = ground
+ base = _c(colour)
+ Y, X = np.mgrid[0:H, 0:W].astype(np.float32)
+ hgt = np.zeros((H, W), np.float32)
+ tone = np.ones((H, W), np.float32)
+ # --- planks
+ seams = []
+ y = -r.uniform(0, planks[0])
+ while y < ground:
+ seams.append(y); y += r.uniform(*planks)
+ seams.append(y)
+ warp = (_aniso(H, W, 260, 26, 3, self._seed()) - 0.5)
+ fine = (_aniso(H, W, 90, 2.2, 2, self._seed()) - 0.5)
+ gshow = noise2d(H, W, 150, 3, self._seed())
+ for i in range(len(seams) - 1):
+ a, b = seams[i], seams[i + 1]
+ ya, yb = max(0, int(np.floor(a))), min(H, int(np.ceil(b)) + 1)
+ if yb <= ya: continue
+ sl = slice(ya, yb)
+ yy, xx = Y[sl], X[sl]
+ inband = ((yy >= a) & (yy < b)).astype(np.float32)
+ # boards of random length inside the band
+ ends = [0.0]
+ while ends[-1] < W: ends.append(ends[-1] + r.uniform(380, 1250))
+ ends[0] = -r.uniform(0, 600)
+ seg = np.searchsorted(np.array(ends[1:]), xx[0], side='right')
+ nseg = len(ends)
+ ph = r.uniform(0, 50, nseg + 1)[seg][None, :]
+ per = r.uniform(4.2, 7.5, nseg + 1)[seg][None, :]
+ amp = r.uniform(5, 14, nseg + 1)[seg][None, :]
+ tn = r.normal(0, 0.035, nseg + 1)[seg][None, :]
+ st = r.normal(0, 0.28, nseg + 1)[seg][None, :]
+ disp = warp[sl] * amp * 2 + (yy - a) * r.uniform(-0.02, 0.02)
+ # knots: grain flows round them
+ knot = np.zeros_like(yy)
+ for _ in range(r.integers(0, 3)):
+ kx, ky = r.uniform(0, W), r.uniform(a + 15, b - 15)
+ rx, ry = r.uniform(18, 40), r.uniform(7, 14)
+ q = ((xx - kx) / rx) ** 2 + ((yy - ky) / ry) ** 2
+ disp = disp + np.sign(yy - ky) * 9 * np.exp(-q * 0.8)
+ knot = np.maximum(knot, np.exp(-q * 3.0))
+ g = np.sin(2 * np.pi * (yy - a + disp + ph) / per)
+ show = smoothstep(0.3, 0.8, gshow[sl]) # grain pressed in here, smooth there
+ grain = (0.11 * smoothstep(0.1, 0.9, g) * show + 0.07 * fine[sl] * 2)
+ hgt[sl] += inband * (grain + st - 0.35 * knot)
+ tone[sl] *= 1 + inband * (tn - 0.05 * knot - 0.025 * smoothstep(0.5, 1.0, g) * show)
+ # board ends: a hairline joint with a little lip
+ for ex in ends[1:-1]:
+ if ex < 0 or ex > W: continue
+ wob = ex + 0.8 * fbm1d(yb - ya, 40, 2, self._seed())[:, None]
+ dj = np.abs(xx - wob)
+ hgt[sl] -= inband * 0.3 * np.exp(-(dj / 0.9) ** 2)
+ tone[sl] *= 1 - inband * 0.03 * np.exp(-(dj / 1.4) ** 2)
+ # paste fins along every seam (broken here and there) and a slight tone step
+ for sy in seams[1:-1]:
+ ya, yb = max(0, int(sy) - 6), min(H, int(sy) + 7)
+ if yb <= ya: continue
+ sl = slice(ya, yb)
+ wob = sy + 0.9 * fbm1d(W, 160, 3, self._seed())[None, :]
+ d = Y[sl] - wob
+ gate = smoothstep(0.25, 0.55, noise2d(1, W, 40, 2, self._seed())[0])[None, :]
+ th = 1.2 + 1.4 * noise2d(1, W, 18, 2, self._seed())[0][None, :]
+ hgt[sl] += gate * 1.15 * np.exp(-(d / th) ** 2) - (1 - gate) * 0.5 * np.exp(-(d / 1.0) ** 2)
+ tone[sl] *= 1 - 0.06 * np.exp(-(d / 1.6) ** 2) * (1 - gate) + 0.03 * gate * np.exp(-(d / th) ** 2)
+ # --- aggregate and cement tone
+ cloud = noise2d(H, W, 260, 4, self._seed())
+ tone *= 1 + 0.085 * (cloud - 0.5)
+ mott = noise2d(H, W, 38, 3, self._seed())
+ tone *= 1 + 0.07 * (mott - 0.5) - 0.05 * smoothstep(0.62, 0.8, mott)
+ lait = smoothstep(0.68, 0.9, noise2d(H, W, 90, 3, self._seed()))
+ tone *= 1 + 0.06 * lait
+ sand = self.rng.random((H, W)).astype(np.float32)
+ tone *= 1 + 0.045 * (sand - 0.5)
+ hgt += 0.18 * (sand - 0.5) + 0.25 * (blur(sand, 1.2) - 0.5)
+ specks = sand > 0.996
+ tone[specks] *= 0.8
+ tone[(sand < 0.003)] *= 1.12
+ # --- bug holes (air pits), more of them near the top of each lift of planks
+ pit = np.zeros((H, W), np.float32)
+ pitd = np.zeros((H, W), np.float32)
+ n = int(W * ground / 1800)
+ cl = noise2d(H // 8 + 1, W // 8 + 1, 18, 2, self._seed())
+ for _ in range(n):
+ x, y = r.uniform(0, W), r.uniform(0, ground - 4)
+ if cl[int(y) // 8, int(x) // 8] < r.uniform(0.25, 0.95): continue
+ rad = r.choice([0.7, 1.0, 1.4, 2.0, 2.8], p=[0.32, 0.3, 0.2, 0.12, 0.06])
+ _disc_splat(pitd, x, y, rad, 1.0, 'max')
+ hgt -= 2.6 * pitd
+ pit = np.maximum(pit, pitd)
+ tone *= 1 - 0.25 * pitd
+ # --- form-tie holes
+ sx = ties[0]
+ rows = ties[1]
+ if rows is None:
+ cent = [(seams[i] + seams[i + 1]) / 2 for i in range(len(seams) - 1)]
+ rows = [cy for j, cy in enumerate(cent) if j % 3 == 1 and 30 < cy < ground - 60]
+ self.tie_holes = []
+ rust = np.zeros((H, W), np.float32)
+ x_off = r.uniform(0.3, 0.7) * sx
+ for ri, cy in enumerate(rows):
+ xs = np.arange(x_off - sx * 2, W + sx, sx)
+ for cx in xs:
+ cx2, cy2 = cx + r.normal(0, 1.5), cy + r.normal(0, 1.0)
+ if cx2 < -20 or cx2 > W + 20: continue
+ kind = r.choice(['rod', 'plug', 'open'], p=[0.5, 0.3, 0.2])
+ self.tie_holes.append((cx2, cy2, kind))
+ R = 12.5
+ ya, yb = max(0, int(cy2 - R - 3)), min(H, int(cy2 + R + 4))
+ xa, xb = max(0, int(cx2 - R - 3)), min(W, int(cx2 + R + 4))
+ if yb <= ya or xb <= xa: continue
+ yy, xx = Y[ya:yb, xa:xb], X[ya:yb, xa:xb]
+ d = np.hypot(xx - cx2, yy - cy2)
+ cone = np.clip(1 - d / R, 0, 1)
+ lip = np.exp(-((d - R) / 1.4) ** 2) * 0.5
+ depth = 7.0 if kind != 'plug' else 2.2
+ hgt[ya:yb, xa:xb] += -depth * np.clip(cone * 1.6, 0, 1) ** 0.8 + lip
+ pit[ya:yb, xa:xb] = np.maximum(pit[ya:yb, xa:xb], np.clip(cone * 1.4, 0, 1) * (0.8 if kind != 'plug' else 0.2))
+ core = np.clip(4.6 - d, 0, 1)
+ if kind == 'rod':
+ tone[ya:yb, xa:xb] *= 1 - 0.5 * core - 0.12 * cone
+ rust[ya:yb, xa:xb] = np.maximum(rust[ya:yb, xa:xb], core * 0.9)
+ elif kind == 'plug':
+ tone[ya:yb, xa:xb] *= 1 + 0.06 * np.clip(9.5 - d, 0, 1) - 0.08 * np.exp(-((d - 9.5) / 1.2) ** 2)
+ else:
+ tone[ya:yb, xa:xb] *= 1 - 0.35 * np.clip(7 - d, 0, 1) - 0.1 * cone
+ # --- weather: rain streaks from ties and seams, rust stains, the damp splash zone
+ streak = np.zeros((H, W), np.float32)
+ for cx, cy, kind in self.tie_holes:
+ if r.random() < 0.75:
+ L = r.uniform(70, 330); wd = r.uniform(5, 15)
+ self._streak(streak, cx + r.normal(0, 2), cy + 6, L, wd, r.uniform(0.5, 1.0))
+ if kind == 'rod' and r.random() < 0.7:
+ self._streak(rust, cx + r.normal(0, 1), cy + 3, r.uniform(40, 190), r.uniform(2.5, 5.5), r.uniform(0.5, 0.9))
+ for _ in range(int(W / 70)):
+ cx, cy = r.uniform(0, W), r.choice(seams[1:-1])
+ self._streak(streak, cx, cy + 2, r.uniform(40, 260), r.uniform(10, 40), r.uniform(0.25, 0.7))
+ for _ in range(5): # long runs from the coping above the frame
+ self._streak(streak, r.uniform(0, W), 0, r.uniform(0.35, 0.8) * ground, r.uniform(25, 70), r.uniform(0.3, 0.6))
+ streak = np.clip(streak, 0, 1.3)
+ rust = np.clip(rust, 0, 1)
+ dirt = 1 - 0.26 * streak[..., None] * np.array([1.0, 0.98, 0.93], np.float32)
+ rust_c = np.array([0.62, 0.36, 0.2], np.float32)
+ # damp splash zone above the pavement: a wavy tide line, algae, efflorescence crust
+ tide = ground - damp + 26 * (fbm1d(W, 300, 4, self._seed()) )[None, :] + 10 * fbm1d(W, 40, 2, self._seed())[None, :]
+ zone = smoothstep(-6, 18, Y - tide)
+ deep = smoothstep(0, ground - (ground - damp * 0.4), Y - (ground - damp * 0.4)) * (Y <= ground)
+ alg = noise2d(H, W, 22, 4, self._seed())
+ damp_m = (zone * (0.55 + 0.45 * deep) * (0.8 + 0.4 * noise2d(H, W, 50, 3, self._seed())))[..., None]
+ crust = noise2d(H, W, 7, 3, self._seed())
+ efflo = np.exp(-((Y - tide + 2) / 4.0) ** 2) * smoothstep(0.45, 0.8, crust) * 0.5 * smoothstep(0.3, 0.6, alg)
+ efflo += zone * smoothstep(0.78, 0.92, noise2d(H // 2 + 1, W // 2 + 1, 6, 2, self._seed())[
+ (np.arange(H) // 2)[:, None], (np.arange(W) // 2)[None, :]]) * 0.25
+ # --- assemble
+ alb = base[None, None, :] * tone[..., None] * dirt
+ alb = alb * (1 - rust[..., None] * 0.55) + rust[..., None] * 0.55 * rust_c * alb.mean(-1, keepdims=True) * 1.6
+ green = np.array([0.80, 0.86, 0.74], np.float32)
+ alb = alb * (1 - damp_m * 0.30) * (1 - damp_m * smoothstep(0.6, 0.85, alg)[..., None] * deep[..., None] * (1 - green))
+ alb = alb + (np.array([0.93, 0.92, 0.88], np.float32) - alb) * np.clip(efflo, 0, 0.8)[..., None]
+ # dust: the whole wall a little lighter and flatter toward the top, dirtier toward the ground
+ alb *= (1.02 - 0.06 * smoothstep(0, ground, Y))[..., None]
+ if crack: self._crack(hgt, alb, self.tie_holes)
+ self.alb = alb.astype(np.float32)
+ self.hgt = hgt.astype(np.float32)
+ self.pit = np.clip(pit, 0, 1).astype(np.float32)
+
+ def _streak(self, arr, x, y, L, wd, s):
+ """a soft vertical run of grime starting at (x, y), widening and fading as it goes down"""
+ H, W = arr.shape
+ ya, yb = max(0, int(y)), min(H, int(y + L))
+ xa, xb = max(0, int(x - wd * 2.5 - 6)), min(W, int(x + wd * 2.5 + 7))
+ if yb <= ya or xb <= xa: return
+ yy = np.arange(ya, yb, dtype=np.float32)[:, None]
+ xx = np.arange(xa, xb, dtype=np.float32)[None, :]
+ t = (yy - y) / L
+ wob = 3 * fbm1d(yb - ya, 60, 3, int(x * 7 + y) % 99991)[:, None]
+ width = wd * (0.45 + 0.8 * np.sqrt(np.clip(t, 0, 1)))
+ prof = np.exp(-((xx - x - wob) / width) ** 2)
+ fade = np.clip(t * 12, 0, 1) * (1 - t) ** 1.4
+ tex = 0.7 + 0.3 * np.cos(xx * 1.7 + wob * 2.1) * np.cos(yy * 0.05)
+ arr[ya:yb, xa:xb] += s * prof * fade * tex
+
+ def _crack(self, hgt, alb, ties):
+ """a hairline crack wandering down from one tie hole"""
+ r = self.rng
+ if not ties: return
+ cx, cy, _ = ties[int(r.integers(len(ties)))]
+ for branch in range(2):
+ x, y = cx + r.normal(0, 3), cy + 10
+ a = np.radians(r.uniform(60, 110) if branch == 0 else r.uniform(20, 60))
+ pts = [(x, y)]
+ for i in range(int(r.uniform(40, 80) if branch == 0 else r.uniform(15, 30))):
+ a += r.normal(0, 0.35)
+ a = np.clip(a, np.radians(15), np.radians(165))
+ step = r.uniform(2, 5)
+ x += np.cos(a) * step; y += np.sin(a) * step
+ pts.append((x, y))
+ for (x0, y0), (x1, y1) in zip(pts[:-1], pts[1:]):
+ for t in np.linspace(0, 1, 6):
+ _disc_splat(hgt, x0 + (x1 - x0) * t, y0 + (y1 - y0) * t, 0.6, -0.5, 'add')
+ im = Image.new('L', (self.W, self.H), 0)
+ ImageDraw.Draw(im).line(pts, fill=255, width=1)
+ m = np.asarray(im, np.float32) / 255
+ m = np.clip(m * 0.5 + blur(m, 1.4) * 0.5, 0, 1)
+ alb *= (1 - 0.32 * m)[..., None]
+ cx, cy = pts[len(pts) // 3]
+
+ def pavement(self, colour='#6f6c68', joint=True):
+ """the strip of pavement under the wall: asphalt seen at a glance, lit from above, with dust and grit
+ along the foot of the wall"""
+ H, W, r = self.H, self.W, self.rng
+ g0 = self.ground_y
+ if g0 >= H: return
+ h = H - g0
+ Y, X = np.mgrid[0:h, 0:W].astype(np.float32)
+ t = Y / max(h - 1, 1)
+ base = _c(colour)
+ grit = self.rng.random((h, W)).astype(np.float32)
+ agg = _aniso(h, W, 7, 3, 2, self._seed())
+ tone = 1 + 0.16 * (agg - 0.5) + 0.10 * (grit - 0.5)
+ tone *= 1 + 0.08 * (noise2d(h, W, 140, 3, self._seed()) - 0.5)
+ g2 = blur(grit, 0.7)
+ g2 = (g2 - g2.mean()) / (g2.std() + 1e-6)
+ tone *= 1 + 0.07 * np.clip(g2, -2.5, 2.5) # aggregate: pale stones in dark binder
+ tone[grit > 0.97] *= 1.22
+ tone[grit < 0.04] *= 0.8
+ alb = base[None, None, :] * tone[..., None] * (0.9 + 0.12 * t)[..., None]
+ # tar-sealed cracks, flattened chewing gum, an oil stain: the life of a pavement
+ tar = Image.new('L', (W, h), 0)
+ dd = ImageDraw.Draw(tar)
+ for _ in range(3):
+ x = r.uniform(0, W); y = r.uniform(h * 0.3, h)
+ pts = [(x, y)]
+ for _ in range(14):
+ x += r.uniform(15, 40); y += r.normal(0, 4) * 0.6
+ pts.append((x, min(max(y, 6), h - 1)))
+ dd.line(pts, fill=255, width=int(r.integers(7, 12)), joint='curve')
+ tm = blur(np.asarray(tar, np.float32) / 255, 1.5) * (0.7 + 0.3 * noise2d(h, W, 20, 2, self._seed()))
+ alb = alb * (1 - 0.32 * tm[..., None])
+ for _ in range(int(W / 70)):
+ gx, gy = r.uniform(0, W), r.uniform(8, h - 3)
+ rr = r.uniform(2.0, 4.2)
+ gum = np.zeros((h, W), np.float32)
+ _disc_splat(gum, gx, gy, rr, 1.0, 'max')
+ gum = np.clip(gum * 2.5, 0, 1)
+ alb = alb * (1 - 0.6 * gum[..., None]) + 0.6 * gum[..., None] * np.array([0.27, 0.27, 0.28], np.float32)
+ oil = smoothstep(0.62, 0.8, noise2d(h, W, 60, 3, self._seed())) * smoothstep(0.5, 0.8, noise2d(h, W, 300, 2, self._seed()))
+ alb = alb * (1 - 0.25 * oil[..., None])
+ # a band of dust and grit swept against the wall
+ dust = np.exp(-Y / 10.0) * (0.6 + 0.4 * noise2d(h, W, 30, 2, self._seed()))
+ alb = alb * (1 - 0.35 * dust[..., None]) + 0.35 * dust[..., None] * np.array([0.62, 0.58, 0.52], np.float32)
+ # a dark crack line where the wall meets the ground
+ alb[:3] *= np.array([0.45, 0.55, 0.75], np.float32)[:, None, None]
+ self.alb[g0:] = alb
+ self.hgt[g0:] = 0.0
+ self.gmask[g0:] = 1.0
+ self.pit[g0:] = 0.0
+ self._weeds()
+
+ def _weeds(self):
+ """a few tufts of grass in the joint at the foot of the wall"""
+ r = self.rng
+ im = Image.new('L', (self.W * 2, (self.H - self.ground_y + 80) * 2), 0)
+ d = ImageDraw.Draw(im)
+ gy = 80
+ for _ in range(int(r.integers(3, 6))):
+ cx = r.uniform(40, self.W - 40)
+ for _ in range(int(r.integers(6, 16))):
+ a = np.radians(r.uniform(-150, -30))
+ L = r.uniform(12, 46)
+ bend = r.normal(0, 0.4)
+ pts = []
+ for s in np.linspace(0, 1, 7):
+ aa = a + bend * s * s
+ pts.append(((cx + np.cos(aa) * L * s) * 2, (gy + 4 + np.sin(aa) * L * s) * 2))
+ for i in range(len(pts) - 1):
+ wdt = int(max(1, (1 - i / 6) * 4))
+ d.line([pts[i], pts[i + 1]], fill=255, width=wdt)
+ m = np.asarray(im.reduce(2), np.float32) / 255
+ y0 = self.ground_y - 80
+ y0c = max(0, y0)
+ m = m[y0c - y0:]
+ h = m.shape[0]
+ sl = slice(y0c, y0c + h)
+ col = np.array([0.33, 0.40, 0.2], np.float32)
+ self.alb[sl] = self.alb[sl] * (1 - m[..., None]) + col * (0.8 + 0.4 * self.U[sl, :, None] * 0.5) * m[..., None]
+ self.hgt[sl] += m * 2.0
+
+ # ------------------------------------------------------------ painting helpers
+ def _deposit(self, sl, film, colour, wash=None, mist_tint=0.22, roll=None):
+ """turn a paint film (local array) into droplets on the wall"""
+ col = _c(colour)
+ hide = HIDE.get(colour, 2.4) if isinstance(colour, str) else 2.4
+ m = 1 - np.exp(-hide * np.clip(film, 0, None))
+ if roll is None: roll = (int(self.rng.integers(self.H)), int(self.rng.integers(self.W)))
+ U = np.roll(self.U, roll, (0, 1))[sl]
+ dots = smoothstep(-0.03, 0.03, m - U)
+ cov = np.clip(dots * (1 - mist_tint) + m * mist_tint, 0, 1)
+ cov *= 1 - 0.78 * self.pit[sl] * (1 - smoothstep(1.6, 3.2, film)) # paint misses the bottom of pits
+ if wash is not None: cov *= wash
+ cov = cov * (1 - self.gmask[sl])
+ a = cov[..., None]
+ self.alb[sl] = self.alb[sl] * (1 - a) + col * a
+ gl = GLOSS.get(colour, 0.35) if isinstance(colour, str) else 0.35
+ self.gloss[sl] = self.gloss[sl] * (1 - cov) + gl * cov
+ return cov
+
+ def _drip(self, x, y, length, width, colour, seed):
+ """one run of paint: a neck where it leaves the edge, a thinning tail, a bead at the end"""
+ r = np.random.default_rng(seed)
+ ss = 4
+ L = float(length)
+ pad = int(width * 3 + 6)
+ x0, y0 = int(x) - pad, int(y) - 2
+ w, h = 2 * pad + 1, int(L + width * 4 + 8)
+ if x0 < 0 or x0 + w > self.W or y0 >= self.ground_y - 2: return
+ h = min(h, self.ground_y - y0 - 1)
+ if h < 4: return
+ im = Image.new('L', (w * ss, h * ss), 0)
+ d = ImageDraw.Draw(im)
+ n = int(L * 2) + 2
+ t = np.linspace(0, 1, n)
+ wob = fbm1d(n, max(4, n / 3), 3, seed) * min(2.2, 0.35 + L / 90) + np.cumsum(r.normal(0, 0.02, n))
+ for i in range(n):
+ tt = t[i]
+ rad = width * (1.0 + 0.9 * np.exp(-tt * L / 4.0)) * (1 - 0.38 * tt) / 2
+ cx, cy = x - x0 + wob[i], y - y0 + tt * L
+ d.ellipse([(cx - rad) * ss, (cy - rad) * ss, (cx + rad) * ss, (cy + rad) * ss], fill=255)
+ rb = width * r.uniform(0.62, 0.85)
+ cx, cy = x - x0 + wob[-1], y - y0 + L
+ d.ellipse([(cx - rb) * ss, (cy - rb * 1.25) * ss, (cx + rb) * ss, (cy + rb * 1.15) * ss], fill=255)
+ m = np.asarray(im.reduce(ss), np.float32) / 255
+ sl = (slice(y0, y0 + h), slice(x0, x0 + w))
+ a = m[:self.H - y0]
+ col = _c(colour)
+ self.alb[sl] = self.alb[sl] * (1 - a[..., None]) + col * a[..., None]
+ self.gloss[sl] = np.maximum(self.gloss[sl], a * 0.85)
+ self.hgt[sl] += blur(a, 1.0) * (0.45 + 0.25 * width / 3)
+
+ def _drips(self, film, open_m, sl, colour, amount, length, wet, seed):
+ """paint runs from the lower edges of the openings where the film is too thick"""
+ if amount <= 0: return
+ r = np.random.default_rng(seed)
+ y0, x0 = sl[0].start, sl[1].start
+ below = shift(open_m, 0, -3) # value 3 px further down
+ clear = np.maximum(shift(open_m, 0, -7), shift(open_m, 0, -12))
+ edge = (open_m > 0.5) & (below < 0.3) & (clear < 0.3) # a real lower edge, not just a bridge
+ ex = film - wet
+ cand = edge & (ex > 0)
+ ys, xs = np.nonzero(cand)
+ if not len(ys): return
+ w = ex[ys, xs]
+ nmax = int(round(amount * min(26, 2 + w.sum() / 40)))
+ p = w / w.sum()
+ taken = []
+ for i in r.choice(len(ys), size=min(nmax * 3, len(ys)), replace=False, p=p):
+ if len(taken) >= nmax: break
+ X, Y = xs[i] + x0, ys[i] + y0
+ if any(abs(X - a) < 9 and abs(Y - b) < 40 for a, b in taken): continue
+ taken.append((X, Y))
+ e = float(ex[ys[i], xs[i]])
+ L = np.clip((18 + 120 * e * r.uniform(0.4, 1.4)) * length, 10, 300)
+ wd = np.clip(1.5 + 0.9 * np.sqrt(e) + r.normal(0, 0.25), 1.3, 3.6)
+ self._drip(X + 0.5, Y, L, wd, colour, int(r.integers(1 << 30)))
+
+ def _lift(self, card, dx, dy):
+ """how far the card stands off the wall (0 flat at the tape .. 1 curled), local to the card"""
+ h, w = card.h, card.w
+ d = np.full((h, w), 1e9, np.float32)
+ for tx, ty in card.tape:
+ d = np.minimum(d, np.hypot(card.XX - tx, card.YY - ty))
+ diag = np.hypot(w, h)
+ L = np.clip(d / (0.7 * diag), 0, 1) ** 1.5
+ curl = smoothstep(0.55, 0.85, noise2d(h, w, 120, 2, card.seed + 11)) # here and there the card bows out
+ return np.clip(0.15 + 0.35 * L + 0.5 * curl, 0, 1).astype(np.float32)
+
+ def _sweeps(self, h, w, box, cone, angle, rng, overshoot=1.2, linger=3):
+ """the path of the can: overlapping parallel sweeps over `box`, dwell weights splatted into an array"""
+ x0, y0, x1, y1 = box
+ a = np.radians(angle)
+ ux, uy = np.cos(a), -np.sin(a)
+ vx, vy = -uy, ux
+ corners = np.array([[x0, y0], [x1, y0], [x0, y1], [x1, y1]], np.float32)
+ u = corners @ np.array([ux, uy]); v = corners @ np.array([vx, vy])
+ sp = cone * 0.95
+ D = np.zeros((h, w), np.float32)
+ pts, wts = [], []
+ for vi, vv in enumerate(np.arange(v.min() - cone * 0.4, v.max() + cone * 0.6, sp)):
+ ua, ub = u.min() - cone * overshoot, u.max() + cone * overshoot
+ n = int((ub - ua) / 1.5) + 2
+ uu = np.linspace(ua, ub, n)
+ speed = 1 + 0.35 * fbm1d(n, max(6, n / 3), 3, int(rng.integers(1 << 30)))
+ tt = (uu - ua) / (ub - ua)
+ speed *= 0.55 + 0.45 * smoothstep(0.0, 0.08, np.minimum(tt, 1 - tt)) # slows at the reversals
+ off = vv + rng.normal(0, cone * 0.12) + np.linspace(0, rng.normal(0, cone * 0.25), n)
+ px = uu * ux + off * vx; py = uu * uy + off * vy
+ pts.append(np.stack([px, py], 1)); wts.append(1.5 / speed)
+ P = np.concatenate(pts); Wt = np.concatenate(wts)
+ for _ in range(linger): # the hand stops to fill a corner
+ k = rng.integers(len(P))
+ P = np.vstack([P, P[k] + rng.normal(0, cone * 0.2, (40, 2))]); Wt = np.concatenate([Wt, np.full(40, 1.1)])
+ ix, iy = np.floor(P[:, 0]).astype(int), np.floor(P[:, 1]).astype(int)
+ fx, fy = P[:, 0] - ix, P[:, 1] - iy
+ for ddx, ddy, ww in ((0, 0, (1 - fx) * (1 - fy)), (1, 0, fx * (1 - fy)), (0, 1, (1 - fx) * fy), (1, 1, fx * fy)):
+ jx, jy = ix + ddx, iy + ddy
+ ok = (jx >= 0) & (jy >= 0) & (jx < w) & (jy < h)
+ np.add.at(D, (jy[ok], jx[ok]), (Wt * ww)[ok])
+ return blur(D, cone)
+
+ # ------------------------------------------------------------ public painting tools
+ def card(self, x0, y0, x1, y1, origin=None, scale=1.0, tape=None, material='manila'):
+ """a sheet of card covering x0..x1, y0..y1 (wall px). Openings are cut with its shape methods."""
+ return Card(self, x0, y0, x1, y1, origin, scale, tape, material, self._seed())
+
+ def spray(self, card, colour, coats=1.8, cone=24, angle=8, misreg=2.2, at=(0, 0), rot=0.0, lift=1.0, mist=1.0,
+ drips=1.0, drip_len=1.0, wet=2.4, linger=3, ghost=1.0):
+ """spray through `card`: overlapping sweeps (cone = spray radius px), the paint lands through the
+ openings with a crisp core, an under-spray fringe where the card lifted, an overspray halo, a ghost of
+ the sheet where sweeps overshot it, and drips where the film is too heavy. at: move the card (reuse it
+ somewhere else); rot: turn it (degrees, about its origin); misreg: random placement error (px) for
+ multi-layer work."""
+ r = self.rng
+ dx = at[0] + r.normal(0, misreg); dy = at[1] + r.normal(0, misreg)
+ idx, idy = int(np.floor(dx)), int(np.floor(dy))
+ fx, fy = dx - idx, dy - idy
+ pad = int(2.5 * cone + 30) # paint also lands round the outside of the card
+ opn, sht = card.open, card.sheet
+ if rot:
+ cx, cy = card.ox - card.x0, card.oy - card.y0
+ opn = np.asarray(Image.fromarray(opn).rotate(rot, Image.BILINEAR, center=(cx, cy)), np.float32)
+ sht = np.asarray(Image.fromarray(sht).rotate(rot, Image.BILINEAR, center=(cx, cy)), np.float32)
+ op = np.pad(opn, pad)
+ op = ((1 - fx) * (1 - fy) * op + fx * (1 - fy) * shift(op, 1, 0) + (1 - fx) * fy * shift(op, 0, 1)
+ + fx * fy * shift(op, 1, 1))
+ sheet = np.pad(sht, pad)
+ Lf = np.pad(self._lift(card, dx, dy), pad, mode='edge') * lift
+ X0, Y0 = card.x0 + idx - pad, card.y0 + idy - pad
+ xa, ya = max(0, X0), max(0, Y0)
+ xb, yb = min(self.W, X0 + card.w + 2 * pad), min(self.ground_y, Y0 + card.h + 2 * pad)
+ if xb <= xa or yb <= ya: return None
+ lsl = (slice(ya - Y0, yb - Y0), slice(xa - X0, xb - X0))
+ sl = (slice(ya, yb), slice(xa, xb))
+ op, sheet, L = op[lsl], sheet[lsl], Lf[lsl]
+ h, w = op.shape
+ ys, xs = np.nonzero(op > 0.3)
+ if not len(ys): return None
+ box = (xs.min(), ys.min(), xs.max(), ys.max())
+ D = self._sweeps(h, w, box, cone, angle + r.normal(0, 4), r, linger=linger)
+ Dm = np.median(D[op > 0.5]) if (op > 0.5).any() else D.max()
+ D = D / (Dm + 1e-6) * coats
+ # paint through the openings: crisp core, under-spray fringe where lifted, halo of drifting mist
+ s1, s2 = blur(op, 0.5), blur(op, 1.8)
+ soft = s1 * (1 - L) + s2 * L
+ open_eff = np.maximum(op, soft * (0.2 + 0.5 * L))
+ halo = (blur(op, 7) * 0.022 + blur(op, 24) * 0.012) * mist * (0.5 + L)
+ film = D * np.clip(open_eff + halo, 0, 1.2) * sheet
+ film += D * (1 - sheet) * 0.0035 * ghost # sweeps that ran past the edge of the card
+ self._deposit(sl, film, colour)
+ if drips > 0:
+ self._drips(film, op, sl, colour, drips, drip_len, wet, self._seed())
+ card.last = dict(sl=sl, lsl=lsl, D=D, colour=colour, offset=(idx, idy), L=L, pad=pad, op=op, sheet=sheet)
+ return card
+
+ def freehand(self, pts, colour, width=4.0, coats=2.0, smooth=True, per=10, speed=None, spits=4, drips=0.6,
+ mist=1.0, wash=None, wet=2.5, drip_len=1.0):
+ """the can without a stencil (a skinny cap): a soft line along pts whose weight follows the hand's speed.
+ speed: optional per-control-point speed factors (slow = heavier). wash: 0..1 how much a pressure washer
+ took off afterwards."""
+ r = self.rng
+ P = np.asarray(pts, np.float32)
+ if smooth and len(P) > 2: P = spline(P, per)
+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1)
+ Ls = np.concatenate([[0], np.cumsum(seg)])
+ n = int(Ls[-1] / 0.8) + 2
+ s = np.linspace(0, Ls[-1], n)
+ x = np.interp(s, Ls, P[:, 0]); y = np.interp(s, Ls, P[:, 1])
+ if speed is not None:
+ sp = np.interp(s / Ls[-1], np.linspace(0, 1, len(speed)), speed)
+ else:
+ sp = np.ones(n)
+ sp = sp * (1 + 0.25 * fbm1d(n, max(8, n / 6), 3, self._seed()))
+ tt = s / max(Ls[-1], 1)
+ sp = sp * (0.45 + 0.55 * smoothstep(0, 0.04, tt)) # starting slow: the heavy blob at the start
+ pad = int(width * 6 + 40)
+ xa, xb = max(0, int(x.min()) - pad), min(self.W, int(x.max()) + pad)
+ ya, yb = max(0, int(y.min()) - pad), min(self.ground_y, int(y.max()) + pad)
+ if xb <= xa or yb <= ya: return
+ h, w = yb - ya, xb - xa
+ D = np.zeros((h, w), np.float32)
+ ix = np.clip(np.round(x - xa).astype(int), 0, w - 1); iy = np.clip(np.round(y - ya).astype(int), 0, h - 1)
+ np.add.at(D, (iy, ix), 0.8 / sp)
+ sig = width / 2.6
+ core = blur(D, sig) * (sig * 2.5066) # = 1 along a steady line
+ film = core * coats + blur(D, sig * 5) * (sig * 12.5) * 0.06 * mist * coats
+ sl = (slice(ya, yb), slice(xa, xb))
+ wm = None
+ if wash is not None and wash > 0:
+ st = _aniso(h, w, 24, 260, 3, self._seed())
+ wm = np.clip(1 - wash * smoothstep(0.25, 0.75, st + 0.3 * (self.rng.random((h, w)) - 0.5)), 0, 1)
+ self._deposit(sl, film, colour, wash=wm)
+ # cap spits: a few fat droplets near the line
+ for _ in range(int(spits)):
+ k = int(r.integers(n))
+ if wm is not None: break
+ rr = r.uniform(1.0, 2.6) * width / 4
+ ox, oy = r.normal(0, width * 2.2, 2)
+ buf = np.zeros((h, w), np.float32)
+ _disc_splat(buf, x[k] - xa + ox, y[k] - ya + oy, rr, 1.0, 'max')
+ self._deposit(sl, buf * 4, colour)
+ # drips where the hand paused
+ if drips > 0 and wm is None:
+ heavy = np.argsort(sp)[: max(1, n // 40)]
+ cnt = 0
+ for k in heavy:
+ if r.random() > drips * 0.5 or cnt > 3 * drips: continue
+ cnt += 1
+ self._drip(x[k], y[k] + width * 0.4, r.uniform(25, 110) * drip_len, width * r.uniform(0.45, 0.7),
+ colour, self._seed())
+
+ def buff(self, x0, y0, x1, y1, colour='#8f8e8a', roller=64, ragged=26):
+ """a council roller patch over old graffiti: not-quite-matching grey laid on in vertical roller passes.
+ Each pass starts and stops at its own height, so the top and bottom edges are stepped; the ends of a pass
+ go dry and streaky; neighbouring passes overlap in slightly darker laps; the nap leaves a fine stipple.
+ Whatever was there before still ghosts through the thin places."""
+ r = self.rng
+ xa, xb = max(0, int(x0) - 20), min(self.W, int(x1) + 20)
+ ya, yb = max(0, int(y0) - ragged - 30), min(self.ground_y, int(y1) + ragged + 30)
+ h, w = yb - ya, xb - xa
+ yy = np.arange(h, dtype=np.float32)[:, None] + ya
+ xx = np.arange(w, dtype=np.float32)[None, :] + xa
+ streak = _aniso(h, w, 2.5, 50, 3, self._seed())
+ nap = noise2d(h, w, 3, 2, self._seed())
+ cover = np.zeros((h, w), np.float32)
+ laps = np.zeros((h, w), np.float32)
+ x = float(x0)
+ while x < x1 - roller * 0.3:
+ wd = roller * r.uniform(0.92, 1.05)
+ top = y0 + r.uniform(-ragged, ragged * 0.6); bot = y1 + r.uniform(-ragged * 0.6, ragged)
+ sx = x + r.normal(0, 3)
+ tilt = r.normal(0, 0.012)
+ cx = sx + (yy - y0) * tilt
+ across = np.clip(np.minimum(xx - cx, cx + wd - xx) + 0.5, 0, 1)
+ dry = 14.0 # the ends of a pass run dry
+ along = smoothstep(0, 1, (np.minimum(yy - top, bot - yy) + streak * dry) / dry)
+ p = across * along
+ laps += p
+ cover = np.maximum(cover, p)
+ x += wd * r.uniform(0.82, 0.92) # passes overlap a little
+ laps = np.clip(laps - 1, 0, 1)
+ cover = np.clip(cover * (0.82 + 0.12 * nap) + 0.06 * laps, 0, 1)
+ sl = (slice(ya, yb), slice(xa, xb))
+ col = _c(colour) * (1 + 0.03 * (noise2d(h, w, 90, 3, self._seed()) - 0.5))[..., None] * (1 - 0.05 * laps[..., None])
+ self.alb[sl] = self.alb[sl] * (1 - cover[..., None]) + col * cover[..., None]
+ self.gloss[sl] *= 1 - cover * 0.8
+ self.pit[sl] *= 1 - 0.6 * cover # roller paint fills the small pits
+
+ # ------------------------------------------------------------ the card on the wall (for snapshots)
+ def _card_overlay(self, img, card):
+ """the stencil still taped up: the card (its own colour, caked with this and older overspray), masking
+ tape, and the shadow the lifted card throws on the wall and into its openings"""
+ if not hasattr(card, 'last'): return img
+ lt = card.last
+ sl, lsl = lt['sl'], lt['lsl']
+ idx, idy = lt['offset']
+ op, sheet = lt['op'], lt['sheet']
+ solid = np.clip(sheet - op, 0, 1)
+ h, w = solid.shape
+ base = _c('#d9c69a') if card.material == 'manila' else _c('#b9b4aa')
+ fib = noise2d(h, w, 3, 2, card.seed + 5)
+ old = smoothstep(0.55, 0.85, noise2d(h, w, 70, 3, card.seed + 6)) * 0.55
+ cardc = base[None, None, :] * (0.94 + 0.08 * fib[..., None])
+ cardc = cardc * (1 - old[..., None]) + _c('#2b2b2b') * old[..., None] * 0.9 + cardc * old[..., None] * 0.1
+ paint = 0.82 * (1 - np.exp(-0.55 * lt['D'])) * (0.85 + 0.3 * fib) # dusty: the card shows through
+ cardc = cardc * (1 - paint[..., None]) + _c(lt['colour']) * paint[..., None]
+ # the cut edges: the card's thickness catches the light on the lit side of every opening
+ bs = blur(solid, 0.8)
+ lit = np.clip(bs - shift(bs, -2, -2), 0, 1)
+ dark = np.clip(bs - shift(bs, 2, 2), 0, 1)
+ cardc = cardc + (0.42 * lit)[..., None] - (0.25 * dark * cardc.mean(-1))[..., None]
+ out = img[sl].copy()
+ sh = np.clip(shift(solid, 4, 5) - solid, 0, 1)
+ sh = blur(sh, 2.5) * 0.45 * (1 - solid)
+ out *= (1 - sh)[..., None]
+ out = out * (1 - solid[..., None]) + cardc * solid[..., None]
+ img = img.copy(); img[sl] = out
+ # masking tape across the corners
+ for tx, ty in card.tape:
+ gx, gy = card.x0 + idx + tx, card.y0 + idy + ty
+ a = np.radians(self.rng.uniform(-35, 35) + (45 if (tx in (0, card.w)) and (ty in (0, card.h)) else 0))
+ Lt, Wt = 70, 26
+ corners = [(-Lt / 2, -Wt / 2), (Lt / 2, -Wt / 2), (Lt / 2, Wt / 2), (-Lt / 2, Wt / 2)]
+ pts = [(gx + u * np.cos(a) - v * np.sin(a), gy + u * np.sin(a) + v * np.cos(a)) for u, v in corners]
+ im = Image.new('L', (self.W, self.H), 0)
+ ImageDraw.Draw(im).polygon(pts, fill=255)
+ m = blur(np.asarray(im, np.float32) / 255, 0.7)
+ ys, xs = np.nonzero(m > 0.01)
+ if not len(ys): continue
+ ts = (slice(ys.min(), ys.max() + 1), slice(xs.min(), xs.max() + 1))
+ mt = m[ts][..., None]
+ tc = _c('#e4d6ad') * (0.95 + 0.05 * self.U[ts][..., None])
+ img[ts] = img[ts] * (1 - 0.88 * mt) + tc * 0.88 * mt
+ return img
+
+ # ------------------------------------------------------------ output
+ def composite(self):
+ n = height_normals(self.hgt)
+ l = self.light
+ ndl = n[..., 0] * l[0] + n[..., 1] * l[1] + n[..., 2] * l[2]
+ rel = ndl / l[2]
+ shade = 1 + 0.9 * (rel - 1)
+ sh = height_shadow(self.hgt, tuple(l), reach=26, step=1.5, soft=1.2)
+ shade *= 1 - 0.38 * sh
+ cav = np.clip((blur(self.hgt, 3) - self.hgt) / 4.0, 0, 1)
+ shade *= 1 - 0.35 * cav
+ sheen = self.gloss * np.clip(rel - 1, 0, 1) * 0.9 + self.gloss * 0.015
+ g = self.gmask
+ shade = shade * (1 - g) + g * 1.08
+ img = self.alb * shade[..., None] + sheen[..., None]
+ H, W = self.H, self.W
+ Y, X = np.mgrid[0:H, 0:W].astype(np.float32)
+ day = 1.05 - 0.10 * (X / W * 0.6 + Y / H * 0.4)
+ vig = 1 - 0.16 * (((X - W / 2) / (W / 2)) ** 2 + ((Y - H / 2) / (H / 2)) ** 2) ** 1.5 * 0.5
+ img = img * (day * vig)[..., None]
+ img = img * np.array([1.0, 0.995, 0.975], np.float32) # afternoon sun, a hair warm
+ return np.clip(img, 0, 1).astype(np.float32)
+
+ def _to_image(self, img):
+ grain = (self.U - 0.5) * 0.018
+ return Image.fromarray((np.clip(img + grain[..., None], 0, 1) * 255 + 0.5).astype(np.uint8))
+
+ def stage(self, name, card=None):
+ img = self.composite()
+ if card is not None: img = self._card_overlay(img, card)
+ self.stages.append((name, self._to_image(img)))
+
+ def save(self, path, stages_dir=None, quality=88):
+ img = self._to_image(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
diff --git a/lib/tomb.py b/lib/tomb.py
new file mode 100644
index 0000000..070ba32
--- /dev/null
+++ b/lib/tomb.py
@@ -0,0 +1,1612 @@
+"""tomb -- an Egyptian tomb wall painting, Theban New Kingdom style (numpy + Pillow only).
+
+The wall is built the way the painters of the Theban necropolis built it, layer by layer, and every layer stays
+in memory so that 3,300 years of damage can later take the top ones away again.
+
+Model:
+ wall rough mud plaster (brown, chopped straw, grit) under a thin skin of fine gypsum plaster (warm white,
+ trowel undulation, pits); `under` keeps this plaster plus everything drawn straight onto it.
+ grid before anything was drawn, red-ochre cords were snapped onto the plaster: a squared grid whose cell is
+ one canon unit of the figures in that area (18 units from sole to hairline), plus register guide lines.
+ sketch the outline draughtsman drew every figure, animal, plant and sign in thin red ochre, searching a
+ little (a second, lighter pass a pixel or two off); hidden parts are sketched too.
+ ground the background wash (yellow ochre, or the bluish white of some tombs) brushed round the figures in
+ broad, patchy sweeps -- the shapes still to be coloured are left as bare plaster with their red sketch;
+ the wash is not perfectly opaque, so streaks of plaster and the grid ghost through.
+ colour secco (dry) painting, one pigment pot at a time: red-ochre skin of men, yellow ochre of women, white
+ linen, orpiment yellow, Egyptian blue (coarse, glittery grains), green frit, carbon black. Each fill is
+ flat and matte with brush streaks, mottling and grain; edges wander a pixel over or short of the line.
+ Fills are z-ordered (a per-pixel z map), so pigments can be laid in any order and still overlap right.
+ Linen can be translucent: the leg shows through a pleated overkilt.
+ ink the final outline: confident, nearly even lines (red-brown round the skin, black everywhere else)
+ masked by whatever is painted above them, so overlapping parts read correctly.
+ canon figures follow the composite view: profile head with a frontal eye and kohl line, frontal shoulders and
+ collar, torso turning to profile at the waist, profile legs with both feet seen from the big-toe side.
+ Poses are joint positions in canon units (sole = 0, hairline = 18), elbows found by two-bone IK.
+ props what the figures hold and work with, each anchored to the figure's hands / canon units: staff, sickle,
+ the inverted-V hoe, plough rods, baskets, tied grain sacks, a grain measure (heqat) with a poured stream,
+ winnowing scoops, papyrus and palette; long-horned oxen (far legs a step apart so all four show), a
+ standing emmer field with stubble and stalks gathered into a reaper's fist, sheaves, grain heaps,
+ a sycamore with scale-like rows of leaves and a waterskin, papyrus clumps.
+ frame the decorative system round the scenes: block border, kheker frieze, striped register bands, a river
+ band with zigzag water, fish and lotus.
+ text hieroglyphs drawn as small polychrome signs (reed leaf, water, mouth, loaf, chick, owl, viper, foot,
+ basket, house, hand, cloth, sun, sickle, grain, jar, scroll, pool, flax, bolt, hoe, numerals ...),
+ laid out in columns by quadrats (tall signs paired, flat signs stacked). The text is pseudo-text.
+ age what time does: paint flakes off in clusters (blue and the crack edges first), deeper flakes down to the
+ plaster (where the red grid and sketch reappear; `zones` places a few on purpose), paint rubbed thin in
+ soft patches, plaster losses down to the straw-tempered mud as a real height field (a broken gypsum rim,
+ paint flaked back in steps around it, cast shadow on the upper-left inner wall), cracks with a dark
+ groove and a lit lip, blue decaying toward grey-green, soot and grime near the ceiling, a moisture
+ tide-line and salt bloom near the floor, fly specks, a lamp-lit falloff to the corners.
+
+ from tomb import TombPainting
+ tp = TombPainting(1920, 1080, seed=3)
+ tp.wall(); tp.grid((100, 100, 900, 600), cell=12, base=600)
+ f = tp.figure(400, 600, 216, 'walk', facing=1) # declare (nothing is painted yet)
+ tp.column(600, 120, 650, 560, n=7) # a column of pseudo-hieroglyphs
+ tp.sketch(); tp.ground('#d8bd84')
+ tp.colour(); tp.ink(); tp.colour(layer='text'); tp.ink(layer='text')
+ tp.age(); tp.save('out.png')
+"""
+import numpy as np
+from PIL import Image, ImageDraw
+from core import blur, fbm1d, spline, noise2d, smoothstep, shift, height_shadow
+
+PIGMENTS = {
+ 'skin': '#a24e2c', # red ochre: men
+ 'skin_f': '#d6a45a', # yellow ochre: women
+ 'red': '#ad4129',
+ 'brown': '#7b4a2c',
+ 'ochre': '#c48a3a',
+ 'yellow': '#dfb245', # orpiment
+ 'linen': '#ebe2cc',
+ 'white': '#efe8d8',
+ 'blue': '#2c5d9a', # Egyptian blue
+ 'lblue': '#6f9cc4',
+ 'green': '#3b8566', # green frit / malachite
+ 'lgreen': '#7eaa6a',
+ 'dkgreen': '#2f6e50',
+ 'black': '#211c1a',
+ 'grey': '#8d8b84',
+}
+INK, REDLINE, SKETCH = '#201a17', '#5e2412', '#b3533a'
+
+# mottle streak grain opacity thin (thin: how much a streak thins the coat)
+_TEX = {'skin': (0.07, 0.05, 0.04, 0.97, 0.05), 'skin_f': (0.07, 0.05, 0.04, 0.96, 0.06),
+ 'red': (0.07, 0.05, 0.05, 0.97, 0.05), 'brown': (0.08, 0.05, 0.05, 0.97, 0.04),
+ 'ochre': (0.07, 0.05, 0.05, 0.96, 0.05), 'yellow': (0.06, 0.05, 0.06, 0.95, 0.07),
+ 'linen': (0.035, 0.04, 0.018, 0.90, 0.10), 'white': (0.035, 0.04, 0.02, 0.93, 0.08),
+ 'blue': (0.10, 0.06, 0.06, 0.97, 0.04), 'lblue': (0.08, 0.05, 0.05, 0.95, 0.05),
+ 'green': (0.09, 0.06, 0.05, 0.97, 0.04), 'lgreen': (0.08, 0.05, 0.05, 0.95, 0.05),
+ 'dkgreen': (0.08, 0.05, 0.12, 0.97, 0.04),
+ 'black': (0.05, 0.06, 0.04, 0.97, 0.04), 'grey': (0.06, 0.05, 0.05, 0.95, 0.05)}
+
+
+_CRYST = {'blue': 0.22, 'lblue': 0.14, 'green': 0.15, 'lgreen': 0.1, 'dkgreen': 0.12}
+
+
+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(PIGMENTS.get(c, c))
+ return np.asarray(c, np.float32)
+
+
+def _closed_spline(pts, per=8):
+ P = np.asarray(pts, np.float32)
+ ext = np.vstack([P[-2:], P, P[:2]])
+ out = spline(ext, per)
+ return out[2 * per:-2 * per - 1] if len(out) > 4 * per + 1 else out
+
+
+def _rot(v, a):
+ c, s = np.cos(a), np.sin(a)
+ v = np.asarray(v, np.float32)
+ return np.stack([v[..., 0] * c - v[..., 1] * s, v[..., 0] * s + v[..., 1] * c], -1)
+
+
+def _ik(S, W, a, b, bend):
+ """two-bone IK: joint between S and W with bone lengths a, b; bend = +1/-1 picks the side"""
+ S, W = np.asarray(S, np.float32), np.asarray(W, np.float32)
+ d = W - S; L = float(np.hypot(*d))
+ L = min(max(L, abs(a - b) + 1e-3), a + b - 1e-3)
+ u = d / (np.hypot(*d) + 1e-9)
+ x = (a * a - b * b + L * L) / (2 * L)
+ h = np.sqrt(max(a * a - x * x, 0))
+ n = np.array([-u[1], u[0]], np.float32) * bend
+ return S + u * x + n * h
+
+
+def _arc(P):
+ s = np.concatenate([[0], np.cumsum(np.hypot(*np.diff(P, axis=0).T))])
+ return s
+
+
+def _limb(joints, wf, wb, per=10, cap0=False):
+ """tapered limb along a smooth path through `joints` (units, y up).
+ wf / wb: lists of (fraction of path length, half width) for the front (+x-ish) and back sides.
+ returns (polygon, outline paths without the end caps)"""
+ P = spline(np.asarray(joints, np.float32), per)
+ s = _arc(P); t = s / (s[-1] + 1e-9)
+ T = np.gradient(P, axis=0); T /= np.hypot(T[:, 0], T[:, 1])[:, None] + 1e-9
+ N = np.stack([-T[:, 1], T[:, 0]], 1)
+ hf = np.interp(t, [k for k, _ in wf], [v for _, v in wf])
+ hb = np.interp(t, [k for k, _ in wb], [v for _, v in wb])
+ if np.mean(N[:, 0]) < 0: hf, hb = hb, hf # left normal points backward: swap sides
+ A = P + N * hf[:, None]; B = P - N * hb[:, None]
+ paths = [A, B]
+ poly = np.vstack([A, B[::-1]])
+ if cap0: # rounded end (shoulder): A[0] -> around the back -> B[0]
+ r = (hf[0] + hb[0]) / 2
+ ang0 = np.arctan2(N[0, 1], N[0, 0])
+ th = np.linspace(ang0, ang0 + np.pi, 14)
+ cap = P[0] + np.stack([np.cos(th), np.sin(th)], 1) * r
+ poly = np.vstack([A, B[::-1], cap[::-1][1:-1]])
+ paths = [np.vstack([A[::-1], cap[1:-1], B])]
+ return poly, paths
+
+
+# --------------------------------------------------------------------------- figure poses (canon units, x forward)
+POSES = {
+ # hip, lean (deg, + = forward), lead leg (knee, ankle, foot angle), back leg, wrists, elbow bends, hands
+ 'stand': dict(hip=(0.0, 9.0), lean=0, kf=(0.9, 5.9), af=(1.6, 0.85), kb=(-0.4, 5.9), ab=(-0.85, 0.85),
+ wf=(2.75, 8.7), wb=(-2.75, 8.7), bf=-1, bb=1, hf='open', hb='open'),
+ 'walk': dict(hip=(0.0, 9.0), lean=0, kf=(1.35, 5.9), af=(2.9, 0.85), kb=(-0.45, 5.9), ab=(-0.95, 0.85),
+ wf=(2.8, 8.7), wb=(-2.7, 8.7), bf=-1, bb=1, hf='open', hb='open'),
+ 'staff': dict(hip=(0.0, 9.0), lean=0, kf=(1.55, 5.9), af=(3.3, 0.85), kb=(-0.45, 5.9), ab=(-0.95, 0.85),
+ wf=(6.2, 13.4), wb=(-2.7, 8.8), bf=-1, bb=1, hf='fist', hb='fist'),
+ 'plough': dict(hip=(0.0, 8.7), lean=24, kf=(2.0, 5.5), af=(3.1, 0.85), kb=(-1.1, 5.4), ab=(-2.9, 0.85),
+ fb=22, wf=(7.3, 9.6), wb=(6.6, 9.2), bf=-1, bb=-1, hf='fist', hb='fist', cross=True),
+ 'reap': dict(hip=(0.0, 8.2), lean=36, kf=(2.2, 5.1), af=(3.0, 0.85), kb=(-1.0, 5.0), ab=(-2.1, 0.85),
+ fb=12, wf=(7.4, 9.0), wb=(6.5, 7.5), bf=-1, bb=-1, hf='fist', hb='fist', cross=True),
+ 'sow': dict(hip=(0.0, 9.0), lean=6, kf=(1.4, 5.9), af=(3.0, 0.85), kb=(-0.5, 5.9), ab=(-1.1, 0.85),
+ fb=8, wf=(6.6, 11.6), wb=(-1.0, 10.6), bf=-1, bb=1, hf='open', hb='fist'),
+ 'hoe': dict(hip=(0.0, 8.4), lean=40, kf=(2.2, 5.3), af=(3.2, 0.85), kb=(-1.0, 5.2), ab=(-2.4, 0.85),
+ fb=15, wf=(6.4, 8.4), wb=(4.9, 9.9), bf=-1, bb=-1, hf='fist', hb='fist', cross=True),
+ 'glean': dict(hip=(0.0, 8.6), lean=48, kf=(1.9, 5.4), af=(2.6, 0.85), kb=(-0.6, 5.3), ab=(-1.4, 0.85),
+ fb=10, wf=(7.0, 3.6), wb=(4.6, 6.4), bf=-1, bb=-1, hf='open', hb='fist', cross=True),
+ 'carry': dict(hip=(0.0, 9.0), lean=3, kf=(1.35, 5.9), af=(2.85, 0.85), kb=(-0.45, 5.9), ab=(-1.0, 0.85),
+ fb=6, wf=(2.9, 8.9), wb=(-2.7, 18.7), bf=-1, bb=1, hf='open', hb='fist'),
+ 'hold': dict(hip=(0.0, 9.0), lean=4, kf=(1.2, 5.9), af=(2.5, 0.85), kb=(-0.45, 5.9), ab=(-0.9, 0.85),
+ wf=(5.2, 10.6), wb=(4.4, 9.9), bf=-1, bb=-1, hf='fist', hb='fist', cross=True),
+ 'scoop': dict(hip=(0.0, 8.5), lean=34, kf=(2.0, 5.4), af=(2.9, 0.85), kb=(-1.0, 5.3), ab=(-2.0, 0.85),
+ fb=10, wf=(7.0, 10.6), wb=(6.0, 8.6), bf=-1, bb=-1, hf='fist', hb='fist', cross=True),
+ 'squat': dict(hip=(0.0, 1.35), lean=0, kf=(2.55, 4.95), af=(3.0, 0.85), kb=(3.7, 0.95), ab=(-0.25, 0.72),
+ mb=True, wf=(4.3, 5.75), wb=(3.0, 6.9), bf=-1, bb=-1, hf='fist', hb='fist', cross=True, seated=True,
+ turn=0.45),
+}
+
+
+class TombPainting:
+ def __init__(self, W=1920, H=1080, seed=0, ss=3, light=(-0.6, -0.8)):
+ self.W, self.H, self.ss = W, H, ss
+ self.rng = np.random.default_rng(seed)
+ self.light = np.asarray(light, np.float32) / np.hypot(*light)
+ self.parts = []
+ self._z = 1.0
+ self.stages = []
+ self.zmap = np.full((H, W), -1.0, np.float32)
+ self.bluemap = np.zeros((H, W), np.float32)
+ self.paintmap = np.zeros((H, W), np.float32)
+ sd = self._seed
+ self.T_mottle = noise2d(H, W, 80, 4, sd())
+ g = self.rng.random((H, W)).astype(np.float32)
+ self.T_grain = np.clip((blur(g, 0.6) - 0.5) * 3.2 + 0.5, 0, 1)
+ self.T_edge = noise2d(H, W, 5, 2, sd())
+ c = self.rng.random((H, W)).astype(np.float32)
+ self.T_cryst = blur((c > 0.94).astype(np.float32), 0.45) * 1.6 - blur((c < 0.05).astype(np.float32), 0.45) * 1.2
+ self.T_streak = {'h': self._streak(False), 'v': self._streak(True)}
+ self.img = np.ones((H, W, 3), np.float32) * hexc('#e4d9c3')
+ self.under = self.img.copy()
+ self.ground_img = self.img.copy()
+ self.plaster = self.img.copy()
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ def _streak(self, vertical):
+ H, W = self.H, self.W
+ out = np.zeros((H, W), np.float32)
+ for k, (a, b, amp) in enumerate([(3, 60, 1.0), (2, 22, 0.6), (8, 140, 0.5)]):
+ if vertical:
+ g = self.rng.random((H // b + 2, W // a + 2)).astype(np.float32)
+ else:
+ g = self.rng.random((H // a + 2, W // b + 2)).astype(np.float32)
+ out += amp * np.asarray(Image.fromarray(g).resize((W, H), Image.BICUBIC), np.float32)
+ out -= out.min(); out /= out.max() + 1e-6
+ return out
+
+ # ------------------------------------------------------------------ raster helpers
+ def _bbox(self, P, pad):
+ x0 = int(max(0, np.floor(P[:, 0].min() - pad))); x1 = int(min(self.W, np.ceil(P[:, 0].max() + pad)))
+ y0 = int(max(0, np.floor(P[:, 1].min() - pad))); y1 = int(min(self.H, np.ceil(P[:, 1].max() + pad)))
+ return x0, y0, x1, y1
+
+ def _poly_mask(self, polys, holes=(), box=None):
+ allp = np.vstack([np.asarray(p, np.float32) for p in polys])
+ x0, y0, x1, y1 = box or self._bbox(allp, 3)
+ if x1 <= x0 or y1 <= y0: return None
+ S = self.ss
+ im = Image.new('L', ((x1 - x0) * S, (y1 - y0) * S), 0)
+ d = ImageDraw.Draw(im)
+ for p, f in [(p, 255) for p in polys] + [(h, 0) for h in holes]:
+ p = np.asarray(p, np.float32)
+ if len(p) < 3: continue
+ d.polygon([((x - x0) * S, (y - y0) * S) for x, y in p], fill=f)
+ m = np.asarray(im.resize((x1 - x0, y1 - y0), Image.BOX), np.float32) / 255
+ return m, (x0, y0, x1, y1)
+
+ def _stroke_mask(self, paths, width, closed=False, var=0.14, taper=0.0, seed=0, box=None, jitter=0.0):
+ paths = [np.asarray(p, np.float32) for p in paths if len(p) >= 2]
+ if not paths: return None
+ allp = np.vstack(paths)
+ x0, y0, x1, y1 = box or self._bbox(allp, width + 3 + jitter)
+ if x1 <= x0 or y1 <= y0: return None
+ S = self.ss
+ im = Image.new('L', ((x1 - x0) * S, (y1 - y0) * S), 0)
+ d = ImageDraw.Draw(im)
+ r = np.random.default_rng(seed)
+ for P in paths:
+ if closed: P = np.vstack([P, P[:1]])
+ s = _arc(P); L = s[-1]
+ if L < 0.5: continue
+ n = max(2, int(L / max(0.45, width * 0.3)) + 1)
+ ss_ = np.linspace(0, L, n)
+ px = np.interp(ss_, s, P[:, 0]); py = np.interp(ss_, s, P[:, 1])
+ if jitter:
+ px = px + fbm1d(n, max(6, n / max(1, L / 30)), 2, int(r.integers(1 << 30))) * jitter
+ py = py + fbm1d(n, max(6, n / max(1, L / 30)), 2, int(r.integers(1 << 30))) * jitter
+ wv = width * (1 + var * fbm1d(n, max(4, n / max(1, L / 50)), 2, int(r.integers(1 << 30))))
+ if taper and not closed:
+ tp = np.clip(np.minimum(ss_, L - ss_) / max(taper, 1e-3), 0, 1)
+ wv = wv * (0.35 + 0.65 * tp)
+ rad = np.maximum(wv * 0.5 * S, 0.6)
+ X = (px - x0) * S; Y = (py - y0) * S
+ for xi, yi, ri in zip(X, Y, rad):
+ d.ellipse([xi - ri, yi - ri, xi + ri, yi + ri], fill=255)
+ m = np.asarray(im.resize((x1 - x0, y1 - y0), Image.BOX), np.float32) / 255
+ return m, (x0, y0, x1, y1)
+
+ # ------------------------------------------------------------------ the wall
+ def wall(self, plaster='#e6dcc6', mud='#74563c'):
+ """mud plaster under a skin of fine gypsum plaster"""
+ H, W = self.H, self.W
+ sd = self._seed
+ # mud: brown, lumpy, chopped straw and grit
+ m = np.ones((H, W, 3), np.float32) * hexc(mud)
+ lump = noise2d(H, W, 18, 4, sd())
+ m *= (0.72 + 0.45 * lump)[..., None]
+ m *= (0.84 + 0.3 * self.T_grain)[..., None]
+ straw = Image.new('L', (W, H), 0); d = ImageDraw.Draw(straw)
+ r = self.rng
+ for _ in range(int(W * H / 900)):
+ x, y = r.uniform(0, W), r.uniform(0, H); a = r.uniform(0, np.pi); L = r.uniform(4, 16)
+ d.line([(x, y), (x + np.cos(a) * L, y + np.sin(a) * L)], fill=int(r.uniform(90, 200)), width=1)
+ st = np.asarray(straw, np.float32) / 255
+ m = m * (1 - 0.55 * st[..., None]) + hexc('#c9a86c') * 0.55 * st[..., None]
+ grit = (r.random((H, W)) > 0.985).astype(np.float32)
+ m *= (1 - 0.35 * blur(grit, 0.5))[..., None]
+ hm = blur(lump, 1.0) * 10 + blur(noise2d(H, W, 4, 2, sd()), 0.6) * 2.5
+ gy, gx = np.gradient(hm)
+ m *= np.clip(1 + 1.1 * (gx * self.light[0] + gy * self.light[1]), 0.55, 1.45)[..., None]
+ self.mud = np.clip(m, 0, 1)
+ # gypsum plaster skin
+ p = np.ones((H, W, 3), np.float32) * hexc(plaster)
+ und = noise2d(H, W, 260, 3, sd()) # trowel undulation
+ stain = noise2d(H, W, 140, 4, sd())
+ p *= (0.95 + 0.07 * und)[..., None]
+ p = p * (1 - 0.08 * smoothstep(0.55, 0.85, stain)[..., None]) + hexc('#d7b98e') * 0.08 * smoothstep(0.55, 0.85, stain)[..., None]
+ relief = blur(noise2d(H, W, 7, 3, sd()), 1.2) * 1.2 + und * 8
+ pits = (r.random((H, W)) > 0.998).astype(np.float32)
+ relief -= blur(pits, 0.9) * 2
+ gy, gx = np.gradient(relief)
+ p *= np.clip(1 + 0.3 * (gx * self.light[0] + gy * self.light[1]), 0.88, 1.12)[..., None]
+ p *= (0.985 + 0.03 * self.T_grain)[..., None]
+ self.plaster = np.clip(p, 0, 1)
+ self.under = self.plaster.copy()
+ self.img = self.plaster.copy()
+ self.ground_img = self.img.copy()
+
+ def _draw_under(self, m, box, colour, alpha):
+ x0, y0, x1, y1 = box
+ col = _c(colour)
+ a = (m * alpha)[..., None]
+ for buf in (self.under, self.img):
+ sl = buf[y0:y1, x0:x1]
+ sl[:] = sl * (1 - a) + col * a
+
+ def grid(self, box, cell, base=None, colour=SKETCH, alpha=0.42, width=1.1):
+ """red-ochre squaring grid snapped onto the plaster, aligned to a baseline"""
+ x0, y0, x1, y1 = box
+ base = y1 if base is None else base
+ paths = []
+ k0 = int(np.floor((y0 - base) / cell)); k1 = int(np.ceil((y1 - base) / cell))
+ for k in range(k0, k1 + 1):
+ y = base + k * cell
+ if y0 - 0.5 <= y <= y1 + 0.5: paths.append(np.array([[x0, y], [x1, y]], np.float32))
+ x = x0
+ while x <= x1 + 0.5:
+ paths.append(np.array([[x, y0], [x, y1]], np.float32)); x += cell
+ res = self._stroke_mask(paths, width, var=0.25, seed=self._seed())
+ if res:
+ m, b = res
+ m = m * (0.6 + 0.4 * self.T_mottle[b[1]:b[3], b[0]:b[2]])
+ self._draw_under(m, b, colour, alpha)
+
+ def guide(self, p0, p1, colour=SKETCH, alpha=0.5, width=1.2):
+ res = self._stroke_mask([np.array([p0, p1], np.float32)], width, var=0.3, seed=self._seed())
+ if res: self._draw_under(res[0], res[1], colour, alpha)
+
+ # ------------------------------------------------------------------ parts (declared, painted later)
+ def part(self, pts=None, colour=None, outline=True, paths=None, closed=None, ink=None, width=None,
+ z=None, alpha=None, clip=None, holes=(), layer='scene', sketch=True, streak=None, rag=1.0):
+ """declare one painted shape. pts: polygon (screen px) or None for a pure line part.
+ outline: True -> ink the polygon boundary; paths: explicit ink paths instead (open unless closed=True).
+ colour: pigment name (PIGMENTS key) or '#rrggbb'. clip: polygon or list of polygons that limit fill & ink.
+ z: stacking order (default: next). Returns the part dict."""
+ if z is None:
+ z = self._z; self._z += 1.0
+ multi = isinstance(pts, (list, tuple)) and len(pts) > 0 and np.asarray(pts[0]).ndim == 2
+ polys = None if pts is None else ([np.asarray(q, np.float32) for q in pts] if multi else [np.asarray(pts, np.float32)])
+ p = dict(pts=None if pts is None else polys[0], polys=polys, colour=colour, z=float(z),
+ ink=ink or INK, width=width or 2.0, alpha=alpha, clip=clip, holes=[np.asarray(h, np.float32) for h in holes],
+ layer=layer, sketch=sketch, streak=streak, rag=rag, painted=False, inked=False)
+ if paths is not None:
+ p['paths'] = [np.asarray(q, np.float32) for q in paths]
+ p['closed'] = bool(closed)
+ elif outline and pts is not None:
+ p['paths'] = list(polys); p['closed'] = True
+ else:
+ p['paths'] = []; p['closed'] = False
+ self.parts.append(p)
+ return p
+
+ def _clip_mask(self, clip, box):
+ if clip is None: return None
+ polys = clip if isinstance(clip, (list, tuple)) else [clip]
+ res = self._poly_mask(polys, box=box)
+ return res[0] if res else None
+
+ # ------------------------------------------------------------------ painting passes
+ def sketch(self, alpha=0.6, layer=None):
+ """red-ochre underdrawing of every declared part, with a lighter searching pass"""
+ for p in self.parts:
+ if not p['sketch'] or not p['paths'] or (layer and p['layer'] != layer): continue
+ w = max(1.0, p['width'] * 0.6)
+ for k, (a, j) in enumerate([(alpha, 0.5), (alpha * 0.45, 1.6)]):
+ if k == 1 and self.rng.random() > 0.5: continue
+ res = self._stroke_mask(p['paths'], w, closed=p['closed'], var=0.3, seed=self._seed(), jitter=j)
+ if res:
+ m, b = res
+ m = m * (0.55 + 0.45 * self.T_mottle[b[1]:b[3], b[0]:b[2]])
+ self._draw_under(m, b, SKETCH, a)
+
+ def ground(self, colour='#d6bb83', box=None, alpha=0.93, around=True):
+ """background wash brushed over the wall in broad strokes (not quite opaque). around: leave the declared
+ opaque shapes unwashed, as the painters did, so their red sketch stays visible until they are coloured"""
+ H, W = self.H, self.W
+ x0, y0, x1, y1 = box or (0, 0, W, H)
+ col = _c(colour)
+ st = 0.5 * self.T_streak['h'] + 0.5 * self.T_streak['v']
+ sweep = noise2d(H, W, 45, 3, self._seed())
+ # broad diagonal brush sweeps: a stretched noise rotated 30 degrees
+ g = np.zeros((H, W), np.float32)
+ for ang in (28, -34): # two directions of broad brush sweeps, patchy
+ gi = Image.fromarray(self.rng.random((H // 6 + 2, W // 50 + 2)).astype(np.float32)).resize((W * 2, H * 2), Image.BICUBIC)
+ gi = np.asarray(gi.rotate(ang, resample=Image.BILINEAR).resize((W, H), Image.BILINEAR), np.float32)
+ g += (gi - gi.mean()) / (gi.std() + 1e-6) * smoothstep(0.35, 0.65, noise2d(H, W, 200, 2, self._seed()))
+ g *= 0.5
+ a = np.clip(alpha + 0.05 * (self.T_mottle - 0.5) * 2 - 0.08 * smoothstep(0.6, 0.95, sweep) + 0.015 * g, 0, 1)
+ f = col * (1 + 0.07 * (self.T_mottle - 0.5) * 2 + 0.035 * (st - 0.5) * 2 + 0.03 * (self.T_grain - 0.5) + 0.012 * g)[..., None]
+ if around: # the painter brushed the ground round the figures
+ ex = Image.new('L', (W, H), 0); d = ImageDraw.Draw(ex)
+ for p in self.parts:
+ if p['polys'] is None or p['colour'] is None or p['alpha'] is not None or p['clip'] is not None: continue
+ for q in p['polys']:
+ if len(q) >= 3: d.polygon([(float(x), float(y)) for x, y in q], fill=255)
+ e = np.asarray(ex, np.float32) / 255
+ e = smoothstep(0.75, 1.0, blur(e, 1.6)) # pull in ~1.5 px: the wash runs under the edge
+ a = a * (1 - e)
+ sl = (slice(y0, y1), slice(x0, x1))
+ aa = a[sl][..., None]
+ self.img[sl] = self.img[sl] * (1 - aa) + np.clip(f[sl], 0, 1) * aa
+ self.ground_img = self.img.copy()
+ self.zmap[sl] = np.maximum(self.zmap[sl], 0)
+
+ def _fill(self, p):
+ if p['pts'] is None or p['colour'] is None: return
+ res = self._poly_mask(p['polys'], holes=p['holes'])
+ if res is None: return
+ m, (x0, y0, x1, y1) = res
+ cm = self._clip_mask(p['clip'], (x0, y0, x1, y1))
+ if cm is not None: m = m * cm
+ sl = (slice(y0, y1), slice(x0, x1))
+ name = p['colour'] if isinstance(p['colour'], str) and p['colour'] in PIGMENTS else None
+ mot, stk, grn, opa, thin = _TEX.get(name, (0.06, 0.05, 0.05, 0.96, 0.05))
+ if p['alpha'] is not None: opa = p['alpha']
+ col = _c(p['colour'])
+ h, w = m.shape
+ sdir = p['streak'] or ('v' if h > w * 1.3 else 'h')
+ st = self.T_streak[sdir][sl]
+ if p['rag'] > 0 and min(h, w) > 4: # brush edge wanders a pixel over / short of the line
+ mb = blur(m, 0.7)
+ m = smoothstep(0.32, 0.68, mb + (self.T_edge[sl] - 0.5) * 0.55 * p['rag'])
+ z = p['z']
+ vis = (self.zmap[sl] <= z).astype(np.float32)
+ a = m * vis * np.clip(opa - thin * smoothstep(0.55, 0.9, st), 0, 1)
+ shade = 1 + mot * (self.T_mottle[sl] - 0.5) * 2 + stk * (st - 0.5) * 2 + grn * (self.T_grain[sl] - 0.5) * 2
+ if name in _CRYST: shade = shade + _CRYST[name] * self.T_cryst[sl] # coarse frit crystals glitter
+ f = np.clip(col[None, None, :] * shade[..., None], 0, 1)
+ a3 = a[..., None]
+ self.img[sl] = self.img[sl] * (1 - a3) + f * a3
+ hit = (m > 0.5) & (vis > 0)
+ self.zmap[sl] = np.where(hit, z, self.zmap[sl])
+ self.paintmap[sl] = np.maximum(self.paintmap[sl], a)
+ if name in ('blue', 'lblue'):
+ self.bluemap[sl] = np.maximum(self.bluemap[sl] * (1 - a), a)
+ else:
+ self.bluemap[sl] *= (1 - a)
+
+ def _ink(self, p):
+ if not p['paths']: return
+ res = self._stroke_mask(p['paths'], p['width'], closed=p['closed'], var=0.16, seed=self._seed(),
+ taper=p['width'] * 2.5 if not p['closed'] else 0)
+ if res is None: return
+ m, (x0, y0, x1, y1) = res
+ cm = self._clip_mask(p['clip'], (x0, y0, x1, y1))
+ if cm is not None: m = m * cm
+ sl = (slice(y0, y1), slice(x0, x1))
+ vis = (self.zmap[sl] <= p['z'] + 1e-3).astype(np.float32)
+ a = m * vis * (0.86 + 0.14 * self.T_mottle[sl]) * (0.94 + 0.06 * self.T_grain[sl])
+ col = _c(p['ink'])
+ a3 = a[..., None]
+ self.img[sl] = self.img[sl] * (1 - a3) + col * a3
+ self.paintmap[sl] = np.maximum(self.paintmap[sl], a)
+ self.bluemap[sl] *= (1 - a)
+
+ def colour(self, pigments=None, layer='scene'):
+ """paint the fills of declared parts (only these pigments, if given), each once"""
+ if isinstance(pigments, str): pigments = [pigments]
+ for p in self.parts:
+ if p['painted'] or p['layer'] != layer: continue
+ if pigments is not None and p['colour'] not in pigments: continue
+ self._fill(p); p['painted'] = True
+
+ def ink(self, layer='scene'):
+ """the final outlines of every painted part of this layer"""
+ for p in self.parts:
+ if p['inked'] or p['layer'] != layer: continue
+ self._ink(p); p['inked'] = True
+
+ # ------------------------------------------------------------------ figures
+ def figure(self, x, y, height, pose='walk', facing=1, skin='skin', sex='m', wig='short', dress='kilt',
+ collar=True, z=None, lw=None, apron=True, **over):
+ """a figure in the composite view. (x, y): point on the baseline under the hip; height: sole to top of
+ the wig in px; facing +1 right / -1 left. pose: a POSES name, overridden by keyword args (same keys).
+ dress: 'kilt' | 'long' (calf-length translucent overkilt) | 'loin' | 'dress' (women's sheath).
+ wig: 'short' | 'long' | 'woman' | 'cap'. Returns a dict of anchor points (screen px) and z values."""
+ P = dict(POSES[pose]); P.update(over)
+ u = height / 19.6
+ F = 1 if facing >= 0 else -1
+ fem = sex == 'f'
+ lw = lw or float(np.clip(0.14 * u, 1.6, 3.6))
+ z0 = self._z if z is None else z
+ self._z = z0 + 20
+
+ def S(pt):
+ pt = np.asarray(pt, np.float32)
+ return np.stack([x + F * u * pt[..., 0], y - u * pt[..., 1]], -1)
+
+ lean = np.radians(P['lean'])
+ hip = np.array(P['hip'], np.float32)
+ wk = 1 - 0.85 * float(smoothstep(4, 32, P['lean'])) # bending figures turn toward profile: narrower shoulders
+ if 'turn' in P: wk = 1 - P['turn']
+
+ def T(pt): # torso frame -> body units
+ return hip + _rot(np.asarray(pt, np.float32), -lean)
+
+ def narrow(pts):
+ q = np.array(pts, np.float32)
+ ax = np.abs(q[:, 0]); s = np.sign(q[:, 0])
+ q[:, 0] = s * (np.minimum(ax, 1.45) + np.maximum(ax - 1.45, 0) * wk)
+ return q
+
+ sk = 'skin_f' if fem else skin
+ skin_ink = REDLINE if not fem else '#7a3f1c'
+ k = 0.88 if fem else 1.0
+ out = {'u': u, 'z0': z0}
+
+ def add(pts, colour, z, paths=None, closed=None, ink=INK, alpha=None, outline=True, clip=None, width=None):
+ pts_s = S(pts) if pts is not None else None
+ pths = [S(q) for q in paths] if paths is not None else None
+ clip_s = None if clip is None else ([S(c) for c in clip] if isinstance(clip, list) else S(clip))
+ return self.part(pts_s, colour, outline=outline, paths=pths, closed=closed, ink=ink, width=width or lw,
+ z=z0 + z, alpha=alpha, clip=clip_s)
+
+ # ---- legs (lead leg first: it is the far one)
+ legs = {}
+ for side, zz in (('f', 0.0), ('b', 1.0)):
+ hj = T((0.45 * (1 if side == 'f' else -1), 0.25))
+ knee = np.array(P['k' + side], np.float32); ank = np.array(P['a' + side], np.float32)
+ wf = [(0, 1.05 * k), (0.22, 0.95 * k), (0.42, 0.56 * k), (0.58, 0.55 * k), (0.97, 0.36 * k), (1, 0.36 * k)]
+ wb = [(0, 1.05 * k), (0.22, 0.9 * k), (0.42, 0.6 * k), (0.56, 0.86 * k), (0.97, 0.36 * k), (1, 0.36 * k)]
+ poly, paths = _limb([hj, knee, ank - (0, 0.3)], wf, wb)
+ legs[side] = (hj, knee, ank)
+ add(poly, sk, zz, paths=paths, ink=skin_ink)
+ fa = np.radians(P.get('f' + side, 0))
+ foot = np.array([(-0.32, 0.12), (-0.62, -0.25), (-0.78, -0.62), (-0.66, -0.85), (0.9, -0.85), (1.9, -0.85),
+ (2.42, -0.8), (2.5, -0.68), (2.36, -0.58), (1.25, -0.33), (0.36, 0.12)], np.float32)
+ foot[:, 0] *= 0.95 * k
+ ball = np.array([1.8, -0.85], np.float32)
+ if fa:
+ foot = ball + _rot(foot - ball, fa)
+ mir = P.get('m' + side, False)
+ if mir: foot[:, 0] *= -1 # foot tucked under, toes pointing back
+ fp = foot + ank
+ add(fp, sk, zz + 0.05, paths=[fp[:-1], ], ink=skin_ink)
+ toe = (np.array([[1.95, -0.62], [2.38, -0.66]], np.float32) - ball)
+ toe = (ball + _rot(toe, fa) if fa else toe + ball)
+ if mir: toe[:, 0] *= -1
+ add(None, None, zz + 0.06, paths=[toe + ank], ink=skin_ink, width=lw * 0.7)
+ out['foot_' + side] = S(fp)
+ # ---- torso
+ if fem:
+ tp = [(1.15, 0.0), (1.25, 1.1), (1.05, 2.1), (1.3, 3.5), (2.05, 4.0), (2.15, 4.55), (1.7, 5.0), (2.35, 5.55),
+ (2.25, 6.25), (1.05, 6.7), (0.5, 6.95), (-0.45, 7.0), (-1.05, 6.7), (-2.3, 6.25), (-2.45, 5.55),
+ (-1.8, 5.0), (-1.15, 3.6), (-0.95, 2.1), (-1.4, 0.6), (-1.25, 0.0)]
+ else:
+ tp = [(1.25, 0.0), (1.36, 1.15), (1.08, 2.1), (1.45, 3.6), (1.95, 4.45), (2.15, 5.0), (3.0, 5.6), (2.85, 6.3),
+ (1.2, 6.75), (0.55, 7.0), (-0.45, 7.05), (-1.2, 6.75), (-2.85, 6.3), (-3.05, 5.6), (-2.1, 5.0),
+ (-1.35, 3.6), (-0.95, 2.1), (-1.45, 0.6), (-1.3, 0.0)]
+ torso = T(_closed_spline(narrow(tp), 6))
+ add(torso, sk, 2.0, ink=skin_ink)
+ if not fem: # nipple: a small dot on the chest profile
+ nip = T(np.array([(1.62, 4.38)], np.float32))[0]
+ th = np.linspace(0, 2 * np.pi, 10)
+ add(nip + np.stack([np.cos(th), np.sin(th)], 1) * 0.11, skin_ink, 2.1, outline=False)
+ else:
+ th = np.linspace(-0.3, 1.9, 12)
+ add(None, None, 2.1, paths=[T(np.stack([1.75 + 0.42 * np.cos(th) - 0.42, 4.25 + 0.4 * np.sin(th) - 0.05], 1) * 1.0)],
+ ink=skin_ink, width=lw * 0.6)
+ # ---- dress / kilt
+ def legpt(side, frac, off):
+ hj, kn, an = legs[side]
+ Pp = spline(np.array([hj, kn, an], np.float32), 10)
+ s = _arc(Pp); t = s / s[-1]
+ q = np.array([np.interp(frac, t, Pp[:, 0]), np.interp(frac, t, Pp[:, 1])], np.float32)
+ i = min(int(np.searchsorted(t, frac)), len(Pp) - 2)
+ tg = Pp[i + 1] - Pp[i]; tg /= np.hypot(*tg) + 1e-9
+ n = np.array([-tg[1], tg[0]], np.float32)
+ if n[0] < 0: n = -n
+ return q + n * off
+ if dress in ('kilt', 'long', 'loin'):
+ hf = {'kilt': 0.3, 'long': 0.74, 'loin': 0.18}[dress]
+ seated = P.get('seated', False)
+ if seated:
+ hemF = legpt('f', 0.52, 1.1); hemB = legpt('b', 0.18, -1.1)
+ kp = [T((-1.2, 2.35)), T((1.25, 2.05)), legpt('f', 0.52, -1.1), hemF, legpt('b', 0.18, 1.05),
+ hemB, T((-1.7, 0.4))]
+ else:
+ hemF = legpt('f', hf, 1.45 * k); hemB = legpt('b', hf, -(1.2 * k))
+ kp = [T((-1.2, 2.35)), T((1.3, 2.05)), T((1.62, 0.85)), hemF, hemB, T((-1.72, 0.5))]
+ kilt = np.array(kp, np.float32)
+ if dress != 'loin': # round the corners a little, keep the edges straight
+ kilt = _closed_spline(np.vstack([kilt[i] * 0.8 + kilt[(i + 1) % len(kilt)] * 0.2 if j else kilt[i]
+ for i in range(len(kilt)) for j in (0, 1)]), 3)
+ add(kilt, 'linen', 3.0, alpha=0.78 if dress == 'long' else None)
+ if dress == 'long':
+ inner_f = legpt('f', 0.34, 1.0); inner_b = legpt('b', 0.34, -1.05)
+ short = np.array([T((-1.2, 2.35)), T((1.3, 2.05)), T((1.5, 0.9)), inner_f, inner_b, T((-1.6, 0.5))])
+ add(_closed_spline(short, 4), 'linen', 3.1)
+ for i in range(7): # pleats of the overkilt
+ a0 = T((1.2 - i * 0.32, 1.9)); a1 = hemF + (hemB - hemF) * (0.12 + i * 0.13)
+ add(None, None, 3.2, paths=[np.array([a0, a1])], ink='#b9a58c', width=lw * 0.5,
+ clip=kilt)
+ belt = [T((-1.2, 2.35)), T((1.3, 2.05)), T((1.32, 2.5)), T((-1.18, 2.8))]
+ add(np.array(belt), 'linen' if dress != 'long' else 'red', 3.3)
+ if apron and dress == 'kilt' and not seated:
+ ap = [T((1.0, 2.05)), T((1.45, 1.0)), hemF + (hemB - hemF) * 0.02, hemF + (hemB - hemF) * 0.32]
+ add(None, None, 3.25, paths=[np.array([ap[0], ap[3]])], ink=INK, width=lw * 0.7)
+ for i in range(3):
+ a0 = T((0.75 - 0.25 * i, 2.0)); a1 = hemF + (hemB - hemF) * (0.1 + 0.07 * i)
+ add(None, None, 3.25, paths=[np.array([a0, a1])], ink='#b9a58c', width=lw * 0.45, clip=kilt)
+ out['kilt'] = S(kilt)
+ elif dress == 'dress':
+ hemF = legpt('f', 0.93, 1.2); hemB = legpt('b', 0.93, -1.2)
+ kneeF = legpt('f', 0.45, 1.05)
+ dp = [T((-1.3, 4.75)), T((1.75, 4.6)), T((1.4, 3.0)), T((1.4, 1.2)), kneeF, hemF, hemB,
+ legpt('b', 0.45, -1.15), T((-1.55, 0.6)), T((-1.15, 2.4))]
+ dr = _closed_spline(np.array(dp), 4)
+ add(dr, 'linen', 3.0, alpha=0.84)
+ for s_ in (-1.0, 0.9): # shoulder straps
+ add(None, None, 3.2, paths=[np.array([T((s_ * 0.55, 6.6)), T((s_ * 0.9 + 0.25, 4.7))])],
+ ink='#e9e0cc', width=lw * 1.6)
+ out['kilt'] = S(dr)
+ # ---- arms
+ cross = P.get('cross', False)
+ for side, zz in (('f', 4.0), ('b', 6.5 if cross else 4.5)):
+ full = (2.0 if fem else 2.42) * (1 if side == 'f' else -1)
+ prof = 0.8 if side == 'f' else 0.05 # in profile both shoulders sit over the chest
+ sh = T((prof + (full - prof) * wk, 6.0 - 0.25 * (1 - wk)))
+ wr = np.array(P['w' + side], np.float32)
+ el = _ik(sh, wr, 3.35, 3.05, P['b' + side])
+ poly, paths = _limb([sh, el, wr], [(0, 0.66 * k), (0.25, 0.56 * k), (0.52, 0.43 * k), (0.68, 0.47 * k), (1, 0.31 * k)],
+ [(0, 0.66 * k), (0.25, 0.56 * k), (0.52, 0.43 * k), (0.68, 0.45 * k), (1, 0.31 * k)],
+ cap0=True)
+ add(poly, sk, zz, paths=paths, ink=skin_ink)
+ d = wr - el; d /= np.hypot(*d) + 1e-9
+ ang = np.arctan2(d[1], d[0])
+ hand = P.get('h' + side, 'open')
+ if hand == 'open':
+ hp = np.array([(-0.25, -0.3), (0.75, -0.33), (1.55, -0.24), (1.85, -0.12), (1.9, 0.0), (1.75, 0.12),
+ (1.05, 0.22), (0.6, 0.33), (-0.25, 0.3)], np.float32)
+ th_ = np.array([(0.25, 0.26), (0.7, 0.58), (1.05, 0.64), (1.12, 0.52), (0.75, 0.32)], np.float32)
+ else:
+ hp = np.array([(-0.25, -0.32), (0.5, -0.43), (0.92, -0.4), (1.08, -0.12), (1.04, 0.24), (0.78, 0.4),
+ (0.3, 0.38), (-0.25, 0.3)], np.float32)
+ th_ = np.array([(0.35, 0.3), (0.85, 0.48), (1.02, 0.36), (0.6, 0.22)], np.float32)
+ sgn = 1.0 if (np.cos(ang) >= -0.2) else -1.0 # thumb up for forward arms
+ hp[:, 1] *= sgn; th_[:, 1] *= sgn
+ hp *= k; th_ *= k
+ hpw = wr + _rot(hp, ang); thw = wr + _rot(th_, ang)
+ add(hpw, sk, zz + 0.02, paths=[hpw[1:-1]], ink=skin_ink)
+ add(thw, sk, zz + 0.03, paths=[thw[1:-1]], ink=skin_ink)
+ if hand != 'open':
+ fl = wr + _rot(np.array([(0.95, -0.3 * sgn), (0.55, -0.05 * sgn), (0.95, 0.15 * sgn)], np.float32) * k, ang)
+ add(None, None, zz + 0.04, paths=[fl[:2]], ink=skin_ink, width=lw * 0.6)
+ out['hand_' + side] = S(wr + _rot(np.array([0.55 * k, 0.0], np.float32), ang))
+ out['wrist_' + side] = S(wr)
+ out['z_hand_' + side] = z0 + zz + 0.02
+ out['dir_' + side] = np.array([F * d[0], -d[1]], np.float32)
+ # ---- collar
+ if collar:
+ cc = (0.0, 6.75)
+ bands = [('blue', 0.62, 0.95), ('red', 0.95, 1.28), ('green', 1.28, 1.62), ('blue', 1.62, 1.95)]
+ if u < 16: bands = [('blue', 0.62, 1.05), ('red', 1.05, 1.45), ('green', 1.45, 1.95)]
+ th = np.linspace(np.pi * 1.03, np.pi * 1.97, 40)
+ sy = 0.78
+ for i, (cl, r0, r1) in enumerate(bands):
+ r0 *= k; r1 *= k
+ cx_ = 1.18 * (0.55 + 0.45 * wk)
+ outer = np.stack([cc[0] + np.cos(th) * r1 * cx_, cc[1] + np.sin(th) * r1 * sy], 1)
+ inner = np.stack([cc[0] + np.cos(th) * r0 * cx_, cc[1] + np.sin(th) * r0 * sy], 1)[::-1]
+ band = T(np.vstack([outer, inner]))
+ add(band, cl, 5.0 + i * 0.01, width=lw * 0.6)
+ if u >= 16: # drop beads on the outer edge
+ rr = bands[-1][2] * k
+ for a in np.linspace(np.pi * 1.08, np.pi * 1.92, 13):
+ c0 = np.array([cc[0] + np.cos(a) * rr * cx_, cc[1] + np.sin(a) * rr * sy])
+ dd = np.array([np.cos(a) * cx_, np.sin(a) * sy]); dd /= np.hypot(*dd)
+ nn = np.array([-dd[1], dd[0]])
+ drop = np.array([c0 - nn * 0.12, c0 + dd * 0.32 - nn * 0.1, c0 + dd * 0.42, c0 + dd * 0.32 + nn * 0.1,
+ c0 + nn * 0.12])
+ add(T(drop), 'yellow' if int(a * 10) % 2 else 'red', 5.2, width=lw * 0.5)
+ # ---- head
+ ha = -lean * (0.55 if not P.get('seated') else 1.0)
+ neck_top = T((0.32, 7.25))
+
+ def Hd(pt):
+ return neck_top + _rot(np.asarray(pt, np.float32) * (0.97 if fem else 1.0), ha)
+ face = [(-0.55, -1.25), (-0.6, -0.2), (-0.75, 0.35), (-1.15, 1.2), (-0.5, 2.35), (0.35, 2.4), (0.68, 2.15),
+ (0.85, 1.85), (0.92, 1.55), (0.86, 1.4), (1.06, 1.08), (1.22, 0.86), (1.04, 0.76), (0.97, 0.74),
+ (1.02, 0.6), (0.92, 0.53), (0.98, 0.45), (0.86, 0.34), (0.9, 0.2), (0.76, 0.03), (0.35, -0.02),
+ (0.32, -0.25), (0.38, -1.25)]
+ fpts = Hd(np.array(face, np.float32))
+ add(fpts, sk, 5.5, paths=[fpts[1:-1]], ink=skin_ink)
+ if fem:
+ wp = [(0.66, 2.16), (0.45, 2.6), (-0.3, 2.82), (-1.15, 2.55), (-1.65, 1.6), (-1.75, 0.2), (-1.75, -1.6),
+ (-1.5, -2.8), (-0.9, -2.95), (-0.6, -1.0), (0.05, -0.1), (0.25, -0.3), (0.55, -1.6), (0.75, -2.7),
+ (1.15, -2.55), (0.75, -0.9), (0.3, 0.6), (0.18, 1.5), (0.35, 1.95)]
+ elif wig == 'long':
+ wp = [(0.7, 2.14), (0.45, 2.62), (-0.3, 2.85), (-1.2, 2.6), (-1.7, 1.7), (-1.85, 0.3), (-1.8, -1.0),
+ (-1.55, -1.3), (-0.4, -1.2), (0.12, -1.05), (0.18, 0.2), (0.16, 1.2), (0.32, 1.9)]
+ elif wig == 'cap':
+ wp = [(0.6, 2.2), (0.35, 2.5), (-0.4, 2.55), (-1.05, 2.2), (-1.3, 1.4), (-1.15, 0.85), (-0.55, 0.95),
+ (0.0, 1.55), (0.3, 1.95)]
+ else:
+ wp = [(0.72, 2.12), (0.45, 2.55), (-0.2, 2.72), (-0.95, 2.5), (-1.42, 1.75), (-1.52, 0.9), (-1.38, 0.15),
+ (-0.85, 0.02), (-0.15, 0.18), (0.1, 0.42), (0.13, 1.0), (0.17, 1.5), (0.35, 1.92)]
+ wpts = Hd(_closed_spline(wp, 5) if wig != 'cap' else _closed_spline(wp, 5))
+ add(wpts, 'black', 7.0)
+ if u >= 10: # wig strands
+ strands = []
+ nst = 9 if u < 20 else 16
+ for i in range(nst):
+ f = (i + 0.5) / nst
+ a0 = np.array([0.55 - 1.9 * f, 2.75 - 0.3 * f], np.float32)
+ bot = -2.9 if (fem or wig == 'long') else 0.0
+ a1 = np.array([0.15 - 1.75 * f, bot + 0.2 * f], np.float32)
+ c = (a0 + a1) / 2 + np.array([-0.35, 0.0])
+ strands.append(Hd(spline(np.array([a0, c, a1]), 6)))
+ for s_ in strands:
+ self.part(None, None, paths=[S(s_)], ink='#3c4250', width=max(1.0, lw * 0.45), z=z0 + 7.05,
+ clip=S(wpts), sketch=False)
+ if fem: # fillet round the wig
+ fb = Hd(np.array([(0.55, 2.0), (-0.4, 2.15), (-1.55, 1.85)], np.float32))
+ add(None, None, 7.1, paths=[spline(fb, 6)], ink='#c84a32', width=lw * 1.4)
+ if wig == 'cap': # ear for close-cropped heads
+ th = np.linspace(0, 2 * np.pi, 16)
+ ear = Hd(np.stack([-0.08 + 0.2 * np.cos(th), 1.08 + 0.34 * np.sin(th)], 1))
+ add(ear, sk, 7.2, ink=skin_ink)
+ # eye: frontal almond, iris, kohl line, brow
+ t_ = np.linspace(0, 1, 12)
+ e0, e1 = np.array([0.34, 1.42]), np.array([0.82, 1.45])
+ top = np.stack([e0[0] + (e1[0] - e0[0]) * t_, e0[1] + (e1[1] - e0[1]) * t_ + 0.13 * np.sin(np.pi * t_)], 1)
+ bot = np.stack([e0[0] + (e1[0] - e0[0]) * t_, e0[1] + (e1[1] - e0[1]) * t_ - 0.08 * np.sin(np.pi * t_)], 1)[::-1]
+ eye = Hd(np.vstack([top, bot]))
+ add(eye, 'white', 7.3, width=lw * 0.7)
+ th = np.linspace(0, 2 * np.pi, 14)
+ iris = Hd(np.stack([0.62 + 0.085 * np.cos(th), 1.46 + 0.095 * np.sin(th)], 1))
+ add(iris, 'black', 7.4, outline=False)
+ kohl = Hd(np.array([[0.36, 1.42], [0.22, 1.38], [0.1, 1.34]], np.float32))
+ add(None, None, 7.5, paths=[kohl], ink=INK, width=lw * 0.8)
+ brow = Hd(np.stack([0.3 + 0.58 * t_, 1.66 + 0.06 * np.sin(np.pi * t_) + 0.02 * t_], 1))
+ add(None, None, 7.5, paths=[brow], ink=INK, width=lw * 0.9)
+ mouth = Hd(np.array([[0.92, 0.53], [0.78, 0.52]], np.float32))
+ add(None, None, 7.5, paths=[mouth], ink=skin_ink, width=lw * 0.6)
+ out['head'] = S(Hd(np.array([0.0, 1.4], np.float32)))
+ out['head_top'] = S(Hd(np.array([-0.3, 2.8], np.float32)))
+ out['ear'] = S(Hd(np.array([-0.1, 1.15], np.float32)))
+ out['shoulder_b'] = S(T((0.05 + (-2.42 - 0.05) * wk, 6.0)))
+ out['shoulder_f'] = S(T((0.8 + (2.42 - 0.8) * wk, 6.0)))
+ out['T'] = lambda pt: S(T(pt))
+ out['S'] = S
+ out['lw'] = lw
+ out['z_top'] = z0 + 8
+ return out
+
+ # ------------------------------------------------------------------ props held or used by figures
+ def _xf(self, x, y, s, facing):
+ F = 1 if facing >= 0 else -1
+ return lambda q: np.stack([x + F * s * np.asarray(q, np.float32)[..., 0], y - s * np.asarray(q, np.float32)[..., 1]], -1)
+
+ def rod(self, p0, p1, width, colour='ochre', z=None, lw=2.0):
+ """a straight wooden rod (staff, handle, pole) as a filled band"""
+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)
+ d = p1 - p0; d /= np.hypot(*d) + 1e-9; n = np.array([-d[1], d[0]]) * width / 2
+ pts = np.array([p0 + n, p1 + n, p1 - n, p0 - n])
+ return self.part(pts, colour, z=z, width=lw)
+
+ def staff(self, hand, length, facing=1, z=None, lw=2.0, width=None):
+ """a long walking staff held upright in the fist, foot on the ground in front"""
+ x, y = hand
+ w = width or max(4, lw * 2.2)
+ return self.rod((x + facing * lw, y - length * 0.18), (x - facing * lw * 0.5, y + length * 0.82), w, 'ochre', z=z, lw=lw)
+
+ def sickle(self, hand, size, facing=1, angle=0.0, z=None, lw=2.0):
+ """wooden sickle with a flint-toothed curved blade; the grip sits in `hand`"""
+ F = 1 if facing >= 0 else -1
+ th = np.linspace(np.radians(200), np.radians(355), 18)
+ outer = np.stack([0.55 + 0.55 * np.cos(th), 0.15 + 0.55 * np.sin(th)], 1)
+ inner = np.stack([0.58 + 0.38 * np.cos(th[::-1]), 0.2 + 0.4 * np.sin(th[::-1])], 1)
+ blade = np.vstack([[[-0.3, -0.02], [-0.25, 0.1]], outer[2:], inner[:-2], [[-0.15, -0.06]]])
+ blade = _rot(blade, np.radians(angle))
+ P = np.stack([hand[0] + F * size * blade[:, 0], hand[1] - size * blade[:, 1]], 1)
+ return self.part(P, 'ochre', z=z, width=lw)
+
+ def hoe(self, fig, apex=(8.7, 6.2), strike=(6.3, 0.35), grip=(3.9, 10.7), width=None):
+ """the Egyptian hoe (an inverted V): a handle held in both fists, a broad wooden blade lashed to its top
+ end and striking the soil, a rope tying the two. Points are in the figure's canon units."""
+ S = fig['S']; lw = fig['lw']; u = fig['u']
+ w = width or max(4.0, u * 0.5)
+ a, s, g = S(np.array(apex, np.float32)), S(np.array(strike, np.float32)), S(np.array(grip, np.float32))
+ z = fig['z_hand_b'] - 0.01
+ self.rod(g, a, w, 'ochre', z=z, lw=lw)
+ d = s - a; L = np.hypot(*d); d /= L; n = np.array([-d[1], d[0]])
+ blade = np.array([a - n * w * 0.45, a + n * w * 0.45, s + n * w * 1.25 + d * 2, s - n * w * 0.9])
+ self.part(blade, 'brown', z=z + 0.002, width=lw)
+ m0 = g + (a - g) * 0.55; m1 = a + (s - a) * 0.5
+ self.part(None, None, paths=[np.array([m0, m1])], ink='#6b5a3a', width=lw * 0.9, z=z + 0.003)
+
+ def basket(self, cx, cy, w, h, colour='lgreen', z=None, lw=2.0, full=None):
+ """a round woven basket (rim at cy), optional heap of ears or grain on top"""
+ t = np.linspace(0, np.pi, 20)
+ body = np.vstack([[[cx - w / 2, cy]], np.stack([cx - np.cos(t) * w / 2 * (0.92 - 0.1 * np.sin(t)), cy + np.sin(t) * h], 1),
+ [[cx + w / 2, cy]]])
+ p = self.part(body, colour, z=z, width=lw)
+ lines = [np.array([[cx - w / 2 + w * f, cy + 2], [cx - w / 2 + w * (f + 0.12), cy + h * 0.9]]) for f in np.linspace(0.08, 0.8, 7)]
+ lines += [np.array([[cx - w / 2 + w * (f + 0.12), cy + 2], [cx - w / 2 + w * f, cy + h * 0.9]]) for f in np.linspace(0.08, 0.8, 7)]
+ self.part(None, None, paths=lines, ink='#2e5b3c', width=lw * 0.5, z=p['z'] + 0.002, clip=body)
+ if full:
+ t2 = np.linspace(0, np.pi, 16)
+ top = np.vstack([np.stack([cx + np.cos(t2) * w / 2 * 0.95, cy - np.sin(t2) * h * 0.55], 1)])
+ self.part(top, full, z=p['z'] - 0.003, width=lw)
+ return p
+
+ def sack(self, cx, base, w, h, colour='linen', tie='red', z=None, lw=2.0, lean=0.0):
+ """a tied linen grain sack standing on its base"""
+ q = np.array([(-0.5, 0.08), (-0.47, 0.5), (-0.38, 0.72), (-0.16, 0.84), (-0.1, 0.9), (-0.2, 1.0), (0.0, 0.95),
+ (0.2, 1.0), (0.1, 0.9), (0.16, 0.84), (0.38, 0.72), (0.47, 0.5), (0.5, 0.08), (0.4, 0.0), (-0.4, 0.0)],
+ np.float32)
+ q = _rot(q, lean)
+ P = np.stack([cx + q[:, 0] * w, base - q[:, 1] * h], 1)
+ p = self.part(_closed_spline(P, 4), colour, z=z, width=lw)
+ band = np.array([(-0.17, 0.8), (0.17, 0.8), (0.15, 0.87), (-0.15, 0.87)], np.float32)
+ band = _rot(band, lean)
+ self.part(np.stack([cx + band[:, 0] * w, base - band[:, 1] * h], 1), tie, z=p['z'] + 0.002, width=lw * 0.6)
+ sm = _rot(np.array([(0.22, 0.62), (0.3, 0.35), (0.26, 0.12)], np.float32), lean)
+ self.part(None, None, paths=[np.stack([cx + sm[:, 0] * w, base - sm[:, 1] * h], 1)], ink='#b9a58c', width=lw * 0.5,
+ z=p['z'] + 0.002)
+ return p
+
+ def heap(self, cx, base, w, h, z=None, lw=2.0):
+ """a heap of threshed grain: a dome stippled with grain dots"""
+ t = np.linspace(0, 1, 40)
+ xs = cx - w / 2 + w * t
+ ys = base - h * (np.sin(np.pi * t) ** 0.85) * (1 + 0.06 * np.cos(2 * np.pi * t))
+ P = np.vstack([np.stack([xs, ys], 1), [[cx + w / 2, base], [cx - w / 2, base]]])
+ p = self.part(P, 'yellow', z=z, width=lw)
+ dots = []
+ r = self.rng
+ for yy in np.arange(base - 6, base - h, -7.0):
+ frac = (base - yy) / h
+ half = w / 2 * np.sqrt(max(0, 1 - frac ** 1.6)) * 0.92
+ for xx in np.arange(cx - half + 4 + (yy % 14) * 0.5, cx + half - 4, 8.0):
+ th = np.linspace(0, 2 * np.pi, 7)
+ rr = r.uniform(1.2, 1.8)
+ dots.append(np.stack([xx + r.normal(0, 0.8) + np.cos(th) * rr * 1.3, yy + np.sin(th) * rr], 1))
+ if dots:
+ self.part(dots, 'ochre', z=p['z'] + 0.002, outline=False, clip=P, rag=0, sketch=False)
+ return p
+
+ def measure(self, cx, base, w, h, z=None, lw=2.0, tilt=0.0):
+ """a wooden grain measure (heqat): a tapering tub with bands"""
+ tf = lambda q: np.stack([cx + (_rot(np.asarray(q, np.float32) - (0, 0.5), tilt) + (0, 0.5))[:, 0] * w,
+ base - (_rot(np.asarray(q, np.float32) - (0, 0.5), tilt) + (0, 0.5))[:, 1] * h], 1)
+ t = np.linspace(0, np.pi, 12)
+ grain = np.vstack([np.stack([-np.cos(t) * 0.5, 1.0 + np.sin(t) * 0.22], 1)])
+ p = self.part(tf(grain), 'yellow', z=z - 0.002 if z is not None else None, width=lw * 0.7)
+ body = tf([(-0.56, 1.0), (0.56, 1.0), (0.42, 0.05), (0.3, 0.0), (-0.3, 0.0), (-0.42, 0.05)])
+ p = self.part(body, 'brown', z=p['z'] + 0.001, width=lw)
+ for f in (0.25, 0.75):
+ k = 0.42 + 0.14 * f
+ self.part(None, None, paths=[tf([(-k, f), (k, f)])], ink='#d9b56a', width=lw * 0.9, z=p['z'] + 0.001)
+ return p
+
+ def papyrus(self, p0, p1, width, z=None, lw=2.0, lines=3):
+ """an unrolled papyrus sheet between two points with a roll at the far end and lines of writing"""
+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)
+ d = p1 - p0; L = np.hypot(*d); d /= L; n = np.array([-d[1], d[0]])
+ P = np.array([p0 - n * width / 2, p1 - n * width / 2, p1 + n * width / 2, p0 + n * width / 2])
+ p = self.part(P, 'white', z=z, width=lw)
+ roll = np.array([p1 - n * width * 0.62 - d * 3, p1 - n * width * 0.62 + d * 4, p1 + n * width * 0.62 + d * 4,
+ p1 + n * width * 0.62 - d * 3])
+ self.part(roll, 'white', z=p['z'] + 0.003, width=lw)
+ paths = []
+ for i in range(lines):
+ o = (i + 1) / (lines + 1) - 0.5
+ a = p0 + d * L * 0.12 + n * width * o; b = p0 + d * L * (0.82 - 0.2 * (i == lines - 1)) + n * width * o
+ paths.append(np.array([a, b]))
+ self.part(None, None, paths=paths, ink='#3a2a22', width=lw * 0.55, z=p['z'] + 0.002)
+ return p
+
+ def palette(self, cx, cy, length, angle=0.0, z=None, lw=2.0):
+ """a scribe's palette: a long slat with a red and a black ink cake and a pen slot"""
+ d = np.array([np.cos(angle), -np.sin(angle)]); n = np.array([-d[1], d[0]])
+ c = np.array([cx, cy], np.float32); w = length * 0.16
+ P = np.array([c - d * length / 2 - n * w / 2, c + d * length / 2 - n * w / 2, c + d * length / 2 + n * w / 2,
+ c - d * length / 2 + n * w / 2])
+ p = self.part(P, 'white', z=z, width=lw)
+ th = np.linspace(0, 2 * np.pi, 10)
+ for k, col in ((0.32, 'black'), (0.18, 'red')):
+ q = c - d * length * k
+ self.part(q + np.stack([np.cos(th), np.sin(th)], 1) * w * 0.3, col, z=p['z'] + 0.002, outline=False)
+ self.part(None, None, paths=[np.array([c - d * length * 0.02, c + d * length * 0.44])], ink='#6b5a44',
+ width=lw * 0.6, z=p['z'] + 0.002)
+ return p
+
+
+ def papyrus_clump(self, x, base, h, n=5, z=None, lw=1.6, spread=None, seed=None):
+ """papyrus stems rising from water or a bank, each topped by a fan-shaped umbel"""
+ r = np.random.default_rng(seed if seed is not None else self._seed())
+ spread = spread if spread is not None else h * 0.45
+ z0 = self._z if z is None else z
+ self._z = z0 + 2
+ stems, umb, rays = [], [], []
+ for i in range(n):
+ f = (i + 0.5) / n - 0.5
+ top = np.array([x + f * spread * 1.6, base - h * (0.78 + 0.22 * r.random())])
+ b = np.array([x + f * spread * 0.4, base])
+ stems.append(spline(np.array([b, (b + top) / 2 + (f * 6, 0), top]), 6))
+ ang = np.radians(-90 + f * 40)
+ R = h * 0.15
+ th = np.linspace(ang - 0.9, ang + 0.9, 14)
+ fan = np.vstack([[top], np.stack([top[0] + np.cos(th) * R, top[1] + np.sin(th) * R], 1)])
+ umb.append(fan)
+ for t in np.linspace(ang - 0.75, ang + 0.75, 5):
+ rays.append(np.array([top, top + np.array([np.cos(t), np.sin(t)]) * R * 0.9]))
+ self.part(None, None, paths=stems, ink='#2f6e50', width=lw * 1.8, z=z0)
+ self.part(umb, 'green', z=z0 + 1, width=lw)
+ self.part(None, None, paths=rays, ink='#1f4a34', width=lw * 0.5, z=z0 + 1.1, sketch=False)
+
+ def scoop(self, hand, size, angle=0.0, facing=1, z=None, lw=2.0):
+ """a wooden winnowing scoop held by its handle"""
+ F = 1 if facing >= 0 else -1
+ q = np.array([(-0.15, -0.07), (0.3, -0.1), (0.5, -0.3), (1.05, -0.28), (1.22, -0.1), (1.2, 0.1), (1.0, 0.24),
+ (0.5, 0.26), (0.3, 0.1), (-0.15, 0.07)], np.float32)
+ q = _rot(q, np.radians(angle))
+ P = np.stack([hand[0] + F * q[:, 0] * size, hand[1] - q[:, 1] * size], 1)
+ return self.part(_closed_spline(P, 3), 'ochre', z=z, width=lw)
+
+ def grain_stream(self, p0, p1, n=24, spread=4.0, z=None, colour='ochre', chaff=0):
+ """grain falling from p0 to p1 (a poured stream, or a winnowed cloud when spread is large)"""
+ r = self.rng; pts = []
+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)
+ for i in range(n):
+ t = r.uniform(0, 1)
+ c = p0 + (p1 - p0) * t + r.normal(0, spread * (0.3 + t), 2)
+ th = np.linspace(0, 2 * np.pi, 6)
+ pts.append(np.stack([c[0] + np.cos(th) * 2.1, c[1] + np.sin(th) * 1.5], 1))
+ p = self.part(pts, colour, z=z, outline=False, rag=0, sketch=False)
+ if chaff:
+ lines = []
+ for i in range(chaff):
+ c = p0 + (p1 - p0) * r.uniform(-0.3, 0.5) + r.normal(0, spread * 1.4, 2)
+ a = r.uniform(0, np.pi)
+ lines.append(np.array([c, c + np.array([np.cos(a), np.sin(a)]) * r.uniform(4, 8)]))
+ self.part(None, None, paths=lines, ink='#a88a52', width=1.2, z=p['z'] + 0.01, sketch=False)
+ return p
+
+ # ------------------------------------------------------------------ animals and plants
+ def ox(self, x, base, length, facing=1, colour='white', patches='black', z=None, lw=2.0, seed=None,
+ horn='#e9dfc6', far=False):
+ """a long-horned ox in profile (x: the hindquarters on the ground line). Four legs: the far pair is
+ drawn first and a step apart from the near pair, so every leg is seen, as Egyptian painters did."""
+ s = length / 15.4
+ X = self._xf(x, base, s, facing)
+ z0 = self._z if z is None else z
+ self._z = z0 + 10
+ r = np.random.default_rng(seed if seed is not None else self._seed())
+ body = [(0.9, 8.1), (0.45, 7.75), (0.2, 6.7), (0.45, 5.3), (1.3, 4.3), (2.6, 3.75), (4.5, 3.45), (7.0, 3.5),
+ (8.9, 3.8), (10.0, 3.9), (10.9, 4.25), (11.45, 4.8), (11.9, 5.5), (12.35, 6.1), (12.55, 7.3),
+ (12.0, 8.45), (10.6, 8.6), (9.4, 8.3), (7.0, 8.0), (4.0, 8.1), (2.0, 8.4)]
+ bpts = _closed_spline(body, 6)
+ dark = colour in ('red', 'brown', 'black', 'ochre')
+ legcol = colour
+
+ def leg(kind, dx, zz):
+ if kind == 'hind':
+ q = [(1.0, 5.3), (0.85, 3.5), (1.2, 2.0), (1.28, 0.75), (1.22, 0.32), (2.0, 0.32), (1.95, 0.8), (1.92, 1.5),
+ (2.05, 2.8), (2.75, 4.0), (2.9, 4.8)]
+ else:
+ q = [(9.1, 4.6), (9.05, 3.0), (9.18, 2.1), (9.15, 0.9), (9.2, 0.32), (9.98, 0.32), (9.9, 0.9), (9.95, 2.0),
+ (10.05, 2.5), (10.25, 3.6), (10.45, 4.6)]
+ q = np.array(q, np.float32) + (dx, 0)
+ P = X(q)
+ self.part(P, legcol, z=z0 + zz, paths=[P[:-1]], width=lw)
+ hoof = np.array([q[4] + (0, 0.02), q[5] + (0, 0.02), q[5] + (0.06, -0.32), q[4] + (-0.1, -0.32)], np.float32)
+ self.part(X(hoof), 'black', z=z0 + zz + 0.05, width=lw * 0.7)
+ leg('hind', 1.3, 0.0); leg('fore', -1.1, 0.1)
+ # tail behind the far legs
+ tail = X(np.array([(0.75, 8.0), (0.15, 7.3), (-0.05, 5.6), (0.1, 3.8), (0.2, 2.6)], np.float32))
+ self.part(None, None, paths=[spline(tail, 6)], ink=INK, width=lw * 1.6, z=z0 + 0.2)
+ tuft = X(np.array([(0.2, 2.9), (-0.15, 2.2), (0.05, 1.5), (0.35, 1.45), (0.45, 2.1)], np.float32))
+ self.part(_closed_spline(tuft, 4), 'black', z=z0 + 0.25, width=lw * 0.6)
+ bp = self.part(X(bpts), colour, z=z0 + 1.0, width=lw)
+ leg('hind', 0.0, 1.5); leg('fore', 0.0, 1.6)
+ # patches (clipped to the body)
+ if patches:
+ blobs = []
+ for i in range(r.integers(3, 6)):
+ cx_, cy_ = r.uniform(1.5, 10.5), r.uniform(4.2, 8.2)
+ rx, ry = r.uniform(0.9, 2.0), r.uniform(0.7, 1.5)
+ th = np.linspace(0, 2 * np.pi, 24, endpoint=False)
+ wob = 1 + 0.25 * fbm1d(24, 6, 2, int(r.integers(1 << 30)))
+ blobs.append(X(np.stack([cx_ + np.cos(th) * rx * wob, cy_ + np.sin(th) * ry * wob], 1)))
+ self.part(blobs, patches, z=z0 + 1.2, clip=X(bpts), outline=False, sketch=False)
+ # head
+ head = [(12.1, 8.65), (12.95, 8.35), (13.6, 7.6), (14.25, 6.3), (14.85, 5.1), (15.1, 4.65), (14.85, 4.35),
+ (14.25, 4.45), (13.55, 5.15), (12.85, 5.9), (12.25, 6.6), (11.95, 7.6)]
+ hp = _closed_spline(head, 5)
+ self.part(X(hp), colour, z=z0 + 2.0, width=lw)
+ if patches and r.random() < 0.6:
+ th = np.linspace(0, 2 * np.pi, 20, endpoint=False)
+ self.part(X(np.stack([13.3 + np.cos(th) * 0.8, 6.7 + np.sin(th) * 0.9], 1)), patches, z=z0 + 2.05,
+ clip=X(hp), outline=False, sketch=False)
+ ear = np.array([(12.15, 8.2), (11.4, 8.35), (10.85, 8.05), (11.5, 7.75), (12.1, 7.75)], np.float32)
+ self.part(X(_closed_spline(ear, 4)), colour, z=z0 + 2.1, width=lw)
+ # lyre horns, both seen
+ for hz, pts in ((1.9, [(12.35, 8.5), (11.75, 9.4), (11.75, 10.6), (12.25, 11.4)]),
+ (2.2, [(12.75, 8.45), (13.55, 9.4), (13.55, 10.6), (13.05, 11.35)])):
+ c = spline(np.array(pts, np.float32), 8)
+ T_ = np.gradient(c, axis=0); T_ /= np.hypot(T_[:, 0], T_[:, 1])[:, None]
+ N_ = np.stack([-T_[:, 1], T_[:, 0]], 1)
+ wv = np.linspace(0.36, 0.08, len(c))[:, None]
+ self.part(X(np.vstack([c + N_ * wv, (c - N_ * wv)[::-1]])), horn, z=z0 + hz, width=lw * 0.8)
+ # face details
+ t_ = np.linspace(0, 1, 10)
+ eye = np.vstack([np.stack([13.0 + 0.55 * t_, 7.45 + 0.18 * np.sin(np.pi * t_) - 0.15 * t_], 1),
+ np.stack([13.0 + 0.55 * t_, 7.45 - 0.12 * np.sin(np.pi * t_) - 0.15 * t_], 1)[::-1]])
+ self.part(X(eye), 'white', z=z0 + 2.3, width=lw * 0.7)
+ th = np.linspace(0, 2 * np.pi, 10)
+ self.part(X(np.stack([13.3 + 0.12 * np.cos(th), 7.4 + 0.12 * np.sin(th)], 1)), 'black', z=z0 + 2.35, outline=False)
+ self.part(None, None, paths=[X(np.array([(14.55, 5.2), (14.8, 5.05), (14.85, 4.85)], np.float32))], width=lw * 0.7,
+ z=z0 + 2.3)
+ self.part(None, None, paths=[X(spline(np.array([(11.5, 4.7), (11.0, 5.4), (11.3, 6.4)], np.float32), 5)),
+ X(spline(np.array([(11.85, 5.3), (11.55, 6.0), (11.85, 6.8)], np.float32), 5))],
+ width=lw * 0.6, z=z0 + 1.3, clip=X(bpts))
+ return {'poll': X(np.array([12.5, 8.7], np.float32)), 'z': z0 + 2.5, 'horns': X(np.array([12.55, 9.6], np.float32)),
+ 'nose': X(np.array([15.0, 4.6], np.float32)), 'X': X, 'body': X(bpts)}
+
+ def wheat(self, x0, x1, base, top, every=9.0, z=None, lw=1.8, stubble=(), grab=(), seed=None):
+ """a standing field of emmer: stalks, ears with awns. stubble: list of (xa, xb) ranges already cut
+ (short stubs); grab: list of (x, y, (xa, xb)) -- stalks in [xa, xb] bend toward a fist at (x, y)."""
+ r = np.random.default_rng(seed if seed is not None else self._seed())
+ z0 = self._z if z is None else z
+ self._z = z0 + 3
+ stalks, ears, awns, stubs = [], [], [], []
+ H = base - top
+ xs = np.arange(x0, x1, every) + r.uniform(-every * 0.3, every * 0.3, len(np.arange(x0, x1, every)))
+ for x in xs:
+ if any(a <= x <= b for a, b in stubble):
+ h = r.uniform(0.08, 0.14) * H
+ stubs.append(np.array([[x, base], [x + r.normal(0, 1), base - h]]))
+ continue
+ tx = x + r.normal(0, every * 0.25); ty = top + r.uniform(0, H * 0.12)
+ mid = None
+ for gx, gy, (ga, gb) in grab:
+ if ga <= x <= gb:
+ mid = (gx + r.normal(0, 1.5), gy + r.normal(0, 2)); tx = gx + (tx - gx) * 0.6 + (gx - x) * 0.25
+ if mid is None:
+ path = np.array([[x, base], [(x + tx) / 2 + r.normal(0, 1.5), (base + ty) / 2], [tx, ty]], np.float32)
+ else:
+ path = np.array([[x, base], [mid[0], mid[1]], [tx, ty]], np.float32)
+ P = spline(path, 6)
+ stalks.append(P)
+ d = P[-1] - P[-4]; d /= np.hypot(*d) + 1e-9; n = np.array([-d[1], d[0]])
+ L = H * r.uniform(0.13, 0.17); W = L * 0.18
+ tip = P[-1] + d * L
+ t = np.linspace(0, 1, 9)
+ sh = np.sin(np.pi * np.clip(t * 1.1, 0, 1)) ** 0.7
+ left = P[-1][None] + d[None] * (t * L)[:, None] + n[None] * (sh * W)[:, None]
+ right = P[-1][None] + d[None] * (t * L)[:, None] - n[None] * (sh * W)[:, None]
+ ears.append(np.vstack([left, right[::-1]]))
+ for k in range(4):
+ a = P[-1] + d * L * (0.3 + 0.18 * k)
+ for sgn in (-1, 1):
+ awns.append(np.array([a + n * sgn * W * 0.8, a + n * sgn * W * 1.6 + d * L * 0.5]))
+ if stalks: self.part(None, None, paths=stalks, ink='#9b6b2c', width=lw * 0.75, z=z0)
+ if stubs: self.part(None, None, paths=stubs, ink='#9b6b2c', width=lw * 0.8, z=z0)
+ if ears: self.part(ears, 'yellow', z=z0 + 1, width=lw * 0.6, ink='#7a4a1c')
+ if awns: self.part(None, None, paths=awns, ink='#9b6b2c', width=lw * 0.35, z=z0 + 1.1, sketch=False)
+
+ def sheaf(self, cx, base, w, h, z=None, lw=1.8):
+ """a bound sheaf of cut emmer lying ready to carry"""
+ r = self.rng
+ z0 = self._z if z is None else z
+ self._z = z0 + 2
+ stalks, ears = [], []
+ for i in range(14):
+ a = np.radians(r.uniform(-14, 14))
+ p0 = np.array([cx + r.normal(0, w * 0.06), base]); p1 = p0 + np.array([np.sin(a), -np.cos(a)]) * h * 0.75
+ stalks.append(np.array([p0, (p0 + p1) / 2 + (r.normal(0, 1), 0), p1]))
+ d = (p1 - p0) / np.hypot(*(p1 - p0)); n = np.array([-d[1], d[0]])
+ L = h * 0.28; W = L * 0.17; t = np.linspace(0, 1, 8); sh = np.sin(np.pi * np.clip(t * 1.1, 0, 1)) ** 0.7
+ ears.append(np.vstack([p1 + np.outer(t * L, d) + np.outer(sh * W, n), (p1 + np.outer(t * L, d) - np.outer(sh * W, n))[::-1]]))
+ self.part(None, None, paths=stalks, ink='#9b6b2c', width=lw * 0.8, z=z0)
+ self.part(ears, 'yellow', z=z0 + 1, width=lw * 0.6, ink='#7a4a1c')
+ band = np.array([[cx - w * 0.22, base - h * 0.3], [cx + w * 0.22, base - h * 0.3], [cx + w * 0.2, base - h * 0.38],
+ [cx - w * 0.2, base - h * 0.38]])
+ self.part(band, 'green', z=z0 + 1.2, width=lw * 0.6)
+
+ def tree(self, cx, base, h, w, z=None, lw=2.0, figs=True, waterskin=None):
+ """a sycamore fig: a trunk and a round crown packed with outlined leaves and red figs;
+ waterskin=(dx, drop) hangs a skin from a branch"""
+ r = self.rng
+ z0 = self._z if z is None else z
+ self._z = z0 + 6
+ tw = w * 0.09
+ trunk = np.array([[cx - tw * 1.3, base], [cx - tw * 0.6, base - h * 0.15], [cx - tw * 0.5, base - h * 0.55],
+ [cx + tw * 0.5, base - h * 0.55], [cx + tw * 0.6, base - h * 0.15], [cx + tw * 1.3, base]])
+ self.part(trunk, 'brown', z=z0, width=lw)
+ ccy = base - h * 0.62; rx, ry = w / 2, h * 0.36
+ th = np.linspace(0, 2 * np.pi, 40, endpoint=False)
+ wob = 1 + 0.07 * np.sin(th * 7 + r.uniform(0, 6))
+ crown = np.stack([cx + np.cos(th) * rx * wob, ccy + np.sin(th) * ry * wob], 1)
+ self.part(crown, 'green', z=z0 + 1, width=lw)
+ rows = []
+ L = ry * 0.24; Wd = L * 0.5
+ ys = np.arange(ccy - ry * 0.95, ccy + ry * 0.92, L * 0.52)
+ for j, yy in enumerate(ys):
+ row = []
+ off = (j % 2) * Wd * 0.95
+ for xx in np.arange(cx - rx - Wd + off, cx + rx + Wd, Wd * 1.9):
+ if ((xx - cx) / (rx * 0.97)) ** 2 + ((yy + L * 0.3 - ccy) / (ry * 0.97)) ** 2 > 1.0: continue
+ t = np.linspace(0, 1, 9)
+ side = np.sin(np.pi * t) ** 0.9 * Wd / 2
+ q = np.vstack([np.stack([xx + side, yy + L * (1 - t)], 1), np.stack([xx - side, yy + L * (1 - t)], 1)[::-1]])
+ row.append(q)
+ if row: rows.append(row)
+ for j, row in enumerate(rows): # lower rows overlap the ones above, like scales
+ self.part(row, 'dkgreen' if j % 2 == 0 else 'lgreen', z=z0 + 2 + j * 0.01, width=lw * 0.5, sketch=j % 2 == 0,
+ clip=crown)
+ if figs:
+ fg = []
+ for i in range(14):
+ a = r.uniform(0, 2 * np.pi); rr = np.sqrt(r.uniform(0.05, 0.75))
+ t = np.linspace(0, 2 * np.pi, 8)
+ fg.append(np.stack([cx + np.cos(a) * rx * rr + np.cos(t) * 2.6, ccy + np.sin(a) * ry * rr + np.sin(t) * 2.6], 1))
+ self.part(fg, 'red', z=z0 + 2.2, width=lw * 0.4)
+ out = {'crown': crown, 'z': z0 + 3}
+ if waterskin: # a goatskin of water hung from a lopped branch
+ dx, drop = waterskin
+ bx0, by0 = cx + np.sign(dx) * tw * 0.4, base - h * 0.42
+ hx, hy = cx + dx, base - h * 0.47
+ self.rod((bx0, by0), (hx + np.sign(dx) * 6, hy), max(3, tw * 0.45), 'brown', z=z0 + 0.5, lw=lw)
+ self.part(None, None, paths=[np.array([[hx, hy], [hx - np.sign(dx) * 3, hy + drop * 0.22]])], ink=INK,
+ width=lw * 0.8, z=z0 + 3)
+ sk = np.array([(0.0, 0.18), (0.22, 0.24), (0.38, 0.5), (0.5, 0.62), (0.58, 0.55), (0.52, 0.8), (0.3, 1.0),
+ (-0.3, 1.0), (-0.48, 0.82), (-0.56, 0.6), (-0.42, 0.62), (-0.36, 0.42), (-0.2, 0.24)], np.float32)
+ P = np.stack([hx + sk[:, 0] * drop * 0.62, hy + drop * 0.18 + sk[:, 1] * drop * 0.82], 1)
+ self.part(_closed_spline(P, 4), 'brown', z=z0 + 3.1, width=lw)
+ self.part(None, None, paths=[np.array([[hx - drop * 0.12, hy + drop * 0.34], [hx + drop * 0.12, hy + drop * 0.34]])],
+ ink='#e9dfc6', width=lw * 1.2, z=z0 + 3.2)
+ out['skin'] = (hx, hy + drop * 0.7)
+ return out
+
+ # ------------------------------------------------------------------ frame: borders, frieze, bands, river
+ def block_border(self, x0, y0, x1, y1, block=30, colours=('blue', 'red', 'green', 'red'), spacer=8, lw=1.8):
+ """the block border: coloured blocks with white spacers between black rules"""
+ horiz = (x1 - x0) >= (y1 - y0)
+ L0, L1 = (x0, x1) if horiz else (y0, y1)
+ pos, k = L0, 0
+ rects, whites = {}, []
+ while pos < L1:
+ e = min(L1, pos + block)
+ rects.setdefault(colours[k % len(colours)], []).append((pos, e))
+ pos = e
+ if pos < L1:
+ whites.append((pos, min(L1, pos + spacer))); pos += spacer
+ k += 1
+ def R(a, b):
+ return np.array([[a, y0], [b, y0], [b, y1], [a, y1]], np.float32) if horiz else \
+ np.array([[x0, a], [x1, a], [x1, b], [x0, b]], np.float32)
+ for col, segs in rects.items():
+ self.part([R(a, b) for a, b in segs], col, width=lw, rag=0.5)
+ if whites:
+ self.part([R(a, b) for a, b in whites], 'white', width=lw, rag=0.5)
+
+ def band(self, x0, x1, y, stripes, lw=1.6):
+ """horizontal stripes from y downward: stripes = [(colour, height), ...] with black rules between"""
+ yy = y
+ for col, h in stripes:
+ if col == 'rule':
+ self.part(None, None, paths=[np.array([[x0, yy + h / 2], [x1, yy + h / 2]])], width=h, ink=INK, sketch=False)
+ else:
+ self.part(np.array([[x0, yy], [x1, yy], [x1, yy + h], [x0, yy + h]], np.float32), col, outline=False, rag=0.4)
+ yy += h
+ return yy
+
+ def kheker(self, x0, x1, y0, y1, w=30, colours=('green', 'red', 'blue'), lw=1.8):
+ """the kheker frieze: a row of tied bundles of reeds with knobbed tops"""
+ n = int((x1 - x0) // w)
+ w = (x1 - x0) / n
+ H = y1 - y0
+ bodies = {}
+ knobs, ties = [], []
+ for i in range(n):
+ cx = x0 + (i + 0.5) * w
+ col = colours[i % len(colours)]
+ q = np.array([(-0.42, 1.0), (-0.38, 0.62), (-0.2, 0.46), (-0.16, 0.34), (-0.26, 0.24), (-0.26, 0.14),
+ (0.26, 0.14), (0.26, 0.24), (0.16, 0.34), (0.2, 0.46), (0.38, 0.62), (0.42, 1.0)], np.float32)
+ P = np.stack([cx + q[:, 0] * w, y0 + q[:, 1] * H], 1)
+ bodies.setdefault(col, []).append(P)
+ th = np.linspace(0, 2 * np.pi, 16)
+ knobs.append(np.stack([cx + np.cos(th) * w * 0.27, y0 + 0.09 * H + np.sin(th) * w * 0.22], 1))
+ for f in (0.5, 0.58):
+ hw = 0.17 + (f - 0.46) * 1.2
+ ties.append(np.array([[cx - w * hw, y0 + f * H], [cx + w * hw, y0 + f * H], [cx + w * hw, y0 + (f + 0.05) * H],
+ [cx - w * hw, y0 + (f + 0.05) * H]], np.float32))
+ for col, ps in bodies.items():
+ self.part(ps, col, width=lw)
+ self.part(knobs, 'red', width=lw)
+ self.part(ties, 'yellow', width=lw * 0.7)
+ mids = [np.array([[x0 + (i + 0.5) * w, y0 + 0.66 * H], [x0 + (i + 0.5) * w, y1 - 2]]) for i in range(n)]
+ self.part(None, None, paths=mids, width=lw * 0.6, sketch=False)
+
+ def river(self, x0, y0, x1, y1, fish=4, lotus=5, lw=1.8, seed=None):
+ """the river: Egyptian-blue water with rows of black zigzags, fish and lotus"""
+ r = np.random.default_rng(seed if seed is not None else self._seed())
+ P = np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]], np.float32)
+ p = self.part(P, 'blue', width=lw, rag=0.4)
+ rows = []
+ hz = (y1 - y0)
+ for k, yy in enumerate(np.arange(y0 + hz * 0.22, y1 - hz * 0.1, hz * 0.26)):
+ xs = np.arange(x0 + 6 + (k % 2) * 7, x1 - 6, 14.0)
+ pts = np.stack([np.repeat(xs, 2)[:-1] + np.tile([0, 7], len(xs))[:-1], np.tile([yy - 4, yy + 4], len(xs))[:-1]], 1)
+ rows.append(pts)
+ self.part(None, None, paths=rows, width=lw * 0.75, z=p['z'] + 0.002, sketch=False)
+ out = []
+ for i in range(fish):
+ fx = x0 + (i + 0.5) / fish * (x1 - x0) + r.normal(0, 30); fy = y0 + hz * r.uniform(0.38, 0.62)
+ F = 1 if r.random() < 0.5 else -1
+ L = hz * 0.62
+ q = np.array([(0.0, 0.0), (0.18, 0.2), (0.45, 0.26), (0.7, 0.18), (0.82, 0.05), (0.98, 0.17), (0.94, 0.0),
+ (0.98, -0.17), (0.82, -0.05), (0.7, -0.16), (0.45, -0.24), (0.18, -0.18)], np.float32)
+ Pq = np.stack([fx + F * (0.5 - q[:, 0]) * L, fy - q[:, 1] * L], 1)
+ fp = self.part(_closed_spline(Pq, 4), 'lblue', z=p['z'] + 1, width=lw * 0.8)
+ th = np.linspace(0, 2 * np.pi, 8)
+ self.part(np.stack([fx + F * 0.38 * L + np.cos(th) * 1.8, fy - 0.04 * L + np.sin(th) * 1.8], 1), 'black',
+ z=fp['z'] + 0.002, outline=False)
+ fin = np.array([[fx + F * 0.1 * L, fy - 0.2 * L], [fx - F * 0.12 * L, fy - 0.36 * L], [fx - F * 0.25 * L, fy - 0.18 * L]])
+ self.part(fin, 'red', z=fp['z'] - 0.002, width=lw * 0.6)
+ for i in range(lotus):
+ lx = x0 + (i + 0.3 + r.uniform(0, 0.4)) / lotus * (x1 - x0); ly = y0 + hz * 0.08
+ stem = np.array([[lx, ly + hz * 0.25], [lx + r.normal(0, 4), y1 - 2]])
+ self.part(None, None, paths=[stem], ink='#2f6e50', width=lw * 1.2, z=p['z'] + 0.5)
+ pet = []
+ for a in (-0.55, 0.0, 0.55):
+ c = np.array([lx, ly + hz * 0.24]); d = np.array([np.sin(a), -np.cos(a)]); n = np.array([-d[1], d[0]])
+ L = hz * 0.32
+ pet.append(np.array([c, c + d * L * 0.5 + n * L * 0.17, c + d * L, c + d * L * 0.5 - n * L * 0.17]))
+ self.part(pet, 'lblue', z=p['z'] + 0.6, width=lw * 0.7)
+ return p
+
+ # ------------------------------------------------------------------ hieroglyphs (pseudo-text)
+ def _sign(self, name):
+ """polygons / lines of one sign in a unit em box (y down, facing right): list of (kind, geom, colour)"""
+ th = np.linspace(0, 2 * np.pi, 20, endpoint=False)
+ E = lambda cx, cy, rx, ry: np.stack([cx + np.cos(th) * rx, cy + np.sin(th) * ry], 1)
+ A = lambda *pts: np.array(pts, np.float32)
+ cs = lambda pts, per=4: _closed_spline(np.array(pts, np.float32), per)
+ if name == 'reed':
+ return [('f', A((0.44, 1.0), (0.37, 0.78), (0.35, 0.52), (0.4, 0.3), (0.5, 0.12), (0.64, 0.0), (0.6, 0.22),
+ (0.57, 0.48), (0.55, 0.74), (0.5, 1.0)), 'green'),
+ ('l', A((0.47, 0.95), (0.5, 0.5), (0.6, 0.1)), None)]
+ if name == 'water':
+ xs = np.linspace(0.02, 0.98, 15); ys = np.where(np.arange(15) % 2 == 0, 0.45, 0.56)
+ top = np.stack([xs, ys - 0.05], 1); bot = np.stack([xs, ys + 0.05], 1)[::-1]
+ return [('f', np.vstack([top, bot]), 'blue')]
+ if name == 'mouth':
+ t = np.linspace(0, 1, 14)
+ return [('f', np.vstack([np.stack([0.05 + 0.9 * t, 0.5 - 0.17 * np.sin(np.pi * t)], 1),
+ np.stack([0.95 - 0.9 * t, 0.5 + 0.15 * np.sin(np.pi * t)], 1)]), 'red')]
+ if name == 'loaf':
+ t = np.linspace(0, np.pi, 16)
+ return [('f', np.vstack([np.stack([0.5 - np.cos(t) * 0.32, 0.72 - np.sin(t) * 0.34], 1)]), 'ochre')]
+ if name == 'sun':
+ return [('f', E(0.5, 0.5, 0.31, 0.31), 'red'), ('f', E(0.5, 0.5, 0.07, 0.07), 'black')]
+ if name == 'stroke':
+ return [('f', A((0.45, 0.1), (0.57, 0.1), (0.56, 0.9), (0.44, 0.9)), 'black')]
+ if name == 'heel':
+ t = np.linspace(0, np.pi, 16)
+ o = np.stack([0.5 - np.cos(t) * 0.33, 0.95 - np.sin(t) * 0.82], 1)
+ i_ = np.stack([0.5 - np.cos(t[::-1]) * 0.18, 0.95 - np.sin(t[::-1]) * 0.64], 1)
+ return [('f', np.vstack([o, i_]), 'black')]
+ if name == 'coil':
+ t = np.linspace(0, 2.6 * np.pi, 40)
+ sp = np.stack([0.5 + np.cos(t) * (0.06 + 0.035 * t), 0.36 + np.sin(t) * (0.06 + 0.035 * t)], 1)
+ return [('l', np.vstack([sp, [[0.5, 0.95]]]), 'thick')]
+ if name == 'foot':
+ return [('f', cs([(0.22, 0.04), (0.42, 0.04), (0.44, 0.6), (0.62, 0.72), (0.95, 0.8), (0.97, 0.94), (0.2, 0.94)], 3), 'skin')]
+ if name == 'hand':
+ return [('f', A((0.02, 0.56), (0.3, 0.46), (0.86, 0.43), (0.98, 0.5), (0.92, 0.58), (0.3, 0.64), (0.02, 0.62)), 'skin'),
+ ('f', A((0.28, 0.48), (0.48, 0.3), (0.6, 0.31), (0.5, 0.46)), 'skin')]
+ if name == 'basket':
+ return [('f', cs([(0.04, 0.38), (0.86, 0.38), (0.8, 0.6), (0.58, 0.72), (0.38, 0.72), (0.14, 0.6)], 4), 'green'),
+ ('l', A((0.86, 0.42), (0.98, 0.44), (0.97, 0.56), (0.83, 0.55)), None)]
+ if name == 'house':
+ return [('f', A((0.1, 0.25), (0.9, 0.25), (0.9, 0.8), (0.6, 0.8), (0.6, 0.66), (0.78, 0.66), (0.78, 0.37),
+ (0.22, 0.37), (0.22, 0.66), (0.4, 0.66), (0.4, 0.8), (0.1, 0.8)), 'red')]
+ if name == 'cloth':
+ return [('f', cs([(0.38, 0.95), (0.38, 0.36), (0.29, 0.25), (0.34, 0.08), (0.56, 0.05), (0.63, 0.2), (0.52, 0.33),
+ (0.6, 0.95)], 3), 'red')]
+ if name == 'chick':
+ return [('f', cs([(0.08, 0.55), (0.3, 0.36), (0.58, 0.3), (0.7, 0.14), (0.84, 0.17), (0.96, 0.27), (0.84, 0.31),
+ (0.79, 0.4), (0.83, 0.58), (0.62, 0.75), (0.42, 0.75), (0.15, 0.63)]), 'yellow'),
+ ('l', A((0.55, 0.74), (0.52, 0.95), (0.63, 0.97)), None), ('l', A((0.45, 0.74), (0.4, 0.95), (0.5, 0.97)), None),
+ ('l', A((0.3, 0.48), (0.62, 0.52)), None), ('f', E(0.77, 0.24, 0.03, 0.03), 'black')]
+ if name == 'owl':
+ return [('f', cs([(0.3, 0.9), (0.24, 0.6), (0.33, 0.3), (0.44, 0.12), (0.62, 0.07), (0.8, 0.14), (0.83, 0.34),
+ (0.73, 0.55), (0.68, 0.8), (0.55, 0.9)]), 'ochre'),
+ ('f', E(0.6, 0.22, 0.06, 0.06), 'white'), ('f', E(0.75, 0.22, 0.06, 0.06), 'white'),
+ ('f', E(0.6, 0.22, 0.025, 0.025), 'black'), ('f', E(0.75, 0.22, 0.025, 0.025), 'black'),
+ ('l', A((0.47, 0.88), (0.45, 0.98)), None), ('l', A((0.58, 0.88), (0.6, 0.98)), None),
+ ('l', A((0.32, 0.45), (0.55, 0.7)), None)]
+ if name == 'vulture':
+ return [('f', cs([(0.04, 0.66), (0.24, 0.42), (0.46, 0.34), (0.6, 0.29), (0.64, 0.13), (0.78, 0.06), (0.9, 0.12),
+ (0.93, 0.2), (0.83, 0.2), (0.79, 0.32), (0.82, 0.52), (0.7, 0.74), (0.45, 0.8), (0.2, 0.76)]), 'lblue'),
+ ('l', A((0.6, 0.78), (0.58, 0.97), (0.7, 0.98)), None), ('l', A((0.24, 0.5), (0.55, 0.62)), None),
+ ('f', E(0.8, 0.14, 0.025, 0.025), 'black')]
+ if name == 'duck':
+ return [('f', cs([(0.02, 0.56), (0.25, 0.46), (0.55, 0.43), (0.68, 0.3), (0.72, 0.13), (0.82, 0.08), (0.88, 0.14),
+ (0.98, 0.21), (0.86, 0.23), (0.8, 0.31), (0.85, 0.55), (0.7, 0.72), (0.35, 0.72)]), 'green'),
+ ('l', A((0.55, 0.72), (0.55, 0.92), (0.64, 0.93)), None), ('l', A((0.3, 0.55), (0.65, 0.6)), None),
+ ('f', E(0.8, 0.15, 0.025, 0.025), 'black')]
+ if name == 'viper':
+ c = spline(A((0.02, 0.86), (0.3, 0.82), (0.5, 0.6), (0.7, 0.8), (0.9, 0.78)), 8)
+ T_ = np.gradient(c, axis=0); T_ /= np.hypot(T_[:, 0], T_[:, 1])[:, None]; N_ = np.stack([-T_[:, 1], T_[:, 0]], 1)
+ wv = np.linspace(0.02, 0.07, len(c))[:, None]
+ body = np.vstack([c + N_ * wv, A((0.98, 0.78), (0.9, 0.7)), (c - N_ * wv)[::-1]])
+ return [('f', body, 'yellow'), ('l', A((0.86, 0.71), (0.84, 0.6)), None), ('l', A((0.92, 0.71), (0.93, 0.6)), None)]
+ if name == 'sickle':
+ return [('f', cs([(0.12, 0.95), (0.1, 0.55), (0.2, 0.3), (0.42, 0.12), (0.7, 0.08), (0.92, 0.15), (0.72, 0.19),
+ (0.46, 0.26), (0.31, 0.42), (0.26, 0.6), (0.27, 0.95)], 3), 'ochre')]
+ if name == 'grain':
+ return [('f', E(0.3, 0.68, 0.1, 0.14), 'ochre'), ('f', E(0.5, 0.42, 0.1, 0.14), 'ochre'), ('f', E(0.7, 0.68, 0.1, 0.14), 'ochre')]
+ if name == 'jar':
+ return [('f', cs([(0.36, 0.95), (0.25, 0.75), (0.22, 0.5), (0.3, 0.32), (0.39, 0.25), (0.37, 0.14), (0.63, 0.14),
+ (0.61, 0.25), (0.7, 0.32), (0.78, 0.5), (0.75, 0.75), (0.64, 0.95)], 3), 'red'),
+ ('l', A((0.3, 0.33), (0.18, 0.4), (0.24, 0.52)), None), ('l', A((0.7, 0.33), (0.82, 0.4), (0.76, 0.52)), None)]
+ if name == 'scroll':
+ return [('f', A((0.05, 0.38), (0.95, 0.38), (0.95, 0.62), (0.05, 0.62)), 'white'),
+ ('f', A((0.45, 0.33), (0.55, 0.33), (0.55, 0.67), (0.45, 0.67)), 'red')]
+ if name == 'pool':
+ return [('f', A((0.05, 0.3), (0.95, 0.3), (0.95, 0.68), (0.05, 0.68)), 'blue'),
+ ('l', A((0.2, 0.36), (0.2, 0.62)), None), ('l', A((0.4, 0.36), (0.4, 0.62)), None),
+ ('l', A((0.6, 0.36), (0.6, 0.62)), None), ('l', A((0.8, 0.36), (0.8, 0.62)), None)]
+ if name == 'flax':
+ t = np.linspace(0, 1, 50)
+ return [('l', np.stack([0.5 + 0.13 * np.sin(t * 6 * np.pi), 0.05 + 0.9 * t + 0.04 * np.cos(t * 6 * np.pi)], 1), 'blue')]
+ if name == 'bolt':
+ return [('f', A((0.05, 0.43), (0.78, 0.43), (0.95, 0.5), (0.78, 0.57), (0.05, 0.57)), 'green'),
+ ('f', A((0.2, 0.38), (0.28, 0.38), (0.28, 0.62), (0.2, 0.62)), 'green')]
+ if name == 'hoe':
+ return [('f', A((0.2, 0.06), (0.3, 0.1), (0.95, 0.86), (0.88, 0.93)), 'ochre'),
+ ('f', A((0.2, 0.06), (0.28, 0.1), (0.3, 0.9), (0.04, 0.95)), 'brown'),
+ ('l', A((0.22, 0.5), (0.55, 0.47)), None)]
+ if name == 'nfr':
+ return [('f', E(0.5, 0.74, 0.19, 0.2), 'red'), ('f', A((0.46, 0.05), (0.54, 0.05), (0.54, 0.56), (0.46, 0.56)), 'black'),
+ ('l', A((0.36, 0.2), (0.64, 0.2)), None)]
+ raise KeyError(name)
+
+ SIGNS = ['reed', 'water', 'mouth', 'loaf', 'sun', 'foot', 'hand', 'basket', 'house', 'cloth', 'chick', 'owl', 'vulture',
+ 'duck', 'viper', 'sickle', 'grain', 'jar', 'scroll', 'pool', 'flax', 'bolt', 'nfr']
+
+ def _sign_box(self, name):
+ g = self._sign(name)
+ allp = np.vstack([q for _, q, _ in g])
+ return allp[:, 0].min(), allp[:, 1].min(), allp[:, 0].max(), allp[:, 1].max()
+
+ def glyph(self, name, x, y, size, facing=1, z=None, lw=None, mono=None):
+ """one sign whose em box has its top-left at (x, y); facing +1 looks right. mono: paint it in one colour"""
+ lw = lw or max(1.0, size * 0.035)
+ F = 1 if facing >= 0 else -1
+ z0 = self._z if z is None else z
+ self._z = z0 + 1
+ for k, (kind, q, col) in enumerate(self._sign(name)):
+ q = np.asarray(q, np.float32)
+ P = np.stack([x + (q[:, 0] if F > 0 else 1 - q[:, 0]) * size, y + q[:, 1] * size], 1)
+ if kind == 'f':
+ c = mono if (mono and col not in ('white', 'black')) else col
+ self.part(P, c, z=z0 + k * 0.01, width=lw, layer='text', rag=0.3)
+ else:
+ ink = INK; w = lw
+ if col == 'thick': w = size * 0.08; ink = INK
+ elif col == 'thickb': w = size * 0.1; ink = '#7b4a2c'
+ elif col == 'blue': w = size * 0.07; ink = PIGMENTS['blue']
+ self.part(None, None, paths=[P], ink=ink, width=w, z=z0 + k * 0.01, layer='text')
+
+ def text(self, n=8, seed=None, signs=None):
+ """a pseudo-text: a list of sign names (no repeats in a row)"""
+ r = np.random.default_rng(seed if seed is not None else self._seed())
+ pool = signs or self.SIGNS
+ out = []
+ for i in range(n):
+ s = pool[int(r.integers(len(pool)))]
+ while out and s == out[-1]:
+ s = pool[int(r.integers(len(pool)))]
+ out.append(s)
+ return out
+
+ def column(self, x0, y0, x1, y1, signs=None, facing=1, n=40, gap=0.14, rules=True, seed=None, mono=None, lw=1.6):
+ """a vertical column of signs between x0 and x1, laid out by quadrats from the top; stops when full.
+ rules: draw the black dividing lines on both sides. Returns the y where the text ended."""
+ W = x1 - x0
+ em = W * 0.86
+ seq = list(signs) if signs is not None else self.text(n, seed)
+ boxes = {s: self._sign_box(s) for s in set(seq)}
+ y = y0 + em * 0.08
+ i = 0
+ while i < len(seq):
+ a = seq[i]; bx = boxes[a]; wa, ha = bx[2] - bx[0], bx[3] - bx[1]
+ group = [a]
+ if i + 1 < len(seq):
+ b = seq[i + 1]; bb = boxes[b]; wb_, hb = bb[2] - bb[0], bb[3] - bb[1]
+ if (wa <= 0.5 and wb_ <= 0.5) or (wa <= 0.7 and ha <= 0.7 and wb_ <= 0.7 and hb <= 0.7 and wa + wb_ <= 1.3):
+ group = [a, b]; mode = 'side'
+ elif ha <= 0.45 and hb <= 0.45:
+ group = [a, b]; mode = 'stack'
+ if len(group) == 1:
+ mode = 'one'
+ if mode == 'side':
+ ws = [boxes[s][2] - boxes[s][0] for s in group]; hs = [boxes[s][3] - boxes[s][1] for s in group]
+ scale = min(1.0, 0.95 / (sum(ws) + 0.08))
+ rowh = max(hs) * em * scale
+ xx = x0 + (W - (sum(ws) + 0.08) * em * scale) / 2
+ if y + rowh > y1: break
+ order = group if facing >= 0 else group[::-1]
+ for s in order:
+ b = boxes[s]
+ gx = xx - (b[0] if facing >= 0 else (1 - b[2])) * em * scale
+ gy = y + (rowh - (b[3] - b[1]) * em * scale) / 2 - b[1] * em * scale
+ self.glyph(s, gx, gy, em * scale, facing, mono=mono)
+ xx += ((b[2] - b[0]) + 0.08) * em * scale
+ y += rowh + gap * em; i += 2
+ elif mode == 'stack':
+ hs = [boxes[s][3] - boxes[s][1] for s in group]
+ rowh = (sum(hs) + 0.06) * em
+ if y + rowh > y1: break
+ yy = y
+ for s in group:
+ b = boxes[s]; wdt = b[2] - b[0]
+ gx = x0 + (W - wdt * em) / 2 - (b[0] if facing >= 0 else (1 - b[2])) * em
+ self.glyph(s, gx, yy - b[1] * em, em, facing, mono=mono)
+ yy += ((b[3] - b[1]) + 0.06) * em
+ y += rowh + gap * em; i += 2
+ else:
+ b = boxes[a]
+ rowh = (b[3] - b[1]) * em
+ if y + rowh > y1: break
+ gx = x0 + (W - wa * em) / 2 - (b[0] if facing >= 0 else (1 - b[2])) * em
+ self.glyph(a, gx, y - b[1] * em, em, facing, mono=mono)
+ y += rowh + gap * em; i += 1
+ if rules:
+ for xx in (x0, x1):
+ self.part(None, None, paths=[np.array([[xx, y0], [xx, y1]], np.float32)], width=lw, layer='text')
+ return y
+
+ def numerals(self, value, x, y, size, facing=1):
+ """a hieroglyphic number: hundreds as coils, tens as heel-bones, units as strokes (left to right)"""
+ h, t, u = value // 100, (value // 10) % 10, value % 10
+ xx = x
+ for _ in range(h):
+ self.glyph('coil', xx - size * 0.2, y, size, facing); xx += size * 0.5
+ for _ in range(t):
+ self.glyph('heel', xx - size * 0.15, y, size, facing); xx += size * 0.78
+ for i in range(u):
+ self.glyph('stroke', xx - size * 0.42, y, size, facing); xx += size * 0.3
+ return xx
+
+ # ------------------------------------------------------------------ 3,300 years
+ def age(self, losses=(), cracks=9, flake=1.0, soot=0.5, fade=0.55, salt=0.5, specks=1.0, wear_amt=1.0, tide=0.5,
+ zones=(), seed=None):
+ """what time does to a secco painting. losses: [(x, y, rx, ry), ...] plaster lost down to the mud;
+ zones: [(x, y, r), ...] patches where the paint has come away down to the plaster (the red grid and
+ sketch show through there)."""
+ H, W = self.H, self.W
+ r = np.random.default_rng(seed if seed is not None else self._seed())
+ sd = lambda: int(r.integers(1 << 30))
+ yy = np.linspace(0, 1, H, dtype=np.float32)[:, None]
+ xx = np.linspace(0, 1, W, dtype=np.float32)[None, :]
+ # ---- cracks: wandering grooves with branches
+ crk = Image.new('L', (W * 2, H * 2), 0); d = ImageDraw.Draw(crk)
+ crack_paths = []
+ for i in range(cracks):
+ x, y = r.uniform(0, W), r.choice([r.uniform(0, H * 0.3), r.uniform(H * 0.7, H), r.uniform(0, H)])
+ a = r.uniform(0, 2 * np.pi); L = r.uniform(180, 620)
+ pts = [(x, y)]
+ for s in range(int(L / 5)):
+ a += r.normal(0, 0.28); x += np.cos(a) * 5; y += np.sin(a) * 5
+ pts.append((x, y))
+ if r.random() < 0.012:
+ b = a + r.choice([-1, 1]) * r.uniform(0.6, 1.2); bx, by = x, y; br = [(bx, by)]
+ for _ in range(int(r.uniform(10, 40))):
+ b += r.normal(0, 0.3); bx += np.cos(b) * 4; by += np.sin(b) * 4; br.append((bx, by))
+ crack_paths.append((br, 1.6))
+ crack_paths.append((pts, 2.6))
+ for pts, wdt in crack_paths:
+ d.line([(px * 2, py * 2) for px, py in pts], fill=255, width=int(wdt), joint='curve')
+ C = np.asarray(crk.resize((W, H), Image.BOX), np.float32) / 255
+ near_crack = blur(C, 3.0) * 4
+ # ---- paint flakes (to the ground) and deeper flakes (to the plaster)
+ vul = 0.25 + 0.3 * self.bluemap + 0.35 * np.clip(near_crack, 0, 1) + 0.2 * salt * smoothstep(0.78, 1.0, yy)
+ vul += 0.25 * smoothstep(0.82, 1.0, np.maximum(np.abs(xx - 0.5) * 2, 0))
+ n1 = noise2d(H, W, 7, 3, sd()); n2 = noise2d(H, W, 60, 3, sd())
+ f1 = smoothstep(0.66, 0.7, n1 * 0.4 + n2 * 0.6 + (vul - 0.5) * 0.35 * flake)
+ f1 = np.maximum(f1, smoothstep(0.5, 0.56, np.clip(near_crack, 0, 1) * noise2d(H, W, 4, 2, sd()) * 1.2) * flake)
+ f1 *= smoothstep(0.02, 0.2, self.paintmap) # only where something was painted over the ground
+ n3 = noise2d(H, W, 5, 2, sd())
+ f2 = smoothstep(0.72, 0.76, n1 * 0.4 + n2 * 0.6 + (vul - 0.5) * 0.3 * flake) * smoothstep(0.35, 0.6, n3)
+ if zones:
+ zm = np.zeros((H, W), np.float32)
+ Y, X = np.mgrid[0:H, 0:W].astype(np.float32)
+ for (zx, zy, zr) in zones:
+ y0_, y1_ = int(max(0, zy - 2 * zr)), int(min(H, zy + 2 * zr)); x0_, x1_ = int(max(0, zx - 2 * zr)), int(min(W, zx + 2 * zr))
+ dd = np.hypot(X[y0_:y1_, x0_:x1_] - zx, Y[y0_:y1_, x0_:x1_] - zy) / zr
+ zm[y0_:y1_, x0_:x1_] = np.maximum(zm[y0_:y1_, x0_:x1_], np.clip(1.3 - dd, 0, 1))
+ edge = noise2d(H, W, 14, 3, sd()) * 0.55 + n1 * 0.25 + noise2d(H, W, 3, 2, sd()) * 0.2
+ zf = smoothstep(0.5, 0.54, zm * 0.8 + (edge - 0.5) * 1.1)
+ f2 = np.maximum(f2, zf)
+ f1 = np.maximum(f1, smoothstep(0.42, 0.46, zm * 0.8 + (edge - 0.5) * 1.1)) # a stepped halo of lost paint
+ # ---- losses down to the mud
+ f3 = np.zeros((H, W), np.float32)
+ for (lx, ly, rx, ry) in losses:
+ th = np.linspace(0, 2 * np.pi, 64, endpoint=False)
+ wob = 1 + 0.22 * fbm1d(64, 8, 4, sd())
+ pts = np.stack([lx + np.cos(th) * rx * wob, ly + np.sin(th) * ry * wob], 1)
+ res = self._poly_mask([pts])
+ if res:
+ m, (x0, y0, x1, y1) = res
+ f3[y0:y1, x0:x1] = np.maximum(f3[y0:y1, x0:x1], m)
+ edge_noise = noise2d(H, W, 10, 3, sd()) * 0.7 + noise2d(H, W, 3, 2, sd()) * 0.3
+ f3 = smoothstep(0.47, 0.53, blur(f3, 3) + (edge_noise - 0.5) * 0.6)
+ chips = smoothstep(0.85, 0.89, noise2d(H, W, 9, 3, sd()) * 0.6 + n2 * 0.25 + 0.3 * smoothstep(0.86, 1.0, yy)
+ + 0.25 * smoothstep(0.9, 1.0, np.abs(xx - 0.5) * 2))
+ f3 = np.maximum(f3, chips * salt)
+ # around a loss the paint has flaked back in steps, and a ragged band of white gypsum shows
+ around = np.clip(blur(f3, 7) * 3, 0, 1)
+ f1 = np.maximum(f1, smoothstep(0.35, 0.6, around * (0.6 + 0.6 * n1)))
+ f2 = np.maximum(f2, smoothstep(0.55, 0.8, around * (0.5 + 0.7 * n3)))
+ rim = np.clip(smoothstep(0.22, 0.5, blur(f3, 1.4) + (edge_noise - 0.5) * 0.7) - f3, 0, 1)
+ # paint rubbed thin in soft patches (hands, dust, brushing): partly back toward the ground or plaster
+ wear = smoothstep(0.62, 0.9, noise2d(H, W, 26, 3, sd()) * 0.6 + n2 * 0.4) * 0.55 * wear_amt
+ # ---- composite the strata
+ img = self.img.copy()
+ img = img * (1 - wear[..., None]) + (self.ground_img * 0.6 + self.under * 0.4) * wear[..., None]
+ img = img * (1 - f1[..., None]) + self.ground_img * f1[..., None]
+ img = img * (1 - f2[..., None]) + self.under * f2[..., None]
+ img = img * (1 - rim[..., None]) + self.plaster * 0.93 * rim[..., None]
+ img = img * (1 - f3[..., None]) + self.mud * f3[..., None]
+ # ---- relief: a height field of the strata (px), lit from the upper left, shadows cast into the holes
+ hgt = -0.5 * f1 - 0.6 * f2 - 1.0 * rim - 8.0 * f3 + (self.mud.mean(-1) - 0.3) * 3.0 * f3
+ hb = blur(hgt, 0.7)
+ gy, gx = np.gradient(hb)
+ lit = np.clip(1 - 0.5 * (gx * self.light[0] + gy * self.light[1]), 0.5, 1.15)
+ img *= lit[..., None]
+ shd = height_shadow(hb, light=(self.light[0], self.light[1], 0.62), reach=30, step=1.0, soft=1.2)
+ img *= (1 - 0.55 * shd)[..., None]
+ ao = np.clip(blur(1 - f3, 6) * 1.6, 0, 1) * f3 # the floor of a hole gets less light near its walls
+ img *= (1 - 0.3 * ao)[..., None]
+ # cracks: dark groove, lit lower lip
+ img *= (1 - 0.6 * C)[..., None]
+ lip = np.clip(shift(C, 1, 1) - C, 0, 1)
+ img = img + (1 - img) * 0.18 * lip[..., None]
+ # ---- Egyptian blue decaying toward grey-green, pigments dulling
+ fz = self.bluemap * fade * (0.45 + 0.55 * noise2d(H, W, 40, 3, sd()))
+ img = img * (1 - fz[..., None]) + (img.mean(-1, keepdims=True) * 0.5 + hexc('#6f8b84') * 0.5) * fz[..., None]
+ grey = img.mean(-1, keepdims=True)
+ img = img * 0.9 + grey * 0.1
+ # ---- grime and soot (lamp smoke rising to the ceiling), salt bloom near the floor
+ g = noise2d(H, W, 220, 4, sd())
+ grime = soot * (0.35 * smoothstep(0.4, 0.0, yy) + 0.12) * (0.4 + 0.8 * g)
+ img *= (1 - 0.35 * grime[..., None] * (1 - hexc('#4a3a2c')[None, None, :]))
+ blob = smoothstep(0.55, 0.85, noise2d(H, W, 300, 2, sd())) * smoothstep(0.5, 0.0, yy)
+ img *= (1 - 0.14 * soot * blob)[..., None]
+ if tide: # moisture rose from the floor and dried at a ragged line
+ tl = 0.82 + 0.04 * fbm1d(W, 400, 4, sd())[None, :]
+ below = smoothstep(tl - 0.004, tl + 0.05, yy)
+ line = np.exp(-((yy - tl) / 0.012) ** 2) * (0.6 + 0.4 * noise2d(H, W, 40, 2, sd()))
+ img *= (1 - tide * (0.08 * below + 0.12 * line))[..., None]
+ img = img * (1 - (tide * 0.12 * below)[..., None]) + hexc('#8a6a48') * (tide * 0.12 * below)[..., None]
+ sb = salt * smoothstep(0.75, 1.0, yy) * smoothstep(0.55, 0.8, noise2d(H, W, 30, 3, sd()))
+ img = img * (1 - 0.35 * sb[..., None]) + hexc('#efe9dd') * 0.35 * sb[..., None]
+ # ---- fly specks and dust
+ if specks:
+ sp2 = Image.new('L', (W * 2, H * 2), 0); d2 = ImageDraw.Draw(sp2)
+ for _ in range(int(350 * specks)):
+ x, y = r.uniform(0, W * 2), r.uniform(0, H * 2); rr = r.uniform(0.9, 2.4)
+ d2.ellipse([x - rr, y - rr, x + rr, y + rr], fill=int(r.uniform(140, 255)))
+ S = np.asarray(sp2.resize((W, H), Image.BOX), np.float32) / 255
+ img *= (1 - 0.55 * S[..., None])
+ img += (self.T_grain[..., None] - 0.5) * 0.025
+ vg = ((xx - 0.5) ** 2 * 1.2 + (yy - 0.48) ** 2 * 1.6) # lamp-lit falloff toward the corners
+ img *= (1 - 0.16 * vg)[..., None]
+ self.img = np.clip(img, 0, 1)
+ self.flakemap = np.clip(f1 + f2 + f3, 0, 1)
+
+ # ------------------------------------------------------------------ stages
+ def stage(self, name):
+ self.stages.append((name, self.image()))
+
+ def image(self):
+ return Image.fromarray((np.clip(self.img, 0, 1) * 255 + 0.5).astype(np.uint8))
+
+ def save(self, path, stages_dir=None, quality=88):
+ img = self.image()
+ if str(path).lower().endswith(('.jpg', '.jpeg')):
+ img.save(path, quality=quality, subsampling=0)
+ else:
+ img.save(path)
+ if stages_dir:
+ import os
+ os.makedirs(stages_dir, exist_ok=True)
+ for i, (name, im) in enumerate(self.stages):
+ im.save(f"{stages_dir}/{i:02d}_{name}.png")
+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")
+ return img