pafta.gno
44.55 Kb · 1516 lines
1// Package pafta is a Sinopia engine: a collection of 256 map sheets that
2// together form one large survey map (16 x 16 sheets). The terrain is one
3// global field, so the edges of neighbouring sheets join exactly; every
4// token is one sheet, with its own settlement, landmark and place name.
5//
6// Fairness. The map and every token's sheet are fixed by the collection's
7// final salt (core commit-reveal), which exists only after the sale closed
8// and both secrets were revealed:
9//
10// mapSeed = sha256hex("art|pafta|map|v1|" + cid + "|" + salt)
11// permKey = sha256hex("art|pafta|perm|v1|" + cid + "|" + salt)
12// tile(tid) = media.Permute(permKey, 256, tid-1)
13//
14// The token's own seed (core's safe.Seed(cid, tid, salt)) only chooses what
15// is drawn on its sheet. Before Final nobody, the creator included, can tell
16// which sheet a token will be or what the map looks like. Without a
17// collection (core.RenderWith, Studio, the registration sample) a seed renders
18// a "standalone" sheet of its own map (Standalone).
19//
20// The adapter (r/…/engines/pafta) decides which of the two a call gets: only
21// core's real TokenURI/TokenTraits call for a Final commit-reveal collection
22// of this engine is placed.
23//
24// frontend/src/engines/pafta.ts is a byte-identical TypeScript twin;
25// pafta_test.gno and pafta.test.ts pin the same golden vectors. Pure integer
26// maths: no floats, no time, no block data.
27package pafta
28
29import (
30 "errors"
31 "strconv"
32 "strings"
33
34 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/engine/v2"
35 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/media/v2"
36 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
37)
38
39// TraitTypes in the order Traits returns them.
40var traitTypes = []string{"Sheet", "Terrain", "Relief", "Settlement", "Landmark", "Palette", "Landform", "Rarity"}
41
42// MaxSVGBytes: see the size table in docs/engines/pafta.md.
43const MaxSVGBytes = 28672
44
45// Side is the number of sheets per map side; a collection is exactly Sheets
46// tokens (CheckLaunch in the adapter).
47const (
48 Side = 16
49 Sheets = 256
50)
51
52// The map face of every sheet: a composite view crops each token's SVG to
53// the box (MapX, MapY, MapSize) of the Width x Height sheet and lays the
54// boxes edge to edge on the 16 x 16 grid.
55const (
56 Width = 560
57 Height = 660
58 MapX = 40
59 MapY = 96
60 MapSize = 480
61)
62
63// Hash domains of the post-reveal map seed and sheet permutation.
64const (
65 MapDomain = "art|pafta|map|v1|"
66 PermDomain = "art|pafta|perm|v1|"
67)
68
69// ParamsSchema is the Studio form. Studio sends JSON.stringify of the values
70// in this property order; ValidateParams accepts exactly that or "".
71const ParamsSchema = `{"type":"object","properties":{` +
72 `"palette":{"type":"string","title":"Palette","enum":["Seeded","Survey","Atlas","Admiralty","Antique"],"default":"Seeded"},` +
73 `"landform":{"type":"string","title":"Landform","enum":["Seeded","Island","Archipelago","Mainland Coast","Inland Sea"],` +
74 `"default":"Seeded"}}}`
75
76// DefaultParams is the canonical form of the defaults; it renders exactly
77// like "".
78const DefaultParams = `{"palette":"Seeded","landform":"Seeded"}`
79
80// Manifest describes the engine. Author and FeeBps are set by the adapter.
81func Manifest() engine.Manifest {
82 return engine.Manifest{
83 Name: "Pafta",
84 Version: "1.0.0",
85 Description: "One map in 256 sheets. Every token is a survey sheet of a single island world whose edges " +
86 "join its neighbours exactly; the map and each token's place are fixed only at the reveal.",
87 License: "CC-BY-NC-4.0",
88 ParamsSchema: ParamsSchema,
89 TraitTypes: append([]string{}, traitTypes...),
90 Living: false,
91 MaxSVGBytes: MaxSVGBytes,
92 Kind: engine.KindSVG,
93 }
94}
95
96// Config is a parsed params string.
97type Config struct {
98 Palette int // -1: from the map seed
99 Landform int // -1: from the map seed
100}
101
102// Defaults is the showcase look (params "").
103func Defaults() Config { return Config{Palette: -1, Landform: -1} }
104
105var errParams = errors.New(`pafta: params must be "" or {"palette":<enum>,"landform":<enum>} without spaces`)
106
107// ParseParams accepts "" or the canonical JSON Studio produces, nothing else.
108func ParseParams(params string) (Config, error) {
109 cfg := Defaults()
110 if params == "" {
111 return cfg, nil
112 }
113 const p1, p2, p3 = `{"palette":"`, `","landform":"`, `"}`
114 if len(params) < len(p1)+len(p3) || !strings.HasPrefix(params, p1) || !strings.HasSuffix(params, p3) {
115 return cfg, errParams
116 }
117 body := params[len(p1) : len(params)-len(p3)]
118 k := strings.Index(body, p2)
119 if k < 0 {
120 return cfg, errParams
121 }
122 pv, lv := body[:k], body[k+len(p2):]
123 if strings.IndexByte(pv, '"') >= 0 || strings.IndexByte(lv, '"') >= 0 {
124 return cfg, errParams
125 }
126 ok := false
127 if cfg.Palette, ok = enumIndex(pv, paletteOpts()); !ok {
128 return cfg, errParams
129 }
130 if cfg.Landform, ok = enumIndex(lv, landforms); !ok {
131 return cfg, errParams
132 }
133 return cfg, nil
134}
135
136// enumIndex maps "Seeded" to -1 and a table name to its index.
137func enumIndex(v string, table []option) (int, bool) {
138 if v == "Seeded" {
139 return -1, true
140 }
141 for i, o := range table {
142 if o.name == v {
143 return i, true
144 }
145 }
146 return 0, false
147}
148
149// ValidateParams accepts "" (the showcase defaults) and the canonical JSON.
150func ValidateParams(params string) error {
151 _, err := ParseParams(params)
152 return err
153}
154
155func mustConfig(params string) Config {
156 cfg, err := ParseParams(params)
157 if err != nil {
158 panic(err)
159 }
160 return cfg
161}
162
163// Place is where a token lies: the map it belongs to and its sheet
164// (0..255, row-major).
165type Place struct {
166 MapSeed string
167 Tile int
168}
169
170// MapSeed is collection cid's map seed for its final salt.
171func MapSeed(cid, salt string) string { return safe.Sha256Hex(MapDomain + cid + "|" + salt) }
172
173// PermKey is collection cid's sheet permutation key for its final salt.
174func PermKey(cid, salt string) string { return safe.Sha256Hex(PermDomain + cid + "|" + salt) }
175
176// Placement is token tid (1..256) of a Final collection with salt salt.
177func Placement(cid string, tid int64, salt string) Place {
178 if tid < 1 || tid > Sheets {
179 panic("pafta: token id must be 1..256")
180 }
181 return Place{MapSeed: MapSeed(cid, salt), Tile: int(media.Permute(PermKey(cid, salt), Sheets, tid-1))}
182}
183
184// Standalone is the placement of a seed without a collection: a sheet of the
185// seed's own map, drawn among the sheets with land at their centre (any sheet when
186// the map has none).
187func Standalone(seed string, cfg Config) Place {
188 p, _ := standalone(seed, cfg)
189 return p
190}
191
192// standalone is Standalone plus the map's landMask (the index map reuses it).
193func standalone(seed string, cfg Config) (Place, []bool) {
194 mask := landMask(mapInfoOf(seed, cfg))
195 tiles := []int{}
196 for t := 0; t < Sheets; t++ {
197 if mask[t] {
198 tiles = append(tiles, t)
199 }
200 }
201 v := newRNG(seed + "|place").next()
202 if len(tiles) == 0 {
203 return Place{MapSeed: seed, Tile: reduce(v, Sheets)}, mask
204 }
205 return Place{MapSeed: seed, Tile: tiles[reduce(v, len(tiles))]}, mask
206}
207
208// SheetCode is "A1" … "P16": row letter + column number.
209func SheetCode(tile int) string {
210 return string(rune('A'+tile/Side)) + strconv.Itoa(tile%Side+1)
211}
212
213// Traits returns the eight traits of a standalone sheet of in.Seed.
214func Traits(in engine.Input) []engine.Trait {
215 cfg := mustConfig(in.Params)
216 return SheetTraits(in.Seed, cfg, Standalone(in.Seed, cfg))
217}
218
219// Render returns the SVG of a standalone sheet of in.Seed.
220func Render(in engine.Input) string {
221 cfg := mustConfig(in.Params)
222 p, mask := standalone(in.Seed, cfg)
223 return sheetSVG(in.Seed, cfg, p, mask)
224}
225
226// SheetTraits are the traits of token seed at place p, in TraitTypes order.
227// It never renders.
228func SheetTraits(seed string, cfg Config, p Place) []engine.Trait {
229 s := survey(seed, cfg, p)
230 return []engine.Trait{
231 {Type: "Sheet", Value: SheetCode(s.tile)},
232 {Type: "Terrain", Value: s.terrain},
233 {Type: "Relief", Value: s.relief},
234 {Type: "Settlement", Value: s.settleKind},
235 {Type: "Landmark", Value: landmarks[s.mark].name},
236 {Type: "Palette", Value: palettes[s.mi.palette].name},
237 {Type: "Landform", Value: landforms[s.mi.landform].name},
238 {Type: "Rarity", Value: s.rarity},
239 }
240}
241
242// ---------------------------------------------------------------------------
243// Deterministic randomness: FNV-1a over the seed, then splitmix64 (the stream
244// of every Sinopia engine).
245// ---------------------------------------------------------------------------
246
247type rng struct{ state uint64 }
248
249func newRNG(seed string) *rng {
250 h := uint64(14695981039346656037)
251 for i := 0; i < len(seed); i++ {
252 h ^= uint64(seed[i])
253 h *= 1099511628211
254 }
255 if h == 0 {
256 h = 1099511628211
257 }
258 return &rng{state: h}
259}
260
261func (r *rng) next() uint64 {
262 r.state += 0x9E3779B97F4A7C15
263 z := r.state
264 z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9
265 z = (z ^ (z >> 27)) * 0x94D049BB133111EB
266 return z ^ (z >> 31)
267}
268
269func (r *rng) u32() uint32 { return uint32(r.next()) }
270
271func (r *rng) intn(n int) int {
272 if n <= 0 {
273 return 0
274 }
275 return int(r.next() % uint64(n))
276}
277
278func (r *rng) between(a, b int) int { return a + r.intn(b-a+1) }
279
280type option struct {
281 name string
282 weight int
283}
284
285func pick(r *rng, table []option) int {
286 total := 0
287 for _, o := range table {
288 total += o.weight
289 }
290 x := r.intn(total)
291 for i, o := range table {
292 x -= o.weight
293 if x < 0 {
294 return i
295 }
296 }
297 return len(table) - 1
298}
299
300// reduce maps a draw that was always taken onto [0, n); -1 when n <= 0.
301func reduce(v uint64, n int) int {
302 if n <= 0 {
303 return -1
304 }
305 return int(v % uint64(n))
306}
307
308// numTbl holds the decimal form of -520..520: every path number of a sheet.
309// Formatting numbers is the dearest part of a render in the VM; a lookup and
310// plain string concatenation cost a fraction of strconv and a Builder.
311const numOff = 520
312
313var numTbl = func() []string {
314 out := make([]string, 2*numOff+1)
315 for k := range out {
316 out[k] = strconv.Itoa(k - numOff)
317 }
318 return out
319}()
320
321// num is strconv.Itoa(v).
322func num(v int) string {
323 if v >= -numOff && v <= numOff {
324 return numTbl[v+numOff]
325 }
326 return strconv.Itoa(v)
327}
328
329// fdiv is floor division (b > 0).
330func fdiv(a, b int) int {
331 q := a / b
332 if a%b != 0 && a < 0 {
333 q--
334 }
335 return q
336}
337
338// ---------------------------------------------------------------------------
339// Geometry and tables
340// ---------------------------------------------------------------------------
341
342const (
343 cG = 24 // lattice cells per sheet side
344 cC = 20 // px per cell
345 cM = cG * cC // 480
346 span = cG + 3 // lattice points per side incl. a one-cell margin (-1 .. G+1)
347 world = Side * cG // 384
348 off = 96 // noise coordinates are offset to stay positive
349 hn = (span - 1) * span
350)
351
352type palette struct {
353 name string
354 weight int
355 paper, ink, ink2, sea, deep, wl, coast, bathy string
356 t0, t1, t2, t3, contour, index, hatch string
357 forest, tree, red, grid string
358}
359
360var palettes = []palette{
361 {"Survey", 35, "#f4efe2", "#2a2420", "#6a5d50", "#bcdbe6", "#a2c6d8", "#d6eaf0", "#2f5a78", "#7ea6bd",
362 "#eef0d6", "#efe3bb", "#e6cfa4", "#d8b78c", "#b08458", "#8a5a32", "#7a5634", "#dce7bf", "#7a9a58", "#b5452f", "#34404a"},
363 {"Atlas", 25, "#f6f3ea", "#1f2a30", "#5a6670", "#93c6e4", "#6aa6d3", "#b4daf0", "#1d4f7a", "#4f86b8",
364 "#bcdb9c", "#e4e4a2", "#e3c184", "#c9966c", "#8f6c40", "#6e4c28", "#f6efe4", "#a3cc88", "#3f7a3a", "#c0392b", "#20303a"},
365 {"Admiralty", 25, "#f3eee0", "#1c2633", "#5b6577", "#cfe3ee", "#f8f6ef", "#a9cde2", "#1c2633", "#6f93ad",
366 "#eedfb6", "#e7d3a2", "#dcc290", "#ceb07c", "#a08050", "#7a5a30", "#8b6b40", "#e3dcae", "#8a8a50", "#b03070", "#1c2633"},
367 {"Antique", 15, "#efe2c4", "#3b2a1a", "#7a6040", "#cdd4bf", "#bcc6b0", "#dde0cb", "#5a4024", "#9a8660",
368 "#efe2c0", "#e7d3a9", "#dcc191", "#cdaa77", "#9a7448", "#6e4a28", "#6e4a28", "#e0d3a7", "#7a6a3a", "#9a3020", "#3b2a1a"},
369}
370
371func paletteOpts() []option {
372 out := make([]option, len(palettes))
373 for i, p := range palettes {
374 out[i] = option{p.name, p.weight}
375 }
376 return out
377}
378
379var landforms = []option{{"Island", 40}, {"Archipelago", 25}, {"Mainland Coast", 20}, {"Inland Sea", 15}}
380
381const (
382 lfIsland = 0
383 lfArchipelago = 1
384 lfCoast = 2 // 3: Inland Sea
385)
386
387var settleKinds = []option{{"Hamlet", 40}, {"Village", 38}, {"Town", 22}}
388
389const sHamlet = 0
390
391var landmarks = []option{
392 {"None", 60}, {"Lighthouse", 9}, {"Wreck", 8}, {"Castle", 8}, {"Ruins", 7}, {"Windmill", 5}, {"Treasure", 3},
393}
394
395const (
396 lmNone = 0
397 lmLighthouse = 1
398 lmWreck = 2
399 lmCastle = 3
400 lmRuins = 4
401 lmWindmill = 5
402 lmTreasure = 6
403)
404
405// Place-name parts: lower, upper (Turkish casing).
406var nameA = [][2]string{
407 {"Kara", "KARA"}, {"Ak", "AK"}, {"Kızıl", "KIZIL"}, {"Gök", "GÖK"}, {"Yel", "YEL"}, {"Tuz", "TUZ"},
408 {"Mercan", "MERCAN"}, {"Sakız", "SAKIZ"}, {"Ilgın", "ILGIN"}, {"Defne", "DEFNE"}, {"Martı", "MARTI"},
409 {"Lodos", "LODOS"}, {"Poyraz", "POYRAZ"}, {"Sünger", "SÜNGER"}, {"İnci", "İNCİ"}, {"Kum", "KUM"},
410}
411
412var nameB = [][2]string{
413 {"ada", "ADA"}, {"burun", "BURUN"}, {"koy", "KOY"}, {"liman", "LİMAN"}, {"kaya", "KAYA"}, {"yalı", "YALI"},
414 {"tepe", "TEPE"}, {"köy", "KÖY"}, {"pınar", "PINAR"}, {"dere", "DERE"}, {"ova", "OVA"}, {"kale", "KALE"},
415}
416
417// ---------------------------------------------------------------------------
418// The map
419// ---------------------------------------------------------------------------
420
421type mapInfo struct {
422 sh, sh2 uint32
423 palette, landform, dir int
424 nameA, nameB int
425}
426
427func mapInfoOf(mapSeed string, cfg Config) mapInfo {
428 r := newRNG(mapSeed + "|map")
429 // Draw order is part of the contract; params override after the draws.
430 var mi mapInfo
431 mi.sh = r.u32()
432 mi.sh2 = r.u32()
433 mi.palette = pick(r, paletteOpts())
434 mi.landform = pick(r, landforms)
435 mi.dir = r.intn(4)
436 mi.nameA = r.intn(len(nameA))
437 mi.nameB = r.intn(len(nameB))
438 if cfg.Palette >= 0 {
439 mi.palette = cfg.Palette
440 }
441 if cfg.Landform >= 0 {
442 mi.landform = cfg.Landform
443 }
444 return mi
445}
446
447func hash32(sh uint32, o, ix, iy int) uint32 {
448 h := uint32(ix)*374761393 + uint32(iy)*668265263 + uint32(o+1)*1442695041
449 h ^= sh
450 h = (h ^ (h >> 13)) * 1274126177
451 h ^= h >> 16
452 return h
453}
454
455// oct is an octave: cell size, amplitude, octave id.
456type oct struct{ s, amp, o int }
457
458var reliefOcts = []oct{{96, 1000, 0}, {48, 640, 1}, {24, 420, 2}, {12, 240, 3}, {6, 110, 4}, {3, 45, 8}}
459var moistOcts = []oct{{32, 1000, 5}, {16, 500, 6}, {8, 220, 7}}
460
461// noiseGrid is value noise (smoothstep, Q10) summed over octaves at the
462// points (x0 + i*step, y0 + j*step), i < nx, j < ny; coordinates >= 0. Node
463// values are scaled by the octave's amplitude first; the bilinear blend is
464// separable (each node row is blended along x once).
465func noiseGrid(sh uint32, octs []oct, x0, y0, step, nx, ny int) []int {
466 out := make([]int, nx*ny)
467 xi := make([]int, nx)
468 xs := make([]int, nx)
469 for _, oc := range octs {
470 S, amp, o := oc.s, oc.amp, oc.o
471 lx, ly := x0/S, y0/S
472 w := (x0+(nx-1)*step)/S - lx + 2
473 h := (y0+(ny-1)*step)/S - ly + 2
474 for i := 0; i < nx; i++ {
475 g := x0 + i*step
476 ix := g / S
477 t := (g - ix*S) * 1024 / S
478 xi[i] = ix - lx
479 xs[i] = t * t * (3072 - 2*t) / 1048576
480 }
481 // rows[r*nx+i]: node row r blended along x at column i (Q10)
482 rows := make([]int, h*nx)
483 node := make([]int, w)
484 for r := 0; r < h; r++ {
485 for k := 0; k < w; k++ {
486 node[k] = fdiv((int(hash32(sh, o, lx+k, ly+r)%2001)-1000)*amp, 1000)
487 }
488 base := r * nx
489 for i := 0; i < nx; i++ {
490 a := node[xi[i]]
491 rows[base+i] = a*1024 + (node[xi[i]+1]-a)*xs[i]
492 }
493 }
494 for j := 0; j < ny; j++ {
495 g := y0 + j*step
496 iy := g / S
497 t := (g - iy*S) * 1024 / S
498 sy := t * t * (3072 - 2*t) / 1048576
499 b0 := (iy - ly) * nx
500 b1 := b0 + nx
501 oj := j * nx
502 for i := 0; i < nx; i++ {
503 a0 := rows[b0+i]
504 out[oj+i] += (a0*1024 + (rows[b1+i]-a0)*sy) >> 20
505 }
506 }
507 }
508 return out
509}
510
511// falloff is the landform's large-scale shape at world lattice point (gx, gy).
512func falloff(mi mapInfo, gx, gy int) int {
513 dx := gx - world/2
514 dy := gy - world/2
515 d2 := dx*dx + dy*dy
516 switch mi.landform {
517 case lfIsland:
518 return 700 - d2*1400/36864
519 case lfArchipelago:
520 return 60 - d2*700/36864
521 case lfCoast:
522 t, u := gx, gy
523 if mi.dir == 1 {
524 t = world - gx
525 }
526 if mi.dir == 2 {
527 t, u = gy, gx
528 }
529 if mi.dir == 3 {
530 t, u = world-gy, gx
531 }
532 du := u - world/2
533 return 1000 - fdiv(t*2000, world) - du*du*500/36864
534 default:
535 return -850 + d2*1500/36864
536 }
537}
538
539// relief is the elevation lattice of sheet (sx, sy): span x span points,
540// i, j in -1 .. G+1.
541func relief(mi mapInfo, sx, sy int) []int {
542 gx0, gy0 := sx*cG-1, sy*cG-1
543 e := noiseGrid(mi.sh, reliefOcts, gx0+off, gy0+off, 1, span, span)
544 for j := 0; j < span; j++ {
545 for i := 0; i < span; i++ {
546 e[j*span+i] += falloff(mi, gx0+i, gy0+j)
547 }
548 }
549 return e
550}
551
552// woodland is the forest field: >= 0 inside woodland (moist ground between
553// 40 and 1100 m).
554func woodland(mi mapInfo, sx, sy int, e []int) []int {
555 m := noiseGrid(mi.sh2, moistOcts, sx*cG-1+off, sy*cG-1+off, 1, span, span)
556 f := make([]int, span*span)
557 for k := 0; k < span*span; k++ {
558 v := e[k]
559 x := m[k] - 220
560 if v-40 < x {
561 x = v - 40
562 }
563 if 1100-v < x {
564 x = 1100 - v
565 }
566 f[k] = x
567 }
568 return f
569}
570
571func at(i, j int) int { return (j+1)*span + i + 1 }
572
573// hillShade is the hill-shading field (light from the north-west): >= 0 on
574// land whose slope turns away from the light. A central difference over the
575// global lattice, so it joins across sheets.
576func hillShade(e []int) []int {
577 f := make([]int, span*span)
578 for k := range f {
579 f[k] = -1
580 }
581 for j := 0; j <= cG; j++ {
582 k := (j+1)*span + 1
583 for i := 0; i <= cG; i++ {
584 d := e[k-span-1] - e[k+span+1] - 70
585 v := e[k]
586 if d < v {
587 f[k] = d
588 } else {
589 f[k] = v
590 }
591 k++
592 }
593 }
594 return f
595}
596
597// landMask is land (true) or sea at the centre of each of the 256 sheets
598// (the index map; row-major like the tiles), from the three coarsest octaves.
599func landMask(mi mapInfo) []bool {
600 n := noiseGrid(mi.sh, reliefOcts[:3], cG/2+off, cG/2+off, cG, Side, Side)
601 out := make([]bool, Sheets)
602 for t := 0; t < Sheets; t++ {
603 out[t] = n[t]+falloff(mi, cG/2+(t%Side)*cG, cG/2+(t/Side)*cG) >= 0
604 }
605 return out
606}
607
608// ---------------------------------------------------------------------------
609// Sheet analysis (traits)
610// ---------------------------------------------------------------------------
611
612type surveyed struct {
613 mi mapInfo
614 tile, sx, sy int
615 e []int
616 terrain, relief string
617 peak int // lattice index of the highest interior point, -1 below 300 m
618 settle int // -1: none
619 settleKind string
620 mark, markAt int // landmark kind; -1: none
621 rarity string
622}
623
624func coastal(e []int, i, j int) bool {
625 return e[at(i-1, j)] < 0 || e[at(i+1, j)] < 0 || e[at(i, j-1)] < 0 || e[at(i, j+1)] < 0
626}
627
628func survey(seed string, cfg Config, p Place) *surveyed {
629 if p.Tile < 0 || p.Tile >= Sheets {
630 panic("pafta: tile must be 0..255")
631 }
632 s := &surveyed{mi: mapInfoOf(p.MapSeed, cfg), tile: p.Tile, sx: p.Tile % Side, sy: p.Tile / Side}
633 e := relief(s.mi, s.sx, s.sy)
634 s.e = e
635 emin, emax := 1<<30, -(1 << 30)
636 borderLand, borderSea := false, false
637 for j := 0; j <= cG; j++ {
638 for i := 0; i <= cG; i++ {
639 v := e[at(i, j)]
640 if v < emin {
641 emin = v
642 }
643 if v > emax {
644 emax = v
645 }
646 if i == 0 || j == 0 || i == cG || j == cG {
647 if v >= 0 {
648 borderLand = true
649 } else {
650 borderSea = true
651 }
652 }
653 }
654 }
655 s.terrain = "Coast"
656 switch {
657 case emax < 0:
658 s.terrain = "Open Sea"
659 case emin >= 0:
660 s.terrain = "Inland"
661 case !borderLand:
662 s.terrain = "Islet"
663 case !borderSea:
664 s.terrain = "Lake"
665 }
666 s.relief = "High Peaks"
667 switch {
668 case emax < -600:
669 s.relief = "Deep Water"
670 case emax < -150:
671 s.relief = "Open Water"
672 case emax < 0:
673 s.relief = "Shoals"
674 case emax < 300:
675 s.relief = "Lowland"
676 case emax < 800:
677 s.relief = "Hills"
678 case emax < 1200:
679 s.relief = "Uplands"
680 case emax < 1800:
681 s.relief = "Mountains"
682 }
683
684 // highest interior point (labels stay inside the sheet)
685 s.peak = -1
686 pv := 300
687 for j := 2; j <= cG-2; j++ {
688 for i := 2; i <= cG-2; i++ {
689 if e[at(i, j)] > pv {
690 pv = e[at(i, j)]
691 s.peak = at(i, j)
692 }
693 }
694 }
695
696 T := newRNG(seed + "|traits")
697 // Draw order is part of the contract: every draw is taken, used or not.
698 kind := pick(T, settleKinds)
699 sPick := T.next()
700 mark := pick(T, landmarks)
701 mPick := T.next()
702
703 towns := []int{}
704 for j := 2; j <= cG-2; j++ {
705 for i := 2; i <= cG-2; i++ {
706 v := e[at(i, j)]
707 if v >= 20 && v <= 300 {
708 towns = append(towns, at(i, j))
709 }
710 }
711 }
712 s.settle = -1
713 s.settleKind = "None"
714 if si := reduce(sPick, len(towns)); si >= 0 {
715 s.settle = towns[si]
716 s.settleKind = settleKinds[kind].name
717 if kind != sHamlet && coastal(e, s.settle%span-1, s.settle/span-1) {
718 s.settleKind = "Port"
719 }
720 }
721
722 s.markAt = -1
723 s.mark = lmNone
724 if mark != lmNone {
725 cands := []int{}
726 for j := 2; j <= cG-2; j++ {
727 for i := 2; i <= cG-2; i++ {
728 k := at(i, j)
729 v := e[k]
730 if s.settle >= 0 {
731 di := i - (s.settle%span - 1)
732 dj := j - (s.settle/span - 1)
733 if dj >= -2 && dj <= 2 && di >= -8 && di <= 8 {
734 continue
735 }
736 }
737 if s.peak >= 0 {
738 di := i - (s.peak%span - 1)
739 dj := j - (s.peak/span - 1)
740 if dj >= -1 && dj <= 1 && di >= -2 && di <= 4 {
741 continue
742 }
743 }
744 ok := false
745 switch mark {
746 case lmLighthouse:
747 ok = v >= 0 && v <= 150 && coastal(e, i, j)
748 case lmWreck:
749 ok = v < -120
750 case lmCastle:
751 ok = v >= 250
752 case lmRuins:
753 ok = v >= 0 && v <= 800
754 case lmWindmill:
755 ok = v >= 30 && v <= 500
756 default:
757 ok = v >= 0
758 }
759 if ok {
760 cands = append(cands, k)
761 }
762 }
763 }
764 if mi2 := reduce(mPick, len(cands)); mi2 >= 0 {
765 s.markAt = cands[mi2]
766 s.mark = mark
767 }
768 }
769
770 score := 0
771 switch s.terrain {
772 case "Islet", "Lake":
773 score += 4
774 case "Open Sea", "Coast":
775 score++
776 }
777 switch s.relief {
778 case "High Peaks":
779 score += 3
780 case "Mountains":
781 score += 2
782 case "Uplands", "Deep Water":
783 score++
784 }
785 switch s.mark {
786 case lmTreasure:
787 score += 5
788 case lmLighthouse, lmWreck, lmCastle:
789 score += 3
790 case lmNone:
791 default:
792 score += 2
793 }
794 if s.settleKind == "Port" || s.settleKind == "Town" {
795 score++
796 }
797 s.rarity = "Common"
798 switch {
799 case score >= 9:
800 s.rarity = "Mythic"
801 case score >= 7:
802 s.rarity = "Legendary"
803 case score >= 5:
804 s.rarity = "Rare"
805 case score >= 3:
806 s.rarity = "Uncommon"
807 }
808 return s
809}
810
811// ---------------------------------------------------------------------------
812// Marching squares
813// ---------------------------------------------------------------------------
814
815// edgeCut is the offset (1..C-1) of level T's crossing on the edge from
816// value a to value b. It never lands on a corner: a crossing rounded onto a
817// cell corner would put a sliver of one sheet's polygon on the shared edge
818// where its neighbour has none.
819func edgeCut(a, b, T int) int {
820 num := (T - a) * cC
821 den := b - a
822 if den < 0 {
823 num, den = -num, -den
824 }
825 r := (2*num + den) / (2 * den)
826 if r < 1 {
827 return 1
828 }
829 if r > cC-1 {
830 return cC - 1
831 }
832 return r
833}
834
835// relPath appends a polyline (or a fill polygon) of n points in relative
836// form to d; zero moves are dropped.
837func relPath(d *string, xs, ys []int, n int) {
838 px, py := xs[0], ys[0]
839 out := "M" + num(px) + " " + num(py)
840 sep := "l"
841 for k := 1; k < n; k++ {
842 dx, dy := xs[k]-px, ys[k]-py
843 if dx == 0 && dy == 0 {
844 continue
845 }
846 out += sep + num(dx) + " " + num(dy)
847 sep = " "
848 px, py = xs[k], ys[k]
849 }
850 *d += out
851}
852
853// region is the area where e >= T (above) or e < T (below) on the sheet's own
854// cells: row runs of full cells plus one polygon per partial cell, all
855// clockwise, in one path. Crossing points are computed from the edge's
856// canonical end, so neighbouring cells (and neighbouring sheets) put them in
857// the same place.
858func region(e []int, T int, above bool) string {
859 sb := ""
860 var xs, ys [6]int
861 for j := 0; j < cG; j++ {
862 run := -1
863 r0 := (j+1)*span + 1 // lattice index of (0, j)
864 r1 := r0 + span // (0, j+1)
865 for i := 0; i <= cG; i++ {
866 full := false
867 c0, c1, c2, c3 := false, false, false, false
868 if i < cG {
869 c0 = (e[r0+i] >= T) == above
870 c1 = (e[r0+i+1] >= T) == above
871 c2 = (e[r1+i+1] >= T) == above
872 c3 = (e[r1+i] >= T) == above
873 full = c0 && c1 && c2 && c3
874 }
875 if full && run < 0 {
876 run = i
877 }
878 if !full && run >= 0 {
879 sb += "M" + num(run*cC) + " " + num(j*cC) + "h" + num((i-run)*cC) + "v20h" + num((run-i)*cC)
880 run = -1
881 }
882 if i < cG && !full && (c0 || c1 || c2 || c3) {
883 cellPoly(&sb, xs[:], ys[:], e[r0+i], e[r0+i+1], e[r1+i+1], e[r1+i], T, above, i, j, c0, c1, c2, c3)
884 }
885 }
886 }
887 return sb
888}
889
890// regions is region for several levels of one field in one pass: the first
891// level is a "below" area (e < T), the others "above" (e >= T).
892func regions(e []int, ts []int) []string {
893 nt := len(ts)
894 sbs := make([]string, nt)
895 runs := make([]int, nt)
896 var xs, ys [6]int
897 for j := 0; j < cG; j++ {
898 for q := range runs {
899 runs[q] = -1
900 }
901 r0 := (j+1)*span + 1
902 r1 := r0 + span
903 for i := 0; i <= cG; i++ {
904 var v0, v1, v2, v3, lo, hi int
905 if i < cG {
906 v0, v1, v2, v3 = e[r0+i], e[r0+i+1], e[r1+i+1], e[r1+i]
907 lo, hi = v0, v0
908 if v1 < lo {
909 lo = v1
910 } else if v1 > hi {
911 hi = v1
912 }
913 if v2 < lo {
914 lo = v2
915 } else if v2 > hi {
916 hi = v2
917 }
918 if v3 < lo {
919 lo = v3
920 } else if v3 > hi {
921 hi = v3
922 }
923 }
924 for q := 0; q < nt; q++ {
925 T := ts[q]
926 above := q > 0
927 full, empty := false, true
928 if i < cG {
929 if above {
930 full, empty = lo >= T, hi < T
931 } else {
932 full, empty = hi < T, lo >= T
933 }
934 }
935 if full && runs[q] < 0 {
936 runs[q] = i
937 }
938 if !full && runs[q] >= 0 {
939 run := runs[q]
940 sbs[q] += "M" + num(run*cC) + " " + num(j*cC) + "h" + num((i-run)*cC) + "v20h" + num((run-i)*cC)
941 runs[q] = -1
942 }
943 if i < cG && !full && !empty {
944 cellPoly(&sbs[q], xs[:], ys[:], v0, v1, v2, v3, T, above, i, j,
945 (v0 >= T) == above, (v1 >= T) == above, (v2 >= T) == above, (v3 >= T) == above)
946 }
947 }
948 }
949 }
950 return sbs
951}
952
953// cellPoly writes the inside part of one partial cell with corner values
954// v0..v3 (clockwise from top-left).
955func cellPoly(sb *string, xs, ys []int, v0, v1, v2, v3, T int, above bool, i, j int, c0, c1, c2, c3 bool) {
956 x, y := i*cC, j*cC
957 // edge crossings X0..X3 (top, right, bottom, left), only where the
958 // inside test changes along the edge
959 x0, y1, x2, y3 := x, y, x, y
960 if c0 != c1 {
961 x0 += edgeCut(v0, v1, T)
962 }
963 if c1 != c2 {
964 y1 += edgeCut(v1, v2, T)
965 }
966 if c3 != c2 {
967 x2 += edgeCut(v3, v2, T)
968 }
969 if c0 != c3 {
970 y3 += edgeCut(v0, v3, T)
971 }
972 if (c0 && c2 && !c1 && !c3) || (c1 && c3 && !c0 && !c2) {
973 sum := v0 + v1 + v2 + v3
974 if (sum >= 4*T) != above {
975 // saddle with the centre outside: two corner triangles
976 if c0 {
977 xs[0], ys[0], xs[1], ys[1], xs[2], ys[2] = x, y, x0, y, x, y3
978 relPath(sb, xs, ys, 3)
979 xs[0], ys[0], xs[1], ys[1], xs[2], ys[2] = x+cC, y1, x+cC, y+cC, x2, y+cC
980 relPath(sb, xs, ys, 3)
981 return
982 }
983 xs[0], ys[0], xs[1], ys[1], xs[2], ys[2] = x0, y, x+cC, y, x+cC, y1
984 relPath(sb, xs, ys, 3)
985 xs[0], ys[0], xs[1], ys[1], xs[2], ys[2] = x2, y+cC, x, y+cC, x, y3
986 relPath(sb, xs, ys, 3)
987 return
988 }
989 }
990 n := 0
991 if c0 {
992 xs[n], ys[n] = x, y
993 n++
994 }
995 if c0 != c1 {
996 xs[n], ys[n] = x0, y
997 n++
998 }
999 if c1 {
1000 xs[n], ys[n] = x+cC, y
1001 n++
1002 }
1003 if c1 != c2 {
1004 xs[n], ys[n] = x+cC, y1
1005 n++
1006 }
1007 if c2 {
1008 xs[n], ys[n] = x+cC, y+cC
1009 n++
1010 }
1011 if c2 != c3 {
1012 xs[n], ys[n] = x2, y+cC
1013 n++
1014 }
1015 if c3 {
1016 xs[n], ys[n] = x, y+cC
1017 n++
1018 }
1019 if c3 != c0 {
1020 xs[n], ys[n] = x, y3
1021 n++
1022 }
1023 if n >= 3 {
1024 relPath(sb, xs, ys, n)
1025 }
1026}
1027
1028// Contour levels: L = lvMin + lvStep*k, k < lvN (-1500 .. 2900 m).
1029const (
1030 lvMin = -1500
1031 lvStep = 100
1032 lvN = 45
1033)
1034
1035// isoLines are the chained iso-lines of every drawn level over the sheet and
1036// its one-cell margin (so strokes that cross an edge are drawn identically by
1037// both sheets): coast (0 m), bathymetry (every 300 m below 0), minor and
1038// index (every 500 m) contours. One pass over the cells collects the
1039// segments of every level a cell spans, in row-major order per level.
1040func isoLines(e []int) (coast, bathy, minor, major string) {
1041 type segs struct{ a, b, ax, ay, bx, by []int }
1042 lv := make([]*segs, lvN)
1043 for lj := 0; lj < span-1; lj++ {
1044 for li := 0; li < span-1; li++ {
1045 k := lj*span + li
1046 v0, v1, v2, v3 := e[k], e[k+1], e[k+span+1], e[k+span]
1047 lo, hi := v0, v0
1048 if v1 < lo {
1049 lo = v1
1050 } else if v1 > hi {
1051 hi = v1
1052 }
1053 if v2 < lo {
1054 lo = v2
1055 } else if v2 > hi {
1056 hi = v2
1057 }
1058 if v3 < lo {
1059 lo = v3
1060 } else if v3 > hi {
1061 hi = v3
1062 }
1063 if hi < lvMin {
1064 continue
1065 }
1066 // levels L with lo < L <= hi
1067 k0 := lo + 1 - lvMin
1068 if k0 <= 0 {
1069 k0 = 0
1070 } else {
1071 k0 = (k0 + lvStep - 1) / lvStep
1072 }
1073 k1 := (hi - lvMin) / lvStep
1074 if k1 > lvN-1 {
1075 k1 = lvN - 1
1076 }
1077 x, y := (li-1)*cC, (lj-1)*cC
1078 id0 := lj*(span-1) + li
1079 id1 := hn + lj*span + li + 1
1080 id2 := (lj+1)*(span-1) + li
1081 id3 := hn + lj*span + li
1082 for q := k0; q <= k1; q++ {
1083 T := lvMin + q*lvStep
1084 if T < 0 && T%300 != 0 {
1085 continue
1086 }
1087 c0, c1, c2, c3 := v0 >= T, v1 >= T, v2 >= T, v3 >= T
1088 var ids, xs, ys [4]int
1089 n := 0
1090 if c0 != c1 {
1091 ids[n], xs[n], ys[n] = id0, x+edgeCut(v0, v1, T), y
1092 n++
1093 }
1094 if c1 != c2 {
1095 ids[n], xs[n], ys[n] = id1, x+cC, y+edgeCut(v1, v2, T)
1096 n++
1097 }
1098 if c2 != c3 {
1099 ids[n], xs[n], ys[n] = id2, x+edgeCut(v3, v2, T), y+cC
1100 n++
1101 }
1102 if c3 != c0 {
1103 ids[n], xs[n], ys[n] = id3, x, y+edgeCut(v0, v3, T)
1104 n++
1105 }
1106 sg := lv[q]
1107 if sg == nil {
1108 sg = &segs{}
1109 lv[q] = sg
1110 }
1111 if n == 2 {
1112 sg.a, sg.ax, sg.ay = append(sg.a, ids[0]), append(sg.ax, xs[0]), append(sg.ay, ys[0])
1113 sg.b, sg.bx, sg.by = append(sg.b, ids[1]), append(sg.bx, xs[1]), append(sg.by, ys[1])
1114 continue
1115 }
1116 // saddle: the centre decides which corners are joined (as region)
1117 if c0 == (v0+v1+v2+v3 >= 4*T) {
1118 // (top, right) and (bottom, left)
1119 sg.a, sg.ax, sg.ay = append(sg.a, ids[0], ids[2]), append(sg.ax, xs[0], xs[2]), append(sg.ay, ys[0], ys[2])
1120 sg.b, sg.bx, sg.by = append(sg.b, ids[1], ids[3]), append(sg.bx, xs[1], xs[3]), append(sg.by, ys[1], ys[3])
1121 } else {
1122 // (left, top) and (right, bottom)
1123 sg.a, sg.ax, sg.ay = append(sg.a, ids[3], ids[1]), append(sg.ax, xs[3], xs[1]), append(sg.ay, ys[3], ys[1])
1124 sg.b, sg.bx, sg.by = append(sg.b, ids[0], ids[2]), append(sg.bx, xs[0], xs[2]), append(sg.by, ys[0], ys[2])
1125 }
1126 }
1127 }
1128 }
1129 ex := make([]int, 2*hn)
1130 ey := make([]int, 2*hn)
1131 adj1 := make([]int, 2*hn)
1132 adj2 := make([]int, 2*hn)
1133 for k := range adj1 {
1134 adj1[k], adj2[k] = -1, -1
1135 }
1136 var cb, bb, nb, jb string
1137 for q := 0; q < lvN; q++ {
1138 sg := lv[q]
1139 if sg == nil {
1140 continue
1141 }
1142 T := lvMin + q*lvStep
1143 out := &nb
1144 switch {
1145 case T == 0:
1146 out = &cb
1147 case T < 0:
1148 out = &bb
1149 case T%500 == 0:
1150 out = &jb
1151 }
1152 chain(out, sg.a, sg.b, sg.ax, sg.ay, sg.bx, sg.by, ex, ey, adj1, adj2)
1153 }
1154 return cb, bb, nb, jb
1155}
1156
1157// chain joins one level's segments (edge ids a[s]-b[s]) into polylines.
1158func chain(sb *string, a, b, ax, ay, bx, by, ex, ey, adj1, adj2 []int) {
1159 ns := len(a)
1160 for s := 0; s < ns; s++ {
1161 ex[a[s]], ey[a[s]] = ax[s], ay[s]
1162 ex[b[s]], ey[b[s]] = bx[s], by[s]
1163 for _, id := range [2]int{a[s], b[s]} {
1164 if adj1[id] == -1 {
1165 adj1[id] = s
1166 } else {
1167 adj2[id] = s
1168 }
1169 }
1170 }
1171 used := make([]bool, ns)
1172 next := func(id int) int {
1173 if t := adj1[id]; t >= 0 && !used[t] {
1174 return t
1175 }
1176 if t := adj2[id]; t >= 0 && !used[t] {
1177 return t
1178 }
1179 return -1
1180 }
1181 xs := make([]int, 0, 64)
1182 ys := make([]int, 0, 64)
1183 fwd := make([]int, 0, 64)
1184 back := make([]int, 0, 64)
1185 walk := func(cur int, list []int) []int {
1186 for {
1187 t := next(cur)
1188 if t < 0 {
1189 return list
1190 }
1191 used[t] = true
1192 if a[t] == cur {
1193 cur = b[t]
1194 } else {
1195 cur = a[t]
1196 }
1197 list = append(list, cur)
1198 }
1199 }
1200 for s := 0; s < ns; s++ {
1201 if used[s] {
1202 continue
1203 }
1204 used[s] = true
1205 // forward from b first (a closed ring is taken whole here), then back
1206 fwd = walk(b[s], append(fwd[:0], a[s], b[s]))
1207 back = walk(a[s], back[:0])
1208 xs, ys = xs[:0], ys[:0]
1209 for k := len(back) - 1; k >= 0; k-- {
1210 xs = append(xs, ex[back[k]])
1211 ys = append(ys, ey[back[k]])
1212 }
1213 for _, id := range fwd {
1214 xs = append(xs, ex[id])
1215 ys = append(ys, ey[id])
1216 }
1217 relPath(sb, xs, ys, len(xs))
1218 }
1219 for s := 0; s < ns; s++ {
1220 adj1[a[s]], adj2[a[s]] = -1, -1
1221 adj1[b[s]], adj2[b[s]] = -1, -1
1222 }
1223}
1224
1225// ---------------------------------------------------------------------------
1226// Rendering
1227// ---------------------------------------------------------------------------
1228
1229func nameOf(a, b int) string { return nameA[a][0] + nameB[b][0] }
1230
1231// gridNo is the grid number of line k (0..4) of sheet column or row c.
1232func gridNo(c, k int) string { return num(10 + c*4 + k) }
1233
1234func neighbour(sx, sy int) string {
1235 if sx < 0 || sy < 0 || sx >= Side || sy >= Side {
1236 return "—"
1237 }
1238 return SheetCode(sy*Side + sx)
1239}
1240
1241// SheetSVG is the full sheet of token seed at place p.
1242func SheetSVG(seed string, cfg Config, p Place) string {
1243 return sheetSVG(seed, cfg, p, nil)
1244}
1245
1246// sheetSVG draws the sheet; mask is the map's landMask when the caller
1247// already has it (nil: computed here).
1248func sheetSVG(seed string, cfg Config, p Place, mask []bool) string {
1249 n := num
1250 s := survey(seed, cfg, p)
1251 mi := s.mi
1252 P := palettes[mi.palette]
1253 e := s.e
1254 R := newRNG(seed + "|art") // separate stream: art draws never shift the traits
1255 na := R.intn(len(nameA))
1256 nb := R.intn(len(nameB))
1257
1258 // --- map layers
1259 emin, emax := 1<<30, -(1 << 30)
1260 for _, v := range e {
1261 if v < emin {
1262 emin = v
1263 }
1264 if v > emax {
1265 emax = v
1266 }
1267 }
1268 bands := regions(e, []int{-300, 0, 500, 1000, 1500})
1269 deep, land, t1, t2, t3 := bands[0], bands[1], bands[2], bands[3], bands[4]
1270 coast, bathyS, minorS, majorS := isoLines(e)
1271 forest := ""
1272 if emax >= 40 {
1273 forest = region(woodland(mi, s.sx, s.sy, e), 0, true)
1274 }
1275
1276 sb := ""
1277 sb += (`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 560 660">`)
1278 sb += (`<defs><clipPath id="mc"><rect width="480" height="480"/></clipPath>` +
1279 `<filter id="pg" x="0" y="0" width="1" height="1"><feTurbulence type="fractalNoise" baseFrequency=".8" numOctaves="2" seed="` +
1280 n(s.tile+1) + `"/><feColorMatrix values="0 0 0 0 .35 0 0 0 0 .28 0 0 0 0 .2 0 0 0 -1.6 .78"/></filter>`)
1281 if t3 != "" {
1282 sb += (`<pattern id="ph" width="8" height="8" patternUnits="userSpaceOnUse"><path d="M-2 2l4-4M0 8l8-8M6 10l4-4" stroke="` +
1283 P.hatch + `" stroke-width=".8"/></pattern><path id="hi" d="` + t3 + `"/>`)
1284 }
1285 if forest != "" {
1286 sb += (`<pattern id="pf" width="12" height="12" patternUnits="userSpaceOnUse"><rect width="12" height="12" fill="` +
1287 P.forest + `"/><path d="M3 2.4a1.8 1.8 0 1 0 .1 0M9 8.4a1.8 1.8 0 1 0 .1 0" fill="` + P.tree + `"/></pattern>`)
1288 }
1289 if coast != "" {
1290 sb += (`<path id="k" d="` + coast + `"/>`)
1291 }
1292 sb += (`</defs>`)
1293 sb += (`<rect width="560" height="660" fill="` + P.paper + `"/><rect width="560" height="660" filter="url(#pg)"/>` +
1294 `<g transform="translate(40 96)" clip-path="url(#mc)">`)
1295
1296 // map face
1297 sb += (`<rect width="480" height="480" fill="` + P.sea + `"/>`)
1298 if deep != "" {
1299 sb += (`<path d="` + deep + `" fill="` + P.deep + `"/>`)
1300 }
1301 if coast != "" {
1302 sb += (`<use href="#k" fill="none" stroke="` + P.wl + `" stroke-width="13"/>` +
1303 `<use href="#k" fill="none" stroke="` + P.sea + `" stroke-width="10"/>` +
1304 `<use href="#k" fill="none" stroke="` + P.wl + `" stroke-width="6"/>`)
1305 }
1306 if land != "" {
1307 sb += (`<path d="` + land + `" fill="` + P.t0 + `"/>`)
1308 }
1309 if forest != "" {
1310 sb += (`<path d="` + forest + `" fill="url(#pf)"/>`)
1311 }
1312 if t1 != "" {
1313 sb += (`<path d="` + t1 + `" fill="` + P.t1 + `"/>`)
1314 }
1315 if t2 != "" {
1316 sb += (`<path d="` + t2 + `" fill="` + P.t2 + `"/>`)
1317 }
1318 if t3 != "" {
1319 sb += (`<use href="#hi" fill="` + P.t3 + `"/><use href="#hi" fill="url(#ph)"/>`)
1320 }
1321 if emax >= 0 {
1322 dark := region(hillShade(e), 0, true)
1323 if dark != "" {
1324 sb += (`<path d="` + dark + `" fill="` + P.ink + `" fill-opacity=".11"/>`)
1325 }
1326 }
1327 if bathyS != "" {
1328 sb += (`<path d="` + bathyS + `" fill="none" stroke="` + P.bathy + `" stroke-width=".7"/>`)
1329 }
1330 if minorS != "" {
1331 sb += (`<path d="` + minorS + `" fill="none" stroke="` + P.contour + `" stroke-width=".6"/>`)
1332 }
1333 if majorS != "" {
1334 sb += (`<path d="` + majorS + `" fill="none" stroke="` + P.index + `" stroke-width="1.3"/>`)
1335 }
1336 if coast != "" {
1337 sb += (`<use href="#k" fill="none" stroke="` + P.coast + `" stroke-width="1.6"/>`)
1338 }
1339 sb += (`<path d="M120 0V480M240 0V480M360 0V480M0 120H480M0 240H480M0 360H480" stroke="` + P.grid +
1340 `" stroke-opacity=".22" stroke-width=".7"/>`)
1341
1342 // soundings: a global choice, so they never depend on the token
1343 snd := ""
1344 for j := 2; j <= cG-2; j++ {
1345 for i := 2; i <= cG-2; i++ {
1346 v := e[at(i, j)]
1347 if v < -80 && hash32(mi.sh, 9, s.sx*cG+i+off, s.sy*cG+j+off)%29 == 0 {
1348 snd += (`<text x="` + n(i*cC) + `" y="` + n(j*cC+3) + `">` + n(-v) + `</text>`)
1349 }
1350 }
1351 }
1352 if snd != "" {
1353 sb += (`<g font-family="Georgia, serif" font-size="8" font-style="italic" text-anchor="middle" fill="` + P.bathy + `">` +
1354 snd + `</g>`)
1355 }
1356
1357 // token marks
1358 marks := ""
1359 if s.peak >= 0 {
1360 x, y := (s.peak%span-1)*cC, (s.peak/span-1)*cC
1361 marks += `<path d="M` + n(x) + " " + n(y-6) + `l6 10h-12z" fill="` + P.ink + `"/><text x="` + n(x+9) + `" y="` + n(y+4) +
1362 `" font-size="10">` + n(e[s.peak]) + `</text>`
1363 }
1364 sheetName := ""
1365 if s.settle >= 0 {
1366 i, j := s.settle%span-1, s.settle/span-1
1367 x, y := i*cC, j*cC
1368 sheetName = nameOf(na, nb)
1369 cnt := 2
1370 switch s.settleKind {
1371 case "Village":
1372 cnt = 4
1373 case "Port":
1374 cnt = 5
1375 case "Town":
1376 cnt = 7
1377 }
1378 blocks := ""
1379 for k := 0; k < cnt; k++ {
1380 bx := x + R.between(-9, 5)
1381 by := y + R.between(-8, 4)
1382 w := R.between(3, 6)
1383 blocks += "M" + n(bx) + " " + n(by) + "h" + n(w) + "v" + n(w) + "h" + n(-w)
1384 }
1385 if s.settleKind == "Port" {
1386 // pier towards the first neighbouring sea point (E, S, W, N)
1387 dx, dy := 0, -1
1388 if e[at(i+1, j)] < 0 {
1389 dx, dy = 1, 0
1390 } else if e[at(i, j+1)] < 0 {
1391 dy = 1
1392 } else if e[at(i-1, j)] < 0 {
1393 dx, dy = -1, 0
1394 }
1395 marks += `<path d="M` + n(x) + " " + n(y) + "l" + n(dx*16) + " " + n(dy*16) + "m" + n(dy*5) + " " + n(dx*5) + "l" +
1396 n(-dy*10) + " " + n(-dx*10) + `" fill="none" stroke="` + P.ink + `" stroke-width="1.6"/>`
1397 }
1398 if s.settleKind == "Town" {
1399 marks += `<circle cx="` + n(x) + `" cy="` + n(y) + `" r="15" fill="none" stroke="` + P.red +
1400 `" stroke-width=".8" stroke-dasharray="2 2"/>`
1401 }
1402 marks += `<path d="` + blocks + `" fill="` + P.red + `"/>`
1403 if x <= 330 {
1404 marks += `<text x="` + n(x+13) + `" y="` + n(y+4) + `" font-size="12" font-style="italic">` + sheetName + `</text>`
1405 } else {
1406 marks += `<text x="` + n(x-13) + `" y="` + n(y+4) + `" font-size="12" font-style="italic" text-anchor="end">` + sheetName + `</text>`
1407 }
1408 } else if s.terrain == "Open Sea" {
1409 sheetName = nameA[na][0] + " Denizi"
1410 } else {
1411 sheetName = nameOf(na, nb) + " Dağları"
1412 }
1413 if s.markAt >= 0 {
1414 x, y := (s.markAt%span-1)*cC, (s.markAt/span-1)*cC
1415 switch s.mark {
1416 case lmLighthouse:
1417 marks += `<path d="M` + n(x) + " " + n(y-15) + "v30M" + n(x-15) + " " + n(y) + "h30M" + n(x-10) + " " + n(y-10) + "l20 20M" +
1418 n(x+10) + " " + n(y-10) + `l-20 20" stroke="` + P.red + `" stroke-opacity=".7"/><circle cx="` + n(x) + `" cy="` + n(y) +
1419 `" r="4" fill="` + P.red + `" stroke="` + P.paper + `"/>`
1420 case lmWreck:
1421 marks += `<path d="M` + n(x-12) + " " + n(y) + "h24M" + n(x) + " " + n(y-8) + "v16M" + n(x-6) + " " + n(y-5) + "v10M" +
1422 n(x+6) + " " + n(y-5) + `v10" stroke="` + P.ink + `" stroke-width="1.6"/>`
1423 case lmCastle:
1424 marks += `<path d="M` + n(x-9) + " " + n(y+7) + `v-12h4v4h3v-4h4v4h3v-4h4v12z" fill="` + P.ink + `"/>`
1425 case lmRuins:
1426 marks += `<path d="M` + n(x-7) + " " + n(y+6) + "h14M" + n(x-5) + " " + n(y+6) + "v-9M" + n(x) + " " + n(y+6) + "v-12M" +
1427 n(x+5) + " " + n(y+6) + `v-6" stroke="` + P.ink + `" stroke-width="1.4" stroke-dasharray="3 1"/>`
1428 case lmWindmill:
1429 marks += `<path d="M` + n(x-7) + " " + n(y-7) + "l14 14M" + n(x+7) + " " + n(y-7) + `l-14 14" stroke="` + P.ink +
1430 `" stroke-width="1.4"/><circle cx="` + n(x) + `" cy="` + n(y) + `" r="2.6" fill="` + P.paper + `" stroke="` + P.ink + `"/>`
1431 default:
1432 if s.settle >= 0 {
1433 marks += `<path d="M` + n((s.settle%span-1)*cC) + " " + n((s.settle/span-1)*cC) + "L" + n(x) + " " + n(y) +
1434 `" fill="none" stroke="` + P.red + `" stroke-width="1.2" stroke-dasharray="4 4"/>`
1435 }
1436 marks += `<path d="M` + n(x-7) + " " + n(y-7) + "l14 14M" + n(x+7) + " " + n(y-7) + `l-14 14" stroke="` + P.red +
1437 `" stroke-width="3" stroke-linecap="round"/>`
1438 }
1439 }
1440 if s.terrain == "Open Sea" && R.intn(3) == 0 {
1441 // a compass rose on some of the empty water
1442 x := R.between(6, 18) * cC
1443 y := R.between(6, 18) * cC
1444 marks += `<g transform="translate(` + n(x) + " " + n(y) + `)" fill="` + P.ink2 + `" fill-opacity=".45"><circle r="22" fill="none" stroke="` +
1445 P.ink2 + `" stroke-opacity=".6"/><path d="M0-34l3 27 11-21-7 18 27 10-27 3 21 11-18-7-10 27-3-27-11 21 7-18-27-10 27-3-21-11 18 7z"/></g>`
1446 }
1447 if marks != "" {
1448 sb += (`<g font-family="Georgia, serif" fill="` + P.ink + `">` + marks + `</g>`)
1449 }
1450 sb += (`</g>`)
1451
1452 // --- the sheet: neatline and the alternating kilometre border
1453 sb += (`<path d="M40 92.5h120m120 0h120M523.5 96v120m0 120v120M40 579.5h120m120 0h120M36.5 96v120m0 120v120" stroke="` + P.ink +
1454 `" stroke-width="5"/><rect x="33.5" y="89.5" width="493" height="493" fill="none" stroke="` + P.ink + `" stroke-width=".8"/>` +
1455 `<rect x="39.5" y="95.5" width="481" height="481" fill="none" stroke="` + P.ink + `" stroke-width=".8"/>`)
1456 sx, sy := s.sx, s.sy
1457 gridNos := ""
1458 for k := 0; k <= 4; k++ {
1459 if k == 2 {
1460 continue
1461 }
1462 q := k * 120
1463 gridNos += `<text x="` + n(MapX+q) + `" y="` + n(MapY-10) + `">` + gridNo(sx, k) + `</text>` +
1464 `<text x="` + n(MapX+q) + `" y="` + n(MapY+cM+17) + `">` + gridNo(sx, k) + `</text>` +
1465 `<text x="` + n(MapX-10) + `" y="` + n(MapY+q+3) + `" text-anchor="end">` + gridNo(Side-1-sy, 4-k) + `</text>` +
1466 `<text x="` + n(MapX+cM+10) + `" y="` + n(MapY+q+3) + `" text-anchor="start">` + gridNo(Side-1-sy, 4-k) + `</text>`
1467 }
1468 sb += (`<g font-family="Georgia, serif" fill="` + P.ink + `">` +
1469 `<text x="40" y="42" font-size="19" letter-spacing="3">` + nameA[mi.nameA][1] + nameB[mi.nameB][1] + `</text>` +
1470 `<text x="40" y="64" font-size="12" fill="` + P.ink2 + `">` + sheetName + ` · 1:25.000</text>` +
1471 `<text x="444" y="66" font-size="28" text-anchor="end">` + SheetCode(s.tile) + `</text>` +
1472 `<g font-size="10" text-anchor="middle"><text x="280" y="` + n(MapY-10) + `">` + neighbour(sx, sy-1) + `</text>` +
1473 `<text x="280" y="` + n(MapY+cM+17) + `">` + neighbour(sx, sy+1) + `</text>` +
1474 `<text x="` + n(MapX-17) + `" y="` + n(MapY+243) + `">` + neighbour(sx-1, sy) + `</text>` +
1475 `<text x="` + n(MapX+cM+17) + `" y="` + n(MapY+243) + `">` + neighbour(sx+1, sy) + `</text></g>` +
1476 `<g font-size="8" fill="` + P.ink2 + `" text-anchor="middle">` + gridNos + `</g>`)
1477 // legend: hypsometric steps, contour interval, scale and north
1478 sb += (`<g transform="translate(40 604)"><rect width="22" height="8" fill="` + P.deep + `"/><rect x="22" width="22" height="8" fill="` +
1479 P.sea + `"/><rect x="44" width="22" height="8" fill="` + P.t0 + `"/><rect x="66" width="22" height="8" fill="` + P.t1 +
1480 `"/><rect x="88" width="22" height="8" fill="` + P.t2 + `"/><rect x="110" width="22" height="8" fill="` + P.t3 +
1481 `"/><rect width="132" height="8" fill="none" stroke="` + P.ink + `" stroke-width=".6"/>` +
1482 `<g font-size="7" text-anchor="middle" fill="` + P.ink2 + `"><text x="22" y="18">-300</text><text x="44" y="18">0</text>` +
1483 `<text x="66" y="18">500</text><text x="88" y="18">1000</text><text x="110" y="18">1500 m</text></g>` +
1484 `<text y="38" font-size="9" fill="` + P.ink2 + `">Eş yükselti aralığı 100 m · kalın eğri 500 m</text></g>` +
1485 `<g transform="translate(400 604)"><path d="M0 0h30v6h-30zM60 0h30v6h-30z" fill="` + P.ink + `"/><rect width="120" height="6" fill="none" stroke="` +
1486 P.ink + `" stroke-width=".8"/><g font-size="8" text-anchor="middle"><text y="18">0</text><text x="60" y="18">500</text>` +
1487 `<text x="120" y="18">1 km</text></g></g>` +
1488 `<g transform="translate(330 620)"><path d="M0-18l7 20-7-6-7 6z"/><text y="14" font-size="10" text-anchor="middle">K</text></g></g>`)
1489
1490 // index map: the whole collection, one sample per sheet, this sheet in red
1491 if mask == nil {
1492 mask = landMask(mi)
1493 }
1494 md := ""
1495 for b := 0; b < Side; b++ {
1496 run := -1
1497 for a := 0; a <= Side; a++ {
1498 ld := a < Side && mask[b*Side+a]
1499 if ld && run < 0 {
1500 run = a
1501 }
1502 if !ld && run >= 0 {
1503 md += ("M" + n(run*4) + " " + n(b*4) + "h" + n((a-run)*4) + "v4h" + n((run-a)*4))
1504 run = -1
1505 }
1506 }
1507 }
1508 sb += (`<g transform="translate(456 14)"><rect width="64" height="64" fill="` + P.sea + `"/>`)
1509 if md != "" {
1510 sb += (`<path d="` + md + `" fill="` + P.t1 + `"/>`)
1511 }
1512 sb += (`<rect x="` + n(sx*4) + `" y="` + n(sy*4) + `" width="4" height="4" fill="` + P.red +
1513 `"/><rect width="64" height="64" fill="none" stroke="` + P.ink + `" stroke-width=".8"/></g>`)
1514 sb += (`</svg>`)
1515 return sb
1516}