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.

rubrica.gno

38.57 Kb · 1216 lines
   1// Package rubrica (v2, "Living Language") is a Sinopia engine: every token
   2// invents a language and writes one manuscript leaf in it.
   3//
   4// The language is an alphabet of 12-20 glyphs (strokes on a 3x4 node grid in
   5// one of five hands) and a lexicon of 22-40 words built from it. Glyph use and
   6// word use both follow a Zipf law and the most frequent words are the
   7// shortest, so the text reads like writing rather than noise. The leaf is
   8// laid out like a real codex page: justified lines, paragraphs closed by a
   9// punctus, ink that fades until the scribe dips the pen again, a great
  10// initial, lombards, rubrics and line fillers, a vine border or a full frame,
  11// a marginal drawing, a running head, a catchword and the folio number,
  12// which is the token number written in medieval numerals (f. xiiij v).
  13//
  14// A stateless p/ package implementing engine/v2. Pure integer maths (FNV-1a +
  15// splitmix64 streams, truncating and floor division), so the TypeScript twin
  16// (frontend/src/engines/rubricav2.ts) renders the same bytes. Traits come
  17// from their own cheap stream (seed+"|traits") and never render; the art uses
  18// seed+"|art", so art draws never shift traits. Words are defined once in
  19// <defs> and placed with <use>; a word budget caps every leaf.
  20//
  21// The render depends on Input.TokenID (the folio number) and on nothing else
  22// outside Seed and Params; it is not a living engine.
  23package rubrica
  24
  25import (
  26	"errors"
  27	"strconv"
  28	"strings"
  29
  30	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/engine/v2"
  31)
  32
  33// TraitTypes in the order Traits returns them.
  34var traitTypes = []string{"Hand", "Layout", "Decoration", "Vellum", "Marginalia", "Condition", "Alphabet", "Rarity"}
  35
  36// MaxSVGBytes: the measured maximum is 25,666 B over ~100,000 renders with
  37// every forced hand/layout set (docs/engines/rubrica-v2.md); WordBudget
  38// bounds the text.
  39const MaxSVGBytes = 28672
  40
  41// WordBudget caps the words placed on one leaf (text, gloss, palimpsest): the
  42// size and gas knob. It binds only on the densest glossed leaves, whose last
  43// gloss (or palimpsest) lines then stay short.
  44const WordBudget = 500
  45
  46// ParamsSchema is the Studio form: three optional overrides and a wear
  47// switch. Studio sends JSON.stringify of the values in this order.
  48const ParamsSchema = `{"type":"object","properties":{` +
  49	`"hand":{"type":"string","title":"Hand","enum":["Any","Angular","Round","Hooked","Dotted","Slanted"],"default":"Any"},` +
  50	`"layout":{"type":"string","title":"Layout","enum":["Any","Single Column","Two Columns","Glossed"],"default":"Any"},` +
  51	`"vellum":{"type":"string","title":"Vellum","enum":["Any","Calfskin","Goatskin","Rag Paper","Purple"],"default":"Any"},` +
  52	`"damage":{"type":"boolean","title":"Wear and damage","default":true}}}`
  53
  54// Manifest describes the engine. Author and FeeBps are set by the adapter.
  55func Manifest() engine.Manifest {
  56	return engine.Manifest{
  57		Name:    "Rubrica v2 · Living Language",
  58		Version: "2.0.0",
  59		Description: "Every Rubrica invents a language, an alphabet of twelve to twenty letters and a lexicon of " +
  60			"its own words, and writes one leaf of a manuscript in it: justified lines, rubrics, lombards, " +
  61			"gilded initials, marginal drawings, and the token's number as the folio.",
  62		License:      "CC-BY-NC-4.0",
  63		ParamsSchema: ParamsSchema,
  64		TraitTypes:   append([]string{}, traitTypes...),
  65		Living:       false,
  66		MaxSVGBytes:  MaxSVGBytes,
  67		Kind:         engine.KindSVG,
  68	}
  69}
  70
  71// ---------------------------------------------------------------------------
  72// Params: "" or exactly the canonical Studio JSON
  73// {"hand":"…","layout":"…","vellum":"…","damage":true|false}.
  74// ---------------------------------------------------------------------------
  75
  76// Params are the decoded collection params. "Any" keeps the seeded draw;
  77// Damage false makes every leaf Fine.
  78type Params struct {
  79	Hand, Layout, Vellum string
  80	Damage               bool
  81}
  82
  83var (
  84	handParam   = []string{"Any", "Angular", "Round", "Hooked", "Dotted", "Slanted"}
  85	layoutParam = []string{"Any", "Single Column", "Two Columns", "Glossed"}
  86	vellumParam = []string{"Any", "Calfskin", "Goatskin", "Rag Paper", "Purple"}
  87	errParams   = errors.New("rubrica v2: params must be \"\" or the canonical JSON")
  88)
  89
  90// DefaultParams is what "" means.
  91func DefaultParams() Params { return Params{"Any", "Any", "Any", true} }
  92
  93// ParseParams decodes "" or the canonical JSON and refuses anything else
  94// (other key order, spaces, unknown keys or values, "{}").
  95func ParseParams(s string) (Params, error) {
  96	if s == "" {
  97		return DefaultParams(), nil
  98	}
  99	var p Params
 100	rest := s
 101	lit := func(l string) bool {
 102		if !strings.HasPrefix(rest, l) {
 103			return false
 104		}
 105		rest = rest[len(l):]
 106		return true
 107	}
 108	str := func(allowed []string) (string, bool) {
 109		end := strings.IndexByte(rest, '"')
 110		if end < 0 {
 111			return "", false
 112		}
 113		v := rest[:end]
 114		rest = rest[end:]
 115		for _, a := range allowed {
 116			if a == v {
 117				return v, true
 118			}
 119		}
 120		return "", false
 121	}
 122	ok := false
 123	if !lit(`{"hand":"`) {
 124		return p, errParams
 125	}
 126	if p.Hand, ok = str(handParam); !ok {
 127		return p, errors.New("rubrica v2: invalid hand")
 128	}
 129	if !lit(`","layout":"`) {
 130		return p, errParams
 131	}
 132	if p.Layout, ok = str(layoutParam); !ok {
 133		return p, errors.New("rubrica v2: invalid layout")
 134	}
 135	if !lit(`","vellum":"`) {
 136		return p, errParams
 137	}
 138	if p.Vellum, ok = str(vellumParam); !ok {
 139		return p, errors.New("rubrica v2: invalid vellum")
 140	}
 141	if !lit(`","damage":`) {
 142		return p, errParams
 143	}
 144	switch rest {
 145	case "true}":
 146		p.Damage = true
 147	case "false}":
 148		p.Damage = false
 149	default:
 150		return p, errParams
 151	}
 152	return p, nil
 153}
 154
 155// ValidateParams accepts "" and the canonical JSON only.
 156func ValidateParams(params string) error {
 157	_, err := ParseParams(params)
 158	return err
 159}
 160
 161func mustParams(s string) Params {
 162	p, err := ParseParams(s)
 163	if err != nil {
 164		panic(err)
 165	}
 166	return p
 167}
 168
 169// ---------------------------------------------------------------------------
 170// Deterministic randomness: FNV-1a over the seed, then splitmix64 (as v1).
 171// ---------------------------------------------------------------------------
 172
 173const (
 174	fnvOffset uint64 = 14695981039346656037
 175	fnvPrime  uint64 = 1099511628211
 176)
 177
 178type rng struct{ s uint64 }
 179
 180func newRNG(seed string) *rng {
 181	h := fnvOffset
 182	for i := 0; i < len(seed); i++ {
 183		h ^= uint64(seed[i])
 184		h *= fnvPrime
 185	}
 186	if h == 0 {
 187		h = fnvPrime
 188	}
 189	return &rng{s: h}
 190}
 191
 192// n returns a value in [0, k). It inlines next: a GnoVM call costs more
 193// than the arithmetic, and the art draws thousands of these.
 194func (r *rng) n(k int) int {
 195	if k <= 0 {
 196		return 0
 197	}
 198	r.s += 0x9E3779B97F4A7C15
 199	z := r.s
 200	z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9
 201	z = (z ^ (z >> 27)) * 0x94D049BB133111EB
 202	return int((z ^ (z >> 31)) % uint64(k))
 203}
 204
 205// rr returns a value in [a, b].
 206func (r *rng) rr(a, b int) int { return a + r.n(b-a+1) }
 207
 208// w returns an index into a weight list.
 209func (r *rng) w(weights []int) int {
 210	total := 0
 211	for _, x := range weights {
 212		total += x
 213	}
 214	roll := r.n(total)
 215	for i, x := range weights {
 216		if roll < x {
 217			return i
 218		}
 219		roll -= x
 220	}
 221	return len(weights) - 1
 222}
 223
 224// cumulative turns positive weights into running sums for pick.
 225func cumulative(weights []int) []int {
 226	cum := make([]int, len(weights))
 227	acc := 0
 228	for i, x := range weights {
 229		acc += x
 230		cum[i] = acc
 231	}
 232	return cum
 233}
 234
 235// pick is w over running sums: the first index whose sum exceeds the roll,
 236// found by bisection (the same index w's linear scan returns).
 237func (r *rng) pick(cum []int) int {
 238	roll := r.n(cum[len(cum)-1])
 239	lo, hi := 0, len(cum)-1
 240	for lo < hi {
 241		mid := (lo + hi) / 2
 242		if roll < cum[mid] {
 243			hi = mid
 244		} else {
 245			lo = mid + 1
 246		}
 247	}
 248	return lo
 249}
 250
 251// ---------------------------------------------------------------------------
 252// Trait tables: names, weights (percent), rarity score.
 253// ---------------------------------------------------------------------------
 254
 255type table struct {
 256	names   []string
 257	weights []int
 258	scores  []int
 259}
 260
 261var (
 262	hands   = table{[]string{"Angular", "Round", "Hooked", "Dotted", "Slanted"}, []int{26, 24, 18, 16, 16}, []int{0, 0, 0, 0, 0}}
 263	layouts = table{[]string{"Single Column", "Two Columns", "Glossed"}, []int{40, 36, 24}, []int{0, 0, 2}}
 264	decos   = table{[]string{"Plain", "Rubricated", "Lombards", "Gilded", "Vine Border", "Full Illumination"},
 265		[]int{20, 28, 22, 16, 9, 5}, []int{0, 0, 0, 1, 2, 4}}
 266	vellums = table{[]string{"Calfskin", "Goatskin", "Rag Paper", "Purple"}, []int{38, 28, 26, 8}, []int{0, 0, 0, 4}}
 267	inks    = table{[]string{"Iron Gall", "Carbon", "Sepia", "Lapis"}, []int{40, 26, 24, 10}, []int{0, 0, 0, 0}}
 268	margs   = table{[]string{"None", "Pointing Hand", "Snail", "Bird", "Flower"}, []int{44, 16, 14, 14, 12}, []int{0, 1, 1, 1, 1}}
 269	conds   = table{[]string{"Fine", "Wormholes", "Water Stain", "Torn Corner", "Palimpsest", "Burnt Edge"},
 270		[]int{40, 18, 17, 12, 8, 5}, []int{0, 1, 1, 1, 3, 3}}
 271)
 272
 273// Rarity tier cut-offs on the score (10,000 SampleSeeds, default params):
 274// Common 48.3% / Uncommon 30.7% / Rare 14.4% / Legendary 5.0% / Mythic 1.5%.
 275const (
 276	scoreMythic    = 9
 277	scoreLegendary = 7
 278	scoreRare      = 5
 279	scoreUncommon  = 3
 280)
 281
 282func indexOf(t table, name string) int {
 283	for i, n := range t.names {
 284		if n == name {
 285			return i
 286		}
 287	}
 288	return 0
 289}
 290
 291// TraitSet is the decoded token: indexes into the tables above. The SVG and
 292// the trait list both read it.
 293type TraitSet struct {
 294	Hand, Layout, Decoration, Vellum, Ink, Marginalia, Condition int
 295	Alphabet, Lexicon                                            int
 296	Score                                                        int
 297	Rarity                                                       string
 298}
 299
 300func derive(seed string, p Params) TraitSet {
 301	r := newRNG(seed + "|traits")
 302	// Draw order is part of the contract: every draw happens whatever the params.
 303	var t TraitSet
 304	t.Hand = r.w(hands.weights)
 305	t.Layout = r.w(layouts.weights)
 306	t.Decoration = r.w(decos.weights)
 307	t.Vellum = r.w(vellums.weights)
 308	t.Ink = r.w(inks.weights)
 309	t.Marginalia = r.w(margs.weights)
 310	t.Condition = r.w(conds.weights)
 311	t.Alphabet = r.rr(12, 20)
 312	t.Lexicon = r.rr(22, 40)
 313	if p.Hand != "Any" {
 314		t.Hand = indexOf(hands, p.Hand)
 315	}
 316	if p.Layout != "Any" {
 317		t.Layout = indexOf(layouts, p.Layout)
 318	}
 319	if p.Vellum != "Any" {
 320		t.Vellum = indexOf(vellums, p.Vellum)
 321	}
 322	if !p.Damage {
 323		t.Condition = 0
 324	}
 325	score := hands.scores[t.Hand] + layouts.scores[t.Layout] + decos.scores[t.Decoration] +
 326		vellums.scores[t.Vellum] + margs.scores[t.Marginalia] + conds.scores[t.Condition]
 327	if t.Alphabet >= 19 {
 328		score++
 329	}
 330	t.Score = score
 331	switch {
 332	case score >= scoreMythic:
 333		t.Rarity = "Mythic"
 334	case score >= scoreLegendary:
 335		t.Rarity = "Legendary"
 336	case score >= scoreRare:
 337		t.Rarity = "Rare"
 338	case score >= scoreUncommon:
 339		t.Rarity = "Uncommon"
 340	default:
 341		t.Rarity = "Common"
 342	}
 343	return t
 344}
 345
 346// TraitsOf returns the decoded traits for a seed and params string; it
 347// panics on invalid params (core validates them at CreateCollection).
 348func TraitsOf(seed, params string) TraitSet { return derive(seed, mustParams(params)) }
 349
 350func traitList(t TraitSet) []engine.Trait {
 351	return []engine.Trait{
 352		{Type: "Hand", Value: hands.names[t.Hand]},
 353		{Type: "Layout", Value: layouts.names[t.Layout]},
 354		{Type: "Decoration", Value: decos.names[t.Decoration]},
 355		{Type: "Vellum", Value: vellums.names[t.Vellum]},
 356		{Type: "Marginalia", Value: margs.names[t.Marginalia]},
 357		{Type: "Condition", Value: conds.names[t.Condition]},
 358		{Type: "Alphabet", Value: strconv.Itoa(t.Alphabet) + " letters"},
 359		{Type: "Rarity", Value: t.Rarity},
 360	}
 361}
 362
 363// Traits returns the eight traits of in.Seed under in.Params, in TraitTypes
 364// order. It never renders.
 365func Traits(in engine.Input) []engine.Trait { return traitList(TraitsOf(in.Seed, in.Params)) }
 366
 367// Render returns the raw SVG for in.Seed under in.Params; in.TokenID is the
 368// folio number.
 369func Render(in engine.Input) string { return SVG(in.Seed, in.Params, in.TokenID) }
 370
 371// TraitString is "Type=Value;…" in TraitTypes order (golden vectors).
 372func TraitString(seed, params string) string {
 373	var b strings.Builder
 374	for i, t := range traitList(TraitsOf(seed, params)) {
 375		if i > 0 {
 376			b.WriteByte(';')
 377		}
 378		b.WriteString(t.Type)
 379		b.WriteByte('=')
 380		b.WriteString(t.Value)
 381	}
 382	return b.String()
 383}
 384
 385// ---------------------------------------------------------------------------
 386// Art
 387// ---------------------------------------------------------------------------
 388
 389const (
 390	hAngular = 0
 391	hRound   = 1
 392	hHooked  = 2
 393	hDotted  = 3
 394	hSlanted = 4
 395
 396	lSingle  = 0
 397	lTwo     = 1
 398	lGlossed = 2
 399
 400	dPlain      = 0
 401	dRubricated = 1
 402	dLombards   = 2
 403	dGilded     = 3
 404	dVine       = 4
 405	dFull       = 5
 406
 407	vGoat   = 1
 408	vRag    = 2
 409	vPurple = 3
 410
 411	mNone   = 0
 412	mHand   = 1
 413	mSnail  = 2
 414	mBird   = 3
 415	mFlower = 4
 416
 417	cWorm       = 1
 418	cStain      = 2
 419	cTorn       = 3
 420	cPalimpsest = 4
 421	cBurnt      = 5
 422
 423	goldInk = "#e2bd62"
 424	green   = "#4f7a3a"
 425	dark    = "#2a221d"
 426
 427	adv    = 11 // glyph advance inside a word
 428	gap    = 7  // word space
 429	tries  = 3  // draws a scribe tries before ending a line
 430	maxGap = 9  // justification never widens a word space by more than this
 431	// one-letter ids of the lexicon's words (Lexicon <= 40 never reaches "v",
 432	// the texture filter)
 433	wid = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmn"
 434)
 435
 436var (
 437	pageLight  = []string{"#efe1c2", "#eadbb9", "#f2ebda", "#4e2346"}
 438	pageEdge   = []string{"#cfb489", "#c8ad80", "#d6c8a8", "#2a0f26"}
 439	inkColor   = []string{"#3a2a1c", "#1e1b18", "#5c3c22", "#1f3566"}
 440	gx3        = []int{0, 4, 8}
 441	gy4        = []int{-12, -8, -4, 0}
 442	qx3        = []int{-2, 4, 10}
 443	qy3        = []int{-14, -6, 2}
 444	stemEnd    = []int{0, 0, -4}
 445	dotY       = []int{-16, 4}
 446	lenWeights = []int{5, 14, 20, 20, 16, 11, 8} // word length 1..7
 447	romanVals  = []int{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}
 448	romanSyms  = []string{"m", "cm", "d", "cd", "c", "xc", "l", "xl", "x", "ix", "v", "iv", "i"}
 449)
 450
 451// pairs holds "00".."99"; itoa slices it instead of calling strconv, whose
 452// formatting loop is the most expensive thing an SVG writer does in GnoVM.
 453const pairs = "00010203040506070809101112131415161718192021222324252627282930313233343536373839" +
 454	"40414243444546474849505152535455565758596061626364656667686970717273747576777879" +
 455	"8081828384858687888990919293949596979899"
 456
 457func itoa(n int) string {
 458	switch {
 459	case n < 0:
 460		return "-" + itoa(-n)
 461	case n < 10:
 462		return pairs[2*n+1 : 2*n+2]
 463	case n < 100:
 464		return pairs[2*n : 2*n+2]
 465	case n < 1000:
 466		q, m := n/100, n%100
 467		return pairs[2*q+1:2*q+2] + pairs[2*m:2*m+2]
 468	}
 469	return strconv.Itoa(n)
 470}
 471
 472func floorDiv(a, b int) int {
 473	q := a / b
 474	if a%b != 0 && (a < 0) != (b < 0) {
 475		q--
 476	}
 477	return q
 478}
 479
 480// RomanFolio writes n in medieval lower-case roman numerals; a final i is
 481// written j (iij, viij).
 482func RomanFolio(n int) string {
 483	s := ""
 484	for i, v := range romanVals {
 485		for n >= v {
 486			s += romanSyms[i]
 487			n -= v
 488		}
 489	}
 490	if len(s) >= 2 && strings.HasSuffix(s, "ii") {
 491		s = s[:len(s)-1] + "j"
 492	}
 493	return s
 494}
 495
 496// FolioNumber reads Input.TokenID: 1..99999, else 0 (sample, Studio).
 497func FolioNumber(tokenID string) int {
 498	if len(tokenID) == 0 || len(tokenID) > 5 {
 499		return 0
 500	}
 501	n := 0
 502	for i := 0; i < len(tokenID); i++ {
 503		c := tokenID[i]
 504		if c < '0' || c > '9' {
 505			return 0
 506		}
 507		n = n*10 + int(c-'0')
 508	}
 509	return n
 510}
 511
 512// part is one stroke of a glyph, points already slanted.
 513// k: 0 line a-b, 1 line a-c-b, 2 quad a(c)b, 3 hook at a, 4 dot at a.
 514type part struct {
 515	k int
 516	p [6]int
 517}
 518
 519// sp is the separator before y in "x y": none before a minus sign.
 520func sp(y int) string {
 521	if y < 0 {
 522		return ""
 523	}
 524	return " "
 525}
 526
 527// glyphPath is the path data of a glyph shifted right by ox.
 528func glyphPath(parts []part, ox int) string {
 529	d := ""
 530	for _, q := range parts {
 531		p := q.p
 532		d += "M" + itoa(p[0]+ox) + sp(p[1]) + itoa(p[1])
 533		switch q.k {
 534		case 0:
 535			d += "L" + itoa(p[2]+ox) + sp(p[3]) + itoa(p[3])
 536		case 1:
 537			d += "L" + itoa(p[4]+ox) + sp(p[5]) + itoa(p[5]) + "L" + itoa(p[2]+ox) + sp(p[3]) + itoa(p[3])
 538		case 2:
 539			d += "Q" + itoa(p[4]+ox) + sp(p[5]) + itoa(p[5]) + " " + itoa(p[2]+ox) + sp(p[3]) + itoa(p[3])
 540		case 3:
 541			d += "l3 2"
 542		default:
 543			d += "h.5"
 544		}
 545	}
 546	return d
 547}
 548
 549// opac is the opacity attribute of an ink level 70..100 (100: none).
 550func opac(v int) string {
 551	if v >= 100 {
 552		return ""
 553	}
 554	return ` opacity=".` + itoa(v) + `"`
 555}
 556
 557type column struct {
 558	x, y int // page x of the column, page y of its first baseline
 559	w, n int // width in text units, lines
 560	s    int // scale x100
 561	ss   string
 562}
 563
 564// leaf holds what the layout helpers share.
 565type leaf struct {
 566	lex    [][]int
 567	wl     []int // drawn width of each word
 568	budget int
 569}
 570
 571// justify returns the final x of each word of a line: justified to width
 572// (the gap left over is spread over the word spaces) unless ragged (a
 573// paragraph's last line).
 574func (l *leaf) justify(words, xs []int, width int, ragged bool) []int {
 575	n := len(words)
 576	extra := 0
 577	if !ragged && n > 1 {
 578		extra = width - (xs[n-1] + l.wl[words[n-1]])
 579		if extra < 0 || extra > maxGap*(n-1) {
 580			extra = 0
 581		}
 582	}
 583	px := make([]int, n)
 584	for i := 0; i < n; i++ {
 585		px[i] = xs[i]
 586		if extra > 0 {
 587			px[i] += extra * i / (n - 1)
 588		}
 589	}
 590	return px
 591}
 592
 593// uses is the <use> elements for words[from:to] at px.
 594func uses(words, px []int, from, to int) string {
 595	out := ""
 596	for i := from; i < to; i++ {
 597		w := words[i]
 598		if px[i] == 0 {
 599			out += `<use href="#` + wid[w:w+1] + `"/>`
 600		} else {
 601			out += `<use href="#` + wid[w:w+1] + `" x="` + itoa(px[i]) + `"/>`
 602		}
 603	}
 604	return out
 605}
 606
 607func leafPath(x, y, s int) string {
 608	return "M" + itoa(x) + " " + itoa(y) + "q" + itoa(6*s) + "-9 " + itoa(18*s) + "-3q" + itoa(-7*s) + " 8 " + itoa(-18*s) + " 3z"
 609}
 610
 611// SVG renders the leaf for a seed, params string and token id ("" or "0":
 612// the folio number is drawn from the seed).
 613func SVG(seed, params, tokenID string) string {
 614	return svgOf(seed, derive(seed, mustParams(params)), tokenID)
 615}
 616
 617func svgOf(seed string, t TraitSet, tokenID string) string {
 618	R := newRNG(seed + "|art")
 619	A := t.Alphabet
 620	V := t.Lexicon
 621	hand := t.Hand
 622	purple := t.Vellum == vPurple
 623	page := pageLight[t.Vellum]
 624	edge := pageEdge[t.Vellum]
 625	ink := inkColor[t.Ink]
 626	red, blue := "#ae3328", "#2a4f8a"
 627	if purple {
 628		ink, red, blue = goldInk, "#e8e2d8", "#9fc2e8"
 629	}
 630	deco := t.Decoration
 631	gilded := deco >= dGilded
 632	hasLomb := deco == dLombards || deco >= dGilded
 633	hasHead := deco == dRubricated || deco == dVine || deco == dFull
 634	usesGold := gilded || t.Marginalia == mBird || t.Marginalia == mFlower
 635
 636	filterSeed := R.rr(1, 900)
 637
 638	// --- the alphabet ---
 639	sk := func(y int) int {
 640		if hand == hSlanted {
 641			return floorDiv(5-3*y, 10)
 642		}
 643		return 0
 644	}
 645	glyphs := make([][]part, A)
 646	for g := 0; g < A; g++ {
 647		var parts []part
 648		ns := R.rr(2, 3)
 649		for s := 0; s < ns; s++ {
 650			var ax, ay, bx, by int
 651			if s == 0 {
 652				ax = gx3[R.n(3)]
 653				ay = -12
 654				if R.n(5) == 0 {
 655					ay = -16 // ascender
 656				}
 657				bx = gx3[R.n(3)]
 658				by = stemEnd[R.n(3)]
 659				if R.n(6) == 0 {
 660					by = 4 // descender
 661				}
 662			} else {
 663				ai := R.n(12)
 664				bi := R.n(12)
 665				for bi == ai {
 666					bi = R.n(12)
 667				}
 668				ax, ay = gx3[ai%3], gy4[ai/3]
 669				bx, by = gx3[bi%3], gy4[bi/3]
 670			}
 671			q := part{k: 0, p: [6]int{ax + sk(ay), ay, bx + sk(by), by, 0, 0}}
 672			if hand == hRound && R.n(100) < 70 {
 673				cy := qy3[R.n(3)]
 674				cx := qx3[R.n(3)]
 675				q.k, q.p[4], q.p[5] = 2, cx+sk(cy), cy
 676			} else if hand == hAngular && R.n(100) < 50 {
 677				cx := gx3[R.n(3)]
 678				cy := gy4[R.n(4)]
 679				q.k, q.p[4], q.p[5] = 1, cx+sk(cy), cy
 680			}
 681			parts = append(parts, q)
 682		}
 683		if hand == hHooked {
 684			e := parts[0].p
 685			parts = append(parts, part{k: 3, p: [6]int{e[2], e[3], 0, 0, 0, 0}})
 686		}
 687		if hand == hDotted && R.n(100) < 55 {
 688			dx := gx3[R.n(3)]
 689			dy := dotY[R.n(2)]
 690			parts = append(parts, part{k: 4, p: [6]int{dx + sk(dy), dy, 0, 0, 0, 0}})
 691		}
 692		glyphs[g] = parts
 693	}
 694
 695	// --- the lexicon: Zipf-weighted glyphs, frequent words shortest ---
 696	gw := make([]int, A)
 697	for i := 0; i < A; i++ {
 698		gw[i] = 600 / (i + 1)
 699	}
 700	gcum := cumulative(gw)
 701	lf := &leaf{lex: make([][]int, V), wl: make([]int, V), budget: WordBudget}
 702	for w := 0; w < V; w++ {
 703		n := 1 + R.w(lenWeights)
 704		word := make([]int, n)
 705		for i := 0; i < n; i++ {
 706			word[i] = R.pick(gcum)
 707		}
 708		lf.lex[w] = word
 709	}
 710	// stable insertion sort by length
 711	for i := 1; i < V; i++ {
 712		for j := i; j > 0 && len(lf.lex[j]) < len(lf.lex[j-1]); j-- {
 713			lf.lex[j], lf.lex[j-1] = lf.lex[j-1], lf.lex[j]
 714		}
 715	}
 716	ww := make([]int, V)
 717	for i := 0; i < V; i++ {
 718		ww[i] = 1000 / (i + 2)
 719		lf.wl[i] = len(lf.lex[i])*adv - 3
 720	}
 721	wcum := cumulative(ww)
 722	wl := lf.wl
 723
 724	var defs strings.Builder
 725	defs.WriteString("<defs>")
 726	for i := 0; i < V; i++ {
 727		d := ""
 728		for k, g := range lf.lex[i] {
 729			d += glyphPath(glyphs[g], k*adv)
 730		}
 731		defs.WriteString(`<path id="` + wid[i:i+1] + `" d="` + d + `"/>`)
 732	}
 733
 734	// --- the leaf ---
 735	defs.WriteString(`<radialGradient id="ed" cx=".5" cy=".48" r=".72"><stop offset=".55" stop-color="` + edge +
 736		`" stop-opacity="0"/><stop offset="1" stop-color="` + edge + `" stop-opacity=".9"/></radialGradient>`)
 737	defs.WriteString(`<filter id="v" x="0" y="0" width="1" height="1"><feTurbulence type="fractalNoise" baseFrequency=".012" numOctaves="3" seed="` +
 738		itoa(filterSeed) + `"/><feColorMatrix values="0 0 0 0 .45 0 0 0 0 .3 0 0 0 0 .15 0 0 0 -1.6 .75"/><feComposite in2="SourceAlpha" operator="in"/></filter>`)
 739	if usesGold {
 740		defs.WriteString(`<linearGradient id="au" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#f6e29a"/><stop offset=".45" stop-color="#c89a3a"/>` +
 741			`<stop offset=".7" stop-color="#f3dc8c"/><stop offset="1" stop-color="#a87a28"/></linearGradient>`)
 742	}
 743	pageD := "M16 14H584V806H16z"
 744	if t.Condition == cTorn {
 745		var pb strings.Builder
 746		pb.WriteString("M16 14H584V656")
 747		x, y := 584, 656
 748		for y < 806 && x > 414 {
 749			x -= R.rr(8, 20)
 750			y += R.rr(8, 22)
 751			yc := y
 752			if yc > 806 {
 753				yc = 806
 754			}
 755			pb.WriteString("L" + itoa(x) + " " + itoa(yc))
 756		}
 757		pb.WriteString("L" + itoa(x) + " 806H16z")
 758		pageD = pb.String()
 759	}
 760	defs.WriteString(`<path id="pg" d="` + pageD + `"/><clipPath id="cp"><use href="#pg"/></clipPath>`)
 761	if t.Vellum == vGoat {
 762		defs.WriteString(`<pattern id="tx" width="9" height="11" patternUnits="userSpaceOnUse"><circle cx="2" cy="3" r=".7" fill="#6a4a2a" fill-opacity=".22"/>` +
 763			`<circle cx="7" cy="8" r=".6" fill="#6a4a2a" fill-opacity=".18"/></pattern>`)
 764	} else if t.Vellum == vRag {
 765		defs.WriteString(`<pattern id="tx" width="40" height="3" patternUnits="userSpaceOnUse"><path d="M0 1h40" stroke="#8a7650" stroke-opacity=".12" stroke-width=".6"/>` +
 766			`<path d="M20 0v3" stroke="#8a7650" stroke-opacity=".2"/></pattern>`)
 767	}
 768	if gilded {
 769		defs.WriteString(`<pattern id="dp" width="6" height="6" patternUnits="userSpaceOnUse"><path d="M3 1v4M1 3h4" stroke="#fff" stroke-opacity=".3" stroke-width=".7"/></pattern>`)
 770	}
 771	body := `<rect width="600" height="820" fill="` + dark + `"/><use href="#pg" fill="` + page + `"/>`
 772	if t.Vellum == vGoat || t.Vellum == vRag {
 773		body += `<use href="#pg" fill="url(#tx)"/>`
 774	}
 775	body += `<use href="#pg" fill="url(#ed)"/><use href="#pg" filter="url(#v)" opacity=".7"/>`
 776
 777	// --- the text block ---
 778	var cols []column
 779	switch t.Layout {
 780	case lSingle:
 781		cols = []column{{78, 118, 360, 24, 115, "1.15"}}
 782	case lTwo:
 783		cols = []column{{70, 116, 190, 26, 100, ""}, {282, 116, 190, 26, 100, ""}}
 784	default:
 785		cols = []column{{182, 126, 210, 23, 120, "1.2"}}
 786	}
 787
 788	var ruling, fill, textOut strings.Builder
 789	var lombards []int // x, y pairs
 790	para, dip, firstWord := 0, 100, -1
 791	sw := "1.35"
 792	if hand == hAngular {
 793		sw = "1.5"
 794	}
 795	for ci, c := range cols {
 796		lh := c.s / 5 // 20 px x scale
 797		right := c.x + c.w*c.s/100
 798		bottom := c.y + (c.n-1)*lh
 799		ruling.WriteString("M" + itoa(c.x) + " " + itoa(c.y-14) + "V" + itoa(bottom+6) + "M" + itoa(right) + " " + itoa(c.y-14) + "V" + itoa(bottom+6))
 800		ox := c.x * 100 / c.s
 801		var inkLines, redLines, puncts strings.Builder
 802		for L := 0; L < c.n; L++ {
 803			yy := c.y + L*lh
 804			uy := yy * 100 / c.s
 805			ruling.WriteString("M" + itoa(c.x) + " " + itoa(yy) + "h" + itoa(right-c.x))
 806			x := 0
 807			if ci == 0 && L*lh < 64 {
 808				x = 66 * 100 / c.s
 809			}
 810			start := ci == 0 && L == 0
 811			lineRed := false
 812			if start {
 813				para = R.rr(4, 7)
 814				if hasHead {
 815					lineRed = true
 816				}
 817			} else if para == 0 {
 818				para = R.rr(4, 8)
 819				if hasLomb {
 820					lombards = append(lombards, c.x+x*c.s/100, yy)
 821					x += 22 * 100 / c.s
 822				}
 823				if hasHead {
 824					lineRed = true
 825				}
 826			}
 827			last := para == 1
 828			lineW := c.w
 829			if last {
 830				lineW = c.w * R.rr(35, 80) / 100
 831			}
 832			var words, xs []int
 833			for miss := 0; miss < tries && lf.budget > 0; {
 834				wi := R.pick(wcum)
 835				if x+wl[wi] > lineW {
 836					miss++
 837					continue
 838				}
 839				lf.budget--
 840				words = append(words, wi)
 841				xs = append(xs, x)
 842				x += wl[wi] + gap
 843			}
 844			if len(words) > 0 {
 845				n := len(words)
 846				px := lf.justify(words, xs, lineW, last)
 847				// a punctus ends some words and every paragraph
 848				for i := 0; i < n; i++ {
 849					if (last && i == n-1) || (i < n-1 && R.n(9) == 0) {
 850						puncts.WriteString("M" + itoa(ox+px[i]+wl[words[i]]+3) + " " + itoa(uy) + "h.1")
 851					}
 852				}
 853				if firstWord < 0 {
 854					firstWord = words[0]
 855				}
 856				tr := `<g transform="translate(` + itoa(ox) + " " + itoa(uy) + `)"`
 857				switch {
 858				case start && !hasHead:
 859					// the first word is rubricated
 860					redLines.WriteString(tr + ">" + uses(words, px, 0, 1) + "</g>")
 861					if n > 1 {
 862						inkLines.WriteString(tr + opac(dip) + ">" + uses(words, px, 1, n) + "</g>")
 863					}
 864				case lineRed:
 865					redLines.WriteString(tr + ">" + uses(words, px, 0, n) + "</g>")
 866				default:
 867					inkLines.WriteString(tr + opac(dip) + ">" + uses(words, px, 0, n) + "</g>")
 868				}
 869				dip -= R.rr(1, 4)
 870				if dip < 70 {
 871					dip = 100
 872				}
 873			}
 874			if last && hasHead && x < lineW {
 875				// line filler after the paragraph's last word
 876				fx := c.x + (x+4)*c.s/100
 877				if right-fx > 12 {
 878					fill.WriteString("M" + itoa(fx) + " " + itoa(yy-4) + "H" + itoa(right))
 879				}
 880			}
 881			para--
 882		}
 883		scale := ""
 884		if c.ss != "" {
 885			scale = ` transform="scale(` + c.ss + `)"`
 886		}
 887		textOut.WriteString("<g" + scale + ` fill="none" stroke="` + ink + `" stroke-width="` + sw + `" stroke-linecap="round" stroke-linejoin="round">`)
 888		textOut.WriteString(inkLines.String())
 889		if puncts.Len() > 0 {
 890			textOut.WriteString(`<path d="` + puncts.String() + `" stroke-width="2.6"/>`)
 891		}
 892		textOut.WriteString("</g>")
 893		if redLines.Len() > 0 {
 894			textOut.WriteString("<g" + scale + ` fill="none" stroke="` + red + `" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">`)
 895			textOut.WriteString(redLines.String())
 896			textOut.WriteString("</g>")
 897		}
 898	}
 899
 900	// --- gloss around a glossed text ---
 901	gloss := ""
 902	if t.Layout == lGlossed {
 903		var gl strings.Builder
 904		for side := 0; side < 2; side++ {
 905			gx, lw := 70, 150
 906			if side == 1 {
 907				gx, lw = 448, 165
 908			}
 909			gox := gx * 100 / 62
 910			y := 128 + R.rr(0, 40)
 911			for b := 0; b < 3 && y < 700; b++ {
 912				nl := R.rr(4, 9)
 913				for L := 0; L < nl && y < 716; L++ {
 914					var words, xs []int
 915					x := 0
 916					for miss := 0; miss < tries && lf.budget > 0; {
 917						wi := R.pick(wcum)
 918						if x+wl[wi] > lw {
 919							miss++
 920							continue
 921						}
 922						lf.budget--
 923						words = append(words, wi)
 924						xs = append(xs, x)
 925						x += wl[wi] + 6
 926					}
 927					if len(words) > 0 {
 928						gl.WriteString(`<g transform="translate(` + itoa(gox) + " " + itoa(y*100/62) + `)">` +
 929							uses(words, lf.justify(words, xs, lw, L == nl-1), 0, len(words)) + "</g>")
 930					}
 931					y += 12
 932				}
 933				y += R.rr(20, 70)
 934			}
 935		}
 936		gloss = `<g transform="scale(.62)" fill="none" stroke="` + ink + `" stroke-opacity=".85" stroke-width="1.6" stroke-linecap="round">` + gl.String() + "</g>"
 937	}
 938
 939	// --- lombards: alternating red and blue, each with a pen flourish in the other colour ---
 940	var lomb, lombPen strings.Builder
 941	lc := R.n(2)
 942	for i := 0; i < len(lombards); i += 2 {
 943		lx, ly := lombards[i], lombards[i+1]
 944		g := R.n(A)
 945		col, pen := red, blue
 946		if lc != 0 {
 947			col, pen = blue, red
 948		}
 949		lomb.WriteString(`<path transform="translate(` + itoa(lx+2) + " " + itoa(ly+4) + `) scale(1.6)" d="` + glyphPath(glyphs[g], 0) + `" stroke="` + col + `"/>`)
 950		lombPen.WriteString(`<path d="M` + itoa(lx-3) + " " + itoa(ly-16) + `q-5 9 0 18t0 18" stroke="` + pen + `"/>`)
 951		lc = 1 - lc
 952	}
 953	lombOut := ""
 954	if lomb.Len() > 0 {
 955		lombOut = `<g fill="none" stroke-width=".8" opacity=".8">` + lombPen.String() +
 956			`</g><g fill="none" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">` + lomb.String() + "</g>"
 957	}
 958	fillOut := ""
 959	if fill.Len() > 0 {
 960		fillOut = `<path d="` + fill.String() + `" stroke="` + red + `" stroke-width="2.2" stroke-linecap="round" stroke-dasharray=".1 5" opacity=".85"/>`
 961	}
 962
 963	// --- the great initial ---
 964	c0 := cols[0]
 965	bx := c0.x - 2
 966	by := c0.y - 18
 967	const bs = 62
 968	if firstWord < 0 {
 969		firstWord = 0
 970	}
 971	ig := glyphPath(glyphs[lf.lex[firstWord][0]], 0)
 972	ini := ""
 973	if gilded {
 974		var dots strings.Builder
 975		for i := 0; i < 6; i++ {
 976			dots.WriteString("M" + itoa(bx+11+i*8) + " " + itoa(by+bs-9) + "h.1")
 977		}
 978		ini = `<rect x="` + itoa(bx) + `" y="` + itoa(by) + `" width="62" height="62" fill="url(#au)" stroke="` + red + `" stroke-width="2"/>` +
 979			`<rect x="` + itoa(bx+5) + `" y="` + itoa(by+5) + `" width="52" height="52" fill="` + blue + `"/>` +
 980			`<rect x="` + itoa(bx+5) + `" y="` + itoa(by+5) + `" width="52" height="52" fill="url(#dp)"/>` +
 981			`<path d="` + dots.String() + `" stroke="#f6e7b0" stroke-width="2.4" stroke-linecap="round"/>` +
 982			`<g fill="none" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path transform="translate(` + itoa(bx+17) + " " + itoa(by+49) +
 983			`) scale(3.2)" d="` + ig + `" stroke="#1a1430" stroke-opacity=".45"/><path transform="translate(` + itoa(bx+15) + " " + itoa(by+47) +
 984			`) scale(3.2)" d="` + ig + `" stroke="#f8ecc4"/></g>`
 985	} else {
 986		letter, penc := red, blue
 987		if deco == dLombards {
 988			letter, penc = blue, red
 989		}
 990		if deco == dPlain {
 991			ini = `<rect x="` + itoa(bx) + `" y="` + itoa(by) + `" width="62" height="62" fill="none" stroke="` + red + `" stroke-width="2"/>`
 992		} else {
 993			// pen-flourished initial: a hairline frame, a dotted halo and a tail down the margin
 994			ini = `<g fill="none" stroke="` + penc + `" stroke-width=".9" stroke-linecap="round"><rect x="` + itoa(bx+3) + `" y="` + itoa(by+3) + `" width="56" height="56"/>` +
 995				`<rect x="` + itoa(bx-2) + `" y="` + itoa(by-2) + `" width="66" height="66" stroke-width="2" stroke-dasharray=".1 5"/>` +
 996				`<path d="M` + itoa(bx+4) + " " + itoa(by+bs) + `q-12 20 0 40t0 40t0 40m0-120q-14 4-16 14m16 26q14 4 16 14m-16 26q-14 4-16 14"/></g>`
 997		}
 998		ini += `<path transform="translate(` + itoa(bx+15) + " " + itoa(by+47) + `) scale(3.2)" d="` + ig + `" fill="none" stroke="` + letter +
 999			`" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"/>`
1000	}
1001
1002	// --- vine border (and the full frame) ---
1003	if deco == dVine || deco == dFull {
1004		// beside the text from the initial down; on a glossed leaf outside the gloss, from the top
1005		glossed := t.Layout == lGlossed
1006		vx, vy, vx0 := c0.x-30, by+bs, bx+4
1007		if glossed {
1008			vx, vy, vx0 = 44, 100, 44
1009		}
1010		var d, leafA, leafB, golds strings.Builder
1011		d.WriteString("M" + itoa(vx0) + " " + itoa(vy) + "Q" + itoa(vx-10) + " " + itoa(vy+20) + " " + itoa(vx) + " " + itoa(vy+50))
1012		y := vy + 50
1013		side := 1
1014		for y < 700 {
1015			ny := y + 56
1016			d.WriteString("T" + itoa(vx) + " " + itoa(ny))
1017			if side > 0 {
1018				leafA.WriteString(leafPath(vx, y+28, side))
1019			} else {
1020				leafB.WriteString(leafPath(vx, y+28, side))
1021			}
1022			golds.WriteString("M" + itoa(vx-side*11) + " " + itoa(y+30) + "h.1")
1023			side = -side
1024			y = ny
1025		}
1026		frame := ""
1027		if deco == dFull {
1028			cl := cols[len(cols)-1]
1029			tx, top := cl.x+cl.w*cl.s/100+24, bx+30
1030			if glossed {
1031				tx, top = 556, vx
1032			}
1033			d.WriteString("Q" + itoa(vx) + " 748 " + itoa(vx+60) + " 748H" + itoa(tx) + "V84H" + itoa(top))
1034			for x := vx + 70; x < tx; x += 48 {
1035				if side > 0 {
1036					leafB.WriteString(leafPath(x, 748, side))
1037				} else {
1038					leafA.WriteString(leafPath(x-18, 748, side))
1039				}
1040				golds.WriteString("M" + itoa(x+24) + " 748h.1")
1041				side = -side
1042			}
1043			frame = `<rect x="` + itoa(vx-18) + `" y="70" width="` + itoa(tx-vx+36) + `" height="696" fill="none" stroke="` + red + `" stroke-width="1.2"/>` +
1044				`<rect x="` + itoa(vx-22) + `" y="66" width="` + itoa(tx-vx+44) + `" height="704" fill="none" stroke="url(#au)" stroke-width="2.5"/>`
1045		}
1046		ini = frame + `<path d="` + d.String() + `" fill="none" stroke="` + green + `" stroke-width="2.2"/><path d="` + leafA.String() + `" fill="` + blue +
1047			`"/><path d="` + leafB.String() + `" fill="` + green + `"/><path d="` + golds.String() + `" stroke="url(#au)" stroke-width="7" stroke-linecap="round"/>` + ini
1048	}
1049
1050	// --- ruling, prickings, running head, catchword, folio ---
1051	ruleColor := "#8a6a48"
1052	if purple {
1053		ruleColor = goldInk
1054	}
1055	rule := `<path d="` + ruling.String() + `" stroke="` + ruleColor + `" stroke-opacity=".16" stroke-width=".7"/>`
1056	var pr strings.Builder
1057	for y := 110; y < 720; y += 40 {
1058		pr.WriteString("M566 " + itoa(y) + "h.1")
1059	}
1060	pricks := `<path d="` + pr.String() + `" stroke="#5a4030" stroke-opacity=".5" stroke-width="2" stroke-linecap="round"/>`
1061	var hw [3]int
1062	hwTotal := 0
1063	for i := 0; i < 3; i++ {
1064		hw[i] = R.n(V)
1065		hwTotal += wl[hw[i]]
1066		if i > 0 {
1067			hwTotal += 12
1068		}
1069	}
1070	hx := 375 - hwTotal/2 // centred on x = 300 at scale .8
1071	var head strings.Builder
1072	head.WriteString(`<g transform="scale(.8)" fill="none" stroke="` + red + `" stroke-width="1.4" stroke-linecap="round">`)
1073	for i := 0; i < 3; i++ {
1074		head.WriteString(`<use href="#` + wid[hw[i]:hw[i]+1] + `" x="` + itoa(hx) + `" y="62"/>`)
1075		hx += wl[hw[i]] + 12
1076	}
1077	head.WriteString("</g>")
1078	cw := R.n(V)
1079	cl := wl[cw]
1080	catchword := `<g transform="translate(` + itoa(470-cl) + ` 784)" fill="none" stroke="` + ink + `" stroke-width="1.3" stroke-linecap="round"><use href="#` +
1081		wid[cw:cw+1] + `"/><path d="M-6 6q` + itoa(cl/2+6) + " 8 " + itoa(cl+12) + ` 0" stroke="` + red + `"/></g>`
1082	fallback := R.rr(1, 240)
1083	sideMark := "v"
1084	if R.n(2) == 0 {
1085		sideMark = "r"
1086	}
1087	fn := FolioNumber(tokenID)
1088	if fn == 0 {
1089		fn = fallback
1090	}
1091	folio := `<text x="548" y="50" font-family="Georgia, serif" font-style="italic" font-size="15" fill="` + ink + `" text-anchor="end">f. ` + RomanFolio(fn) +
1092		`<tspan font-size="10" dy="-6">` + sideMark + "</tspan></text>"
1093
1094	// --- marginal drawing ---
1095	my := R.rr(260, 600)
1096	bxm := R.rr(200, 400)
1097	mg := ""
1098	if t.Marginalia != mNone {
1099		mx, yy := 522, my
1100		if t.Layout == lGlossed || deco == dFull { // bas-de-page, standing on y = 748
1101			mx = bxm
1102			foot := 12 // lower on a bare page
1103			if deco == dFull {
1104				foot = 0 // on the frame's lower bar
1105			}
1106			switch t.Marginalia {
1107			case mHand:
1108				yy = foot + 739
1109			case mSnail:
1110				yy = foot + 738
1111			case mBird:
1112				yy = foot + 726
1113			default:
1114				yy = foot + 708
1115			}
1116		}
1117		at := `<g transform="translate(` + itoa(mx) + " " + itoa(yy) + `)" stroke="` + ink + `"`
1118		switch t.Marginalia {
1119		case mHand:
1120			mg = at + ` stroke-width="1.3" fill="` + page + `"><rect x="18" y="-9" width="22" height="18" rx="3"/><path d="M22-9v18M27-9v18M32-9v18" fill="none" stroke-opacity=".5"/>` +
1121				`<path d="M18-7h-14q-4 0-4 4t4 4h6q-3 2 0 5h8z"/><path d="M-26-4h30q3 0 3 3t-3 3h-30q-3 0-3-3t3-3z"/></g>`
1122		case mSnail:
1123			shell := blue
1124			if R.n(2) == 0 {
1125				shell = red
1126			}
1127			body2 := "#c9c79a"
1128			if purple {
1129				body2 = "#6f6a4a"
1130			}
1131			mg = at + ` stroke-width="1.3"><path d="M-30 10h50q8 0 10-8l4-10M30-6l-2-12M34-6l4-10" fill="` + body2 +
1132				`"/><path d="M0 8a3 3 0 0 1 6 0a7 7 0 0 1-14 0a11 11 0 0 1 22 0a15 15 0 0 1-30 0" fill="` + shell + `" fill-opacity=".85"/></g>`
1133		case mBird:
1134			mg = at + ` stroke-width="1.2"><path d="M-22 4l-12 6M-22 2l-13 0" fill="none"/><ellipse rx="22" ry="12" fill="` + blue + `"/><circle cx="20" cy="-10" r="8" fill="` +
1135				blue + `"/><path d="M27-11l9 2-9 3z" fill="url(#au)"/><path d="M-12-4q10-14 22 0q-10-4-22 0z" fill="` + red +
1136				`"/><path d="M-4 12l-2 10M4 12l2 10" fill="none"/><circle cx="22" cy="-12" r="1.4" fill="` + ink + `"/></g>`
1137		default:
1138			mg = at + ` stroke-width="1.1"><path d="M0 40q-10-30 0-80" fill="none" stroke="` + green + `" stroke-width="2"/><path d="M-1 12q-14-2-18-12q12 0 18 12z" fill="` +
1139				green + `"/><path d="M9-40a7 7 0 1 0 0 1zM3-31a7 7 0 1 0 0 1zM-7-34a7 7 0 1 0 0 1zM-7-46a7 7 0 1 0 0 1zM3-49a7 7 0 1 0 0 1z" fill="` + red +
1140				`"/><circle cy="-40" r="5" fill="url(#au)"/></g>`
1141		}
1142	}
1143
1144	// --- condition ---
1145	dm, pal := "", ""
1146	switch t.Condition {
1147	case cWorm:
1148		x := R.rr(120, 460)
1149		y := R.rr(150, 650)
1150		n := R.rr(5, 11)
1151		var holes strings.Builder
1152		for i := 0; i < n; i++ {
1153			r := R.rr(2, 5)
1154			holes.WriteString(`<ellipse cx="` + itoa(x) + `" cy="` + itoa(y) + `" rx="` + itoa(r) + `" ry="` + itoa(r+1) + `"/>`)
1155			x += R.rr(-30, 30)
1156			y += R.rr(10, 40)
1157		}
1158		dm = `<g fill="` + dark + `" stroke="` + edge + `" stroke-width="1.5">` + holes.String() + "</g>"
1159	case cStain:
1160		defs.WriteString(`<radialGradient id="st"><stop offset=".6" stop-color="#8a6a40" stop-opacity="0"/><stop offset=".93" stop-color="#7a5a32" stop-opacity=".18"/>` +
1161			`<stop offset=".98" stop-color="#5a3a1a" stop-opacity=".45"/><stop offset="1" stop-color="#5a3a1a" stop-opacity="0"/></radialGradient>`)
1162		cx := R.rr(100, 500)
1163		cy := R.rr(600, 760)
1164		rx := R.rr(140, 220)
1165		ry := R.rr(90, 150)
1166		rot := R.rr(-20, 20)
1167		dm = `<ellipse cx="` + itoa(cx) + `" cy="` + itoa(cy) + `" rx="` + itoa(rx) + `" ry="` + itoa(ry) + `" fill="url(#st)" transform="rotate(` + itoa(rot) + ` 300 700)"/>`
1168	case cBurnt:
1169		defs.WriteString(`<linearGradient id="bn" x1="1" y1="0" x2="0" y2="0"><stop offset="0" stop-color="#140c08"/><stop offset=".06" stop-color="#3a2210" stop-opacity=".9"/>` +
1170			`<stop offset=".16" stop-color="#7a4a20" stop-opacity=".3"/><stop offset=".3" stop-color="#7a4a20" stop-opacity="0"/></linearGradient>` +
1171			`<filter id="bf"><feTurbulence type="fractalNoise" baseFrequency=".04" numOctaves="3" seed="` + itoa(R.rr(1, 99)) +
1172			`"/><feDisplacementMap in="SourceGraphic" scale="40" xChannelSelector="R" yChannelSelector="G"/></filter>`)
1173		dm = `<rect x="300" width="300" height="820" fill="url(#bn)" filter="url(#bf)"/>`
1174	case cPalimpsest:
1175		// the scraped older text, written across the leaf
1176		var u strings.Builder
1177		for L := 0; L < 9; L++ {
1178			var words, xs []int
1179			x := 0
1180			for lf.budget > 0 {
1181				wi := R.n(V)
1182				if x+wl[wi] > 400 {
1183					break
1184				}
1185				lf.budget--
1186				words = append(words, wi)
1187				xs = append(xs, x)
1188				x += wl[wi] + 10
1189			}
1190			u.WriteString(`<g transform="translate(22 ` + itoa(L*38-404) + `)">` + uses(words, lf.justify(words, xs, 400, false), 0, len(words)) + "</g>")
1191		}
1192		pal = `<g transform="rotate(90) scale(1.4)" fill="none" stroke="#8a3a22" stroke-opacity=".16" stroke-width="2.2" stroke-linecap="round">` + u.String() + "</g>"
1193	}
1194
1195	var out strings.Builder
1196	out.WriteString(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 820">`)
1197	out.WriteString(defs.String())
1198	out.WriteString("</defs>")
1199	out.WriteString(body)
1200	out.WriteString(`<g clip-path="url(#cp)">`)
1201	out.WriteString(pal)
1202	out.WriteString(rule)
1203	out.WriteString(pricks)
1204	out.WriteString(textOut.String())
1205	out.WriteString(gloss)
1206	out.WriteString(fillOut)
1207	out.WriteString(lombOut)
1208	out.WriteString(ini)
1209	out.WriteString(head.String())
1210	out.WriteString(catchword)
1211	out.WriteString(folio)
1212	out.WriteString(mg)
1213	out.WriteString(dm)
1214	out.WriteString("</g></svg>")
1215	return out.String()
1216}