box3d.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  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.type === 'asset') && 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, fillOnly) {
  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. // 结构副面(如扣底/平口箱的补位摇盖)只刷底色与纹理,不重复印图案
  263. if (!fillOnly) drawFaceArt(ctx, cw, ch, data, cw / Math.max(1, size.w));
  264. }
  265. function getFaceTexture(face, size, fillOnly) {
  266. const key = (state.side || 'outer') + '|' + face + (fillOnly ? '|fill' : '');
  267. let entry = faceTexCache[key];
  268. if (!entry) {
  269. const cw = opts.mini ? 360 : 760;
  270. const ch = Math.max(160, Math.round(cw * size.h / Math.max(1, size.w)));
  271. const c = document.createElement('canvas');
  272. c.width = cw;
  273. c.height = ch;
  274. const texture = new THREE.CanvasTexture(c);
  275. texture.encoding = THREE.sRGBEncoding;
  276. texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
  277. entry = { canvas: c, ctx: c.getContext('2d'), texture: texture, cw: cw, ch: ch, sizeW: size.w, sizeH: size.h };
  278. faceTexCache[key] = entry;
  279. }
  280. return entry;
  281. }
  282. function refreshTextures() {
  283. const prefix = (state.side || 'outer') + '|';
  284. // 清理另一侧的缓存(内外侧切换后不再使用)
  285. Object.keys(faceTexCache).forEach(function (k) {
  286. if (k.indexOf(prefix) !== 0) {
  287. faceTexCache[k].texture.dispose();
  288. delete faceTexCache[k];
  289. }
  290. });
  291. meshes.forEach(function (mesh) {
  292. const face = mesh.userData.face || mesh.userData.paint;
  293. if (!face || !mesh.material) return;
  294. const entry = getFaceTexture(face, mesh.userData.faceSize || { w: 1, h: 1 }, mesh.userData.fillOnly);
  295. drawFaceTo(entry, face, mesh.userData.fillOnly);
  296. entry.texture.needsUpdate = true;
  297. if (mesh.material.map !== entry.texture) {
  298. mesh.material.map = entry.texture;
  299. mesh.material.needsUpdate = true;
  300. }
  301. });
  302. }
  303. function makeMaterial(face, size, inner, fillOnly) {
  304. const entry = getFaceTexture(face, size, fillOnly);
  305. drawFaceTo(entry, face, fillOnly);
  306. entry.texture.needsUpdate = true;
  307. return new THREE.MeshStandardMaterial({
  308. map: entry.texture,
  309. color: 0xffffff,
  310. roughness: 0.8,
  311. metalness: 0.02,
  312. side: THREE.DoubleSide
  313. });
  314. }
  315. function cardboardMaterial() {
  316. const sideData = (state.faces[state.side || 'outer'] || {});
  317. const plain = sideData._plain || {};
  318. return new THREE.MeshStandardMaterial({
  319. color: new THREE.Color(plain.color || material.paper || '#fbf7ee'),
  320. roughness: 0.86,
  321. metalness: 0.02,
  322. side: THREE.DoubleSide
  323. });
  324. }
  325. function makePanelMesh(p, box) {
  326. const geom = planeGeometry(box, p.poly);
  327. const face = p.face || p.paint || null;
  328. const fillOnly = !p.face && !!p.paint;
  329. const mat = face ? makeMaterial(face, { w: box.w, h: box.h }, state.side === 'inner', fillOnly) : cardboardMaterial();
  330. const mesh = new THREE.Mesh(geom, mat);
  331. mesh.position.z = panelLayer(p);
  332. mesh.userData.face = p.face || null;
  333. mesh.userData.paint = p.paint || null;
  334. mesh.userData.fillOnly = fillOnly;
  335. mesh.userData.faceSize = face ? { w: box.w, h: box.h } : null;
  336. mesh.add(new THREE.LineSegments(
  337. new THREE.EdgesGeometry(geom),
  338. new THREE.LineBasicMaterial({ color: 0x17140f, transparent: true, opacity: 0.24 })
  339. ));
  340. meshes.push(mesh);
  341. return mesh;
  342. }
  343. function clearRoot() {
  344. if (root) {
  345. root.traverse(function (o) {
  346. if (o.geometry) o.geometry.dispose();
  347. if (o.material) o.material.dispose();
  348. });
  349. scene.remove(root);
  350. }
  351. // 纹理缓存随几何一起释放(key 含 side,重建后按需重建)
  352. Object.keys(faceTexCache).forEach(function (k) {
  353. faceTexCache[k].texture.dispose();
  354. delete faceTexCache[k];
  355. });
  356. root = new THREE.Group();
  357. scene.add(root);
  358. meshes = [];
  359. hinges = [];
  360. components = [];
  361. }
  362. function buildComponent(indices, panels, boxes, adj, prefer) {
  363. const start = rootIndexFor(indices, panels, boxes, prefer);
  364. if (start < 0) return null;
  365. const comp = new THREE.Group();
  366. const rootGroup = new THREE.Group();
  367. comp.add(rootGroup);
  368. const rootBox = boxes[start];
  369. const rootMesh = makePanelMesh(panels[start], rootBox);
  370. rootMesh.userData.kind = panels[start].kind;
  371. rootGroup.add(rootMesh);
  372. const infos = new Map();
  373. infos.set(start, { group: rootGroup, origin: boxCenter(rootBox) });
  374. const visited = new Set([start]);
  375. const best = new Map();
  376. const addLinks = function (pi) {
  377. adj[pi].forEach(function (link) {
  378. if (visited.has(link.j)) return;
  379. const cur = best.get(link.j);
  380. if (!cur || link.overlap > cur.overlap) best.set(link.j, { from: pi, link: link });
  381. });
  382. };
  383. addLinks(start);
  384. while (visited.size < indices.length) {
  385. let pick = -1, pickW = -1;
  386. best.forEach(function (v, k) {
  387. if (visited.has(k)) return;
  388. if (v.link.overlap > pickW) { pickW = v.link.overlap; pick = k; }
  389. });
  390. if (pick < 0) break;
  391. const chosen = best.get(pick);
  392. const parent = infos.get(chosen.from);
  393. const link = chosen.link;
  394. const hinge = hingePoint(link.edge);
  395. const cb = boxes[pick];
  396. const pivot = new THREE.Group();
  397. pivot.position.set(hinge.x - parent.origin.x, -(hinge.y - parent.origin.y), 0);
  398. const n3 = new THREE.Vector3(link.edge.n.x, -link.edge.n.y, 0);
  399. if (n3.lengthSq() < 0.5) n3.set(0, 1, 0);
  400. n3.normalize();
  401. const axis = new THREE.Vector3(0, 0, 1).cross(n3).normalize();
  402. pivot.userData.axis = axis;
  403. pivot.userData.angle = Math.PI / 2;
  404. hinges.push(pivot);
  405. parent.group.add(pivot);
  406. const cc = boxCenter(cb);
  407. const mesh = makePanelMesh(panels[pick], cb);
  408. mesh.position.x = cc.x - hinge.x;
  409. mesh.position.y = -(cc.y - hinge.y);
  410. mesh.userData.kind = panels[pick].kind;
  411. pivot.add(mesh);
  412. infos.set(pick, { group: pivot, origin: hinge });
  413. visited.add(pick);
  414. best.delete(pick);
  415. addLinks(pick);
  416. }
  417. return { group: comp, root: start };
  418. }
  419. function buildFromDieline(panels) {
  420. const boxes = panels.map(panelBox);
  421. const adj = buildAdjacency(panels, boxes);
  422. const seen = new Set();
  423. const groups = [];
  424. for (let i = 0; i < panels.length; i += 1) {
  425. if (seen.has(i)) continue;
  426. const stack = [i];
  427. const indices = [];
  428. seen.add(i);
  429. while (stack.length) {
  430. const cur = stack.pop();
  431. indices.push(cur);
  432. adj[cur].forEach(function (link) {
  433. if (seen.has(link.j)) return;
  434. seen.add(link.j);
  435. stack.push(link.j);
  436. });
  437. }
  438. groups.push(indices);
  439. }
  440. const prefer = 'front';
  441. const built = [];
  442. groups.forEach(function (indices) {
  443. const comp = buildComponent(indices, panels, boxes, adj, prefer);
  444. if (comp) built.push(comp);
  445. });
  446. if (!built.length) return false;
  447. const main = built[0];
  448. const mainOrigin = boxCenter(boxes[main.root]);
  449. built.forEach(function (c) {
  450. const center = boxCenter(boxes[c.root]);
  451. c.home = new THREE.Vector3(center.x - mainOrigin.x, -(center.y - mainOrigin.y), 0);
  452. c.assembled = new THREE.Vector3(0, 0, 0);
  453. c.assembledScale = 1;
  454. c.isMain = c === main;
  455. if (!c.isMain) {
  456. c.assembled.set(0, 0, -2);
  457. c.assembledScale = 0.94;
  458. }
  459. c.group.position.copy(c.home);
  460. root.add(c.group);
  461. components.push(c);
  462. });
  463. root.userData.mainOrigin = { x: mainOrigin.x, y: mainOrigin.y };
  464. return true;
  465. }
  466. function buildRigid() {
  467. const t = material.thickness || 0;
  468. const W = state.w + t * 2;
  469. const D = state.d + t * 2;
  470. const H = state.h + t * 2;
  471. const inner = state.side === 'inner';
  472. const defs = [
  473. { face: 'front', w: W, h: H, pos: [0, 0, D / 2], rot: [0, 0, 0] },
  474. { face: 'back', w: W, h: H, pos: [0, 0, -D / 2], rot: [0, Math.PI, 0] },
  475. { face: 'right', w: D, h: H, pos: [W / 2, 0, 0], rot: [0, Math.PI / 2, 0] },
  476. { face: 'left', w: D, h: H, pos: [-W / 2, 0, 0], rot: [0, -Math.PI / 2, 0] },
  477. { face: 'top', w: W, h: D, pos: [0, H / 2, 0], rot: [-Math.PI / 2, 0, 0] },
  478. { face: 'bottom', w: W, h: D, pos: [0, -H / 2, 0], rot: [Math.PI / 2, 0, 0] }
  479. ];
  480. defs.forEach(function (def) {
  481. const geom = new THREE.PlaneGeometry(def.w, def.h);
  482. const mat = makeMaterial(def.face, { w: def.w, h: def.h }, inner);
  483. const mesh = new THREE.Mesh(geom, mat);
  484. mesh.position.set(def.pos[0], def.pos[1], def.pos[2]);
  485. mesh.rotation.set(def.rot[0], def.rot[1], def.rot[2]);
  486. mesh.userData.face = def.face;
  487. mesh.userData.faceSize = { w: def.w, h: def.h };
  488. root.add(mesh);
  489. meshes.push(mesh);
  490. mesh.add(new THREE.LineSegments(
  491. new THREE.EdgesGeometry(geom),
  492. new THREE.LineBasicMaterial({ color: 0x17140f, transparent: true, opacity: 0.22 })
  493. ));
  494. });
  495. }
  496. /* ---- 动效引擎 ---- */
  497. const anim = { id: null, t0: 0, dur: 0, onEnd: null };
  498. const animState = { theta: 0, phi: 0, zoom: 1, dx: 0, dy: 0, dz: 0, fold: null };
  499. const EASE = {
  500. io: function (t) { return t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2; },
  501. out: function (t) { return 1 - Math.pow(1 - t, 3); },
  502. bounce: function (t) {
  503. const n1 = 7.5625, d1 = 2.75;
  504. if (t < 1 / d1) return n1 * t * t;
  505. if (t < 2 / d1) return n1 * (t -= 1.5 / d1) * t + 0.75;
  506. if (t < 2.5 / d1) return n1 * (t -= 2.25 / d1) * t + 0.9375;
  507. return n1 * (t -= 2.625 / d1) * t + 0.984375;
  508. }
  509. };
  510. const ANIM_TICKS = {
  511. fold: function (p) {
  512. animState.fold = p < 0.5 ? EASE.io(p * 2) : 1 - EASE.io((p - 0.5) * 2);
  513. },
  514. spinFlat: function (p) {
  515. animState.phi = 0.18;
  516. animState.theta = EASE.io(p) * Math.PI * 2;
  517. },
  518. spinTop: function (p) {
  519. animState.phi = -1.05;
  520. animState.theta = EASE.io(p) * Math.PI * 2;
  521. },
  522. dropSpin: function (p) {
  523. const k = EASE.out(Math.min(1, p / 0.55));
  524. animState.dy = (1 - k) * 260;
  525. animState.theta = (1 - k) * Math.PI * 2.2;
  526. animState.dz = (1 - k) * -80;
  527. },
  528. zoomIn: function (p) {
  529. animState.zoom = 0.35 + EASE.io(p) * 0.75;
  530. animState.phi = 0.12;
  531. },
  532. dropZoom: function (p) {
  533. if (p < 0.375) {
  534. const k = EASE.out(p / 0.375);
  535. animState.dy = (1 - k) * 300;
  536. animState.theta = (1 - k) * Math.PI * 2.4;
  537. } else {
  538. const k = EASE.io((p - 0.375) / 0.625);
  539. animState.zoom = 1 + k * 1.1;
  540. animState.phi = 0.1 + k * 0.2;
  541. }
  542. },
  543. zoomDetail: function (p) {
  544. animState.zoom = 0.4 + EASE.io(p) * 1.2;
  545. animState.theta = -0.3 * (1 - p);
  546. animState.phi = 0.25 - p * 0.12;
  547. },
  548. fromLeft: function (p) {
  549. const k = EASE.out(p);
  550. animState.dx = (1 - k) * -220;
  551. animState.theta = (1 - k) * -Math.PI * 1.5;
  552. animState.phi = 0.3;
  553. },
  554. curveIn: function (p) {
  555. const k = EASE.io(p);
  556. animState.dz = (1 - k) * -400;
  557. animState.dx = Math.sin(p * Math.PI) * -120 * (1 - p);
  558. animState.dy = Math.sin(p * Math.PI) * 90;
  559. animState.theta = (1 - k) * -0.9;
  560. },
  561. foldBounce: function (p) {
  562. animState.fold = EASE.io(Math.min(1, p / 0.7));
  563. if (p > 0.7) animState.dy = -(1 - EASE.bounce((p - 0.7) / 0.3)) * 14;
  564. }
  565. };
  566. function tickAnim(now) {
  567. if (!anim.id) return false;
  568. const p = Math.min(1, (now - anim.t0) / (anim.dur * 1000));
  569. Object.assign(animState, { theta: 0, phi: 0, zoom: 1, dx: 0, dy: 0, dz: 0, fold: null });
  570. if (anim.custom) anim.custom(p);
  571. else ANIM_TICKS[anim.id](p);
  572. if (p >= 1) {
  573. const end = anim.onEnd;
  574. const wasCustom = anim.custom;
  575. anim.id = null;
  576. anim.custom = null;
  577. if (wasCustom) stopAudioHeart();
  578. if (end) end();
  579. }
  580. return true;
  581. }
  582. function applyCamera() {
  583. if (!camera || !root) return;
  584. root.updateMatrixWorld(true);
  585. const bbox = new THREE.Box3().setFromObject(root);
  586. if (bbox.isEmpty()) return;
  587. const center = bbox.getCenter(new THREE.Vector3());
  588. const size = bbox.getSize(new THREE.Vector3());
  589. const maxDim = Math.max(size.x, size.y, size.z, 1);
  590. const zoom = orbit.zoom * animState.zoom;
  591. const r = maxDim * 2.85 / Math.max(0.3, zoom);
  592. const phi = Math.max(0.15, Math.min(Math.PI - 0.15, orbit.phi + animState.phi));
  593. const theta = orbit.theta + animState.theta;
  594. const x = r * Math.sin(phi) * Math.sin(theta);
  595. const y = r * Math.cos(phi);
  596. const z = r * Math.sin(phi) * Math.cos(theta);
  597. camera.position.set(center.x + x + animState.dx, center.y + y + animState.dy, center.z + z + animState.dz);
  598. camera.lookAt(center.x + animState.dx * 0.2, center.y - maxDim * (opts.mini ? 0.02 : 0.05), center.z);
  599. }
  600. function applyFold(t) {
  601. foldT = Math.max(0, Math.min(1, Number(t) || 0));
  602. hinges.forEach(function (g) {
  603. g.setRotationFromAxisAngle(g.userData.axis, g.userData.angle * (1 - foldT));
  604. });
  605. // 盒体闭合时插舌应插入盒内,简化折纸模型无法表达穿插,直接隐藏
  606. const showTuck = foldT > 0.35;
  607. meshes.forEach(function (m) {
  608. if (m.userData.kind === 'tuck') m.visible = showTuck;
  609. });
  610. components.forEach(function (c) {
  611. if (c.isMain) return;
  612. c.group.position.lerpVectors(c.assembled, c.home, foldT);
  613. const s = c.assembledScale + (1 - c.assembledScale) * foldT;
  614. c.group.scale.set(s, s, s);
  615. });
  616. }
  617. function applyLines() {
  618. if (!root) return;
  619. root.traverse(function (o) { if (o.isLineSegments) o.visible = showLines; });
  620. }
  621. /* ---- 交互 ---- */
  622. function bindPointer() {
  623. canvas.addEventListener('pointerdown', function (e) {
  624. if (e.button !== 0) return;
  625. if (opts.mini && opts.onInteract) opts.onInteract(); // 按下即接管(停掉 CSS 自动播放)
  626. drag = { x: e.clientX, y: e.clientY, theta: orbit.theta, phi: orbit.phi };
  627. moved = false;
  628. canvas.style.cursor = 'grabbing';
  629. canvas.setPointerCapture(e.pointerId);
  630. });
  631. canvas.addEventListener('pointermove', function (e) {
  632. if (!drag) return;
  633. const dx = e.clientX - drag.x;
  634. const dy = e.clientY - drag.y;
  635. if (Math.abs(dx) + Math.abs(dy) > 3) moved = true;
  636. orbit.theta = drag.theta - dx * 0.008;
  637. orbit.phi = Math.max(0.25, Math.min(Math.PI - 0.25, drag.phi - dy * 0.006));
  638. if (opts.mini && autoRotate && moved && opts.onInteract) {
  639. autoRotate = false;
  640. opts.onInteract();
  641. }
  642. applyCamera();
  643. flush(); // 交互即时渲染:拖拽旋转不依赖 rAF 节奏
  644. });
  645. canvas.addEventListener('pointerup', function (e) {
  646. if (!drag) return;
  647. const wasMoved = moved;
  648. drag = null;
  649. canvas.style.cursor = 'grab';
  650. try { canvas.releasePointerCapture(e.pointerId); } catch (err) {}
  651. if (wasMoved || !onFacePick) return;
  652. const rect = canvas.getBoundingClientRect();
  653. const px = ((e.clientX - rect.left) / rect.width) * 2 - 1;
  654. const py = -((e.clientY - rect.top) / rect.height) * 2 + 1;
  655. const rc = new THREE.Raycaster();
  656. rc.setFromCamera(new THREE.Vector2(px, py), camera);
  657. const hits = rc.intersectObjects(meshes, false);
  658. if (hits.length && hits[0].object.userData.face) onFacePick(hits[0].object.userData.face);
  659. });
  660. canvas.addEventListener('pointercancel', function () {
  661. drag = null;
  662. canvas.style.cursor = 'grab';
  663. });
  664. canvas.addEventListener('wheel', function (e) {
  665. e.preventDefault();
  666. e.stopPropagation();
  667. orbit.zoom = Math.max(0.4, Math.min(3.2, orbit.zoom * (e.deltaY > 0 ? 0.92 : 1.08)));
  668. applyCamera();
  669. flush();
  670. }, { passive: false });
  671. }
  672. bindPointer();
  673. let lastFrameAt = performance.now();
  674. // 虚拟时钟:页面时钟可能被节流冻结(rAF 停、setInterval 降频、performance.now 冻结),
  675. // 由 Web Worker 心跳(Worker 定时器不受页面可见性节流)持续推进,保证自动播放匀速循环。
  676. let vNow = performance.now();
  677. let lastVTick = vNow;
  678. const AUTO_SPEED = 0.28; // 约 22 秒一圈
  679. function tickCore() {
  680. const dt = Math.min(0.12, Math.max(0, vNow - lastVTick)) / 1000;
  681. lastVTick = vNow;
  682. try {
  683. const hasAnim = tickAnim(vNow);
  684. if (!anim.id && audioDriving) stopAudioHeart();
  685. if (autoRotate && !anim.id) orbit.theta += AUTO_SPEED * dt;
  686. if (animState.fold != null) applyFold(animState.fold);
  687. applyCamera();
  688. if (renderer && scene && camera) renderer.render(scene, camera);
  689. } catch (e) {
  690. // 单帧异常不终止渲染循环
  691. }
  692. }
  693. let framesSinceRaf = 0; // worker 心跳消息计数,rAF 有效帧清零
  694. let lastRafNow = 0;
  695. /* 音频线程心跳:AudioContext 回调独立于页面渲染节流,动画播放期提供 ~46fps 稳定帧 */
  696. let audioCtx = null, audioNode = null, audioDriving = false, lastAudioT = null;
  697. function startAudioHeart() {
  698. try {
  699. const AC = window.AudioContext || window.webkitAudioContext;
  700. if (!AC) return;
  701. if (!audioCtx) {
  702. audioCtx = new AC();
  703. audioNode = audioCtx.createScriptProcessor(2048, 1, 1);
  704. audioNode.onaudioprocess = function () {
  705. if (!audioDriving || !anim.id) return;
  706. // 用音频硬件时钟精确推进(单调、不受页面渲染节流影响)
  707. const t = audioCtx.currentTime;
  708. if (lastAudioT != null) vNow += Math.max(0, Math.min(200, (t - lastAudioT) * 1000));
  709. lastAudioT = t;
  710. tickCore();
  711. };
  712. const gain = audioCtx.createGain();
  713. gain.gain.value = 0; // 完全静音,仅用心跳
  714. audioNode.connect(gain);
  715. gain.connect(audioCtx.destination);
  716. }
  717. lastAudioT = null;
  718. // 同步判定当前状态;suspended 时异步 resume,成功后回调自动生效
  719. audioDriving = audioCtx.state === 'running';
  720. if (audioCtx.state === 'suspended') {
  721. audioCtx.resume().then(function () {
  722. audioDriving = audioCtx.state === 'running';
  723. }).catch(function () { audioDriving = false; });
  724. }
  725. } catch (e) { audioDriving = false; }
  726. }
  727. function stopAudioHeart() {
  728. audioDriving = false;
  729. lastAudioT = null;
  730. }
  731. let lastWall = Date.now();
  732. function animate() {
  733. raf = requestAnimationFrame(animate);
  734. const now = performance.now();
  735. const rafDt = lastRafNow ? now - lastRafNow : 16.7;
  736. lastRafNow = now;
  737. const audioActive = audioDriving && audioCtx && audioCtx.state === 'running' && !!anim.id;
  738. // 虚拟时钟推进源互斥:动画音频心跳运行时由音频帧推进,rAF 帧仅重渲染
  739. if (audioActive) {
  740. framesSinceRaf = 0;
  741. try { renderer.render(scene, camera); lastFrameAt = performance.now(); } catch (e) {}
  742. return;
  743. }
  744. // 墙钟流逝(Date.now 不受渲染节流冻结影响):空闲期掉帧也能补齐进度
  745. const wallNow = Date.now();
  746. const wallDt = Math.min(5000, Math.max(0, wallNow - lastWall));
  747. lastWall = wallNow;
  748. let step;
  749. if (rafDt >= 1 && rafDt < 100) step = rafDt; // rAF 时钟正常:按帧间隔
  750. else if (wallDt > 0) step = wallDt; // 渲染被节流:按墙钟补齐真实流逝
  751. else step = 16.7; // 兜底
  752. vNow += step;
  753. framesSinceRaf = 0;
  754. tickCore();
  755. }
  756. // 心跳自愈:rAF 停止(页面不可见/被节流)时由 Worker 定时器以 12fps 兜底驱动。
  757. // 判据用消息计数而非页面时钟——节流环境下页面 performance.now 可能冻结。
  758. try {
  759. const heartCode = 'setInterval(function(){postMessage(1)},83);';
  760. const heartUrl = URL.createObjectURL(new Blob([heartCode], { type: 'application/javascript' }));
  761. const heart = new Worker(heartUrl);
  762. heart.onmessage = function () {
  763. framesSinceRaf += 1;
  764. const audioActive = audioDriving && audioCtx && audioCtx.state === 'running' && !!anim.id;
  765. // rAF 停止时由 worker 帧接管;音频心跳实际运行时让位(避免双重计时)
  766. if ((framesSinceRaf > 3 || anim.id) && !audioActive) {
  767. vNow += 83;
  768. tickCore();
  769. }
  770. };
  771. if (typeof window !== 'undefined') window.__workerOk = (window.__workerOk || 0) + 1;
  772. } catch (e) {
  773. if (typeof window !== 'undefined') window.__workerFail = (window.__workerFail || 0) + 1;
  774. setInterval(function () {
  775. framesSinceRaf += 1;
  776. const audioActive = audioDriving && audioCtx && audioCtx.state === 'running' && !!anim.id;
  777. if ((framesSinceRaf > 3 || anim.id) && !audioActive) {
  778. vNow += 83;
  779. tickCore();
  780. }
  781. }, 84);
  782. }
  783. /* ---- 对外 API ---- */
  784. let lastGeomSig = '';
  785. function render(nextState, nextMaterial, panels) {
  786. resize();
  787. state = nextState;
  788. material = nextMaterial;
  789. // 结构签名:盒型/尺寸/内外侧/面数变化才重建几何;否则仅刷新面纹理(增量,避免卡顿)
  790. const sig = [state.structure, state.w, state.d, state.h, state.side, panels ? panels.length : 0].join('|');
  791. if (sig !== lastGeomSig) {
  792. lastGeomSig = sig;
  793. clearRoot();
  794. const hasParts = panels && panels.length && FOLD_PARTS[state.structure];
  795. if (hasParts) buildFromDieline(panels);
  796. if (!meshes.length) buildRigid();
  797. applyFold(foldT);
  798. applyLines();
  799. }
  800. refreshTextures();
  801. applyCamera();
  802. // 状态变化立即上屏(不依赖下一帧)
  803. try { renderer.render(scene, camera); lastFrameAt = performance.now(); } catch (e) {}
  804. }
  805. function flush() {
  806. try { renderer.render(scene, camera); lastFrameAt = performance.now(); } catch (e) {}
  807. }
  808. return {
  809. render: render,
  810. _dbg: {
  811. get scene() { return scene; },
  812. get camera() { return camera; },
  813. get renderer() { return renderer; },
  814. get meshes() { return meshes; },
  815. get hinges() { return hinges; },
  816. get root() { return root; },
  817. get orbit() { return orbit; },
  818. get autoFlag() { return autoRotate; }
  819. },
  820. setFold: function (t) { applyFold(t); flush(); },
  821. setAutoRotate: function (v) { autoRotate = !!v; },
  822. isAutoRotate: function () { return !!autoRotate; },
  823. setZoom: function (z) { orbit.zoom = Math.max(0.4, Math.min(3.2, Number(z) || 1)); applyCamera(); flush(); },
  824. setLines: function (v) { showLines = v !== false; applyLines(); flush(); },
  825. // 自动转向指定面:2D 选中面时让 3D 视角同步
  826. focusFace: function (face) {
  827. const target = {
  828. front: [0, Math.PI / 2], back: [Math.PI, Math.PI / 2],
  829. right: [Math.PI / 2, Math.PI / 2], left: [-Math.PI / 2, Math.PI / 2],
  830. top: [0, 0.32], bottom: [0, Math.PI - 0.32]
  831. }[face];
  832. if (!target) return;
  833. const fromT = orbit.theta, fromP = orbit.phi;
  834. let toT = target[0];
  835. while (toT - fromT > Math.PI) toT -= Math.PI * 2;
  836. while (toT - fromT < -Math.PI) toT += Math.PI * 2;
  837. const dur = 420, t0 = performance.now();
  838. function step(now) {
  839. const p = Math.min(1, (now - t0) / dur);
  840. const e = p < 0.5 ? 2 * p * p : 1 - Math.pow(-2 * p + 2, 2) / 2;
  841. orbit.theta = fromT + (toT - fromT) * e;
  842. orbit.phi = fromP + (target[1] - fromP) * e;
  843. applyCamera();
  844. flush();
  845. if (p < 1) requestAnimationFrame(step);
  846. }
  847. requestAnimationFrame(step);
  848. },
  849. resetView: function () {
  850. orbit.theta = orbitHome.theta;
  851. orbit.phi = orbitHome.phi;
  852. orbit.zoom = orbitHome.zoom;
  853. anim.id = null;
  854. applyCamera();
  855. flush();
  856. },
  857. playAnim: function (id, dur, onEnd) {
  858. const def = (window.PL.boxlib && window.PL.boxlib.ANIMS.find(function (a) { return a.id === id; })) || { dur: 4 };
  859. anim.id = id;
  860. anim.custom = null;
  861. anim.dur = dur || def.dur;
  862. anim.t0 = vNow; // 与 tickAnim 同一虚拟时钟,步进连续(页面时钟可能冻结不可用)
  863. anim.onEnd = onEnd || null;
  864. startAudioHeart();
  865. },
  866. // 通用补间(音频线程心跳驱动,冻结环境流畅):onUpdate 接收 0~1 进度
  867. tween: function (dur, onUpdate, onDone) {
  868. anim.id = '__tween';
  869. anim.custom = onUpdate;
  870. anim.dur = dur;
  871. anim.t0 = vNow;
  872. anim.onEnd = onDone || null;
  873. startAudioHeart();
  874. },
  875. stopAnim: function () { anim.id = null; anim.custom = null; stopAudioHeart(); },
  876. animating: function () { return !!anim.id; },
  877. snapshot: function (w, h2, transparent) {
  878. const keepW = el.clientWidth, keepH = el.clientHeight, keepZoom = orbit.zoom;
  879. if (w && h2) {
  880. renderer.setPixelRatio(1);
  881. renderer.setSize(w, h2, false);
  882. camera.aspect = w / h2;
  883. camera.updateProjectionMatrix();
  884. }
  885. renderer.render(scene, camera);
  886. let url;
  887. if (transparent) {
  888. // 用离屏合成保留透明通道
  889. const src = canvas;
  890. const c = document.createElement('canvas');
  891. c.width = src.width; c.height = src.height;
  892. const ctx = c.getContext('2d');
  893. ctx.drawImage(src, 0, 0);
  894. url = c.toDataURL('image/png');
  895. } else {
  896. url = canvas.toDataURL('image/png');
  897. }
  898. if (w && h2) {
  899. renderer.setPixelRatio(opts.mini ? 1 : Math.min(window.devicePixelRatio || 1, 2));
  900. renderer.setSize(keepW, keepH, false);
  901. camera.aspect = keepW / keepH;
  902. camera.updateProjectionMatrix();
  903. }
  904. return url;
  905. },
  906. dispose: function () {
  907. cancelAnimationFrame(raf);
  908. disposeFns.forEach(function (f) { f(); });
  909. clearRoot();
  910. renderer.dispose();
  911. if (canvas.parentNode) canvas.parentNode.removeChild(canvas);
  912. },
  913. ready: function () { return !!renderer; }
  914. };
  915. }
  916. window.PL = window.PL || {};
  917. window.PL.box3d = { create: create };
  918. })();