Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

giornate.gno

39.41 Kb · 1271 lines
   1// Package giornate (v2, "Wall Scenes") is a Sinopia signature engine: a
   2// fresco wall with a real scene on it (a procession, a gathering, an
   3// encounter at a city gate, an Annunciation, a lone saint or a landscape),
   4// caught mid-work. A fresco is painted on wet plaster one day-patch
   5// (giornata) at a time, from the top of the wall down. Finished patches show
   6// the scene in pigment; the rest of the wall still shows the same scene as
   7// the red-ochre sinopia underdrawing on the rough arriccio plaster, with its
   8// squaring grid, compass-drawn haloes and hatching. Where the painted plaster
   9// has fallen away (lacunae) the sinopia shows through again, as it does on
  10// real walls.
  11//
  12// Every element of the scene is defined once in <defs> and drawn twice with
  13// <use>: filled in the painted layer, outlined in the sinopia layer. That
  14// keeps figure-heavy walls small.
  15//
  16// Everything is integer maths (a 64-step quarter-sine table, truncating
  17// division), so the TypeScript twin in frontend/src/engines/giornatev2.ts is
  18// byte-identical. Two RNG streams come from the seed: seed+"|traits" decides
  19// the traits (cheap, no geometry: Traits never renders) and seed+"|art"
  20// draws the picture, so art draws never shift traits.
  21package giornate
  22
  23import (
  24	"errors"
  25	"strconv"
  26	"strings"
  27
  28	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/engine/v2"
  29)
  30
  31// Trait types in the order Traits returns them.
  32var traitTypes = []string{"Scene", "Pigments", "Sky", "Completion", "Giornate", "Drawing", "Condition", "Rarity"}
  33
  34// MaxSVGBytes: see docs/engines/giornate-v2.md for the measured sizes.
  35const MaxSVGBytes = 28672
  36
  37const paramsSchema = `{"type":"object","additionalProperties":false,"properties":{` +
  38	`"palette":{"type":"string","title":"Pigments","enum":["Seeded","Terra Verde","Lapis & Ochre","Cinnabar","Pompeian","Umber","Rose Madder","Verdaccio"],"default":"Seeded"},` +
  39	`"scene":{"type":"string","title":"Scene","enum":["Seeded","Procession","Gathering","Encounter","Annunciation","Lone Figure","Landscape"],"default":"Seeded"},` +
  40	`"sky":{"type":"string","title":"Sky","enum":["Seeded","Clear Sky","Starry Vault","Gold Ground"],"default":"Seeded"},` +
  41	`"stage":{"type":"string","title":"Completion","enum":["Seeded","Pure Sinopia","Fresh Start","Half Wall","Advanced","Nearly Done","Finished"],"default":"Seeded"}}}`
  42
  43// Manifest describes the engine. Author and FeeBps are set by the adapter.
  44func Manifest() engine.Manifest {
  45	return engine.Manifest{
  46		Name:    "Giornate II",
  47		Version: "2.0.0",
  48		Description: "A fresco wall with a real scene, caught mid-work: finished day-patches (giornate) " +
  49			"in pigment, the rest still in the red sinopia underdrawing the platform is named after.",
  50		License:      "CC-BY-NC-4.0",
  51		ParamsSchema: paramsSchema,
  52		TraitTypes:   append([]string{}, traitTypes...),
  53		Living:       false,
  54		MaxSVGBytes:  MaxSVGBytes,
  55		Kind:         engine.KindSVG,
  56	}
  57}
  58
  59// ---------------------------------------------------------------------------
  60// Params: "" (the showcase look) or exactly the canonical JSON Studio sends,
  61// keys in schema order, no whitespace:
  62//   {"palette":"Seeded","scene":"Annunciation","sky":"Seeded","stage":"Seeded"}
  63// "Seeded" leaves that trait to the seed. Anything else is rejected.
  64// ---------------------------------------------------------------------------
  65
  66type params struct {
  67	palette, scene, sky, stage int // table index, -1 = seeded
  68}
  69
  70func parseParams(s string) (params, error) {
  71	p := params{-1, -1, -1, -1}
  72	if s == "" {
  73		return p, nil
  74	}
  75	keys := []string{`{"palette":"`, `","scene":"`, `","sky":"`, `","stage":"`}
  76	tables := [][]string{pigmentNames(), names(scenes), names(skies), names(stages)}
  77	out := []int{0, 0, 0, 0}
  78	rest := s
  79	for i, k := range keys {
  80		if !strings.HasPrefix(rest, k) {
  81			return p, errors.New("giornate params: expected " + strconv.Quote(k))
  82		}
  83		rest = rest[len(k):]
  84		end := strings.IndexByte(rest, '"')
  85		if end < 0 || strings.IndexByte(rest[:end], '\\') >= 0 {
  86			return p, errors.New("giornate params: bad value")
  87		}
  88		v := rest[:end]
  89		rest = rest[end:]
  90		idx, ok := lookup(v, tables[i])
  91		if !ok {
  92			return p, errors.New("giornate params: unknown value " + strconv.Quote(v))
  93		}
  94		out[i] = idx
  95	}
  96	if rest != `"}` {
  97		return p, errors.New("giornate params: expected end of object")
  98	}
  99	return params{out[0], out[1], out[2], out[3]}, nil
 100}
 101
 102func lookup(v string, names []string) (int, bool) {
 103	if v == "Seeded" {
 104		return -1, true
 105	}
 106	for i, n := range names {
 107		if n == v {
 108			return i, true
 109		}
 110	}
 111	return -1, false
 112}
 113
 114// ValidateParams accepts "" and the canonical params JSON only.
 115func ValidateParams(s string) error {
 116	_, err := parseParams(s)
 117	return err
 118}
 119
 120// Traits returns the eight traits of in.Seed under in.Params. It never
 121// renders: one 7-draw RNG pass and a few table walks.
 122func Traits(in engine.Input) []engine.Trait {
 123	t := TraitsWith(in.Seed, in.Params)
 124	return []engine.Trait{
 125		{Type: "Scene", Value: t.Scene},
 126		{Type: "Pigments", Value: t.Pigments},
 127		{Type: "Sky", Value: t.Sky},
 128		{Type: "Completion", Value: t.Completion},
 129		{Type: "Giornate", Value: t.Giornate},
 130		{Type: "Drawing", Value: t.Drawing},
 131		{Type: "Condition", Value: t.Condition},
 132		{Type: "Rarity", Value: t.Rarity},
 133	}
 134}
 135
 136// Render returns the raw SVG for in.Seed under in.Params. Core validates
 137// params before every render; invalid params panic.
 138func Render(in engine.Input) string { return SVGWith(in.Seed, in.Params) }
 139
 140// SVG renders a seed with the default (showcase) params.
 141func SVG(seed string) string { return SVGWith(seed, "") }
 142
 143// TraitsOf decodes a seed with the default params.
 144func TraitsOf(seed string) TraitSet { return TraitsWith(seed, "") }
 145
 146// ---------------------------------------------------------------------------
 147// Deterministic randomness: FNV-1a over the seed, then splitmix64 (as v1).
 148// ---------------------------------------------------------------------------
 149
 150const (
 151	fnvOffset uint64 = 14695981039346656037
 152	fnvPrime  uint64 = 1099511628211
 153)
 154
 155type rng struct{ state uint64 }
 156
 157func newRNG(seed string) *rng {
 158	h := fnvOffset
 159	for i := 0; i < len(seed); i++ {
 160		h ^= uint64(seed[i])
 161		h *= fnvPrime
 162	}
 163	if h == 0 {
 164		h = fnvPrime
 165	}
 166	return &rng{state: h}
 167}
 168
 169func (r *rng) next() uint64 {
 170	r.state += 0x9E3779B97F4A7C15
 171	z := r.state
 172	z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9
 173	z = (z ^ (z >> 27)) * 0x94D049BB133111EB
 174	return z ^ (z >> 31)
 175}
 176
 177// intn returns a value in [0, n).
 178func (r *rng) intn(n int) int {
 179	if n <= 0 {
 180		return 0
 181	}
 182	return int(r.next() % uint64(n))
 183}
 184
 185// rr returns a value in [a, b].
 186func (r *rng) rr(a, b int) int { return a + r.intn(b-a+1) }
 187
 188// pick walks cumulative weights once.
 189func (r *rng) pick(weights []int) int {
 190	total := 0
 191	for _, w := range weights {
 192		total += w
 193	}
 194	roll := r.intn(total)
 195	for i, w := range weights {
 196		roll -= w
 197		if roll < 0 {
 198			return i
 199		}
 200	}
 201	return len(weights) - 1
 202}
 203
 204// Quarter sine, 64 steps per quarter turn, scaled by 1024.
 205var qsin = []int{0, 25, 50, 75, 100, 125, 150, 175, 200, 224, 249, 273, 297, 321, 345, 369, 392, 415, 438, 460,
 206	483, 505, 526, 548, 569, 590, 610, 630, 650, 669, 688, 706, 724, 742, 759, 775, 792, 807, 822,
 207	837, 851, 865, 878, 891, 903, 915, 926, 936, 946, 955, 964, 972, 980, 987, 993, 999, 1004, 1009,
 208	1013, 1016, 1019, 1021, 1023, 1024, 1024}
 209
 210// isin takes an angle in 1/256 turn and returns sin*1024.
 211func isin(a int) int {
 212	a = ((a % 256) + 256) % 256
 213	switch {
 214	case a < 64:
 215		return qsin[a]
 216	case a < 128:
 217		return qsin[128-a]
 218	case a < 192:
 219		return -qsin[a-128]
 220	}
 221	return -qsin[256-a]
 222}
 223
 224func icos(a int) int { return isin(a + 64) }
 225
 226// ---------------------------------------------------------------------------
 227// Trait tables. Weights per table sum to 100; score feeds the rarity tier.
 228// ---------------------------------------------------------------------------
 229
 230type option struct {
 231	name   string
 232	weight int
 233	score  int
 234}
 235
 236// pigment: cols = robe, second robe, accent, light (walls, frame), land.
 237type pigment struct {
 238	option
 239	flesh, dark string
 240	cols        []string
 241}
 242
 243var pigments = []pigment{
 244	{option{"Terra Verde", 18, 0}, "#e6c3a0", "#2f2a22", []string{"#6f8a5e", "#c69a5a", "#a8553f", "#e2d3b0", "#4f6a52"}},
 245	{option{"Lapis & Ochre", 17, 0}, "#e6c3a0", "#1f2433", []string{"#2f4f8a", "#c9893a", "#b5452f", "#e8dcc0", "#7a5a8a"}},
 246	{option{"Cinnabar", 15, 0}, "#e8c2a0", "#2a1d19", []string{"#c0392b", "#e6c178", "#3b5a7a", "#efe3c8", "#6a7a4a"}},
 247	{option{"Pompeian", 13, 1}, "#ddb08c", "#1d1a17", []string{"#9e2a22", "#d8b24a", "#2f2a26", "#e9d6b0", "#5a7a6a"}},
 248	{option{"Umber", 14, 0}, "#e2bf9a", "#1e1a17", []string{"#6a4a32", "#b88a52", "#3f4a3a", "#e2d2b2", "#8a3a2a"}},
 249	{option{"Rose Madder", 13, 1}, "#ecc8aa", "#3a2630", []string{"#c96b7a", "#6f8fb0", "#e3c27a", "#efe2cc", "#8a6aa0"}},
 250	{option{"Verdaccio", 10, 2}, "#cfc29c", "#34362a", []string{"#5f6b4a", "#9a8a5a", "#b98a6a", "#ddd2b6", "#7a6a5a"}},
 251}
 252
 253const (
 254	scProcession = iota
 255	scGathering
 256	scEncounter
 257	scAnnunciation
 258	scLone
 259	scLandscape
 260)
 261
 262var scenes = []option{
 263	{"Procession", 24, 0}, {"Gathering", 22, 0}, {"Encounter", 20, 0},
 264	{"Annunciation", 8, 3}, {"Lone Figure", 14, 2}, {"Landscape", 12, 2},
 265}
 266
 267const (
 268	skyClear = iota
 269	skyStarry
 270	skyGold
 271)
 272
 273var skies = []option{{"Clear Sky", 40, 0}, {"Starry Vault", 36, 1}, {"Gold Ground", 24, 2}}
 274
 275const (
 276	stPure = iota
 277	stFresh
 278	stHalf
 279	stAdvanced
 280	stNearly
 281	stFinished
 282)
 283
 284var stages = []option{
 285	{"Pure Sinopia", 6, 3}, {"Fresh Start", 16, 1}, {"Half Wall", 26, 0},
 286	{"Advanced", 26, 0}, {"Nearly Done", 18, 1}, {"Finished", 8, 2},
 287}
 288
 289// giornate buckets: patch-count ranges in lo/hi.
 290type bucket struct {
 291	option
 292	lo, hi int
 293}
 294
 295var buckets = []bucket{
 296	{option{"Few", 18, 1}, 6, 9},
 297	{option{"Several", 34, 0}, 10, 14},
 298	{option{"Many", 32, 0}, 15, 20},
 299	{option{"Countless", 16, 1}, 21, 28},
 300}
 301
 302const (
 303	drLine = iota
 304	drSpolvero
 305	drPentimento
 306)
 307
 308var drawings = []option{{"Sinopia Line", 72, 0}, {"Spolvero", 16, 2}, {"Pentimento", 12, 3}}
 309
 310const (
 311	cdIntact = iota
 312	cdCraquelure
 313	cdLacunae
 314	cdRuined
 315)
 316
 317var conditions = []option{{"Intact", 40, 0}, {"Craquelure", 30, 0}, {"Lacunae", 20, 1}, {"Ruined", 10, 2}}
 318
 319func names(t []option) []string {
 320	out := make([]string, len(t))
 321	for i, o := range t {
 322		out[i] = o.name
 323	}
 324	return out
 325}
 326
 327func pigmentNames() []string {
 328	out := make([]string, len(pigments))
 329	for i, p := range pigments {
 330		out[i] = p.name
 331	}
 332	return out
 333}
 334
 335func weights(t []option) []int {
 336	out := make([]int, len(t))
 337	for i, o := range t {
 338		out[i] = o.weight
 339	}
 340	return out
 341}
 342
 343func pigmentWeights() []int {
 344	out := make([]int, len(pigments))
 345	for i, p := range pigments {
 346		out[i] = p.weight
 347	}
 348	return out
 349}
 350
 351func bucketWeights() []int {
 352	out := make([]int, len(buckets))
 353	for i, b := range buckets {
 354		out[i] = b.weight
 355	}
 356	return out
 357}
 358
 359// Weights per table, built once at package init (Traits runs for hundreds of
 360// tokens per query).
 361var (
 362	pigmentW   = pigmentWeights()
 363	sceneW     = weights(scenes)
 364	skyW       = weights(skies)
 365	stageW     = weights(stages)
 366	bucketW    = bucketWeights()
 367	drawingW   = weights(drawings)
 368	conditionW = weights(conditions)
 369)
 370
 371// Tier cut-offs on the score, chosen on a 10,000-seed simulation with
 372// default params (docs/engines/giornate-v2.md has the distribution).
 373const (
 374	scoreMythic    = 9
 375	scoreLegendary = 7
 376	scoreRare      = 5
 377	scoreUncommon  = 3
 378)
 379
 380// TraitSet is a decoded seed. The SVG builder and the trait list read the
 381// same struct, so picture and metadata cannot disagree.
 382type TraitSet struct {
 383	Scene, Pigments, Sky, Completion, Giornate, Drawing, Condition string
 384	Score                                                          int
 385	Rarity                                                         string
 386
 387	pig, scene, sky, stage, gio, draw, cond int // table indices actually used
 388}
 389
 390// derive draws all seven picks in a fixed order (the order is part of the
 391// contract), then applies params. A trait fixed by params or hidden by the
 392// completion stage adds nothing to the score: rarity only counts what the
 393// seed chose and the picture shows.
 394func derive(seed string, p params) TraitSet {
 395	r := newRNG(seed + "|traits")
 396	t := TraitSet{
 397		pig:   r.pick(pigmentW),
 398		scene: r.pick(sceneW),
 399		sky:   r.pick(skyW),
 400		stage: r.pick(stageW),
 401		gio:   r.pick(bucketW),
 402		draw:  r.pick(drawingW),
 403		cond:  r.pick(conditionW),
 404	}
 405	score := 0
 406	if p.scene >= 0 {
 407		t.scene = p.scene
 408	} else {
 409		score += scenes[t.scene].score
 410	}
 411	if p.sky >= 0 {
 412		t.sky = p.sky
 413	} else {
 414		score += skies[t.sky].score
 415	}
 416	if p.stage >= 0 {
 417		t.stage = p.stage
 418	} else {
 419		score += stages[t.stage].score
 420	}
 421	if p.palette >= 0 {
 422		t.pig = p.palette
 423	}
 424	t.Scene = scenes[t.scene].name
 425	t.Pigments = pigments[t.pig].name
 426	t.Sky = skies[t.sky].name
 427	t.Completion = stages[t.stage].name
 428	t.Giornate = buckets[t.gio].name
 429	t.Drawing = drawings[t.draw].name
 430	t.Condition = conditions[t.cond].name
 431	score += conditions[t.cond].score
 432	if t.stage == stPure { // no pigment and no day-patch shows yet
 433		t.Pigments = "Unpainted"
 434		t.Giornate = "None"
 435	} else {
 436		score += buckets[t.gio].score
 437		if p.palette < 0 {
 438			score += pigments[t.pig].score
 439		}
 440	}
 441	if t.stage == stFinished && t.draw != drPentimento && (t.cond == cdIntact || t.cond == cdCraquelure) {
 442		// the drawing is painted over everywhere (no loss reopens it)
 443		t.Drawing = "Covered"
 444	} else {
 445		score += drawings[t.draw].score
 446	}
 447	t.Score = score
 448	switch {
 449	case score >= scoreMythic:
 450		t.Rarity = "Mythic"
 451	case score >= scoreLegendary:
 452		t.Rarity = "Legendary"
 453	case score >= scoreRare:
 454		t.Rarity = "Rare"
 455	case score >= scoreUncommon:
 456		t.Rarity = "Uncommon"
 457	default:
 458		t.Rarity = "Common"
 459	}
 460	return t
 461}
 462
 463// TraitsWith decodes a seed under params; invalid params panic.
 464func TraitsWith(seed, ps string) TraitSet {
 465	p, err := parseParams(ps)
 466	if err != nil {
 467		panic(err)
 468	}
 469	return derive(seed, p)
 470}
 471
 472// ---------------------------------------------------------------------------
 473// Small helpers
 474// ---------------------------------------------------------------------------
 475
 476func itoa(n int) string { return strconv.Itoa(n) }
 477
 478func hexv(c byte) int {
 479	if c >= 'a' {
 480		return int(c-'a') + 10
 481	}
 482	return int(c - '0')
 483}
 484
 485const hexDigits = "0123456789abcdef"
 486
 487func hex2(v int) string { return string([]byte{hexDigits[v>>4], hexDigits[v&15]}) }
 488
 489// mix blends a towards b by t percent (truncating), both "#rrggbb".
 490func mix(a, b string, t int) string {
 491	out := "#"
 492	for i := 1; i < 7; i += 2 {
 493		x := hexv(a[i])*16 + hexv(a[i+1])
 494		y := hexv(b[i])*16 + hexv(b[i+1])
 495		out += hex2(x + (y-x)*t/100)
 496	}
 497	return out
 498}
 499
 500// shade scales a colour by f percent (f <= 100).
 501func shade(a string, f int) string {
 502	out := "#"
 503	for i := 1; i < 7; i += 2 {
 504		out += hex2((hexv(a[i])*16 + hexv(a[i+1])) * f / 100)
 505	}
 506	return out
 507}
 508
 509type pt struct{ x, y int }
 510
 511// relPath: "M x y l dx dy dx dy …z" (zero moves skipped).
 512func relPath(p []pt) string {
 513	var b strings.Builder
 514	px, py := p[0].x, p[0].y
 515	b.WriteString("M" + itoa(px) + " " + itoa(py))
 516	first := true
 517	for i := 1; i < len(p); i++ {
 518		dx, dy := p[i].x-px, p[i].y-py
 519		if dx == 0 && dy == 0 {
 520			continue
 521		}
 522		if first {
 523			b.WriteString("l")
 524			first = false
 525		} else {
 526			b.WriteString(" ")
 527		}
 528		b.WriteString(itoa(dx) + " " + itoa(dy))
 529		px, py = p[i].x, p[i].y
 530	}
 531	b.WriteString("z")
 532	return b.String()
 533}
 534
 535// ---------------------------------------------------------------------------
 536// Day-patches: convex polygons cut by lines (v1's subdivision on 600x800).
 537// ---------------------------------------------------------------------------
 538
 539const (
 540	cW = 600
 541	cH = 800
 542)
 543
 544func area2(p []pt) int {
 545	s := 0
 546	n := len(p)
 547	for i := 0; i < n; i++ {
 548		a, b := p[i], p[(i+1)%n]
 549		s += a.x*b.y - b.x*a.y
 550	}
 551	if s < 0 {
 552		return -s
 553	}
 554	return s
 555}
 556
 557// cut splits poly by the line through (px,py) with direction (dx,dy).
 558func cut(poly []pt, px, py, dx, dy int) ([]pt, []pt) {
 559	var a, b []pt
 560	n := len(poly)
 561	for i := 0; i < n; i++ {
 562		p, q := poly[i], poly[(i+1)%n]
 563		sa := dx*(p.y-py) - dy*(p.x-px)
 564		sb := dx*(q.y-py) - dy*(q.x-px)
 565		if sa >= 0 {
 566			a = append(a, p)
 567		}
 568		if sa <= 0 {
 569			b = append(b, p)
 570		}
 571		if (sa > 0 && sb < 0) || (sa < 0 && sb > 0) {
 572			c := pt{p.x + (q.x-p.x)*sa/(sa-sb), p.y + (q.y-p.y)*sa/(sa-sb)}
 573			a = append(a, c)
 574			b = append(b, c)
 575		}
 576	}
 577	return a, b
 578}
 579
 580// subdivide cuts the wall into target patches, always cutting the largest.
 581func subdivide(r *rng, target int) [][]pt {
 582	polys := [][]pt{{{0, 0}, {cW, 0}, {cW, cH}, {0, cH}}}
 583	areas := []int{2 * cW * cH}
 584	mn := 2 * cW * cH / (target * 4)
 585	for tries := 0; len(polys) < target && tries < 400; tries++ {
 586		bi := 0
 587		for i := 1; i < len(areas); i++ {
 588			if areas[i] > areas[bi] {
 589				bi = i
 590			}
 591		}
 592		p := polys[bi]
 593		minx, maxx, miny, maxy, sx, sy := p[0].x, p[0].x, p[0].y, p[0].y, 0, 0
 594		for _, q := range p {
 595			sx += q.x
 596			sy += q.y
 597			if q.x < minx {
 598				minx = q.x
 599			}
 600			if q.x > maxx {
 601				maxx = q.x
 602			}
 603			if q.y < miny {
 604				miny = q.y
 605			}
 606			if q.y > maxy {
 607				maxy = q.y
 608			}
 609		}
 610		bw, bh := maxx-minx, maxy-miny
 611		cx := sx/len(p) + r.rr(-bw/5, bw/5)
 612		cy := sy/len(p) + r.rr(-bh/5, bh/5)
 613		ang := r.rr(-12, 12)
 614		if bw > bh {
 615			ang += 64
 616		}
 617		a, b := cut(p, cx, cy, icos(ang), isin(ang))
 618		if len(a) < 3 || len(b) < 3 {
 619			continue
 620		}
 621		aa, ab := area2(a), area2(b)
 622		if aa < mn || ab < mn {
 623			continue
 624		}
 625		polys[bi], areas[bi] = a, aa
 626		polys = append(polys, b)
 627		areas = append(areas, ab)
 628	}
 629	return polys
 630}
 631
 632// ---------------------------------------------------------------------------
 633// The scene: every element is a part, defined once in <defs> and drawn as a
 634// filled <use> in the painted layer and an outlined <use> in the sinopia.
 635// ---------------------------------------------------------------------------
 636
 637type part struct {
 638	ref   int    // id of the <defs> element (q<ref>)
 639	fill  string // painted fill; "" for a line part
 640	line  string // line colour (line parts)
 641	sw    string // line width (line parts)
 642	dash  bool   // dotted line in the painted layer (halo punchwork)
 643	hatch bool   // hatched in the sinopia (draperies)
 644	ghost bool   // painted only: no sinopia outline, no painted contour
 645	over  bool   // painted overlay of an earlier element (sky pattern)
 646	sketch bool  // sinopia only (a ridge line)
 647}
 648
 649type scene struct {
 650	defs  strings.Builder
 651	parts []part
 652	n     int
 653	hatch  bool   // a hatch pattern is needed
 654	gold   bool   // the gold gradient is needed
 655	shadow string // cast-shadow colour on the ground
 656}
 657
 658func (s *scene) def(tag, attrs string) int {
 659	id := s.n
 660	s.n++
 661	s.defs.WriteString("<" + tag + ` id="q` + itoa(id) + `" ` + attrs + "/>")
 662	return id
 663}
 664
 665func (s *scene) fill(tag, attrs, fill string) int {
 666	id := s.def(tag, attrs)
 667	s.parts = append(s.parts, part{ref: id, fill: fill})
 668	return id
 669}
 670
 671func (s *scene) ghost(tag, attrs, fill string) int {
 672	id := s.def(tag, attrs)
 673	s.parts = append(s.parts, part{ref: id, fill: fill, ghost: true})
 674	return id
 675}
 676
 677func (s *scene) drape(d, fill string) int {
 678	id := s.def("path", `d="`+d+`"`)
 679	s.parts = append(s.parts, part{ref: id, fill: fill, hatch: true})
 680	s.hatch = true
 681	return id
 682}
 683
 684func (s *scene) line(d, colour, width string) int {
 685	id := s.def("path", `d="`+d+`"`)
 686	s.parts = append(s.parts, part{ref: id, line: colour, sw: width})
 687	return id
 688}
 689
 690func path(d string) string { return `d="` + d + `"` }
 691
 692func circleA(cx, cy, r int) string {
 693	return `cx="` + itoa(cx) + `" cy="` + itoa(cy) + `" r="` + itoa(r) + `"`
 694}
 695
 696func ellipseA(cx, cy, rx, ry int) string {
 697	return `cx="` + itoa(cx) + `" cy="` + itoa(cy) + `" rx="` + itoa(rx) + `" ry="` + itoa(ry) + `"`
 698}
 699
 700// hill: a rolling ridge across the wall (two sine harmonics), painted as a
 701// ghost fill down to bottom; the sinopia draws only its ridge line.
 702func (s *scene) hill(yb, amp, ph, bottom int, fill string) {
 703	var b strings.Builder
 704	for x := 40; x <= 560; x += 20 {
 705		t := (x - 40) * 256 / 520
 706		y := yb - amp*(1536+isin(ph+t)+isin(3*ph+2*t)/2)/3072
 707		if x == 40 {
 708			b.WriteString("M40 " + itoa(y) + "L")
 709		} else {
 710			b.WriteString(" " + itoa(x) + " " + itoa(y))
 711		}
 712	}
 713	ridge := b.String()
 714	s.ghost("path", path(ridge+"V"+itoa(bottom)+"H40z"), fill)
 715	id := s.def("path", path(ridge))
 716	s.parts = append(s.parts, part{ref: id, sketch: true})
 717}
 718
 719// robe: the bell-shaped gown of a standing figure.
 720func robe(x, y, ht, sy, sw, hw int) string {
 721	return "M" + itoa(x-sw) + " " + itoa(sy) +
 722		"C" + itoa(x-sw-6) + " " + itoa(sy+ht*3/10) + " " + itoa(x-hw) + " " + itoa(y-ht/5) + " " + itoa(x-hw) + " " + itoa(y) +
 723		"H" + itoa(x+hw) +
 724		"C" + itoa(x+hw) + " " + itoa(y-ht/5) + " " + itoa(x+sw+6) + " " + itoa(sy+ht*3/10) + " " + itoa(x+sw) + " " + itoa(sy) +
 725		"Q" + itoa(x) + " " + itoa(sy-10) + " " + itoa(x-sw) + " " + itoa(sy) + "z"
 726}
 727
 728var hairs = []string{"#4a3222", "#8a5a2a", "#2a2020", "#c9a060", "#6a6a6a"}
 729
 730const (
 731	atNone = iota
 732	atBook
 733	atStaff
 734	atFlower
 735	atScroll
 736)
 737
 738var attrW = []int{30, 25, 20, 15, 10}
 739
 740type figure struct{ x, y, ht int }
 741
 742// person draws one standing figure; it returns the ids of its robe and head
 743// (the pentimento redraws them). attr < 0 draws the attribute from r.
 744func (s *scene) person(r *rng, pg pigment, f figure, halo, wings bool, attr int) (int, int) {
 745	pal := pg.cols
 746	x, y, ht := f.x, f.y, f.ht
 747	hr := ht * 3 / 40
 748	hy := y - ht + hr
 749	sy := hy + hr + hr*6/10
 750	sw := ht * 12 / 100
 751	hw := ht*17/100 + r.rr(-4, 6)
 752	c1 := pal[r.intn(4)]
 753	c2 := pal[r.intn(5)]
 754	if c2 == c1 {
 755		c2 = pal[4]
 756	}
 757	s.ghost("ellipse", ellipseA(x, y, hw+12, 7), s.shadow)
 758	if wings {
 759		wy := sy + 6
 760		wing := "#ece2cc"
 761		s.fill("path", path(
 762			"M"+itoa(x-8)+" "+itoa(wy)+"C"+itoa(x-60)+" "+itoa(wy-80)+" "+itoa(x-128)+" "+itoa(wy-30)+" "+itoa(x-112)+" "+itoa(wy+120)+
 763				"C"+itoa(x-86)+" "+itoa(wy+66)+" "+itoa(x-46)+" "+itoa(wy+52)+" "+itoa(x-8)+" "+itoa(wy+40)+"z"+
 764				"M"+itoa(x+8)+" "+itoa(wy)+"C"+itoa(x+60)+" "+itoa(wy-80)+" "+itoa(x+128)+" "+itoa(wy-30)+" "+itoa(x+112)+" "+itoa(wy+120)+
 765				"C"+itoa(x+86)+" "+itoa(wy+66)+" "+itoa(x+46)+" "+itoa(wy+52)+" "+itoa(x+8)+" "+itoa(wy+40)+"z"), wing)
 766		fd := ""
 767		for k := 0; k < 3; k++ {
 768			o := 30 + k*26
 769			fd += "M" + itoa(x-o) + " " + itoa(wy-14+k*8) + "l" + itoa(-24+k*6) + " " + itoa(70-k*14) +
 770				"M" + itoa(x+o) + " " + itoa(wy-14+k*8) + "l" + itoa(24-k*6) + " " + itoa(70-k*14)
 771		}
 772		s.line(fd, mix(pal[2], "#a89070", 50), "1.4")
 773	}
 774	if halo {
 775		s.gold = true
 776		s.fill("circle", circleA(x, hy, hr*17/10), "url(#au)")
 777		dot := s.def("circle", circleA(x, hy, hr*145/100))
 778		s.parts = append(s.parts, part{ref: dot, line: "#8a6420", sw: "1.4", dash: true})
 779	}
 780	nw := hr * 4 / 10
 781	s.ghost("path", path("M"+itoa(x-nw)+" "+itoa(hy+hr/2)+"V"+itoa(sy+4)+"H"+itoa(x+nw)+"V"+itoa(hy+hr/2)+"z"), shade(pg.flesh, 88))
 782	rb := s.drape(robe(x, y, ht, sy, sw, hw), c1)
 783	ms := 1
 784	if r.intn(2) == 0 {
 785		ms = -1
 786	}
 787	s.drape("M"+itoa(x-ms*sw)+" "+itoa(sy)+
 788		"Q"+itoa(x+ms*sw*2)+" "+itoa(sy+ht/4)+" "+itoa(x+ms*hw)+" "+itoa(y-ht/4)+
 789		"L"+itoa(x+ms*hw)+" "+itoa(y-ht/20)+
 790		"Q"+itoa(x-ms*(hw*4/10))+" "+itoa(y-ht*3/10)+" "+itoa(x-ms*sw)+" "+itoa(sy)+"z", c2)
 791	fd := ""
 792	for k := 0; k < 4; k++ {
 793		fx := x - hw*6/10 + k*(hw*4/10)
 794		fd += "M" + itoa(x-sw/2+k*(sw/3)) + " " + itoa(sy+ht*35/100) +
 795			"Q" + itoa(fx+r.rr(-8, 8)) + " " + itoa(y-ht/5) + " " + itoa(fx) + " " + itoa(y-4)
 796	}
 797	s.line(fd, shade(c1, 62), "1.6")
 798	hd := s.fill("ellipse", ellipseA(x, hy, hr*82/100, hr), pg.flesh)
 799	hc := hairs[r.intn(len(hairs))]
 800	s.fill("path", path("M"+itoa(x-hr)+" "+itoa(hy+4)+
 801		"Q"+itoa(x-hr)+" "+itoa(hy-hr*125/100)+" "+itoa(x)+" "+itoa(hy-hr*105/100)+
 802		"Q"+itoa(x+hr)+" "+itoa(hy-hr*125/100)+" "+itoa(x+hr)+" "+itoa(hy+4)+
 803		"Q"+itoa(x+hr*6/10)+" "+itoa(hy-hr/2)+" "+itoa(x)+" "+itoa(hy-hr*55/100)+
 804		"Q"+itoa(x-hr*6/10)+" "+itoa(hy-hr/2)+" "+itoa(x-hr)+" "+itoa(hy+4)+"z"), hc)
 805	s.line("M"+itoa(x-hr*35/100)+" "+itoa(hy-1)+"h4M"+itoa(x+hr*2/10)+" "+itoa(hy-1)+"h4M"+itoa(x)+" "+itoa(hy+3)+"v"+itoa(hr/5)+"M"+itoa(x-2)+" "+itoa(hy+hr*45/100)+"h5",
 806		"#5a3a2a", "1.4")
 807	if attr < 0 {
 808		attr = r.pick(attrW)
 809	}
 810	hx := x + r.rr(-6, 6)
 811	hyy := sy + ht/4
 812	switch attr {
 813	case atBook:
 814		s.fill("path", path("M"+itoa(hx-12)+" "+itoa(hyy-14)+"h24v28h-24z"), pal[2])
 815	case atStaff:
 816		s.line("M"+itoa(x+sw+4)+" "+itoa(sy-hr*2)+"V"+itoa(y), "#6a4a2a", "3.5")
 817	case atFlower:
 818		s.line("M"+itoa(hx)+" "+itoa(hyy)+"v-34", "#4f6a3a", "2")
 819		s.fill("circle", circleA(hx, hyy-38, 6), "#f2ece0")
 820	case atScroll:
 821		s.fill("path", path("M"+itoa(hx-14)+" "+itoa(hyy-6)+"h28v14h-28z"), "#efe4c8")
 822	}
 823	s.fill("ellipse", ellipseA(hx, hyy+2, 6, 5), pg.flesh)
 824	return rb, hd
 825}
 826
 827// ---------------------------------------------------------------------------
 828// SVG
 829// ---------------------------------------------------------------------------
 830
 831const (
 832	sinRed   = "#a8432c"
 833	intonaco = "#efe6d4"
 834	arriccio = "#cdb497"
 835)
 836
 837// SVGWith renders a seed under params as a standalone SVG document.
 838func SVGWith(seed, ps string) string {
 839	t := TraitsWith(seed, ps)
 840	pg := pigments[t.pig]
 841	pal := pg.cols
 842	r := newRNG(seed + "|art")
 843	s := &scene{}
 844
 845	// 1. sky, hills, city, road, trees
 846	yh := r.rr(440, 500)
 847	if t.scene == scLandscape {
 848		yh = r.rr(420, 480)
 849	}
 850	skyFill := "url(#sk)"
 851	if t.sky == skyStarry {
 852		skyFill = "#23386b"
 853	} else if t.sky == skyGold {
 854		skyFill = "url(#au)"
 855		s.gold = true
 856	}
 857	sky := s.ghost("rect", `x="40" y="40" width="520" height="`+itoa(yh-40)+`"`, skyFill)
 858	if t.sky == skyClear {
 859		for c := 0; c < 3; c++ {
 860			cx := r.rr(90, 510)
 861			cy := r.rr(80, 220)
 862			s.fill("path", path("M"+itoa(cx-40)+" "+itoa(cy)+"q10-22 30-12q14-20 34-2q22-4 20 14z"), "#f1f3ee")
 863		}
 864	} else {
 865		s.parts = append(s.parts, part{ref: sky, fill: "url(#st)", ghost: true, over: true})
 866	}
 867	s.hill(yh-10, r.rr(40, 110), r.intn(256), yh+40, mix(pal[4], "#c8c0a0", 40))
 868	if t.scene != scProcession || r.intn(2) == 0 {
 869		cx := r.rr(140, 460)
 870		if t.scene == scLone { // the town stands beside the saint, not behind
 871			cx = 150 + (cx%2)*300
 872		}
 873		cy := yh - r.rr(30, 70)
 874		camp := r.intn(6)
 875		d, rf := "", ""
 876		for k := 0; k < 6; k++ {
 877			x := cx - 70 + k*24 + r.rr(-4, 4)
 878			hgt := r.rr(26, 70)
 879			if k == camp {
 880				hgt += 40
 881			}
 882			d += "M" + itoa(x) + " " + itoa(cy) + "v-" + itoa(hgt) + "h20v" + itoa(hgt) + "z"
 883			rf += "M" + itoa(x-3) + " " + itoa(cy-hgt) + "l13-14 13 14z"
 884		}
 885		s.fill("path", path("M"+itoa(cx-80)+" "+itoa(yh+30)+"V"+itoa(cy)+"h160V"+itoa(yh+30)+"z"+d), pal[3])
 886		s.fill("path", path(rf), pal[2])
 887	}
 888	s.hill(yh+20, r.rr(20, 60), r.intn(256), yh+60, mix(pal[4], "#8a9a60", 30))
 889	ground := mix(pal[4], "#9a8a5a", 50)
 890	s.shadow = shade(ground, 80)
 891	s.hill(yh+40, r.rr(4, 14), r.intn(256), 760, ground)
 892	if t.scene == scLandscape {
 893		bx := r.rr(200, 400)
 894		tx := r.rr(220, 380)
 895		mx := (bx+tx)/2 + r.rr(-60, 60)
 896		my := (760 + yh) / 2
 897		s.fill("path", path("M"+itoa(bx-44)+" 760Q"+itoa(mx-18)+" "+itoa(my)+" "+itoa(tx-3)+" "+itoa(yh+42)+
 898			"h6Q"+itoa(mx+18)+" "+itoa(my)+" "+itoa(bx+44)+" 760z"), mix(pal[3], "#c9b48a", 40))
 899		x := r.rr(90, 470)
 900		s.fill("path", path("M"+itoa(x)+" "+itoa(yh+30)+"v-34h40v34zM"+itoa(x+30)+" "+itoa(yh-4)+"v-30h12v30z"), pal[3])
 901		s.fill("path", path("M"+itoa(x-4)+" "+itoa(yh-4)+"l24-18 24 18zM"+itoa(x+28)+" "+itoa(yh-34)+"l8-12 8 12z"), pal[2])
 902	}
 903	ntree := r.rr(1, 3)
 904	if t.scene == scLandscape {
 905		ntree = r.rr(4, 7)
 906	}
 907	depth := 60
 908	if t.scene == scLandscape {
 909		depth = 230
 910	}
 911	for k := 0; k < ntree; k++ {
 912		x := r.rr(70, 530)
 913		y := yh + r.rr(10, depth)
 914		g := 100 + (y-yh-10)*80/230 // nearer trees are larger
 915		if r.intn(2) == 0 {
 916			s.fill("ellipse", ellipseA(x, y-40*g/100, 11*g/100, 42*g/100), mix("#3f5a3a", pal[4], 25))
 917		} else {
 918			s.line("M"+itoa(x)+" "+itoa(y)+"v-"+itoa(30*g/100), "#5a3e28", "4")
 919			s.fill("circle", circleA(x, y-44*g/100, 22*g/100), mix("#5d7a3c", pal[4], 25))
 920		}
 921	}
 922	if t.scene == scLandscape { // vineyard rows and a flight of birds
 923		vx := r.rr(60, 330)
 924		vy := yh + r.rr(90, 190)
 925		d := ""
 926		for k := 0; k < 6; k++ {
 927			d += "M" + itoa(vx+k*8) + " " + itoa(vy+k*14) + "h" + itoa(150+k*10)
 928		}
 929		s.line(d, shade(ground, 70), "3")
 930		d = ""
 931		for k := 0; k < 7; k++ {
 932			bx := r.rr(120, 480)
 933			by := r.rr(70, yh-120)
 934			w := r.rr(5, 9)
 935			d += "M" + itoa(bx-w) + " " + itoa(by-w/2) + "q" + itoa(w/2) + " 0 " + itoa(w) + " " + itoa(w/2) + "q" + itoa(w/2) + "-" + itoa(w/2) + " " + itoa(w) + "-" + itoa(w/2)
 936		}
 937		bird := "#3a332c"
 938		if t.sky == skyStarry {
 939			bird = "#d8dcea"
 940		}
 941		s.line(d, bird, "1.4")
 942	}
 943
 944	// 2. the figures
 945	gY := 760 - r.rr(50, 80)
 946	var figs []figure
 947	switch t.scene {
 948	case scProcession:
 949		n := r.rr(4, 6)
 950		for k := 0; k < n; k++ {
 951			x := 100 + k*420/(n-1) + r.rr(-8, 8)
 952			y := gY - r.rr(0, 10)
 953			figs = append(figs, figure{x, y, r.rr(340, 400)})
 954		}
 955	case scGathering:
 956		n := r.rr(5, 7)
 957		b := n / 2
 958		for j := 0; j < b; j++ {
 959			x := 300 - (b-1)*55 + j*110 + r.rr(-10, 10)
 960			figs = append(figs, figure{x, gY - 46, r.rr(310, 350)})
 961		}
 962		f := n - b
 963		for j := 0; j < f; j++ {
 964			figs = append(figs, figure{300 - (f-1)*60 + j*120, gY, r.rr(350, 400)})
 965		}
 966	case scEncounter:
 967		l := r.rr(2, 3)
 968		rt := r.rr(2, 3)
 969		for k := l - 1; k >= 0; k-- {
 970			figs = append(figs, figure{95 + k*70, gY - k*4, r.rr(350, 400)})
 971		}
 972		for k := rt - 1; k >= 0; k-- {
 973			figs = append(figs, figure{505 - k*70, gY - k*4, r.rr(350, 400)})
 974		}
 975	case scAnnunciation:
 976		figs = append(figs, figure{r.rr(150, 180), gY, r.rr(360, 395)})
 977		figs = append(figs, figure{r.rr(430, 450), gY - 6, r.rr(330, 355)})
 978	case scLone:
 979		figs = append(figs, figure{300, gY + 10, r.rr(540, 600)})
 980	}
 981	hm := r.intn(3) // haloes: none, some, all
 982	if t.scene == scAnnunciation || t.scene == scLone {
 983		hm = 2
 984	}
 985	if t.scene == scEncounter {
 986		s.fill("path", path("M250 "+itoa(gY)+"v-150a50 50 0 0 1 100 0v150z"), pal[3])
 987		s.fill("path", path("M274 "+itoa(gY)+"v-110a26 26 0 0 1 52 0v110z"), "#2c241e")
 988	}
 989	if t.scene == scAnnunciation {
 990		top := gY - 328
 991		s.ghost("path", path("M368 "+itoa(gY)+"V"+itoa(top)+"H522V"+itoa(gY)+"z"), mix(pal[1], "#2c241e", 55))
 992		s.fill("path", path("M354 "+itoa(gY)+"V"+itoa(top)+"h14V"+itoa(gY)+"zM522 "+itoa(gY)+"V"+itoa(top)+"h14V"+itoa(gY)+
 993			"zM368 "+itoa(top)+"H522V"+itoa(top+78)+"A77 60 0 0 0 368 "+itoa(top+78)+"z"), pal[3])
 994		s.fill("path", path("M344 "+itoa(top-22)+"h202v22h-202z"), pal[2])
 995	}
 996	var robes, heads []int
 997	for i, f := range figs {
 998		halo := hm == 2 || (hm == 1 && r.intn(2) == 0)
 999		attr := -1
1000		wings := false
1001		if t.scene == scAnnunciation {
1002			if i == 0 {
1003				attr, wings = atFlower, true
1004			} else {
1005				attr = atBook
1006			}
1007		}
1008		rb, hd := s.person(r, pg, f, halo, wings, attr)
1009		robes = append(robes, rb)
1010		heads = append(heads, hd)
1011	}
1012	if t.scene == scAnnunciation {
1013		v := figs[1]
1014		vhy := v.y - v.ht + v.ht*3/40
1015		s.line("M60 60L"+itoa(v.x-8)+" "+itoa(vhy)+"M60 60L"+itoa(v.x)+" "+itoa(vhy-10)+"M60 60L"+itoa(v.x-14)+" "+itoa(vhy+10), "#d9b54a", "1.5")
1016		dx := 60 + (v.x-60)*45/100
1017		dy := 60 + (vhy-60)*45/100
1018		s.fill("path", path("M"+itoa(dx-9)+" "+itoa(dy)+"q9-9 18 0q-9 5-18 0zM"+itoa(dx-2)+" "+itoa(dy-2)+"l-6-9 10 5z"), "#f6f1e6")
1019	}
1020
1021	// 3. pentimento: a figure the painter moved, still showing through
1022	pent := ""
1023	if t.draw == drPentimento {
1024		if len(robes) > 0 {
1025			gi := r.intn(len(robes))
1026			dx := r.rr(20, 44)
1027			if r.intn(2) == 0 {
1028				dx = -dx
1029			}
1030			dy := r.rr(-20, 6)
1031			pent = `<g transform="translate(` + itoa(dx) + " " + itoa(dy) + `)" fill="none" stroke="` + sinRed +
1032				`" stroke-opacity=".55" stroke-width="2.4"><use href="#q` + itoa(robes[gi]) + `"/><use href="#q` + itoa(heads[gi]) + `"/></g>`
1033		} else {
1034			x := r.rr(220, 380)
1035			ht := r.rr(320, 370)
1036			hr := ht * 3 / 40
1037			hy := gY - ht + hr
1038			sy := hy + hr + hr*6/10
1039			pent = `<g fill="none" stroke="` + sinRed + `" stroke-opacity=".55" stroke-width="2.4"><path d="` +
1040				robe(x, gY, ht, sy, ht*12/100, ht*17/100) + `"/><ellipse ` + ellipseA(x, hy, hr*82/100, hr) + `/></g>`
1041		}
1042	}
1043
1044	// 4. the wall, cut into day-patches, painted top-down
1045	gb := buckets[t.gio]
1046	polys := subdivide(r, r.rr(gb.lo, gb.hi))
1047	n := len(polys)
1048	key := make([]int, n)
1049	order := make([]int, n)
1050	for i, p := range polys {
1051		sy := 0
1052		for _, q := range p {
1053			sy += q.y
1054		}
1055		key[i] = sy/len(p) + r.rr(0, 170)
1056		order[i] = i
1057	}
1058	for i := 1; i < n; i++ { // stable insertion sort
1059		for j := i; j > 0 && key[order[j-1]] > key[order[j]]; j-- {
1060			order[j-1], order[j] = order[j], order[j-1]
1061		}
1062	}
1063	pct := 0
1064	switch t.stage {
1065	case stFresh:
1066		pct = r.rr(12, 28)
1067	case stHalf:
1068		pct = r.rr(40, 60)
1069	case stAdvanced:
1070		pct = r.rr(65, 82)
1071	case stNearly:
1072		pct = r.rr(86, 96)
1073	case stFinished:
1074		pct = 100
1075	}
1076	k := (n*pct + 50) / 100
1077	if pct > 0 && pct < 100 {
1078		if k < 1 {
1079			k = 1
1080		}
1081		if k > n-1 {
1082			k = n - 1
1083		}
1084	}
1085	arSeed := r.rr(1, 900)
1086	cracks := t.cond == cdCraquelure || t.cond == cdRuined
1087	ckSeed := 0
1088	if cracks {
1089		ckSeed = r.rr(1, 900)
1090	}
1091	lac, core := "", ""
1092	if t.cond == cdLacunae || t.cond == cdRuined {
1093		nl := r.rr(1, 3)
1094		if t.cond == cdRuined {
1095			nl = r.rr(3, 5)
1096		}
1097		for l := 0; l < nl; l++ {
1098			cx := r.rr(70, 530)
1099			cy := r.rr(90, 730)
1100			r0 := r.rr(18, 56)
1101			var outer, inner []pt
1102			for a := 0; a < 256; a += 21 {
1103				rad := r0 * r.rr(70, 120) / 100
1104				outer = append(outer, pt{cx + rad*icos(a)/1024, cy + rad*isin(a)/1024})
1105				ri := rad * 55 / 100
1106				inner = append(inner, pt{cx + ri*icos(a)/1024, cy + ri*isin(a)/1024})
1107			}
1108			lac += relPath(outer)
1109			core += relPath(inner)
1110		}
1111	}
1112
1113	// 5. write the document
1114	fresco := k > 0
1115	sinopia := k < n || lac != ""
1116	clip := fresco && k < n
1117	var b strings.Builder
1118	b.WriteString(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 800" width="600" height="800"><defs>`)
1119	if s.gold && fresco {
1120		b.WriteString(`<linearGradient id="au" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#e9c873"/><stop offset=".5" stop-color="#c49a3e"/><stop offset="1" stop-color="#ead18a"/></linearGradient>`)
1121	}
1122	switch {
1123	case !fresco && t.sky != skyStarry:
1124	case t.sky == skyClear:
1125		b.WriteString(`<linearGradient id="sk" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#8fb3c8"/><stop offset="1" stop-color="#dfe6dc"/></linearGradient>`)
1126	case t.sky == skyStarry:
1127		if fresco {
1128			b.WriteString(`<pattern id="st" width="46" height="40" patternUnits="userSpaceOnUse"><path d="M10 6l1.6 3.4 3.4 1.6-3.4 1.6-1.6 3.4-1.6-3.4-3.4-1.6 3.4-1.6zM33 26l1.4 3 3 1.4-3 1.4-1.4 3-1.4-3-3-1.4 3-1.4z" fill="#e3c26a"/></pattern>`)
1129		}
1130		if sinopia {
1131			b.WriteString(`<pattern id="sm" width="46" height="40" patternUnits="userSpaceOnUse"><path d="M10 6v8M6 10h8M33 26v8M29 30h8" stroke="` + sinRed + `" stroke-opacity=".6"/></pattern>`)
1132		}
1133	case t.sky == skyGold:
1134		b.WriteString(`<pattern id="st" width="14" height="14" patternUnits="userSpaceOnUse"><circle cx="7" cy="7" r="1.1" fill="#8a6420" fill-opacity=".5"/></pattern>`)
1135	}
1136	if sinopia && s.hatch {
1137		b.WriteString(`<pattern id="ht" width="7" height="7" patternUnits="userSpaceOnUse" patternTransform="rotate(35)"><path d="M0 3.5h7" stroke="` +
1138			sinRed + `" stroke-opacity=".55" stroke-width=".9"/></pattern>`)
1139	}
1140	if fresco {
1141		b.WriteString(`<pattern id="fr" width="24" height="24" patternUnits="userSpaceOnUse"><rect width="24" height="24" fill="` + pal[3] +
1142			`"/><path d="M0 0l12 12L0 24zM24 0L12 12l12 12z" fill="` + pal[2] + `"/><path d="M12 6l6 6-6 6-6-6z" fill="` + pal[0] + `"/></pattern>`)
1143	}
1144	b.WriteString(`<filter id="ar" x="0" y="0" width="1" height="1"><feTurbulence type="fractalNoise" baseFrequency=".05" numOctaves="3" seed="` +
1145		itoa(arSeed) + `"/><feColorMatrix values="0 0 0 0 .45 0 0 0 0 .32 0 0 0 0 .22 0 0 0 -1.3 .62"/></filter>`)
1146	if cracks {
1147		b.WriteString(`<filter id="ck" x="0" y="0" width="1" height="1"><feTurbulence type="fractalNoise" baseFrequency=".03" numOctaves="2" seed="` +
1148			itoa(ckSeed) + `" result="t"/><feColorMatrix in="t" values="0 0 0 0 .2 0 0 0 0 .14 0 0 0 0 .1 1 0 0 0 0" result="a"/>` +
1149			`<feComponentTransfer in="a" result="c"><feFuncA type="discrete" tableValues="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"/></feComponentTransfer>` +
1150			`<feComposite in="c" in2="SourceAlpha" operator="in" result="d"/><feMerge><feMergeNode in="SourceGraphic"/><feMergeNode in="d"/></feMerge></filter>`)
1151	}
1152	b.WriteString(s.defs.String())
1153	if fresco {
1154		var dn strings.Builder
1155		for i := 0; i < k; i++ {
1156			dn.WriteString(relPath(polys[order[i]]))
1157		}
1158		b.WriteString(`<path id="dn" d="` + dn.String() + `"/>`)
1159		if clip {
1160			b.WriteString(`<clipPath id="cp"><use href="#dn"/></clipPath>`)
1161		}
1162	}
1163	if lac != "" {
1164		b.WriteString(`<path id="lc" d="` + lac + `"/>`)
1165		if fresco {
1166			b.WriteString(`<mask id="lm"><rect width="600" height="800" fill="#fff"/><use href="#lc" fill="#000"/></mask>`)
1167		}
1168	}
1169	if sinopia {
1170		// the sinopia strokes, once, for the drawing and its searching double
1171		b.WriteString(`<g id="sn">`)
1172		for _, p := range s.parts {
1173			if !p.over && !p.ghost {
1174				b.WriteString(`<use href="#q` + itoa(p.ref) + `"/>`)
1175			}
1176		}
1177		b.WriteString(`</g>`)
1178	}
1179	b.WriteString(`</defs>`)
1180	if cracks {
1181		b.WriteString(`<g filter="url(#ck)">`)
1182	}
1183
1184	// sinopia layer: arriccio, squaring grid, the drawing
1185	if sinopia {
1186		b.WriteString(`<rect width="600" height="800" fill="` + arriccio + `"/><rect width="600" height="800" filter="url(#ar)"/><path d="`)
1187		for x := 40; x <= 560; x += 52 {
1188			b.WriteString("M" + itoa(x) + " 40V760")
1189		}
1190		for y := 40; y <= 760; y += 52 {
1191			b.WriteString("M40 " + itoa(y) + "H560")
1192		}
1193		b.WriteString(`M300 40V760M40 ` + itoa(yh) + `H560" stroke="` + sinRed + `" stroke-opacity=".28" stroke-width=".8"/>`)
1194		switch t.sky {
1195		case skyStarry:
1196			b.WriteString(`<use href="#q` + itoa(sky) + `" fill="url(#sm)"/>`)
1197		case skyGold: // the red bole laid under gold
1198			b.WriteString(`<use href="#q` + itoa(sky) + `" fill="#b5653f" fill-opacity=".22"/>`)
1199		}
1200		b.WriteString(`<path d="M40 40H560V760H40z" fill="none" stroke="` + sinRed + `" stroke-width="1.5"/>`)
1201		b.WriteString(`<g fill="none" stroke="` + sinRed + `" stroke-linejoin="round" stroke-linecap="round"`)
1202		if t.draw == drSpolvero {
1203			b.WriteString(` stroke-dasharray="1.2 4" stroke-width="2.4"><use href="#sn"/>`)
1204		} else {
1205			b.WriteString(` stroke-width="1.8"><use href="#sn"/><use href="#sn" transform="translate(3 -2)" stroke-opacity=".35" stroke-width="1"/>`)
1206		}
1207		for _, p := range s.parts {
1208			if p.hatch {
1209				b.WriteString(`<use href="#q` + itoa(p.ref) + `" fill="url(#ht)" stroke="none"/>`)
1210			}
1211		}
1212		b.WriteString(`</g>`)
1213	}
1214
1215	// painted layer: the finished giornate
1216	if fresco {
1217		if lac != "" {
1218			b.WriteString(`<g mask="url(#lm)">`)
1219		}
1220		if clip {
1221			b.WriteString(`<g clip-path="url(#cp)">`)
1222		} else {
1223			b.WriteString(`<g>`)
1224		}
1225		b.WriteString(`<rect width="600" height="800" fill="` + intonaco + `"/><g stroke="` + pg.dark + `" stroke-opacity=".45" stroke-width="1.1" stroke-linejoin="round">`)
1226		for _, p := range s.parts {
1227			if p.sketch {
1228				continue
1229			}
1230			b.WriteString(`<use href="#q` + itoa(p.ref) + `"`)
1231			switch {
1232			case p.fill == "":
1233				b.WriteString(` fill="none" stroke="` + p.line + `" stroke-width="` + p.sw + `" stroke-opacity="1"`)
1234				if p.dash {
1235					b.WriteString(` stroke-dasharray="2 4"`)
1236				}
1237			case p.ghost:
1238				b.WriteString(` fill="` + p.fill + `" stroke="none"`)
1239			default:
1240				b.WriteString(` fill="` + p.fill + `"`)
1241			}
1242			b.WriteString(`/>`)
1243		}
1244		b.WriteString(`</g><path d="M0 0H600V800H0zM40 40V760H560V40z" fill="url(#fr)" fill-rule="evenodd" stroke="` + pg.dark + `" stroke-width="2"/></g>`)
1245		if lac != "" {
1246			b.WriteString(`</g>`)
1247		}
1248		// the seams between the days: a raised lip of plaster and its shadow
1249		b.WriteString(`<use href="#dn" fill="none" stroke="#fbf5ea" stroke-opacity=".5" stroke-width="2.4"/><use href="#dn" fill="none" stroke="#5a4434" stroke-opacity=".35" stroke-width=".8"/>`)
1250		if clip { // today's giornata, its intonaco still wet
1251			b.WriteString(`<path d="` + relPath(polys[order[k-1]]) + `" fill="#3a2a1a" fill-opacity=".07" stroke="#7a6050" stroke-opacity=".5" stroke-width="1.4"/>`)
1252		}
1253	}
1254	b.WriteString(pent)
1255	if cracks {
1256		b.WriteString(`</g>`)
1257	}
1258	if lac != "" {
1259		if fresco { // the broken edge of the intonaco around each loss
1260			if clip {
1261				b.WriteString(`<g clip-path="url(#cp)">`)
1262			} else {
1263				b.WriteString(`<g>`)
1264			}
1265			b.WriteString(`<use href="#lc" fill="none" stroke="#f3ead8" stroke-width="2.5"/></g>`)
1266		}
1267		b.WriteString(`<path d="` + core + `" fill="#9c8770" stroke="#e2d4be" stroke-width="1.5"/>`)
1268	}
1269	b.WriteString(`<rect width="600" height="800" filter="url(#ar)" opacity=".3"/></svg>`)
1270	return b.String()
1271}