tiny-scene-three / web /js /editor.js
paralaif's picture
Add generated music and sound: Tone.js band, ambience, beat-synced animation, video export
4a0e872 verified
Raw History Blame Contribute Delete
8.25 kB
// Hand-editing panel: scene settings, the object list and the selected object's properties.
// It never touches three.js directly: every change produces a new scene description.
import { resolveMusic } from './audio/theory.js';
import { PALETTE } from './scene/prims.js';
const SCENE_KEYS = [['loc', 'Lugar'], ['time', 'Hora'], ['weather', 'Clima'], ['shot', 'Plano'], ['cam', 'Cámara']];
const SIZES = ['tiny', 'small', 'big', 'giant'];
const COUNTS = [1, 2, 3, 4, 5, 6];
function h(tag, props = {}, ...kids) {
const el = document.createElement(tag);
for (const [k, v] of Object.entries(props)) {
if (k === 'class') el.className = v;
else if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
else if (v !== undefined && v !== false) el.setAttribute(k, v === true ? '' : v);
}
for (const k of kids.flat()) if (k != null) el.append(k);
return el;
}
/** "dog", or "dog 2" when the scene has several dogs. */
export function entLabel(scene, e) {
const same = scene.ents.filter((o) => o.type === e.type);
return same.length > 1 ? `${e.type} ${same.indexOf(e) + 1}` : e.type;
}
/** Lists of values for every field, read from the model's vocabulary so the editor offers exactly what the model knows. */
export function vocabFrom(tokens) {
const v = {};
for (const t of tokens) {
const i = t.indexOf('=');
if (i < 1) continue;
(v[t.slice(0, i)] ??= []).push(t.slice(i + 1));
}
v.type = v.type.filter((x) => x !== 'it' && x !== 'all');
v.shot = v.shot.filter((x) => x !== 'in' && x !== 'out');
v.tempo = (v.tempo ?? []).filter((x) => x !== 'up' && x !== 'down');
return v;
}
function select(label, value, options, onset, none) {
const s = h('select', { onchange: () => onset(s.value === '' ? undefined : s.value) },
none != null ? h('option', { value: '' }, none) : null,
options.map(([v, text]) => h('option', { value: v }, text)));
s.value = value ?? '';
return h('label', { class: 'field' }, h('span', {}, label), s);
}
const opts = (list) => list.map((x) => [x, x]);
/**
* root: container element. ctx: { scene, selected, vocab, change(fn), select(id), notice }
* change(fn, camera?) receives a copy of the scene to mutate; the caller rebuilds and records undo.
* camera 'auto' reframes if the scene grew (used when adding objects).
*/
export function renderEditor(root, { scene, selected, vocab, change, select: pick }) {
const ent = scene.ents.find((e) => e.id === selected);
const setEnt = (key, transform = (x) => x) => (value) => change((sc) => {
const e = sc.ents.find((x) => x.id === selected);
if (!e) return;
const v = value === undefined ? undefined : transform(value);
if (v === undefined) delete e[key]; else e[key] = v;
if (key === 'rel') {
if (!v) delete e.ref;
else if (!sc.ents.some((x) => x.id === e.ref && x.id !== e.id)) e.ref = sc.ents.find((x) => x.id !== e.id)?.id;
if (!e.ref) delete e.rel;
}
});
// ---- scene settings
const sceneBox = h('section', { class: 'ed-sec' }, h('h3', {}, 'Escena'),
h('div', { class: 'grid' }, SCENE_KEYS.map(([k, label]) => select(label, scene[k], opts(vocab[k]), (v) => change((sc) => {
sc[k] = v ?? (k === 'loc' ? 'studio' : vocab[k][0]);
if (k === 'shot') sc.zoom = 0;
})))));
// ---- object list + add
let addType = vocab.type[0];
const list = scene.ents.length
? h('div', { class: 'ent-list' }, scene.ents.map((e) => h('button', {
type: 'button', class: 'ent' + (e.id === selected ? ' on' : ''), onclick: () => pick(e.id === selected ? null : e.id),
}, e.color ? h('i', { class: 'dot', style: `background:#${PALETTE[e.color].toString(16).padStart(6, '0')}` }) : null,
(e.n > 1 ? e.n + '× ' : '') + entLabel(scene, e), e.act ? h('small', {}, ' ' + e.act) : null)))
: h('p', { class: 'hint' }, 'La escena está vacía.');
const addSel = select('Nuevo objeto', addType, opts(vocab.type), (v) => { addType = v; });
const objBox = h('section', { class: 'ed-sec' }, h('h3', {}, 'Objetos'), list,
h('div', { class: 'row' }, addSel, h('button', {
type: 'button', onclick: () => {
const id = 'e' + scene.nextId;
change((sc) => { sc.ents.push({ id: 'e' + sc.nextId++, type: addType }); }, 'auto');
pick(id);
},
}, 'Añadir')));
// ---- selected object
let inspector = h('section', { class: 'ed-sec' }, h('p', { class: 'hint' }, 'Haz clic en un objeto de la vista o de la lista para editarlo. Arrástralo en la vista para moverlo.'));
if (ent) {
const others = scene.ents.filter((e) => e.id !== ent.id);
const swatches = h('div', { class: 'swatches' },
h('button', { type: 'button', title: 'original', class: 'sw none' + (ent.color ? '' : ' on'), onclick: () => setEnt('color')(undefined) }, '×'),
vocab.color.map((c) => h('button', {
type: 'button', title: c, class: 'sw' + (ent.color === c ? ' on' : ''),
style: `background:#${PALETTE[c].toString(16).padStart(6, '0')}`, onclick: () => setEnt('color')(c),
})));
inspector = h('section', { class: 'ed-sec' },
h('h3', {}, entLabel(scene, ent)),
h('div', { class: 'grid' },
select('Tipo', ent.type, opts(vocab.type), setEnt('type')),
select('Acción', ent.act, opts(vocab.act), setEnt('act'), '(ninguna)'),
select('Tamaño', ent.size, opts(SIZES), setEnt('size'), 'normal'),
select('Cantidad', String(ent.n ?? 1), COUNTS.map((n) => [String(n), String(n)]), setEnt('n', (v) => (Number(v) > 1 ? Number(v) : undefined))),
select('Velocidad', ent.spd, [['slow', 'slow'], ['fast', 'fast']], setEnt('spd'), 'normal'),
select('Relación', ent.rel, opts(vocab.rel), setEnt('rel'), '(ninguna)'),
ent.rel ? select('Con', ent.ref, others.map((e) => [e.id, entLabel(scene, e)]), setEnt('ref')) : null),
h('div', { class: 'field' }, h('span', {}, 'Color'), swatches),
h('div', { class: 'row' },
ent.dx || ent.dz ? h('button', { type: 'button', onclick: () => change((sc) => { const e = sc.ents.find((x) => x.id === ent.id); delete e.dx; delete e.dz; }) }, 'Posición automática') : null,
h('button', {
type: 'button', onclick: () => {
const id = 'e' + scene.nextId;
change((sc) => {
const src = sc.ents.find((x) => x.id === ent.id), copy = { ...structuredClone(src), id: 'e' + sc.nextId++ };
delete copy.rel; delete copy.ref; delete copy.dx; delete copy.dz;
sc.ents.push(copy);
}, 'auto');
pick(id);
},
}, 'Duplicar'),
h('button', { type: 'button', class: 'danger', onclick: () => change((sc) => { sc.ents = sc.ents.filter((x) => x.id !== ent.id); for (const e of sc.ents) if (e.ref === ent.id) { delete e.rel; delete e.ref; } }) }, 'Borrar')));
}
// ---- music
let musicBox = null;
if (vocab.mood) {
const m = scene.mus ?? {}, r = resolveMusic(scene);
const setMus = (k) => (v) => change((sc) => {
sc.mus ??= {};
if (v === undefined) delete sc.mus[k]; else sc.mus[k] = v;
if (k === 'tempo') sc.mus.shift = 0;
});
const layer = (k, label) => {
const box = h('input', { type: 'checkbox', onchange: () => change((sc) => { (sc.mus ??= {})[k] = box.checked; }) });
box.checked = m[k] !== false;
return h('label', { class: 'check' }, box, label);
};
musicBox = h('section', { class: 'ed-sec' }, h('h3', {}, 'Música'),
h('div', { class: 'grid' },
select('Música', m.on === false ? 'off' : 'on', [['on', 'sí'], ['off', 'no']], (v) => change((sc) => { (sc.mus ??= {}).on = v !== 'off'; })),
select('Ánimo', m.mood, opts(vocab.mood), setMus('mood'), `auto (${r.mood})`),
select('Estilo', m.genre, opts(vocab.genre), setMus('genre'), `auto (${r.genre})`),
select('Tempo', m.tempo, opts(vocab.tempo), setMus('tempo'), `auto (${r.tempo})`)),
h('div', { class: 'row' }, layer('drums', 'Batería'), layer('bass', 'Bajo'), layer('melody', 'Melodía')),
h('p', { class: 'hint' }, r.on ? `${r.bpm} pulsos por minuto` : 'Música desactivada en esta escena'));
}
root.replaceChildren(...[inspector, objBox, sceneBox, musicBox].filter(Boolean));
}