box3d.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. /**
  2. * box3d.js — Three.js 盒子 3D 渲染(多实例工厂版)
  3. * - 从刀版 panels 自动构建铰链折叠
  4. * - 外侧 / 内侧独立贴图
  5. * - 10 种动效(折叠展开 / 自转 / 掉落 / 由远到近……)
  6. * - 重置视角、2K/3K/4K 高清截图、透明背景
  7. */
  8. (function () {
  9. const THREE = window.THREE;
  10. if (!THREE) return;
  11. function fontStack(key) {
  12. const fonts = window.PL && window.PL.data && window.PL.data.fonts;
  13. return (fonts && fonts[key] && fonts[key].stack) || '"PingFang SC", "Helvetica Neue", sans-serif';
  14. }
  15. function panelBox(p) {
  16. if (p.poly) {
  17. const xs = p.poly.map(function (pt) { return pt[0]; });
  18. const ys = p.poly.map(function (pt) { return pt[1]; });
  19. const x = Math.min.apply(null, xs);
  20. const y = Math.min.apply(null, ys);
  21. return { x: x, y: y, w: Math.max.apply(null, xs) - x, h: Math.max.apply(null, ys) - y };
  22. }
  23. return { x: p.x, y: p.y, w: p.w, h: p.h };
  24. }
  25. function boxCenter(b) { return { x: b.x + b.w / 2, y: b.y + b.h / 2 }; }
  26. function planeGeometry(b, poly) {
  27. if (!poly) return new THREE.PlaneGeometry(b.w, b.h);
  28. const shape = new THREE.Shape();
  29. poly.forEach(function (pt, i) {
  30. const x = pt[0] - b.x - b.w / 2;
  31. const y = -(pt[1] - b.y - b.h / 2);
  32. if (i === 0) shape.moveTo(x, y);
  33. else shape.lineTo(x, y);
  34. });
  35. shape.closePath();
  36. const geom = new THREE.ShapeGeometry(shape);
  37. const pos = geom.attributes.position;
  38. const uv = geom.attributes.uv;
  39. for (let i = 0; i < pos.count; i += 1) {
  40. uv.setXY(i, (pos.getX(i) + b.w / 2) / Math.max(0.001, b.w), (pos.getY(i) + b.h / 2) / Math.max(0.001, b.h));
  41. }
  42. uv.needsUpdate = true;
  43. return geom;
  44. }
  45. const FOLD_PARTS = { carton: 1, rsc: 1, mailbox: 1, tuck: 1, straight: 1, autobottom: 1, mailer: 1, drawer: 1, bag: 1, sleeve: 1 };
  46. function panelLayer(p) {
  47. if (p.kind === 'glue') return -0.6;
  48. if (p.kind === 'lip') return -0.9;
  49. if (p.kind === 'dust') return -0.35;
  50. if (p.kind === 'tuck') return -0.28;
  51. if (p.kind === 'flap') return -0.12;
  52. return 0;
  53. }
  54. function isBodyKind(k) {
  55. return !(k === 'glue' || k === 'flap' || k === 'dust' || k === 'tuck' || k === 'lip');
  56. }
  57. function canHinge(a, b) {
  58. const ka = a.kind || 'body';
  59. const kb = b.kind || 'body';
  60. if (isBodyKind(ka) !== isBodyKind(kb)) return true;
  61. if (isBodyKind(ka) && isBodyKind(kb)) return true;
  62. return (ka === 'tuck' && kb === 'flap') || (ka === 'flap' && kb === 'tuck');
  63. }
  64. function panelEdges(p) {
  65. const b = panelBox(p);
  66. const pts = p.poly || [[b.x, b.y], [b.x + b.w, b.y], [b.x + b.w, b.y + b.h], [b.x, b.y + b.h]];
  67. const out = [];
  68. for (let i = 0; i < pts.length; i += 1) {
  69. const a = pts[i];
  70. const c = pts[(i + 1) % pts.length];
  71. if (Math.abs(a[0] - c[0]) < 0.05) out.push({ axis: 'v', c: a[0], lo: Math.min(a[1], c[1]), hi: Math.max(a[1], c[1]) });
  72. else if (Math.abs(a[1] - c[1]) < 0.05) out.push({ axis: 'h', c: a[1], lo: Math.min(a[0], c[0]), hi: Math.max(a[0], c[0]) });
  73. }
  74. return out;
  75. }
  76. function sharedEdge(a, b) {
  77. let best = null;
  78. panelEdges(a).forEach(function (ea) {
  79. panelEdges(b).forEach(function (eb) {
  80. if (ea.axis !== eb.axis || Math.abs(ea.c - eb.c) > 0.6) return;
  81. const lo = Math.max(ea.lo, eb.lo);
  82. const hi = Math.min(ea.hi, eb.hi);
  83. const len = hi - lo;
  84. if (len <= 2) return;
  85. if (!best || len > best.len) best = { axis: ea.axis, c: ea.c, lo: lo, hi: hi, len: len };
  86. });
  87. });
  88. return best;
  89. }
  90. function buildAdjacency(panels, boxes) {
  91. const adj = panels.map(function () { return []; });
  92. for (let i = 0; i < panels.length; i += 1) {
  93. for (let j = i + 1; j < panels.length; j += 1) {
  94. if (!canHinge(panels[i], panels[j])) continue;
  95. const edge = sharedEdge(panels[i], panels[j]);
  96. if (!edge) continue;
  97. const ca = boxCenter(boxes[i]);
  98. const cb = boxCenter(boxes[j]);
  99. let n;
  100. if (edge.axis === 'v') n = { x: cb.x >= ca.x ? 1 : -1, y: 0 };
  101. else n = { x: 0, y: cb.y >= ca.y ? 1 : -1 };
  102. const mk = function (s) {
  103. return edge.axis === 'v'
  104. ? { axis: 'v', x: edge.c, y0: edge.lo, y1: edge.hi, n: { x: n.x * s, y: n.y * s } }
  105. : { axis: 'h', x0: edge.lo, x1: edge.hi, y: edge.c, n: { x: n.x * s, y: n.y * s } };
  106. };
  107. adj[i].push({ j: j, edge: mk(1), overlap: edge.len });
  108. adj[j].push({ j: i, edge: mk(-1), overlap: edge.len });
  109. }
  110. }
  111. return adj;
  112. }
  113. function hingePoint(edge) {
  114. if (edge.axis === 'v') return { x: edge.x, y: (edge.y0 + edge.y1) / 2 };
  115. return { x: (edge.x0 + edge.x1) / 2, y: edge.y };
  116. }
  117. function rootIndexFor(indices, panels, boxes, prefer) {
  118. let best = -1, bestScore = -Infinity;
  119. indices.forEach(function (idx) {
  120. const b = boxes[idx];
  121. const face = panels[idx].face;
  122. const score = (face === prefer ? 1e9 : 0) + (face ? 1e6 : 0) + b.w * b.h;
  123. if (score > bestScore) { bestScore = score; best = idx; }
  124. });
  125. return best;
  126. }
  127. /* ================= 实例工厂 ================= */
  128. function create(el, opts) {
  129. opts = opts || {};
  130. let renderer = null, scene = null, camera = null, root = null, canvas = null;
  131. let meshes = [], hinges = [], components = [];
  132. const orbit = { theta: -0.55, phi: 1.08, zoom: 1 };
  133. const orbitHome = { theta: -0.55, phi: 1.08, zoom: 1 };
  134. let autoRotate = false;
  135. let onFacePick = opts.onFacePick || null;
  136. let drag = null, moved = false, raf = null;
  137. let foldT = 0;
  138. let showLines = true;
  139. let state = null, material = null;
  140. let disposeFns = [];
  141. renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });
  142. renderer.setPixelRatio(opts.mini ? 1 : Math.min(window.devicePixelRatio || 1, 2));
  143. renderer.outputEncoding = THREE.sRGBEncoding;
  144. renderer.setClearColor(0x000000, 0);
  145. canvas = renderer.domElement;
  146. canvas.className = 'box3d-canvas';
  147. canvas.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;display:block;z-index:2;touch-action:none;cursor:grab;';
  148. el.appendChild(canvas);
  149. el.classList.add('three-active');
  150. scene = new THREE.Scene();
  151. camera = new THREE.PerspectiveCamera(32, 1, 1, 60000);
  152. scene.add(new THREE.AmbientLight(0xffffff, 0.82));
  153. const key = new THREE.DirectionalLight(0xffffff, 0.8);
  154. key.position.set(-350, 600, 800);
  155. scene.add(key);
  156. const fill = new THREE.DirectionalLight(0xffffff, 0.34);
  157. fill.position.set(600, -260, -500);
  158. scene.add(fill);
  159. const rim = new THREE.DirectionalLight(0xffffff, 0.22);
  160. rim.position.set(-500, -200, -700);
  161. scene.add(rim);
  162. function resize() {
  163. const w = Math.max(1, el.clientWidth);
  164. const hh = Math.max(1, el.clientHeight);
  165. renderer.setSize(w, hh, false);
  166. camera.aspect = w / hh;
  167. camera.updateProjectionMatrix();
  168. }
  169. resize();
  170. if (window.ResizeObserver) {
  171. const ro = new ResizeObserver(resize);
  172. ro.observe(el);
  173. disposeFns.push(function () { ro.disconnect(); });
  174. }
  175. /* ---- 贴图 ---- */
  176. function drawFaceArt(ctx, cw, ch, data, px2mm) {
  177. const items = (data && data.items) || [];
  178. items.forEach(function (it) {
  179. if (it.hidden) return;
  180. if (it.type === 'text') {
  181. const px = it.size * px2mm;
  182. const lines = String(it.text || '').split('\n');
  183. const lh = (it.lineHeight || 1.25) * px;
  184. ctx.save();
  185. ctx.fillStyle = it.color || '#17140f';
  186. ctx.textAlign = it.align === 'center' ? 'center' : it.align === 'right' ? 'right' : 'left';
  187. ctx.textBaseline = 'middle';
  188. ctx.font = (it.italic ? 'italic ' : '') + (it.weight || 400) + ' ' + px + 'px ' + fontStack(it.font);
  189. const x = (it.x / 100) * cw;
  190. const y = (it.y / 100) * ch;
  191. lines.forEach(function (line, i) {
  192. ctx.fillText(line, x, y + (i - (lines.length - 1) / 2) * lh);
  193. });
  194. ctx.restore();
  195. } else if (it.type === 'image' && it.src) {
  196. const img = getCachedImage(it.src, function () { refreshTextures(); });
  197. if (img) {
  198. const iw = ((it.w == null ? 70 : it.w) / 100) * cw;
  199. const ix = ((it.x == null ? 50 : it.x) / 100) * cw;
  200. const iy = ((it.y == null ? 50 : it.y) / 100) * ch;
  201. try { ctx.drawImage(img, ix - iw / 2, iy - (iw * (img.height / Math.max(1, img.width))) / 2, iw, iw * (img.height / Math.max(1, img.width))); } catch (e) {}
  202. }
  203. } else if (it.type === 'barcode' && it.src) {
  204. const img = getCachedImage(it.src, function () { refreshTextures(); });
  205. if (img) {
  206. const iw = ((it.w || 40) / 100) * cw;
  207. const ix = (it.x / 100) * cw;
  208. const iy = (it.y / 100) * ch;
  209. try { ctx.drawImage(img, ix - iw / 2, iy - iw * 0.42, iw, iw * 0.84); } catch (e) {}
  210. }
  211. }
  212. });
  213. // 兼容旧数据
  214. (data && data.texts || []).forEach(function (t) {
  215. const px = t.size * px2mm;
  216. const lines = String(t.text || '').split('\n');
  217. const lh = (t.lineHeight || 1.25) * px;
  218. ctx.save();
  219. ctx.fillStyle = t.color || '#17140f';
  220. ctx.textAlign = t.align === 'center' ? 'center' : t.align === 'right' ? 'right' : 'left';
  221. ctx.textBaseline = 'middle';
  222. ctx.font = (t.italic ? 'italic ' : '') + (t.weight || 400) + ' ' + px + 'px ' + fontStack(t.font);
  223. const x = (t.x / 100) * cw;
  224. const y = (t.y / 100) * ch;
  225. lines.forEach(function (line, i) { ctx.fillText(line, x, y + (i - (lines.length - 1) / 2) * lh); });
  226. ctx.restore();
  227. });
  228. }
  229. /* ---- 面纹理缓存:几何不变时仅重绘画布内容(needsUpdate),避免整场景重建 ---- */
  230. const faceTexCache = {}; // side|face -> { canvas, ctx, texture, cw, ch }
  231. const imgCache = new Map(); // src -> HTMLImageElement(避免重复解码)
  232. function getCachedImage(src, onReady) {
  233. if (imgCache.has(src)) {
  234. const img = imgCache.get(src);
  235. if (img.complete && img.naturalWidth) return img;
  236. return null;
  237. }
  238. const img = new Image();
  239. img.onload = function () { if (onReady) onReady(); };
  240. img.src = src;
  241. imgCache.set(src, img);
  242. return null;
  243. }
  244. function drawFaceTo(entry, face) {
  245. const sideData = (state.faces[state.side || 'outer'] || {});
  246. const data = sideData[face] || {};
  247. const ctx = entry.ctx;
  248. const cw = entry.cw, ch = entry.ch;
  249. const size = { w: entry.sizeW, h: entry.sizeH };
  250. ctx.setTransform(1, 0, 0, 1, 0, 0);
  251. ctx.fillStyle = data.color || material.paper || '#fbf7ee';
  252. ctx.fillRect(0, 0, cw, ch);
  253. if (data.texture) {
  254. const tex = getCachedImage(data.texture, function () { refreshTextures(); });
  255. if (tex) {
  256. const scale = Math.max(cw / 220, ch / 220);
  257. for (let tx = 0; tx < cw; tx += 220 * scale) for (let ty = 0; ty < ch; ty += 220 * scale) {
  258. ctx.drawImage(tex, tx, ty, 220 * scale, 220 * scale);
  259. }
  260. }
  261. }
  262. drawFaceArt(ctx, cw, ch, data, cw / Math.max(1, size.w));
  263. }
  264. function getFaceTexture(face, size) {
  265. const key = (state.side || 'outer') + '|' + face;
  266. let entry = faceTexCache[key];
  267. if (!entry) {
  268. const cw = opts.mini ? 360 : 760;
  269. const ch = Math.max(160, Math.round(cw * size.h / Math.max(1, size.w)));
  270. const c = document.createElement('canvas');
  271. c.width = cw;
  272. c.height = ch;
  273. const texture = new THREE.CanvasTexture(c);
  274. texture.encoding = THREE.sRGBEncoding;
  275. texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
  276. entry = { canvas: c, ctx: c.getContext('2d'), texture: texture, cw: cw, ch: ch, sizeW: size.w, sizeH: size.h };
  277. faceTexCache[key] = entry;
  278. }
  279. return entry;
  280. }
  281. function refreshTextures() {
  282. const prefix = (state.side || 'outer') + '|';
  283. // 清理另一侧的缓存(内外侧切换后不再使用)
  284. Object.keys(faceTexCache).forEach(function (k) {
  285. if (k.indexOf(prefix) !== 0) {
  286. faceTexCache[k].texture.dispose();
  287. delete faceTexCache[k];
  288. }
  289. });
  290. meshes.forEach(function (mesh) {
  291. const face = mesh.userData.face;
  292. if (!face || !mesh.material) return;
  293. const entry = getFaceTexture(face, mesh.userData.faceSize || { w: 1, h: 1 });
  294. drawFaceTo(entry, face);
  295. entry.texture.needsUpdate = true;
  296. if (mesh.material.map !== entry.texture) {
  297. mesh.material.map = entry.texture;
  298. mesh.material.needsUpdate = true;
  299. }
  300. });
  301. }
  302. function makeMaterial(face, size, inner) {
  303. const entry = getFaceTexture(face, size);
  304. drawFaceTo(entry, face);
  305. entry.texture.needsUpdate = true;
  306. return new THREE.MeshStandardMaterial({
  307. map: entry.texture,
  308. color: 0xffffff,
  309. roughness: 0.8,
  310. metalness: 0.02,
  311. side: THREE.DoubleSide
  312. });
  313. }
  314. function cardboardMaterial() {
  315. const sideData = (state.faces[state.side || 'outer'] || {});
  316. const plain = sideData._plain || {};
  317. return new THREE.MeshStandardMaterial({
  318. color: new THREE.Color(plain.color || material.paper || '#fbf7ee'),
  319. roughness: 0.86,
  320. metalness: 0.02,
  321. side: THREE.DoubleSide
  322. });
  323. }
  324. function makePanelMesh(p, box) {
  325. const geom = planeGeometry(box, p.poly);
  326. const mat = p.face ? makeMaterial(p.face, { w: box.w, h: box.h }, state.side === 'inner') : cardboardMaterial();
  327. const mesh = new THREE.Mesh(geom, mat);
  328. mesh.position.z = panelLayer(p);
  329. mesh.userData.face = p.face || null;
  330. mesh.userData.faceSize = p.face ? { w: box.w, h: box.h } : null;
  331. mesh.add(new THREE.LineSegments(
  332. new THREE.EdgesGeometry(geom),
  333. new THREE.LineBasicMaterial({ color: 0x17140f, transparent: true, opacity: 0.24 })
  334. ));
  335. meshes.push(mesh);
  336. return mesh;
  337. }
  338. function clearRoot() {
  339. if (root) {
  340. root.traverse(function (o) {
  341. if (o.geometry) o.geometry.dispose();
  342. if (o.material) o.material.dispose();
  343. });
  344. scene.remove(root);
  345. }
  346. // 纹理缓存随几何一起释放(key 含 side,重建后按需重建)
  347. Object.keys(faceTexCache).forEach(function (k) {
  348. faceTexCache[k].texture.dispose();
  349. delete faceTexCache[k];
  350. });
  351. root = new THREE.Group();
  352. scene.add(root);
  353. meshes = [];
  354. hinges = [];
  355. components = [];
  356. }
  357. function buildComponent(indices, panels, boxes, adj, prefer) {
  358. const start = rootIndexFor(indices, panels, boxes, prefer);
  359. if (start < 0) return null;
  360. const comp = new THREE.Group();
  361. const rootGroup = new THREE.Group();
  362. comp.add(rootGroup);
  363. const rootBox = boxes[start];
  364. const rootMesh = makePanelMesh(panels[start], rootBox);
  365. rootMesh.userData.kind = panels[start].kind;
  366. rootGroup.add(rootMesh);
  367. const infos = new Map();
  368. infos.set(start, { group: rootGroup, origin: boxCenter(rootBox) });
  369. const visited = new Set([start]);
  370. const best = new Map();
  371. const addLinks = function (pi) {
  372. adj[pi].forEach(function (link) {
  373. if (visited.has(link.j)) return;
  374. const cur = best.get(link.j);
  375. if (!cur || link.overlap > cur.overlap) best.set(link.j, { from: pi, link: link });
  376. });
  377. };
  378. addLinks(start);
  379. while (visited.size < indices.length) {
  380. let pick = -1, pickW = -1;
  381. best.forEach(function (v, k) {
  382. if (visited.has(k)) return;
  383. if (v.link.overlap > pickW) { pickW = v.link.overlap; pick = k; }
  384. });
  385. if (pick < 0) break;
  386. const chosen = best.get(pick);
  387. const parent = infos.get(chosen.from);
  388. const link = chosen.link;
  389. const hinge = hingePoint(link.edge);
  390. const cb = boxes[pick];
  391. const pivot = new THREE.Group();
  392. pivot.position.set(hinge.x - parent.origin.x, -(hinge.y - parent.origin.y), 0);
  393. const n3 = new THREE.Vector3(link.edge.n.x, -link.edge.n.y, 0);
  394. if (n3.lengthSq() < 0.5) n3.set(0, 1, 0);
  395. n3.normalize();
  396. const axis = new THREE.Vector3(0, 0, 1).cross(n3).normalize();
  397. pivot.userData.axis = axis;
  398. pivot.userData.angle = Math.PI / 2;
  399. hinges.push(pivot);
  400. parent.group.add(pivot);
  401. const cc = boxCenter(cb);
  402. const mesh = makePanelMesh(panels[pick], cb);
  403. mesh.position.x = cc.x - hinge.x;
  404. mesh.position.y = -(cc.y - hinge.y);
  405. mesh.userData.kind = panels[pick].kind;
  406. pivot.add(mesh);
  407. infos.set(pick, { group: pivot, origin: hinge });
  408. visited.add(pick);
  409. best.delete(pick);
  410. addLinks(pick);
  411. }
  412. return { group: comp, root: start };
  413. }
  414. function buildFromDieline(panels) {
  415. const boxes = panels.map(panelBox);
  416. const adj = buildAdjacency(panels, boxes);
  417. const seen = new Set();
  418. const groups = [];
  419. for (let i = 0; i < panels.length; i += 1) {
  420. if (seen.has(i)) continue;
  421. const stack = [i];
  422. const indices = [];
  423. seen.add(i);
  424. while (stack.length) {
  425. const cur = stack.pop();
  426. indices.push(cur);
  427. adj[cur].forEach(function (link) {
  428. if (seen.has(link.j)) return;
  429. seen.add(link.j);
  430. stack.push(link.j);
  431. });
  432. }
  433. groups.push(indices);
  434. }
  435. const prefer = 'front';
  436. const built = [];
  437. groups.forEach(function (indices) {
  438. const comp = buildComponent(indices, panels, boxes, adj, prefer);
  439. if (comp) built.push(comp);
  440. });
  441. if (!built.length) return false;
  442. const main = built[0];
  443. const mainOrigin = boxCenter(boxes[main.root]);
  444. built.forEach(function (c) {
  445. const center = boxCenter(boxes[c.root]);
  446. c.home = new THREE.Vector3(center.x - mainOrigin.x, -(center.y - mainOrigin.y), 0);
  447. c.assembled = new THREE.Vector3(0, 0, 0);
  448. c.assembledScale = 1;
  449. c.isMain = c === main;
  450. if (!c.isMain) {
  451. c.assembled.set(0, 0, -2);
  452. c.assembledScale = 0.94;
  453. }
  454. c.group.position.copy(c.home);
  455. root.add(c.group);
  456. components.push(c);
  457. });
  458. root.userData.mainOrigin = { x: mainOrigin.x, y: mainOrigin.y };
  459. return true;
  460. }
  461. function buildRigid() {
  462. const t = material.thickness || 0;
  463. const W = state.w + t * 2;
  464. const D = state.d + t * 2;
  465. const H = state.h + t * 2;
  466. const inner = state.side === 'inner';
  467. const defs = [
  468. { face: 'front', w: W, h: H, pos: [0, 0, D / 2], rot: [0, 0, 0] },
  469. { face: 'back', w: W, h: H, pos: [0, 0, -D / 2], rot: [0, Math.PI, 0] },
  470. { face: 'right', w: D, h: H, pos: [W / 2, 0, 0], rot: [0, Math.PI / 2, 0] },
  471. { face: 'left', w: D, h: H, pos: [-W / 2, 0, 0], rot: [0, -Math.PI / 2, 0] },
  472. { face: 'top', w: W, h: D, pos: [0, H / 2, 0], rot: [-Math.PI / 2, 0, 0] },
  473. { face: 'bottom', w: W, h: D, pos: [0, -H / 2, 0], rot: [Math.PI / 2, 0, 0] }
  474. ];
  475. defs.forEach(function (def) {
  476. const geom = new THREE.PlaneGeometry(def.w, def.h);
  477. const mat = makeMaterial(def.face, { w: def.w, h: def.h }, inner);
  478. const mesh = new THREE.Mesh(geom, mat);
  479. mesh.position.set(def.pos[0], def.pos[1], def.pos[2]);
  480. mesh.rotation.set(def.rot[0], def.rot[1], def.rot[2]);
  481. mesh.userData.face = def.face;
  482. mesh.userData.faceSize = { w: def.w, h: def.h };
  483. root.add(mesh);
  484. meshes.push(mesh);
  485. mesh.add(new THREE.LineSegments(
  486. new THREE.EdgesGeometry(geom),
  487. new THREE.LineBasicMaterial({ color: 0x17140f, transparent: true, opacity: 0.22 })
  488. ));
  489. });
  490. }
  491. /* ---- 动效引擎 ---- */
  492. const anim = { id: null, t0: 0, dur: 0, onEnd: null };
  493. const animState = { theta: 0, phi: 0, zoom: 1, dx: 0, dy: 0, dz: 0, fold: null };
  494. const EASE = {
  495. io: function (t) { return t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2; },
  496. out: function (t) { return 1 - Math.pow(1 - t, 3); },
  497. bounce: function (t) {
  498. const n1 = 7.5625, d1 = 2.75;
  499. if (t < 1 / d1) return n1 * t * t;
  500. if (t < 2 / d1) return n1 * (t -= 1.5 / d1) * t + 0.75;
  501. if (t < 2.5 / d1) return n1 * (t -= 2.25 / d1) * t + 0.9375;
  502. return n1 * (t -= 2.625 / d1) * t + 0.984375;
  503. }
  504. };
  505. const ANIM_TICKS = {
  506. fold: function (p) {
  507. animState.fold = p < 0.5 ? EASE.io(p * 2) : 1 - EASE.io((p - 0.5) * 2);
  508. },
  509. spinFlat: function (p) {
  510. animState.phi = 0.18;
  511. animState.theta = EASE.io(p) * Math.PI * 2;
  512. },
  513. spinTop: function (p) {
  514. animState.phi = -1.05;
  515. animState.theta = EASE.io(p) * Math.PI * 2;
  516. },
  517. dropSpin: function (p) {
  518. const k = EASE.out(Math.min(1, p / 0.55));
  519. animState.dy = (1 - k) * 260;
  520. animState.theta = (1 - k) * Math.PI * 2.2;
  521. animState.dz = (1 - k) * -80;
  522. },
  523. zoomIn: function (p) {
  524. animState.zoom = 0.35 + EASE.io(p) * 0.75;
  525. animState.phi = 0.12;
  526. },
  527. dropZoom: function (p) {
  528. if (p < 0.375) {
  529. const k = EASE.out(p / 0.375);
  530. animState.dy = (1 - k) * 300;
  531. animState.theta = (1 - k) * Math.PI * 2.4;
  532. } else {
  533. const k = EASE.io((p - 0.375) / 0.625);
  534. animState.zoom = 1 + k * 1.1;
  535. animState.phi = 0.1 + k * 0.2;
  536. }
  537. },
  538. zoomDetail: function (p) {
  539. animState.zoom = 0.4 + EASE.io(p) * 1.2;
  540. animState.theta = -0.3 * (1 - p);
  541. animState.phi = 0.25 - p * 0.12;
  542. },
  543. fromLeft: function (p) {
  544. const k = EASE.out(p);
  545. animState.dx = (1 - k) * -220;
  546. animState.theta = (1 - k) * -Math.PI * 1.5;
  547. animState.phi = 0.3;
  548. },
  549. curveIn: function (p) {
  550. const k = EASE.io(p);
  551. animState.dz = (1 - k) * -400;
  552. animState.dx = Math.sin(p * Math.PI) * -120 * (1 - p);
  553. animState.dy = Math.sin(p * Math.PI) * 90;
  554. animState.theta = (1 - k) * -0.9;
  555. },
  556. foldBounce: function (p) {
  557. animState.fold = EASE.io(Math.min(1, p / 0.7));
  558. if (p > 0.7) animState.dy = -(1 - EASE.bounce((p - 0.7) / 0.3)) * 14;
  559. }
  560. };
  561. function tickAnim(now) {
  562. if (!anim.id) return false;
  563. const p = Math.min(1, (now - anim.t0) / (anim.dur * 1000));
  564. Object.assign(animState, { theta: 0, phi: 0, zoom: 1, dx: 0, dy: 0, dz: 0, fold: null });
  565. if (anim.custom) anim.custom(p);
  566. else ANIM_TICKS[anim.id](p);
  567. if (p >= 1) {
  568. const end = anim.onEnd;
  569. const wasCustom = anim.custom;
  570. anim.id = null;
  571. anim.custom = null;
  572. if (wasCustom) stopAudioHeart();
  573. if (end) end();
  574. }
  575. return true;
  576. }
  577. function applyCamera() {
  578. if (!camera || !root) return;
  579. root.updateMatrixWorld(true);
  580. const bbox = new THREE.Box3().setFromObject(root);
  581. if (bbox.isEmpty()) return;
  582. const center = bbox.getCenter(new THREE.Vector3());
  583. const size = bbox.getSize(new THREE.Vector3());
  584. const maxDim = Math.max(size.x, size.y, size.z, 1);
  585. const zoom = orbit.zoom * animState.zoom;
  586. const r = maxDim * 2.85 / Math.max(0.3, zoom);
  587. const phi = Math.max(0.15, Math.min(Math.PI - 0.15, orbit.phi + animState.phi));
  588. const theta = orbit.theta + animState.theta;
  589. const x = r * Math.sin(phi) * Math.sin(theta);
  590. const y = r * Math.cos(phi);
  591. const z = r * Math.sin(phi) * Math.cos(theta);
  592. camera.position.set(center.x + x + animState.dx, center.y + y + animState.dy, center.z + z + animState.dz);
  593. camera.lookAt(center.x + animState.dx * 0.2, center.y - maxDim * (opts.mini ? 0.02 : 0.05), center.z);
  594. }
  595. function applyFold(t) {
  596. foldT = Math.max(0, Math.min(1, Number(t) || 0));
  597. hinges.forEach(function (g) {
  598. g.setRotationFromAxisAngle(g.userData.axis, g.userData.angle * (1 - foldT));
  599. });
  600. components.forEach(function (c) {
  601. if (c.isMain) return;
  602. c.group.position.lerpVectors(c.assembled, c.home, foldT);
  603. const s = c.assembledScale + (1 - c.assembledScale) * foldT;
  604. c.group.scale.set(s, s, s);
  605. });
  606. }
  607. function applyLines() {
  608. if (!root) return;
  609. root.traverse(function (o) { if (o.isLineSegments) o.visible = showLines; });
  610. }
  611. /* ---- 交互 ---- */
  612. function bindPointer() {
  613. canvas.addEventListener('pointerdown', function (e) {
  614. if (e.button !== 0) return;
  615. if (opts.mini && opts.onInteract) opts.onInteract(); // 按下即接管(停掉 CSS 自动播放)
  616. drag = { x: e.clientX, y: e.clientY, theta: orbit.theta, phi: orbit.phi };
  617. moved = false;
  618. canvas.style.cursor = 'grabbing';
  619. canvas.setPointerCapture(e.pointerId);
  620. });
  621. canvas.addEventListener('pointermove', function (e) {
  622. if (!drag) return;
  623. const dx = e.clientX - drag.x;
  624. const dy = e.clientY - drag.y;
  625. if (Math.abs(dx) + Math.abs(dy) > 3) moved = true;
  626. orbit.theta = drag.theta - dx * 0.008;
  627. orbit.phi = Math.max(0.25, Math.min(Math.PI - 0.25, drag.phi - dy * 0.006));
  628. if (opts.mini && autoRotate && moved && opts.onInteract) {
  629. autoRotate = false;
  630. opts.onInteract();
  631. }
  632. applyCamera();
  633. flush(); // 交互即时渲染:拖拽旋转不依赖 rAF 节奏
  634. });
  635. canvas.addEventListener('pointerup', function (e) {
  636. if (!drag) return;
  637. const wasMoved = moved;
  638. drag = null;
  639. canvas.style.cursor = 'grab';
  640. try { canvas.releasePointerCapture(e.pointerId); } catch (err) {}
  641. if (wasMoved || !onFacePick) return;
  642. const rect = canvas.getBoundingClientRect();
  643. const px = ((e.clientX - rect.left) / rect.width) * 2 - 1;
  644. const py = -((e.clientY - rect.top) / rect.height) * 2 + 1;
  645. const rc = new THREE.Raycaster();
  646. rc.setFromCamera(new THREE.Vector2(px, py), camera);
  647. const hits = rc.intersectObjects(meshes, false);
  648. if (hits.length && hits[0].object.userData.face) onFacePick(hits[0].object.userData.face);
  649. });
  650. canvas.addEventListener('pointercancel', function () {
  651. drag = null;
  652. canvas.style.cursor = 'grab';
  653. });
  654. canvas.addEventListener('wheel', function (e) {
  655. e.preventDefault();
  656. e.stopPropagation();
  657. orbit.zoom = Math.max(0.4, Math.min(3.2, orbit.zoom * (e.deltaY > 0 ? 0.92 : 1.08)));
  658. applyCamera();
  659. flush();
  660. }, { passive: false });
  661. }
  662. bindPointer();
  663. let lastFrameAt = performance.now();
  664. // 虚拟时钟:页面时钟可能被节流冻结(rAF 停、setInterval 降频、performance.now 冻结),
  665. // 由 Web Worker 心跳(Worker 定时器不受页面可见性节流)持续推进,保证自动播放匀速循环。
  666. let vNow = performance.now();
  667. let lastVTick = vNow;
  668. const AUTO_SPEED = 0.28; // 约 22 秒一圈
  669. function tickCore() {
  670. const dt = Math.min(0.12, Math.max(0, vNow - lastVTick)) / 1000;
  671. lastVTick = vNow;
  672. try {
  673. const hasAnim = tickAnim(vNow);
  674. if (!anim.id && audioDriving) stopAudioHeart();
  675. if (autoRotate && !anim.id) orbit.theta += AUTO_SPEED * dt;
  676. if (animState.fold != null) applyFold(animState.fold);
  677. applyCamera();
  678. if (renderer && scene && camera) renderer.render(scene, camera);
  679. } catch (e) {
  680. // 单帧异常不终止渲染循环
  681. }
  682. }
  683. let framesSinceRaf = 0; // worker 心跳消息计数,rAF 有效帧清零
  684. let lastRafNow = 0;
  685. /* 音频线程心跳:AudioContext 回调独立于页面渲染节流,动画播放期提供 ~46fps 稳定帧 */
  686. let audioCtx = null, audioNode = null, audioDriving = false, lastAudioT = null;
  687. function startAudioHeart() {
  688. try {
  689. const AC = window.AudioContext || window.webkitAudioContext;
  690. if (!AC) return;
  691. if (!audioCtx) {
  692. audioCtx = new AC();
  693. audioNode = audioCtx.createScriptProcessor(2048, 1, 1);
  694. audioNode.onaudioprocess = function () {
  695. if (!audioDriving || !anim.id) return;
  696. // 用音频硬件时钟精确推进(单调、不受页面渲染节流影响)
  697. const t = audioCtx.currentTime;
  698. if (lastAudioT != null) vNow += Math.max(0, Math.min(200, (t - lastAudioT) * 1000));
  699. lastAudioT = t;
  700. tickCore();
  701. };
  702. const gain = audioCtx.createGain();
  703. gain.gain.value = 0; // 完全静音,仅用心跳
  704. audioNode.connect(gain);
  705. gain.connect(audioCtx.destination);
  706. }
  707. lastAudioT = null;
  708. // 同步判定当前状态;suspended 时异步 resume,成功后回调自动生效
  709. audioDriving = audioCtx.state === 'running';
  710. if (audioCtx.state === 'suspended') {
  711. audioCtx.resume().then(function () {
  712. audioDriving = audioCtx.state === 'running';
  713. }).catch(function () { audioDriving = false; });
  714. }
  715. } catch (e) { audioDriving = false; }
  716. }
  717. function stopAudioHeart() {
  718. audioDriving = false;
  719. lastAudioT = null;
  720. }
  721. let lastWall = Date.now();
  722. function animate() {
  723. raf = requestAnimationFrame(animate);
  724. const now = performance.now();
  725. const rafDt = lastRafNow ? now - lastRafNow : 16.7;
  726. lastRafNow = now;
  727. const audioActive = audioDriving && audioCtx && audioCtx.state === 'running' && !!anim.id;
  728. // 虚拟时钟推进源互斥:动画音频心跳运行时由音频帧推进,rAF 帧仅重渲染
  729. if (audioActive) {
  730. framesSinceRaf = 0;
  731. try { renderer.render(scene, camera); lastFrameAt = performance.now(); } catch (e) {}
  732. return;
  733. }
  734. // 墙钟流逝(Date.now 不受渲染节流冻结影响):空闲期掉帧也能补齐进度
  735. const wallNow = Date.now();
  736. const wallDt = Math.min(5000, Math.max(0, wallNow - lastWall));
  737. lastWall = wallNow;
  738. let step;
  739. if (rafDt >= 1 && rafDt < 100) step = rafDt; // rAF 时钟正常:按帧间隔
  740. else if (wallDt > 0) step = wallDt; // 渲染被节流:按墙钟补齐真实流逝
  741. else step = 16.7; // 兜底
  742. vNow += step;
  743. framesSinceRaf = 0;
  744. tickCore();
  745. }
  746. // 心跳自愈:rAF 停止(页面不可见/被节流)时由 Worker 定时器以 12fps 兜底驱动。
  747. // 判据用消息计数而非页面时钟——节流环境下页面 performance.now 可能冻结。
  748. try {
  749. const heartCode = 'setInterval(function(){postMessage(1)},83);';
  750. const heartUrl = URL.createObjectURL(new Blob([heartCode], { type: 'application/javascript' }));
  751. const heart = new Worker(heartUrl);
  752. heart.onmessage = function () {
  753. framesSinceRaf += 1;
  754. const audioActive = audioDriving && audioCtx && audioCtx.state === 'running' && !!anim.id;
  755. // rAF 停止时由 worker 帧接管;音频心跳实际运行时让位(避免双重计时)
  756. if ((framesSinceRaf > 3 || anim.id) && !audioActive) {
  757. vNow += 83;
  758. tickCore();
  759. }
  760. };
  761. if (typeof window !== 'undefined') window.__workerOk = (window.__workerOk || 0) + 1;
  762. } catch (e) {
  763. if (typeof window !== 'undefined') window.__workerFail = (window.__workerFail || 0) + 1;
  764. setInterval(function () {
  765. framesSinceRaf += 1;
  766. const audioActive = audioDriving && audioCtx && audioCtx.state === 'running' && !!anim.id;
  767. if ((framesSinceRaf > 3 || anim.id) && !audioActive) {
  768. vNow += 83;
  769. tickCore();
  770. }
  771. }, 84);
  772. }
  773. /* ---- 对外 API ---- */
  774. let lastGeomSig = '';
  775. function render(nextState, nextMaterial, panels) {
  776. resize();
  777. state = nextState;
  778. material = nextMaterial;
  779. // 结构签名:盒型/尺寸/内外侧/面数变化才重建几何;否则仅刷新面纹理(增量,避免卡顿)
  780. const sig = [state.structure, state.w, state.d, state.h, state.side, panels ? panels.length : 0].join('|');
  781. if (sig !== lastGeomSig) {
  782. lastGeomSig = sig;
  783. clearRoot();
  784. const hasParts = panels && panels.length && FOLD_PARTS[state.structure];
  785. if (hasParts) buildFromDieline(panels);
  786. if (!meshes.length) buildRigid();
  787. applyFold(foldT);
  788. applyLines();
  789. }
  790. refreshTextures();
  791. applyCamera();
  792. // 状态变化立即上屏(不依赖下一帧)
  793. try { renderer.render(scene, camera); lastFrameAt = performance.now(); } catch (e) {}
  794. }
  795. function flush() {
  796. try { renderer.render(scene, camera); lastFrameAt = performance.now(); } catch (e) {}
  797. }
  798. return {
  799. render: render,
  800. _dbg: {
  801. get scene() { return scene; },
  802. get camera() { return camera; },
  803. get renderer() { return renderer; },
  804. get meshes() { return meshes; },
  805. get hinges() { return hinges; },
  806. get root() { return root; },
  807. get orbit() { return orbit; },
  808. get autoFlag() { return autoRotate; }
  809. },
  810. setFold: function (t) { applyFold(t); flush(); },
  811. setAutoRotate: function (v) { autoRotate = !!v; },
  812. isAutoRotate: function () { return !!autoRotate; },
  813. setZoom: function (z) { orbit.zoom = Math.max(0.4, Math.min(3.2, Number(z) || 1)); applyCamera(); flush(); },
  814. setLines: function (v) { showLines = v !== false; applyLines(); flush(); },
  815. // 自动转向指定面:2D 选中面时让 3D 视角同步
  816. focusFace: function (face) {
  817. const target = {
  818. front: [0, Math.PI / 2], back: [Math.PI, Math.PI / 2],
  819. right: [Math.PI / 2, Math.PI / 2], left: [-Math.PI / 2, Math.PI / 2],
  820. top: [0, 0.32], bottom: [0, Math.PI - 0.32]
  821. }[face];
  822. if (!target) return;
  823. const fromT = orbit.theta, fromP = orbit.phi;
  824. let toT = target[0];
  825. while (toT - fromT > Math.PI) toT -= Math.PI * 2;
  826. while (toT - fromT < -Math.PI) toT += Math.PI * 2;
  827. const dur = 420, t0 = performance.now();
  828. function step(now) {
  829. const p = Math.min(1, (now - t0) / dur);
  830. const e = p < 0.5 ? 2 * p * p : 1 - Math.pow(-2 * p + 2, 2) / 2;
  831. orbit.theta = fromT + (toT - fromT) * e;
  832. orbit.phi = fromP + (target[1] - fromP) * e;
  833. applyCamera();
  834. flush();
  835. if (p < 1) requestAnimationFrame(step);
  836. }
  837. requestAnimationFrame(step);
  838. },
  839. resetView: function () {
  840. orbit.theta = orbitHome.theta;
  841. orbit.phi = orbitHome.phi;
  842. orbit.zoom = orbitHome.zoom;
  843. anim.id = null;
  844. applyCamera();
  845. flush();
  846. },
  847. playAnim: function (id, dur, onEnd) {
  848. const def = (window.PL.boxlib && window.PL.boxlib.ANIMS.find(function (a) { return a.id === id; })) || { dur: 4 };
  849. anim.id = id;
  850. anim.custom = null;
  851. anim.dur = dur || def.dur;
  852. anim.t0 = vNow; // 与 tickAnim 同一虚拟时钟,步进连续(页面时钟可能冻结不可用)
  853. anim.onEnd = onEnd || null;
  854. startAudioHeart();
  855. },
  856. // 通用补间(音频线程心跳驱动,冻结环境流畅):onUpdate 接收 0~1 进度
  857. tween: function (dur, onUpdate, onDone) {
  858. anim.id = '__tween';
  859. anim.custom = onUpdate;
  860. anim.dur = dur;
  861. anim.t0 = vNow;
  862. anim.onEnd = onDone || null;
  863. startAudioHeart();
  864. },
  865. stopAnim: function () { anim.id = null; anim.custom = null; stopAudioHeart(); },
  866. animating: function () { return !!anim.id; },
  867. snapshot: function (w, h2, transparent) {
  868. const keepW = el.clientWidth, keepH = el.clientHeight, keepZoom = orbit.zoom;
  869. if (w && h2) {
  870. renderer.setPixelRatio(1);
  871. renderer.setSize(w, h2, false);
  872. camera.aspect = w / h2;
  873. camera.updateProjectionMatrix();
  874. }
  875. renderer.render(scene, camera);
  876. let url;
  877. if (transparent) {
  878. // 用离屏合成保留透明通道
  879. const src = canvas;
  880. const c = document.createElement('canvas');
  881. c.width = src.width; c.height = src.height;
  882. const ctx = c.getContext('2d');
  883. ctx.drawImage(src, 0, 0);
  884. url = c.toDataURL('image/png');
  885. } else {
  886. url = canvas.toDataURL('image/png');
  887. }
  888. if (w && h2) {
  889. renderer.setPixelRatio(opts.mini ? 1 : Math.min(window.devicePixelRatio || 1, 2));
  890. renderer.setSize(keepW, keepH, false);
  891. camera.aspect = keepW / keepH;
  892. camera.updateProjectionMatrix();
  893. }
  894. return url;
  895. },
  896. dispose: function () {
  897. cancelAnimationFrame(raf);
  898. disposeFns.forEach(function (f) { f(); });
  899. clearRoot();
  900. renderer.dispose();
  901. if (canvas.parentNode) canvas.parentNode.removeChild(canvas);
  902. },
  903. ready: function () { return !!renderer; }
  904. };
  905. }
  906. window.PL = window.PL || {};
  907. window.PL.box3d = { create: create };
  908. })();