| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424 |
- /**
- * pouch3d.js — 袋子 3D 预览(Three.js + FBX 真实模型)
- * 两个模型:pouch-closed.fbx(自立袋族) / mailer-open.fbx(邮封袋,开启态)
- * 每个模型单网格双材质(FRONT/BACK 各占 0-1 UV)→ 正/背设计稿各渲染一张贴图。
- * 交互:拖拽旋转 / 滚轮缩放;渲染循环带 rAF+定时器兜底。
- */
- (function () {
- const THREE = window.THREE;
- if (!THREE) return;
- const MODELS = {
- mailer: { url: 'assets/models/mailer-open.fbx' },
- pouch: { url: 'assets/models/pouch-closed.fbx' }
- };
- const SHAPE_MAP = { mailer: 'mailer', pouch: 'pouch', open: 'mailer', closed: 'pouch' };
- const TARGET_H = 3.4; // 归一化高度(世界单位)
- function fontReady() { return true; }
- function create(el, opts) {
- opts = opts || {};
- let renderer = null, scene = null, camera = null, modelGroup = null, pivot = null, shadowMesh = null;
- let raf = null, drag = null, container = el;
- const orbit = { theta: -24, phi: 0, zoom: 1 };
- const orbitHome = { theta: -24, phi: 0, zoom: 1 };
- let materials = { FRONT: null, BACK: null };
- let faceAspect = { FRONT: 0.68, BACK: 0.68 };
- let texCanvas = { FRONT: null, BACK: null };
- let texTexture = { FRONT: null, BACK: null };
- let currentKey = null; // 已加载模型的映射键(pouch/mailer)
- let loadingKey = null; // 正在加载的映射键
- let pendingDone = null; // 加载期间到来的回调(只保留最新)
- let disposed = false;
- const onReady = opts.onReady || null;
- renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });
- renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
- renderer.outputEncoding = THREE.sRGBEncoding;
- renderer.setClearColor(0x000000, 0);
- renderer.physicallyCorrectLights = false;
- const canvas = renderer.domElement;
- canvas.className = 'pouch-gl-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);
- scene = new THREE.Scene();
- camera = new THREE.PerspectiveCamera(28, 1, 0.01, 100);
- // 低强度布光:保证贴图文字清晰(总曝光 ≈1.0)
- scene.add(new THREE.HemisphereLight(0xffffff, 0x9a8f7d, 0.52));
- const key = new THREE.DirectionalLight(0xffffff, 0.5);
- key.position.set(-2.6, 4.5, 5.5);
- scene.add(key);
- const fill = new THREE.DirectionalLight(0xffffff, 0.12);
- fill.position.set(5, -2, 4);
- scene.add(fill);
- const rim = new THREE.DirectionalLight(0xfff4e0, 0.14);
- rim.position.set(2, 3, -6);
- scene.add(rim);
- pivot = new THREE.Group();
- scene.add(pivot);
- function resize() {
- const w = Math.max(1, el.clientWidth);
- const h = Math.max(1, el.clientHeight);
- renderer.setSize(w, h, false);
- camera.aspect = w / h;
- camera.updateProjectionMatrix();
- }
- resize();
- if (window.ResizeObserver) new ResizeObserver(resize).observe(el);
- /* ---------- 模型加载 ---------- */
- function modelUrl(shapeKey) {
- const key = SHAPE_MAP[shapeKey] || 'pouch';
- return MODELS[key].url;
- }
- function clearModel() {
- if (modelGroup) {
- modelGroup.traverse(function (o) {
- if (o.geometry) o.geometry.dispose();
- });
- pivot.remove(modelGroup);
- modelGroup = null;
- }
- materials = { FRONT: null, BACK: null };
- if (shadowMesh) { pivot.remove(shadowMesh); shadowMesh = null; }
- }
- function applyOrbit() {
- if (!modelGroup) return;
- // 模型自转,相机固定在正前略俯视位(避免角度叠加导致镜头穿模)
- modelGroup.rotation.y = orbit.theta * Math.PI / 180;
- modelGroup.updateMatrixWorld(true);
- const box = new THREE.Box3().setFromObject(modelGroup);
- const center = box.getCenter(new THREE.Vector3());
- const size = box.getSize(new THREE.Vector3());
- // 按竖直 FOV 精确取距:保证袋高 1.26 倍完整可见
- const fovRad = camera.fov * Math.PI / 180;
- const r = (TARGET_H * 1.26 / (2 * Math.tan(fovRad / 2))) / orbit.zoom;
- camera.position.set(center.x, center.y + size.y * 0.06, center.z + r);
- camera.lookAt(center.x, center.y, center.z);
- }
- function loadModel(mappedKey, done) {
- const url = MODELS[mappedKey].url;
- fetch(url).then(function (r) { return r.arrayBuffer(); }).then(function (buf) {
- const loader = new THREE.FBXLoader();
- const group = loader.parse(buf, '');
- clearModel();
- modelGroup = new THREE.Group();
- modelGroup.add(group);
- // 归一化:等比缩放到 TARGET_H,底部落地、水平居中
- group.updateMatrixWorld(true);
- const box = new THREE.Box3().setFromObject(group);
- const size = box.getSize(new THREE.Vector3());
- const scale = TARGET_H / Math.max(0.001, size.y);
- group.scale.setScalar(scale);
- group.updateMatrixWorld(true);
- const box2 = new THREE.Box3().setFromObject(group);
- const c = box2.getCenter(new THREE.Vector3());
- group.position.set(-c.x, -box2.min.y, -c.z);
- // 材质替换:按名称 FRONT/BACK 建占位材质(贴图由 applyDesign 填充)
- const seen = {};
- group.traverse(function (o) {
- if (!o.isMesh) return;
- o.frustumCulled = false;
- const mats = Array.isArray(o.material) ? o.material : [o.material];
- const next = mats.map(function (m) {
- const isFront = /FRONT/i.test(m.name) || /FRONT/i.test(o.name);
- const side = isFront ? 'FRONT' : 'BACK';
- if (!seen[side]) {
- seen[side] = new THREE.MeshStandardMaterial({
- color: new THREE.Color('#ffffff'),
- roughness: 0.55,
- metalness: 0.0,
- side: THREE.DoubleSide
- });
- }
- return seen[side];
- });
- o.material = Array.isArray(o.material) ? next : next[0];
- });
- materials = seen;
- // 每面世界宽高比(按材质分组的顶点世界包围盒)
- ['FRONT', 'BACK'].forEach(function (side) {
- let minX = 1e9, maxX = -1e9, minY = 1e9, maxY = -1e9, hit = false;
- group.traverse(function (o) {
- if (!o.isMesh) return;
- const g = o.geometry;
- const uv = g.attributes.uv;
- const pos = g.attributes.position;
- const mats = Array.isArray(o.material) ? o.material : [o.material];
- const indexed = !!g.index;
- const groups = (g.groups && g.groups.length) ? g.groups : [{ start: 0, count: indexed ? g.index.count : pos.count, materialIndex: 0 }];
- groups.forEach(function (gr) {
- const m = mats[gr.materialIndex] || mats[0];
- const isFront = /FRONT/i.test(m.name);
- if ((side === 'FRONT') !== isFront) return;
- if (side === 'FRONT' ? !isFront : isFront) return;
- const end = gr.count;
- const step = Math.max(1, Math.floor(end / 4000)); // 采样即可
- for (let i = 0; i < end; i += step) {
- const vi = indexed ? g.index.getX(gr.start + i) : gr.start + i;
- const v = new THREE.Vector3().fromBufferAttribute(pos, vi).applyMatrix4(o.matrixWorld);
- if (v.x < minX) minX = v.x; if (v.x > maxX) maxX = v.x;
- if (v.y < minY) minY = v.y; if (v.y > maxY) maxY = v.y;
- hit = true;
- }
- });
- });
- if (hit) faceAspect[side] = Math.max(0.2, (maxX - minX) / Math.max(0.001, maxY - minY));
- });
- // 接触阴影(贴地柔影)
- const shadowC = document.createElement('canvas');
- shadowC.width = shadowC.height = 256;
- const sctx = shadowC.getContext('2d');
- const grd = sctx.createRadialGradient(128, 128, 8, 128, 128, 126);
- grd.addColorStop(0, 'rgba(30,22,10,0.42)');
- grd.addColorStop(0.55, 'rgba(30,22,10,0.20)');
- grd.addColorStop(1, 'rgba(30,22,10,0)');
- sctx.fillStyle = grd;
- sctx.fillRect(0, 0, 256, 256);
- const shadowTex = new THREE.CanvasTexture(shadowC);
- shadowMesh = new THREE.Mesh(
- new THREE.PlaneGeometry(size.x * scale * 2.6, size.z * scale * 5.2),
- new THREE.MeshBasicMaterial({ map: shadowTex, transparent: true, depthWrite: false })
- );
- shadowMesh.rotation.x = -Math.PI / 2;
- shadowMesh.position.y = 0.005;
- pivot.add(shadowMesh);
- pivot.add(modelGroup);
- currentKey = mappedKey;
- loadingKey = null;
- applyOrbit();
- if (done) done();
- if (pendingDone) { var d = pendingDone; pendingDone = null; d(); }
- if (onReady) onReady();
- }).catch(function (e) {
- window.__pouchGLerr = String(e && e.stack || e).slice(0, 400);
- if (opts.onLoadError) opts.onLoadError(e);
- });
- if (opts.onLoadLog) opts.onLoadLog(url);
- }
- /* ---------- 设计贴图 ---------- */
- function svgToImage(svgStr, cw, ch) {
- // 关键:SVG 带百分比尺寸作为 Image 加载时 Chromium 不渲染 <text>,
- // 必须注入显式像素尺寸;slice 改 meet 防裁切(画布底色已同设计底色)
- const fixed = svgStr
- .replace(/width="100%"\s+height="100%"/, 'width="' + cw + '" height="' + ch + '"')
- .replace(/preserveAspectRatio="xMidYMid slice"/, 'preserveAspectRatio="xMidYMid meet"');
- return new Promise(function (res, rej) {
- const img = new Image();
- img.onload = function () { res(img); };
- img.onerror = rej;
- img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(fixed);
- });
- }
- function drawTextElement(ctx, el, px, W, H) {
- // 文本用 canvas 原生绘制(SVG-as-Image 在部分环境不渲染 viewBox 内文本)
- const R = window.PL.render;
- if (!R || el.hidden) return;
- const size = (el.size || 12) * px;
- const lh = (el.lineHeight || 1.25) * size;
- const lines = R.textLines(el);
- const boxW = (el.w == null ? 60 : el.w) * px;
- const x0 = el.x * px, y0 = el.y * px;
- const anchor = el.align === 'center' ? 'center' : el.align === 'right' ? 'right' : 'left';
- const cx = anchor === 'center' ? x0 + boxW / 2 : anchor === 'right' ? x0 + boxW : x0;
- ctx.save();
- ctx.globalAlpha = el.opacity == null ? 1 : el.opacity;
- ctx.textAlign = anchor;
- ctx.textBaseline = 'alphabetic';
- const fontStackF = R.fontStack ? R.fontStack(el.font) : 'sans-serif';
- ctx.font = (el.italic ? 'italic ' : '') + (el.weight || 400) + ' ' + size + 'px ' + fontStackF;
- if ('letterSpacing' in ctx) ctx.letterSpacing = ((el.spacing || 0) * size) + 'px';
- const fill = el.color === 'none' ? null : (el.color || '#17140f');
- const hasStroke = el.stroke && el.stroke !== 'none';
- if (hasStroke) {
- ctx.strokeStyle = el.stroke;
- ctx.lineWidth = Math.max(el.strokeWidth || 0, (el.size || 12) * 0.045) * px;
- ctx.lineJoin = 'round';
- }
- lines.forEach(function (line, i) {
- const y = y0 + size * 0.83 + i * lh;
- if (fill) ctx.fillText(line, cx, y);
- if (hasStroke) ctx.strokeText(line, cx, y);
- });
- if ('letterSpacing' in ctx) ctx.letterSpacing = '0px';
- ctx.restore();
- }
- function drawSide(side, color, svgStr, designW, designH, bg, design) {
- // 画布比例 = 设计稿比例(UV 拉伸到模型面,印刷区域满幅)
- const designAspect = designW / Math.max(1, designH);
- const cw = 1400;
- const ch = Math.max(64, Math.round(cw / designAspect));
- let entry = texCanvas[side];
- if (!entry || entry.canvas.width !== cw || entry.canvas.height !== ch) {
- 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 };
- texCanvas[side] = entry;
- texTexture[side] = texture;
- }
- const ctx = entry.ctx;
- ctx.setTransform(1, 0, 0, 1, 0, 0);
- // 画布底 = 设计稿背景色(无底色时用袋色),保证整面无纸色边
- ctx.fillStyle = bg || color || '#e8e2d4';
- ctx.fillRect(0, 0, cw, ch);
- if (svgStr) {
- return svgToImage(svgStr, cw, ch).then(function (img) {
- try { ctx.drawImage(img, 0, 0, cw, ch); } catch (e) { window.__pouchGLerr3 = 'draw: ' + String(e); }
- // 文本:canvas 原生绘制(规避 SVG 文本渲染缺陷)
- if (design && design.elements) {
- const px = cw / Math.max(1, designW);
- design.elements.forEach(function (el) {
- if (el.type === 'text') drawTextElement(ctx, el, px, designW, designH);
- });
- }
- entry.texture.needsUpdate = true;
- assignTexture(side);
- }).catch(function (e) {
- window.__pouchGLerr3 = window.__pouchGLerr3 || ('img: ' + String(e).slice(0, 200));
- });
- }
- entry.texture.needsUpdate = true;
- assignTexture(side);
- return Promise.resolve();
- }
- function assignTexture(side) {
- const tex = texTexture[side];
- if (!tex || !materials[side]) return;
- if (materials[side].map !== tex) {
- materials[side].map = tex;
- materials[side].needsUpdate = true;
- }
- }
- function applyDesign(spec) {
- // spec: { color, frontSVG, backSVG, W, H }
- const color = spec.color || '#e8e2d4';
- if (materials.FRONT) materials.FRONT.color.set('#ffffff');
- if (materials.BACK) materials.BACK.color.set('#ffffff');
- function svgOf(design, W, H) {
- const noText = Object.assign({}, design, { elements: (design.elements || []).filter(function (e) { return e.type !== 'text'; }) });
- return window.PL.render.designSVG(noText, W, H);
- }
- const fd = spec.frontDesign || { elements: [] };
- const bd = spec.backDesign || { elements: [] };
- const jobs = [
- drawSide('FRONT', color, svgOf(fd, spec.W || 140, spec.H || 210), spec.W || 140, spec.H || 210, spec.frontBg, fd),
- drawSide('BACK', color, svgOf(bd, spec.W || 140, spec.H || 210), spec.W || 140, spec.H || 210, spec.backBg, bd)
- ];
- return Promise.all(jobs).catch(function (e) {
- window.__pouchGLerr3 = String(e && e.stack || e).slice(0, 400);
- });
- }
- /* ---------- 交互 ---------- */
- function bindPointer() {
- canvas.addEventListener('pointerdown', function (e) {
- if (e.button !== 0) return;
- drag = { x: e.clientX, y: e.clientY, theta: orbit.theta };
- moved = false;
- canvas.style.cursor = 'grabbing';
- canvas.setPointerCapture(e.pointerId);
- });
- let moved = false;
- 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.4;
- applyOrbit();
- flush();
- });
- canvas.addEventListener('pointerup', function (e) {
- if (!drag) return;
- drag = null;
- canvas.style.cursor = 'grab';
- try { canvas.releasePointerCapture(e.pointerId); } catch (err) {}
- });
- canvas.addEventListener('pointercancel', function () { drag = null; canvas.style.cursor = 'grab'; });
- // 兜底:捕获丢失/指针离开画布/在窗口任意处抬起,都强制结束拖拽
- window.addEventListener('pointerup', function () {
- if (drag) { drag = null; canvas.style.cursor = 'grab'; }
- });
- canvas.addEventListener('pointerleave', function () {
- if (drag) { drag = null; canvas.style.cursor = 'grab'; }
- });
- canvas.addEventListener('wheel', function (e) {
- e.preventDefault();
- e.stopPropagation();
- orbit.zoom = Math.max(0.55, Math.min(2.6, orbit.zoom * (e.deltaY > 0 ? 0.92 : 1.08)));
- applyOrbit();
- flush();
- }, { passive: false });
- }
- bindPointer();
- function flush() {
- try { renderer.render(scene, camera); } catch (e) {}
- }
- let lastFrameAt = 0;
- function tick() {
- lastFrameAt = performance.now();
- try { renderer.render(scene, camera); } catch (e) {}
- }
- function animate() {
- raf = requestAnimationFrame(animate);
- tick();
- }
- setInterval(function () {
- if (performance.now() - lastFrameAt > 320) tick();
- }, 84);
- animate();
- /* ---------- 对外 API ---------- */
- return {
- load: function (shapeKey, done) {
- const mapped = SHAPE_MAP[shapeKey] || 'pouch';
- if (currentKey === mapped) { if (done) done(); return; }
- if (loadingKey === mapped) { pendingDone = done || null; return; } // 同模型加载中:合并回调
- loadModel(mapped, done);
- },
- applyDesign: applyDesign,
- setRotation: function (deg) {
- orbit.theta = Number(deg) || 0;
- applyOrbit();
- flush();
- },
- getRotation: function () { return orbit.theta; },
- setZoom: function (z) { orbit.zoom = Math.max(0.55, Math.min(2.6, Number(z) || 1)); applyOrbit(); flush(); },
- resetView: function () { orbit.theta = orbitHome.theta; orbit.zoom = orbitHome.zoom; applyOrbit(); flush(); },
- snapshot: function () { renderer.render(scene, camera); return canvas.toDataURL('image/png'); },
- dispose: function () {
- disposed = true;
- cancelAnimationFrame(raf);
- clearModel();
- renderer.dispose();
- if (canvas.parentNode) canvas.parentNode.removeChild(canvas);
- },
- ready: function () { return !disposed && !!renderer; }
- };
- }
- window.PL = window.PL || {};
- window.PL.pouch3d = { create: create };
- })();
|