@ninkch/dsh-infinite-canvas 0.20.5 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1446,6 +1446,254 @@ export function parseGlb(buf) {
1446
1446
  };
1447
1447
  }
1448
1448
 
1449
+ /**
1450
+ * 面片 → GLB 2.0 静态网格(本地导出,不接第三方)。
1451
+ * 同一个对象的部件颜色拆成多个 primitive/material;坐标以包围盒中心为原点、底面落地。
1452
+ */
1453
+ export function encodeDirectorGlb(faces, opts) {
1454
+ const o = opts || {};
1455
+ const src = Array.isArray(faces) ? faces : [];
1456
+ const tris = [];
1457
+ for (const f of src) {
1458
+ const v = (f && f.v) || [];
1459
+ for (let i = 1; i + 1 < v.length; i++) tris.push({ v: [v[0], v[i], v[i + 1]], color: f.color });
1460
+ }
1461
+ if (!tris.length) throw new Error('没有可导出的三角面');
1462
+ let minX = Infinity, minY = Infinity, minZ = Infinity, maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;
1463
+ for (const tr of tris) for (const p of tr.v) {
1464
+ minX = Math.min(minX, p.x); maxX = Math.max(maxX, p.x);
1465
+ minY = Math.min(minY, p.y); maxY = Math.max(maxY, p.y);
1466
+ minZ = Math.min(minZ, p.z); maxZ = Math.max(maxZ, p.z);
1467
+ }
1468
+ const cx = (minX + maxX) / 2, cy = minY, cz = (minZ + maxZ) / 2;
1469
+ const positions = [], normals = [];
1470
+ const groupMap = new Map();
1471
+ for (const tr of tris) {
1472
+ const n = directorFaceNormal(tr.v);
1473
+ const color = String(tr.color || o.color || '#b3b8bf');
1474
+ let g = groupMap.get(color);
1475
+ if (!g) { g = { color, start: positions.length / 3, count: 0 }; groupMap.set(color, g); }
1476
+ for (const p of tr.v) {
1477
+ positions.push(p.x - cx, p.y - cy, p.z - cz);
1478
+ normals.push(n.x, n.y, n.z);
1479
+ g.count++;
1480
+ }
1481
+ }
1482
+ const groups = [...groupMap.values()];
1483
+ const posF = new Float32Array(positions);
1484
+ const nrmF = new Float32Array(normals);
1485
+ const idx = groups.map((g) => {
1486
+ const a = new Uint32Array(g.count);
1487
+ for (let i = 0; i < g.count; i++) a[i] = g.start + i;
1488
+ return a;
1489
+ });
1490
+ // 二进制缓冲:POSITION / NORMAL / 每组索引(全部 4 字节对齐)
1491
+ const views = [];
1492
+ let byteOffset = 0;
1493
+ const addView = (len, target) => { views.push({ buffer: 0, byteOffset, byteLength: len, ...(target ? { target } : {}) }); byteOffset += len; };
1494
+ addView(posF.byteLength, 34962);
1495
+ addView(nrmF.byteLength, 34962);
1496
+ for (const a of idx) addView(a.byteLength, 34963);
1497
+ const bin = new Uint8Array(byteOffset);
1498
+ let at = 0;
1499
+ const put = (a) => { bin.set(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), at); at += a.byteLength; };
1500
+ put(posF); put(nrmF); for (const a of idx) put(a);
1501
+ const pmin = [Infinity, Infinity, Infinity], pmax = [-Infinity, -Infinity, -Infinity];
1502
+ for (let i = 0; i < posF.length; i += 3) for (let c = 0; c < 3; c++) {
1503
+ pmin[c] = Math.min(pmin[c], posF[i + c]);
1504
+ pmax[c] = Math.max(pmax[c], posF[i + c]);
1505
+ }
1506
+ const accessors = [
1507
+ { bufferView: 0, componentType: 5126, count: posF.length / 3, type: 'VEC3', min: pmin, max: pmax },
1508
+ { bufferView: 1, componentType: 5126, count: nrmF.length / 3, type: 'VEC3' },
1509
+ ];
1510
+ groups.forEach((g, i) => accessors.push({ bufferView: 2 + i, componentType: 5125, count: g.count, type: 'SCALAR' }));
1511
+ const gltf = {
1512
+ asset: { version: '2.0', generator: 'dsh-infinite-canvas' },
1513
+ scene: 0,
1514
+ scenes: [{ name: String(o.name || 'director-export'), nodes: [0] }],
1515
+ nodes: [{ name: String(o.name || 'director-export'), mesh: 0 }],
1516
+ meshes: [{
1517
+ name: String(o.name || 'director-export'),
1518
+ primitives: groups.map((g, i) => ({ attributes: { POSITION: 0, NORMAL: 1 }, indices: 2 + i, material: i })),
1519
+ }],
1520
+ materials: groups.map((g) => ({
1521
+ name: g.color,
1522
+ pbrMetallicRoughness: { baseColorFactor: [...directorHexToRgb(g.color), 1], metallicFactor: 0, roughnessFactor: 0.9 },
1523
+ })),
1524
+ buffers: [{ byteLength: bin.length }],
1525
+ bufferViews: views,
1526
+ accessors,
1527
+ };
1528
+ const jsonBytes = new TextEncoder().encode(JSON.stringify(gltf));
1529
+ const jsonPad = (4 - (jsonBytes.length % 4)) % 4;
1530
+ const binPad = (4 - (bin.length % 4)) % 4;
1531
+ const total = 12 + 8 + jsonBytes.length + jsonPad + 8 + bin.length + binPad;
1532
+ const out = new ArrayBuffer(total);
1533
+ const dv = new DataView(out);
1534
+ const u8 = new Uint8Array(out);
1535
+ dv.setUint32(0, GLB_MAGIC, true);
1536
+ dv.setUint32(4, 2, true);
1537
+ dv.setUint32(8, total, true);
1538
+ let off = 12;
1539
+ dv.setUint32(off, jsonBytes.length + jsonPad, true);
1540
+ dv.setUint32(off + 4, 0x4e4f534a, true);
1541
+ u8.set(jsonBytes, off + 8);
1542
+ for (let i = 0; i < jsonPad; i++) u8[off + 8 + jsonBytes.length + i] = 0x20;
1543
+ off += 8 + jsonBytes.length + jsonPad;
1544
+ dv.setUint32(off, bin.length + binPad, true);
1545
+ dv.setUint32(off + 4, 0x004e4942, true);
1546
+ u8.set(bin, off + 8);
1547
+ return out;
1548
+ }
1549
+
1550
+ /**
1551
+ * 已解析的 glTF 资产 → GLB 2.0(完整导出:网格 + 骨架 + 全部动画)。
1552
+ * 与 encodeDirectorGlb(静态面片)互补:角色/导入 GLB 走这里,导出的文件
1553
+ * 在 Blender/引擎里带骨骼与动画,而不是一尊静态雕像。不接第三方转换服务。
1554
+ */
1555
+ export function encodeGltfAssetGlb(asset, opts) {
1556
+ const o = opts || {};
1557
+ if (!asset || !asset.positions || !asset.positions.length || !asset.indices || !asset.indices.length) throw new Error('没有可导出的网格');
1558
+ const views = [];
1559
+ let byteOffset = 0;
1560
+ const chunks = [];
1561
+ const addView = (typed, target) => {
1562
+ if (byteOffset % 4) { const pad = 4 - (byteOffset % 4); chunks.push(new Uint8Array(pad)); byteOffset += pad; }
1563
+ views.push({ buffer: 0, byteOffset, byteLength: typed.byteLength, ...(target ? { target } : {}) });
1564
+ byteOffset += typed.byteLength;
1565
+ chunks.push(new Uint8Array(typed.buffer, typed.byteOffset, typed.byteLength));
1566
+ return views.length - 1;
1567
+ };
1568
+ const addAccessor = (viewIdx, componentType, count, type, extra) => {
1569
+ accessors.push(Object.assign({ bufferView: viewIdx, componentType, count, type }, extra || {}));
1570
+ return accessors.length - 1;
1571
+ };
1572
+ const accessors = [];
1573
+ // 顶点/法线
1574
+ const posAcc = addAccessor(addView(asset.positions, 34962), 5126, asset.positions.length / 3, 'VEC3', { min: positionsBounds(asset.positions).min, max: positionsBounds(asset.positions).max });
1575
+ const nrmAcc = addAccessor(addView(asset.normals && asset.normals.length === asset.positions.length ? asset.normals : new Float32Array(asset.positions.length), 34962), 5126, asset.positions.length / 3, 'VEC3');
1576
+ const attributes = { POSITION: posAcc, NORMAL: nrmAcc };
1577
+ // 蒙皮:JOINTS 必须是 ubyte/ushort(glTF 规范不允许 float)
1578
+ const hasSkin = !!(asset.bones && asset.bones.length && asset.joints && asset.weights);
1579
+ if (hasSkin) {
1580
+ const nb = asset.bones.length;
1581
+ const joints = new Uint16Array(asset.joints.length);
1582
+ for (let i = 0; i < asset.joints.length; i++) joints[i] = Math.max(0, Math.min(nb - 1, Math.round(Number(asset.joints[i]) || 0)));
1583
+ const wgt = asset.weights instanceof Float32Array ? asset.weights : Float32Array.from(asset.weights);
1584
+ attributes.JOINTS_0 = addAccessor(addView(joints, 34962), 5123, joints.length / 4, 'VEC4');
1585
+ attributes.WEIGHTS_0 = addAccessor(addView(wgt, 34962), 5126, wgt.length / 4, 'VEC4');
1586
+ }
1587
+ const idxView = addView(asset.indices, 34963);
1588
+ const indicesAcc = addAccessor(idxView, asset.indices instanceof Uint32Array ? 5125 : 5123, asset.indices.length, 'SCALAR');
1589
+ const primitive = { attributes, indices: indicesAcc, material: 0 };
1590
+ // 骨架 + 逆绑定矩阵
1591
+ let skinIdx = null;
1592
+ if (hasSkin) {
1593
+ const ibm = new Float32Array(asset.bones.length * 16);
1594
+ asset.bones.forEach((b, bi) => {
1595
+ const src = (b && b.ibm) || [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
1596
+ for (let i = 0; i < 16; i++) ibm[bi * 16 + i] = Number(src[i]) || 0;
1597
+ });
1598
+ const ibmAcc = addAccessor(addView(ibm, 0), 5126, asset.bones.length, 'MAT4');
1599
+ skinIdx = { inverseBindMatrices: ibmAcc, joints: asset.bones.map((b) => Number(b.nodeIdx) || 0), name: (o.name || 'armature') + '-skin' };
1600
+ }
1601
+ // 动画:times(SCALAR) + vals(VEC3/VEC4),节点索引沿用资产原序
1602
+ const samplers = [];
1603
+ const channels = [];
1604
+ const animations = (asset.animations || []).map((an, ai) => {
1605
+ const s0 = samplers.length;
1606
+ const c0 = channels.length;
1607
+ (an.tracks || []).forEach((tr) => {
1608
+ if (!tr || (!Array.isArray(tr.times) && !(tr.times instanceof Float32Array))) return;
1609
+ const input = addAccessor(addView(Float32Array.from(tr.times), 0), 5126, tr.times.length, 'SCALAR');
1610
+ const vecType = tr.path === 'rotation' ? 'VEC4' : 'VEC3';
1611
+ const output = addAccessor(addView(Float32Array.from(tr.vals), 0), 5126, tr.vals.length / (vecType === 'VEC4' ? 4 : 3), vecType);
1612
+ samplers.push({ input, output, interpolation: 'LINEAR' });
1613
+ channels.push({ sampler: samplers.length - 1 - s0, target: { node: Number(tr.node) || 0, path: String(tr.path || 'translation') } });
1614
+ });
1615
+ return { name: String(an.name || ('clip' + ai)), samplers: samplers.slice(s0), channels: channels.slice(c0) };
1616
+ });
1617
+ // 重建节点层级(原序保留,动画目标索引不变);网格节点单独挂在根上
1618
+ const nodes = (asset.nodes || []).map((n, i) => {
1619
+ void i;
1620
+ return {
1621
+ name: String((n && n.name) || ''),
1622
+ translation: (n && n.t) || [0, 0, 0],
1623
+ rotation: (n && n.r) || [0, 0, 0, 1],
1624
+ scale: (n && n.s) || [1, 1, 1],
1625
+ };
1626
+ });
1627
+ const childrenOf = new Map();
1628
+ (asset.parentOfAll || []).forEach((p, i) => {
1629
+ if (p >= 0 && p !== i) {
1630
+ if (!childrenOf.has(p)) childrenOf.set(p, []);
1631
+ childrenOf.get(p).push(i);
1632
+ }
1633
+ });
1634
+ nodes.forEach((n, i) => { const ch = childrenOf.get(i); if (ch && ch.length) n.children = ch; });
1635
+ const meshNode = {
1636
+ name: String(o.name || 'export'),
1637
+ mesh: 0,
1638
+ ...(skinIdx ? { skin: 0 } : {}),
1639
+ };
1640
+ const meshNodeIdx = nodes.length;
1641
+ nodes.push(meshNode);
1642
+ const roots = (asset.parentOfAll || []).map((p, i) => (p < 0 || p === i ? i : -1)).filter((i) => i >= 0);
1643
+ roots.push(meshNodeIdx);
1644
+ const gltf = {
1645
+ asset: { version: '2.0', generator: 'dsh-infinite-canvas' },
1646
+ scene: 0,
1647
+ scenes: [{ name: String(o.name || 'export'), nodes: roots }],
1648
+ nodes,
1649
+ meshes: [{ name: String(o.name || 'export'), primitives: [primitive] }],
1650
+ materials: [{ name: 'clay', pbrMetallicRoughness: { baseColorFactor: [...directorHexToRgb('#c9ced6'), 1], metallicFactor: 0, roughnessFactor: 0.9 } }],
1651
+ ...(skinIdx ? { skins: [skinIdx] } : {}),
1652
+ animations,
1653
+ buffers: [{ byteLength: 0 }],
1654
+ bufferViews: views,
1655
+ accessors,
1656
+ };
1657
+ // 拼装二进制与 JSON 块
1658
+ const bin = new Uint8Array(byteOffset);
1659
+ let at = 0;
1660
+ for (const c of chunks) { bin.set(c, at); at += c.length; }
1661
+ gltf.buffers[0].byteLength = bin.length;
1662
+ return assembleGlb(gltf, bin);
1663
+ }
1664
+ /** 顶点包围盒(导出 accessor 的 min/max 用;与 assetBounds(资产级)不同)。 */
1665
+ function positionsBounds(positions) {
1666
+ const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
1667
+ for (let i = 0; i < positions.length; i += 3) for (let c = 0; c < 3; c++) {
1668
+ min[c] = Math.min(min[c], positions[i + c]);
1669
+ max[c] = Math.max(max[c], positions[i + c]);
1670
+ }
1671
+ return { min, max };
1672
+ }
1673
+ /** glTF JSON + BIN → GLB 容器(encodeDirectorGlb / encodeGltfAssetGlb 共用)。 */
1674
+ function assembleGlb(gltf, bin) {
1675
+ const jsonBytes = new TextEncoder().encode(JSON.stringify(gltf));
1676
+ const jsonPad = (4 - (jsonBytes.length % 4)) % 4;
1677
+ const binPad = (4 - (bin.length % 4)) % 4;
1678
+ const total = 12 + 8 + jsonBytes.length + jsonPad + 8 + bin.length + binPad;
1679
+ const out = new ArrayBuffer(total);
1680
+ const dv = new DataView(out);
1681
+ const u8 = new Uint8Array(out);
1682
+ dv.setUint32(0, GLB_MAGIC, true);
1683
+ dv.setUint32(4, 2, true);
1684
+ dv.setUint32(8, total, true);
1685
+ let off = 12;
1686
+ dv.setUint32(off, jsonBytes.length + jsonPad, true);
1687
+ dv.setUint32(off + 4, 0x4e4f534a, true);
1688
+ u8.set(jsonBytes, off + 8);
1689
+ for (let i = 0; i < jsonPad; i++) u8[off + 8 + jsonBytes.length + i] = 0x20;
1690
+ off += 8 + jsonBytes.length + jsonPad;
1691
+ dv.setUint32(off, bin.length + binPad, true);
1692
+ dv.setUint32(off + 4, 0x004e4942, true);
1693
+ u8.set(bin, off + 8);
1694
+ return out;
1695
+ }
1696
+
1449
1697
  /** 采样动画轨道(线性插值;四元数用最短弧 nlerp)。 */
1450
1698
  /**
1451
1699
  * 动画时间 → 循环时间。idle/run/walk 等骨骼动画片段都是循环动画:
@@ -1519,7 +1767,7 @@ export function boneMatrices(asset, time) {
1519
1767
  const skin = directorMat4Multiply(w, new Float32Array(b.ibm));
1520
1768
  out.set(skin, bi * 16);
1521
1769
  });
1522
- return { mats: out, count: asset.bones.length };
1770
+ return { mats: out, count: asset.bones.length, world: worldM };
1523
1771
  }
1524
1772
 
1525
1773
  /** TRS → 4x4(列主序)。 */
@@ -2266,7 +2514,7 @@ export function boneMatricesWithPose(asset, time, poseMap, dirs, baseEuler, root
2266
2514
  out.set(jw, o);
2267
2515
  }
2268
2516
  });
