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.

katman.gno

13.79 Kb · 450 lines
  1// Package katman is the composition logic of Katman, Sinopia's open PFP
  2// tool engine: an artist uploads trait layers (SVG parts with rarity
  3// weights) to a sealed assets/v1 store, and every revealed token is one part
  4// per layer, drawn from the token's final seed by weight and stacked
  5// bottom-up into one SVG. Parts may paint with currentColor; the
  6// collection's palette then gives every layer its own ink, shuffled per
  7// token, over a paper backdrop.
  8//
  9// This package is pure: it never reads a store. The adapter realm
 10// (r/…/sinopia/engines/katman) reads the drawn parts from assets/v1 and
 11// hands their bytes to ComposeParts. The demo kit in demo.gno (params store
 12// 0) is the engine's own sample: the jug characters of the engine gallery,
 13// redrawn. frontend/src/engines/katman.ts is a byte-identical TypeScript
 14// twin; katman_test.gno and katman.test.ts pin the same golden vectors.
 15//
 16// Why composition can never break the SVG allowlist: every part is a whole
 17// document that passed safe.AssertSVG when its last byte was stored
 18// (assets/v1 AppendBytes → media.CheckImage). Its root tag is exactly
 19// Root(w, h) and the document ends with the closing tag of that root
 20// (AssertSVG refuses content after the root), so the bytes between them are
 21// a balanced run of allowlisted elements, attributes and text. ComposeParts
 22// only concatenates such runs inside <g> elements under one Root(w, h); every
 23// rule of the allowlist is local to an element, an attribute value or a text
 24// run, so the result passes too. Core re-checks every render anyway.
 25//
 26// Pure integer maths: no floats, no time, no block data.
 27package katman
 28
 29import (
 30	"errors"
 31	"strconv"
 32	"strings"
 33
 34	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/engine/v2"
 35)
 36
 37// Kit limits (the adapter enforces them on a store at CreateCollection).
 38const (
 39	MaxLayers        = 8      // = assets/v1 MaxTraitTypes = MaxTiers; trait types
 40	MaxPartsPerLayer = 64     // parts of one layer
 41	MaxParts         = 128    // parts of a kit
 42	MaxKitBytes      = 262144 // on-chain bytes of a kit (sum of part files)
 43	MaxSVGBytes      = 28672  // worst composed token (Manifest.MaxSVGBytes)
 44	MaxCanvas        = 4096   // viewBox width and height, 1..MaxCanvas
 45	MaxStore         = 999999999
 46	DemoCanvas       = 400
 47)
 48
 49// ParamsSchema is the Studio form. Studio sends JSON.stringify of the values
 50// in this property order; ValidateParams accepts exactly that or "".
 51const ParamsSchema = `{"type":"object","properties":{` +
 52	`"store":{"type":"integer","title":"Part store (0 = demo kit)","minimum":0,"maximum":999999999,"default":0},` +
 53	`"palette":{"type":"string","title":"Palette","enum":["Terracotta","Riso","Iznik","Sea Glass","Dusk",` +
 54	`"Sinopia","Mono","Kit Colours"],"default":"Terracotta"}}}`
 55
 56// DefaultParams is the canonical form of the defaults; it renders exactly
 57// like "".
 58const DefaultParams = `{"store":0,"palette":"Terracotta"}`
 59
 60// PaletteKit is the index of "Kit Colours": no paper, no layer inks.
 61const PaletteKit = 7
 62
 63type part struct {
 64	name   string
 65	weight int64
 66	inner  string
 67}
 68
 69type layer struct {
 70	name  string
 71	parts []part
 72}
 73
 74type palette struct {
 75	name, paper string
 76	inks        []string
 77}
 78
 79// Manifest describes the engine. Author and FeeBps are set by the adapter.
 80func Manifest() engine.Manifest {
 81	return engine.Manifest{
 82		Name:    "Katman",
 83		Version: "1.0.0",
 84		Description: "Open PFP tool: artists upload their own trait layers (SVG parts with rarity weights) to a " +
 85			"sealed asset store; at reveal the chain draws one part per layer from each token's seed and stacks " +
 86			"them. A palette can ink every layer per token. Params store 0 is the built-in demo kit.",
 87		License:      "CC-BY-NC-4.0",
 88		ParamsSchema: ParamsSchema,
 89		TraitTypes:   DemoLayerNames(),
 90		Living:       false,
 91		MaxSVGBytes:  MaxSVGBytes,
 92		Kind:         engine.KindSVG,
 93	}
 94}
 95
 96// DemoLayerNames are the demo kit's layers: its trait types.
 97func DemoLayerNames() []string {
 98	out := make([]string, len(demoLayers))
 99	for i, l := range demoLayers {
100		out[i] = l.name
101	}
102	return out
103}
104
105// Config is a parsed params string.
106type Config struct {
107	Store   int64 // assets/v1 store id; 0 = the demo kit
108	Palette int   // index into the palettes; PaletteKit = the kit's own colours
109}
110
111// Defaults is params "": the demo kit in Terracotta.
112func Defaults() Config { return Config{} }
113
114var errParams = errors.New(`katman: params must be "" or {"store":<0..999999999>,"palette":<enum>} without spaces`)
115
116// ParseParams accepts "" or the canonical JSON Studio produces, nothing else.
117func ParseParams(params string) (Config, error) {
118	cfg := Defaults()
119	if params == "" {
120		return cfg, nil
121	}
122	const pre, mid, post = `{"store":`, `,"palette":"`, `"}`
123	if !strings.HasPrefix(params, pre) || !strings.HasSuffix(params, post) {
124		return cfg, errParams
125	}
126	rest := params[len(pre) : len(params)-len(post)]
127	k := strings.Index(rest, mid)
128	if k < 1 || k > 9 {
129		return cfg, errParams
130	}
131	digits, name := rest[:k], rest[k+len(mid):]
132	if len(digits) > 1 && digits[0] == '0' {
133		return cfg, errParams
134	}
135	var n int64
136	for i := 0; i < len(digits); i++ {
137		c := digits[i]
138		if c < '0' || c > '9' {
139			return cfg, errParams
140		}
141		n = n*10 + int64(c-'0')
142	}
143	cfg.Store = n
144	for i, p := range palettes {
145		if p.name == name {
146			cfg.Palette = i
147			return cfg, nil
148		}
149	}
150	return cfg, errParams
151}
152
153// ValidateParams accepts "" (the demo kit) and the canonical JSON. Whether a
154// store kit is usable is the adapter's call (it reads the store).
155func ValidateParams(params string) error {
156	_, err := ParseParams(params)
157	return err
158}
159
160// MustConfig is ParseParams for params core already validated.
161func MustConfig(params string) Config {
162	cfg, err := ParseParams(params)
163	if err != nil {
164		panic(err)
165	}
166	return cfg
167}
168
169// PaletteName is the palette's enum value.
170func PaletteName(i int) string { return palettes[i].name }
171
172// ---------------------------------------------------------------------------
173// Deterministic randomness: FNV-1a over the seed, then splitmix64 (the stream
174// of every Sinopia engine). Parts use seed+"|katman|parts", inks
175// seed+"|katman|inks", so a palette never moves a token's parts.
176// ---------------------------------------------------------------------------
177
178type rng struct{ state uint64 }
179
180func newRNG(seed string) *rng {
181	h := uint64(14695981039346656037)
182	for i := 0; i < len(seed); i++ {
183		h ^= uint64(seed[i])
184		h *= 1099511628211
185	}
186	if h == 0 {
187		h = 1099511628211
188	}
189	return &rng{state: h}
190}
191
192func (r *rng) next() uint64 {
193	r.state += 0x9E3779B97F4A7C15
194	z := r.state
195	z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9
196	z = (z ^ (z >> 27)) * 0x94D049BB133111EB
197	return z ^ (z >> 31)
198}
199
200func (r *rng) intn(n int) int {
201	if n <= 0 {
202		return 0
203	}
204	return int(r.next() % uint64(n))
205}
206
207// Draw returns, per layer, a point in 0..totals[k]-1: the token's position
208// on that layer's weight line (the sum of its parts' weights). Part i of a
209// layer covers [w_0+…+w_{i-1}, w_0+…+w_i): exactly the slot ranges assets/v1
210// gives editions, so the adapter maps the point to a part with
211// assets.SlotArtwork. One draw per layer, also for an empty layer (0).
212func Draw(seed string, totals []int64) []int64 {
213	r := newRNG(seed + "|katman|parts")
214	out := make([]int64, len(totals))
215	for k, t := range totals {
216		v := r.next()
217		if t > 0 {
218			out[k] = int64(v % uint64(t))
219		}
220	}
221	return out
222}
223
224// Pick maps Draw onto explicit weight lists: the index of the drawn part of
225// every layer (the walk the TS twin and the demo kit use).
226func Pick(seed string, weights [][]int64) []int {
227	totals := make([]int64, len(weights))
228	for k, ws := range weights {
229		for _, w := range ws {
230			totals[k] += w
231		}
232	}
233	at := Draw(seed, totals)
234	out := make([]int, len(weights))
235	for k, ws := range weights {
236		x := at[k]
237		out[k] = len(ws) - 1
238		for i, w := range ws {
239			if x < w {
240				out[k] = i
241				break
242			}
243			x -= w
244		}
245	}
246	return out
247}
248
249// Inks is the ink of each of n layers under palette pal for seed: the
250// palette's eight inks shuffled per token (Fisher-Yates), layer k taking the
251// (k mod 8)-th. nil for Kit Colours.
252func Inks(seed string, pal, n int) []string {
253	p := palettes[pal]
254	m := len(p.inks)
255	if m == 0 {
256		return nil
257	}
258	order := make([]int, m)
259	for i := range order {
260		order[i] = i
261	}
262	r := newRNG(seed + "|katman|inks")
263	for i := m - 1; i > 0; i-- {
264		j := r.intn(i + 1)
265		order[i], order[j] = order[j], order[i]
266	}
267	out := make([]string, n)
268	for k := range out {
269		out[k] = p.inks[order[k%m]]
270	}
271	return out
272}
273
274// ---------------------------------------------------------------------------
275// Parts and composition.
276// ---------------------------------------------------------------------------
277
278const rootPrefix = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 `
279
280// Root is the one root tag every part of a w x h kit starts with, and the
281// root of every composed token.
282func Root(w, h int) string {
283	return rootPrefix + strconv.Itoa(w) + " " + strconv.Itoa(h) + `">`
284}
285
286// ParseRoot reads a part's root tag: exactly Root(w, h) with canonical
287// decimals 1..MaxCanvas. ok is false for anything else.
288func ParseRoot(svg string) (root string, w, h int, ok bool) {
289	if !strings.HasPrefix(svg, rootPrefix) {
290		return "", 0, 0, false
291	}
292	i := len(rootPrefix)
293	w, i, ok = dim(svg, i, ' ')
294	if !ok {
295		return "", 0, 0, false
296	}
297	h, i, ok = dim(svg, i, '"')
298	if !ok || i >= len(svg) || svg[i] != '>' {
299		return "", 0, 0, false
300	}
301	return svg[:i+1], w, h, true
302}
303
304// dim parses a canonical decimal 1..MaxCanvas at s[i:] followed by end;
305// it returns the index after end.
306func dim(s string, i int, end byte) (int, int, bool) {
307	v, start := 0, i
308	for i < len(s) && i-start <= 4 && s[i] >= '0' && s[i] <= '9' {
309		v = v*10 + int(s[i]-'0')
310		i++
311	}
312	n := i - start
313	if n == 0 || n > 4 || s[start] == '0' || v > MaxCanvas || i >= len(s) || s[i] != end {
314		return 0, 0, false
315	}
316	return v, i + 1, true
317}
318
319// Inner is a part's content between its root tag and its final </svg>, or
320// ok false when the part does not start with root or end with </svg>.
321func Inner(svg, root string) (string, bool) {
322	if len(svg) < len(root)+6 || svg[:len(root)] != root || svg[len(svg)-6:] != "</svg>" {
323		return "", false
324	}
325	return svg[len(root) : len(svg)-6], true
326}
327
328// compose stacks the layers' inner SVG bottom-up: root, the palette's paper,
329// then one <g> per non-empty layer (with its ink when the palette has
330// inks), then </svg>.
331func compose(root string, w, h, pal int, inks []string, inners []string) string {
332	var b strings.Builder
333	b.WriteString(root)
334	if p := palettes[pal].paper; p != "" {
335		b.WriteString(`<rect width="` + strconv.Itoa(w) + `" height="` + strconv.Itoa(h) + `" fill="` + p + `"/>`)
336	}
337	for k, in := range inners {
338		if in == "" {
339			continue
340		}
341		if inks != nil {
342			b.WriteString(`<g color="` + inks[k] + `">`)
343		} else {
344			b.WriteString(`<g>`)
345		}
346		b.WriteString(in)
347		b.WriteString(`</g>`)
348	}
349	b.WriteString(`</svg>`)
350	return b.String()
351}
352
353// ComposeParts is a store kit's token: parts[k] is the whole file of the
354// part drawn for layer k (bottom first). The canvas is the first part whose
355// root parses; a part with another root, or no file (""), leaves its layer
356// empty, so an unchecked kit still composes a valid document (a checked kit
357// never has such a part: the adapter refuses it at CreateCollection).
358func ComposeParts(seed string, pal int, parts []string) string {
359	root, w, h := "", 0, 0
360	for _, p := range parts {
361		if r, ww, hh, ok := ParseRoot(p); ok {
362			root, w, h = r, ww, hh
363			break
364		}
365	}
366	if root == "" {
367		root, w, h = Root(DemoCanvas, DemoCanvas), DemoCanvas, DemoCanvas
368	}
369	inners := make([]string, len(parts))
370	for k, p := range parts {
371		if in, ok := Inner(p, root); ok {
372			inners[k] = in
373		}
374	}
375	return compose(root, w, h, pal, Inks(seed, pal, len(parts)), inners)
376}
377
378// WorstBytes is the largest token a kit can compose under palette pal:
379// maxInner[k] is the largest inner part of layer k (0 = all empty).
380func WorstBytes(root string, w, h, pal int, maxInner []int) int {
381	n := len(root) + len(`</svg>`)
382	if p := palettes[pal].paper; p != "" {
383		n += len(`<rect width="` + strconv.Itoa(w) + `" height="` + strconv.Itoa(h) + `" fill="` + p + `"/>`)
384	}
385	open := len(`<g>`)
386	if len(palettes[pal].inks) > 0 {
387		open = len(`<g color="#000000">`)
388	}
389	for _, m := range maxInner {
390		if m > 0 {
391			n += open + m + len(`</g>`)
392		}
393	}
394	return n
395}
396
397// ---------------------------------------------------------------------------
398// The demo kit (params store 0): the engine's sample and Studio preview.
399// ---------------------------------------------------------------------------
400
401func demoPick(seed string) []int {
402	ws := make([][]int64, len(demoLayers))
403	for k, l := range demoLayers {
404		ws[k] = make([]int64, len(l.parts))
405		for i, p := range l.parts {
406			ws[k][i] = p.weight
407		}
408	}
409	return Pick(seed, ws)
410}
411
412// SVG is the demo kit's token for seed under palette pal.
413func SVG(seed string, pal int) string {
414	at := demoPick(seed)
415	inners := make([]string, len(demoLayers))
416	for k, l := range demoLayers {
417		inners[k] = l.parts[at[k]].inner
418	}
419	return compose(Root(DemoCanvas, DemoCanvas), DemoCanvas, DemoCanvas, pal,
420		Inks(seed, pal, len(demoLayers)), inners)
421}
422
423// DemoTraits are the demo kit's part names for seed, in layer order.
424func DemoTraits(seed string) []engine.Trait {
425	at := demoPick(seed)
426	out := make([]engine.Trait, len(demoLayers))
427	for k, l := range demoLayers {
428		out[k] = engine.Trait{Type: l.name, Value: l.parts[at[k]].name}
429	}
430	return out
431}
432
433// Render is the demo kit's art (params store 0). Store kits are composed by
434// the adapter (ComposeParts); asking this package for one panics.
435func Render(in engine.Input) string {
436	cfg := MustConfig(in.Params)
437	if cfg.Store != 0 {
438		panic("katman: a store kit is composed by the adapter")
439	}
440	return SVG(in.Seed, cfg.Palette)
441}
442
443// Traits are the demo kit's traits (params store 0): one per layer.
444func Traits(in engine.Input) []engine.Trait {
445	cfg := MustConfig(in.Params)
446	if cfg.Store != 0 {
447		panic("katman: a store kit's traits come from the adapter")
448	}
449	return DemoTraits(in.Seed)
450}