// Tune panel: per-model adjustments written into the converted VRM (convert/vrm_edit.py) — name, thumbnail,
// which expression drives each VRM preset and how strong, gaze range, SpringBone multipliers.
// Physics changes preview live; everything else is written on "Save" — or by itself before converting and when
// switching to another file, so edits aren't lost when "Save" is forgotten.
import { $, S, api, clone, errText, esc, num, presetLabel, t, toast } from './core.js';
import { loadModel, modelUrl, showPanel, viewer } from './preview.js';
export const T = {
fid: null, info: null, edits: {}, dirty: false,
open: { meta: true, expr: true, look: true, physics: true, chains: false }, // collapsible sections (kept across models)
};
// three-vrm loads VRM 0.x presets under their 1.0 names
const V0_TO_V1 = { a: 'aa', i: 'ih', u: 'ou', e: 'ee', o: 'oh', joy: 'happy', sorrow: 'sad', fun: 'relaxed', blink_l: 'blinkLeft', blink_r: 'blinkRight' };
// which model of the file a VRM / preview URL or file name is (vrm_edit.model_key): thumbnails are kept per model
export const modelOf = (s) => (s ? decodeURIComponent(s.split('?')[0].split('/').pop()).replace(/\.[^.]+$/, '') : null);
// switching to another file: save the unsaved tune edits of the one on screen (in the background; that file's
// VRM isn't on screen any more). Edits are per file, so other outputs of the same file keep them unsaved.
export function leaveTune(id) {
if (!T.dirty || !T.fid || T.fid === id) return true;
const fid = T.fid, edits = clone(T.edits), f = S.files.find((x) => x.id === fid);
T.dirty = false;
api('/api/tune/save', { id: fid, edits }).then((r) =>
toast(r.error ? errText(r.error, r.error_en) : t('tuneAutoSaved', { name: f ? f.name : '' })));
return true;
}
export async function loadTune() {
if ($('tunePanel').hidden && !S.autoTune) return;
const fid = S.current;
if (!fid) { T.fid = null; T.info = null; renderTune(); return; }
const r = await api('/api/tune', { id: fid, model: modelOf(modelUrl) });
if (fid !== S.current) return;
T.fid = fid; T.info = r; T.edits = clone(r.edits); delete T.edits.thumbnail; delete T.edits.thumbnail_auto; delete T.edits.thumbnails;
T.dirty = false;
if (S.autoTune && r.ready && $('tunePanel').hidden) { showPanel('tunePanel'); S.autoTune = false; }
if (!$('tunePanel').hidden) renderTune();
}
function assigned(p, edits) {
const e = (edits || T.edits).expressions || {};
return p in e ? e[p] : (T.info.assign[p] || '');
}
// name of a source expression in the currently loaded (saved) model, for the "Try" button
function exprNameInModel(sid) {
const saved = clone(T.info.edits);
const is1 = T.info.spec === '1.0';
for (const p of T.info.presets) if (assigned(p, saved) === sid) return is1 ? p : (V0_TO_V1[p] || p);
return sid.startsWith('@') ? 'orig_' + sid.slice(1) : sid;
}
export function springParams() {
const sp = T.edits.spring || {}, gs = num(sp.stiffness, 1), gd = num(sp.drag, 1), gg = num(sp.gravity, 0), ch = sp.chains || {};
const out = [];
for (const c of T.info.springs || []) {
const e = ch[c.key] || {}, cs = num(e.stiffness, 1), cg = num(e.gravity, 0);
for (const j of c.joints) {
out.push({ node: j.node, enabled: !e.off, stiffness: Math.max(0, j.stiffness * gs * cs),
gravityPower: Math.max(0, j.gravityPower + gg + cg), dragForce: Math.min(1, Math.max(0, j.dragForce * gd)) });
}
}
return out;
}
function markDirty() {
T.dirty = true;
$('tuneState').textContent = t('tuneDirty');
$('tuneSave').disabled = false;
}
function slider(label, val, min, max, step, onInput, fmt) {
const d = document.createElement('div'); d.className = 'field';
d.innerHTML = ``;
const inp = d.querySelector('input'), o = d.querySelector('output');
inp.addEventListener('input', () => { o.textContent = fmt(inp.value); onInput(+inp.value); });
return d;
}
const fmtMul = (v) => '×' + (+v).toFixed(2), fmtAdd = (v) => '+' + (+v).toFixed(2), fmtDeg = (v) => (+v).toFixed(1) + '°';
const hint = (text) => { const d = document.createElement('div'); d.className = 'hint flush'; d.textContent = text; return d; };
// a collapsible section; its open / closed state is remembered in T.open
function section(parent, key, title) {
const d = document.createElement('details'); d.className = 'sec'; d.open = T.open[key];
d.addEventListener('toggle', () => { T.open[key] = d.open; });
const s = document.createElement('summary'); s.textContent = title;
d.append(s); parent.append(d);
return d;
}
export function renderTune() {
const body = $('tuneBody');
const keep = T.renderedFid === T.fid ? body.scrollTop : 0; // re-render (reset / thumbnail …) stays in place
T.renderedFid = T.fid;
requestAnimationFrame(() => { body.scrollTop = keep; });
body.innerHTML = '';
const msg = (text) => { body.innerHTML = `
${esc(text)}
`; $('tuneFoot').hidden = true; };
if (!T.info || T.fid !== S.current) return msg(t('tuneNoFile'));
if (T.info.error) return msg(errText(T.info.error, T.info.error_en));
if (T.info.editable === false) return msg(t('tuneNotEditable'));
if (!T.info.ready) {
const f = S.files.find((x) => x.id === T.fid);
return msg(t(f && f.kind === 'pmx' ? 'tuneNotReadyPmx' : 'tuneNotReady'));
}
$('tuneFoot').hidden = false;
$('tuneState').textContent = T.dirty ? t('tuneDirty') : t('tuneClean');
$('tuneSave').disabled = !T.dirty;
renderMeta(section(body, 'meta', t('tuneMeta')));
renderExpr(section(body, 'expr', t('tuneExpr')));
if (T.info.look) renderLook(section(body, 'look', t('tuneLook')));
if ((T.info.springs || []).length) renderPhysics(section(body, 'physics', t('tunePhysics')));
}
// ---- name + thumbnail (the thumbnail is saved right away: it is a picture of the current view)
function renderMeta(sec) {
const nf = document.createElement('div'); nf.className = 'field';
nf.innerHTML = ``;
nf.querySelector('input').addEventListener('input', (e) => { T.edits.title = e.target.value.trim(); markDirty(); });
const tr = document.createElement('div'); tr.className = 'thumb-row';
tr.innerHTML = (T.info.thumbnail ? `
` : `${t('thumbNone')}
`) +
` ` +
(T.info.thumbnail ? `` : '') +
(T.info.thumbnail && T.info.thumbnail_auto ? `${t('thumbAuto')}` : '') +
`
${t('thumbHint')}
`;
tr.addEventListener('click', async (e) => {
const a = e.target.dataset.a;
if (!a || !viewer.loaded) return;
const r = await api('/api/tune/thumb', { id: T.fid, data: a === 'shot' ? viewer.snapshotSquare(1024) : '', model: modelOf(modelUrl) });
if (r.error) return toast(errText(r.error, r.error_en));
T.info.thumbnail = r.thumbnail || null;
T.info.thumbnail_auto = false; // set by hand now: never replaced automatically
toast(t('thumbSaved'));
renderTune();
});
sec.append(nf, tr);
}
// ---- which expression drives each preset, and how strong
function renderExpr(sec) {
sec.append(hint(t('exprHint')));
const tryExpr = (sid, w) => {
if (!sid) return;
viewer.resetExpressions(); viewer.setExpression(exprNameInModel(sid), w);
clearTimeout(renderTune.tryTimer); renderTune.tryTimer = setTimeout(() => viewer.resetExpressions(), 1500);
};
const choices = T.info.expressions.map((x) => ``).join('');
// gaze presets are driven by the gaze range below, not picked here
for (const p of (T.info.presets || []).filter((x) => !/^look/i.test(x))) {
const base = T.info.assign[p] || '';
const none = ``;
const d = document.createElement('div'); d.className = 'field preset';
const k = num((T.edits.intensity || {})[p], 1);
d.innerHTML = `` +
`` +
``;
const sel = d.querySelector('select'), rng = d.querySelector('input'), out = d.querySelector('output');
const sync = () => {
sel.classList.toggle('changed', sel.value !== base);
sel.title = sel.selectedOptions[0] ? sel.selectedOptions[0].textContent : ''; // combos are long: full text on hover
d.classList.toggle('missing', !sel.value);
rng.classList.toggle('changed', +rng.value !== 1);
};
sel.value = assigned(p);
sync();
rng.addEventListener('input', () => {
const v = +rng.value;
out.textContent = Math.round(v * 100) + '%';
T.edits.intensity = T.edits.intensity || {};
if (v === 1) delete T.edits.intensity[p]; else T.edits.intensity[p] = v;
sync(); tryExpr(sel.value, v); markDirty();
});
sel.addEventListener('change', () => {
T.edits.expressions = T.edits.expressions || {};
if (sel.value === base) delete T.edits.expressions[p]; else T.edits.expressions[p] = sel.value;
sync(); markDirty();
});
d.querySelector('button').addEventListener('click', () => tryExpr(sel.value, +rng.value));
sec.append(d);
}
}
// ---- gaze range (VRM look-at max angles; also re-weights the added gaze expressions)
function renderLook(sec) {
sec.append(hint(t('lookHint')));
const cur = () => Object.assign({}, T.info.look, T.edits.lookAt || {});
// yaw / pitch for each preview arrow, as seen on screen from the front (VRM look-at input:
// +yaw = the model's own left = screen right; ±90 = full range)
const peek = (dir) => {
const [yaw, pitch] = { left: [-90, 0], right: [90, 0], up: [0, 90], down: [0, -90] }[dir];
viewer.setLook(yaw, pitch, cur());
clearTimeout(renderTune.lookTimer); renderTune.lookTimer = setTimeout(() => viewer.setLook(null), 1500);
};
const set = (key, v) => { T.edits.lookAt = Object.assign(cur(), { [key]: v }); markDirty(); };
sec.append(slider(t('lookH'), cur().h, 0, 40, 0.5, (v) => { set('h', v); peek('left'); }, fmtDeg),
slider(t('lookDown'), cur().down, 0, 30, 0.5, (v) => { set('down', v); peek('down'); }, fmtDeg),
slider(t('lookUp'), cur().up, 0, 30, 0.5, (v) => { set('up', v); peek('up'); }, fmtDeg));
const row = document.createElement('div'); row.className = 'field';
row.innerHTML = `` + ['left', 'right', 'up', 'down'].map((d) =>
``).join(' ') +
(T.edits.lookAt ? ` ` : '');
row.addEventListener('click', (e) => {
const d = e.target.dataset.d;
if (!d) return;
if (d === 'reset') { delete T.edits.lookAt; markDirty(); renderTune(); return; }
peek(d);
});
sec.append(row);
}
// ---- physics (VRM 1.0 SpringBone / 0.x spring groups): overall multipliers, then each chain (collapsed by default)
// the chain kept shown in the preview (pin button), per file; hovering another chain shows that one meanwhile
let pinned = null; // { fid, key, nodes }
const pinnedNodes = () => (pinned && pinned.fid === T.fid ? pinned.nodes : null);
const ICON_EYE = '';
const ICON_AIM = '';
function renderPhysics(sec) {
if (pinned && (pinned.fid !== T.fid || !T.info.springs.some((c) => c.key === pinned.key))) pinned = null;
viewer.highlightChain(pinnedNodes());
const sp = T.edits.spring = T.edits.spring || {};
sp.chains = sp.chains || {};
const live = () => { viewer.setSpringParams(springParams()); markDirty(); };
sec.append(hint(t('allChains')),
slider(t('stiffMul'), num(sp.stiffness, 1), 0.2, 3, 0.05, (v) => { sp.stiffness = v; live(); }, fmtMul),
slider(t('dragMul'), num(sp.drag, 1), 0.2, 2, 0.05, (v) => { sp.drag = v; live(); }, fmtMul),
slider(t('gravAdd'), num(sp.gravity, 0), 0, 1, 0.02, (v) => { sp.gravity = v; live(); }, fmtAdd));
const chains = section(sec, 'chains', t('chains', { n: T.info.springs.length }));
const flt = document.createElement('div'); flt.className = 'field';
flt.innerHTML = ``;
const list = document.createElement('div'); list.className = 'chain-list';
chains.append(flt, list);
for (const c of T.info.springs) {
const e = sp.chains[c.key] || {};
const get = () => (sp.chains[c.key] = sp.chains[c.key] || {});
const row = document.createElement('div'); row.className = 'chain' + (e.off ? ' off' : ''); row.dataset.name = c.name.toLowerCase();
const nodes = c.joints.map((j) => j.node);
row.classList.toggle('pinned', !!pinned && pinned.fid === T.fid && pinned.key === c.key);
const head = document.createElement('div'); head.className = 'chain-head';
const pin = document.createElement('button'); pin.className = 'ibtn' + (row.classList.contains('pinned') ? ' on' : '');
pin.innerHTML = ICON_EYE; pin.title = t('pinChain'); pin.setAttribute('aria-label', t('pinChain'));
pin.onclick = () => {
const on = !row.classList.contains('pinned');
list.querySelectorAll('.chain.pinned').forEach((r) => { r.classList.remove('pinned'); r.querySelector('.ibtn').classList.remove('on'); });
pinned = on ? { fid: T.fid, key: c.key, nodes } : null;
row.classList.toggle('pinned', on); pin.classList.toggle('on', on);
viewer.highlightChain(on ? nodes : null);
};
const aim = document.createElement('button'); aim.className = 'ibtn';
aim.innerHTML = ICON_AIM; aim.title = t('focusChain'); aim.setAttribute('aria-label', t('focusChain'));
aim.onclick = () => viewer.focusChain(nodes);
const sw = document.createElement('label'); sw.className = 'switch';
sw.innerHTML = `${esc(c.name)} · ${c.joints.length}`;
sw.querySelector('input').addEventListener('change', (ev) => { get().off = !ev.target.checked; row.classList.toggle('off', !ev.target.checked); live(); });
head.append(sw, pin, aim);
row.append(head,
slider(t('stiffMul'), num(e.stiffness, 1), 0.2, 3, 0.05, (v) => { get().stiffness = v; live(); }, fmtMul),
slider(t('gravAdd'), num(e.gravity, 0), 0, 1, 0.02, (v) => { get().gravity = v; live(); }, fmtAdd));
// hovering a chain shows it in the preview (joints, hit radius, its colliders)
row.addEventListener('pointerenter', () => viewer.highlightChain(nodes));
row.addEventListener('pointerleave', () => viewer.highlightChain(pinnedNodes()));
list.append(row);
}
flt.querySelector('input').addEventListener('input', (ev) => {
const q = ev.target.value.trim().toLowerCase();
for (const r of list.children) r.style.display = !q || r.dataset.name.includes(q) ? '' : 'none';
});
}
export async function saveTune(edits) {
const r = await api('/api/tune/save', { id: T.fid, edits });
if (r.error) return toast(errText(r.error, r.error_en));
toast(r.applied ? t('tuneSaved', { n: r.applied }) : t('tuneSavedNone'));
T.dirty = false;
if (modelUrl && r.applied) await loadModel(modelUrl, viewer.name, true);
await loadTune();
}
$('tuneSave').onclick = () => saveTune(T.edits);
$('tuneReset').onclick = () => { T.edits = {}; saveTune({}); };