2269
- return { mats: out };
2517
+ return { mats: out, world: worldM };
2270
2518
  }
2271
2519
 
2272
2520
  /**
@@ -2401,7 +2649,7 @@ export function boneMatricesWithPoseMix(asset, time, list) {
2401
2649
  }
2402
2650
  } else out.set(jw, o);
2403
2651
  });
2404
- return { mats: out };
2652
+ return { mats: out, world: worldM };
2405
2653
  }
2406
2654
 
2407
2655
  /* ============================================================
@@ -2966,6 +3214,18 @@ export function objectPathPos(ob, time, duration) {
2966
3214
  // ============================================================
2967
3215
  const SPEC_PRESET_IDS = ['box', 'sphere', 'cylinder', 'cone', 'plane', 'capsule', 'torus', 'pyramid', 'disc', 'arc', 'half_cylinder', 'ancient_house', 'ancient_stall', 'stone_step'];
2968
3216
 
3217
+ /** 确定性撒点:同一 seed + index 永远得到同一位置,避免每次播放/导出树的位置乱跳。 */
3218
+ function directorScatterOffset(i, seed, radius) {
3219
+ let h = (Math.round(Number(seed) || 1) * 374761393 + i * 668265263) | 0;
3220
+ h = Math.imul(h ^ (h >>> 13), 1274126177);
3221
+ const a = ((h >>> 0) % 10000) / 10000;
3222
+ let h2 = (h ^ 0x9e3779b9) | 0;
3223
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822519);
3224
+ const b = ((h2 >>> 0) % 10000) / 10000;
3225
+ const r = Math.sqrt(a) * Math.max(0, Number(radius) || 0);
3226
+ return { x: Math.cos(b * Math.PI * 2) * r, z: Math.sin(b * Math.PI * 2) * r, rotY: b * Math.PI * 2 };
3227
+ }
3228
+
2969
3229
  /**
2970
3230
  * 规格 → 场景。数组坐标一律简写 [x,y,z] 或 [x,z](两维视为地面 x/z,y=0)。
2971
3231
  */
@@ -3043,16 +3303,119 @@ export function buildStageFromSpec(spec) {
3043
3303
  }
3044
3304
  objects.push(ob);
3045
3305
  }
