kilim.gno
22.52 Kb · 854 lines
1// Package kilim is a Sinopia engine: a flat-woven rug computed cell by cell
2// on a warp grid. Medallions are the stepped rings of an integer distance
3// field (the grid turns every diagonal into a staircase, as on a loom), the
4// border is a running sawtooth, diamond or stripe band, and "abrash" bands
5// shift a dye lot mid-rug like hand-dyed wool.
6//
7// It is a port of the kilim prototype (Python). The RNG stream, trait
8// tables and draw order are the prototype's; the deliberate changes are the
9// Weaver's Flaw rule (now visible in every field), the params, and a compact
10// SVG encoding that renders the same pixels. Python's // and % floor towards
11// minus infinity and Go's truncate, so the lattice maths goes through
12// floorDiv/floorMod; kilim_test.gno pins golden vectors produced by the
13// Python reference, and frontend/src/engines/kilim.ts asserts the same ones.
14//
15// Pure integer maths: no floats, no time, no block data.
16package kilim
17
18import (
19 "errors"
20 "strconv"
21 "strings"
22
23 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/engine/v2"
24)
25
26// TraitTypes in the order Traits returns them.
27var traitTypes = []string{"Dyes", "Field", "Motif", "Border", "Abrash", "Symmetry", "Fringe", "Rarity"}
28
29// MaxSVGBytes: the largest output over 10,000 default seeds is 8,514 B
30// (Coarse loom: 5,984 B over 2,000 seeds x field); about 2x margin.
31const MaxSVGBytes = 16384
32
33// ParamsSchema is the Studio form. Studio sends JSON.stringify of the values
34// in this property order; ValidateParams accepts exactly that or "".
35const ParamsSchema = `{"type":"object","properties":{` +
36 `"dyes":{"type":"string","title":"Dyes","enum":["Seeded","Madder & Indigo","Saffron","Walnut & Bone",` +
37 `"Pomegranate","Night Indigo","Steppe","Undyed","Sinopia Earth"],"default":"Seeded"},` +
38 `"field":{"type":"string","title":"Field","enum":["Seeded","Medallion","Triple","Lattice","Banded","Ladder"],` +
39 `"default":"Seeded"},` +
40 `"loom":{"type":"string","title":"Loom","enum":["Fine","Coarse"],"default":"Fine"},` +
41 `"abrash":{"type":"boolean","title":"Abrash dye lots","default":true}}}`
42
43// DefaultParams is the canonical form of the defaults; it renders exactly
44// like "".
45const DefaultParams = `{"dyes":"Seeded","field":"Seeded","loom":"Fine","abrash":true}`
46
47// Manifest describes the engine. Author and FeeBps are set by the adapter.
48func Manifest() engine.Manifest {
49 return engine.Manifest{
50 Name: "Kilim",
51 Version: "1.0.0",
52 Description: "A flat-woven rug computed cell by cell on the loom grid: stepped medallions from an " +
53 "integer distance field, running borders and abrash dye-lot shifts.",
54 License: "CC-BY-NC-4.0",
55 ParamsSchema: ParamsSchema,
56 TraitTypes: append([]string{}, traitTypes...),
57 Living: false,
58 MaxSVGBytes: MaxSVGBytes,
59 Kind: engine.KindSVG,
60 }
61}
62
63// Config is a parsed params string.
64type Config struct {
65 Dyes int // -1: drawn from the seed, else an index into the dye table
66 Field int // -1: drawn from the seed, else an index into the field table
67 Coarse bool // 27 x 41 cells of 26 px instead of 37 x 55 cells of 20 px
68 Abrash bool // false: no dye-lot bands (Abrash "None")
69}
70
71// Defaults is the showcase look (params "").
72func Defaults() Config { return Config{Dyes: -1, Field: -1, Abrash: true} }
73
74var errParams = errors.New(`kilim: params must be "" or ` +
75 `{"dyes":<enum>,"field":<enum>,"loom":"Fine"|"Coarse","abrash":true|false} in that order, without spaces`)
76
77// ParseParams accepts "" or the canonical JSON Studio produces, nothing else.
78func ParseParams(params string) (Config, error) {
79 cfg := Defaults()
80 if params == "" {
81 return cfg, nil
82 }
83 v, rest, ok := strValue(params, `{"dyes":"`)
84 if !ok {
85 return cfg, errParams
86 }
87 if cfg.Dyes, ok = enumIndex(v, dyeOpts); !ok {
88 return cfg, errParams
89 }
90 if v, rest, ok = strValue(rest, `","field":"`); !ok {
91 return cfg, errParams
92 }
93 if cfg.Field, ok = enumIndex(v, fieldOpts); !ok {
94 return cfg, errParams
95 }
96 if v, rest, ok = strValue(rest, `","loom":"`); !ok {
97 return cfg, errParams
98 }
99 switch v {
100 case "Fine":
101 case "Coarse":
102 cfg.Coarse = true
103 default:
104 return cfg, errParams
105 }
106 switch rest {
107 case `","abrash":true}`:
108 case `","abrash":false}`:
109 cfg.Abrash = false
110 default:
111 return cfg, errParams
112 }
113 return cfg, nil
114}
115
116// strValue expects s to start with prefix and returns the text up to the
117// next '"' and the remainder starting at that quote.
118func strValue(s, prefix string) (string, string, bool) {
119 if !strings.HasPrefix(s, prefix) {
120 return "", "", false
121 }
122 s = s[len(prefix):]
123 end := strings.IndexByte(s, '"')
124 if end < 0 {
125 return "", "", false
126 }
127 return s[:end], s[end:], true
128}
129
130func enumIndex(v string, table []option) (int, bool) {
131 if v == "Seeded" {
132 return -1, true
133 }
134 for i, o := range table {
135 if o.name == v {
136 return i, true
137 }
138 }
139 return 0, false
140}
141
142// ValidateParams accepts "" (the showcase defaults) and the canonical JSON.
143func ValidateParams(params string) error {
144 _, err := ParseParams(params)
145 return err
146}
147
148func mustConfig(params string) Config {
149 cfg, err := ParseParams(params)
150 if err != nil {
151 panic(err)
152 }
153 return cfg
154}
155
156// Traits returns the eight traits of in.Seed in TraitTypes order. It never
157// renders: seven table draws and a score.
158func Traits(in engine.Input) []engine.Trait {
159 t := TraitsOf(in.Seed, mustConfig(in.Params))
160 return []engine.Trait{
161 {Type: "Dyes", Value: t.Dyes},
162 {Type: "Field", Value: t.Field},
163 {Type: "Motif", Value: t.Motif},
164 {Type: "Border", Value: t.Border},
165 {Type: "Abrash", Value: t.Abrash},
166 {Type: "Symmetry", Value: t.Symmetry},
167 {Type: "Fringe", Value: t.Fringe},
168 {Type: "Rarity", Value: t.Rarity},
169 }
170}
171
172// Render returns the raw SVG for in.Seed and in.Params.
173func Render(in engine.Input) string { return SVG(in.Seed, mustConfig(in.Params)) }
174
175// ---------------------------------------------------------------------------
176// Deterministic randomness: FNV-1a over the seed, then splitmix64 (Genesis's
177// stream). Traits use seed+"|traits", the art seed+"|art".
178// ---------------------------------------------------------------------------
179
180type rng struct{ state uint64 }
181
182func newRNG(seed string) *rng {
183 h := uint64(14695981039346656037)
184 for i := 0; i < len(seed); i++ {
185 h ^= uint64(seed[i])
186 h *= 1099511628211
187 }
188 if h == 0 {
189 h = 1099511628211
190 }
191 return &rng{state: h}
192}
193
194func (r *rng) next() uint64 {
195 r.state += 0x9E3779B97F4A7C15
196 z := r.state
197 z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9
198 z = (z ^ (z >> 27)) * 0x94D049BB133111EB
199 return z ^ (z >> 31)
200}
201
202// intn is in [0, n); one draw whenever n > 0.
203func (r *rng) intn(n int) int {
204 if n <= 0 {
205 return 0
206 }
207 return int(r.next() % uint64(n))
208}
209
210// between is in [a, b].
211func (r *rng) between(a, b int) int { return a + r.intn(b-a+1) }
212
213// ---------------------------------------------------------------------------
214// Trait tables. A weight is a percent; score feeds the rarity tier.
215// ---------------------------------------------------------------------------
216
217type option struct {
218 name string
219 weight int
220 score int
221}
222
223func pick(r *rng, table []option) int {
224 total := 0
225 for _, o := range table {
226 total += o.weight
227 }
228 x := r.intn(total)
229 for i, o := range table {
230 x -= o.weight
231 if x < 0 {
232 return i
233 }
234 }
235 return len(table) - 1
236}
237
238var dyeOpts = []option{
239 {"Madder & Indigo", 22, 0}, {"Saffron", 15, 0}, {"Walnut & Bone", 15, 0}, {"Pomegranate", 14, 0},
240 {"Night Indigo", 12, 1}, {"Steppe", 10, 1}, {"Undyed", 7, 2}, {"Sinopia Earth", 5, 3},
241}
242
243// palettes: 0 ground, 1..3 motif dyes, 4 dark outline, 5 light.
244var palettes = [][]string{
245 {"#9e2a22", "#1f2f5a", "#d9a441", "#4a7a6a", "#2a1712", "#ecdfc2"},
246 {"#d6962a", "#7a1f1f", "#2c3d5c", "#4f6b3a", "#3a2416", "#f1e4c6"},
247 {"#5a4030", "#a0806a", "#c49a5a", "#2b211b", "#1d1611", "#e9dfc8"},
248 {"#b2343b", "#3d5a4a", "#e0a35a", "#5a2a4a", "#2e1c22", "#f0e2cc"},
249 {"#1c2848", "#c23b2e", "#6b8fb0", "#d9a441", "#0b1020", "#e5d8b8"},
250 {"#4f6b3a", "#d9b45a", "#8c2f23", "#2c3d5c", "#1f2618", "#efe6cf"},
251 {"#e2d8c3", "#8a7c66", "#b8ab94", "#5e5346", "#3a332b", "#f3ede0"},
252 {"#8f3a26", "#c5643f", "#e8c49a", "#5e2a1a", "#3a150e", "#f4e6cf"},
253}
254
255const (
256 fieldMedallion = iota
257 fieldTriple
258 fieldLattice
259 fieldBanded
260 fieldLadder
261)
262
263var fieldOpts = []option{{"Medallion", 22, 0}, {"Triple", 22, 0}, {"Lattice", 26, 0}, {"Banded", 18, 0}, {"Ladder", 12, 1}}
264
265const (
266 motifDiamond = iota
267 motifHooked
268 motifStar
269 motifComb
270 motifEye
271)
272
273var motifOpts = []option{{"Diamond", 26, 0}, {"Hooked", 24, 0}, {"Star", 20, 0}, {"Comb", 18, 0}, {"Eye", 12, 1}}
274
275const (
276 borderSawtooth = iota
277 borderDiamonds
278 borderStripes
279 borderDouble
280 borderOpen
281)
282
283var borderOpts = []option{
284 {"Sawtooth", 32, 0}, {"Running Diamonds", 26, 0}, {"Stripes", 24, 0}, {"Double", 12, 1}, {"Open Field", 6, 3},
285}
286
287const (
288 abrashNone = iota
289 abrashFaint
290 abrashStrong
291)
292
293var abrashOpts = []option{{"None", 40, 0}, {"Faint", 40, 0}, {"Strong", 20, 1}}
294
295var symmetryOpts = []option{{"Mirrored", 82, 0}, {"Weaver's Flaw", 18, 2}}
296
297const (
298 fringeLoose = iota
299 fringeKnotted
300 fringeBound
301)
302
303var fringeOpts = []option{{"Loose", 50, 0}, {"Knotted", 38, 0}, {"Bound", 12, 1}}
304
305// Rarity tiers by score (sum of the drawn traits' scores; a trait fixed by
306// params scores 0). Over 10,000 sample seeds with default params:
307// Common 23.8% / Uncommon 47.9% / Rare 23.0% / Legendary 4.7% / Mythic 0.6%.
308const (
309 scoreMythic = 7
310 scoreLegendary = 5
311 scoreRare = 3
312 scoreUncommon = 1
313)
314
315type draw struct {
316 dyes, field, motif, border, abrash, flaw, fringe int
317 score int
318 rarity string
319}
320
321func derive(seed string, cfg Config) draw {
322 r := newRNG(seed + "|traits")
323 // Draw order is part of the contract: changing it changes every token.
324 var d draw
325 d.dyes = pick(r, dyeOpts)
326 d.field = pick(r, fieldOpts)
327 d.motif = pick(r, motifOpts)
328 d.border = pick(r, borderOpts)
329 d.abrash = pick(r, abrashOpts)
330 d.flaw = pick(r, symmetryOpts)
331 d.fringe = pick(r, fringeOpts)
332 // Params override after the draws, so the stream never shifts.
333 score := motifOpts[d.motif].score + borderOpts[d.border].score +
334 symmetryOpts[d.flaw].score + fringeOpts[d.fringe].score
335 if cfg.Dyes >= 0 {
336 d.dyes = cfg.Dyes
337 } else {
338 score += dyeOpts[d.dyes].score
339 }
340 if cfg.Field >= 0 {
341 d.field = cfg.Field
342 } else {
343 score += fieldOpts[d.field].score
344 }
345 if !cfg.Abrash {
346 d.abrash = abrashNone
347 } else {
348 score += abrashOpts[d.abrash].score
349 }
350 d.score = score
351 switch {
352 case score >= scoreMythic:
353 d.rarity = "Mythic"
354 case score >= scoreLegendary:
355 d.rarity = "Legendary"
356 case score >= scoreRare:
357 d.rarity = "Rare"
358 case score >= scoreUncommon:
359 d.rarity = "Uncommon"
360 default:
361 d.rarity = "Common"
362 }
363 return d
364}
365
366// TraitSet is the decoded properties of a seed under a config.
367type TraitSet struct {
368 Dyes, Field, Motif, Border, Abrash, Symmetry, Fringe string
369 Score int
370 Rarity string
371}
372
373// TraitsOf returns the decoded traits for a seed.
374func TraitsOf(seed string, cfg Config) TraitSet {
375 d := derive(seed, cfg)
376 return TraitSet{
377 Dyes: dyeOpts[d.dyes].name,
378 Field: fieldOpts[d.field].name,
379 Motif: motifOpts[d.motif].name,
380 Border: borderOpts[d.border].name,
381 Abrash: abrashOpts[d.abrash].name,
382 Symmetry: symmetryOpts[d.flaw].name,
383 Fringe: fringeOpts[d.fringe].name,
384 Score: d.score,
385 Rarity: d.rarity,
386 }
387}
388
389// ---------------------------------------------------------------------------
390// Integer helpers. Python semantics where the prototype relied on them.
391// ---------------------------------------------------------------------------
392
393func abs(a int) int {
394 if a < 0 {
395 return -a
396 }
397 return a
398}
399
400// floorDiv and floorMod are Python's // and % (b > 0).
401func floorDiv(a, b int) int {
402 q := a / b
403 if a%b != 0 && a < 0 {
404 q--
405 }
406 return q
407}
408
409func floorMod(a, b int) int {
410 m := a % b
411 if m < 0 {
412 m += b
413 }
414 return m
415}
416
417// dist is the medallion's integer distance field (arguments >= 0 after abs,
418// so / is exact floor division here).
419func dist(motif, du, dv int) int {
420 au, av := abs(du), abs(dv)
421 switch motif {
422 case motifStar:
423 m := au
424 if av > m {
425 m = av
426 }
427 m = m * 3 / 2
428 if au+av < m {
429 return au + av
430 }
431 return m
432 case motifEye:
433 return au*3/2 + av
434 }
435 return au + av
436}
437
438// medallion returns the palette index of a ring cell, or -1 outside.
439func medallion(motif, ringw, du, dv, size int, s []int) int {
440 d := dist(motif, du, dv)
441 if d > size {
442 return -1
443 }
444 if d == size {
445 return 4
446 }
447 k := (size - d) / ringw
448 if motif == motifHooked && d >= size-2 && abs(du)%3 == 0 {
449 return 0
450 }
451 if motif == motifComb && d >= size-3 && abs(dv)%2 == 0 && abs(du) > 1 {
452 return 0
453 }
454 return s[k%len(s)]
455}
456
457// flawed is a Weaver's Flaw sequence: every dye moved one place along 1..5.
458func flawed(s []int) []int {
459 out := make([]int, len(s))
460 for i, c := range s {
461 out[i] = c%5 + 1
462 }
463 return out
464}
465
466func shade(col string, d int) string {
467 const hexd = "0123456789abcdef"
468 out := []byte{'#', 0, 0, 0, 0, 0, 0}
469 for i := 1; i < 7; i += 2 {
470 v := unhex(col[i])*16 + unhex(col[i+1]) + d
471 if v < 0 {
472 v = 0
473 }
474 if v > 255 {
475 v = 255
476 }
477 out[i], out[i+1] = hexd[v>>4], hexd[v&15]
478 }
479 return string(out)
480}
481
482func unhex(c byte) int {
483 if c >= 'a' {
484 return int(c-'a') + 10
485 }
486 return int(c - '0')
487}
488
489// ---------------------------------------------------------------------------
490// Rendering
491// ---------------------------------------------------------------------------
492
493const (
494 ox = 30 // rug offset in px
495 oy = 80
496)
497
498// SVG renders the artwork for a seed under cfg.
499func SVG(seed string, cfg Config) string {
500 t := derive(seed, cfg)
501 C, R, cell := 37, 55, 20
502 if cfg.Coarse {
503 C, R, cell = 27, 41, 26
504 }
505 W, H := C*cell+2*ox, R*cell+2*oy
506 r := newRNG(seed + "|art") // separate stream: trait draws never shift the art
507 pal := palettes[t.dyes]
508
509 bw := 0
510 if t.border == borderDouble {
511 bw = 6
512 } else if t.border != borderOpen {
513 bw = r.between(4, 5)
514 }
515 fw, fh := C-2*bw, R-2*bw
516 seq := make([]int, r.between(3, 5))
517 for i := range seq {
518 seq[i] = r.between(1, 5)
519 }
520 seq2 := make([]int, len(seq))
521 for i := range seq2 {
522 seq2[i] = r.between(1, 5)
523 }
524 ringw := r.between(1, 2)
525 grid := make([]int, R*C)
526
527 var cu, cv, cs []int // medallion centres and sizes
528 switch t.field {
529 case fieldMedallion:
530 sz := fw/2 - 1
531 if fh/2-1 < sz {
532 sz = fh/2 - 1
533 }
534 cu, cv, cs = []int{fw / 2}, []int{fh / 2}, []int{sz}
535 case fieldTriple:
536 sz := fw/2 - 1
537 if fh/6 < sz {
538 sz = fh / 6
539 }
540 for k := 1; k <= 5; k += 2 {
541 cu, cv, cs = append(cu, fw/2), append(cv, fh*k/6), append(cs, sz)
542 }
543 case fieldLadder:
544 sz := r.between(4, 6)
545 step := 2*sz + 2
546 n := fh / step
547 off := (fh-n*step)/2 + sz + 1
548 for k := 0; k < n; k++ {
549 cu, cv, cs = append(cu, fw/2), append(cv, off+k*step), append(cs, sz)
550 }
551 }
552 flaw := -1
553 if t.flaw == 1 {
554 if t.field == fieldLattice || t.field == fieldBanded {
555 flaw = r.intn(3)
556 } else {
557 n := len(cu)
558 if n < 1 {
559 n = 1
560 }
561 flaw = r.intn(n)
562 }
563 }
564 lat := r.between(5, 7)
565 filler := r.between(5, 7)
566 band := r.between(7, 10)
567 nbands := (fh + band - 1) / band
568 seqF, seq2F := flawed(seq), flawed(seq2)
569 motif := t.motif
570
571 for v := 0; v < fh; v++ {
572 row := (v + bw) * C
573 for u := 0; u < fw; u++ {
574 c := 0
575 switch t.field {
576 case fieldMedallion, fieldTriple, fieldLadder:
577 for i := 0; i < len(cu); i++ {
578 odd := i == flaw
579 if t.field == fieldMedallion {
580 odd = flaw >= 0 && u > cu[i] && v < cv[i]
581 }
582 s := seq
583 if odd {
584 s = seq2
585 }
586 if m := medallion(motif, ringw, u-cu[i], v-cv[i], cs[i], s); m >= 0 {
587 c = m
588 break
589 }
590 }
591 if c == 0 && t.field != fieldLadder {
592 fu, fv := u%filler-filler/2, v%filler-filler/2
593 if abs(fu)+abs(fv) <= 1 {
594 near := false
595 for i := 0; i < len(cu); i++ {
596 if dist(motif, u-cu[i], v-cv[i])-cs[i] <= 2 {
597 near = true
598 break
599 }
600 }
601 if !near {
602 c = seq[len(seq)-1]
603 }
604 }
605 }
606 if t.field == fieldLadder && c == 0 && (u < 3 || u >= fw-3) && u%2 == 0 {
607 c = seq[(v/2)%len(seq)]
608 }
609 case fieldLattice:
610 p := 2 * lat
611 x, y := u-fw/2, v-fh/2
612 du, dv := floorMod(x, p)-lat, floorMod(y, p)-lat
613 odd := floorMod(floorDiv(x+lat, p)+floorDiv(y+lat, p), 2) != 0
614 isFlaw := flaw >= 0 && floorDiv(x, p) == 0 && floorDiv(y, p) == flaw-1
615 s := seq
616 if odd {
617 s = seq2
618 }
619 if isFlaw {
620 s = seqF
621 if odd {
622 s = seq2F
623 }
624 }
625 if m := medallion(motif, ringw, du, dv, lat-1, s); m >= 0 {
626 c = m
627 } else if floorMod(du+dv, 2) == 0 && abs(du) == abs(dv) {
628 c = 4
629 }
630 default: // fieldBanded
631 bi := v / band
632 dv := v%band - band/2
633 if dv == -(band / 2) {
634 c = 4
635 } else {
636 per := band - 1
637 du := (u+(bi%2)*(per/2))%per - per/2
638 s := seq
639 if bi%2 != 0 {
640 s = seq2
641 }
642 if flaw >= 0 && bi == nbands/2-1+flaw {
643 s = seqF
644 if bi%2 != 0 {
645 s = seq2F
646 }
647 }
648 if m := medallion(motif, ringw, du, dv, band/2-1, s); m >= 0 {
649 c = m
650 } else if bi%3 == 2 {
651 c = 5
652 }
653 }
654 }
655 grid[row+u+bw] = c
656 }
657 }
658
659 if bw > 0 {
660 bc0 := r.between(1, 3)
661 bc2 := r.between(1, 3)
662 bc := []int{bc0, 5, bc2}
663 for v := 0; v < R; v++ {
664 for u := 0; u < C; u++ {
665 s := u
666 if v < s {
667 s = v
668 }
669 if C-1-u < s {
670 s = C - 1 - u
671 }
672 if R-1-v < s {
673 s = R - 1 - v
674 }
675 if s >= bw {
676 continue
677 }
678 along := v
679 if s == v || s == R-1-v {
680 along = u
681 }
682 c := 0
683 switch {
684 case s == 0 || s == bw-1:
685 c = 4
686 case t.border == borderStripes:
687 c = bc[s%3]
688 case t.border == borderSawtooth || (t.border == borderDouble && s >= 3):
689 span, ss := bw-2, s-1
690 if t.border == borderDouble {
691 span, ss = 2, s-3
692 }
693 c = 5
694 if ss < abs(along%(2*span)-span) {
695 c = bc[0]
696 }
697 case t.border == borderDiamonds:
698 p := 2 * (bw - 2)
699 e := 0
700 if bw%2 == 0 {
701 e = 1
702 }
703 c = 5
704 if abs(along%p-p/2)+abs(s-(bw-1)/2-e) <= (bw-2)/2 {
705 c = bc[2]
706 }
707 default: // Double, inner stripes
708 c = bc[s%2]
709 }
710 grid[v*C+u] = c
711 }
712 }
713 }
714
715 // abrash: dye lots change in horizontal bands. Both counts are always
716 // drawn (the prototype evaluated a dict literal).
717 nFaint := r.between(1, 2)
718 nStrong := r.between(2, 3)
719 nab, amt := 0, 30
720 if t.abrash == abrashFaint {
721 nab, amt = nFaint, 14
722 } else if t.abrash == abrashStrong {
723 nab = nStrong
724 }
725 var la, lb, lc, ld []int
726 for k := 0; k < nab; k++ {
727 y0 := r.between(bw, R-bw-4)
728 la = append(la, y0)
729 lb = append(lb, y0+r.between(2, 8))
730 lc = append(lc, r.between(0, 3))
731 if r.intn(2) != 0 {
732 ld = append(ld, amt)
733 } else {
734 ld = append(ld, -amt)
735 }
736 }
737
738 // run-length rows; colours keyed by their final hex string, first-seen order
739 var cols []string
740 var counts []int
741 var ru, rv, rn, rc []int
742 for v := 0; v < R; v++ {
743 u := 0
744 for u < C {
745 c := grid[v*C+u]
746 col := pal[c]
747 for k := 0; k < len(la); k++ {
748 if la[k] <= v && v < lb[k] && lc[k] == c {
749 col = shade(col, ld[k])
750 }
751 }
752 e := u + 1
753 for e < C && grid[v*C+e] == c {
754 e++
755 }
756 ci := -1
757 for k := 0; k < len(cols); k++ {
758 if cols[k] == col {
759 ci = k
760 break
761 }
762 }
763 if ci < 0 {
764 ci = len(cols)
765 cols = append(cols, col)
766 counts = append(counts, 0)
767 }
768 counts[ci]++
769 ru, rv, rn, rc = append(ru, u), append(rv, v), append(rn, e-u), append(rc, ci)
770 u = e
771 }
772 }
773 bg := 0
774 for k := 1; k < len(counts); k++ {
775 if counts[k] > counts[bg] {
776 bg = k
777 }
778 }
779
780 var b strings.Builder
781 sW, sH, sC, sR, sOX, sOY := strconv.Itoa(W), strconv.Itoa(H), strconv.Itoa(C), strconv.Itoa(R), strconv.Itoa(ox), strconv.Itoa(oy)
782 b.WriteString(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 `)
783 b.WriteString(sW + " " + sH + `" width="` + sW + `" height="` + sH + `">`)
784 b.WriteString(`<defs><pattern id="w" width="4" height="2" patternUnits="userSpaceOnUse">` +
785 `<path d="M0 1.6L4 .4" stroke="#000" stroke-width=".7" opacity=".22"/></pattern>` +
786 `<pattern id="k" width="1" height="1" patternUnits="userSpaceOnUse">` +
787 `<path d="M0 0h1" stroke="#fff" stroke-width=".12" opacity=".2"/></pattern><path id="f" d="`)
788 // fringe (warp ends), drawn after the lots: the stream order is the prototype's
789 loose := t.fringe == fringeLoose
790 top, bottom := strconv.Itoa(oy), strconv.Itoa(oy+R*cell)
791 for u := 0; u < C; u++ {
792 x := strconv.Itoa(ox + u*cell + cell/2)
793 for side := 0; side < 2; side++ {
794 ln, sway := 50, 0
795 if loose {
796 ln = r.between(46, 62)
797 sway = r.between(-6, 6)
798 }
799 b.WriteString("M" + x + " ")
800 if side == 0 {
801 b.WriteString(top + "l" + strconv.Itoa(sway) + " " + strconv.Itoa(-ln))
802 } else {
803 b.WriteString(bottom + "l" + strconv.Itoa(sway) + " " + strconv.Itoa(ln))
804 }
805 }
806 }
807 b.WriteString(`"/></defs><rect width="` + sW + `" height="` + sH + `" fill="#e9e4da"/>`)
808 b.WriteString(`<use href="#f" stroke="#e7dcc4" stroke-width="5" stroke-linecap="round"/>` +
809 `<use href="#f" stroke="#b9ab8e" stroke-width="1.2" opacity=".6"/>`)
810 switch t.fringe {
811 case fringeKnotted:
812 b.WriteString(`<g fill="#d8cbb0">`)
813 kw := strconv.Itoa(4*cell - 16)
814 y1, y2 := strconv.Itoa(oy-22), strconv.Itoa(oy+R*cell+12)
815 for u := 1; u < C-3; u += 4 {
816 x := strconv.Itoa(ox + u*cell - 2)
817 b.WriteString(`<rect x="` + x + `" y="` + y1 + `" width="` + kw + `" height="10" rx="5"/>`)
818 b.WriteString(`<rect x="` + x + `" y="` + y2 + `" width="` + kw + `" height="10" rx="5"/>`)
819 }
820 b.WriteString(`</g>`)
821 case fringeBound:
822 rw := strconv.Itoa(C * cell)
823 b.WriteString(`<path d="M` + sOX + " " + strconv.Itoa(oy-6) + "h" + rw + "M" + sOX + " " +
824 strconv.Itoa(oy+R*cell+6) + "h" + rw + `" stroke="` + pal[4] + `" stroke-width="12"/>`)
825 }
826 b.WriteString(`<g transform="translate(` + sOX + " " + sOY + ") scale(" + strconv.Itoa(cell) +
827 `)" shape-rendering="crispEdges"><rect width="` + sC + `" height="` + sR + `" fill="` + cols[bg] +
828 `"/><g transform="translate(0 .5)">`)
829 // every run except the background colour's is a one-cell-wide stroke on
830 // its row's centre line; same-row runs continue with a relative move
831 for k := 0; k < len(cols); k++ {
832 if k == bg {
833 continue
834 }
835 b.WriteString(`<path d="`)
836 lastV, lastE := -1, 0
837 for i := 0; i < len(rc); i++ {
838 if rc[i] != k {
839 continue
840 }
841 if rv[i] == lastV {
842 b.WriteString("m" + strconv.Itoa(ru[i]-lastE) + " 0h" + strconv.Itoa(rn[i]))
843 } else {
844 b.WriteString("M" + strconv.Itoa(ru[i]) + " " + strconv.Itoa(rv[i]) + "h" + strconv.Itoa(rn[i]))
845 }
846 lastV, lastE = rv[i], ru[i]+rn[i]
847 }
848 b.WriteString(`" stroke="` + cols[k] + `"/>`)
849 }
850 b.WriteString(`</g><rect width="` + sC + `" height="` + sR + `" fill="url(#k)"/></g>`)
851 b.WriteString(`<rect x="` + sOX + `" y="` + sOY + `" width="` + strconv.Itoa(C*cell) + `" height="` +
852 strconv.Itoa(R*cell) + `" fill="url(#w)"/></svg>`)
853 return b.String()
854}