diff --git a/client/src/appearance-editor.css b/client/src/appearance-editor.css new file mode 100644 index 0000000..ac9f990 --- /dev/null +++ b/client/src/appearance-editor.css @@ -0,0 +1,22 @@ +.appearance-editor{display:grid;grid-template-columns:minmax(220px,1.35fr) minmax(230px,1fr);gap:0;border:1px solid #ffffff18;border-radius:18px;overflow:hidden;background:#223239;color:#edece4;margin:16px 0;isolation:isolate} +.appearance-stage{position:relative;min-height:440px;background:#18262c;overflow:hidden} +.appearance-stage canvas{display:block;width:100%;height:100%;position:absolute;inset:0;touch-action:none} +.appearance-caption{position:absolute;top:24px;left:24px;right:20px;pointer-events:none;display:grid;gap:9px} +.appearance-caption span,.appearance-eyebrow{font-size:10px;letter-spacing:.18em;color:#a3c0b8;font-weight:700} +.appearance-caption strong{font-family:Georgia,serif;font-size:22px;font-weight:400;max-width:220px;color:#e8e7d9} +.appearance-hint{position:absolute;bottom:12px;left:0;right:0;text-align:center;color:#b5c5c1;font-size:11px;pointer-events:none} +.appearance-controls{padding:24px;display:flex;flex-direction:column;gap:16px;min-width:0} +.appearance-controls label{display:flex!important;flex-direction:column;gap:7px!important;font-size:12px;font-weight:500;color:#d2dcd6!important} +.appearance-controls select,.appearance-controls input[type=number]{box-sizing:border-box;width:100%;padding:9px 11px;border:1px solid #5e7576!important;border-radius:7px;background:#17272e!important;color:#f2ede0!important;min-height:36px} +.appearance-controls input[type=range]{width:100%;min-height:20px;padding:0;accent-color:#b4d7bb;cursor:pointer} +.appearance-swatches{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px} +.appearance-swatches input[type=color]{width:100%;height:36px;padding:3px;border:1px solid #5e7576;border-radius:8px;background:#17272e;cursor:pointer} +.appearance-actions{display:flex;flex-wrap:wrap;gap:8px}.appearance-editor button{background:#38514e!important;color:#e7f1df!important;border:1px solid #638079!important;border-radius:8px;padding:9px 12px;font-size:12px;cursor:pointer} +.appearance-note,.appearance-status{font-size:11px;line-height:1.6;color:#a8bcb5;margin:0}.appearance-status:empty{display:none} +.appearance-dialog{box-sizing:border-box;width:min(920px,96vw)!important;max-width:96vw!important;max-height:94dvh;overflow:auto;background:#18272b!important;color:#f1eee2!important;padding:28px!important;border:1px solid #536b66!important;border-radius:22px!important;box-shadow:0 24px 100px #0008} +.appearance-dialog::backdrop{background:#071317b8;backdrop-filter:blur(7px)} +.appearance-dialog h2{font-family:Georgia,serif;font-weight:400;font-size:28px;margin:8px 0 18px} +.appearance-dialog form{display:block!important}.appearance-dialog footer{display:flex;justify-content:flex-end;gap:10px;margin-top:18px} +.appearance-dialog footer button{border-radius:8px;padding:12px 18px;background:#263d40;color:#e9eee4;border:1px solid #658379;cursor:pointer} +.appearance-dialog footer button[type=submit]{background:#bfdbb8;color:#183832;border-color:#bfdbb8;font-weight:600} +@media(max-width:640px){.appearance-editor{grid-template-columns:1fr}.appearance-stage{min-height:300px}.appearance-controls{padding:18px;gap:13px}.appearance-dialog{padding:16px!important}.appearance-dialog h2{font-size:23px}.appearance-caption strong{font-size:19px}} diff --git a/client/src/appearance-editor.ts b/client/src/appearance-editor.ts new file mode 100644 index 0000000..a927a32 --- /dev/null +++ b/client/src/appearance-editor.ts @@ -0,0 +1,153 @@ +import './appearance-editor.css'; +import * as T from 'three'; +import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; +import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js'; +import { buildAppearance, defaultAppearance, disposeAppearance, forms } from './appearance-model'; +import { registerMenu } from './menu-focus'; +import type { Appearance, VisualPreset } from './generated'; + +const node = (tag: K, text = '', className = '') => { + const e = document.createElement(tag); e.textContent = text; e.className = className; return e; +}; +const button = (text: string, action: () => void) => { const b = node('button', text); b.type = 'button'; b.onclick = action; return b; }; + +export function createAppearanceEditor(families: string[], initial?: Appearance, library: VisualPreset[] = []) { + let value = structuredClone(initial ?? defaultAppearance(families[0])); + const root = node('section', '', 'appearance-editor'); + const stage = node('div', '', 'appearance-stage'), canvas = node('canvas'); + canvas.setAttribute('aria-label', '3D model preview. Drag to rotate and scroll to zoom.'); + const caption = node('div', '', 'appearance-caption'); + caption.append(node('span', 'AETERNALIS / CREATOR'), node('strong', 'A little life, shaped by you.')); + const hint = node('p', 'Drag to orbit · scroll to zoom', 'appearance-hint'); + stage.append(canvas, caption, hint); + const panel = node('div', '', 'appearance-controls'); + root.append(stage, panel); + const family = node('select'), variant = node('select'), presets = node('select'); + for (const f of families) family.append(new Option(f === 'human' ? 'Character' : f[0].toUpperCase() + f.slice(1), f)); + const field = (label: string, input: HTMLElement) => { const wrap = node('label', label); wrap.append(input); panel.append(wrap); }; + if (families.length > 1) field('Create', family); + field('Form', variant); + const sliders = new Map(), colors = new Map(); + const colorLabels = new Map(); + for (const [key, label, min, max] of [['height', 'Height', .75, 1.25], ['width', 'Build / fullness', .75, 1.25], ['detail', 'Feature size / foliage', 0, 1]] as const) { + const input = node('input'); input.type = 'range'; input.min = String(min); input.max = String(max); input.step = '.01'; + sliders.set(key, input); field(label, input); + } + const swatches = node('div', '', 'appearance-swatches'); + for (const [key, label] of [['primary', 'Skin / main'], ['secondary', 'Hair / secondary'], ['accent', 'Clothes / accent']] as const) { + const wrap = node('label'), caption = node('span', label), input = node('input'); input.type = 'color'; wrap.append(caption, input); swatches.append(wrap); colors.set(key, input); colorLabels.set(key, caption); + } + panel.append(swatches); + const seed = node('input'); seed.type = 'number'; seed.min = '1'; seed.max = '65535'; seed.step = '1'; seed.required = true; + field('Variation seed', seed); + presets.append(new Option('Choose a saved design…', '')); + for (const preset of library.filter(p => families.includes(p.appearance.family))) presets.append(new Option(preset.name, preset.id)); + if (presets.options.length > 1) field('Start from the visual library', presets); + const actions = node('div', '', 'appearance-actions'); + actions.append(button('New variation', () => { + const variation = crypto.getRandomValues(new Uint16Array(4)); + value.seed = 1 + variation[0] % 65535; + value.variant = (value.variant + 1 + variation[1] % 3) % 4; + value.detail = Math.round(variation[2] / 65535 * 100) / 100; + value.width = .8 + (variation[3] % 41) / 100; + sync(); + })); + const exportButton = button('Download GLB', () => void exportModel()); actions.append(exportButton); panel.append(actions); + const status = node('p', '', 'appearance-status'); status.setAttribute('role', 'status'); panel.append(status); + panel.append(node('p', 'Your look does not change your stats, movement, or reach.', 'appearance-note')); + + let renderer: T.WebGLRenderer | undefined, controls: OrbitControls | undefined, model: T.Group | undefined; + const scene = new T.Scene(); scene.background = new T.Color('#18262c'); + const camera = new T.PerspectiveCamera(35, 1, .01, 100); + scene.add(new T.HemisphereLight('#f5f3e8', '#728382', 2.5)); + const key = new T.DirectionalLight('#ffebd3', 3); key.position.set(-3, 6, -4); scene.add(key); + const rim = new T.DirectionalLight('#9cdbd9', 2); rim.position.set(3, 3, 2); scene.add(rim); + const pedestal = new T.Mesh(new T.CylinderGeometry(1.5, 1.55, .16, 64), new T.MeshStandardMaterial({ color: '#435957', roughness: .9 })); + pedestal.position.y = -.08; scene.add(pedestal); + let dirty = true, alive = true, attached = false, frame = 0, framedForm = ''; + try { + renderer = new T.WebGLRenderer({ canvas, antialias: true, alpha: false }); + renderer.setPixelRatio(Math.min(devicePixelRatio, 1.5)); renderer.toneMapping = T.ACESFilmicToneMapping; + controls = new OrbitControls(camera, canvas); controls.enablePan = false; controls.minDistance = 1; controls.maxDistance = 20; + controls.maxPolarAngle = Math.PI * .49; controls.addEventListener('change', () => { dirty = true; }); + } catch { status.textContent = '3D preview is unavailable on this device. You can still edit and save the design.'; } + function rebuild() { + if (model) { scene.remove(model); disposeAppearance(model); } + model = buildAppearance(value); scene.add(model); + const bounds = new T.Box3().setFromObject(model), size = bounds.getSize(new T.Vector3()); + const height = Math.max(size.y, size.x, size.z), centerY = size.y / 2; + pedestal.scale.setScalar(Math.max(.65, size.x / 2)); + const frameKey = value.family + ':' + value.variant; + if (framedForm !== frameKey) { + controls?.target.set(0, centerY, 0); + camera.position.set(height * .9, centerY + height * .45, -height * 2.3); camera.lookAt(0, centerY, 0); + framedForm = frameKey; + } + controls?.update(); dirty = true; + } + function sync() { + family.value = value.family; variant.replaceChildren(...forms[value.family].map((name, i) => new Option(name, String(i)))); variant.value = String(value.variant); + for (const [key, input] of sliders) input.value = String(value[key as 'height' | 'width' | 'detail']); + for (const [key, input] of colors) input.value = value[key as 'primary' | 'secondary' | 'accent']; + const labels: Record = { human: ['Skin', 'Hair', 'Clothes'], creature: ['Fur / body', 'Markings', 'Accent'], tree: ['Canopy', 'Bark', 'Blossoms'], rock: ['Stone', 'Shading', 'Crystal / moss'], plant: ['Leaves', 'Stems / petals', 'Flowers / caps'] }; + [...colorLabels.values()].forEach((label, index) => { label.textContent = labels[value.family][index]; }); + seed.value = String(value.seed); rebuild(); + } + function readInputs() { + value = { ...value, variant: Number(variant.value), seed: Number(seed.value), ...Object.fromEntries([...sliders].map(([k, i]) => [k, Number(i.value)])), ...Object.fromEntries([...colors].map(([k, i]) => [k, i.value])) }; + if (seed.validity.valid && seed.value) rebuild(); + } + family.onchange = () => { value = defaultAppearance(family.value); sync(); }; + variant.onchange = readInputs; seed.oninput = readInputs; + for (const input of [...sliders.values(), ...colors.values()]) input.oninput = readInputs; + presets.onchange = () => { const preset = library.find(p => p.id === presets.value); if (preset) { value = structuredClone(preset.appearance); sync(); } }; + async function exportModel() { + exportButton.disabled = true; + const exported = buildAppearance(value); + try { + const glb = await new GLTFExporter().parseAsync(exported, { binary: true }); + if (!(glb instanceof ArrayBuffer)) throw new Error('GLB export failed'); + const url = URL.createObjectURL(new Blob([glb], { type: 'model/gltf-binary' })); + const link = node('a'); link.href = url; link.download = `aeternalis-${value.family}-${value.seed}.glb`; link.click(); + setTimeout(() => URL.revokeObjectURL(url), 1000); status.textContent = 'GLB downloaded. Your editable recipe stays in the creator.'; + } catch (e) { status.textContent = (e as Error).message; } + finally { disposeAppearance(exported); exportButton.disabled = false; } + } + function tick() { + if (!alive) return; + if (root.isConnected) attached = true; + else if (attached) { dispose(); return; } + if (renderer && root.isConnected && !document.hidden) { + const width = stage.clientWidth, height = stage.clientHeight; + if (width && height) { + const size = renderer.getSize(new T.Vector2()); + if (size.x !== width || size.y !== height) { renderer.setSize(width, height, false); camera.aspect = width / height; camera.updateProjectionMatrix(); dirty = true; } + if (dirty) { renderer.render(scene, camera); dirty = false; } + } + } + frame = requestAnimationFrame(tick); + } + function dispose() { + if (!alive) return; alive = false; cancelAnimationFrame(frame); controls?.dispose(); + if (model) disposeAppearance(model); pedestal.geometry.dispose(); pedestal.material.dispose(); renderer?.dispose(); renderer?.forceContextLoss(); + } + sync(); frame = requestAnimationFrame(tick); + return { node: root, read: () => structuredClone(value), dispose }; +} + +export function showCharacterCreator(initial: Appearance | undefined, save: (appearance: Appearance) => Promise) { + const dialog = node('dialog', '', 'appearance-dialog'), header = node('header'), editor = createAppearanceEditor(['human'], initial); + header.append(node('div', 'YOUR CHARACTER', 'appearance-eyebrow'), node('h2', 'Give your traveler a face.')); + const footer = node('footer'), error = node('p', '', 'error'), form = node('form'); + let busy = false; + const menu = registerMenu(dialog, () => { if (!busy) { dialog.close(); editor.dispose(); dialog.remove(); menu.dispose(); } }); + const cancel = button('Cancel', () => menu.close()), submit = node('button', 'Save appearance'); submit.type = 'submit'; + footer.append(cancel, submit); form.append(editor.node, error, footer); dialog.append(header, form); + form.onsubmit = async event => { + event.preventDefault(); if (busy) return; busy = true; submit.disabled = cancel.disabled = true; editor.node.inert = true; + try { await save(editor.read()); busy = false; menu.close(); } + catch (e) { error.textContent = (e as Error).message; } + finally { busy = false; submit.disabled = cancel.disabled = false; editor.node.inert = false; } + }; + const previous = document.activeElement; document.body.append(dialog); dialog.showModal(); menu.opened(previous); +} diff --git a/client/src/appearance-model.ts b/client/src/appearance-model.ts new file mode 100644 index 0000000..c6bfa43 --- /dev/null +++ b/client/src/appearance-model.ts @@ -0,0 +1,179 @@ +import * as T from 'three'; +import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js'; +import type { Appearance } from './generated'; + +export const forms: Record = { + human: ['Tousled hair', 'Side swept', 'Rounded bob', 'Twin braids'], + creature: ['Woodland fox', 'Moss bear', 'Moon rabbit', 'Jelly sprite'], + tree: ['Cloud canopy', 'Layered evergreen', 'Willow crown', 'Blossom tree'], + rock: ['River stones', 'Boulder cluster', 'Crystal bloom', 'Mossy outcrop'], + plant: ['Broadleaf herb', 'Wildflowers', 'Mushroom cluster', 'Fern'], +}; + +export function defaultAppearance(family = 'human'): Appearance { + const colors: Record = { + human: ['#d8a582', '#493947', '#578f8b'], + creature: ['#cd8959', '#fff0cf', '#607a67'], + tree: ['#80a77a', '#785443', '#d8ae85'], + rock: ['#a2acb0', '#697e7b', '#9dc897'], + plant: ['#73a47f', '#d9aa8c', '#e6c86d'], + }; + const [primary, secondary, accent] = colors[family] ?? colors.human; + return { version: 1, family, variant: 0, seed: 42, height: 1, width: 1, detail: .5, primary, secondary, accent }; +} + +/** Stable procedural recipe, shared by the editor, world renderer and GLB export. + * Meshes are combined by material so a tree is a few instanced draws, not one + * draw per leaf. No collision or gameplay attributes are inferred from the mesh. + */ +export function buildAppearance(a: Appearance): T.Group { + const buckets = new Map(); + const transform = new T.Object3D(); + let seed = a.seed; + const random = () => { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; return seed / 4294967296; }; + const add = (geometry: T.BufferGeometry, color: string, x: number, y: number, z: number, sx = 1, sy = 1, sz = 1, rx = 0, rz = 0) => { + transform.position.set(x, y, z); transform.rotation.set(rx, 0, rz); transform.scale.set(sx, sy, sz); transform.updateMatrix(); + geometry.applyMatrix4(transform.matrix); + const flat = geometry.index ? geometry.toNonIndexed() : geometry; + if (flat !== geometry) geometry.dispose(); + const list = buckets.get(color) ?? []; list.push(flat); buckets.set(color, list); + }; + const orb = (c: string, x: number, y: number, z: number, sx: number, sy = sx, sz = sx, rz = 0) => + add(new T.SphereGeometry(1, 16, 10), c, x, y, z, sx, sy, sz, 0, rz); + const stem = (c: string, x: number, y: number, z: number, radius: number, height: number, rz = 0) => + add(new T.CylinderGeometry(radius * .8, radius, height, 10), c, x, y, z, 1, 1, 1, 0, rz); + const eyes = (x: number, y: number, z: number, r = .055) => { + for (const sign of [-1, 1]) { + orb('#263445', sign * x, y, z, r, r * 1.2, r * .65); + orb('#ffffff', sign * x - r * .23, y + r * .3, z - r * .55, r * .27); + } + }; + + if (a.family === 'human') { + // Rounded boots, tunic, belt, hands, face and layered hair. + for (const sign of [-1, 1]) { + orb(a.secondary, sign * .19, .38, 0, .14, .31, .15); + orb('#484b53', sign * .19, .13, -.06, .17, .13, .24); + orb(a.accent, sign * .4, 1.08, 0, .16, .28, .16, sign * -.16); + orb(a.primary, sign * .43, .78, -.01, .11, .16, .12); + orb(a.primary, sign * .29, 1.7, 0, .07 + a.detail * .05, .105, .065); + } + orb(a.accent, 0, .97, 0, .34, .4, .23); + orb('#495e64', 0, .77, -.005, .34, .07, .23); + orb('#d9bb7b', 0, .77, -.23, .065, .055, .025); + stem(a.primary, 0, 1.38, 0, .11, .22); + orb(a.primary, 0, 1.67, 0, .285, .32, .255); + orb(a.primary, 0, 1.65, -.25, .055, .062, .055); + eyes(.105, 1.73, -.236, .032); + orb('#ad7266', 0, 1.555, -.239, .07, .014, .015); + orb(a.secondary, 0, 1.86, .02, .296, .2, .267); + if (a.variant === 0 || a.variant === 1) { + for (let i = 0; i < 5; i++) orb(a.secondary, -.22 + i * .1, 1.86 + random() * .045, -.15, .105, .105, .13, a.variant === 1 ? .5 : 0); + } else if (a.variant === 2) { + for (const sign of [-1, 1]) orb(a.secondary, sign * .265, 1.68, .045, .075, .26, .225); + } else { + for (const sign of [-1, 1]) for (let i = 0; i < 4; i++) orb(a.secondary, sign * (.29 + .013 * Math.sin(i)), 1.65 - i * .11, .035, .075, .085, .085); + for (const sign of [-1, 1]) orb(a.accent, sign * .29, 1.25, .035, .07, .04, .07); + } + } else if (a.family === 'creature') { + if (a.variant === 3) { + orb(a.primary, 0, .65, 0, .85, .68, .75); + orb(a.secondary, 0, .32, -.58, .52, .19, .15); + eyes(.24, .77, -.69, .085); + for (let i = 0; i < 3; i++) orb(a.accent, (i - 1) * .28, 1.28 + (i === 1 ? .18 : 0), 0, .13, .2 + a.detail * .12, .1); + orb('#fff9e3', -.3, 1.06, -.48, .16, .09, .05); + } else { + const bear = a.variant === 1, rabbit = a.variant === 2; + orb(a.primary, 0, .76, .12, bear ? .68 : .43, .55, .72); + orb(a.secondary, 0, .7, -.43, .3, .34, .18); + for (const sign of [-1, 1]) for (const z of [-.35, .53]) orb(a.primary, sign * (bear ? .42 : .3), .24, z, .19, .27, .25); + orb(a.primary, 0, 1.18, -.47, bear ? .49 : .4, .42, .38); + orb(a.secondary, 0, 1.03, -.81, .26, .19, .17); + orb('#344447', 0, 1.105, -.954, .095, .065, .05); + eyes(.18, 1.27, -.798, .05); + for (const sign of [-1, 1]) { + const length = rabbit ? .48 + a.detail * .35 : bear ? .14 : .23 + a.detail * .15; + orb(a.primary, sign * .29, 1.52 + length * .5, -.4, bear ? .17 : .115, length, .13, sign * -.2); + orb(a.secondary, sign * .29, 1.54 + length * .5, -.515, bear ? .09 : .063, length * .7, .028, sign * -.2); + } + orb(a.primary, .05, .85, .93, rabbit ? .23 : .28, rabbit ? .23 : .32, rabbit ? .23 : .48); + if (!bear && !rabbit) orb(a.secondary, .05, .99, 1.23, .21, .22, .23); + if (bear) for (let i = 0; i < 5; i++) orb(a.accent, -.35 + i * .17, 1.21 + random() * .11, .2 + random() * .3, .16, .1, .2); + } + } else if (a.family === 'tree') { + stem(a.secondary, 0, 1.55, 0, .26, 3.1); + for (let i = 0; i < 4; i++) { + const angle = i * Math.PI / 2 + .3; + orb(a.secondary, Math.cos(angle) * .3, .13, Math.sin(angle) * .3, .46, .15, .2); + } + if (a.variant === 1) { + for (let i = 0; i < 4; i++) { + const r = 1.5 - i * .3; + orb(i % 2 ? a.accent : a.primary, 0, 2 + i * .62, 0, r, .63, r); + } + orb(a.primary, 0, 4.32, 0, .26, .48, .26); + } else { + const n = 6 + Math.floor(a.detail * 5); + for (let i = 0; i < n; i++) { + const angle = i * Math.PI * 2 / n, reach = .6 + random() * .65; + const x = Math.cos(angle) * reach, z = Math.sin(angle) * reach; + stem(a.secondary, x * .45, 2.4, z * .45, .12, 1.5, -x * .45); + orb(a.variant === 3 && i % 3 === 0 ? a.accent : a.primary, x, 3 + random() * .7, z, .85 + random() * .3, a.variant === 2 ? 1.25 : .85, .9); + if (a.variant === 2) orb(a.primary, x * 1.1, 2.2, z * 1.1, .32, 1.05, .32); + } + orb(a.primary, 0, 3.8, 0, 1.1, .85, 1.05); + if (a.variant === 3) for (let i = 0; i < 8; i++) orb(a.accent, (random() - .5) * 3, 3 + random(), (random() - .5) * 3, .2); + } + } else if (a.family === 'rock') { + const n = a.variant === 0 ? 5 : 3 + Math.floor(a.detail * 5); + for (let i = 0; i < n; i++) { + const angle = i * 2.4, radius = i === 0 ? 0 : .4 + random() * .55; + const x = Math.sin(angle) * radius, z = Math.cos(angle) * radius, size = .45 + random() * .5; + if (a.variant === 2) { + const h = .7 + random() * 1.1; + add(new T.CylinderGeometry(.22, .3, h, 5), i % 2 ? a.accent : a.primary, x, h / 2, z); + add(new T.ConeGeometry(.22, .35, 5), i % 2 ? a.accent : a.primary, x, h + .17, z); + } else { + orb(i % 2 ? a.secondary : a.primary, x, size * .42, z, size, size * (a.variant === 0 ? .42 : .75), size * .8, random() * .3); + if (a.variant === 3) orb(a.accent, x, size * 1.05, z, size * .85, .11, size * .63); + } + } + } else if (a.family === 'plant') { + if (a.variant === 2) { + for (let i = 0; i < 4; i++) { + const x = (random() - .5) * .8, z = (random() - .5) * .8, h = .35 + random() * .6; + stem(a.secondary, x, h / 2, z, .07, h); + orb(a.accent, x, h, z, .28 + a.detail * .15, .16, .28); + for (let k = 0; k < 3; k++) orb('#fff1d0', x + (random() - .5) * .3, h + .145, z + (random() - .5) * .3, .045, .014, .045); + } + } else { + const n = 5 + Math.floor(a.detail * 5); + for (let i = 0; i < n; i++) { + const angle = i * Math.PI * 2 / n, x = Math.sin(angle), z = Math.cos(angle); + orb(a.primary, x * .25, .24, z * .25, .17, .32, .25, -x * .65); + if (a.variant === 1) { + const h = .55 + random() * .45; stem(a.primary, x * .22, h / 2, z * .22, .023, h); + for (let k = 0; k < 5; k++) orb(a.secondary, x * .22 + Math.cos(k * 1.26) * .1, h, z * .22 + Math.sin(k * 1.26) * .1, .09, .04, .09); + orb(a.accent, x * .22, h + .025, z * .22, .06, .035, .06); + } else if (a.variant === 3) { + for (let k = 1; k < 5; k++) orb(k % 2 ? a.accent : a.primary, x * k * .13, .55 - k * .08, z * k * .13, .1, .06, .18, -x * .4); + } + } + } + } + const root = new T.Group(); root.name = `${a.family}-${a.variant}-v1`; + for (const [color, geometries] of buckets) { + const merged = mergeGeometries(geometries)!; + for (const g of geometries) g.dispose(); + merged.scale(a.width, a.height, a.width); + const mesh = new T.Mesh(merged, new T.MeshStandardMaterial({ color, roughness: .78 })); + mesh.castShadow = true; mesh.receiveShadow = true; root.add(mesh); + } + return root; +} + +export function disposeAppearance(root: T.Object3D) { + root.traverse(o => { + if (o instanceof T.Mesh) { o.geometry.dispose(); for (const m of Array.isArray(o.material) ? o.material : [o.material]) m.dispose(); } + }); +} diff --git a/client/src/content-editor.ts b/client/src/content-editor.ts index bc63a85..05c3177 100644 --- a/client/src/content-editor.ts +++ b/client/src/content-editor.ts @@ -1,4 +1,6 @@ import './content-editor.css'; +import { createAppearanceEditor } from './appearance-editor'; +import type { MobDefinition, VisualPreset } from './generated'; import { api } from './portal-shared'; import { derivedStats, itemSlots, modifiersView, node, primaryStats, statLabel } from './character-stats'; import type { ContentCatalog as Catalog, ContentRequirement as Requirement, ContentPreview, StatModifier } from './generated'; @@ -41,7 +43,7 @@ const statKeys=[...primaryStats,...derivedStats],metrics=['level','kills','world const root=node('section','','catalog-editor'),header=node('div','','catalog-heading'),version=node('p'),tabs=node('div','','catalog-tabs'),list=node('div','','catalog-list'),forms=node('div'),message=node('p','','message'); const refresh=button('Refresh catalog',()=>void load());header.append(node('h2','Game content'),version,refresh);message.hidden=true;message.setAttribute('role','status');root.append(header,message,tabs,list,forms); let catalog:Catalog,changes:Audit[]=[],section='titles',editing=false,loading=false,saving=false; -for(const [key,label] of [['titles','Titles'],['items','Equipment'],['requirements','Requirement sets'],['effects','Effect sets'],['gathering','Gathering'],['resources','Resources'],['biomes','Biomes'],['consumables','Consumables'],['attacks','Attacks'],['mobs','Mobs'],['loot','Loot tables'],['spawns','Mob spawns'],['buildings','Structures'],['powers','Spells and abilities'],['weapons','Weapon types'],['craft-recipes','Recipes'],['craft-professions','Crafting professions'],['craft-materials','Crafting materials'],['craft-rules','Crafting tuning'],['stats','Stat formulas'],['audit','Content audit']]){const b=button(label,()=>{if(editing||saving){show('Finish or cancel the open draft first.');return;}section=key;render()});b.dataset.section=key;tabs.append(b);} +for(const [key,label] of [['visuals','Visual workshop'],['titles','Titles'],['items','Equipment'],['requirements','Requirement sets'],['effects','Effect sets'],['gathering','Gathering'],['resources','Resources'],['biomes','Biomes'],['consumables','Consumables'],['attacks','Attacks'],['mobs','Mobs'],['loot','Loot tables'],['spawns','Mob spawns'],['buildings','Structures'],['powers','Spells and abilities'],['weapons','Weapon types'],['craft-recipes','Recipes'],['craft-professions','Crafting professions'],['craft-materials','Crafting materials'],['craft-rules','Crafting tuning'],['stats','Stat formulas'],['audit','Content audit']]){const b=button(label,()=>{if(editing||saving){show('Finish or cancel the open draft first.');return;}section=key;render()});b.dataset.section=key;tabs.append(b);} function button(text:string,fn:()=>void){const b=node('button',text,'button secondary');b.type='button';b.onclick=fn;return b;} function show(text:string){message.textContent=text;message.hidden=false;} function field(label:string,input:HTMLElement){const wrap=node('label',label);wrap.append(input);return wrap;} @@ -140,7 +142,8 @@ function statsForm(){ } function render(){ version.textContent=`Catalog version ${catalog.version}`;for(const b of tabs.querySelectorAll('button'))b.setAttribute('aria-pressed',String(b.dataset.section===section));list.replaceChildren(); - if(section==='buildings'){buildingList(); + if(section==='visuals'){visualList(); + }else if(section==='buildings'){buildingList(); }else if(section==='powers'||section==='weapons'){powerList(); }else if(section.startsWith('craft-')){craftingList(); }else if(['attacks','mobs','loot','spawns'].includes(section)){combatList(); @@ -203,9 +206,11 @@ function gatheringForm(kind:string,existing?:NonNullable[' const skill=contentChoice(g?.skills??[]),model=select(['tree','ore','herb']),output=select(['wood','ore','herb','self']),level=number(1,1,10000,'1'),amount=number(1,1,1000,'1'),xp=number(2,0,1000000,'1'),seconds=number(1,0.1,3600),respawn=number(120,1,604800),density=number(4,0,32,'1'); output.options[3].text='New material named after this resource'; const biomeFields=node('fieldset','','catalog-title-choices');biomeFields.append(node('legend','Spawn biomes')); + const visualHost=node('div');let visual=createAppearanceEditor(['tree'],undefined,catalog.visuals??[]);visualHost.append(visual.node); + model.onchange=()=>{visual.dispose();visual=createAppearanceEditor([{tree:'tree',ore:'rock',herb:'plant'}[model.value]??'tree'],undefined,catalog.visuals??[]);visualHost.replaceChildren(visual.node)}; const checks=(g?.biomes??[]).map(b=>{const i=node('input');i.type='checkbox';biomeFields.append(field(b.name,i));return{id:b.id,input:i}}); - const fields=form('Create resource','create-resource',()=>{const biomes=checks.filter(v=>v.input.checked).map(v=>v.id);if(!biomes.length)throw new Error('Choose at least one biome.');return{resource:{...values.read(),skillId:skill.value,model:model.value,output:output.value,requiredLevel:Number(level.value),amount:Number(amount.value),xp:Number(xp.value),seconds:Number(seconds.value),respawnSeconds:Number(respawn.value),density:Number(density.value),biomes}}}); - fields.append(values.node,field('Gathering skill',skill),field('Model preset',model),field('Gathered material',output),field('Required effective skill level',level),field('Base amount per success',amount),field('Base profession XP per success',xp),field('Gathering interval (seconds)',seconds),field('Respawn interval (seconds)',respawn),field('Nodes per matching chunk (before forest density bonus)',density),biomeFields,node('p','Players may risk attempts up to 20 levels below this requirement. Failures can destroy the node until respawn and inflict damage/fatigue. New definitions appear in unexplored chunks of new-generation worlds; explored layouts stay fixed. Models use existing placeholders until milestone 4.5.','muted')); + const fields=form('Create resource','create-resource',()=>{const biomes=checks.filter(v=>v.input.checked).map(v=>v.id);if(!biomes.length)throw new Error('Choose at least one biome.');return{resource:{...values.read(),appearance:visual.read(),skillId:skill.value,model:model.value,output:output.value,requiredLevel:Number(level.value),amount:Number(amount.value),xp:Number(xp.value),seconds:Number(seconds.value),respawnSeconds:Number(respawn.value),density:Number(density.value),biomes}}}); + fields.append(values.node,field('Gathering skill',skill),field('Resource type',model),visualHost,field('Gathered material',output),field('Required effective skill level',level),field('Base amount per success',amount),field('Base profession XP per success',xp),field('Gathering interval (seconds)',seconds),field('Respawn interval (seconds)',respawn),field('Nodes per matching chunk (before forest density bonus)',density),biomeFields,node('p','Players may risk attempts up to 20 levels below this requirement. Failures can destroy the node until respawn and inflict damage/fatigue. New definitions appear in unexplored chunks of new-generation worlds; explored layouts stay fixed. The visual recipe is copied into this resource; saved visual designs can be reused.','muted')); }else if(kind==='biomes'){ const color=text(existing?.color??'#426044',7);color.type='color';const weight=number(existing?.weight??3,1,100,'1'); const resources=node('fieldset','','catalog-title-choices');resources.append(node('legend','Resources in this biome')); @@ -229,9 +234,9 @@ function gatheringList(){ list.append(d);} } -function combatForm(kind:string){ +function combatForm(kind:string,source?:MobDefinition){ if(editing||saving){show('Finish the open draft first.');return;} - const values=identity(),c=catalog.combat; + const values=identity(source ? {...source,name:source.name+' variation'} : undefined),c=catalog.combat; if(kind==='attacks'){ const delivery=select(['melee','projectile']),effect=select(['damage','heal']),stat=select(['meleeDamage','rangedDamage','magicDamage']); const settings=[['multiplier','Stat multiplier',1,.01,100],['range','Range (m)',6,1,128],['cooldown','Cooldown (seconds)',1,.1,120],['stamina','Player stamina cost',0,0,10000],['speed','Weapon base projectile speed (m/s)',35,1,100],['dexteritySpeed','Extra m/s per Dexterity point',.1,0,5],['strengthSpeed','Extra m/s per Strength point',.05,0,5],['radius','Area radius (0 = single target)',0,0,24],['duration','Area duration (0 = burst)',0,0,60],['interval','Area tick interval (seconds)',1,.2,60]] as const; @@ -239,11 +244,12 @@ function combatForm(kind:string){ const fields=form('Create attack profile','create-attack',()=>({attack:{...values.read(),delivery:delivery.value,effect:effect.value,stat:stat.value,...Object.fromEntries(inputs.map(v=>[v.key,Number(v.input.value)]))}})); fields.append(values.node,field('Delivery',delivery),field('Effect',effect),field('Player stat to scale',stat),...inputs.map(v=>field(v.label,v.input)),node('p','Damage targets opponents; healing targets allies. Players currently target mobs and the Harbinger, while player healing targets living players. Projectiles fly toward the selected position and can miss. Areas remain fixed at impact. Damage is sampled at attack time.','muted')); }else if(kind==='mobs'){ - const model=select(['sentinel','boss']),behavior=select(['aggressive','guard','passive']),attack=contentChoice(c?.attacks??[]),loot=contentChoice([{id:'',name:'No loot'},...(c?.loot??[])]);loot.required=false; + const model=select(['sentinel','boss'],source?.model),behavior=select(['aggressive','guard','passive'],source?.behavior),attack=contentChoice(c?.attacks??[],source?.attackId),loot=contentChoice([{id:'',name:'No loot'},...(c?.loot??[])],source?.lootId); + const visual=createAppearanceEditor(['creature','human'],source?.appearance,catalog.visuals??[]);loot.required=false; const settings=[['level','Level',1,1,10000],['hp','Base health per level',54,1,1000000],['damage','Base attack power per level',6,0,100000],['defence','Flat defence',0,0,100000],['speed','Movement speed',4,.1,30],['aggroRange','Detection range',24,1,128],['leashRange','Maximum distance from home',160,1,512],['scalePerDay','World-age scaling per day',.1,0,10],['xp','Character XP on defeat',50,0,1000000000]] as const; - const inputs=settings.map(([key,label,value,min,max])=>({key,label,input:number(value,min,max,key==='xp'||key==='level'?'1':'any')})); - const fields=form('Create mob','create-mob',()=>({mob:{...values.read(),model:model.value,behavior:behavior.value,attackId:attack.value,lootId:loot.value,...Object.fromEntries(inputs.map(v=>[v.key,Number(v.input.value)]))}})); - fields.append(values.node,field('Model preset',model),field('Behavior',behavior),field('Attack profile',attack),field('Loot table',loot),...inputs.map(v=>field(v.label,v.input)),node('p','Health/power = base × level × (1 + world age in days × scaling). Defence is flat. Aggressive creatures pursue within the leash; guards defend their detection radius; passive creatures retaliate only when attacked. Models remain placeholders until milestone 4.5.','muted')); + const inputs=settings.map(([key,label,value,min,max])=>({key,label,input:number(source?.[key]??value,min,max,key==='xp'||key==='level'?'1':'any')})); + const fields=form('Create mob','create-mob',()=>({mob:{...values.read(),appearance:visual.read(),model:model.value,behavior:behavior.value,attackId:attack.value,lootId:loot.value,...Object.fromEntries(inputs.map(v=>[v.key,Number(v.input.value)]))}})); + fields.append(values.node,visual.node,field('Fallback model',model),field('Behavior',behavior),field('Attack profile',attack),field('Loot table',loot),...inputs.map(v=>field(v.label,v.input)),node('p','Health/power = base × level × (1 + world age in days × scaling). Defence is flat. Aggressive creatures pursue within the leash; guards defend their detection radius; passive creatures retaliate only when attacked. The visual recipe is copied into this mob. Publish a spawn rule or use Control → Spawn mobs to place it.','muted')); }else if(kind==='loot'){ const items=[...catalog.items,...craftMaterials()]; const entries=repeat('Loot entries','Add loot entry',()=>{const group=node('div','','catalog-fields'),item=contentChoice(items),amount=number(1,1,100,'1'),chance=number(100,0,100),pool=text('',40),weight=number(1,1,10000,'1');pool.required=false;group.append(field('Item',item),field('Quantity',amount),field('Drop chance (%)',chance),field('Weighted group (blank = independent)',pool),field('Group weight',weight));return{node:group,read:()=>({item:item.value,amount:Number(amount.value),chance:Number(chance.value),group:pool.value.trim(),weight:Number(weight.value)})}},[],32); @@ -258,7 +264,7 @@ function combatList(){ const c=catalog.combat,entries=section==='attacks'?c?.attacks:section==='mobs'?c?.mobs:section==='loot'?c?.loot:c?.spawns; const labels:Record={attacks:'attack profile',mobs:'mob',loot:'loot table',spawns:'mob spawn rule'}; list.append(button(`Create ${labels[section]}`,()=>combatForm(section))); - for(const v of entries??[]){const d=node('details','','catalog-definition');d.append(node('summary',v.name),node('p',v.description),readableDefinition(v));list.append(d)} + for(const v of entries??[]){const d=node('details','','catalog-definition');d.append(node('summary',v.name),node('p',v.description),readableDefinition(v));if(section==='mobs')d.append(button('Create variation',()=>combatForm('mobs',v as MobDefinition)));list.append(d)} } function powerList(){ @@ -289,3 +295,17 @@ function buildingList(){ fields.append(values.node,field('Appearance preset',model),field('Width (m)',width),field('Depth (m)',depth),field('Height (m)',height),field('Health',hp),field('Placement profession',profession),field('Minimum profession level',level)); }));for(const d of catalog.building?.definitions??[]){const row=node('details','','catalog-definition');row.append(node('summary',d.name),readableDefinition(d));list.append(row)} } + +function visualList(){ + list.append(node('p','Create rounded fantasy models, save reusable designs, or download a GLB. Saved visuals appear in the resource and mob creators. They do not spawn content on their own.','muted'),button('Create a visual',()=>visualForm())); + for(const preset of catalog.visuals??[]){ + const card=node('article','','catalog-definition');card.append(node('h3',preset.name),node('p',preset.description),node('p',statLabel(preset.appearance.family)+' · procedural version '+preset.appearance.version,'muted'),button('Preview / create variation',()=>visualForm(preset)));list.append(card); + } +} +function visualForm(source?:VisualPreset){ + if(editing||saving){show('Finish or cancel the open draft first.');return;} + const values=identity(source?{name:source.name+' variation',description:source.description}:undefined); + const editor=createAppearanceEditor(['human','creature','tree','rock','plant'],source?.appearance,catalog.visuals??[]); + const fields=form('Visual workshop','create-visual',()=>({visual:{...values.read(),appearance:editor.read()}})); + fields.append(values.node,editor.node,node('p','Publishing saves an immutable design with a server-assigned identity. Resource and mob creators copy the selected design, so later variations cannot change existing content.','muted')); +} diff --git a/client/src/generated.ts b/client/src/generated.ts index 997ca19..6e7f1f9 100644 --- a/client/src/generated.ts +++ b/client/src/generated.ts @@ -27,6 +27,7 @@ export interface ContentCatalog { stats: ContentStatsRules; titles: TitleDefinition[]; version: number; + visuals?: VisualPreset[]; } export interface BuildingContent { @@ -93,6 +94,7 @@ export interface LootEntry { export interface MobDefinition { aggroRange: number; + appearance?: Appearance; attackId: string; behavior: string; damage: number; @@ -110,6 +112,19 @@ export interface MobDefinition { xp: number; } +export interface Appearance { + accent: string; + detail: number; + family: string; + height: number; + primary: string; + secondary: string; + seed: number; + variant: number; + version: number; + width: number; +} + export interface MobSpawn { biomes: string[]; count: number; @@ -223,6 +238,7 @@ export interface ItemUseEffect { export interface ResourceDefinition { amount: number; + appearance?: Appearance; biomes: string[]; density: number; description: string; @@ -338,6 +354,13 @@ export interface TitleEffects { moveSpeed: number; } +export interface VisualPreset { + appearance: Appearance; + description: string; + id: string; + name: string; +} + export interface ContentChange { attack?: CombatAttackDraft; biome?: BiomeDefinitionDraft; @@ -365,6 +388,7 @@ export interface ContentChange { stats?: ContentStatsRules; targetId?: string; title?: TitleDraft; + visual?: VisualPresetDraft; weapon?: GatheringSkillDraft; } @@ -480,6 +504,7 @@ export interface LootTableDraft { export interface MobDefinitionDraft { aggroRange: number; + appearance?: Appearance; attackId: string; behavior: string; damage: number; @@ -529,6 +554,7 @@ export interface RequirementSetDraft { export interface ResourceDefinitionDraft { amount: number; + appearance?: Appearance; biomes: string[]; density: number; description: string; @@ -566,6 +592,13 @@ export interface TitleDraft { scope: string; } +export interface VisualPresetDraft { + appearance: Appearance; + description: string; + id?: string; + name: string; +} + export interface ContentPreview { basedOnVersion: number; proposedVersion: number; @@ -633,6 +666,7 @@ export interface HouseSummary { } export interface Entity { + appearance?: Appearance; depth?: number; height?: number; hp: number; diff --git a/client/src/house-view.ts b/client/src/house-view.ts index b90dd0a..ce07891 100644 --- a/client/src/house-view.ts +++ b/client/src/house-view.ts @@ -1,4 +1,5 @@ import * as T from 'three'; +import { buildAppearance, disposeAppearance } from './appearance-model'; import type {Entity, HouseScene, Snapshot} from './generated'; /** Indoor presentation only. Positions and furniture geometry come from Go. */ @@ -15,7 +16,7 @@ export class HouseView { const signature=JSON.stringify([house.id,house.size,house.furniture]);if(this.signature!==signature){this.clear();this.active=true;this.signature=signature;this.build(house)} const entities=[...house.people.filter(p=>p.id!==snapshot.self.entity.id),{...snapshot.self.entity,position:snapshot.self.housePosition??{x:0,y:0,z:0}}]; const ids=new Set(entities.map(p=>p.id));for(const [id,v] of this.actors)if(!ids.has(id)){this.scene.remove(v.root);v.dispose();this.actors.delete(id)} - for(const e of entities){let actor=this.actors.get(e.id);if(!actor){const firstDisposable=this.disposables.length,root=new T.Group();if(model)root.add(model.clone(true));else{this.box(.55,1.25,.45,0,.8,0,e.id===snapshot.self.entity.id?'#bdd1ad':'#88a9c6',root);this.box(.4,.4,.4,0,1.65,0,'#d6b49a',root)} + for(const e of entities){let actor=this.actors.get(e.id);const appearanceKey=JSON.stringify(e.appearance??null);if(actor&&actor.root.userData.appearance!==appearanceKey){this.scene.remove(actor.root);actor.dispose();this.actors.delete(e.id);actor=undefined}if(!actor){const firstDisposable=this.disposables.length,root=new T.Group();root.userData.appearance=appearanceKey;if(e.appearance){const visual=buildAppearance(e.appearance);root.add(visual);this.disposables.push(()=>disposeAppearance(visual))}else if(model)root.add(model.clone(true));else{this.box(.55,1.25,.45,0,.8,0,e.id===snapshot.self.entity.id?'#bdd1ad':'#88a9c6',root);this.box(.4,.4,.4,0,1.65,0,'#d6b49a',root)} const canvas=document.createElement('canvas');canvas.width=256;canvas.height=48;const ctx=canvas.getContext('2d')!;ctx.fillStyle='#13201ee6';ctx.fillRect(0,0,256,48);ctx.fillStyle='#fff5df';ctx.textAlign='center';ctx.font='24px sans-serif';ctx.fillText(e.name,128,32,248);const texture=new T.CanvasTexture(canvas),material=new T.SpriteMaterial({map:texture,depthTest:false}),name=new T.Sprite(material);name.position.y=2.2;name.scale.set(2.5,.47,1);root.add(name);this.disposables.push(()=>{texture.dispose();material.dispose()});root.position.set(e.position.x,e.position.y,e.position.z);const cleanup=this.disposables.splice(firstDisposable);actor={root,target:root.position.clone(),dispose:()=>cleanup.forEach(f=>f())};this.actors.set(e.id,actor);this.scene.add(root) }actor.target.set(e.position.x,e.position.y,e.position.z) } diff --git a/client/src/main.ts b/client/src/main.ts index 547954e..898bff0 100644 --- a/client/src/main.ts +++ b/client/src/main.ts @@ -1,4 +1,7 @@ import './style.css'; +import { showCharacterCreator } from './appearance-editor'; +import type { Appearance } from './generated'; +let draftAppearance: Appearance | undefined; import {createItemActions} from './item-actions'; import { showTravel } from './travel'; import { createHousingPanel } from './housing-panel'; @@ -340,9 +343,15 @@ async function boot() { } if(config.kind==='hub'){visible('join-form',false);$('arrival-error').textContent='Enter a hub through travel from your current character. Open your account to continue.';} } + const customize = document.createElement('button'); customize.type = 'button'; customize.textContent = 'Create your look'; + customize.onclick = () => showCharacterCreator(draftAppearance, async appearance => { draftAppearance = appearance; customize.textContent = 'Edit your look'; }); + $('join-form').insertBefore(customize, $('join')); + const restyle = document.createElement('button'); restyle.type = 'button'; restyle.textContent = 'Character appearance'; + restyle.onclick = () => showCharacterCreator(snapshot?.self.entity.appearance, async appearance => { await api('/api/appearance', appearance); notice('Appearance saved.'); }); + $('settings').append(restyle); $('join-form').onsubmit = async event => { event.preventDefault(); const button = $('join'); button.disabled = true; - try { await api('/api/join', { name: $('name').value, passage: '' }); $('arrival').close(); connect(); } + try { await api('/api/join', { name: $('name').value, passage: '', appearance: draftAppearance }); $('arrival').close(); connect(); } catch (e) { $('arrival-error').textContent = (e as Error).message; } finally { button.disabled = false; } }; diff --git a/client/src/world-view.ts b/client/src/world-view.ts index 821a1bf..4a590a8 100644 --- a/client/src/world-view.ts +++ b/client/src/world-view.ts @@ -1,4 +1,5 @@ import * as T from 'three'; +import { buildAppearance, disposeAppearance } from './appearance-model'; import {HouseView} from './house-view'; import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; import { ProjectilePresentation } from './projectile-presentation'; @@ -27,6 +28,7 @@ export class WorldView { distance = 30; frames = 0; moving = false; + private playerAppearance = ''; private highQuality = true; private initialized = false; private clock = new T.Clock(); @@ -177,7 +179,33 @@ export class WorldView { } updateEntities(entities: Entity[]) { for (const batch of this.batches.values()) batch.entities = []; - for (const entity of entities) this.batches.get(entity.model??(entity.kind==='area'?`area-${entity.state}`:entity.kind))?.entities.push(entity); + const groups = new Map(); + for (const entity of entities) { + const key = entity.appearance && entity.kind !== 'corpse' ? 'appearance:' + JSON.stringify(entity.appearance) : entity.model ?? (entity.kind === 'area' ? 'area-' + entity.state : entity.kind); + const group = groups.get(key) ?? []; group.push(entity); groups.set(key, group); + } + for (const [key, batch] of this.batches) { + if (!key.startsWith('appearance:')) continue; + if (!groups.has(key) || (groups.get(key)!.length > batch.parts[0].instanceMatrix.count && batch.parts[0].instanceMatrix.count < 2048)) { + for (const mesh of batch.parts) { this.scene.remove(mesh); mesh.geometry.dispose(); for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) material.dispose(); mesh.dispose(); } + this.batches.delete(key); + } + } + for (const [key, group] of groups) { + if (key.startsWith('appearance:') && !this.batches.has(key)) { + const template = buildAppearance(group[0].appearance!); + const batch: Batch = { parts: [], entities: [] }; + const capacity = Math.min(2048, 2 ** Math.ceil(Math.log2(Math.max(1, group.length)))); + for (const child of template.children) { + if (!(child instanceof T.Mesh)) continue; + const mesh = new T.InstancedMesh(child.geometry, child.material, capacity); + mesh.count = 0; mesh.castShadow = true; mesh.receiveShadow = true; mesh.userData.kind = key; + mesh.instanceMatrix.setUsage(T.DynamicDrawUsage); this.scene.add(mesh); batch.parts.push(mesh); + } + this.batches.set(key, batch); + } + const batch = this.batches.get(key); if (batch) batch.entities = group; + } for (const batch of this.batches.values()) { const count = Math.min(2048, batch.entities.length); for (let i = 0; i < count; i++) { @@ -194,6 +222,13 @@ export class WorldView { } update(snapshot: Snapshot) { this.snapshot = snapshot; + const appearanceKey = JSON.stringify(snapshot.self.entity.appearance ?? null); + if (appearanceKey !== this.playerAppearance) { + if (this.player) { this.scene.remove(this.player); if (this.playerAppearance && this.playerAppearance !== 'null') disposeAppearance(this.player); } + this.player = snapshot.self.entity.appearance ? buildAppearance(snapshot.self.entity.appearance) : this.models.get('player')!.clone(true); + this.player.traverse(o => { if (o instanceof T.Mesh) { o.castShadow = true; o.receiveShadow = true; } }); + this.scene.add(this.player); this.playerAppearance = appearanceKey; + } this.houseView.update(snapshot,this.models.get('player')); this.projectiles.receive(snapshot.projectileVisuals??[]); if (!this.initialized) this.addChunks([], []); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 07957b1..79e416c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -33,6 +33,13 @@ The highest-risk requirements are: ## Implemented boundaries +The [creator detour](CREATOR-WORKSHOP.md) adds bounded, versioned procedural +appearance recipes. Go validates and persists character looks and admin-authored +visual presets; resource/mob definitions copy their selected recipes. Three.js +builds matching preview, world, housing, and export geometry, merging by material +and instancing repeated appearances. Appearance does not affect gameplay geometry +or stats. Full rigs, visible equipment, animation/audio, and CDN uploads remain. + Revised milestone 3 places a world portal and one shared housing entrance in each hub. Source-owner travel and housing transactions validate physical proximity and obstruction; key-targeted entry also validates the exact active carried key. Existing diff --git a/docs/CREATOR-WORKSHOP.md b/docs/CREATOR-WORKSHOP.md new file mode 100644 index 0000000..0a6ca2c --- /dev/null +++ b/docs/CREATOR-WORKSHOP.md @@ -0,0 +1,112 @@ +# Creator detour: rounded fantasy models + +September 11 playable handoff. The user chose softer, rounded fantasy shapes. +This is a focused creator detour before revised milestone 4's reliability and +persistence work. It completes part of the presentation/customization foundation, +not the full original 4.5 or the account cosmetics milestone. + +## Where to find it + +- **New character:** choose **Create your look** before **Enter world**. Save the + draft, then enter the world to create that character with the selected appearance. +- **Existing living character:** open **Display settings → Character appearance**. + Saving changes only that character's appearance, including in housing. Cancel or + Escape discards the draft. Character-creation retries do not overwrite a look + already saved on the existing life. +- **Control → Content → Visual workshop:** create a named visual, rotate/zoom its + preview, adjust its form/proportions/colors, and publish it with a reason. The + server assigns its permanent ID. **Preview / create variation** starts another + editable design; it does not replace the published original. +- **Control → Content → Mobs:** create a mob or expand one and choose **Create + variation** to copy its gameplay settings. Select a saved visual or make a new + look inside the form. Existing behavior, attack, loot, level, and stat controls + still determine gameplay. Use **Worlds → Actions → Spawn mobs**, or publish a + mob spawn rule, to place the new definition. +- **Control → Content → Resources:** select Tree, Ore, or Herb as the resource + type, then edit the matching tree, rock, or plant visual. Saved compatible designs + are available in the library selector. Publish gathering settings and biomes as + usual. New definitions appear in unexplored generator-2 chunks; existing explored + layouts and legacy generator-1 resources keep their current models. +- **Download GLB** exports the current static model for external editing or a future + asset upload pipeline. The editable procedural recipe remains the source for + this creator. Downloading does not publish or spawn anything. + +## Included forms + +| Family | Forms | +| --- | --- | +| Character | Tousled hair, side swept, rounded bob, twin braids | +| Creature | Woodland fox, moss bear, moon rabbit, jelly sprite | +| Tree | Cloud canopy, layered evergreen, willow crown, blossom tree | +| Rock | River stones, boulder cluster, crystal bloom, mossy outcrop | +| Plant | Broadleaf herb, wildflowers, mushroom cluster, fern | + +Each family supports bounded height/build, feature size or density, three colors, +and a deterministic variation seed. New variation changes form/features while +keeping the selected palette. The preview supports mouse/touch orbit and zoom; +phone layouts stack the preview above the controls. + +## Ownership, durability, and rendering + +Appearance is a character-owned, version-1 presentation recipe. It survives travel, +revival, and restart with that life. Replacement starts without the previous life's +appearance. This is free base customization; account-bound cosmetic unlocks and +their transfer/drop/furniture rules remain a separate system. + +Go validates families, colors, seeds, and bounded numeric values. Players can save +only human appearances and only to their current living character's owning world; +anonymous, cross-origin, invalid, and in-transit/foreign-world edits are rejected. +Appearance changes use the existing fenced save path and do not change stats, +hitboxes, movement, daily usage, items, or progression. + +Visual library publication uses the existing admin catalog authorization, audit, +version conflict checks, and idempotent request handling. Resource/mob definitions +copy the selected recipe, so later library variations cannot silently change their +appearance. Library records are bounded to 1,024 and need no uploaded executable +content or external model fetches. A future generator version must retain support +for existing recipes rather than silently changing version 1. + +The same procedural mesh builder drives previews, export, characters, resources, +and mobs. Geometry is merged by material; repeated appearances use instance batches +whose buffers grow to their visible population. Inactive custom batches and closed +editor previews release geometry, materials, controls, and WebGL resources. Player +looks render in the world and housing; corpse loot keeps the existing corpse +presentation. No higher tested player capacity is claimed. + +## Manual playtest + +1. Customize a new traveler, enter, reload, and reopen appearance. Confirm the saved + form/colors match; Cancel and Escape should preserve the previous saved look. +2. Change an existing character's appearance. Check another player's view and a + house interior, then travel/reconnect. Stats, inventory, and daily time must stay + unchanged. Revival retains the look; replacement does not inherit it. +3. Publish a named visual. Reload Control, create a variation, and confirm the + original still exists. Download a GLB and inspect it in your preferred viewer. +4. Create a passive creature from a saved visual and spawn it nearby. Check its + appearance, targeting, combat, loot, and ordinary spawn/respawn behavior. +5. Create a tree/ore/herb resource with the appropriate visual and biome selection. + Visit unexplored chunks of a generator-2 world; gather, revisit, and restart. + Explored old layouts should not change when publishing another design. +6. Try each family on a phone and desktop. Orbit/zoom, change forms, close/reopen + editors, and confirm all controls remain reachable. + +Typecheck, production build, generated-contract check, and Go suite are required. +Server coverage includes validation, catalog replay/reopen, resource compatibility, +appearance authorization and persistence, travel, revival, and replacement. Browser +spot checks verified character preview/in-game rendering, visual publication, +library reuse in mob publication, scenery previews, GLB export, and phone-width +layout. Routine Playwright authoring/runs remain deferred. + +## Still pending + +- Skeletal rigs, locomotion/action animations, equipment attachment sockets and + visible equipped gear, sound hooks, LODs, and production asset optimization. +- Freeform mesh/part editing, arbitrary model imports, additional faces/body parts, + rig compatibility checks, and general decorative-object placement. Current + scenery is authored through the existing gathering resource system. +- Object storage/CDN upload and delivery, asset manifests/version retention, and + the larger Control/website redesign. GLB export is available now; CDN integration + is not required to use these procedural creators. +- Account cosmetic ownership/application and its established loss/transfer rules. +- The [reliability and persistence plan](../planning/RELIABILITY-AND-PERSISTENCE.md), + followed by the expanding-world milestones. This detour does not fix those issues. diff --git a/planning/Changes-Needed.md b/planning/Changes-Needed.md index 93ec381..a86e8ac 100644 --- a/planning/Changes-Needed.md +++ b/planning/Changes-Needed.md @@ -229,6 +229,12 @@ is the next milestone. ### September 11 reliability dependency update +**Creator detour:** the user requested a character creator and simple admin +mob/object variation tools before returning to the main engineering sequence, +with softer rounded fantasy shapes. See [Creator workshop](../docs/CREATOR-WORKSHOP.md) +for the implemented procedural creators and handoff. This does not renumber the +nine milestones or complete the full rigs/equipment/animation/audio scope. + Milestones 1–3 have implementation handoffs above. Milestone 4 now includes the storage work that must precede expanding worlds; it is no longer only a rules discussion. The [reliability issue register and persistence plan](RELIABILITY-AND-PERSISTENCE.md) diff --git a/planning/PLAYWRIGHT-TODO.md b/planning/PLAYWRIGHT-TODO.md index e2b6d2b..3de9f0f 100644 --- a/planning/PLAYWRIGHT-TODO.md +++ b/planning/PLAYWRIGHT-TODO.md @@ -1,5 +1,10 @@ # Deferred Playwright coverage +- [ ] Creator: new/existing character appearance save/cancel, reload/travel/housing, + visual library publishing/reuse, mob/resource variants, GLB export, phone layout, + and cleanup after repeatedly opening/closing previews. See + [Creator workshop](../docs/CREATOR-WORKSHOP.md) for manual checks. + The user will manually test each milestone after commit/push. New automated Playwright tests and routine local suite runs are deferred to conserve resources. Keep existing tests; this decision does not modify CI, required type/build checks, diff --git a/planning/SYSTEMS-ROADMAP.md b/planning/SYSTEMS-ROADMAP.md index f666151..efcef6e 100644 --- a/planning/SYSTEMS-ROADMAP.md +++ b/planning/SYSTEMS-ROADMAP.md @@ -16,6 +16,12 @@ See the [eleven-issue register and resolution plan](RELIABILITY-AND-PERSISTENCE. The existing owner/lease/revision model stays; full-world JSON persistence is the part to replace. This planning update does not implement those repairs. +**Creator detour:** [rounded fantasy creators](../docs/CREATOR-WORKSHOP.md) now +provide character appearance, a reusable admin visual library, and visual editing +for new mobs/resources with GLB export. The user requested this detour before +returning to revised milestone 4. Original 4.5's skeletal rigs, visible equipment, +animations, and sound remain pending; account cosmetics remain revised milestone 7. + Draft for discussion, 2026-09-08. This document organizes requested work; it does not authorize gameplay implementation or finalize the open decisions below. Existing behavior is described in `docs/ARCHITECTURE.md` and `docs/PROGRESSION.md`. diff --git a/schemas/protocol.json b/schemas/protocol.json index 46891a1..620a1ad 100644 --- a/schemas/protocol.json +++ b/schemas/protocol.json @@ -95,6 +95,7 @@ "ContentCatalog": { "type": "object", "additionalProperties": false, "properties": { + "visuals": {"type": "array", "items": {"$ref": "#/definitions/VisualPreset"}}, "version": {"type": "integer"}, "titles": {"type": "array", "items": {"$ref": "#/definitions/TitleDefinition"}}, "items": {"type": "array", "items": {"$ref": "#/definitions/ItemDefinition"}}, @@ -113,6 +114,7 @@ "ContentChange": { "type": "object", "additionalProperties": false, "properties": { + "visual": {"$ref": "#/definitions/VisualPresetDraft"}, "id": {"type": "string"}, "expectedVersion": {"type": "integer"}, "op": {"type": "string"}, @@ -203,9 +205,105 @@ }, "required": ["op", "seq", "x", "z", "target", "slot"] }, + "Appearance": { + "type": "object", + "additionalProperties": false, + "properties": { + "version": { + "type": "integer" + }, + "family": { + "type": "string" + }, + "variant": { + "type": "integer" + }, + "seed": { + "type": "integer" + }, + "height": { + "type": "number" + }, + "width": { + "type": "number" + }, + "detail": { + "type": "number" + }, + "primary": { + "type": "string" + }, + "secondary": { + "type": "string" + }, + "accent": { + "type": "string" + } + }, + "required": [ + "version", + "family", + "variant", + "seed", + "height", + "width", + "detail", + "primary", + "secondary", + "accent" + ] + }, + "VisualPreset": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "appearance": { + "$ref": "#/definitions/Appearance" + } + }, + "required": [ + "id", + "name", + "description", + "appearance" + ] + }, + "VisualPresetDraft": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "appearance": { + "$ref": "#/definitions/Appearance" + } + }, + "required": [ + "name", + "description", + "appearance" + ] + }, "Entity": { "type": "object", "additionalProperties": false, "properties": { + "appearance": {"$ref": "#/definitions/Appearance"}, "id": {"type": "string"}, "kind": {"type": "string"}, "name": {"type": "string"}, @@ -405,6 +503,7 @@ "ResourceDefinition": { "type": "object", "additionalProperties": false, "properties": { + "appearance": {"$ref": "#/definitions/Appearance"}, "id": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}, @@ -424,6 +523,7 @@ "ResourceDefinitionDraft": { "type": "object", "additionalProperties": false, "properties": { + "appearance": {"$ref": "#/definitions/Appearance"}, "id": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}, @@ -626,6 +726,7 @@ "MobDefinition": { "type": "object", "additionalProperties": false, "properties": { + "appearance": {"$ref": "#/definitions/Appearance"}, "id": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}, @@ -648,6 +749,7 @@ "MobDefinitionDraft": { "type": "object", "additionalProperties": false, "properties": { + "appearance": {"$ref": "#/definitions/Appearance"}, "id": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}, diff --git a/server/content/appearance.go b/server/content/appearance.go new file mode 100644 index 0000000..8d0e5d8 --- /dev/null +++ b/server/content/appearance.go @@ -0,0 +1,48 @@ +package content + +import ( + p "aeternalis/server/internal/protocol" + "fmt" + "regexp" + "slices" +) + +// Appearance is a bounded, versioned presentation recipe. It never changes combat +// radius, collision, movement speed, or any character/creature stats. +type Appearance = p.Appearance + +type VisualPreset struct { + ID string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + Appearance Appearance `json:"appearance"` +} + +var appearanceColor = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`) + +func ValidateAppearance(a *Appearance, families ...string) error { + if a == nil { + return nil + } // Existing worlds retain their original models. + if !slices.Contains(families, a.Family) || a.Version != 1 || a.Variant < 0 || a.Variant > 3 || a.Seed < 1 || a.Seed > 65535 || !finiteRange(a.Height, .75, 1.25) || !finiteRange(a.Width, .75, 1.25) || !finiteRange(a.Detail, 0, 1) || !appearanceColor.MatchString(a.Primary) || !appearanceColor.MatchString(a.Secondary) || !appearanceColor.MatchString(a.Accent) { + return fmt.Errorf("invalid appearance: choose a supported form, bounded proportions, and six-digit colors") + } + return nil +} + +func (c Catalog) validateVisuals() error { + if len(c.Visuals) > 1024 { + return fmt.Errorf("visual library is full") + } + seen := map[string]bool{} + for _, v := range c.Visuals { + if !titleID.MatchString(v.ID) || len(v.Name) < 1 || len(v.Name) > 80 || len(v.Description) > 500 || seen[v.ID] { + return fmt.Errorf("invalid visual identity") + } + if err := ValidateAppearance(&v.Appearance, "human", "creature", "tree", "rock", "plant"); err != nil { + return err + } + seen[v.ID] = true + } + return nil +} diff --git a/server/content/appearance_test.go b/server/content/appearance_test.go new file mode 100644 index 0000000..453fc6b --- /dev/null +++ b/server/content/appearance_test.go @@ -0,0 +1,25 @@ +package content + +import ( + "math" + "testing" +) + +func TestAppearanceValidation(t *testing.T) { + base := Appearance{Version: 1, Family: "human", Variant: 0, Seed: 42, Height: 1, Width: 1, Detail: .5, Primary: "#d8a582", Secondary: "#493947", Accent: "#578f8b"} + if err := ValidateAppearance(&base, "human"); err != nil { + t.Fatal(err) + } + for _, mutate := range []func(*Appearance){ + func(a *Appearance) { a.Family = "tree" }, func(a *Appearance) { a.Version = 2 }, + func(a *Appearance) { a.Height = 100 }, func(a *Appearance) { a.Width = math.NaN() }, + func(a *Appearance) { a.Detail = math.Inf(1) }, func(a *Appearance) { a.Variant = 4 }, + func(a *Appearance) { a.Seed = 0 }, func(a *Appearance) { a.Primary = "url(bad)" }, + } { + v := base + mutate(&v) + if ValidateAppearance(&v, "human") == nil { + t.Fatal("invalid appearance accepted", v) + } + } +} diff --git a/server/content/combat.go b/server/content/combat.go index 411bfe4..c00cece 100644 --- a/server/content/combat.go +++ b/server/content/combat.go @@ -51,22 +51,23 @@ type LootTable struct { Entries []LootEntry `json:"entries" yaml:"entries"` } type MobDefinition struct { - ID string `json:"id" yaml:"id"` - Name string `json:"name" yaml:"name"` - Description string `json:"description" yaml:"description"` - Model string `json:"model" yaml:"model"` - Behavior string `json:"behavior" yaml:"behavior"` - Level int64 `json:"level" yaml:"level"` - HP float64 `json:"hp" yaml:"hp"` - Damage float64 `json:"damage" yaml:"damage"` - Defence float64 `json:"defence" yaml:"defence"` - Speed float64 `json:"speed" yaml:"speed"` - AggroRange float64 `json:"aggroRange" yaml:"aggroRange"` - LeashRange float64 `json:"leashRange" yaml:"leashRange"` - ScalePerDay float64 `json:"scalePerDay" yaml:"scalePerDay"` - XP int64 `json:"xp" yaml:"xp"` - AttackID string `json:"attackId" yaml:"attackId"` - LootID string `json:"lootId" yaml:"lootId"` + Appearance *Appearance `json:"appearance,omitempty" yaml:"appearance,omitempty"` + ID string `json:"id" yaml:"id"` + Name string `json:"name" yaml:"name"` + Description string `json:"description" yaml:"description"` + Model string `json:"model" yaml:"model"` + Behavior string `json:"behavior" yaml:"behavior"` + Level int64 `json:"level" yaml:"level"` + HP float64 `json:"hp" yaml:"hp"` + Damage float64 `json:"damage" yaml:"damage"` + Defence float64 `json:"defence" yaml:"defence"` + Speed float64 `json:"speed" yaml:"speed"` + AggroRange float64 `json:"aggroRange" yaml:"aggroRange"` + LeashRange float64 `json:"leashRange" yaml:"leashRange"` + ScalePerDay float64 `json:"scalePerDay" yaml:"scalePerDay"` + XP int64 `json:"xp" yaml:"xp"` + AttackID string `json:"attackId" yaml:"attackId"` + LootID string `json:"lootId" yaml:"lootId"` } type MobSpawn struct { ID string `json:"id" yaml:"id"` @@ -168,6 +169,9 @@ func (c Catalog) validateCombat() error { } } for _, m := range v.Mobs { + if err := ValidateAppearance(m.Appearance, "creature", "human"); err != nil { + return err + } if !identity(m.ID, m.Name, m.Description) || !slices.Contains([]string{"sentinel", "boss"}, m.Model) || !slices.Contains([]string{"aggressive", "guard", "passive"}, m.Behavior) || m.Level < 1 || m.Level > 10000 || !finiteRange(m.HP, 1, 1000000) || !finiteRange(m.Damage, 0, 100000) || !finiteRange(m.Defence, 0, 100000) || !finiteRange(m.Speed, .1, 30) || !finiteRange(m.AggroRange, 1, 128) || !finiteRange(m.LeashRange, m.AggroRange, 512) || !finiteRange(m.ScalePerDay, 0, 10) || m.XP < 0 || m.XP > 1000000000 || !attacks[m.AttackID] || (m.LootID != "" && !loot[m.LootID]) { return fmt.Errorf("invalid mob %q or missing attack/loot reference", m.ID) } diff --git a/server/content/gathering.go b/server/content/gathering.go index 9dfb77d..19f15a2 100644 --- a/server/content/gathering.go +++ b/server/content/gathering.go @@ -16,19 +16,20 @@ type GatheringSkill struct { MaxLevel int64 `json:"maxLevel" yaml:"maxLevel"` } type ResourceDefinition struct { - ID string `json:"id" yaml:"id"` - Name string `json:"name" yaml:"name"` - Description string `json:"description" yaml:"description"` - SkillID string `json:"skillId" yaml:"skillId"` - Model string `json:"model" yaml:"model"` - Output string `json:"output" yaml:"output"` - RequiredLevel int64 `json:"requiredLevel" yaml:"requiredLevel"` - Amount int64 `json:"amount" yaml:"amount"` - XP int64 `json:"xp" yaml:"xp"` - Seconds float64 `json:"seconds" yaml:"seconds"` - RespawnSeconds float64 `json:"respawnSeconds" yaml:"respawnSeconds"` - Density int64 `json:"density" yaml:"density"` - Biomes []string `json:"biomes" yaml:"biomes"` + Appearance *Appearance `json:"appearance,omitempty" yaml:"appearance,omitempty"` + ID string `json:"id" yaml:"id"` + Name string `json:"name" yaml:"name"` + Description string `json:"description" yaml:"description"` + SkillID string `json:"skillId" yaml:"skillId"` + Model string `json:"model" yaml:"model"` + Output string `json:"output" yaml:"output"` + RequiredLevel int64 `json:"requiredLevel" yaml:"requiredLevel"` + Amount int64 `json:"amount" yaml:"amount"` + XP int64 `json:"xp" yaml:"xp"` + Seconds float64 `json:"seconds" yaml:"seconds"` + RespawnSeconds float64 `json:"respawnSeconds" yaml:"respawnSeconds"` + Density int64 `json:"density" yaml:"density"` + Biomes []string `json:"biomes" yaml:"biomes"` } type BiomeDefinition struct { Revision int64 `json:"revision,omitempty" yaml:"revision"` @@ -121,6 +122,9 @@ func (g GatheringContent) Validate() error { biomes[b.ID] = true } for _, r := range g.Resources { + if err := ValidateAppearance(r.Appearance, map[string]string{"tree": "tree", "ore": "rock", "herb": "plant"}[r.Model]); err != nil { + return err + } if !identity(r.ID, r.Name, r.Description) || !skills[r.SkillID] || !slices.Contains([]string{"tree", "ore", "herb"}, r.Model) || !slices.Contains([]string{"wood", "ore", "herb", "self"}, r.Output) || r.RequiredLevel < 1 || r.RequiredLevel > 10000 || r.Amount < 1 || r.Amount > 1000 || r.XP < 0 || r.XP > 1000000 || !finiteRange(r.Seconds, 0.1, 3600) || !finiteRange(r.RespawnSeconds, 1, 604800) || r.Density < 0 || r.Density > 32 || len(r.Biomes) < 1 || len(r.Biomes) > 32 { return fmt.Errorf("invalid resource %q", r.ID) } diff --git a/server/content/stats.go b/server/content/stats.go index 954c133..3326e26 100644 --- a/server/content/stats.go +++ b/server/content/stats.go @@ -50,6 +50,7 @@ type ItemDefinition struct { Modifiers []StatModifier `json:"modifiers" yaml:"modifiers"` } type Catalog struct { + Visuals []VisualPreset `json:"visuals,omitempty"` HousingVersion int `json:"housingVersion,omitempty"` Building *BuildingContent `json:"building,omitempty"` Powers *PowerContent `json:"powers,omitempty"` @@ -145,6 +146,9 @@ func (item ItemDefinition) Validate() error { return ValidateModifiers(item.Modifiers) } func (c Catalog) Validate() error { + if err := c.validateVisuals(); err != nil { + return err + } if e := c.validateBuilding(); e != nil { return e } diff --git a/server/internal/game/appearance_test.go b/server/internal/game/appearance_test.go new file mode 100644 index 0000000..5b23769 --- /dev/null +++ b/server/internal/game/appearance_test.go @@ -0,0 +1,36 @@ +package game + +import ( + p "aeternalis/server/internal/protocol" + "encoding/json" + "testing" +) + +func TestAppearanceRestartAndReplacement(t *testing.T) { + w, c := fixture(t) + a := p.Appearance{Version: 1, Family: "human", Variant: 1, Seed: 42, Height: 1, Width: 1, Detail: .5, Primary: "#d8a582", Secondary: "#493947", Accent: "#578f8b"} + c.View.Entity.Appearance = &a + raw, err := json.Marshal(w) + if err != nil { + t.Fatal(err) + } + var restored World + if err = json.Unmarshal(raw, &restored); err != nil { + t.Fatal(err) + } + if err = restored.Restore(w.now); err != nil { + t.Fatal(err) + } + life := restored.Characters[c.View.Entity.ID] + if life.View.Entity.Appearance == nil || *life.View.Entity.Appearance != a { + t.Fatal("appearance lost on restart") + } + restored.kill(life, "test replacement") + replacement, err := restored.Join(c.Account, "Replacement") + if err != nil { + t.Fatal(err) + } + if replacement.View.Entity.ID == life.View.Entity.ID || replacement.View.Entity.Appearance != nil { + t.Fatal("replacement inherited prior life's appearance") + } +} diff --git a/server/internal/game/biomes.go b/server/internal/game/biomes.go index 42612f2..54b8f12 100644 --- a/server/internal/game/biomes.go +++ b/server/internal/game/biomes.go @@ -77,14 +77,14 @@ func (t *Terrain) Chunk(x, z int) p.Chunk { if math.Hypot(px, pz) > t.B.WorldRadius || math.Hypot(px, pz) < 25 { continue } - c.Resources = append(c.Resources, p.Entity{ID: fmt.Sprintf("r:%d:%d:%s:%d", x, z, r.ID, i), Kind: r.Model, Name: r.Name, ResourceID: stringPtr(r.ID), SkillID: stringPtr(r.SkillID), RequiredLevel: &r.RequiredLevel, Position: t.Position(px, pz), HP: 1, MaxHP: 1, State: "available"}) + c.Resources = append(c.Resources, p.Entity{ID: fmt.Sprintf("r:%d:%d:%s:%d", x, z, r.ID, i), Kind: r.Model, Appearance: r.Appearance, Name: r.Name, ResourceID: stringPtr(r.ID), SkillID: stringPtr(r.SkillID), RequiredLevel: &r.RequiredLevel, Position: t.Position(px, pz), HP: 1, MaxHP: 1, State: "available"}) } } if x == 0 && z == 0 { for i, id := range []string{"tree", "ore", "herb"} { for _, r := range t.B.Gathering.Resources { if r.ID == id { - c.Resources = append(c.Resources, p.Entity{ID: "arrival:" + id, Kind: r.Model, Name: r.Name, ResourceID: stringPtr(id), SkillID: stringPtr(r.SkillID), RequiredLevel: &r.RequiredLevel, Position: t.Position(12+float64(i)*5, 12), HP: 1, MaxHP: 1, State: "available"}) + c.Resources = append(c.Resources, p.Entity{ID: "arrival:" + id, Kind: r.Model, Appearance: r.Appearance, Name: r.Name, ResourceID: stringPtr(id), SkillID: stringPtr(r.SkillID), RequiredLevel: &r.RequiredLevel, Position: t.Position(12+float64(i)*5, 12), HP: 1, MaxHP: 1, State: "available"}) } } } diff --git a/server/internal/game/mobs.go b/server/internal/game/mobs.go index 8f5089a..8c02db8 100644 --- a/server/internal/game/mobs.go +++ b/server/internal/game/mobs.go @@ -45,7 +45,7 @@ func (w *World) newMob(id string, d content.MobDefinition, pos p.Vec3, respawn f scale := float64(d.Level) * (1 + w.Age()/86400*d.ScalePerDay) hp := d.HP * scale home := pos - m := &Mob{Entity: p.Entity{ID: id, Kind: "mob", Model: stringPtr(d.Model), Name: d.Name, Position: pos, HP: hp, MaxHP: hp, State: "alive"}, Definition: &d, Home: &home, HomeX: ChunkCoord(pos.X, w.Balance.ChunkSize), HomeZ: ChunkCoord(pos.Z, w.Balance.ChunkSize), RespawnDelay: respawn, Power: d.Damage * scale} + m := &Mob{Entity: p.Entity{ID: id, Kind: "mob", Model: stringPtr(d.Model), Appearance: d.Appearance, Name: d.Name, Position: pos, HP: hp, MaxHP: hp, State: "alive"}, Definition: &d, Home: &home, HomeX: ChunkCoord(pos.X, w.Balance.ChunkSize), HomeZ: ChunkCoord(pos.Z, w.Balance.ChunkSize), RespawnDelay: respawn, Power: d.Damage * scale} for _, a := range w.Balance.Combat.Attacks { if a.ID == d.AttackID { m.Attack = protocolAttack(a) diff --git a/server/internal/game/powers_test.go b/server/internal/game/powers_test.go index 21cee39..9481786 100644 --- a/server/internal/game/powers_test.go +++ b/server/internal/game/powers_test.go @@ -1,6 +1,7 @@ package game import ( + p "aeternalis/server/internal/protocol" "encoding/json" "reflect" "testing" @@ -152,6 +153,8 @@ func TestCastingInterruptMissAndWeaponUnlock(t *testing.T) { func TestCorpseRevivalKeepsLootAndDailyBudget(t *testing.T) { w, c := fixture(t) + appearance := p.Appearance{Version: 1, Family: "human", Variant: 2, Seed: 42, Height: 1, Width: 1, Detail: .5, Primary: "#d8a582", Secondary: "#493947", Accent: "#578f8b"} + c.View.Entity.Appearance = &appearance rescuer, e := w.Join("rescuer", "Rescuer") if e != nil { t.Fatal(e) @@ -179,6 +182,9 @@ func TestCorpseRevivalKeepsLootAndDailyBudget(t *testing.T) { if len(c.View.Inventory) != 0 || len(c.View.Items) != 0 || c.DailySeconds != 123 || rescuer.View.Inventory["wood"] != 7 || rescuer.View.Inventory["revival_stone"] != 1 { t.Fatal("revival recreated loot or daily time") } + if !reflect.DeepEqual(c.View.Entity.Appearance, &appearance) { + t.Fatal("revival changed character appearance") + } if _, e = w.Revive(rescuer, corpse, "item"); e == nil || rescuer.View.Inventory["revival_stone"] != 1 { t.Fatal("revived twice") } diff --git a/server/internal/protocol/generated.go b/server/internal/protocol/generated.go index 09288bc..355e5c8 100644 --- a/server/internal/protocol/generated.go +++ b/server/internal/protocol/generated.go @@ -29,6 +29,7 @@ type ContentCatalog struct { Stats ContentStatsRules `json:"stats"` Titles []TitleDefinition `json:"titles"` Version int64 `json:"version"` + Visuals []VisualPreset `json:"visuals,omitempty"` } type BuildingContent struct { @@ -94,22 +95,36 @@ type LootEntry struct { } type MobDefinition struct { - AggroRange float64 `json:"aggroRange"` - AttackID string `json:"attackId"` - Behavior string `json:"behavior"` - Damage float64 `json:"damage"` - Defence float64 `json:"defence"` - Description string `json:"description"` - HP float64 `json:"hp"` - ID string `json:"id"` - LeashRange float64 `json:"leashRange"` - Level int64 `json:"level"` - LootID string `json:"lootId"` - Model string `json:"model"` - Name string `json:"name"` - ScalePerDay float64 `json:"scalePerDay"` - Speed float64 `json:"speed"` - XP int64 `json:"xp"` + AggroRange float64 `json:"aggroRange"` + Appearance *Appearance `json:"appearance,omitempty"` + AttackID string `json:"attackId"` + Behavior string `json:"behavior"` + Damage float64 `json:"damage"` + Defence float64 `json:"defence"` + Description string `json:"description"` + HP float64 `json:"hp"` + ID string `json:"id"` + LeashRange float64 `json:"leashRange"` + Level int64 `json:"level"` + LootID string `json:"lootId"` + Model string `json:"model"` + Name string `json:"name"` + ScalePerDay float64 `json:"scalePerDay"` + Speed float64 `json:"speed"` + XP int64 `json:"xp"` +} + +type Appearance struct { + Accent string `json:"accent"` + Detail float64 `json:"detail"` + Family string `json:"family"` + Height float64 `json:"height"` + Primary string `json:"primary"` + Secondary string `json:"secondary"` + Seed int64 `json:"seed"` + Variant int64 `json:"variant"` + Version int64 `json:"version"` + Width float64 `json:"width"` } type MobSpawn struct { @@ -224,19 +239,20 @@ type ItemUseEffect struct { } type ResourceDefinition struct { - Amount int64 `json:"amount"` - Biomes []string `json:"biomes"` - Density int64 `json:"density"` - Description string `json:"description"` - ID string `json:"id"` - Model string `json:"model"` - Name string `json:"name"` - Output string `json:"output"` - RequiredLevel int64 `json:"requiredLevel"` - RespawnSeconds float64 `json:"respawnSeconds"` - Seconds float64 `json:"seconds"` - SkillID string `json:"skillId"` - XP int64 `json:"xp"` + Amount int64 `json:"amount"` + Appearance *Appearance `json:"appearance,omitempty"` + Biomes []string `json:"biomes"` + Density int64 `json:"density"` + Description string `json:"description"` + ID string `json:"id"` + Model string `json:"model"` + Name string `json:"name"` + Output string `json:"output"` + RequiredLevel int64 `json:"requiredLevel"` + RespawnSeconds float64 `json:"respawnSeconds"` + Seconds float64 `json:"seconds"` + SkillID string `json:"skillId"` + XP int64 `json:"xp"` } type ItemDefinition struct { @@ -340,6 +356,13 @@ type TitleEffects struct { MoveSpeed float64 `json:"moveSpeed"` } +type VisualPreset struct { + Appearance Appearance `json:"appearance"` + Description string `json:"description"` + ID string `json:"id"` + Name string `json:"name"` +} + type ContentChange struct { Attack *CombatAttackDraft `json:"attack,omitempty"` Biome *BiomeDefinitionDraft `json:"biome,omitempty"` @@ -367,6 +390,7 @@ type ContentChange struct { Stats *ContentStatsRules `json:"stats,omitempty"` TargetID *string `json:"targetId,omitempty"` Title *TitleDraft `json:"title,omitempty"` + Visual *VisualPresetDraft `json:"visual,omitempty"` Weapon *GatheringSkillDraft `json:"weapon,omitempty"` } @@ -481,22 +505,23 @@ type LootTableDraft struct { } type MobDefinitionDraft struct { - AggroRange float64 `json:"aggroRange"` - AttackID string `json:"attackId"` - Behavior string `json:"behavior"` - Damage float64 `json:"damage"` - Defence float64 `json:"defence"` - Description string `json:"description"` - HP float64 `json:"hp"` - ID *string `json:"id,omitempty"` - LeashRange float64 `json:"leashRange"` - Level int64 `json:"level"` - LootID string `json:"lootId"` - Model string `json:"model"` - Name string `json:"name"` - ScalePerDay float64 `json:"scalePerDay"` - Speed float64 `json:"speed"` - XP int64 `json:"xp"` + AggroRange float64 `json:"aggroRange"` + Appearance *Appearance `json:"appearance,omitempty"` + AttackID string `json:"attackId"` + Behavior string `json:"behavior"` + Damage float64 `json:"damage"` + Defence float64 `json:"defence"` + Description string `json:"description"` + HP float64 `json:"hp"` + ID *string `json:"id,omitempty"` + LeashRange float64 `json:"leashRange"` + Level int64 `json:"level"` + LootID string `json:"lootId"` + Model string `json:"model"` + Name string `json:"name"` + ScalePerDay float64 `json:"scalePerDay"` + Speed float64 `json:"speed"` + XP int64 `json:"xp"` } type PowerDraft struct { @@ -530,19 +555,20 @@ type RequirementSetDraft struct { } type ResourceDefinitionDraft struct { - Amount int64 `json:"amount"` - Biomes []string `json:"biomes"` - Density int64 `json:"density"` - Description string `json:"description"` - ID *string `json:"id,omitempty"` - Model string `json:"model"` - Name string `json:"name"` - Output string `json:"output"` - RequiredLevel int64 `json:"requiredLevel"` - RespawnSeconds float64 `json:"respawnSeconds"` - Seconds float64 `json:"seconds"` - SkillID string `json:"skillId"` - XP int64 `json:"xp"` + Amount int64 `json:"amount"` + Appearance *Appearance `json:"appearance,omitempty"` + Biomes []string `json:"biomes"` + Density int64 `json:"density"` + Description string `json:"description"` + ID *string `json:"id,omitempty"` + Model string `json:"model"` + Name string `json:"name"` + Output string `json:"output"` + RequiredLevel int64 `json:"requiredLevel"` + RespawnSeconds float64 `json:"respawnSeconds"` + Seconds float64 `json:"seconds"` + SkillID string `json:"skillId"` + XP int64 `json:"xp"` } type MobSpawnDraft struct { @@ -568,6 +594,13 @@ type TitleDraft struct { Scope string `json:"scope"` } +type VisualPresetDraft struct { + Appearance Appearance `json:"appearance"` + Description string `json:"description"` + ID *string `json:"id,omitempty"` + Name string `json:"name"` +} + type ContentPreview struct { BasedOnVersion int64 `json:"basedOnVersion"` ProposedVersion int64 `json:"proposedVersion"` @@ -635,21 +668,22 @@ type HouseSummary struct { } type Entity struct { - Depth *float64 `json:"depth,omitempty"` - HP float64 `json:"hp"` - Height *float64 `json:"height,omitempty"` - ID string `json:"id"` - Kind string `json:"kind"` - MaxHP float64 `json:"maxHp"` - Model *string `json:"model,omitempty"` - Name string `json:"name"` - Position Vec3 `json:"position"` - Radius *float64 `json:"radius,omitempty"` - RequiredLevel *int64 `json:"requiredLevel,omitempty"` - ResourceID *string `json:"resourceId,omitempty"` - SkillID *string `json:"skillId,omitempty"` - State string `json:"state"` - Width *float64 `json:"width,omitempty"` + Appearance *Appearance `json:"appearance,omitempty"` + Depth *float64 `json:"depth,omitempty"` + HP float64 `json:"hp"` + Height *float64 `json:"height,omitempty"` + ID string `json:"id"` + Kind string `json:"kind"` + MaxHP float64 `json:"maxHp"` + Model *string `json:"model,omitempty"` + Name string `json:"name"` + Position Vec3 `json:"position"` + Radius *float64 `json:"radius,omitempty"` + RequiredLevel *int64 `json:"requiredLevel,omitempty"` + ResourceID *string `json:"resourceId,omitempty"` + SkillID *string `json:"skillId,omitempty"` + State string `json:"state"` + Width *float64 `json:"width,omitempty"` } type Vec3 struct { diff --git a/server/internal/store/catalog.go b/server/internal/store/catalog.go index 77c4957..c02d5c6 100644 --- a/server/internal/store/catalog.go +++ b/server/internal/store/catalog.go @@ -17,6 +17,7 @@ var ErrCatalogInvalid = errors.New("invalid catalog change") var catalogRequestID = regexp.MustCompile(`^[a-f0-9-]{32,36}$`) type CatalogChange struct { + Visual *content.VisualPreset `json:"visual,omitempty"` Building *content.BuildingDefinition `json:"building,omitempty"` Power *content.PowerDefinition `json:"power,omitempty"` Weapon *content.GatheringSkill `json:"weapon,omitempty"` @@ -54,6 +55,9 @@ type CatalogResult struct { // Explicit definition IDs are reserved for trusted seed/import code. Browser // publications omit them; the server assigns an ID after resolving request replay. func (c CatalogChange) HasDefinitionID() bool { + if c.Visual != nil && c.Visual.ID != "" { + return true + } return (c.Building != nil && c.Building.ID != "") || (c.Power != nil && c.Power.ID != "") || (c.Weapon != nil && c.Weapon.ID != "") || (c.CraftRecipe != nil && c.CraftRecipe.ID != "") || (c.CraftProfession != nil && c.CraftProfession.ID != "") || (c.CraftMaterial != nil && c.CraftMaterial.ID != "") || (c.Attack != nil && c.Attack.ID != "") || (c.Mob != nil && c.Mob.ID != "") || (c.Loot != nil && c.Loot.ID != "") || (c.Spawn != nil && c.Spawn.ID != "") || (c.GatheringSkill != nil && c.GatheringSkill.ID != "") || (c.Resource != nil && c.Resource.ID != "") || (c.Biome != nil && c.Biome.ID != "") || (c.Consumable != nil && c.Consumable.ID != "") || (c.Title != nil && c.Title.ID != "") || (c.Item != nil && c.Item.ID != "") || (c.RequirementSet != nil && c.RequirementSet.ID != "") || (c.EffectSet != nil && c.EffectSet.ID != "") } @@ -196,12 +200,17 @@ func (c CatalogChange) validate() error { } valid := false count := 0 + if c.Visual != nil { + count++ + } for _, present := range []bool{c.Building != nil, c.Power != nil, c.Weapon != nil, c.CraftRecipe != nil, c.CraftProfession != nil, c.CraftMaterial != nil, c.CraftRules != nil, c.Attack != nil, c.Mob != nil, c.Loot != nil, c.Spawn != nil, c.GatheringSkill != nil, c.Resource != nil, c.Biome != nil, c.Consumable != nil, c.Title != nil, c.Item != nil, c.Stats != nil, c.RequirementSet != nil, c.EffectSet != nil} { if present { count++ } } switch c.Op { + case "create-visual": + valid = c.Visual != nil case "create-building": valid = c.Building != nil case "create-power": diff --git a/server/internal/store/catalog_preview.go b/server/internal/store/catalog_preview.go index 6315f47..61617a8 100644 --- a/server/internal/store/catalog_preview.go +++ b/server/internal/store/catalog_preview.go @@ -35,6 +35,9 @@ func (d *DB) PreviewCatalog(ctx context.Context, change CatalogChange) (CatalogP } // Preview validates a provisional identity but does not reserve or expose it. if !change.HasDefinitionID() { + if resolved.Visual != nil { + resolved.Visual.ID = "" + } if resolved.Building != nil { resolved.Building.ID = "" } @@ -152,6 +155,14 @@ func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, str building := *c.Building c.Building = &building switch change.Op { + case "create-visual": + v := *change.Visual + if v.ID == "" { + v.ID = "visual_" + game.ID() + } + resolved.Visual = &v + c.Visuals = append(slices.Clone(c.Visuals), v) + target = v.ID case "create-building": v := *change.Building if v.ID == "" { diff --git a/server/internal/store/travel_test.go b/server/internal/store/travel_test.go index e825041..2b7dd74 100644 --- a/server/internal/store/travel_test.go +++ b/server/internal/store/travel_test.go @@ -64,6 +64,7 @@ func runTravelTests(t *testing.T, dsn string) { c.View.Experience = 7 c.View.StatPoints = 20 c.DailySeconds = 123 + c.View.Entity.Appearance = &content.Appearance{Version: 1, Family: "human", Variant: 2, Seed: 42, Height: 1, Width: 1, Detail: .5, Primary: "#d8a582", Secondary: "#493947", Accent: "#578f8b"} c.WorldsSurvived = 2 if e = source.AdminItems(c, "grant-item", "spear:1"); e != nil { t.Fatal(e) @@ -183,7 +184,7 @@ func runTravelTests(t *testing.T, dsn string) { if copies != 1 { t.Fatalf("arrival copies: %d", copies) } - if !reflect.DeepEqual(arrived.View.Powers, c.View.Powers) || !reflect.DeepEqual(arrived.View.Weapons, c.View.Weapons) || !reflect.DeepEqual(arrived.View.Items, c.View.Items) || !reflect.DeepEqual(arrived.View.Gathering, c.View.Gathering) || !reflect.DeepEqual(arrived.View.AllocatedStats, c.View.AllocatedStats) { + if !reflect.DeepEqual(arrived.View.Entity.Appearance, c.View.Entity.Appearance) || !reflect.DeepEqual(arrived.View.Powers, c.View.Powers) || !reflect.DeepEqual(arrived.View.Weapons, c.View.Weapons) || !reflect.DeepEqual(arrived.View.Items, c.View.Items) || !reflect.DeepEqual(arrived.View.Gathering, c.View.Gathering) || !reflect.DeepEqual(arrived.View.AllocatedStats, c.View.AllocatedStats) { t.Fatal("item identities or character progression changed during travel") } if arrived.View.Inventory["escape_stone"] != 1 || arrived.View.Inventory["wood"] != 31 || arrived.View.Level != 3 || arrived.View.Experience != 7 || arrived.View.StatPoints != 20 || arrived.View.Skills["combat"] != 29 || arrived.DailySeconds != 123 || arrived.WorldsSurvived != 2 || arrived.View.Entity.ID != id || !reflect.DeepEqual(arrived.View.Titles, c.View.Titles) { diff --git a/server/internal/store/visual_catalog_test.go b/server/internal/store/visual_catalog_test.go new file mode 100644 index 0000000..9b718ba --- /dev/null +++ b/server/internal/store/visual_catalog_test.go @@ -0,0 +1,70 @@ +package store + +import ( + "aeternalis/server/content" + "aeternalis/server/internal/game" + "context" + "path/filepath" + "testing" +) + +func TestVisualLibraryPublicationReplayAndResourceCompatibility(t *testing.T) { + ctx := context.Background() + dsn := "file:" + filepath.ToSlash(filepath.Join(t.TempDir(), "visual.db")) + db, err := Open(ctx, dsn) + if err != nil { + t.Fatal(err) + } + defer func() { db.Close() }() + c, err := db.Catalog(ctx) + if err != nil { + t.Fatal(err) + } + a := content.Appearance{Version: 1, Family: "tree", Variant: 3, Seed: 42, Height: 1, Width: 1, Detail: .5, Primary: "#80a77a", Secondary: "#785443", Accent: "#d8ae85"} + change := CatalogChange{ID: game.ID(), ExpectedVersion: c.Version, Op: "create-visual", Reason: "Create blossom design", Visual: &content.VisualPreset{Name: "Blossom", Appearance: a}} + preview, err := db.PreviewCatalog(ctx, change) + if err != nil || preview.Resolved.HasDefinitionID() { + t.Fatal("preview reserved identity", err) + } + result, err := db.PublishCatalog(ctx, "artist", change) + if err != nil || result.ID == "" { + t.Fatal(err) + } + retry, err := db.PublishCatalog(ctx, "artist", change) + if err != nil || retry != result { + t.Fatal("replay changed design identity", err) + } + if change.Visual.ID != "" { + t.Fatal("publication mutated submitted design") + } + if err = db.Close(); err != nil { + t.Fatal(err) + } + db, err = Open(ctx, dsn) + if err != nil { + t.Fatal(err) + } + c, err = db.Catalog(ctx) + if err != nil || len(c.Visuals) != 1 || c.Visuals[0].Appearance != a { + t.Fatal("visual not durable", err) + } + r := c.Gathering.Resources[0] + r.ID = "" + r.Name = "Blossom tree" + r.Model = "tree" + r.Appearance = &a + publication := CatalogChange{ID: game.ID(), ExpectedVersion: c.Version, Op: "create-resource", Reason: "Use reusable blossom design", Resource: &r} + if _, err = db.PublishCatalog(ctx, "artist", publication); err != nil { + t.Fatal(err) + } + c, err = db.Catalog(ctx) + if err != nil { + t.Fatal(err) + } + r.Model = "ore" + publication.ID = game.ID() + publication.ExpectedVersion = c.Version + if _, err = db.PublishCatalog(ctx, "artist", publication); err == nil { + t.Fatal("tree appearance assigned to ore") + } +} diff --git a/server/internal/transport/appearance.go b/server/internal/transport/appearance.go new file mode 100644 index 0000000..dba32f5 --- /dev/null +++ b/server/internal/transport/appearance.go @@ -0,0 +1,54 @@ +package transport + +import ( + "aeternalis/server/content" + p "aeternalis/server/internal/protocol" + "context" + "net/http" + "time" +) + +func (h *HTTP) appearanceRoutes(mux *http.ServeMux) { + mux.HandleFunc("POST /api/appearance", func(w http.ResponseWriter, r *http.Request) { + account, err := h.auth.account(r) + if err != nil { + fail(w, 401, "sign in required") + return + } + var appearance p.Appearance + if decode(w, r, &appearance) != nil || content.ValidateAppearance(&appearance, "human") != nil { + fail(w, 400, "invalid character appearance") + return + } + h.s.mu.Lock() + defer h.s.mu.Unlock() + if !h.s.ready.Load() { + fail(w, 503, "world unavailable") + return + } + c := h.s.world.ForAccount(account) + if c == nil || (c.View.Entity.State != "alive" && c.View.Entity.State != "eligible") { + fail(w, 409, "no living character in this world") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + active, err := h.auth.db.ActiveCharacter(ctx, account) + if err != nil { + fail(w, 503, "character registry unavailable") + return + } + if active == nil || active.WorldID != h.s.world.ID || active.ID != c.View.Entity.ID || active.State == "transit" { + fail(w, 409, "character belongs to another world or is traveling") + return + } + previous := c.View.Entity.Appearance + c.View.Entity.Appearance = &appearance + if err := h.s.persist(ctx, ""); err != nil { + c.View.Entity.Appearance = previous + fail(w, 503, "appearance could not be saved") + return + } + respond(w, 200, map[string]bool{"saved": true}) + }) +} diff --git a/server/internal/transport/appearance_test.go b/server/internal/transport/appearance_test.go new file mode 100644 index 0000000..47d5911 --- /dev/null +++ b/server/internal/transport/appearance_test.go @@ -0,0 +1,86 @@ +package transport + +import ( + "aeternalis/server/content" + "aeternalis/server/internal/game" + "aeternalis/server/internal/store" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestCharacterAppearanceOwnershipAndDurability(t *testing.T) { + ctx := context.Background() + db, err := store.Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "appearance.db"))) + if err != nil { + t.Fatal(err) + } + defer db.Close() + b, _ := content.Load() + world := game.New("appearance", 1, time.Now(), b) + lease, _, err := db.Acquire(ctx, world) + if err != nil { + t.Fatal(err) + } + svc := NewService(world, lease) + a := content.Appearance{Version: 1, Family: "human", Variant: 3, Seed: 42, Height: 1, Width: 1, Detail: .5, Primary: "#d8a582", Secondary: "#493947", Accent: "#578f8b"} + view, err := svc.join(ctx, "artist", "Artist", "", &a) + if err != nil { + t.Fatal(err) + } + if view.Entity.Appearance == nil || *view.Entity.Appearance != a { + t.Fatal("new character appearance missing") + } + other := a + other.Primary = "#ffffff" + if _, err = svc.join(ctx, "artist", "Artist", "", &other); err != nil { + t.Fatal(err) + } + if *world.ForAccount("artist").View.Entity.Appearance != a { + t.Fatal("join retry overwrote appearance") + } + auth, _ := NewAuth(ctx, db, true, "http://127.0.0.1", "", "", "") + server := httptest.NewServer(NewHTTP(svc, auth, t.TempDir(), nil).Handler()) + defer server.Close() + auth.base = server.URL + token := game.ID() + game.ID() + if err = db.CreateSession(ctx, hash(token), "artist"); err != nil { + t.Fatal(err) + } + request := func(value any, cookie, origin string) int { + t.Helper() + raw, _ := json.Marshal(value) + r, _ := http.NewRequest("POST", server.URL+"/api/appearance", strings.NewReader(string(raw))) + r.Header.Set("Origin", origin) + if cookie != "" { + r.AddCookie(&http.Cookie{Name: auth.cookieName(), Value: cookie}) + } + resp, err := server.Client().Do(r) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + return resp.StatusCode + } + if request(other, "", server.URL) != 401 || request(other, token, "https://elsewhere.example") != 403 { + t.Fatal("appearance auth boundary bypassed") + } + bad := other + bad.Family = "creature" + if request(bad, token, server.URL) != 400 { + t.Fatal("player could choose creature") + } + before := world.ForAccount("artist").View.Stats["movementSpeed"] + if request(other, token, server.URL) != 200 { + t.Fatal("appearance save rejected") + } + record, err := db.ActiveCharacter(ctx, "artist") + if err != nil || *record.Character.View.Entity.Appearance != other || record.Character.View.Stats["movementSpeed"] != before { + t.Fatal("appearance not durable or changed stats", err) + } +} diff --git a/server/internal/transport/http.go b/server/internal/transport/http.go index 9b82f49..3d07d34 100644 --- a/server/internal/transport/http.go +++ b/server/internal/transport/http.go @@ -103,6 +103,7 @@ func (h *HTTP) Handler() http.Handler { h.powerRoutes(mux) h.housingRoutes(mux) h.catalogRoutes(mux) + h.appearanceRoutes(mux) mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { if !h.s.ready.Load() { fail(w, 503, "world frozen") @@ -196,8 +197,9 @@ func (h *HTTP) Handler() http.Handler { return } var req struct { - Name string `json:"name"` - Passage string `json:"passage"` + Name string `json:"name"` + Passage string `json:"passage"` + Appearance *p.Appearance `json:"appearance,omitempty"` } if decode(w, r, &req) != nil { fail(w, 400, "invalid request") @@ -208,7 +210,7 @@ func (h *HTTP) Handler() http.Handler { fail(w, 400, "Name must be 2-24 letters, numbers, spaces, or hyphens.") return } - c, err := h.s.join(r.Context(), account, req.Name, req.Passage) + c, err := h.s.join(r.Context(), account, req.Name, req.Passage, req.Appearance) if err != nil { fail(w, 409, err.Error()) return diff --git a/server/internal/transport/service.go b/server/internal/transport/service.go index 02ddcc6..177b029 100644 --- a/server/internal/transport/service.go +++ b/server/internal/transport/service.go @@ -10,6 +10,7 @@ import ( "sync/atomic" "time" + "aeternalis/server/content" "aeternalis/server/internal/game" p "aeternalis/server/internal/protocol" "aeternalis/server/internal/store" @@ -126,7 +127,7 @@ func (s *Service) Stop(ctx context.Context) error { } return s.lease.Release(ctx) } -func (s *Service) join(ctx context.Context, account, name, claim string) (p.Character, error) { +func (s *Service) join(ctx context.Context, account, name, claim string, appearance ...*p.Appearance) (p.Character, error) { s.mu.Lock() defer s.mu.Unlock() if !s.ready.Load() { @@ -152,6 +153,14 @@ func (s *Service) join(ctx context.Context, account, name, claim string) (p.Char } } existing := s.world.ForAccount(account) + var chosen *p.Appearance + if len(appearance) > 0 && appearance[0] != nil { + if err := content.ValidateAppearance(appearance[0], "human"); err != nil { + return p.Character{}, err + } + copy := *appearance[0] + chosen = © + } if claim != "" { c, err = s.lease.DB.ReadPassage(ctx, claim, account) if err != nil { @@ -166,6 +175,9 @@ func (s *Service) join(ctx context.Context, account, name, claim string) (p.Char return p.Character{}, err } } + if existing == nil && chosen != nil { + c.View.Entity.Appearance = chosen + } if err = s.lease.Save(ctx, s.world, claim); err != nil { if errors.Is(err, store.ErrLivingCharacter) { if existing == nil {