3306
+ // 本地资产目录(bld_* / furn_* / tree_* / 人形等):真实 GLB,按 assetId 预加载与渲染。
3307
+ let modelInstances = 0;
3308
+ for (const m of Array.isArray(sp.models) ? sp.models : []) {
3309
+ if (!m || typeof m !== 'object') continue;
3310
+ const id = String((m && m.assetId) || '');
3311
+ if (!id) continue;
3312
+ const basePos = v3of(m.pos, 0);
3313
+ const arr = m.array && typeof m.array === 'object' ? m.array : null;
3314
+ const scat = m.scatter && typeof m.scatter === 'object' ? m.scatter : null;
3315
+ const count = Math.max(1, Math.min(40, Math.round(num((arr || scat || {}).count, 1))));
3316
+ const off = arr ? v3of(arr.offset, 0) : v3(0, 0, 0);
3317
+ const stepRot = arr ? num(arr.rotY, 0) : 0;
3318
+ const radius = scat ? Math.max(0, num(scat.radius, 0)) : 0;
3319
+ const seed = scat ? num(scat.seed, 1) : 1;
3320
+ const mirror = String(m.mirror || '').toLowerCase();
3321
+ const mirrorAxes = [''];
3322
+ if (mirror.includes('x')) mirrorAxes.push('x');
3323
+ if (mirror.includes('z')) mirrorAxes.push('z');
3324
+ if (mirror.includes('x') && mirror.includes('z')) mirrorAxes.push('xz');
3325
+ for (let i = 0; i < count; i++) {
3326
+ if (modelInstances >= 160) break; // 防 AI 一次生成上千棵树
3327
+ const scattered = scat ? directorScatterOffset(i, seed, radius) : { x: 0, z: 0, rotY: 0 };
3328
+ const px = basePos.x + off.x * i + scattered.x;
3329
+ const py = basePos.y + off.y * i;
3330
+ const pz = basePos.z + off.z * i + scattered.z;
3331
+ const prot = num(m.rotY, 0) + stepRot * i + scattered.rotY;
3332
+ for (const ax of mirrorAxes) {
3333
+ if (modelInstances >= 160) break;
3334
+ seq += 1;
3335
+ modelInstances += 1;
3336
+ const suffix = (count > 1 ? '_' + (i + 1) : '') + (ax ? '_m' + ax : '');
3337
+ const mob = {
3338
+ id: String(m.id || 'model' + seq) + suffix,
3339
+ name: String(m.name || m.label || id) + (count > 1 ? ' ' + (i + 1) : '') + (ax ? ' M' + ax.toUpperCase() : ''),
3340
+ kind: 'gltf', assetId: id, catalog: true,
3341
+ pos: v3(ax.includes('x') ? -px : px, py, ax.includes('z') ? -pz : pz),
3342
+ rotY: ax ? -prot : prot, rx: num(m.rx, 0), rz: ax ? -num(m.rz, 0) : num(m.rz, 0),
3343
+ scale: m.scale ? v3of(m.scale, 1) : v3(1, 1, 1),
3344
+ h: num(m.h, 1.7), visible: m.visible !== false, color: String(m.color || ''),
3345
+ clip: String(m.clip || ''), animTime: 0,
3346
+ };
3347
+ if (m.material && typeof m.material === 'object') mob.material = { ...m.material };
3348
+ if (m.attach && typeof m.attach === 'object') mob.attach = JSON.parse(JSON.stringify(m.attach));
3349
+ if (Array.isArray(m.keys)) {
3350
+ mob.keys = m.keys.map((k) => ({ t: num(k.t, 0), pos: v3of(k.pos, 0), rotY: num(k.rotY, 0), ease: String(k.ease || 'auto') })).sort((a, b) => a.t - b.t);
3351
+ }
3352
+ objects.push(mob);
3353
+ }
3354
+ }
3355
+ }
3046
3356
  for (const p of Array.isArray(sp.props) ? sp.props : []) {
3047
3357
  seq += 1;
3048
3358
  const preset = SPEC_PRESET_IDS.includes(p.preset) ? p.preset : 'box';
3049
3359
  const pob = {
3050
3360
  id: String(p.id || 'prop' + seq), name: String(p.name || p.label || ('布景' + seq)),
3051
- kind: 'geom', preset, pos: v3of(p.pos, 0), rotY: num(p.rotY, 0), rx: num(p.rx, 0), rz: num(p.rz, 0),
3361
+ kind: p.assetId ? 'gltf' : 'geom', preset, pos: v3of(p.pos, 0), rotY: num(p.rotY, 0), rx: num(p.rx, 0), rz: num(p.rz, 0),
3052
3362
  scale: p.scale ? v3of(p.scale, 1) : v3(1, 1, 1), visible: p.visible !== false,
3053
3363
  color: String(p.color || '#b3b8bf'),
3054
3364
  };
3365
+ if (p.assetId) {
3366
+ pob.assetId = String(p.assetId); pob.clip = String(p.clip || ''); pob.animTime = 0;
3367
+ } else if (Array.isArray(p.parts) && p.parts.length) {
3368
+ // 参数化组合道具(警车/武器/桌椅等):一个对象由多个基础几何体组成,跟随父对象移动/旋转。
3369
+ // array 复制成排(栅栏/窗格),mirror 沿父对象原点镜像(左右车轮);展开后统一归一化。
3370
+ pob.kind = 'compound';
3371
+ const rawParts = [];
3372
+ for (const pt of p.parts) {
3373
+ if (!pt || typeof pt !== 'object') continue;
3374
+ const arr = pt.array && typeof pt.array === 'object' ? pt.array : null;
3375
+ const scat = pt.scatter && typeof pt.scatter === 'object' ? pt.scatter : null;
3376
+ const count = Math.max(1, Math.min(24, Math.round(num((arr || scat || {}).count, 1))));
3377
+ const basePos = v3of(pt.pos, 0);
3378
+ const off = arr ? v3of(arr.offset, 0) : v3(0, 0, 0);
3379
+ const stepRot = arr ? num(arr.rotY, 0) : 0;
3380
+ const radius = scat ? Math.max(0, num(scat.radius, 0)) : 0;
3381
+ const seed = scat ? num(scat.seed, 1) : 1;
3382
+ const mirror = String(pt.mirror || '').toLowerCase();
3383
+ const axes = [''];
3384
+ if (mirror.includes('x')) axes.push('x');
3385
+ if (mirror.includes('z')) axes.push('z');
3386
+ if (mirror.includes('x') && mirror.includes('z')) axes.push('xz');
3387
+ for (let i = 0; i < count; i++) {
3388
+ const sc = scat ? directorScatterOffset(i, seed, radius) : { x: 0, z: 0, rotY: 0 };
3389
+ const x = basePos.x + off.x * i + sc.x, y = basePos.y + off.y * i, z2 = basePos.z + off.z * i + sc.z;
3390
+ const rotY = num(pt.rotY, 0) + stepRot * i + sc.rotY;
3391
+ for (const ax of axes) {
3392
+ rawParts.push({
3393
+ ...pt,
3394
+ pos: [ax.includes('x') ? -x : x, y, ax.includes('z') ? -z2 : z2],
3395
+ rotY: ax ? -rotY : rotY,
3396
+ rz: ax ? -num(pt.rz, 0) : num(pt.rz, 0),
3397
+ });
3398
+ }
3399
+ }
3400
+ }
3401
+ pob.parts = rawParts.slice(0, 64).map((pt) => {
3402
+ const preset2 = SPEC_PRESET_IDS.includes(pt && pt.preset) ? pt.preset : 'box';
3403
+ const part = {
3404
+ preset: preset2,
3405
+ pos: v3of(pt && pt.pos, 0),
3406
+ rotY: num(pt && pt.rotY, 0), rx: num(pt && pt.rx, 0), rz: num(pt && pt.rz, 0),
3407
+ scale: (pt && pt.scale) ? v3of(pt.scale, 1) : v3(1, 1, 1),
3408
+ color: String((pt && pt.color) || p.color || '#b3b8bf'),
3409
+ };
3410
+ if (pt && pt.material && typeof pt.material === 'object') part.material = { ...pt.material };
3411
+ return part;
3412
+ });
3413
+ // 组合道具的默认高度取最高部件(车顶/灯罩),供高度参考线与 gizmo 使用。
3414
+ const partTop = pob.parts.reduce((m, pt) => Math.max(m, (Number(pt.pos && pt.pos.y) || 0) + directorPrimitiveUnitHeight(pt.preset) * (Number(pt.scale && pt.scale.y) || 1)), 0);
3415
+ pob.h = num(p.h, partTop || 1);
3416
+ }
3055
3417
  if (p.material && typeof p.material === 'object') pob.material = { ...p.material };
3418
+ if (p.attach && typeof p.attach === 'object') pob.attach = JSON.parse(JSON.stringify(p.attach));
3056
3419
  // 道具关键帧:与角色同构(t/pos/rotY/rx/rz/ease),供长枪等跟手(applyPlayhead 对所有对象统一应用)
3057
3420
  if (Array.isArray(p.keys)) {
3058
3421
  pob.keys = p.keys.map((k) => ({
@@ -3065,6 +3428,9 @@ export function buildStageFromSpec(spec) {
3065
3428
  ...(k.interp ? { interp: String(k.interp) } : {}),
3066
3429
  })).sort((x, y) => x.t - y.t);
3067
3430
  }
3431
+ // 道具路径:与角色同构(画路径线即可让警车/道具沿线运动)
3432
+ addPath(pob, p.path, p.pathMode);
3433
+ if (pob.path && p.pathFace === false) pob.pathFace = false;
3068
3434
  objects.push(pob);
3069
3435
  }
3070
3436
  const cameras = (Array.isArray(sp.cameras) ? sp.cameras : []).map((c, i) => {
@@ -3159,6 +3525,7 @@ export function compileStageSpec(scene) {
3159
3525
  const arr = (p) => [round3(p.x), round3(p.y), round3(p.z)];
3160
3526
  const characters = [];
3161
3527
  const props = [];
3528
+ const models = [];
3162
3529
  for (const ob of sc.objects || []) {
3163
3530
  if (ob.kind === 'model') {
3164
3531
  const c = {
@@ -3188,17 +3555,47 @@ export function compileStageSpec(scene) {
3188
3555
  if (Array.isArray(ob.poseKeys) && ob.poseKeys.length) c.poseKeys = ob.poseKeys.map((k) => ({ t: round3(k.t), bonePose: JSON.parse(JSON.stringify(k.bonePose || {})), ease: k.ease || 'auto' }));
3189
3556
  if (Array.isArray(ob.keys) && ob.keys.length) c.keys = ob.keys.map((k) => ({ t: round3(k.t), pos: arr(k.pos), rotY: round3(k.rotY || 0), rx: round3(k.rx || 0), rz: round3(k.rz || 0), ease: k.ease || 'auto' }));
3190
3557
  characters.push(c);
3558
+ } else if (ob.kind === 'gltf' && ob.catalog) {
3559
+ // 来自本地资产目录的 models[]:往返时仍归入 models,避免退化成“带 assetId 的道具”
3560
+ const m = {
3561
+ id: ob.id, name: ob.name || ob.id, assetId: ob.assetId,
3562
+ pos: arr(ob.pos || v3(0, 0, 0)), rotY: round3(ob.rotY || 0), rx: round3(ob.rx || 0), rz: round3(ob.rz || 0),
3563
+ h: round3(ob.h || 1.7),
3564
+ };
3565
+ if (ob.scale && (Number(ob.scale.x) !== 1 || Number(ob.scale.y) !== 1 || Number(ob.scale.z) !== 1)) m.scale = arr(ob.scale);
3566
+ if (ob.visible === false) m.visible = false;
3567
+ if (ob.color) m.color = ob.color;
3568
+ if (ob.clip) m.clip = ob.clip;
3569
+ if (ob.material) m.material = { ...ob.material };
3570
+ if (ob.attach) m.attach = JSON.parse(JSON.stringify(ob.attach));
3571
+ if (Array.isArray(ob.keys) && ob.keys.length) m.keys = ob.keys.map((k) => ({ t: round3(k.t), pos: arr(k.pos), rotY: round3(k.rotY || 0), ease: k.ease || 'auto' }));
3572
+ models.push(m);
3191
3573
  } else {
3192
- props.push({
3574
+ const rec = {
3193
3575
  id: ob.id, name: ob.name || ob.id, preset: ob.preset || 'box',
3576
+ ...(ob.kind === 'gltf' && ob.assetId ? { assetId: ob.assetId, clip: ob.clip || undefined } : {}),
3194
3577
  pos: arr(ob.pos || v3(0, 0, 0)), rotY: round3(ob.rotY || 0), rx: round3(ob.rx || 0), rz: round3(ob.rz || 0),
3195
3578
  scale: arr(ob.scale || v3(1, 1, 1)), color: ob.color,
3196
3579
  visible: ob.visible === false ? false : undefined,
3197
3580
  material: ob.material ? { ...ob.material } : undefined,
3581
+ ...(ob.attach ? { attach: JSON.parse(JSON.stringify(ob.attach)) } : {}),
3198
3582
  ...(Array.isArray(ob.keys) && ob.keys.length
3199
3583
  ? { keys: ob.keys.map((k) => ({ t: round3(k.t), pos: arr(k.pos), rotY: round3(k.rotY || 0), rx: round3(k.rx || 0), rz: round3(k.rz || 0), ease: k.ease || 'auto' })) }
3200
3584
  : {}),
3201
- });
3585
+ ...(Array.isArray(ob.path) && ob.path.length
3586
+ ? { path: ob.path.map(arr), pathMode: ob.pathMode || 'curve', ...(ob.pathFace === false ? { pathFace: false } : {}) }
3587
+ : {}),
3588
+ };
3589
+ // 参数化组合道具:parts 必须原样往返,否则二次编辑会退化成单个方块
3590
+ if (ob.kind === 'compound' && Array.isArray(ob.parts) && ob.parts.length) {
3591
+ rec.parts = ob.parts.map((pt) => ({
3592
+ preset: pt.preset || 'box', pos: arr(pt.pos || v3(0, 0, 0)),
3593
+ rotY: round3(pt.rotY || 0), rx: round3(pt.rx || 0), rz: round3(pt.rz || 0),
3594
+ scale: arr(pt.scale || v3(1, 1, 1)), color: pt.color,
3595
+ ...(pt.material ? { material: { ...pt.material } } : {}),
3596
+ }));
3597
+ }
3598
+ props.push(rec);
3202
3599
  }
3203
3600
  }
3204
3601
  return {
@@ -3212,7 +3609,7 @@ export function compileStageSpec(scene) {
3212
3609
  note: (sc.shot && sc.shot.note) || undefined,
3213
3610
  },
3214
3611
  env: Object.assign({}, sc.env || {}),
3215
- characters, props,
3612
+ characters, models, props,
3216
3613
  cameras: (sc.cameras || []).map((c) => ({
3217
3614
  id: c.id, name: c.name || c.id, pos: arr(c.pos), target: arr(c.target),
3218
3615
  fov: round3(c.fov || 42), roll: round3(c.roll || 0), sensorFit: c.sensorFit || 'AUTO',
@@ -3241,6 +3638,479 @@ export const BRIEF_TEMPLATES = [
3241
3638
  { id: 'dialogue', zh: '对话', en: 'Dialogue', keywords: ['对话', '说话', '交谈', '对峙', '谈判', 'dialogue', 'talk', 'conversation', '聊'] },
3242
3639
  ];
3243
3640
 
3641
+ // ============================================================
3642
+ // 3D-BOX 预设库(场景 / 导演风格 / 运镜)
3643
+ // 产品原则:用户只说一句,Agent 选场景 + 风格 + 运镜先搭第一版;
3644
+ // 这些清单同时给 Host 工具、客户端下拉和 Agent 技能引用,避免三处漂移。
3645
+ // ============================================================
3646
+ export const SCENE_PRESETS = [
3647
+ { id: 'blank', zh: '空白场景', en: 'Blank scene', descZh: '纯网格 + 默认机位', descEn: 'Grid + default camera' },
3648
+ { id: 'dialogue2', zh: '对话双人', en: 'Two-person dialogue', descZh: '2 人面对面 + 中景机位', descEn: '2 people, eye line, medium shot' },
3649
+ { id: 'dialogue3', zh: '三人对话', en: 'Three-person dialogue', descZh: '3 人三角站位 + 全景机位', descEn: '3 people, triangle blocking, wide shot' },
3650
+ { id: 'interview', zh: '采访场景', en: 'Interview', descZh: '1 主持 + 1 嘉宾 + 桌子 + 双机位', descEn: 'Host + guest + table + two cameras' },
3651
+ { id: 'monologue', zh: '独白特写', en: 'Monologue close-up', descZh: '1 人 + 特写正面机位', descEn: '1 person + frontal close-up' },
3652
+ { id: 'lecture', zh: '课堂/演讲', en: 'Lecture', descZh: '1 讲者 + 3 听众', descEn: 'Speaker + 3 listeners' },
3653
+ { id: 'chase', zh: '追逐场景', en: 'Chase', descZh: '2 人前后 + 侧面跟拍 + 低角度', descEn: '2 runners, side tracking + low angle' },
3654
+ { id: 'outdoor_walk', zh: '户外行走', en: 'Outdoor walk', descZh: '2 人并排 + 侧面跟拍', descEn: '2 people side by side, tracking' },
3655
+ { id: 'meeting', zh: '会议室', en: 'Meeting room', descZh: '4 人围桌 + 俯拍机位', descEn: '4 people around a table + top-down' },
3656
+ ];
3657
+
3658
+ export const DIRECTOR_STYLES = [
3659
+ { id: 'animation', zh: '动画剧情', en: 'Animation', promptZh: '中近景叙事 · 慢速推进 · 高饱和光影 · 配乐主导', promptEn: 'Medium-close storytelling, slow push, saturated light, score-led' },
3660
+ { id: 'tvc', zh: 'TVC 广告', en: 'TVC', promptZh: '特写堆叠 · 微距环绕 · 高对比布光 · 音效突出', promptEn: 'Close-up stacking, macro orbit, high-contrast lighting, sound-led' },
3661
+ { id: 'mv', zh: '卡点 MV', en: 'Music video', promptZh: '景别跳跃 · 快切环绕 · 强反差调色 · 音频驱动', promptEn: 'Jump cuts, fast orbit, high-contrast grade, beat-driven' },
3662
+ { id: 'documentary', zh: '纪录片', en: 'Documentary', promptZh: '中远景观察 · 手持横移 · 自然光低饱和 · 环境音优先', promptEn: 'Wide observation, handheld lateral, natural low-sat light, ambience-led' },
3663
+ { id: 'commerce', zh: '口播带货', en: 'Commerce', promptZh: '近中景固定 · 缓慢推进 · 明亮布光 · 人声优先', promptEn: 'Medium-close static, slow push, bright lighting, voice-led' },
3664
+ { id: 'suspense', zh: '悬疑短剧', en: 'Suspense', promptZh: '远近交替 · 手持降镜头 · 冷色低调 · 静音对比', promptEn: 'Alternating wide/close, handheld descent, cool low-key, silence contrast' },
3665
+ ];
3666
+
3667
+ /**
3668
+ * 运镜预设:id 同时用于 3D 机位关键帧生成与视频提示词标签。
3669
+ * path 是生成策略名(applyCameraMove 里 switch),不是文件路径。
3670
+ */
3671
+ export const CAMERA_MOVES = [
3672
+ { id: 'static', zh: '固定机位', en: 'Static', category: 'basic', promptZh: '固定机位', promptEn: 'static camera' },
3673
+ { id: 'push_in', zh: '推近', en: 'Push in', category: 'basic', promptZh: '缓慢推近主体', promptEn: 'slow push in' },
3674
+ { id: 'pull_out', zh: '拉远', en: 'Pull out', category: 'basic', promptZh: '缓慢拉远,交代环境', promptEn: 'slow pull out' },
3675
+ { id: 'pan_left', zh: '向左摇', en: 'Pan left', category: 'basic', promptZh: '机位向左横摇', promptEn: 'pan left' },
3676
+ { id: 'pan_right', zh: '向右摇', en: 'Pan right', category: 'basic', promptZh: '机位向右横摇', promptEn: 'pan right' },
3677
+ { id: 'orbit_left', zh: '左环绕', en: 'Orbit left', category: 'orbit', promptZh: '机位绕主体左环绕', promptEn: 'orbit left around subject' },
3678
+ { id: 'orbit_right', zh: '右环绕', en: 'Orbit right', category: 'orbit', promptZh: '机位绕主体右环绕', promptEn: 'orbit right around subject' },
3679
+ { id: 'handheld', zh: '手持微晃', en: 'Handheld', category: 'basic', promptZh: '手持跟拍,轻微自然晃动', promptEn: 'handheld with natural micro-shake' },
3680
+ { id: 'arc_left', zh: '左弧滑行', en: 'Arc left', category: 'orbit', promptZh: '左弧滑行,边环绕边靠近', promptEn: 'arc left while closing in' },
3681
+ { id: 'arc_right', zh: '右弧滑行', en: 'Arc right', category: 'orbit', promptZh: '右弧滑行,边环绕边靠近', promptEn: 'arc right while closing in' },
3682
+ { id: 'crane_up', zh: '升镜', en: 'Crane up', category: 'crane', promptZh: '机位垂直升起,揭示空间', promptEn: 'crane up to reveal the space' },
3683
+ { id: 'crane_down', zh: '降镜', en: 'Crane down', category: 'crane', promptZh: '机位垂直下降,压近主体', promptEn: 'crane down toward subject' },
3684
+ { id: 'dolly_zoom', zh: '滑动变焦', en: 'Dolly zoom', category: 'special', promptZh: '滑动变焦:推进同时拉宽视角,背景压缩', promptEn: 'dolly zoom: push in while widening FOV' },
3685
+ { id: 'crash_zoom', zh: '急速推镜', en: 'Crash zoom', category: 'special', promptZh: '急速推镜,制造冲击', promptEn: 'crash zoom for impact' },
3686
+ { id: 'follow', zh: '跟随', en: 'Follow', category: 'tracking', promptZh: '机位跟随主体同向移动', promptEn: 'follow the subject' },
3687
+ { id: 'reveal', zh: '拉远揭示', en: 'Reveal', category: 'special', promptZh: '从近景拉远,揭示完整场景', promptEn: 'pull back to reveal the full scene' },
3688
+ { id: 'whip_pan', zh: '甩镜', en: 'Whip pan', category: 'special', promptZh: '快速甩镜,带运动模糊', promptEn: 'whip pan with motion blur' },
3689
+ { id: 'orbit_high', zh: '高位环绕', en: 'High orbit', category: 'orbit', promptZh: '高位环绕,俯拍主体', promptEn: 'high orbit looking down' },
3690
+ { id: 'tracking', zh: '横向跟拍', en: 'Lateral tracking', category: 'tracking', promptZh: '横向跟拍,保持主体在画面中心', promptEn: 'lateral tracking, subject centered' },
3691
+ { id: 'vertigo', zh: '眩晕变焦', en: 'Vertigo', category: 'special', promptZh: '眩晕变焦,空间拉伸', promptEn: 'vertigo zoom, spatial stretch' },
3692
+ ];
3693
+
3694
+ /**
3695
+ * 运镜/转场预设库:视频节点“尝试”区、3D-BOX 预设页与 Agent 共用一份。
3696
+ * kind: camera(机位运动)/ transition(转场,映射到基础机位运动)/ template(分镜/版式模板)。
3697
+ */
3698
+ export const MOTION_PRESETS = [
3699
+ ...CAMERA_MOVES.map((m) => ({
3700
+ id: m.id, zh: m.zh, en: m.en, kind: 'camera', category: m.category,
3701
+ promptZh: m.promptZh, promptEn: m.promptEn, cameraMove: m.id,
3702
+ })),
3703
+ { id: 'travel_zoom_in', zh: '旅拍转场 zoom in', en: 'Travel zoom in', kind: 'transition', category: 'travel', promptZh: '旅拍转场:快速推近并轻微右旋,接下一场', promptEn: 'Travel transition: quick zoom in with a slight right rotation', cameraMove: 'push_in' },
3704
+ { id: 'travel_zoom_out', zh: '旅拍转场 zoom out', en: 'Travel zoom out', kind: 'transition', category: 'travel', promptZh: '旅拍转场:快速拉远并轻微左旋,交代新环境', promptEn: 'Travel transition: quick zoom out with a slight left rotation', cameraMove: 'pull_out' },
3705
+ { id: 'travel_rotate', zh: '旅拍转场 旋转', en: 'Travel rotate', kind: 'transition', category: 'travel', promptZh: '旅拍转场:旋转镜头带出下一场', promptEn: 'Travel transition: rotate into the next scene', cameraMove: 'orbit_right' },
3706
+ { id: 'travel_grow', zh: '旅拍转场 生长', en: 'Travel grow', kind: 'transition', category: 'travel', promptZh: '旅拍转场:从局部生长拉出全貌', promptEn: 'Travel transition: grow from detail to full scene', cameraMove: 'reveal' },
3707
+ { id: 'spin_360', zh: '360 旋转展示', en: '360 spin', kind: 'transition', category: 'product', promptZh: '360 度旋转展示主体,背景干净', promptEn: '360-degree product spin on a clean background', cameraMove: 'orbit_right' },
3708
+ { id: 'robot_arm', zh: '机械臂视角', en: 'Robot arm', kind: 'transition', category: 'product', promptZh: '机械臂视角:低角度弧线滑入,精密感', promptEn: 'Robot-arm move: low arc slide-in, precise feel', cameraMove: 'arc_left' },
3709
+ { id: 'pupil_zoom', zh: '瞳孔拉近', en: 'Pupil zoom', kind: 'transition', category: 'dramatic', promptZh: '瞳孔/细节急速拉近,制造压迫感', promptEn: 'Pupil/detail crash zoom for pressure', cameraMove: 'crash_zoom' },
3710
+ { id: 'bird_disintegrate', zh: '飞鸟解体', en: 'Bird dissolve', kind: 'transition', category: 'dramatic', promptZh: '主体解体为粒子/飞鸟散开,转场到下一场', promptEn: 'Subject dissolves into particles/birds into the next scene', cameraMove: 'dolly_zoom' },
3711
+ { id: 'box_break', zh: '破盒而出', en: 'Box break', kind: 'transition', category: 'dramatic', promptZh: '从盒内破出,镜头快速拉远揭示全貌', promptEn: 'Break out of the box, pull back to reveal', cameraMove: 'reveal' },
3712
+ { id: 'anti_gravity', zh: '反重力漂浮', en: 'Anti-gravity', kind: 'transition', category: 'dramatic', promptZh: '人物/物体反重力漂浮,机位升起环绕', promptEn: 'Anti-gravity float, camera rises and orbits', cameraMove: 'crane_up' },
3713
+ { id: 'particle_dissolve', zh: '粒子融解', en: 'Particle dissolve', kind: 'transition', category: 'dramatic', promptZh: '画面粒子化融解,平滑转场', promptEn: 'Image dissolves into particles, smooth transition', cameraMove: 'dolly_zoom' },
3714
+ { id: 'hero_shot', zh: '英雄视角', en: 'Hero shot', kind: 'transition', category: 'dramatic', promptZh: '英雄视角:低机位仰拍,高位环绕收尾', promptEn: 'Hero shot: low angle, high orbit finish', cameraMove: 'orbit_high' },
3715
+ { id: 'storyboard_grid', zh: '大师分镜九宫格-经典暗调', en: 'Master storyboard 9-grid', kind: 'template', category: 'storyboard', promptZh: '九宫格分镜:经典暗调、统一光影、每格一个镜头', promptEn: 'Nine-panel storyboard: classic low-key, consistent light, one shot per panel', cameraMove: null },
3716
+ ];
3717
+
3718
+ const cloneSpec = (s) => JSON.parse(JSON.stringify(s || {}));
3719
+ const asVec3 = (v, d) => {
3720
+ const q = d || [0, 0, 0];
3721
+ if (Array.isArray(v)) return [Number(v[0]) || 0, Number(v[1]) || 0, Number(v[2]) || 0];
3722
+ if (v && typeof v === 'object') return [Number(v.x) || 0, Number(v.y) || 0, Number(v.z) || 0];
3723
+ return q.slice();
3724
+ };
3725
+ const lerpVec = (a, b, k) => [a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k, a[2] + (b[2] - a[2]) * k];
3726
+ const orbitVec = (pos, target, deg, radiusScale) => {
3727
+ const dx = pos[0] - target[0];
3728
+ const dz = pos[2] - target[2];
3729
+ const r = Math.sqrt(dx * dx + dz * dz) * (radiusScale === undefined ? 1 : radiusScale);
3730
+ const a0 = Math.atan2(dz, dx);
3731
+ const a = a0 + (deg * Math.PI) / 180;
3732
+ return [target[0] + Math.cos(a) * r, pos[1], target[2] + Math.sin(a) * r];
3733
+ };
3734
+ const clampFov = (v) => Math.max(8, Math.min(140, Number(v) || 42));
3735
+
3736
+ /** 把导演风格写进规格:只改光影/雾/景深与备注,不改角色与分镜结构。 */
3737
+ export function applyDirectorStyle(spec, styleId) {
3738
+ const st = DIRECTOR_STYLES.find((x) => x.id === String(styleId || ''));
3739
+ if (!st) return spec;
3740
+ const out = cloneSpec(spec);
3741
+ out.style = st.id;
3742
+ out.shot = out.shot || {};
3743
+ out.shot.note = [out.shot.note, st.promptZh].filter(Boolean).join(' · ');
3744
+ out.env = Object.assign({ preset: 'studio', grid: true, tonemap: 'agx' }, out.env || {});
3745
+ const setKey = (dir, color, intensity) => {
3746
+ const list = Array.isArray(out.lights) ? out.lights : [];
3747
+ if (list.length) list[0] = Object.assign({}, list[0], { dir, color, intensity });
3748
+ else list.push({ dir, color, intensity });
3749
+ out.lights = list;
3750
+ };
3751
+ if (st.id === 'suspense') {
3752
+ out.env.preset = 'night'; out.env.bg = '#0a0d12';
3753
+ out.env.fog = { color: '#0d141d', near: 2, far: 14, density: 1.5 };
3754
+ setKey([0.3, -0.7, 0.4], '#9fb6d4', 0.75);
3755
+ out.dof = Object.assign({ focus: 4, range: 2, maxBlur: 7 }, out.dof || {});
3756
+ } else if (st.id === 'mv') {
3757
+ out.env.preset = 'night'; out.env.bg = '#0a0714';
3758
+ setKey([0.4, -0.6, 0.5], '#ff5ea8', 1.5);
3759
+ out.lights = (out.lights || []).concat([{ dir: [-0.4, -0.3, -0.5], color: '#31d7ff', intensity: 0.8 }]);
3760
+ out.dof = Object.assign({ focus: 4.5, range: 3, maxBlur: 6 }, out.dof || {});
3761
+ } else if (st.id === 'documentary') {
3762
+ out.env.preset = 'daylight'; out.env.bg = '#cfd8e0';
3763
+ setKey([0.45, -0.8, 0.35], '#fff3df', 1.15);
3764
+ out.dof = Object.assign({ focus: 5, range: 4, maxBlur: 3 }, out.dof || {});
3765
+ } else if (st.id === 'commerce') {
3766
+ out.env.preset = 'studio'; out.env.bg = '#e8e6e2';
3767
+ setKey([0.2, -0.55, 0.6], '#ffffff', 1.8);
3768
+ out.lights = (out.lights || []).concat([{ dir: [-0.3, -0.3, 0.5], color: '#fff6e8', intensity: 0.7 }]);
3769
+ out.dof = Object.assign({ focus: 5, range: 4, maxBlur: 2 }, out.dof || {});
3770
+ } else if (st.id === 'tvc') {
3771
+ out.env.bg = '#0c0f14';
3772
+ setKey([0.35, -0.65, 0.55], '#ffffff', 1.85);
3773
+ out.dof = Object.assign({ focus: 4.2, range: 2.4, maxBlur: 4 }, out.dof || {});
3774
+ } else {
3775
+ out.env.bg = '#1b1a22';
3776
+ setKey([0.35, -0.7, 0.5], '#ffe7c4', 1.4);
3777
+ }
3778
+ return out;
3779
+ }
3780
+
3781
+ /**
3782
+ * 给规格里的机位生成一段可编辑关键帧。纯函数:不改入参。
3783
+ * opts = { duration, camera(id 或 name,缺省第一台), fovEnd }
3784
+ */
3785
+ export function applyCameraMove(spec, moveId, opts) {
3786
+ const o = opts || {};
3787
+ const id = String(moveId || 'static');
3788
+ const out = cloneSpec(spec);
3789
+ const cams = Array.isArray(out.cameras) ? out.cameras : [];
3790
+ if (!cams.length) return out;
3791
+ let cam = cams[0];
3792
+ if (o.camera) cam = cams.find((c) => c.id === o.camera || c.name === o.camera) || cam;
3793
+ const pos = asVec3(cam.pos, [0, 2, 6]);
3794
+ const target = asVec3(cam.target, [0, 1, 0]);
3795
+ const fov = clampFov(cam.fov);
3796
+ const dur = Math.max(0.5, Number(o.duration) || Number(out.duration) || 5);
3797
+ const toc = (p, tg, f, t, ease) => ({ t, pos: p.slice(), target: (tg || target).slice(), fov: f === undefined ? fov : clampFov(f), ...(ease ? { ease } : {}) });
3798
+ const dir = [target[0] - pos[0], target[1] - pos[1], target[2] - pos[2]];
3799
+ const dist = Math.max(0.001, Math.sqrt(dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]));
3800
+ const unit = [dir[0] / dist, dir[1] / dist, dir[2] / dist];
3801
+ let keys;
3802
+ switch (id) {
3803
+ case 'push_in':
3804
+ keys = [toc(pos, target, fov, 0), toc(lerpVec(pos, target, 0.3), target, fov, dur)];
3805
+ break;
3806
+ case 'pull_out':
3807
+ keys = [toc(pos, target, fov, 0), toc(lerpVec(pos, target, -0.3), target, fov, dur)];
3808
+ break;
3809
+ case 'pan_left':
3810
+ keys = [toc(pos, target, fov, 0), toc(pos, [target[0] - 1.2, target[1], target[2]], fov, dur)];
3811
+ break;
3812
+ case 'pan_right':
3813
+ keys = [toc(pos, target, fov, 0), toc(pos, [target[0] + 1.2, target[1], target[2]], fov, dur)];
3814
+ break;
3815
+ case 'orbit_left':
3816
+ keys = [toc(pos, target, fov, 0), toc(orbitVec(pos, target, -45), target, fov, dur)];
3817
+ break;
3818
+ case 'orbit_right':
3819
+ keys = [toc(pos, target, fov, 0), toc(orbitVec(pos, target, 45), target, fov, dur)];
3820
+ break;
3821
+ case 'arc_left':
3822
+ keys = [toc(pos, target, fov, 0), toc(orbitVec(pos, target, -60, 0.9), target, fov, dur)];
3823
+ break;
3824
+ case 'arc_right':
3825
+ keys = [toc(pos, target, fov, 0), toc(orbitVec(pos, target, 60, 0.9), target, fov, dur)];
3826
+ break;
3827
+ case 'crane_up':
3828
+ keys = [toc(pos, target, fov, 0), toc([pos[0], pos[1] + 1.3, pos[2]], [target[0], target[1] + 0.2, target[2]], fov, dur)];
3829
+ break;
3830
+ case 'crane_down':
3831
+ keys = [toc(pos, target, fov, 0), toc([pos[0], Math.max(0.3, pos[1] - 1.3), pos[2]], [target[0], Math.max(0.2, target[1] - 0.2), target[2]], fov, dur)];
3832
+ break;
3833
+ case 'dolly_zoom':
3834
+ keys = [toc(pos, target, fov, 0), toc(lerpVec(pos, target, 0.25), target, Math.min(140, fov * 1.35), dur)];
3835
+ break;
3836
+ case 'crash_zoom':
3837
+ keys = [toc(pos, target, fov, 0), toc(lerpVec(pos, target, 0.45), target, Math.max(8, fov * 0.72), dur * 0.35, 'linear'), toc(lerpVec(pos, target, 0.45), target, Math.max(8, fov * 0.72), dur, 'constant')];
3838
+ break;
3839
+ case 'follow':
3840
+ keys = [toc(pos, target, fov, 0), toc([pos[0] + unit[0] * 1.6, pos[1], pos[2] + unit[2] * 1.6], [target[0] + unit[0] * 1.6, target[1], target[2] + unit[2] * 1.6], fov, dur)];
3841
+ break;
3842
+ case 'tracking':
3843
+ keys = [toc(pos, target, fov, 0), toc([pos[0] + 2, pos[1], pos[2]], [target[0] + 2, target[1], target[2]], fov, dur)];
3844
+ break;
3845
+ case 'reveal':
3846
+ keys = [toc(lerpVec(pos, target, 0.35), target, fov, 0), toc(pos, target, fov, dur)];
3847
+ break;
3848
+ case 'whip_pan':
3849
+ keys = [toc(pos, target, fov, 0), toc(pos, [target[0] + 3, target[1], target[2]], fov, dur * 0.2, 'linear'), toc(pos, [target[0] + 3, target[1], target[2]], fov, dur, 'constant')];
3850
+ break;
3851
+ case 'orbit_high':
3852
+ keys = [toc(pos, target, fov, 0), toc([orbitVec(pos, target, 45)[0], pos[1] + 1.1, orbitVec(pos, target, 45)[2]], target, fov, dur)];
3853
+ break;
3854
+ case 'vertigo':
3855
+ keys = [toc(pos, target, fov, 0), toc(lerpVec(pos, target, 0.25), target, Math.max(8, fov * 0.7), dur)];
3856
+ break;
3857
+ case 'handheld':
3858
+ keys = [0, 0.25, 0.5, 0.75, 1].map((k) => toc([
3859
+ pos[0] + Math.sin(k * 17.3) * 0.025,
3860
+ pos[1] + Math.sin(k * 23.1) * 0.02,
3861
+ pos[2] + Math.cos(k * 19.7) * 0.025,
3862
+ ], target, fov, dur * k));
3863
+ break;
3864
+ case 'static':
3865
+ default:
3866
+ keys = [toc(pos, target, fov, 0), toc(pos, target, fov, dur)];
3867
+ break;
3868
+ }
3869
+ cam.keys = keys;
3870
+ out.cameraMove = id;
3871
+ out.shot = out.shot || {};
3872
+ out.shot.cameraMove = id;
3873
+ return out;
3874
+ }
3875
+
3876
+ /**
3877
+ * 应用运镜/转场预设:转场映射到基础机位运动;模板只写备注。
3878
+ * 纯函数,不修改入参。
3879
+ */
3880
+ export function applyMotionPreset(spec, presetId, opts) {
3881
+ const p = MOTION_PRESETS.find((x) => x.id === String(presetId || ''));
3882
+ if (!p) return spec;
3883
+ let out = p.cameraMove ? applyCameraMove(spec, p.cameraMove, opts) : cloneSpec(spec);
3884
+ out.motionPreset = p.id;
3885
+ out.shot = out.shot || {};
3886
+ out.shot.note = [out.shot.note, p.promptZh].filter(Boolean).join(' · ');
3887
+ return out;
3888
+ }
3889
+
3890
+ /**
3891
+ * 以当前机位为基准,生成四/十二方位截图用的临时机位(纯函数)。
3892
+ * count=4:围绕主体的前/右/后/左;count=12:3 个高度层 × 4 个方向。
3893
+ * 返回 [{ name, nameEn, pos:[x,y,z], target:[x,y,z], fov }],不修改入参。
3894
+ */
3895
+ export function viewCamerasAround(scene, opts) {
3896
+ const o = opts || {};
3897
+ const count = Number(o.count) === 12 ? 12 : 4;
3898
+ const cams = Array.isArray(scene && scene.cameras) ? scene.cameras : [];
3899
+ const base = cams.find((c) => c && c.id === (scene && scene.activeCameraId)) || cams[0] || {};
3900
+ const target = asVec3(base.target, [0, 1, 0]);
3901
+ const pos = asVec3(base.pos, [0, 2, 6]);
3902
+ const fov = clampFov(base.fov);
3903
+ const dist = Math.max(1.6, Math.hypot(pos[0] - target[0], pos[2] - target[2]));
3904
+ const baseYaw = Math.atan2(pos[0] - target[0], pos[2] - target[2]);
3905
+ const dirs = [
3906
+ { zh: '前', en: 'front', a: 0 },
3907
+ { zh: '右', en: 'right', a: Math.PI / 2 },
3908
+ { zh: '后', en: 'back', a: Math.PI },
3909
+ { zh: '左', en: 'left', a: -Math.PI / 2 },
3910
+ ];
3911
+ const out = [];
3912
+ if (count === 4) {
3913
+ for (const d of dirs) {
3914
+ const a = baseYaw + d.a;
3915
+ out.push({
3916
+ name: d.zh, nameEn: d.en,
3917
+ pos: [target[0] + Math.sin(a) * dist, Math.max(0.3, pos[1]), target[2] + Math.cos(a) * dist],
3918
+ target: target.slice(), fov,
3919
+ });
3920
+ }
3921
+ return out;
3922
+ }
3923
+ const heights = [
3924
+ Math.max(0.8, pos[1] - 0.8),
3925
+ Math.max(1.2, pos[1]),
3926
+ Math.max(1.8, pos[1] + 1.2),
3927
+ ];
3928
+ const levels = [{ zh: '低', en: 'low' }, { zh: '中', en: 'mid' }, { zh: '高', en: 'high' }];
3929
+ for (let li = 0; li < 3; li++) {
3930
+ for (const d of dirs) {
3931
+ const a = baseYaw + d.a;
3932
+ out.push({
3933
+ name: levels[li].zh + d.zh, nameEn: levels[li].en + '-' + d.en,
3934
+ pos: [target[0] + Math.sin(a) * dist, heights[li], target[2] + Math.cos(a) * dist],
3935
+ target: target.slice(), fov,
3936
+ });
3937
+ }
3938
+ }
3939
+ return out;
3940
+ }
3941
+
3942
+ /**
3943
+ * 手绘运镜:地面路径点 → 相机关键帧(纯函数)。
3944
+ * path: [{x,z}] 或 [[x,z]];opts = { duration, posY, targetY, fov }
3945
+ * 相机沿路径移动,target 看向下一个路径点(末点用前一段方向延伸)。
3946
+ */
3947
+ export function cameraPathKeys(path, opts) {
3948
+ const o = opts || {};
3949
+ const raw = Array.isArray(path) ? path : [];
3950
+ const pts = raw.map((p) => {
3951
+ if (Array.isArray(p)) return { x: Number(p[0]) || 0, z: Number(p[1]) || 0 };
3952
+ return { x: Number(p && p.x) || 0, z: Number(p && p.z) || 0 };
3953
+ });
3954
+ if (!pts.length) return { keys: [] };
3955
+ if (pts.length === 1) pts.push({ x: pts[0].x, z: pts[0].z });
3956
+ const dur = Math.max(0.5, Number(o.duration) || 5);
3957
+ const y = Number.isFinite(o.posY) ? o.posY : 1.6;
3958
+ const ty = Number.isFinite(o.targetY) ? o.targetY : 1.0;
3959
+ const fov = clampFov(o.fov);
3960
+ const keys = pts.map((p, i) => {
3961
+ const t = dur * i / (pts.length - 1);
3962
+ const next = pts[Math.min(pts.length - 1, i + 1)];
3963
+ const prev = pts[Math.max(0, i - 1)];
3964
+ let tx = next.x, tz = next.z;
3965
+ if (Math.abs(tx - p.x) < 1e-6 && Math.abs(tz - p.z) < 1e-6) {
3966
+ tx = p.x + (p.x - prev.x);
3967
+ tz = p.z + (p.z - prev.z);
3968
+ }
3969
+ return { t, pos: [p.x, y, p.z], target: [tx, ty, tz], fov, ease: 'auto' };
3970
+ });
3971
+ return { keys };
3972
+ }
3973
+
3974
+ /**
3975
+ * 从设定集角色添加一个 3D 场景对象(纯函数)。
3976
+ * char = { name, assetIds? };opts = { x,z,rotY,h,color,pose,assetId }
3977
+ * 同名(model/actor/body)已存在时只返回 id,不重复添加。
3978
+ */
3979
+ export function addBibleCharacter(scene, char, opts) {
3980
+ const name = String((char && char.name) || '').trim();
3981
+ const src = JSON.parse(JSON.stringify(scene || {}));
3982
+ const objects = Array.isArray(src.objects) ? src.objects : [];
3983
+ if (!name) {
3984
+ src.objects = objects;
3985
+ return { added: false, scene: src, id: null };
3986
+ }
3987
+ const hit = objects.find((o) => String(o.name || '').trim() === name && (o.kind === 'model' || o.kind === 'actor' || o.kind === 'body'));
3988
+ if (hit) return { added: false, scene: src, id: hit.id || null };
3989
+ const o = opts || {};
3990
+ const id = 'char_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 5);
3991
+ objects.push({
3992
+ id, kind: 'model', assetId: String(o.assetId || 'xbot'),
3993
+ name: name.slice(0, 40),
3994
+ pos: { x: Number(o.x) || 0, y: 0, z: Number(o.z) || 0 },
3995
+ rotY: Number(o.rotY) || 0,
3996
+ h: Number(o.h) || 1.75,
3997
+ color: String(o.color || '#c9ced6'),
3998
+ visible: true,
3999
+ poseId: String(o.pose || 'stand'),
4000
+ refAssetIds: Array.isArray(char && char.assetIds) ? char.assetIds.map(String).filter(Boolean).slice(0, 8) : [],
4001
+ });
4002
+ src.objects = objects;
4003
+ return { added: true, scene: src, id };
4004
+ }
4005
+
4006
+ /** 9 个场景预设 → 规格。所有坐标用 [x,y,z],与 buildStageFromSpec 的二维 [x,z] 兼容。 */
4007
+ export function specFromScenePreset(presetId, opts) {
4008
+ const o = opts || {};
4009
+ const id = String(presetId || 'dialogue2');
4010
+ const dur = Math.max(1.5, Number(o.duration) || 8);
4011
+ const actors = Array.isArray(o.actors) && o.actors.length ? o.actors : ['主角', '对手', '第三角色', '第四角色'];
4012
+ const A = String(actors[0] || '主角');
4013
+ const B = String(actors[1] || '对手');
4014
+ const C = String(actors[2] || '第三角色');
4015
+ const D = String(actors[3] || '第四角色');
4016
+ const base = (title, env) => ({
4017
+ title: String(o.brief || title).slice(0, 40),
4018
+ duration: dur,
4019
+ env: Object.assign({ preset: 'studio', grid: true, tonemap: 'agx' }, env || {}),
4020
+ });
4021
+ const lights = [{ dir: [0.35, -0.78, 0.45], color: '#ffffff', intensity: 1.3 }, { dir: [-0.45, -0.25, -0.5], color: '#9fb4d8', intensity: 0.5 }];
4022
+ const table = { name: '桌子', preset: 'box', pos: [0, 0, 0], scale: [2.2, 0.75, 1.1], color: '#8f98a3' };
4023
+ if (id === 'blank') {
4024
+ return Object.assign(base('空白场景', { preset: 'studio' }), {
4025
+ characters: [], props: [{ name: '地面', preset: 'plane', pos: [0, 0, 0], scale: [14, 1, 14], color: '#9aa3ad' }],
4026
+ cameras: [{ name: '主机位', pos: [0, 2.2, 6], target: [0, 1, 0], fov: 42 }],
4027
+ shots: [{ camera: '主机位', start: 0, end: dur }], lights, dof: { focus: 5, range: 4, maxBlur: 4 },
4028
+ });
4029
+ }
4030
+ if (id === 'chase') {
4031
+ const half = Math.max(0.8, dur / 2);
4032
+ return Object.assign(base('追逐场景', { preset: 'daylight' }), {
4033
+ characters: [
4034
+ { name: A, pos: [-3, 0, 0], rotY: 0, clip: 'run', color: '#c9ced6', path: [[-3, 0], [-3, 0], [4, -1.5], [9, -1.5]], pathFace: true, locomotion: { source: 'clip', stride: 1.1, cycle: 0.8, refSpeed: 4 } },
4035
+ { name: B, pos: [-4.6, 0, 0.6], rotY: 0, clip: 'run', color: '#b3bcc6', path: [[-4.6, 0.6], [-4.6, 0.6], [3, -1.0], [8.2, -1.0]], pathFace: true, locomotion: { source: 'clip', stride: 1.1, cycle: 0.8, refSpeed: 4 } },
4036
+ ],
4037
+ props: [{ name: '路面', preset: 'plane', pos: [2, 0, 0], scale: [26, 1, 10], color: '#9aa3ad' }],
4038
+ cameras: [{ name: '侧跟', pos: [1.5, 1.6, 7.5], target: [1.5, 1.0, 0], fov: 44 }, { name: '低位追', pos: [5.5, 0.8, 5.2], target: [3.5, 1.0, 0], fov: 40 }],
4039
+ shots: [{ camera: '侧跟', start: 0, end: half }, { camera: '低位追', start: half, end: dur }],
4040
+ lights: [{ dir: [0.4, -0.75, 0.4], color: '#fff4e0', intensity: 1.3 }], dof: { focus: 6, range: 5, maxBlur: 4 },
4041
+ });
4042
+ }
4043
+ if (id === 'dialogue2' || id === 'dialogue3') {
4044
+ const three = id === 'dialogue3';
4045
+ const chars = three
4046
+ ? [{ name: A, pos: [-1.1, 0, 0.2], rotY: 1.2, clip: 'idle', color: '#c9ced6' }, { name: B, pos: [1.1, 0, 0.2], rotY: -1.2, clip: 'idle', color: '#b9c2cc' }, { name: C, pos: [0, 0, -1.3], rotY: 0.2, clip: 'idle', color: '#c3bdd0' }]
4047
+ : [{ name: A, pos: [-0.9, 0, 0], rotY: 1.45, clip: 'idle', color: '#c9ced6' }, { name: B, pos: [0.9, 0, 0], rotY: -1.45, clip: 'idle', color: '#b9c2cc' }];
4048
+ const half = Math.max(0.8, dur / 2);
4049
+ const cams = three
4050
+ ? [{ name: '全景', pos: [0, 1.9, 5.2], target: [0, 1.05, 0], fov: 44 }, { name: 'A 过肩', pos: [-1.8, 1.55, -2.2], target: [0.9, 1.4, 0], fov: 40 }, { name: 'B 过肩', pos: [1.8, 1.55, -2.2], target: [-0.9, 1.4, 0], fov: 40 }]
4051
+ : [{ name: 'A 过肩', pos: [-1.5, 1.55, -2.1], target: [0.9, 1.4, 0], fov: 40 }, { name: 'B 过肩', pos: [1.5, 1.55, -2.1], target: [-0.9, 1.4, 0], fov: 40 }, { name: '双人', pos: [0, 1.5, 4.6], target: [0, 1.05, 0], fov: 40 }];
4052
+ const shots = three
4053
+ ? [{ camera: '全景', start: 0, end: dur * 0.25 }, { camera: 'A 过肩', start: dur * 0.25, end: dur * 0.62 }, { camera: 'B 过肩', start: dur * 0.62, end: dur }]
4054
+ : [{ camera: '双人', start: 0, end: Math.max(0.6, dur * 0.2) }, { camera: 'A 过肩', start: Math.max(0.6, dur * 0.2), end: half }, { camera: 'B 过肩', start: half, end: dur }];
4055
+ return Object.assign(base(three ? '三人对话' : '对话双人', { preset: 'studio' }), {
4056
+ characters: chars, props: [table], cameras: cams, shots, lights,
4057
+ dof: { focus: 4.5, range: 2.2, maxBlur: 7 },
4058
+ });
4059
+ }
4060
+ if (id === 'interview') {
4061
+ return Object.assign(base('采访场景', { preset: 'studio' }), {
4062
+ characters: [{ name: A, pos: [-1.1, 0, 0], rotY: 1.35, clip: 'idle', color: '#c9ced6' }, { name: B, pos: [1.1, 0, 0], rotY: -1.35, clip: 'idle', color: '#b9c2cc' }],
4063
+ props: [table, { name: '水杯', preset: 'cylinder', pos: [0.7, 0.82, 0.2], scale: [0.09, 0.16, 0.09], color: '#b9c6d2' }],
4064
+ cameras: [{ name: '主持近景', pos: [-2.2, 1.55, 1.8], target: [-1.1, 1.4, 0], fov: 36 }, { name: '嘉宾近景', pos: [2.2, 1.55, 1.8], target: [1.1, 1.4, 0], fov: 36 }, { name: '双人', pos: [0, 1.65, 4.4], target: [0, 1.1, 0], fov: 42 }],
4065
+ shots: [{ camera: '双人', start: 0, end: dur * 0.2 }, { camera: '主持近景', start: dur * 0.2, end: dur * 0.6 }, { camera: '嘉宾近景', start: dur * 0.6, end: dur }],
4066
+ lights, dof: { focus: 4.2, range: 2.4, maxBlur: 5 },
4067
+ });
4068
+ }
4069
+ if (id === 'monologue') {
4070
+ return Object.assign(base('独白特写', { preset: 'studio' }), {
4071
+ characters: [{ name: A, pos: [0, 0, 0], rotY: 0, clip: 'idle', color: '#c9ced6' }],
4072
+ props: [{ name: '地面', preset: 'plane', pos: [0, 0, 0], scale: [10, 1, 10], color: '#9aa3ad' }],
4073
+ cameras: [{ name: '正面特写', pos: [0, 1.55, 1.5], target: [0, 1.42, 0], fov: 30 }, { name: '侧面近景', pos: [1.7, 1.5, 1.2], target: [0, 1.35, 0], fov: 34 }],
4074
+ shots: [{ camera: '正面特写', start: 0, end: dur * 0.65 }, { camera: '侧面近景', start: dur * 0.65, end: dur }],
4075
+ lights, dof: { focus: 1.8, range: 1.1, maxBlur: 8 },
4076
+ });
4077
+ }
4078
+ if (id === 'lecture') {
4079
+ return Object.assign(base('课堂/演讲', { preset: 'daylight' }), {
4080
+ characters: [{ name: A, pos: [0, 0, -1.4], rotY: 0, clip: 'idle', color: '#c9ced6' }, { name: B, pos: [-1.8, 0, 1.5], rotY: -2.6, clip: 'idle', color: '#b9c2cc' }, { name: C, pos: [0, 0, 1.8], rotY: -3.1, clip: 'idle', color: '#c3bdd0' }, { name: D, pos: [1.8, 0, 1.5], rotY: 2.6, clip: 'idle', color: '#b7c6bd' }],
4081
+ props: [{ name: '讲台', preset: 'box', pos: [0, 0.55, -0.9], scale: [2.4, 0.8, 0.7], color: '#8f98a3' }],
4082
+ cameras: [{ name: '全景', pos: [0, 2.4, 7], target: [0, 1.0, 0], fov: 44 }, { name: '讲者', pos: [0, 1.6, 2.4], target: [0, 1.25, -1.4], fov: 36 }],
4083
+ shots: [{ camera: '全景', start: 0, end: dur * 0.55 }, { camera: '讲者', start: dur * 0.55, end: dur }],
4084
+ lights: [{ dir: [0.4, -0.8, 0.35], color: '#fff7e8', intensity: 1.25 }], dof: { focus: 6, range: 4, maxBlur: 3 },
4085
+ });
4086
+ }
4087
+ if (id === 'outdoor_walk') {
4088
+ return Object.assign(base('户外行走', { preset: 'daylight' }), {
4089
+ characters: [
4090
+ { name: A, pos: [-0.55, 0, 0], rotY: 0, clip: 'walk', color: '#c9ced6', path: [[-0.55, 0], [-0.55, 0], [5, 0]], pathFace: true, locomotion: { source: 'clip', stride: 0.9, cycle: 1.0, refSpeed: 1.6 } },
4091
+ { name: B, pos: [0.55, 0, 0.2], rotY: 0, clip: 'walk', color: '#b9c2cc', path: [[0.55, 0.2], [0.55, 0.2], [5, 0.2]], pathFace: true, locomotion: { source: 'clip', stride: 0.9, cycle: 1.0, refSpeed: 1.6 } },
4092
+ ],
4093
+ props: [{ name: '路面', preset: 'plane', pos: [2, 0, 0], scale: [20, 1, 8], color: '#9aa3ad' }],
4094
+ cameras: [{ name: '侧面跟拍', pos: [1.8, 1.65, 5.2], target: [1.8, 1.0, 0], fov: 42 }, { name: '正面跟拍', pos: [1.8, 1.6, -4.5], target: [1.8, 1.05, 0], fov: 38 }],
4095
+ shots: [{ camera: '侧面跟拍', start: 0, end: dur * 0.55 }, { camera: '正面跟拍', start: dur * 0.55, end: dur }],
4096
+ lights: [{ dir: [0.45, -0.8, 0.35], color: '#fff4e0', intensity: 1.2 }], dof: { focus: 6, range: 5, maxBlur: 3 },
4097
+ });
4098
+ }
4099
+ // meeting
4100
+ return Object.assign(base('会议室', { preset: 'studio' }), {
4101
+ characters: [
4102
+ { name: A, pos: [-1.7, 0, 0], rotY: 1.5, clip: 'idle', color: '#c9ced6' },
4103
+ { name: B, pos: [1.7, 0, 0], rotY: -1.5, clip: 'idle', color: '#b9c2cc' },
4104
+ { name: C, pos: [0, 0, -1.4], rotY: 0.2, clip: 'idle', color: '#c3bdd0' },
4105
+ { name: D, pos: [0, 0, 1.4], rotY: 3.1, clip: 'idle', color: '#b7c6bd' },
4106
+ ],
4107
+ props: [{ name: '会议桌', preset: 'box', pos: [0, 0.4, 0], scale: [3.6, 0.8, 1.8], color: '#7f8a96' }],
4108
+ cameras: [{ name: '俯拍', pos: [0, 4.2, 3.4], target: [0, 0.4, 0], fov: 46 }, { name: '侧方全景', pos: [0, 2.1, 5.2], target: [0, 1.0, 0], fov: 42 }],
4109
+ shots: [{ camera: '俯拍', start: 0, end: dur * 0.45 }, { camera: '侧方全景', start: dur * 0.45, end: dur }],
4110
+ lights, dof: { focus: 5, range: 4, maxBlur: 4 },
4111
+ });
4112
+ }
4113
+
3244
4114
  /**
3245
4115
  * 一句话 → 场景规格。
3246
4116
  * opts = { template, duration, actors, mood }
@@ -3265,8 +4135,16 @@ export function specFromBrief(brief, opts) {
3265
4135
  duration: dur,
3266
4136
  env: { preset: tpl === 'chase' ? 'daylight' : tpl === 'fight' ? 'night' : 'studio', grid: true, tonemap: 'agx' },
3267
4137
  };
4138
+ // 3D-BOX 组合入口:显式场景预设优先;风格与运镜在最后统一施加,保持旧模板行为不变。
4139
+ const finish = (spec) => {
4140
+ let out = spec;
4141
+ if (o.style) out = applyDirectorStyle(out, o.style);
4142
+ if (o.cameraMove) out = applyCameraMove(out, o.cameraMove, { duration: out.duration || dur });
4143
+ return out;
4144
+ };
4145
+ if (o.scene) return finish(specFromScenePreset(o.scene, { brief, duration: dur, actors }));
3268
4146
  if (tpl === 'fight') {
3269
- return Object.assign(base, {
4147
+ return finish(Object.assign(base, {
3270
4148
  characters: [
3271
4149
  { name: A, pos: [-1.1, 0, 0], rotY: 1.2, pose: 'fight', color: '#c9ced6' },
3272
4150
  { name: B, pos: [1.1, 0, 0], rotY: -1.2, pose: 'fight', color: '#b9c2cc' },
@@ -3287,10 +4165,10 @@ export function specFromBrief(brief, opts) {
3287
4165
  fog: { color: '#2a3038', near: 6, far: 22, density: 1 },
3288
4166
  dof: { focus: 4.2, range: 2.6, maxBlur: 5 },
3289
4167
  poseAnim: null,
3290
- });
4168
+ }));
3291
4169
  }
3292
4170
  if (tpl === 'chase') {
3293
- return Object.assign(base, {
4171
+ return finish(Object.assign(base, {
3294
4172
  characters: [
3295
4173
  { name: A, pos: [-3, 0, 0], rotY: 0, pose: 'run' && null, clip: 'run', color: '#c9ced6',
3296
4174
  path: [[-3, 0], [-3, 0], [4, -1.5], [9, -1.5]], pathFace: true,
@@ -3307,10 +4185,10 @@ export function specFromBrief(brief, opts) {
3307
4185
  shots: [{ camera: '侧跟', start: 0, end: half }, { camera: '低位追', start: half, end: dur }],
3308
4186
  lights: [{ dir: [0.4, -0.75, 0.4], color: '#fff4e0', intensity: 1.3 }],
3309
4187
  dof: { focus: 6, range: 5, maxBlur: 4 },
3310
- });
4188
+ }));
3311
4189
  }
3312
4190
  // dialogue:正反打
3313
- return Object.assign(base, {
4191
+ return finish(Object.assign(base, {
3314
4192
  characters: [
3315
4193
  { name: A, pos: [-0.9, 0, 0], rotY: 1.45, clip: 'idle', color: '#c9ced6' },
3316
4194
  { name: B, pos: [0.9, 0, 0], rotY: -1.45, clip: 'idle', color: '#b9c2cc' },
@@ -3328,7 +4206,7 @@ export function specFromBrief(brief, opts) {
3328
4206
  ],
3329
4207
  lights: [{ dir: [0.3, -0.7, 0.5], color: '#fff6ea', intensity: 1.15 }, { dir: [-0.5, -0.2, -0.4], color: '#cfd6e2', intensity: 0.5 }],
3330
4208
  dof: { focus: 4.5, range: 2.2, maxBlur: 7 },
3331
- });
4209
+ }));
3332
4210
  }
3333
4211
 
3334
4212
 
@@ -3418,6 +4296,120 @@ export function dopeSheetInfo(scene) {
3418
4296
  out.markers = Array.isArray(scene && scene.markers) ? scene.markers.slice() : [];
3419
4297
  return out;
3420
4298
  }
4299
+ /**
4300
+ * 角色某时刻的骨骼世界矩阵(与 skinModel 使用同一套姿态/IK/约束管线)。
4301
+ * 只给「骨骼附件」用;返回 asset/世界矩阵/身高缩放。
4302
+ */
4303
+ function directorCharacterBoneMats(ob) {
4304
+ const asset = gltfAssetOf(ob && ob.assetId);
4305
+ if (!asset || !asset.bones || !asset.nodes) return null;
4306
+ const clipName = ob.clip || (asset.animations && asset.animations[0] && asset.animations[0].name) || '';
4307
+ const clip = clipName && typeof asset.clipByName === 'function' ? asset.clipByName(clipName) : null;
4308
+ asset._anim = clip;
4309
+ const shape = Object.assign({},
4310
+ ob.typeId ? bodyShapeOf(ob.typeId) : {},
4311
+ ob.bonePose ? { bonePose: ob.bonePose } : {},
4312
+ ob.poseId ? { poseId: ob.poseId } : {},
4313
+ ob.poseBlend ? { poseBlend: ob.poseBlend } : {},
4314
+ ob.skinning ? { skinning: ob.skinning } : {},
4315
+ ob.ik ? { ik: ob.ik } : {},
4316
+ ob.constraints ? { constraints: ob.constraints } : {},
4317
+ ob.clips ? { clips: ob.clips } : {});
4318
+ const time = Number(ob.animTime) || 0;
4319
+ const poseMap = shape.bonePose && Object.keys(shape.bonePose).length ? shape.bonePose : null;
4320
+ const poseId = shape.poseId || null;
4321
+ const spec = poseId ? (BONE_POSES.find((p) => p.id === poseId) || null) : null;
4322
+ const poseDirs = spec ? (spec.dirs || []) : (shape.poseDirs || null);
4323
+ const poseBase = spec ? (spec.base || null) : null;
4324
+ const poseRootY = spec ? (Number(spec.rootY) || 0) : (Number(shape.rootY) || 0);
4325
+ const poseBlend = shape.poseBlend && shape.poseBlend.length ? shape.poseBlend : null;
4326
+ const wantPose = !!(poseMap || (poseDirs && poseDirs.length) || poseBase || poseBlend || shape.ik || shape.constraints || shape.clips);
4327
+ const bm = poseBlend
4328
+ ? boneMatricesWithPoseMix(asset, time, poseBlend)
4329
+ : (wantPose
4330
+ ? boneMatricesWithPose(asset, time, poseMap, poseDirs, poseBase, poseRootY,
4331
+ (shape.ik || shape.constraints || shape.clips) ? { ik: shape.ik, constraints: shape.constraints, clips: shape.clips } : null)
4332
+ : boneMatrices(asset, time));
4333
+ if (!bm || !bm.world) return null;
4334
+ const ms = Number(asset.rawHeight) > 0 ? (Number(ob.h) || 1.78) / asset.rawHeight : 1;
4335
+ return { asset, world: bm.world, scale: ms };
4336
+ }
4337
+
4338
+ const directorNormBone = (s) => String(s || '').toLowerCase().replace(/^mixamorig:?/, '').replace(/[^a-z0-9]/g, '');
4339
+
4340
+ /** 骨骼名容错:RightHand / right_hand / mixamorig:RightHand 都能命中;找不到返回 -1。 */
4341
+ export function directorBoneIndex(asset, name) {
4342
+ if (!asset || !Array.isArray(asset.bones)) return -1;
4343
+ const want = directorNormBone(name);
4344
+ if (!want) return -1;
4345
+ let i = asset.bones.findIndex((b) => directorNormBone(b && b.name) === want);
4346
+ if (i < 0) i = asset.bones.findIndex((b) => directorNormBone(b && b.name).includes(want));
4347
+ return i;
4348
+ }
4349
+
4350
+ /** 欧拉角 → 局部轴(R = Ry·Rx·Rz,与 objectAxes 同序)。 */
4351
+ function directorAxesFromEuler(rx, ry, rz) {
4352
+ const cx = Math.cos(rx), sx = Math.sin(rx);
4353
+ const cy = Math.cos(ry), sy = Math.sin(ry);
4354
+ const cz = Math.cos(rz), sz = Math.sin(rz);
4355
+ return {
4356
+ x: v3(cy * cz + sy * sx * sz, cx * sz, -sy * cz + cy * sx * sz),
4357
+ y: v3(-cy * sz + sy * sx * cz, cx * cz, sy * sz + cy * sx * cz),
4358
+ z: v3(sy * cx, -sx, cy * cx),
4359
+ };
4360
+ }
4361
+ /** 局部轴相乘:返回 A·B(先作用 B 再作用 A)。 */
4362
+ function directorAxesMul(A, B) {
4363
+ const mul = (c) => v3(A.x.x * c.x + A.y.x * c.y + A.z.x * c.z, A.x.y * c.x + A.y.y * c.y + A.z.y * c.z, A.x.z * c.x + A.y.z * c.y + A.z.z * c.z);
4364
+ return { x: mul(B.x), y: mul(B.y), z: mul(B.z) };
4365
+ }
4366
+ /** 局部轴 → 欧拉角(R = Ry·Rx·Rz 约定);万向锁时 rz 置 0。 */
4367
+ function directorEulerFromAxes(A) {
4368
+ const rx = Math.asin(Math.max(-1, Math.min(1, -A.z.y)));
4369
+ const cx = Math.cos(rx);
4370
+ let ry, rz;
4371
+ if (Math.abs(cx) > 1e-6) {
4372
+ ry = Math.atan2(A.z.x, A.z.z);
4373
+ rz = Math.atan2(A.x.y / cx, A.y.y / cx);
4374
+ } else {
4375
+ rz = 0;
4376
+ ry = Math.atan2(A.x.x, -A.x.z);
4377
+ }
4378
+ return { rx, ry, rz };
4379
+ }
4380
+
4381
+ /**
4382
+ * 骨骼插槽(角色局部坐标):返回骨骼原点 + 完整局部轴 + 偏航角,供武器/帽子/背包跟随。
4383
+ * 不生成网格,只读骨骼世界矩阵;找不到骨骼时返回 null(不把道具瞬移到脚下)。
4384
+ */
4385
+ export function directorObjectBoneSocket(ob, boneName) {
4386
+ const mats = directorCharacterBoneMats(ob);
4387
+ if (!mats) return null;
4388
+ const bi = directorBoneIndex(mats.asset, boneName);
4389
+ if (bi < 0) return null;
4390
+ const bone = mats.asset.bones[bi];
4391
+ const m = mats.world[bone.nodeIdx];
4392
+ if (!m) return null;
4393
+ const k = mats.scale * (Number(ob.s) || 1);
4394
+ const sc = ob.scale || { x: 1, y: 1, z: 1 };
4395
+ // 骨骼旋转列归一化(蒙皮矩阵带缩放,附件只要方向)
4396
+ const norm = (x, y, z) => { const l = Math.hypot(x, y, z) || 1; return v3(x / l, y / l, z / l); };
4397
+ return {
4398
+ x: m[12] * k * (Number(sc.x) || 1),
4399
+ y: m[13] * k * (Number(sc.y) || 1),
4400
+ z: m[14] * k * (Number(sc.z) || 1),
4401
+ yaw: Math.atan2(m[8], m[10]),
4402
+ axes: { x: norm(m[0], m[1], m[2]), y: norm(m[4], m[5], m[6]), z: norm(m[8], m[9], m[10]) },
4403
+ };
4404
+ }
4405
+
4406
+ /** 资产的骨骼名清单(去掉 mixamorig: 前缀),供附件 UI 与 AI prompt 使用。 */
4407
+ export function directorBoneNames(assetId) {
4408
+ const asset = gltfAssetOf(assetId);
4409
+ if (!asset || !Array.isArray(asset.bones)) return [];
4410
+ return asset.bones.map((b) => String((b && b.name) || '').replace(/^mixamorig:?/i, '')).filter(Boolean);
4411
+ }
4412
+
3421
4413
  export function applyPlayhead(scene, t) {
3422
4414
  if (!scene) return scene;
3423
4415
  const time = Math.max(0, Number(t) || 0);
@@ -3575,6 +4567,54 @@ export function applyPlayhead(scene, t) {
3575
4567
  return next;
3576
4568
  });
3577
4569
 
4570
+ // 骨骼附件:武器/帽子/背包跟随角色骨骼(在对象运动求值之后覆盖 pos/rotY/rx/rz)
4571
+ {
4572
+ const byId = new Map();
4573
+ const byName = new Map();
4574
+ for (const o of out.objects) {
4575
+ byId.set(String(o.id), o);
4576
+ if (o.name && !byName.has(String(o.name))) byName.set(String(o.name), o);
4577
+ }
4578
+ for (const ob of out.objects) {
4579
+ const at = ob.attach;
4580
+ if (!at || typeof at !== 'object') continue;
4581
+ const key = String(at.to || at.character || at.target || '');
4582
+ // 先按 id 精确匹配,找不到再按 name(避免角色名与道具 id 撞名时绑错)
4583
+ const target = byId.get(key) || byName.get(key);
4584
+ if (!target || target === ob || (target.kind !== 'model' && target.kind !== 'actor')) continue;
4585
+ const sock = directorObjectBoneSocket(target, at.bone || 'RightHand');
4586
+ if (!sock) continue;
4587
+ const cry = Number(target.rotY) || 0;
4588
+ const cc = Math.cos(cry), cs = Math.sin(cry);
4589
+ const bx = target.pos.x + sock.x * cc + sock.z * cs;
4590
+ const by = target.pos.y + sock.y;
4591
+ const bz = target.pos.z - sock.x * cs + sock.z * cc;
4592
+ const oo = Array.isArray(at.offset) ? at.offset : (at.offset || []);
4593
+ const ox = Number(oo[0] !== undefined ? oo[0] : oo.x) || 0;
4594
+ const oy = Number(oo[1] !== undefined ? oo[1] : oo.y) || 0;
4595
+ const oz = Number(oo[2] !== undefined ? oo[2] : oo.z) || 0;
4596
+ // 朝向 = 角色偏航 · 骨骼旋转 · 附件自转(含俯仰/翻滚,不只是偏航)
4597
+ const worldAxes = sock.axes
4598
+ ? directorAxesMul(directorAxesMul(directorAxesFromEuler(0, cry, 0), sock.axes), directorAxesFromEuler(Number(at.rx) || 0, Number(at.rotY) || 0, Number(at.rz) || 0))
4599
+ : null;
4600
+ const eul = worldAxes ? directorEulerFromAxes(worldAxes) : { rx: 0, ry: cry + sock.yaw + (Number(at.rotY) || 0), rz: 0 };
4601
+ ob.pos = worldAxes
4602
+ ? v3(bx + ox * worldAxes.x.x + oy * worldAxes.y.x + oz * worldAxes.z.x,
4603
+ by + ox * worldAxes.x.y + oy * worldAxes.y.y + oz * worldAxes.z.y,
4604
+ bz + ox * worldAxes.x.z + oy * worldAxes.y.z + oz * worldAxes.z.z)
4605
+ : (() => { const oc = Math.cos(cry + sock.yaw), os = Math.sin(cry + sock.yaw); return v3(bx + ox * oc + oz * os, by + oy, bz - ox * os + oz * oc); })();
4606
+ ob.rotY = eul.ry;
4607
+ ob.rx = eul.rx;
4608
+ ob.rz = eul.rz;
4609
+ ob.attachBone = String(at.bone || 'RightHand');
4610
+ const k2 = Number(at.scale);
4611
+ if (k2 > 0) {
4612
+ const bs = ob.scale || { x: 1, y: 1, z: 1 };
4613
+ ob.scale = v3((Number(bs.x) || 1) * k2, (Number(bs.y) || 1) * k2, (Number(bs.z) || 1) * k2);
4614
+ }
4615
+ }
4616
+ }
4617
+
3578
4618
  // 分镜串联:当前时间的活动相机(覆盖 activeCameraId)
3579
4619
  const liveCamId = activeCameraAt(scene, time);
3580
4620
  out.activeCameraId = liveCamId || scene.activeCameraId;
@@ -4124,6 +5164,81 @@ export function actorTypeIdOf(presetId) {
4124
5164
  }
4125
5165
  return 'm_standard';
4126
5166
  }
5167
+ /**
5168
+ * 基础几何体的局部单位面(底面在 y=0,X/Z 居中,单位高度 1)。
5169
+ * compound 与普通 geom 共用同一套图元,避免两处尺寸漂移。
5170
+ */
5171
+ function directorPrimitiveLocalFaces(preset) {
5172
+ const p = String(preset || 'box');
5173
+ if (p === 'sphere') return directorSphereFaces(0, 0.5, 0, 0.5);
5174
+ if (p === 'cylinder') return directorCylinderFaces(0, 0.5, 0, 0.5, 1);
5175
+ if (p === 'cone') return directorConeFaces(0, 0, 0, 0.5, 1);
5176
+ if (p === 'plane') return directorBoxFaces(0, 0.005, 0, 1, 0.01, 1);
5177
+ if (p === 'capsule') return directorCapsuleFaces(0, 0.5, 0, 0.25, 0.5);
5178
+ if (p === 'torus') return directorTorusFaces(0, 0.5, 0, 0.35, 0.15);
5179
+ if (p === 'pyramid') return directorPyramidFaces(0, 0, 0, 1, 1, 1);
5180
+ if (p === 'disc') return directorDiskFaces(0, 0.01, 0, 0.5);
5181
+ if (p === 'arc') return directorHalfArcFaces(0, 0.5, 0, 0.5, 0.1);
5182
+ if (p === 'half_cylinder') return directorHalfCylinderFaces(0, 0.5, 0, 0.5, 1);
5183
+ if (p === 'ancient_house') return ancientHouseFaces(0, 0, 0, 1, 1, 1, 0.34);
5184
+ if (p === 'ancient_stall') return ancientStallFaces(0, 0, 0, 1, 1, 1);
5185
+ if (p === 'stone_step') return directorBoxFaces(0, 0.15, 0, 1, 0.3, 1);
5186
+ return directorBoxFaces(0, 0.5, 0, 1, 1, 1);
5187
+ }
5188
+
5189
+ /** 单位图元高度(锚点/包围盒用,绝不生成网格)。 */
5190
+ function directorPrimitiveUnitHeight(preset) {
5191
+ const p = String(preset || 'box');
5192
+ if (p === 'plane' || p === 'disc') return 0.01;
5193
+ if (p === 'ancient_house') return 1.34;
5194
+ if (p === 'ancient_stall') return 0.84;
5195
+ if (p === 'stone_step') return 0.3;
5196
+ return 1;
5197
+ }
5198
+
5199
+ /**
5200
+ * 参数化组合道具:一个对象由多个基础图元组成(警车/武器/路灯/桌椅)。
5201
+ * part.pos 是相对父对象的地面偏移(底面中心),part.scale 是 [宽,高,深];
5202
+ * 各部件跟随父对象的 pos/rotY/scale,并保留自己的颜色供渲染分批。
5203
+ */
5204
+ function directorCompoundFaces(ob) {
5205
+ const sc = ob.scale || { x: 1, y: 1, z: 1 };
5206
+ const k = Number(ob.s) || 1;
5207
+ const psx = k * (Number(sc.x) || 1), psy = k * (Number(sc.y) || 1), psz = k * (Number(sc.z) || 1);
5208
+ const pry = Number(ob.rotY) || 0;
5209
+ const pc = Math.cos(pry), pn = Math.sin(pry);
5210
+ const out = [];
5211
+ for (const pt of ob.parts.slice(0, 64)) {
5212
+ if (!pt) continue;
5213
+ const psc = pt.scale || { x: 1, y: 1, z: 1 };
5214
+ const sx = Number(psc.x) || 1, sy = Number(psc.y) || 1, sz = Number(psc.z) || 1;
5215
+ const rx = Number(pt.rx) || 0, ry = Number(pt.rotY) || 0, rz = Number(pt.rz) || 0;
5216
+ const cx = Math.cos(rx), snx = Math.sin(rx);
5217
+ const cy = Math.cos(ry), sny = Math.sin(ry);
5218
+ const cz = Math.cos(rz), snz = Math.sin(rz);
5219
+ // 与 objectAxes 同序:R = Ry·Rx·Rz;三列即局部轴。
5220
+ const ax = v3(cy * cz + sny * snx * snz, cx * snz, -sny * cz + cy * snx * snz);
5221
+ const ay = v3(-cy * snz + sny * snx * cz, cx * cz, sny * snz + cy * snx * cz);
5222
+ const az = v3(sny * cx, -snx, cy * cx);
5223
+ const ox = Number(pt.pos && pt.pos.x) || 0;
5224
+ const oy = Number(pt.pos && pt.pos.y) || 0;
5225
+ const oz = Number(pt.pos && pt.pos.z) || 0;
5226
+ const color = String(pt.color || ob.color || '');
5227
+ for (const f of directorPrimitiveLocalFaces(pt.preset)) {
5228
+ const vv = f.v.map((p) => {
5229
+ const x = p.x * sx, y = p.y * sy, z = p.z * sz;
5230
+ const xr = ax.x * x + ay.x * y + az.x * z;
5231
+ const yr = ax.y * x + ay.y * y + az.y * z;
5232
+ const zr = ax.z * x + ay.z * y + az.z * z;
5233
+ const lx = (xr + ox) * psx, ly = (yr + oy) * psy, lz = (zr + oz) * psz;
5234
+ return v3(ob.pos.x + lx * pc + lz * pn, ob.pos.y + ly, ob.pos.z - lx * pn + lz * pc);
5235
+ });
5236
+ out.push({ v: vv, shade: f.shade, ...(color ? { color } : {}) });
5237
+ }
5238
+ }
5239
+ return out;
5240
+ }
5241
+
4127
5242
  /**
4128
5243
  * 物体锚点(标签/构图用):**O(1) 解析计算,绝不生成网格**。
4129
5244
  * 历史事故:早期版本在这里调用 directorObjectFaces(),单个模型要蒙皮 4.9 万三角形 ≈ 77ms,
@@ -4135,14 +5250,16 @@ export function directorObjectAnchor(ob) {
4135
5250
  const sc = ob.scale || { x: 1, y: 1, z: 1 };
4136
5251
  const sy = (Number(sc.y) || 1) * (Number(ob.s) || 1);
4137
5252
  let top = py + (Number(ob.h) || 1.7) * sy; // 模型/人偶:按设定身高
4138
- if (ob.kind === 'geom' || ob.kind === 'obj' || !ob.kind) {
4139
- const preset = String(ob.preset || 'box');
4140
- const unitH = preset === 'plane' || preset === 'disc' ? 0.01
4141
- : preset === 'ancient_house' ? 1.34 // 墙身 1 + 屋顶 0.34
4142
- : preset === 'ancient_stall' ? 0.84 // 台面+遮棚
4143
- : preset === 'stone_step' ? 0.3
4144
- : 1; // 其余单位图元高度 1
4145
- top = py + unitH * sy;
5253
+ if (ob.kind === 'compound' && Array.isArray(ob.parts) && ob.parts.length) {
5254
+ let partTop = 0;
5255
+ for (const pt of ob.parts) {
5256
+ const psc = pt.scale || { x: 1, y: 1, z: 1 };
5257
+ const y = (Number(pt.pos && pt.pos.y) || 0) + directorPrimitiveUnitHeight(pt.preset) * (Number(psc.y) || 1);
5258
+ if (y > partTop) partTop = y;
5259
+ }
5260
+ top = py + Math.max(0.05, Math.max(partTop, Number(ob.h) || 0)) * sy;
5261
+ } else if (ob.kind === 'geom' || ob.kind === 'obj' || !ob.kind) {
5262
+ top = py + directorPrimitiveUnitHeight(ob.preset) * sy;
4146
5263
  }
4147
5264
  // 朝向只影响平面轮廓,标签用轴对齐包围盒中心即可(不引入旋转误差)
4148
5265
  return { top, center: v3(px, top, pz) };
@@ -4177,6 +5294,9 @@ export function directorObjectFaces(ob) {
4177
5294
  }
4178
5295
  return actorFaces(ob);
4179
5296
  }
5297
+ if (ob.kind === 'compound' && Array.isArray(ob.parts) && ob.parts.length) {
5298
+ return directorCompoundFaces(ob);
5299
+ }
4180
5300
  const sc = ob.scale || { x: 1, y: 1, z: 1 };
4181
5301
  const s = Number(ob.s) || 1;
4182
5302
  const sx = s * (Number(sc.x) || 1), sy = s * (Number(sc.y) || 1), sz = s * (Number(sc.z) || 1);
@@ -4216,21 +5336,7 @@ export function directorObjectFaces(ob) {
4216
5336
  return directorBoxFaces(0, hgt / 2, 0, w, hgt, w * 0.6).map((f) => ({ v: f.v.map(xf), shade: f.shade }));
4217
5337
  }
4218
5338
  const preset = String(ob.preset || 'box');
4219
- let local;
4220
- if (preset === 'sphere') local = directorSphereFaces(0, 0.5, 0, 0.5);
4221
- else if (preset === 'cylinder') local = directorCylinderFaces(0, 0.5, 0, 0.5, 1);
4222
- else if (preset === 'cone') local = directorConeFaces(0, 0, 0, 0.5, 1);
4223
- else if (preset === 'plane') local = directorBoxFaces(0, 0.005, 0, 1, 0.01, 1);
4224
- else if (preset === 'capsule') local = directorCapsuleFaces(0, 0.5, 0, 0.25, 0.5);
4225
- else if (preset === 'torus') local = directorTorusFaces(0, 0.5, 0, 0.35, 0.15);
4226
- else if (preset === 'pyramid') local = directorPyramidFaces(0, 0, 0, 1, 1, 1);
4227
- else if (preset === 'disc') local = directorDiskFaces(0, 0.01, 0, 0.5);
4228
- else if (preset === 'arc') local = directorHalfArcFaces(0, 0.5, 0, 0.5, 0.1);
4229
- else if (preset === 'half_cylinder') local = directorHalfCylinderFaces(0, 0.5, 0, 0.5, 1);
4230
- else if (preset === 'ancient_house') local = ancientHouseFaces(0, 0, 0, 1, 1, 1, 0.34);
4231
- else if (preset === 'ancient_stall') local = ancientStallFaces(0, 0, 0, 1, 1, 1);
4232
- else if (preset === 'stone_step') local = directorBoxFaces(0, 0.15, 0, 1, 0.3, 1);
4233
- else local = directorBoxFaces(0, 0.5, 0, 1, 1, 1);
5339
+ const local = directorPrimitiveLocalFaces(preset);
4234
5340
  return local.map((f) => ({ v: f.v.map(xf), shade: f.shade }));
4235
5341
  }
4236
5342
 
@@ -4564,7 +5670,7 @@ const DIRECTOR_GL_FS = [
4564
5670
  // ============================================================
4565
5671
  // 舞台文档持久化(按项目 id 存 localStorage)
4566
5672
  // ============================================================
4567
- export const directorDocKey = (pid) => 'dsh-director-stage:' + String(pid || 'default');
5673
+ export const directorDocKey = (pid, stageId) => 'dsh-director-stage:' + String(pid || 'default') + (stageId ? '::' + String(stageId) : '');
4568
5674
  /** 用户自建动作(骨骼+姿态编排后保存;出现在「动作」下拉里,与模型自带片段并列)。 */
4569
5675
  const userActionsKey = (pid) => 'dsh-director-actions:' + String(pid || 'default');
4570
5676
  export function loadUserActions(pid) {
@@ -4623,10 +5729,10 @@ export function applyUserAction(ob, action) {
4623
5729
  if (!ob.poseLoop) delete ob.poseLoop;
4624
5730
  return ob;
4625
5731
  }
4626
- export function saveStageDoc(pid, scene) {
5732
+ export function saveStageDoc(pid, scene, stageId) {
4627
5733
  try {
4628
5734
  if (typeof localStorage === 'undefined') return false;
4629
- localStorage.setItem(directorDocKey(pid), JSON.stringify(Object.assign({}, scene, { updatedAt: Date.now() })));
5735
+ localStorage.setItem(directorDocKey(pid, stageId), JSON.stringify(Object.assign({}, scene, { updatedAt: Date.now() })));
4630
5736
  return true;
4631
5737
  } catch { return false; }
4632
5738
  }
@@ -4660,10 +5766,10 @@ export function migrateStageScene(scene) {
4660
5766
  return scene;
4661
5767
  }
4662
5768
 
4663
- export function loadStageDoc(pid, title) {
5769
+ export function loadStageDoc(pid, title, stageId) {
4664
5770
  try {
4665
5771
  if (typeof localStorage === 'undefined') return directorDefaultScene(title);
4666
- const raw = localStorage.getItem(directorDocKey(pid));
5772
+ const raw = localStorage.getItem(directorDocKey(pid, stageId));
4667
5773
  if (!raw) return directorDefaultScene(title);
4668
5774
  const doc = JSON.parse(raw);
4669
5775
  if (!doc || !Array.isArray(doc.objects)) return directorDefaultScene(title);
@@ -4675,8 +5781,8 @@ export function loadStageDoc(pid, title) {
4675
5781
  return migrateStageScene(doc); // 旧场景自动升级到真实人偶资产
4676
5782
  } catch { return directorDefaultScene(title); }
4677
5783
  }
4678
- export function clearStageDoc(pid) {
4679
- try { if (typeof localStorage !== 'undefined') localStorage.removeItem(directorDocKey(pid)); return true; }
5784
+ export function clearStageDoc(pid, stageId) {
5785
+ try { if (typeof localStorage !== 'undefined') localStorage.removeItem(directorDocKey(pid, stageId)); return true; }
4680
5786
  catch { return false; }
4681
5787
  }
4682
5788
 
@@ -5254,7 +6360,7 @@ export function createDirectorGlRenderer(canvas) {
5254
6360
  gl.enable(gl.BLEND);
5255
6361
  gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
5256
6362
 
5257
- const buildMesh = (id, faces, ob) => {
6363
+ const buildMesh = (id, faces, ob, sigExtra) => {
5258
6364
  const tris = directorTriangulateFaces(faces);
5259
6365
  const pos = new Float32Array(tris.length * 9);
5260
6366
  const nrm = new Float32Array(tris.length * 9);
@@ -5271,7 +6377,7 @@ export function createDirectorGlRenderer(canvas) {
5271
6377
  if (!rec) { rec = { vbo: gl.createBuffer(), nbo: gl.createBuffer(), count: 0, sig: '' }; meshCache.set(id, rec); }
5272
6378
  const t = (ob && ob.pos) || { x: 0, y: 0, z: 0 };
5273
6379
  const sc = (ob && ob.scale) || { x: 1, y: 1, z: 1 };
5274
- const sig = tris.length + '|' + t.x + ',' + t.y + ',' + t.z + '|' + (Number(ob && ob.rotY) || 0) + '|' + sc.x + ',' + sc.y + ',' + sc.z + '|' + (Number(ob && ob.h) || 1) + '|' + String(ob && ob.preset || '');
6380
+ const sig = tris.length + '|' + t.x + ',' + t.y + ',' + t.z + '|' + (Number(ob && ob.rotY) || 0) + '|' + sc.x + ',' + sc.y + ',' + sc.z + '|' + (Number(ob && ob.h) || 1) + '|' + String(ob && ob.preset || '') + '|' + String(sigExtra || '');
5275
6381
  if (rec.sig !== sig) {
5276
6382
  gl.bindBuffer(gl.ARRAY_BUFFER, rec.vbo); gl.bufferData(gl.ARRAY_BUFFER, pos, gl.DYNAMIC_DRAW);
5277
6383
  gl.bindBuffer(gl.ARRAY_BUFFER, rec.nbo); gl.bufferData(gl.ARRAY_BUFFER, nrm, gl.DYNAMIC_DRAW);
@@ -5702,6 +6808,8 @@ export function createDirectorGlRenderer(canvas) {
5702
6808
  if (asset) {
5703
6809
  const rec = uploadSkin(ob.assetId, asset);
5704
6810
  const t = Number(ob.animTime) || 0;
6811
+ // 外部生成的 GLB 可能带多个动画:优先按对象 clip 选,其次第一条。
6812
+ if (ob.clip && typeof asset.clipByName === 'function') asset._anim = asset.clipByName(ob.clip) || asset._anim;
5705
6813
  const bones = asset.bones ? boneMatrices(asset, t) : null;
5706
6814
  const cc2 = directorHexToRgb(ob.color || mannequinColorOf(ob.typeId) || CLAY);
5707
6815
  const model = directorMat4Model(ob.pos, Number(ob.rotY) || 0, v3(Number(ob.s) || 1, Number(ob.s) || 1, Number(ob.s) || 1));
@@ -5716,20 +6824,32 @@ export function createDirectorGlRenderer(canvas) {
5716
6824
  const faces = directorObjectFaces(ob);
5717
6825
  stats.faces += faces.length;
5718
6826
  if (!faces.length) return;
5719
- const rec = buildMesh(ob.id, faces, ob);
5720
- stats.tris += rec.count / 3;
5721
- gl.bindBuffer(gl.ARRAY_BUFFER, rec.vbo);
5722
- gl.enableVertexAttribArray(loc.aPosition);
5723
- gl.vertexAttribPointer(loc.aPosition, 3, gl.FLOAT, false, 0, 0);
5724
- gl.bindBuffer(gl.ARRAY_BUFFER, rec.nbo);
5725
- gl.enableVertexAttribArray(loc.aNormal);
5726
- gl.vertexAttribPointer(loc.aNormal, 3, gl.FLOAT, false, 0, 0);
5727
- gl.uniformMatrix4fv(loc.uModel, false, directorMat4Identity());
5728
- gl.uniformMatrix3fv(loc.uNormalMat, false, directorMat3NormalFrom(v3(0, 0, 0), 0, v3(1, 1, 1)));
5729
- const cc = directorHexToRgb(ob.color || mannequinColorOf(ob.typeId) || CLAY);
5730
- gl.uniform3f(loc.uColor, cc[0], cc[1], cc[2]);
5731
- gl.uniform1f(loc.uSelected, (o.selectedId && ob.id === o.selectedId) ? 1 : 0);
5732
- gl.drawArrays(gl.TRIANGLES, 0, rec.count);
6827
+ // 组合道具的每个 part 可带自己的颜色:按颜色分批绘制,避免整车被刷成同一色。
6828
+ const faceGroups = new Map();
6829
+ for (const f of faces) {
6830
+ const key = f.color || '';
6831
+ let arr = faceGroups.get(key);
6832
+ if (!arr) { arr = []; faceGroups.set(key, arr); }
6833
+ arr.push(f);
6834
+ }
6835
+ const sigExtra = ob.kind === 'compound' ? JSON.stringify(ob.parts || []) : '';
6836
+ const isSel = (o.selectedId && ob.id === o.selectedId) ? 1 : 0;
6837
+ for (const [colorKey, groupFaces] of faceGroups) {
6838
+ const rec = buildMesh(colorKey ? ob.id + '|' + colorKey : ob.id, groupFaces, ob, sigExtra);
6839
+ stats.tris += rec.count / 3;
6840
+ gl.bindBuffer(gl.ARRAY_BUFFER, rec.vbo);
6841
+ gl.enableVertexAttribArray(loc.aPosition);
6842
+ gl.vertexAttribPointer(loc.aPosition, 3, gl.FLOAT, false, 0, 0);
6843
+ gl.bindBuffer(gl.ARRAY_BUFFER, rec.nbo);
6844
+ gl.enableVertexAttribArray(loc.aNormal);
6845
+ gl.vertexAttribPointer(loc.aNormal, 3, gl.FLOAT, false, 0, 0);
6846
+ gl.uniformMatrix4fv(loc.uModel, false, directorMat4Identity());
6847
+ gl.uniformMatrix3fv(loc.uNormalMat, false, directorMat3NormalFrom(v3(0, 0, 0), 0, v3(1, 1, 1)));
6848
+ const cc = directorHexToRgb(colorKey || ob.color || mannequinColorOf(ob.typeId) || CLAY);
6849
+ gl.uniform3f(loc.uColor, cc[0], cc[1], cc[2]);
6850
+ gl.uniform1f(loc.uSelected, isSel);
6851
+ gl.drawArrays(gl.TRIANGLES, 0, rec.count);
6852
+ }
5733
6853
  stats.drawn++;
5734
6854
  });
5735
6855
  // gizmo:三根轴 + 旋转环(深度测试关闭 → 永远可见;最后画)
@@ -5984,7 +7104,7 @@ export function directorRenderScene(ctx, w, h, scene, opts) {
5984
7104
  (scene.objects || []).forEach((ob) => {
5985
7105
  const fs = directorObjectFaces(ob);
5986
7106
  stats.faces += fs.length;
5987
- fs.forEach((f) => items.push({ f, color: ob.color || mannequinColorOf(ob.typeId) || CLAY, base: ob }));
7107
+ fs.forEach((f) => items.push({ f, color: f.color || ob.color || mannequinColorOf(ob.typeId) || CLAY, base: ob }));
5988
7108
  });
5989
7109
  if (false && env.groundVisible !== false) {
5990
7110
  const s = 400, op = 0; // 不画地面填充,只画网格
@@ -6136,18 +7256,23 @@ function directorObjectScreenBox(ob, project) {
6136
7256
  const k = Number(ob.s) || 1;
6137
7257
  const sx = k * (Number(sc.x) || 1), sy = k * (Number(sc.y) || 1), sz = k * (Number(sc.z) || 1);
6138
7258
  let hx, hy, hz;
6139
- if (ob.kind === 'model' || ob.kind === 'gltf' || ob.kind === 'actor') {
7259
+ if (ob.kind === 'compound' && Array.isArray(ob.parts) && ob.parts.length) {
7260
+ // 组合道具:按部件实际展开范围估包围盒(仍不生成网格)
7261
+ let mx = 0, my = 0, mz = 0;
7262
+ for (const pt of ob.parts) {
7263
+ const psc = pt.scale || { x: 1, y: 1, z: 1 };
7264
+ mx = Math.max(mx, Math.abs(Number(pt.pos && pt.pos.x) || 0) + 0.5 * (Number(psc.x) || 1));
7265
+ mz = Math.max(mz, Math.abs(Number(pt.pos && pt.pos.z) || 0) + 0.5 * (Number(psc.z) || 1));
7266
+ my = Math.max(my, (Number(pt.pos && pt.pos.y) || 0) + directorPrimitiveUnitHeight(pt.preset) * (Number(psc.y) || 1));
7267
+ }
7268
+ hx = mx * sx; hy = my * sy; hz = mz * sz;
7269
+ } else if (ob.kind === 'model' || ob.kind === 'gltf' || ob.kind === 'actor') {
6140
7270
  const h = Number(ob.h) || 1.78;
6141
7271
  hx = h * 0.30 * Math.max(0.5, sx);
6142
7272
  hy = h * Math.max(0.5, sy);
6143
7273
  hz = h * 0.22 * Math.max(0.5, sz);
6144
7274
  } else {
6145
- const preset = String(ob.preset || 'box');
6146
- const H = preset === 'plane' || preset === 'disc' ? 0.02
6147
- : preset === 'ancient_house' ? 1.34
6148
- : preset === 'ancient_stall' ? 0.84
6149
- : preset === 'stone_step' ? 0.3 : 1;
6150
- hx = 0.5 * sx; hy = H * sy; hz = 0.5 * sz;
7275
+ hx = 0.5 * sx; hy = directorPrimitiveUnitHeight(ob.preset) * sy; hz = 0.5 * sz;
6151
7276
  }
6152
7277
  const ry = Number(ob.rotY) || 0, c = Math.cos(ry), sn = Math.sin(ry);
6153
7278
  const xf = (x, y, z) => v3(ob.pos.x + x * c + z * sn, ob.pos.y + Math.max(0, y), ob.pos.z - x * sn + z * c);
@@ -6358,16 +7483,7 @@ export function compileDirectorPrompt(scene, opts) {
6358
7483
  // 景别/运镜文案一律从中英双语的单一来源取:避免输出内部 id(如 medium_close),也避免英文分支里混中文
6359
7484
  const fillDef = SHOT_FILLS.find((f) => f.id === shot.shotSize) || null;
6360
7485
  const sizeLabel = fillDef ? (zh ? fillDef.zh : fillDef.en) : String(shot.shotSize || '');
6361
- const MOVE_LABELS = {
6362
- static: { zh: '固定机位', en: 'static camera' },
6363
- push_in: { zh: '推近', en: 'push in' },
6364
- pull_out: { zh: '拉远', en: 'pull out' },
6365
- pan_left: { zh: '向左摇', en: 'pan left' },
6366
- pan_right: { zh: '向右摇', en: 'pan right' },
6367
- orbit_left: { zh: '左环绕', en: 'orbit left' },
6368
- orbit_right: { zh: '右环绕', en: 'orbit right' },
6369
- handheld: { zh: '手持微晃', en: 'handheld' },
6370
- };
7486
+ const MOVE_LABELS = Object.fromEntries(CAMERA_MOVES.map((m) => [m.id, { zh: m.zh, en: m.en }]));
6371
7487
  const mvDef = MOVE_LABELS[shot.cameraMove] || null;
6372
7488
  const moveLabel = mvDef ? (zh ? mvDef.zh : mvDef.en) : String(shot.cameraMove || '');
6373
7489
  const cam = (scene.cameras || []).find((c) => c.id === scene.activeCameraId) || (scene.cameras || [])[0] || {};