| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935 |
- /**
- * box3d.js — Three.js 盒子 3D 渲染(多实例工厂版)
- * - 从刀版 panels 自动构建铰链折叠
- * - 外侧 / 内侧独立贴图
- * - 10 种动效(折叠展开 / 自转 / 掉落 / 由远到近……)
- * - 重置视角、2K/3K/4K 高清截图、透明背景
- */
- (function () {
- const THREE = window.THREE;
- if (!THREE) return;
- function fontStack(key) {
- const fonts = window.PL && window.PL.data && window.PL.data.fonts;
- return (fonts && fonts[key] && fonts[key].stack) || '"PingFang SC", "Helvetica Neue", sans-serif';
- }
- function panelBox(p) {
- if (p.poly) {
- const xs = p.poly.map(function (pt) { return pt[0]; });
- const ys = p.poly.map(function (pt) { return pt[1]; });
- const x = Math.min.apply(null, xs);
- const y = Math.min.apply(null, ys);
- return { x: x, y: y, w: Math.max.apply(null, xs) - x, h: Math.max.apply(null, ys) - y };
- }
- return { x: p.x, y: p.y, w: p.w, h: p.h };
- }
- function boxCenter(b) { return { x: b.x + b.w / 2, y: b.y + b.h / 2 }; }
- function planeGeometry(b, poly) {
- if (!poly) return new THREE.PlaneGeometry(b.w, b.h);
- const shape = new THREE.Shape();
- poly.forEach(function (pt, i) {
- const x = pt[0] - b.x - b.w / 2;
- const y = -(pt[1] - b.y - b.h / 2);
- if (i === 0) shape.moveTo(x, y);
- else shape.lineTo(x, y);
- });
- shape.closePath();
- const geom = new THREE.ShapeGeometry(shape);
- const pos = geom.attributes.position;
- const uv = geom.attributes.uv;
- for (let i = 0; i < pos.count; i += 1) {
- 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));
- }
- uv.needsUpdate = true;
- return geom;
- }
- const FOLD_PARTS = { carton: 1, rsc: 1, mailbox: 1, tuck: 1, straight: 1, autobottom: 1, mailer: 1, drawer: 1, bag: 1, sleeve: 1 };
- function panelLayer(p) {
- if (p.kind === 'glue') return -0.6;
- if (p.kind === 'lip') return -0.9;
- if (p.kind === 'dust') return -0.35;
- if (p.kind === 'tuck') return -0.28;
- if (p.kind === 'flap') return -0.12;
- return 0;
- }
- function isBodyKind(k) {
- return !(k === 'glue' || k === 'flap' || k === 'dust' || k === 'tuck' || k === 'lip');
- }
- function canHinge(a, b) {
- const ka = a.kind || 'body';
- const kb = b.kind || 'body';
- if (isBodyKind(ka) !== isBodyKind(kb)) return true;
- if (isBodyKind(ka) && isBodyKind(kb)) return true;
- return (ka === 'tuck' && kb === 'flap') || (ka === 'flap' && kb === 'tuck');
- }
- function panelEdges(p) {
- const b = panelBox(p);
- 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]];
- const out = [];
- for (let i = 0; i < pts.length; i += 1) {
- const a = pts[i];
- const c = pts[(i + 1) % pts.length];
- 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]) });
- 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]) });
- }
- return out;
- }
- function sharedEdge(a, b) {
- let best = null;
- panelEdges(a).forEach(function (ea) {
- panelEdges(b).forEach(function (eb) {
- if (ea.axis !== eb.axis || Math.abs(ea.c - eb.c) > 0.6) return;
- const lo = Math.max(ea.lo, eb.lo);
- const hi = Math.min(ea.hi, eb.hi);
- const len = hi - lo;
- if (len <= 2) return;
- if (!best || len > best.len) best = { axis: ea.axis, c: ea.c, lo: lo, hi: hi, len: len };
- });
- });
- return best;
- }
- function buildAdjacency(panels, boxes) {
- const adj = panels.map(function () { return []; });
- for (let i = 0; i < panels.length; i += 1) {
- for (let j = i + 1; j < panels.length; j += 1) {
- if (!canHinge(panels[i], panels[j])) continue;
- const edge = sharedEdge(panels[i], panels[j]);
- if (!edge) continue;
- const ca = boxCenter(boxes[i]);
- const cb = boxCenter(boxes[j]);
- let n;
- if (edge.axis === 'v') n = { x: cb.x >= ca.x ? 1 : -1, y: 0 };
- else n = { x: 0, y: cb.y >= ca.y ? 1 : -1 };
- const mk = function (s) {
- return edge.axis === 'v'
- ? { axis: 'v', x: edge.c, y0: edge.lo, y1: edge.hi, n: { x: n.x * s, y: n.y * s } }
- : { axis: 'h', x0: edge.lo, x1: edge.hi, y: edge.c, n: { x: n.x * s, y: n.y * s } };
- };
- adj[i].push({ j: j, edge: mk(1), overlap: edge.len });
- adj[j].push({ j: i, edge: mk(-1), overlap: edge.len });
- }
- }
- return adj;
- }
- function hingePoint(edge) {
- if (edge.axis === 'v') return { x: edge.x, y: (edge.y0 + edge.y1) / 2 };
- return { x: (edge.x0 + edge.x1) / 2, y: edge.y };
- }
- function rootIndexFor(indices, panels, boxes, prefer) {
- let best = -1, bestScore = -Infinity;
- indices.forEach(function (idx) {
- const b = boxes[idx];
- const face = panels[idx].face;
- const score = (face === prefer ? 1e9 : 0) + (face ? 1e6 : 0) + b.w * b.h;
- if (score > bestScore) { bestScore = score; best = idx; }
- });
- return best;
- }
- /* ================= 实例工厂 ================= */
- function create(el, opts) {
- opts = opts || {};
- let renderer = null, scene = null, camera = null, root = null, canvas = null;
- let meshes = [], hinges = [], components = [];
- const orbit = { theta: -0.55, phi: 1.08, zoom: 1 };
- const orbitHome = { theta: -0.55, phi: 1.08, zoom: 1 };
- let autoRotate = false;
- let onFacePick = opts.onFacePick || null;
- let drag = null, moved = false, raf = null;
- let foldT = 0;
- let showLines = true;
- let state = null, material = null;
- let disposeFns = [];
- renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });
- renderer.setPixelRatio(opts.mini ? 1 : Math.min(window.devicePixelRatio || 1, 2));
- renderer.outputEncoding = THREE.sRGBEncoding;
- renderer.setClearColor(0x000000, 0);
- canvas = renderer.domElement;
- canvas.className = 'box3d-canvas';
- canvas.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;display:block;z-index:2;touch-action:none;cursor:grab;';
- el.appendChild(canvas);
- el.classList.add('three-active');
- scene = new THREE.Scene();
- camera = new THREE.PerspectiveCamera(32, 1, 1, 60000);
- scene.add(new THREE.AmbientLight(0xffffff, 0.82));
- const key = new THREE.DirectionalLight(0xffffff, 0.8);
- key.position.set(-350, 600, 800);
- scene.add(key);
- const fill = new THREE.DirectionalLight(0xffffff, 0.34);
- fill.position.set(600, -260, -500);
- scene.add(fill);
- const rim = new THREE.DirectionalLight(0xffffff, 0.22);
- rim.position.set(-500, -200, -700);
- scene.add(rim);
- function resize() {
- const w = Math.max(1, el.clientWidth);
- const hh = Math.max(1, el.clientHeight);
- renderer.setSize(w, hh, false);
- camera.aspect = w / hh;
- camera.updateProjectionMatrix();
- }
- resize();
- if (window.ResizeObserver) {
- const ro = new ResizeObserver(resize);
- ro.observe(el);
- disposeFns.push(function () { ro.disconnect(); });
- }
- /* ---- 贴图 ---- */
- function drawFaceArt(ctx, cw, ch, data, px2mm) {
- const items = (data && data.items) || [];
- items.forEach(function (it) {
- if (it.hidden) return;
- if (it.type === 'text') {
- const px = it.size * px2mm;
- const lines = String(it.text || '').split('\n');
- const lh = (it.lineHeight || 1.25) * px;
- ctx.save();
- ctx.fillStyle = it.color || '#17140f';
- ctx.textAlign = it.align === 'center' ? 'center' : it.align === 'right' ? 'right' : 'left';
- ctx.textBaseline = 'middle';
- ctx.font = (it.italic ? 'italic ' : '') + (it.weight || 400) + ' ' + px + 'px ' + fontStack(it.font);
- const x = (it.x / 100) * cw;
- const y = (it.y / 100) * ch;
- lines.forEach(function (line, i) {
- ctx.fillText(line, x, y + (i - (lines.length - 1) / 2) * lh);
- });
- ctx.restore();
- } else if (it.type === 'image' && it.src) {
- const img = getCachedImage(it.src, function () { refreshTextures(); });
- if (img) {
- const iw = ((it.w == null ? 70 : it.w) / 100) * cw;
- const ix = ((it.x == null ? 50 : it.x) / 100) * cw;
- const iy = ((it.y == null ? 50 : it.y) / 100) * ch;
- 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) {}
- }
- } else if (it.type === 'barcode' && it.src) {
- const img = getCachedImage(it.src, function () { refreshTextures(); });
- if (img) {
- const iw = ((it.w || 40) / 100) * cw;
- const ix = (it.x / 100) * cw;
- const iy = (it.y / 100) * ch;
- try { ctx.drawImage(img, ix - iw / 2, iy - iw * 0.42, iw, iw * 0.84); } catch (e) {}
- }
- }
- });
- // 兼容旧数据
- (data && data.texts || []).forEach(function (t) {
- const px = t.size * px2mm;
- const lines = String(t.text || '').split('\n');
- const lh = (t.lineHeight || 1.25) * px;
- ctx.save();
- ctx.fillStyle = t.color || '#17140f';
- ctx.textAlign = t.align === 'center' ? 'center' : t.align === 'right' ? 'right' : 'left';
- ctx.textBaseline = 'middle';
- ctx.font = (t.italic ? 'italic ' : '') + (t.weight || 400) + ' ' + px + 'px ' + fontStack(t.font);
- const x = (t.x / 100) * cw;
- const y = (t.y / 100) * ch;
- lines.forEach(function (line, i) { ctx.fillText(line, x, y + (i - (lines.length - 1) / 2) * lh); });
- ctx.restore();
- });
- }
- /* ---- 面纹理缓存:几何不变时仅重绘画布内容(needsUpdate),避免整场景重建 ---- */
- const faceTexCache = {}; // side|face -> { canvas, ctx, texture, cw, ch }
- const imgCache = new Map(); // src -> HTMLImageElement(避免重复解码)
- function getCachedImage(src, onReady) {
- if (imgCache.has(src)) {
- const img = imgCache.get(src);
- if (img.complete && img.naturalWidth) return img;
- return null;
- }
- const img = new Image();
- img.onload = function () { if (onReady) onReady(); };
- img.src = src;
- imgCache.set(src, img);
- return null;
- }
- function drawFaceTo(entry, face) {
- const sideData = (state.faces[state.side || 'outer'] || {});
- const data = sideData[face] || {};
- const ctx = entry.ctx;
- const cw = entry.cw, ch = entry.ch;
- const size = { w: entry.sizeW, h: entry.sizeH };
- ctx.setTransform(1, 0, 0, 1, 0, 0);
- ctx.fillStyle = data.color || material.paper || '#fbf7ee';
- ctx.fillRect(0, 0, cw, ch);
- if (data.texture) {
- const tex = getCachedImage(data.texture, function () { refreshTextures(); });
- if (tex) {
- const scale = Math.max(cw / 220, ch / 220);
- for (let tx = 0; tx < cw; tx += 220 * scale) for (let ty = 0; ty < ch; ty += 220 * scale) {
- ctx.drawImage(tex, tx, ty, 220 * scale, 220 * scale);
- }
- }
- }
- drawFaceArt(ctx, cw, ch, data, cw / Math.max(1, size.w));
- }
- function getFaceTexture(face, size) {
- const key = (state.side || 'outer') + '|' + face;
- let entry = faceTexCache[key];
- if (!entry) {
- const cw = opts.mini ? 360 : 760;
- const ch = Math.max(160, Math.round(cw * size.h / Math.max(1, size.w)));
- const c = document.createElement('canvas');
- c.width = cw;
- c.height = ch;
- const texture = new THREE.CanvasTexture(c);
- texture.encoding = THREE.sRGBEncoding;
- texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
- entry = { canvas: c, ctx: c.getContext('2d'), texture: texture, cw: cw, ch: ch, sizeW: size.w, sizeH: size.h };
- faceTexCache[key] = entry;
- }
- return entry;
- }
- function refreshTextures() {
- const prefix = (state.side || 'outer') + '|';
- // 清理另一侧的缓存(内外侧切换后不再使用)
- Object.keys(faceTexCache).forEach(function (k) {
- if (k.indexOf(prefix) !== 0) {
- faceTexCache[k].texture.dispose();
- delete faceTexCache[k];
- }
- });
- meshes.forEach(function (mesh) {
- const face = mesh.userData.face;
- if (!face || !mesh.material) return;
- const entry = getFaceTexture(face, mesh.userData.faceSize || { w: 1, h: 1 });
- drawFaceTo(entry, face);
- entry.texture.needsUpdate = true;
- if (mesh.material.map !== entry.texture) {
- mesh.material.map = entry.texture;
- mesh.material.needsUpdate = true;
- }
- });
- }
- function makeMaterial(face, size, inner) {
- const entry = getFaceTexture(face, size);
- drawFaceTo(entry, face);
- entry.texture.needsUpdate = true;
- return new THREE.MeshStandardMaterial({
- map: entry.texture,
- color: 0xffffff,
- roughness: 0.8,
- metalness: 0.02,
- side: THREE.DoubleSide
- });
- }
- function cardboardMaterial() {
- const sideData = (state.faces[state.side || 'outer'] || {});
- const plain = sideData._plain || {};
- return new THREE.MeshStandardMaterial({
- color: new THREE.Color(plain.color || material.paper || '#fbf7ee'),
- roughness: 0.86,
- metalness: 0.02,
- side: THREE.DoubleSide
- });
- }
- function makePanelMesh(p, box) {
- const geom = planeGeometry(box, p.poly);
- const mat = p.face ? makeMaterial(p.face, { w: box.w, h: box.h }, state.side === 'inner') : cardboardMaterial();
- const mesh = new THREE.Mesh(geom, mat);
- mesh.position.z = panelLayer(p);
- mesh.userData.face = p.face || null;
- mesh.userData.faceSize = p.face ? { w: box.w, h: box.h } : null;
- mesh.add(new THREE.LineSegments(
- new THREE.EdgesGeometry(geom),
- new THREE.LineBasicMaterial({ color: 0x17140f, transparent: true, opacity: 0.24 })
- ));
- meshes.push(mesh);
- return mesh;
- }
- function clearRoot() {
- if (root) {
- root.traverse(function (o) {
- if (o.geometry) o.geometry.dispose();
- if (o.material) o.material.dispose();
- });
- scene.remove(root);
- }
- // 纹理缓存随几何一起释放(key 含 side,重建后按需重建)
- Object.keys(faceTexCache).forEach(function (k) {
- faceTexCache[k].texture.dispose();
- delete faceTexCache[k];
- });
- root = new THREE.Group();
- scene.add(root);
- meshes = [];
- hinges = [];
- components = [];
- }
- function buildComponent(indices, panels, boxes, adj, prefer) {
- const start = rootIndexFor(indices, panels, boxes, prefer);
- if (start < 0) return null;
- const comp = new THREE.Group();
- const rootGroup = new THREE.Group();
- comp.add(rootGroup);
- const rootBox = boxes[start];
- const rootMesh = makePanelMesh(panels[start], rootBox);
- rootMesh.userData.kind = panels[start].kind;
- rootGroup.add(rootMesh);
- const infos = new Map();
- infos.set(start, { group: rootGroup, origin: boxCenter(rootBox) });
- const visited = new Set([start]);
- const best = new Map();
- const addLinks = function (pi) {
- adj[pi].forEach(function (link) {
- if (visited.has(link.j)) return;
- const cur = best.get(link.j);
- if (!cur || link.overlap > cur.overlap) best.set(link.j, { from: pi, link: link });
- });
- };
- addLinks(start);
- while (visited.size < indices.length) {
- let pick = -1, pickW = -1;
- best.forEach(function (v, k) {
- if (visited.has(k)) return;
- if (v.link.overlap > pickW) { pickW = v.link.overlap; pick = k; }
- });
- if (pick < 0) break;
- const chosen = best.get(pick);
- const parent = infos.get(chosen.from);
- const link = chosen.link;
- const hinge = hingePoint(link.edge);
- const cb = boxes[pick];
- const pivot = new THREE.Group();
- pivot.position.set(hinge.x - parent.origin.x, -(hinge.y - parent.origin.y), 0);
- const n3 = new THREE.Vector3(link.edge.n.x, -link.edge.n.y, 0);
- if (n3.lengthSq() < 0.5) n3.set(0, 1, 0);
- n3.normalize();
- const axis = new THREE.Vector3(0, 0, 1).cross(n3).normalize();
- pivot.userData.axis = axis;
- pivot.userData.angle = Math.PI / 2;
- hinges.push(pivot);
- parent.group.add(pivot);
- const cc = boxCenter(cb);
- const mesh = makePanelMesh(panels[pick], cb);
- mesh.position.x = cc.x - hinge.x;
- mesh.position.y = -(cc.y - hinge.y);
- mesh.userData.kind = panels[pick].kind;
- pivot.add(mesh);
- infos.set(pick, { group: pivot, origin: hinge });
- visited.add(pick);
- best.delete(pick);
- addLinks(pick);
- }
- return { group: comp, root: start };
- }
- function buildFromDieline(panels) {
- const boxes = panels.map(panelBox);
- const adj = buildAdjacency(panels, boxes);
- const seen = new Set();
- const groups = [];
- for (let i = 0; i < panels.length; i += 1) {
- if (seen.has(i)) continue;
- const stack = [i];
- const indices = [];
- seen.add(i);
- while (stack.length) {
- const cur = stack.pop();
- indices.push(cur);
- adj[cur].forEach(function (link) {
- if (seen.has(link.j)) return;
- seen.add(link.j);
- stack.push(link.j);
- });
- }
- groups.push(indices);
- }
- const prefer = 'front';
- const built = [];
- groups.forEach(function (indices) {
- const comp = buildComponent(indices, panels, boxes, adj, prefer);
- if (comp) built.push(comp);
- });
- if (!built.length) return false;
- const main = built[0];
- const mainOrigin = boxCenter(boxes[main.root]);
- built.forEach(function (c) {
- const center = boxCenter(boxes[c.root]);
- c.home = new THREE.Vector3(center.x - mainOrigin.x, -(center.y - mainOrigin.y), 0);
- c.assembled = new THREE.Vector3(0, 0, 0);
- c.assembledScale = 1;
- c.isMain = c === main;
- if (!c.isMain) {
- c.assembled.set(0, 0, -2);
- c.assembledScale = 0.94;
- }
- c.group.position.copy(c.home);
- root.add(c.group);
- components.push(c);
- });
- root.userData.mainOrigin = { x: mainOrigin.x, y: mainOrigin.y };
- return true;
- }
- function buildRigid() {
- const t = material.thickness || 0;
- const W = state.w + t * 2;
- const D = state.d + t * 2;
- const H = state.h + t * 2;
- const inner = state.side === 'inner';
- const defs = [
- { face: 'front', w: W, h: H, pos: [0, 0, D / 2], rot: [0, 0, 0] },
- { face: 'back', w: W, h: H, pos: [0, 0, -D / 2], rot: [0, Math.PI, 0] },
- { face: 'right', w: D, h: H, pos: [W / 2, 0, 0], rot: [0, Math.PI / 2, 0] },
- { face: 'left', w: D, h: H, pos: [-W / 2, 0, 0], rot: [0, -Math.PI / 2, 0] },
- { face: 'top', w: W, h: D, pos: [0, H / 2, 0], rot: [-Math.PI / 2, 0, 0] },
- { face: 'bottom', w: W, h: D, pos: [0, -H / 2, 0], rot: [Math.PI / 2, 0, 0] }
- ];
- defs.forEach(function (def) {
- const geom = new THREE.PlaneGeometry(def.w, def.h);
- const mat = makeMaterial(def.face, { w: def.w, h: def.h }, inner);
- const mesh = new THREE.Mesh(geom, mat);
- mesh.position.set(def.pos[0], def.pos[1], def.pos[2]);
- mesh.rotation.set(def.rot[0], def.rot[1], def.rot[2]);
- mesh.userData.face = def.face;
- mesh.userData.faceSize = { w: def.w, h: def.h };
- root.add(mesh);
- meshes.push(mesh);
- mesh.add(new THREE.LineSegments(
- new THREE.EdgesGeometry(geom),
- new THREE.LineBasicMaterial({ color: 0x17140f, transparent: true, opacity: 0.22 })
- ));
- });
- }
- /* ---- 动效引擎 ---- */
- const anim = { id: null, t0: 0, dur: 0, onEnd: null };
- const animState = { theta: 0, phi: 0, zoom: 1, dx: 0, dy: 0, dz: 0, fold: null };
- const EASE = {
- io: function (t) { return t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2; },
- out: function (t) { return 1 - Math.pow(1 - t, 3); },
- bounce: function (t) {
- const n1 = 7.5625, d1 = 2.75;
- if (t < 1 / d1) return n1 * t * t;
- if (t < 2 / d1) return n1 * (t -= 1.5 / d1) * t + 0.75;
- if (t < 2.5 / d1) return n1 * (t -= 2.25 / d1) * t + 0.9375;
- return n1 * (t -= 2.625 / d1) * t + 0.984375;
- }
- };
- const ANIM_TICKS = {
- fold: function (p) {
- animState.fold = p < 0.5 ? EASE.io(p * 2) : 1 - EASE.io((p - 0.5) * 2);
- },
- spinFlat: function (p) {
- animState.phi = 0.18;
- animState.theta = EASE.io(p) * Math.PI * 2;
- },
- spinTop: function (p) {
- animState.phi = -1.05;
- animState.theta = EASE.io(p) * Math.PI * 2;
- },
- dropSpin: function (p) {
- const k = EASE.out(Math.min(1, p / 0.55));
- animState.dy = (1 - k) * 260;
- animState.theta = (1 - k) * Math.PI * 2.2;
- animState.dz = (1 - k) * -80;
- },
- zoomIn: function (p) {
- animState.zoom = 0.35 + EASE.io(p) * 0.75;
- animState.phi = 0.12;
- },
- dropZoom: function (p) {
- if (p < 0.375) {
- const k = EASE.out(p / 0.375);
- animState.dy = (1 - k) * 300;
- animState.theta = (1 - k) * Math.PI * 2.4;
- } else {
- const k = EASE.io((p - 0.375) / 0.625);
- animState.zoom = 1 + k * 1.1;
- animState.phi = 0.1 + k * 0.2;
- }
- },
- zoomDetail: function (p) {
- animState.zoom = 0.4 + EASE.io(p) * 1.2;
- animState.theta = -0.3 * (1 - p);
- animState.phi = 0.25 - p * 0.12;
- },
- fromLeft: function (p) {
- const k = EASE.out(p);
- animState.dx = (1 - k) * -220;
- animState.theta = (1 - k) * -Math.PI * 1.5;
- animState.phi = 0.3;
- },
- curveIn: function (p) {
- const k = EASE.io(p);
- animState.dz = (1 - k) * -400;
- animState.dx = Math.sin(p * Math.PI) * -120 * (1 - p);
- animState.dy = Math.sin(p * Math.PI) * 90;
- animState.theta = (1 - k) * -0.9;
- },
- foldBounce: function (p) {
- animState.fold = EASE.io(Math.min(1, p / 0.7));
- if (p > 0.7) animState.dy = -(1 - EASE.bounce((p - 0.7) / 0.3)) * 14;
- }
- };
- function tickAnim(now) {
- if (!anim.id) return false;
- const p = Math.min(1, (now - anim.t0) / (anim.dur * 1000));
- Object.assign(animState, { theta: 0, phi: 0, zoom: 1, dx: 0, dy: 0, dz: 0, fold: null });
- if (anim.custom) anim.custom(p);
- else ANIM_TICKS[anim.id](p);
- if (p >= 1) {
- const end = anim.onEnd;
- const wasCustom = anim.custom;
- anim.id = null;
- anim.custom = null;
- if (wasCustom) stopAudioHeart();
- if (end) end();
- }
- return true;
- }
- function applyCamera() {
- if (!camera || !root) return;
- root.updateMatrixWorld(true);
- const bbox = new THREE.Box3().setFromObject(root);
- if (bbox.isEmpty()) return;
- const center = bbox.getCenter(new THREE.Vector3());
- const size = bbox.getSize(new THREE.Vector3());
- const maxDim = Math.max(size.x, size.y, size.z, 1);
- const zoom = orbit.zoom * animState.zoom;
- const r = maxDim * 2.85 / Math.max(0.3, zoom);
- const phi = Math.max(0.15, Math.min(Math.PI - 0.15, orbit.phi + animState.phi));
- const theta = orbit.theta + animState.theta;
- const x = r * Math.sin(phi) * Math.sin(theta);
- const y = r * Math.cos(phi);
- const z = r * Math.sin(phi) * Math.cos(theta);
- camera.position.set(center.x + x + animState.dx, center.y + y + animState.dy, center.z + z + animState.dz);
- camera.lookAt(center.x + animState.dx * 0.2, center.y - maxDim * (opts.mini ? 0.02 : 0.05), center.z);
- }
- function applyFold(t) {
- foldT = Math.max(0, Math.min(1, Number(t) || 0));
- hinges.forEach(function (g) {
- g.setRotationFromAxisAngle(g.userData.axis, g.userData.angle * (1 - foldT));
- });
- components.forEach(function (c) {
- if (c.isMain) return;
- c.group.position.lerpVectors(c.assembled, c.home, foldT);
- const s = c.assembledScale + (1 - c.assembledScale) * foldT;
- c.group.scale.set(s, s, s);
- });
- }
- function applyLines() {
- if (!root) return;
- root.traverse(function (o) { if (o.isLineSegments) o.visible = showLines; });
- }
- /* ---- 交互 ---- */
- function bindPointer() {
- canvas.addEventListener('pointerdown', function (e) {
- if (e.button !== 0) return;
- if (opts.mini && opts.onInteract) opts.onInteract(); // 按下即接管(停掉 CSS 自动播放)
- drag = { x: e.clientX, y: e.clientY, theta: orbit.theta, phi: orbit.phi };
- moved = false;
- canvas.style.cursor = 'grabbing';
- canvas.setPointerCapture(e.pointerId);
- });
- canvas.addEventListener('pointermove', function (e) {
- if (!drag) return;
- const dx = e.clientX - drag.x;
- const dy = e.clientY - drag.y;
- if (Math.abs(dx) + Math.abs(dy) > 3) moved = true;
- orbit.theta = drag.theta - dx * 0.008;
- orbit.phi = Math.max(0.25, Math.min(Math.PI - 0.25, drag.phi - dy * 0.006));
- if (opts.mini && autoRotate && moved && opts.onInteract) {
- autoRotate = false;
- opts.onInteract();
- }
- applyCamera();
- flush(); // 交互即时渲染:拖拽旋转不依赖 rAF 节奏
- });
- canvas.addEventListener('pointerup', function (e) {
- if (!drag) return;
- const wasMoved = moved;
- drag = null;
- canvas.style.cursor = 'grab';
- try { canvas.releasePointerCapture(e.pointerId); } catch (err) {}
- if (wasMoved || !onFacePick) return;
- const rect = canvas.getBoundingClientRect();
- const px = ((e.clientX - rect.left) / rect.width) * 2 - 1;
- const py = -((e.clientY - rect.top) / rect.height) * 2 + 1;
- const rc = new THREE.Raycaster();
- rc.setFromCamera(new THREE.Vector2(px, py), camera);
- const hits = rc.intersectObjects(meshes, false);
- if (hits.length && hits[0].object.userData.face) onFacePick(hits[0].object.userData.face);
- });
- canvas.addEventListener('pointercancel', function () {
- drag = null;
- canvas.style.cursor = 'grab';
- });
- canvas.addEventListener('wheel', function (e) {
- e.preventDefault();
- e.stopPropagation();
- orbit.zoom = Math.max(0.4, Math.min(3.2, orbit.zoom * (e.deltaY > 0 ? 0.92 : 1.08)));
- applyCamera();
- flush();
- }, { passive: false });
- }
- bindPointer();
- let lastFrameAt = performance.now();
- // 虚拟时钟:页面时钟可能被节流冻结(rAF 停、setInterval 降频、performance.now 冻结),
- // 由 Web Worker 心跳(Worker 定时器不受页面可见性节流)持续推进,保证自动播放匀速循环。
- let vNow = performance.now();
- let lastVTick = vNow;
- const AUTO_SPEED = 0.28; // 约 22 秒一圈
- function tickCore() {
- const dt = Math.min(0.12, Math.max(0, vNow - lastVTick)) / 1000;
- lastVTick = vNow;
- try {
- const hasAnim = tickAnim(vNow);
- if (!anim.id && audioDriving) stopAudioHeart();
- if (autoRotate && !anim.id) orbit.theta += AUTO_SPEED * dt;
- if (animState.fold != null) applyFold(animState.fold);
- applyCamera();
- if (renderer && scene && camera) renderer.render(scene, camera);
- } catch (e) {
- // 单帧异常不终止渲染循环
- }
- }
- let framesSinceRaf = 0; // worker 心跳消息计数,rAF 有效帧清零
- let lastRafNow = 0;
- /* 音频线程心跳:AudioContext 回调独立于页面渲染节流,动画播放期提供 ~46fps 稳定帧 */
- let audioCtx = null, audioNode = null, audioDriving = false, lastAudioT = null;
- function startAudioHeart() {
- try {
- const AC = window.AudioContext || window.webkitAudioContext;
- if (!AC) return;
- if (!audioCtx) {
- audioCtx = new AC();
- audioNode = audioCtx.createScriptProcessor(2048, 1, 1);
- audioNode.onaudioprocess = function () {
- if (!audioDriving || !anim.id) return;
- // 用音频硬件时钟精确推进(单调、不受页面渲染节流影响)
- const t = audioCtx.currentTime;
- if (lastAudioT != null) vNow += Math.max(0, Math.min(200, (t - lastAudioT) * 1000));
- lastAudioT = t;
- tickCore();
- };
- const gain = audioCtx.createGain();
- gain.gain.value = 0; // 完全静音,仅用心跳
- audioNode.connect(gain);
- gain.connect(audioCtx.destination);
- }
- lastAudioT = null;
- // 同步判定当前状态;suspended 时异步 resume,成功后回调自动生效
- audioDriving = audioCtx.state === 'running';
- if (audioCtx.state === 'suspended') {
- audioCtx.resume().then(function () {
- audioDriving = audioCtx.state === 'running';
- }).catch(function () { audioDriving = false; });
- }
- } catch (e) { audioDriving = false; }
- }
- function stopAudioHeart() {
- audioDriving = false;
- lastAudioT = null;
- }
- let lastWall = Date.now();
- function animate() {
- raf = requestAnimationFrame(animate);
- const now = performance.now();
- const rafDt = lastRafNow ? now - lastRafNow : 16.7;
- lastRafNow = now;
- const audioActive = audioDriving && audioCtx && audioCtx.state === 'running' && !!anim.id;
- // 虚拟时钟推进源互斥:动画音频心跳运行时由音频帧推进,rAF 帧仅重渲染
- if (audioActive) {
- framesSinceRaf = 0;
- try { renderer.render(scene, camera); lastFrameAt = performance.now(); } catch (e) {}
- return;
- }
- // 墙钟流逝(Date.now 不受渲染节流冻结影响):空闲期掉帧也能补齐进度
- const wallNow = Date.now();
- const wallDt = Math.min(5000, Math.max(0, wallNow - lastWall));
- lastWall = wallNow;
- let step;
- if (rafDt >= 1 && rafDt < 100) step = rafDt; // rAF 时钟正常:按帧间隔
- else if (wallDt > 0) step = wallDt; // 渲染被节流:按墙钟补齐真实流逝
- else step = 16.7; // 兜底
- vNow += step;
- framesSinceRaf = 0;
- tickCore();
- }
- // 心跳自愈:rAF 停止(页面不可见/被节流)时由 Worker 定时器以 12fps 兜底驱动。
- // 判据用消息计数而非页面时钟——节流环境下页面 performance.now 可能冻结。
- try {
- const heartCode = 'setInterval(function(){postMessage(1)},83);';
- const heartUrl = URL.createObjectURL(new Blob([heartCode], { type: 'application/javascript' }));
- const heart = new Worker(heartUrl);
- heart.onmessage = function () {
- framesSinceRaf += 1;
- const audioActive = audioDriving && audioCtx && audioCtx.state === 'running' && !!anim.id;
- // rAF 停止时由 worker 帧接管;音频心跳实际运行时让位(避免双重计时)
- if ((framesSinceRaf > 3 || anim.id) && !audioActive) {
- vNow += 83;
- tickCore();
- }
- };
- if (typeof window !== 'undefined') window.__workerOk = (window.__workerOk || 0) + 1;
- } catch (e) {
- if (typeof window !== 'undefined') window.__workerFail = (window.__workerFail || 0) + 1;
- setInterval(function () {
- framesSinceRaf += 1;
- const audioActive = audioDriving && audioCtx && audioCtx.state === 'running' && !!anim.id;
- if ((framesSinceRaf > 3 || anim.id) && !audioActive) {
- vNow += 83;
- tickCore();
- }
- }, 84);
- }
- /* ---- 对外 API ---- */
- let lastGeomSig = '';
- function render(nextState, nextMaterial, panels) {
- resize();
- state = nextState;
- material = nextMaterial;
- // 结构签名:盒型/尺寸/内外侧/面数变化才重建几何;否则仅刷新面纹理(增量,避免卡顿)
- const sig = [state.structure, state.w, state.d, state.h, state.side, panels ? panels.length : 0].join('|');
- if (sig !== lastGeomSig) {
- lastGeomSig = sig;
- clearRoot();
- const hasParts = panels && panels.length && FOLD_PARTS[state.structure];
- if (hasParts) buildFromDieline(panels);
- if (!meshes.length) buildRigid();
- applyFold(foldT);
- applyLines();
- }
- refreshTextures();
- applyCamera();
- // 状态变化立即上屏(不依赖下一帧)
- try { renderer.render(scene, camera); lastFrameAt = performance.now(); } catch (e) {}
- }
- function flush() {
- try { renderer.render(scene, camera); lastFrameAt = performance.now(); } catch (e) {}
- }
- return {
- render: render,
- _dbg: {
- get scene() { return scene; },
- get camera() { return camera; },
- get renderer() { return renderer; },
- get meshes() { return meshes; },
- get hinges() { return hinges; },
- get root() { return root; },
- get orbit() { return orbit; },
- get autoFlag() { return autoRotate; }
- },
- setFold: function (t) { applyFold(t); flush(); },
- setAutoRotate: function (v) { autoRotate = !!v; },
- isAutoRotate: function () { return !!autoRotate; },
- setZoom: function (z) { orbit.zoom = Math.max(0.4, Math.min(3.2, Number(z) || 1)); applyCamera(); flush(); },
- setLines: function (v) { showLines = v !== false; applyLines(); flush(); },
- resetView: function () {
- orbit.theta = orbitHome.theta;
- orbit.phi = orbitHome.phi;
- orbit.zoom = orbitHome.zoom;
- anim.id = null;
- applyCamera();
- flush();
- },
- playAnim: function (id, dur, onEnd) {
- const def = (window.PL.boxlib && window.PL.boxlib.ANIMS.find(function (a) { return a.id === id; })) || { dur: 4 };
- anim.id = id;
- anim.custom = null;
- anim.dur = dur || def.dur;
- anim.t0 = vNow; // 与 tickAnim 同一虚拟时钟,步进连续(页面时钟可能冻结不可用)
- anim.onEnd = onEnd || null;
- startAudioHeart();
- },
- // 通用补间(音频线程心跳驱动,冻结环境流畅):onUpdate 接收 0~1 进度
- tween: function (dur, onUpdate, onDone) {
- anim.id = '__tween';
- anim.custom = onUpdate;
- anim.dur = dur;
- anim.t0 = vNow;
- anim.onEnd = onDone || null;
- startAudioHeart();
- },
- stopAnim: function () { anim.id = null; anim.custom = null; stopAudioHeart(); },
- animating: function () { return !!anim.id; },
- snapshot: function (w, h2, transparent) {
- const keepW = el.clientWidth, keepH = el.clientHeight, keepZoom = orbit.zoom;
- if (w && h2) {
- renderer.setPixelRatio(1);
- renderer.setSize(w, h2, false);
- camera.aspect = w / h2;
- camera.updateProjectionMatrix();
- }
- renderer.render(scene, camera);
- let url;
- if (transparent) {
- // 用离屏合成保留透明通道
- const src = canvas;
- const c = document.createElement('canvas');
- c.width = src.width; c.height = src.height;
- const ctx = c.getContext('2d');
- ctx.drawImage(src, 0, 0);
- url = c.toDataURL('image/png');
- } else {
- url = canvas.toDataURL('image/png');
- }
- if (w && h2) {
- renderer.setPixelRatio(opts.mini ? 1 : Math.min(window.devicePixelRatio || 1, 2));
- renderer.setSize(keepW, keepH, false);
- camera.aspect = keepW / keepH;
- camera.updateProjectionMatrix();
- }
- return url;
- },
- dispose: function () {
- cancelAnimationFrame(raf);
- disposeFns.forEach(function (f) { f(); });
- clearRoot();
- renderer.dispose();
- if (canvas.parentNode) canvas.parentNode.removeChild(canvas);
- },
- ready: function () { return !!renderer; }
- };
- }
- window.PL = window.PL || {};
- window.PL.box3d = { create: create };
- })();
|