Add rounded fantasy character and admin visual creators
This commit is contained in:
@@ -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}}
|
||||
@@ -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 = <K extends keyof HTMLElementTagNameMap>(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<string, HTMLInputElement>(), colors = new Map<string, HTMLInputElement>();
|
||||
const colorLabels = new Map<string, HTMLSpanElement>();
|
||||
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<string, string[]> = { 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<void>) {
|
||||
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);
|
||||
}
|
||||
@@ -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<string, string[]> = {
|
||||
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<string, string[]> = {
|
||||
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<string, T.BufferGeometry[]>();
|
||||
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(); }
|
||||
});
|
||||
}
|
||||
@@ -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<Catalog['gathering']>['
|
||||
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<string,string>={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'));
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
+10
-1
@@ -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);
|
||||
$<HTMLFormElement>('join-form').onsubmit = async event => {
|
||||
event.preventDefault(); const button = $<HTMLButtonElement>('join'); button.disabled = true;
|
||||
try { await api('/api/join', { name: $<HTMLInputElement>('name').value, passage: '' }); $<HTMLDialogElement>('arrival').close(); connect(); }
|
||||
try { await api('/api/join', { name: $<HTMLInputElement>('name').value, passage: '', appearance: draftAppearance }); $<HTMLDialogElement>('arrival').close(); connect(); }
|
||||
catch (e) { $('arrival-error').textContent = (e as Error).message; }
|
||||
finally { button.disabled = false; }
|
||||
};
|
||||
|
||||
@@ -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<string, Entity[]>();
|
||||
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([], []);
|
||||
|
||||
Reference in New Issue
Block a user