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.

cantiere.gno

27.26 Kb · 1005 lines
   1// Package cantiere is a Sinopia showcase engine: isometric maquettes of
   2// imaginary hill towns on a ruled drafting sheet, with red scaffolding for
   3// the storeys not yet built ("cantiere" is Italian for building site).
   4//
   5// A plan generator writes an N x N height map (N = 6..8); columns are drawn
   6// back to front, one anti-diagonal at a time. Columns on one diagonal never
   7// overlap, so each diagonal is a handful of merged paths, one per fill, and
   8// windows are skewed <pattern> tiles instead of one element per window. That
   9// keeps the SVG small (median ~5.5 KB) and the render cheap.
  10//
  11// Determinism: the same FNV-1a + splitmix64 stream as Genesis, with separate
  12// streams for traits (seed+"|traits") and art (seed+"|art"), so art draws
  13// never shift traits. Pure integer math; every division truncates (Go). The
  14// TypeScript twin (frontend/src/engines/cantiere.ts) is byte-identical; the
  15// golden vectors in cantiere_test.gno pin both.
  16//
  17// Params ("" = the showcase): canonical JSON in schema order, e.g.
  18// {"light":"Night","material":"Any","plan":"Any","scaffold":true}. A param
  19// pins one trait after all trait draws, so the other traits of a seed stay
  20// the same in every variant.
  21package cantiere
  22
  23import (
  24	"errors"
  25	"strconv"
  26	"strings"
  27
  28	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/engine/v1"
  29)
  30
  31// traitTypes in the order Traits returns them.
  32var traitTypes = []string{"Plan", "Material", "Light", "Scaffold", "Openings", "Garden", "Water", "Storeys", "Rarity"}
  33
  34// MaxSVGBytes: the largest output measured is 15,448 B (5,000 default seeds)
  35// and 15,174 B (19,600 renders over every param set); median ~5.5 KB. 2x margin.
  36const MaxSVGBytes = 32768
  37
  38// ParamsSchema is the Studio form: three trait pins and a scaffolding switch.
  39const ParamsSchema = `{"type":"object","properties":{` +
  40	`"light":{"type":"string","title":"Light","enum":["Any","Morning","Evening","Noon","Night"],"default":"Any"},` +
  41	`"material":{"type":"string","title":"Material","enum":["Any","Tufa","Brick","Travertine","Painted Plaster","Concrete","Basalt"],"default":"Any"},` +
  42	`"plan":{"type":"string","title":"Plan","enum":["Any","Hill Town","Ziggurat","Courtyard","Terraces","Towers","Ruin"],"default":"Any"},` +
  43	`"scaffold":{"type":"boolean","title":"Scaffolding","default":true}}}`
  44
  45// Manifest describes the engine. Author and FeeBps are set by the adapter
  46// realm that registers it.
  47func Manifest() engine.Manifest {
  48	return engine.Manifest{
  49		Name:    "Cantiere",
  50		Version: "1.0.0",
  51		Description: "Isometric maquettes of imaginary hill towns on a ruled drafting sheet, " +
  52			"with red scaffolding for the storeys not yet built.",
  53		License:      "TBD",
  54		ParamsSchema: ParamsSchema,
  55		TraitTypes:   append([]string{}, traitTypes...),
  56		Living:       false,
  57		MaxSVGBytes:  MaxSVGBytes,
  58	}
  59}
  60
  61// ValidateParams accepts "" or exactly the canonical params JSON.
  62func ValidateParams(params string) error {
  63	_, err := ParseParams(params)
  64	return err
  65}
  66
  67// Traits returns the nine traits of in.Seed in TraitTypes order. It never
  68// renders: a few table draws only.
  69func Traits(in engine.Input) []engine.Trait {
  70	t := TraitsOf(in.Seed, in.Params)
  71	return []engine.Trait{
  72		{Type: "Plan", Value: t.Plan},
  73		{Type: "Material", Value: t.Material},
  74		{Type: "Light", Value: t.Light},
  75		{Type: "Scaffold", Value: t.Scaffold},
  76		{Type: "Openings", Value: t.Openings},
  77		{Type: "Garden", Value: t.Garden},
  78		{Type: "Water", Value: t.Water},
  79		{Type: "Storeys", Value: strconv.Itoa(t.Storeys)},
  80		{Type: "Rarity", Value: t.Rarity},
  81	}
  82}
  83
  84// Render returns the raw SVG for in.Seed and in.Params.
  85func Render(in engine.Input) string { return SVG(in.Seed, in.Params) }
  86
  87// ---------------------------------------------------------------------------
  88// Params
  89// ---------------------------------------------------------------------------
  90
  91const anyValue = "Any"
  92
  93var (
  94	paramLights    = []string{anyValue, "Morning", "Evening", "Noon", "Night"}
  95	paramMaterials = []string{anyValue, "Tufa", "Brick", "Travertine", "Painted Plaster", "Concrete", "Basalt"}
  96	paramPlans     = []string{anyValue, "Hill Town", "Ziggurat", "Courtyard", "Terraces", "Towers", "Ruin"}
  97)
  98
  99// Params are the decoded collection params.
 100type Params struct {
 101	Light, Material, Plan string
 102	Scaffold              bool
 103}
 104
 105var errParams = errors.New(`cantiere params: want "" or {"light":"…","material":"…","plan":"…","scaffold":true|false} with values from the schema`)
 106
 107type paramReader struct {
 108	s string
 109	i int
 110}
 111
 112func (q *paramReader) lit(l string) bool {
 113	if !strings.HasPrefix(q.s[q.i:], l) {
 114		return false
 115	}
 116	q.i += len(l)
 117	return true
 118}
 119
 120func (q *paramReader) str(allowed []string) (string, bool) {
 121	end := strings.IndexByte(q.s[q.i:], '"')
 122	if end < 0 {
 123		return "", false
 124	}
 125	v := q.s[q.i : q.i+end]
 126	q.i += end + 1
 127	for _, a := range allowed {
 128		if a == v {
 129			return v, true
 130		}
 131	}
 132	return "", false
 133}
 134
 135// ParseParams decodes "" (defaults) or the canonical JSON Studio sends
 136// (schema order, no whitespace). Anything else is an error.
 137func ParseParams(s string) (Params, error) {
 138	p := Params{Light: anyValue, Material: anyValue, Plan: anyValue, Scaffold: true}
 139	if s == "" {
 140		return p, nil
 141	}
 142	q := &paramReader{s: s}
 143	var ok bool
 144	if !q.lit(`{"light":"`) {
 145		return p, errParams
 146	}
 147	if p.Light, ok = q.str(paramLights); !ok || !q.lit(`,"material":"`) {
 148		return p, errParams
 149	}
 150	if p.Material, ok = q.str(paramMaterials); !ok || !q.lit(`,"plan":"`) {
 151		return p, errParams
 152	}
 153	if p.Plan, ok = q.str(paramPlans); !ok || !q.lit(`,"scaffold":`) {
 154		return p, errParams
 155	}
 156	switch {
 157	case q.lit("true"):
 158		p.Scaffold = true
 159	case q.lit("false"):
 160		p.Scaffold = false
 161	default:
 162		return p, errParams
 163	}
 164	if !q.lit("}") || q.i != len(s) {
 165		return p, errParams
 166	}
 167	return p, nil
 168}
 169
 170func mustParams(s string) Params {
 171	p, err := ParseParams(s)
 172	if err != nil {
 173		panic(err.Error())
 174	}
 175	return p
 176}
 177
 178// ---------------------------------------------------------------------------
 179// Deterministic randomness: FNV-1a over the seed, then splitmix64 (Genesis).
 180// ---------------------------------------------------------------------------
 181
 182const (
 183	fnvOffset uint64 = 14695981039346656037
 184	fnvPrime  uint64 = 1099511628211
 185)
 186
 187type rng struct {
 188	state uint64
 189}
 190
 191func newRNG(seed string) *rng {
 192	h := fnvOffset
 193	for i := 0; i < len(seed); i++ {
 194		h ^= uint64(seed[i])
 195		h *= fnvPrime
 196	}
 197	if h == 0 {
 198		h = fnvPrime
 199	}
 200	return &rng{state: h}
 201}
 202
 203func (r *rng) next() uint64 {
 204	r.state += 0x9E3779B97F4A7C15
 205	z := r.state
 206	z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9
 207	z = (z ^ (z >> 27)) * 0x94D049BB133111EB
 208	return z ^ (z >> 31)
 209}
 210
 211// intn returns a value in [0, n).
 212func (r *rng) intn(n int) int {
 213	if n <= 0 {
 214		return 0
 215	}
 216	return int(r.next() % uint64(n))
 217}
 218
 219// rangeIn returns a value in [lo, hi].
 220func (r *rng) rangeIn(lo, hi int) int { return lo + r.intn(hi-lo+1) }
 221
 222// ---------------------------------------------------------------------------
 223// Trait tables: weights sum to 100; score feeds the rarity tier.
 224// ---------------------------------------------------------------------------
 225
 226type option struct {
 227	name   string
 228	weight int
 229	score  int
 230}
 231
 232// weightTotal: every table's weights sum to 100 (TestTableWeights), so one
 233// draw of intn(100) walks the table; the TS twin sums them, same value.
 234const weightTotal = 100
 235
 236// pickIdx returns the index of the drawn option.
 237func pickIdx(r *rng, table []option) int {
 238	roll := r.intn(weightTotal)
 239	acc := 0
 240	for k := 0; k < len(table); k++ {
 241		acc += table[k].weight
 242		if roll < acc {
 243			return k
 244		}
 245	}
 246	return len(table) - 1
 247}
 248
 249func findIdx(table []option, name string) int {
 250	for k := 0; k < len(table); k++ {
 251		if table[k].name == name {
 252			return k
 253		}
 254	}
 255	return 0
 256}
 257
 258var (
 259	plans     = []option{{"Hill Town", 26, 0}, {"Ziggurat", 18, 1}, {"Courtyard", 18, 1}, {"Terraces", 16, 1}, {"Towers", 14, 1}, {"Ruin", 8, 3}}
 260	materials = []option{{"Tufa", 22, 0}, {"Brick", 20, 0}, {"Travertine", 18, 0}, {"Painted Plaster", 18, 1}, {"Concrete", 12, 1}, {"Basalt", 10, 2}}
 261	lights    = []option{{"Morning", 34, 0}, {"Evening", 34, 0}, {"Noon", 18, 1}, {"Night", 14, 3}}
 262	scaffolds = []option{{"None", 40, 0}, {"Some", 40, 0}, {"Heavy", 20, 2}}
 263	openingsT = []option{{"Windows", 55, 0}, {"Loggias", 25, 1}, {"Blind", 20, 1}}
 264	gardens   = []option{{"None", 55, 0}, {"Cypresses", 32, 1}, {"Roof Gardens", 13, 2}}
 265	waters    = []option{{"None", 55, 0}, {"Pool", 25, 1}, {"Canal", 20, 1}}
 266)
 267
 268// materialColours in materials order; Painted Plaster picks one per column.
 269var materialColours = [][]string{
 270	{"#d9b46a"},
 271	{"#b3563a"},
 272	{"#e6dcc6"},
 273	{"#e8a06a", "#e9c46a", "#d9786a", "#c9b48a", "#9ab08a", "#e6d2b0"},
 274	{"#a9a59c"},
 275	{"#5a5650"},
 276}
 277
 278// Tier cut-offs on the summed scores (Storeys is derived, not scored). Over
 279// 1,000 sample seeds: Common 25% / Uncommon 39% / Rare 26% / Legendary 9% /
 280// Mythic 1%.
 281const (
 282	scoreMythic    = 9
 283	scoreLegendary = 7
 284	scoreRare      = 5
 285	scoreUncommon  = 3
 286)
 287
 288// TraitSet is the decoded properties of a seed; the SVG and the trait list
 289// both read it, so picture and metadata cannot disagree.
 290type TraitSet struct {
 291	Plan, Material, Light, Scaffold, Openings, Garden, Water string
 292	Storeys                                                  int // tallest built column
 293	Score                                                    int
 294	Rarity                                                   string
 295	material                                                 int // index into materials
 296}
 297
 298func derive(seed string, p Params) TraitSet {
 299	r := newRNG(seed + "|traits")
 300	// Draw order is part of the contract: changing it changes every token.
 301	ip := pickIdx(r, plans)
 302	im := pickIdx(r, materials)
 303	il := pickIdx(r, lights)
 304	is := pickIdx(r, scaffolds)
 305	io := pickIdx(r, openingsT)
 306	ig := pickIdx(r, gardens)
 307	iw := pickIdx(r, waters)
 308	hm := r.rangeIn(5, 8)
 309
 310	if p.Plan != anyValue {
 311		ip = findIdx(plans, p.Plan)
 312	}
 313	if p.Material != anyValue {
 314		im = findIdx(materials, p.Material)
 315	}
 316	if p.Light != anyValue {
 317		il = findIdx(lights, p.Light)
 318	}
 319	if !p.Scaffold {
 320		is = 0
 321	}
 322	if ip == 2 && iw == 0 { // Courtyard: the court always holds a pool
 323		iw = 1
 324	}
 325	plan, material, light, scaffold := plans[ip], materials[im], lights[il], scaffolds[is]
 326	openings, garden, water := openingsT[io], gardens[ig], waters[iw]
 327
 328	storeys := hm
 329	if ip == 4 { // Towers
 330		storeys = hm + 2
 331	} else if ip == 5 { // Ruin
 332		storeys = hm - 2
 333	}
 334
 335	t := TraitSet{
 336		Plan: plan.name, Material: material.name, Light: light.name, Scaffold: scaffold.name,
 337		Openings: openings.name, Garden: garden.name, Water: water.name, Storeys: storeys,
 338		material: im,
 339	}
 340	t.Score = plan.score + material.score + light.score + scaffold.score + openings.score + garden.score + water.score
 341	switch {
 342	case t.Score >= scoreMythic:
 343		t.Rarity = "Mythic"
 344	case t.Score >= scoreLegendary:
 345		t.Rarity = "Legendary"
 346	case t.Score >= scoreRare:
 347		t.Rarity = "Rare"
 348	case t.Score >= scoreUncommon:
 349		t.Rarity = "Uncommon"
 350	default:
 351		t.Rarity = "Common"
 352	}
 353	return t
 354}
 355
 356// TraitsOf returns the decoded traits of a seed; it panics on invalid params.
 357func TraitsOf(seed, params string) TraitSet {
 358	return derive(seed, mustParams(params))
 359}
 360
 361// TraitString is "Type=Value;…" in TraitTypes order (the golden-vector form
 362// shared with the TypeScript twin).
 363func TraitString(seed, params string) string {
 364	var b strings.Builder
 365	for i, tr := range Traits(engine.Input{Seed: seed, Params: params}) {
 366		if i > 0 {
 367			b.WriteString(";")
 368		}
 369		b.WriteString(tr.Type + "=" + tr.Value)
 370	}
 371	return b.String()
 372}
 373
 374// ---------------------------------------------------------------------------
 375// Art
 376// ---------------------------------------------------------------------------
 377
 378const (
 379	canvas     = 1000
 380	gardenTone = 6 // top-tone key of a roof garden
 381	hexDigits  = "0123456789abcdef"
 382)
 383
 384func hexVal(c byte) int {
 385	if c >= 'a' {
 386		return int(c-'a') + 10
 387	}
 388	return int(c - '0')
 389}
 390
 391// shade adds d to each channel of #rrggbb, clamped to 0..255.
 392func shade(col string, d int) string {
 393	out := []byte{'#', 0, 0, 0, 0, 0, 0}
 394	for k := 1; k < 7; k += 2 {
 395		v := hexVal(col[k])*16 + hexVal(col[k+1]) + d
 396		if v < 0 {
 397			v = 0
 398		}
 399		if v > 255 {
 400			v = 255
 401		}
 402		out[k] = hexDigits[v>>4]
 403		out[k+1] = hexDigits[v&15]
 404	}
 405	return string(out)
 406}
 407
 408func isqrt(n int) int {
 409	if n <= 0 {
 410		return 0
 411	}
 412	x := n
 413	y := (x + 1) / 2
 414	for y < x {
 415		x = y
 416		y = (x + n/x) / 2
 417	}
 418	return x
 419}
 420
 421func absInt(x int) int {
 422	if x < 0 {
 423		return -x
 424	}
 425	return x
 426}
 427
 428func maxInt(x, y int) int {
 429	if x > y {
 430		return x
 431	}
 432	return y
 433}
 434
 435func minInt(x, y int) int {
 436	if x < y {
 437		return x
 438	}
 439	return y
 440}
 441
 442func grid(n int) [][]int {
 443	g := make([][]int, n)
 444	for i := range g {
 445		g[i] = make([]int, n)
 446	}
 447	return g
 448}
 449
 450func flags(n int) [][]bool {
 451	g := make([][]bool, n)
 452	for i := range g {
 453		g[i] = make([]bool, n)
 454	}
 455	return g
 456}
 457
 458func heights(r *rng, plan string, n, peak int) [][]int {
 459	h := grid(n)
 460	for i := 0; i < n; i++ {
 461		for j := 0; j < n; j++ {
 462			k := maxInt(absInt(2*i-(n-1)), absInt(2*j-(n-1))) // 2 x Chebyshev distance from the centre
 463			v := 0
 464			switch plan {
 465			case "Ziggurat":
 466				top := 0
 467				if k <= 1 {
 468					top = 1
 469				}
 470				v = maxInt(1, peak-(k/2)*r.rangeIn(1, 2)+top)
 471			case "Courtyard":
 472				if i == 0 || i == n-1 || j == 0 || j == n-1 {
 473					v = r.rangeIn(3, peak)
 474				} else if k >= n-3 {
 475					v = 1
 476				}
 477			case "Terraces":
 478				v = maxInt(1, peak-((i+j)*peak)/(2*n-2)+r.rangeIn(0, 1))
 479			case "Towers":
 480				v = 1
 481			case "Ruin":
 482				if r.intn(10) < 3 {
 483					v = 0
 484				} else {
 485					v = r.rangeIn(1, peak)
 486				}
 487			default: // Hill Town
 488				dx := 2*i - n - 1
 489				dy := 2*j - n + 2
 490				d := isqrt(dx*dx + dy*dy)
 491				v = maxInt(0, peak-(d*3)/4+r.rangeIn(-1, 1))
 492				if r.intn(9) == 0 {
 493					v = 0
 494				}
 495			}
 496			h[i][j] = minInt(v, peak)
 497		}
 498	}
 499	if plan == "Towers" {
 500		towers := r.rangeIn(4, 8)
 501		for k := 0; k < towers; k++ {
 502			ti := r.intn(n)
 503			tj := r.intn(n)
 504			h[ti][tj] = r.rangeIn(4, peak)
 505		}
 506	}
 507	return h
 508}
 509
 510// town is the laid-out maquette: grid, scale and projection origin.
 511type town struct {
 512	n, a, b, c, ox, oy int
 513	hts                [][]int
 514}
 515
 516func (t *town) px(i, j int) int    { return t.ox + (i-j)*t.a }
 517func (t *town) py(i, j, z int) int { return t.oy + (i+j)*t.b - z*t.c }
 518
 519func (t *town) hl(i, j int) int { // height of the neighbour in front-left
 520	if j+1 < t.n {
 521		return t.hts[i][j+1]
 522	}
 523	return 0
 524}
 525
 526func (t *town) hr(i, j int) int { // height of the neighbour in front-right
 527	if i+1 < t.n {
 528		return t.hts[i+1][j]
 529	}
 530	return 0
 531}
 532
 533func num(b *strings.Builder, v int) { b.WriteString(strconv.Itoa(v)) }
 534
 535func (t *town) rhomb(b *strings.Builder, x, y int) {
 536	b.WriteString("M")
 537	num(b, x)
 538	b.WriteString(" ")
 539	num(b, y)
 540	b.WriteString("l")
 541	num(b, t.a)
 542	b.WriteString(" ")
 543	num(b, t.b)
 544	num(b, -t.a)
 545	b.WriteString(" ")
 546	num(b, t.b)
 547	num(b, -t.a)
 548	b.WriteString(" ")
 549	num(b, -t.b)
 550	b.WriteString("z")
 551}
 552
 553// face writes the visible part of a column's left (side 0) or right (side 1) face.
 554func (t *town) face(b *strings.Builder, side, i, j int) {
 555	h := t.hts[i][j]
 556	var x, y, lo, dx int
 557	if side == 0 {
 558		lo = t.hl(i, j)
 559		x, y, dx = t.px(i, j+1), t.py(i, j+1, lo), t.a
 560	} else {
 561		lo = t.hr(i, j)
 562		x, y, dx = t.px(i+1, j), t.py(i+1, j, lo), -t.a
 563	}
 564	b.WriteString("M")
 565	num(b, x)
 566	b.WriteString(" ")
 567	num(b, y)
 568	b.WriteString("l")
 569	num(b, dx)
 570	b.WriteString(" ")
 571	num(b, t.b)
 572	b.WriteString("v")
 573	num(b, -(h-lo)*t.c)
 574	b.WriteString("l")
 575	num(b, -dx)
 576	b.WriteString(" ")
 577	num(b, -t.b)
 578	b.WriteString("z")
 579}
 580
 581func (t *town) hasFace(side, i, j int) bool {
 582	if side == 0 {
 583		return t.hts[i][j] > t.hl(i, j)
 584	}
 585	return t.hts[i][j] > t.hr(i, j)
 586}
 587
 588// opening writes one window (Windows: slot k of 2) or loggia of the bay
 589// whose tile corner is (u, v).
 590func opening(b *strings.Builder, openings string, a, u, v, k int) {
 591	ww := maxInt(3, a/8)
 592	wy := (a * 3) / 10
 593	wh := a / 2
 594	x, w := u+a/4, a/2
 595	if openings == "Windows" {
 596		wh = (a * 45) / 100
 597		w = ww
 598		x = u + a/3 - ww/2
 599		if k != 0 {
 600			x = u + (2*a)/3 - ww/2
 601		}
 602	}
 603	b.WriteString("M")
 604	num(b, x)
 605	b.WriteString(" ")
 606	num(b, v+wy)
 607	b.WriteString("h")
 608	num(b, w)
 609	b.WriteString("v")
 610	num(b, wh)
 611	b.WriteString("h")
 612	num(b, -w)
 613	b.WriteString("z")
 614}
 615
 616func pathEl(b *strings.Builder, d, attrs string) {
 617	b.WriteString(`<path d="`)
 618	b.WriteString(d)
 619	b.WriteString(`" `)
 620	b.WriteString(attrs)
 621	b.WriteString(`/>`)
 622}
 623
 624// SVG renders the artwork for a seed and params; it panics on invalid params.
 625func SVG(seed, params string) string {
 626	tr := derive(seed, mustParams(params))
 627	return draw(seed, tr)
 628}
 629
 630func draw(seed string, tr TraitSet) string {
 631	r := newRNG(seed + "|art") // separate stream: art draws never shift traits
 632	n := r.rangeIn(6, 8)
 633	peak := tr.Storeys
 634	hts := heights(r, tr.Plan, n, peak)
 635	water := flags(n)
 636
 637	if tr.Water == "Canal" {
 638		cj := r.rangeIn(1, n-2)
 639		for i := 0; i < n; i++ {
 640			hts[i][cj] = 0
 641			water[i][cj] = true
 642		}
 643	} else if tr.Water == "Pool" {
 644		ci := n/2 - 1
 645		cj := ci
 646		if tr.Plan != "Courtyard" { // towards the front, where the town does not hide it
 647			ci = r.rangeIn(n/2-1, n-2)
 648			cj = r.rangeIn(n/2-1, n-2)
 649		}
 650		for i := ci; i <= ci+1; i++ {
 651			for j := cj; j <= cj+1; j++ {
 652				hts[i][j] = 0
 653				water[i][j] = true
 654			}
 655		}
 656	}
 657
 658	// The landmark: the tallest dry column is raised to the Storeys trait.
 659	li, lj := -1, -1
 660	for i := 0; i < n; i++ {
 661		for j := 0; j < n; j++ {
 662			if !water[i][j] && (li < 0 || hts[i][j] > hts[li][lj]) {
 663				li, lj = i, j
 664			}
 665		}
 666	}
 667	hts[li][lj] = peak
 668
 669	// Per-column choices, scanned row by row.
 670	cols := materialColours[tr.material]
 671	plaster := len(cols) > 1
 672	tone := grid(n)
 673	roof := flags(n)
 674	tree := flags(n)
 675	toneUsed := make([]bool, 6)
 676	roofs, trees := 0, 0
 677	for i := 0; i < n; i++ {
 678		for j := 0; j < n; j++ {
 679			h := hts[i][j]
 680			if h > 0 && plaster {
 681				tone[i][j] = r.intn(6)
 682			}
 683			if h > 0 {
 684				toneUsed[tone[i][j]] = true
 685			}
 686			if tr.Garden == "Roof Gardens" && h > 0 && r.intn(3) == 0 {
 687				roof[i][j] = true
 688				roofs++
 689			}
 690			if tr.Garden == "Cypresses" && !water[i][j] && h <= 3 && r.intn(4) == 0 {
 691				tree[i][j] = true
 692				trees++
 693			}
 694		}
 695	}
 696	// A garden trait is always visible: fall back to the front-most column that can carry it.
 697	if tr.Garden == "Roof Gardens" && roofs == 0 {
 698		done := false
 699		for i := n - 1; i >= 0 && !done; i-- {
 700			for j := n - 1; j >= 0; j-- {
 701				if hts[i][j] > 0 {
 702					roof[i][j] = true
 703					done = true
 704					break
 705				}
 706			}
 707		}
 708	}
 709	if tr.Garden == "Cypresses" && trees == 0 {
 710		// the front-most low dry column, else the front-most dry one
 711		fi, fj, gi, gj := -1, -1, -1, -1
 712		for i := n - 1; i >= 0; i-- {
 713			for j := n - 1; j >= 0; j-- {
 714				if water[i][j] {
 715					continue
 716				}
 717				if gi < 0 {
 718					gi, gj = i, j
 719				}
 720				if fi < 0 && hts[i][j] <= 3 {
 721					fi, fj = i, j
 722				}
 723			}
 724		}
 725		if fi < 0 {
 726			fi, fj = gi, gj
 727		}
 728		tree[fi][fj] = true
 729	}
 730
 731	// Scaffolding: unbuilt storeys on top of a column (or on an empty lot).
 732	scaf := grid(n)
 733	ns := 0
 734	if tr.Scaffold == "Some" {
 735		ns = r.rangeIn(2, 4)
 736	} else if tr.Scaffold == "Heavy" {
 737		ns = r.rangeIn(6, 11)
 738	}
 739	if tr.Plan == "Ruin" && ns > 0 {
 740		ns += 3
 741	}
 742	for k := 0; k < ns; k++ {
 743		si := r.intn(n)
 744		sj := r.intn(n)
 745		for water[si][sj] {
 746			sj = (sj + 1) % n
 747		}
 748		scaf[si][sj] = r.rangeIn(1, 3)
 749	}
 750
 751	sunY := r.rangeIn(130, 200)
 752	sunR := r.rangeIn(50, 80)
 753
 754	night := tr.Light == "Night"
 755	openings := tr.Openings
 756	slots := 1
 757	if openings == "Windows" {
 758		slots = 2
 759	}
 760	// Night: which windows of a 3 x 4 bay tile are lit.
 761	var lit []bool
 762	if night && openings != "Blind" {
 763		for k := 0; k < 12*slots; k++ {
 764			lit = append(lit, r.intn(5) < 2)
 765		}
 766	}
 767
 768	hmax := 0
 769	for i := 0; i < n; i++ {
 770		for j := 0; j < n; j++ {
 771			hmax = maxInt(hmax, hts[i][j]+scaf[i][j])
 772		}
 773	}
 774
 775	// Scale: fit the tallest stack and the plan inside the sheet.
 776	a := minInt(380/n, 1800/(2*hmax+2*n+1))
 777	a -= a % 2
 778	t := &town{n: n, a: a, b: a / 2, c: a, ox: 500, hts: hts} // storey height = bay width: window tiles fit exactly
 779	total := hmax*t.c + n*a + t.c/2
 780	t.oy = (canvas-total)/2 + hmax*t.c + 20
 781	ox, oy, b, c := t.ox, t.oy, t.b, t.c
 782
 783	paper, sun := "#1b2a44", "#e8e4d0"
 784	switch tr.Light {
 785	case "Morning":
 786		paper, sun = "#efe8d8", "#e9b44c"
 787	case "Evening":
 788		paper, sun = "#eadfd0", "#d9643a"
 789	case "Noon":
 790		paper, sun = "#f2efe6", "#f2d27a"
 791	}
 792	gridc, base, ink, winc := "#c9b9a0", "#cdbfa5", "#4a3b2e", "#3a3430"
 793	if night {
 794		gridc, base, ink, winc = "#4a6a9a", "#2c3e60", "#060c18", "#0d1424"
 795	}
 796
 797	// Face tones per material colour: top, left, right.
 798	tops := make([]string, len(cols))
 799	lefts := make([]string, len(cols))
 800	rights := make([]string, len(cols))
 801	for k, col := range cols {
 802		if night {
 803			col = shade(col, -95)
 804		}
 805		switch tr.Light {
 806		case "Morning":
 807			tops[k], lefts[k], rights[k] = shade(col, 40), col, shade(col, -55)
 808		case "Evening":
 809			tops[k], lefts[k], rights[k] = shade(col, 40), shade(col, -55), col
 810		default:
 811			tops[k], lefts[k], rights[k] = shade(col, 55), shade(col, -25), shade(col, -45)
 812		}
 813	}
 814
 815	var o strings.Builder
 816	o.WriteString(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000" width="1000" height="1000"><defs>`)
 817	o.WriteString(`<pattern id="g" x="` + strconv.Itoa(ox) + `" y="` + strconv.Itoa(oy) + `" width="` + strconv.Itoa(2*a) +
 818		`" height="` + strconv.Itoa(a) + `" patternUnits="userSpaceOnUse">`)
 819	o.WriteString(`<path d="M0 0L` + strconv.Itoa(2*a) + " " + strconv.Itoa(a) + "M0 " + strconv.Itoa(a) + "L" + strconv.Itoa(2*a) +
 820		` 0" stroke="` + gridc + `"/></pattern>`)
 821
 822	// Openings live in skewed pattern tiles of one bay x one storey.
 823	matrix := " 0 1 " + strconv.Itoa(ox) + " " + strconv.Itoa(oy) + `)">`
 824	if openings != "Blind" {
 825		var tile strings.Builder
 826		for k := 0; k < slots; k++ {
 827			opening(&tile, openings, a, 0, 0, k)
 828		}
 829		as := strconv.Itoa(a)
 830		for k := range cols {
 831			if !toneUsed[k] {
 832				continue
 833			}
 834			ks := strconv.Itoa(k)
 835			o.WriteString(`<pattern id="l` + ks + `" width="` + as + `" height="` + as + `" patternUnits="userSpaceOnUse" patternTransform="matrix(1 .5` + matrix)
 836			o.WriteString(`<rect width="` + as + `" height="` + as + `" fill="` + lefts[k] + `"/><path d="` + tile.String() + `" fill="` + winc + `"/></pattern>`)
 837			o.WriteString(`<pattern id="r` + ks + `" width="` + as + `" height="` + as + `" patternUnits="userSpaceOnUse" patternTransform="matrix(1 -.5` + matrix)
 838			o.WriteString(`<rect width="` + as + `" height="` + as + `" fill="` + rights[k] + `"/><path d="` + tile.String() + `" fill="` + winc + `"/></pattern>`)
 839		}
 840		if night {
 841			var litd strings.Builder
 842			for by := 0; by < 4; by++ {
 843				for bx := 0; bx < 3; bx++ {
 844					for k := 0; k < slots; k++ {
 845						if lit[(by*3+bx)*slots+k] {
 846							opening(&litd, openings, a, bx*a, by*a, k)
 847						}
 848					}
 849				}
 850			}
 851			if litd.Len() == 0 {
 852				opening(&litd, openings, a, 0, 0, 0)
 853			}
 854			dims := `" width="` + strconv.Itoa(3*a) + `" height="` + strconv.Itoa(4*a) + `" patternUnits="userSpaceOnUse" patternTransform="matrix(1 `
 855			o.WriteString(`<pattern id="nl` + dims + `.5` + matrix + `<path d="` + litd.String() + `" fill="#f2c35a"/></pattern>`)
 856			o.WriteString(`<pattern id="nr` + dims + `-.5` + matrix + `<path d="` + litd.String() + `" fill="#f2c35a"/></pattern>`)
 857		}
 858	}
 859	o.WriteString(`</defs><rect width="1000" height="1000" fill="` + paper + `"/><rect width="1000" height="1000" fill="url(#g)" opacity=".7"/>`)
 860	sx := 820
 861	if tr.Light == "Morning" {
 862		sx = 180
 863	}
 864	o.WriteString(`<circle cx="` + strconv.Itoa(sx) + `" cy="` + strconv.Itoa(sunY) + `" r="` + strconv.Itoa(sunR) + `" fill="` + sun + `" opacity=".9"/>`)
 865
 866	// Plinth, half a storey thick.
 867	na, nb, hc := n*a, n*b, c/2
 868	o.WriteString(`<path d="M` + strconv.Itoa(t.px(0, n)) + " " + strconv.Itoa(t.py(0, n, 0)) + "l" + strconv.Itoa(na) + " " + strconv.Itoa(nb) +
 869		"v" + strconv.Itoa(hc) + "l" + strconv.Itoa(-na) + " " + strconv.Itoa(-nb) + `z" fill="` + shade(base, -30) + `"/>`)
 870	o.WriteString(`<path d="M` + strconv.Itoa(t.px(n, 0)) + " " + strconv.Itoa(t.py(n, 0, 0)) + "l" + strconv.Itoa(-na) + " " + strconv.Itoa(nb) +
 871		"v" + strconv.Itoa(hc) + "l" + strconv.Itoa(na) + " " + strconv.Itoa(-nb) + `z" fill="` + shade(base, -55) + `"/>`)
 872	o.WriteString(`<path d="M` + strconv.Itoa(t.px(0, 0)) + " " + strconv.Itoa(t.py(0, 0, 0)) + "l" + strconv.Itoa(na) + " " + strconv.Itoa(nb) +
 873		strconv.Itoa(-na) + " " + strconv.Itoa(nb) + strconv.Itoa(-na) + " " + strconv.Itoa(-nb) + `z" fill="` + base + `"/>`)
 874
 875	waterFill := "#3d6f8f"
 876	if night {
 877		waterFill = "#20406a"
 878	}
 879	o.WriteString(`<g stroke="` + ink + `" stroke-opacity=".55">`)
 880	// Back to front: columns on one diagonal (i + j = s) never overlap, so
 881	// each diagonal is drawn as a few merged paths, one per fill.
 882	for s := 0; s <= 2*n-2; s++ {
 883		i0 := maxInt(0, s-n+1)
 884		i1 := minInt(s, n-1)
 885
 886		var wd, rip strings.Builder
 887		for i := i0; i <= i1; i++ {
 888			j := s - i
 889			if !water[i][j] {
 890				continue
 891			}
 892			t.rhomb(&wd, t.px(i, j), t.py(i, j, 0))
 893			x, y := t.px(i, j+1), t.py(i, j+1, 0)
 894			rip.WriteString("M" + strconv.Itoa(x+a/2) + " " + strconv.Itoa(y-b/4) + "l" + strconv.Itoa(a/2) + " " + strconv.Itoa(b/4))
 895			rip.WriteString("M" + strconv.Itoa(x+a/2+a/3) + " " + strconv.Itoa(y-b/2-b/4) + "l" + strconv.Itoa(a/2) + " " + strconv.Itoa(b/4))
 896		}
 897		if wd.Len() > 0 {
 898			pathEl(&o, wd.String(), `fill="`+waterFill+`"`)
 899			pathEl(&o, rip.String(), `stroke="#a9d0e0" stroke-width="2"`)
 900		}
 901
 902		// faces: left then right, one path per tone
 903		for side := 0; side < 2; side++ {
 904			for k := 0; k < 6; k++ {
 905				var d strings.Builder
 906				for i := i0; i <= i1; i++ {
 907					j := s - i
 908					if hts[i][j] == 0 || tone[i][j] != k || !t.hasFace(side, i, j) {
 909						continue
 910					}
 911					t.face(&d, side, i, j)
 912				}
 913				if d.Len() == 0 {
 914					continue
 915				}
 916				fill := ""
 917				switch {
 918				case openings == "Blind" && side == 0:
 919					fill = lefts[k]
 920				case openings == "Blind":
 921					fill = rights[k]
 922				case side == 0:
 923					fill = "url(#l" + strconv.Itoa(k) + ")"
 924				default:
 925					fill = "url(#r" + strconv.Itoa(k) + ")"
 926				}
 927				pathEl(&o, d.String(), `fill="`+fill+`"`)
 928			}
 929		}
 930		for k := 0; k <= gardenTone; k++ {
 931			var d strings.Builder
 932			for i := i0; i <= i1; i++ {
 933				j := s - i
 934				h := hts[i][j]
 935				if h == 0 {
 936					continue
 937				}
 938				key := tone[i][j]
 939				if roof[i][j] {
 940					key = gardenTone
 941				}
 942				if key == k {
 943					t.rhomb(&d, t.px(i, j), t.py(i, j, h))
 944				}
 945			}
 946			if d.Len() == 0 {
 947				continue
 948			}
 949			fill := "#7a9a5a"
 950			if k != gardenTone {
 951				fill = tops[k]
 952			}
 953			pathEl(&o, d.String(), `fill="`+fill+`"`)
 954		}
 955		if night && openings != "Blind" {
 956			for side := 0; side < 2; side++ {
 957				var d strings.Builder
 958				for i := i0; i <= i1; i++ {
 959					j := s - i
 960					if t.hasFace(side, i, j) {
 961						t.face(&d, side, i, j)
 962					}
 963				}
 964				if d.Len() == 0 {
 965					continue
 966				}
 967				if side == 0 {
 968					pathEl(&o, d.String(), `fill="url(#nl)" stroke="none"`)
 969				} else {
 970					pathEl(&o, d.String(), `fill="url(#nr)" stroke="none"`)
 971				}
 972			}
 973		}
 974		for i := i0; i <= i1; i++ {
 975			j := s - i
 976			if !tree[i][j] {
 977				continue
 978			}
 979			o.WriteString(`<ellipse cx="` + strconv.Itoa(t.px(i, j)) + `" cy="` + strconv.Itoa(t.py(i, j, hts[i][j])+b-c) +
 980				`" rx="` + strconv.Itoa(a/6) + `" ry="` + strconv.Itoa(c) + `" fill="#2f4a2a"/>`)
 981		}
 982		var sd strings.Builder
 983		for i := i0; i <= i1; i++ {
 984			j := s - i
 985			sc := scaf[i][j]
 986			if sc == 0 {
 987				continue
 988			}
 989			z0 := hts[i][j]
 990			corners := [4][2]int{{i, j}, {i + 1, j}, {i + 1, j + 1}, {i, j + 1}}
 991			for _, cn := range corners {
 992				sd.WriteString("M" + strconv.Itoa(t.px(cn[0], cn[1])) + " " + strconv.Itoa(t.py(cn[0], cn[1], z0)) + "v" + strconv.Itoa(-sc*c))
 993			}
 994			for z := z0 + 1; z <= z0+sc; z++ {
 995				t.rhomb(&sd, t.px(i, j), t.py(i, j, z))
 996			}
 997			sd.WriteString("M" + strconv.Itoa(t.px(i, j+1)) + " " + strconv.Itoa(t.py(i, j+1, z0)) + "l" + strconv.Itoa(a) + " " + strconv.Itoa(b-sc*c))
 998		}
 999		if sd.Len() > 0 {
1000			pathEl(&o, sd.String(), `fill="none" stroke="#b0442c" stroke-width="2" stroke-opacity=".9"`)
1001		}
1002	}
1003	o.WriteString(`</g></svg>`)
1004	return o.String()
1005}