pouch3d.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. /**
  2. * pouch3d.js — 袋子 3D 预览(Three.js + FBX 真实模型)
  3. * 两个模型:pouch-closed.fbx(自立袋族) / mailer-open.fbx(邮封袋,开启态)
  4. * 每个模型单网格双材质(FRONT/BACK 各占 0-1 UV)→ 正/背设计稿各渲染一张贴图。
  5. * 交互:拖拽旋转 / 滚轮缩放;渲染循环带 rAF+定时器兜底。
  6. */
  7. (function () {
  8. const THREE = window.THREE;
  9. if (!THREE) return;
  10. const MODELS = {
  11. mailer: { url: 'assets/models/mailer-open.fbx' },
  12. pouch: { url: 'assets/models/pouch-closed.fbx' }
  13. };
  14. const SHAPE_MAP = { mailer: 'mailer', pouch: 'pouch', open: 'mailer', closed: 'pouch' };
  15. const TARGET_H = 3.4; // 归一化高度(世界单位)
  16. function fontReady() { return true; }
  17. function create(el, opts) {
  18. opts = opts || {};
  19. let renderer = null, scene = null, camera = null, modelGroup = null, pivot = null, shadowMesh = null;
  20. let raf = null, drag = null, container = el;
  21. const orbit = { theta: -24, phi: 0, zoom: 1 };
  22. const orbitHome = { theta: -24, phi: 0, zoom: 1 };
  23. let materials = { FRONT: null, BACK: null };
  24. let faceAspect = { FRONT: 0.68, BACK: 0.68 };
  25. let texCanvas = { FRONT: null, BACK: null };
  26. let texTexture = { FRONT: null, BACK: null };
  27. let currentKey = null; // 已加载模型的映射键(pouch/mailer)
  28. let loadingKey = null; // 正在加载的映射键
  29. let pendingDone = null; // 加载期间到来的回调(只保留最新)
  30. let disposed = false;
  31. const onReady = opts.onReady || null;
  32. renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });
  33. renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
  34. renderer.outputEncoding = THREE.sRGBEncoding;
  35. renderer.setClearColor(0x000000, 0);
  36. renderer.physicallyCorrectLights = false;
  37. const canvas = renderer.domElement;
  38. canvas.className = 'pouch-gl-canvas';
  39. canvas.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;display:block;z-index:2;touch-action:none;cursor:grab;';
  40. el.appendChild(canvas);
  41. scene = new THREE.Scene();
  42. camera = new THREE.PerspectiveCamera(28, 1, 0.01, 100);
  43. // 低强度布光:保证贴图文字清晰(总曝光 ≈1.0)
  44. scene.add(new THREE.HemisphereLight(0xffffff, 0x9a8f7d, 0.52));
  45. const key = new THREE.DirectionalLight(0xffffff, 0.5);
  46. key.position.set(-2.6, 4.5, 5.5);
  47. scene.add(key);
  48. const fill = new THREE.DirectionalLight(0xffffff, 0.12);
  49. fill.position.set(5, -2, 4);
  50. scene.add(fill);
  51. const rim = new THREE.DirectionalLight(0xfff4e0, 0.14);
  52. rim.position.set(2, 3, -6);
  53. scene.add(rim);
  54. pivot = new THREE.Group();
  55. scene.add(pivot);
  56. function resize() {
  57. const w = Math.max(1, el.clientWidth);
  58. const h = Math.max(1, el.clientHeight);
  59. renderer.setSize(w, h, false);
  60. camera.aspect = w / h;
  61. camera.updateProjectionMatrix();
  62. }
  63. resize();
  64. if (window.ResizeObserver) new ResizeObserver(resize).observe(el);
  65. /* ---------- 模型加载 ---------- */
  66. function modelUrl(shapeKey) {
  67. const key = SHAPE_MAP[shapeKey] || 'pouch';
  68. return MODELS[key].url;
  69. }
  70. function clearModel() {
  71. if (modelGroup) {
  72. modelGroup.traverse(function (o) {
  73. if (o.geometry) o.geometry.dispose();
  74. });
  75. pivot.remove(modelGroup);
  76. modelGroup = null;
  77. }
  78. materials = { FRONT: null, BACK: null };
  79. if (shadowMesh) { pivot.remove(shadowMesh); shadowMesh = null; }
  80. }
  81. function applyOrbit() {
  82. if (!modelGroup) return;
  83. // 模型自转,相机固定在正前略俯视位(避免角度叠加导致镜头穿模)
  84. modelGroup.rotation.y = orbit.theta * Math.PI / 180;
  85. modelGroup.updateMatrixWorld(true);
  86. const box = new THREE.Box3().setFromObject(modelGroup);
  87. const center = box.getCenter(new THREE.Vector3());
  88. const size = box.getSize(new THREE.Vector3());
  89. // 按竖直 FOV 精确取距:保证袋高 1.26 倍完整可见
  90. const fovRad = camera.fov * Math.PI / 180;
  91. const r = (TARGET_H * 1.26 / (2 * Math.tan(fovRad / 2))) / orbit.zoom;
  92. camera.position.set(center.x, center.y + size.y * 0.06, center.z + r);
  93. camera.lookAt(center.x, center.y, center.z);
  94. }
  95. function loadModel(mappedKey, done) {
  96. const url = MODELS[mappedKey].url;
  97. fetch(url).then(function (r) { return r.arrayBuffer(); }).then(function (buf) {
  98. const loader = new THREE.FBXLoader();
  99. const group = loader.parse(buf, '');
  100. clearModel();
  101. modelGroup = new THREE.Group();
  102. modelGroup.add(group);
  103. // 归一化:等比缩放到 TARGET_H,底部落地、水平居中
  104. group.updateMatrixWorld(true);
  105. const box = new THREE.Box3().setFromObject(group);
  106. const size = box.getSize(new THREE.Vector3());
  107. const scale = TARGET_H / Math.max(0.001, size.y);
  108. group.scale.setScalar(scale);
  109. group.updateMatrixWorld(true);
  110. const box2 = new THREE.Box3().setFromObject(group);
  111. const c = box2.getCenter(new THREE.Vector3());
  112. group.position.set(-c.x, -box2.min.y, -c.z);
  113. // 材质替换:按名称 FRONT/BACK 建占位材质(贴图由 applyDesign 填充)
  114. const seen = {};
  115. group.traverse(function (o) {
  116. if (!o.isMesh) return;
  117. o.frustumCulled = false;
  118. const mats = Array.isArray(o.material) ? o.material : [o.material];
  119. const next = mats.map(function (m) {
  120. const isFront = /FRONT/i.test(m.name) || /FRONT/i.test(o.name);
  121. const side = isFront ? 'FRONT' : 'BACK';
  122. if (!seen[side]) {
  123. seen[side] = new THREE.MeshStandardMaterial({
  124. color: new THREE.Color('#ffffff'),
  125. roughness: 0.55,
  126. metalness: 0.0,
  127. side: THREE.DoubleSide
  128. });
  129. }
  130. return seen[side];
  131. });
  132. o.material = Array.isArray(o.material) ? next : next[0];
  133. });
  134. materials = seen;
  135. // 每面世界宽高比(按材质分组的顶点世界包围盒)
  136. ['FRONT', 'BACK'].forEach(function (side) {
  137. let minX = 1e9, maxX = -1e9, minY = 1e9, maxY = -1e9, hit = false;
  138. group.traverse(function (o) {
  139. if (!o.isMesh) return;
  140. const g = o.geometry;
  141. const uv = g.attributes.uv;
  142. const pos = g.attributes.position;
  143. const mats = Array.isArray(o.material) ? o.material : [o.material];
  144. const indexed = !!g.index;
  145. const groups = (g.groups && g.groups.length) ? g.groups : [{ start: 0, count: indexed ? g.index.count : pos.count, materialIndex: 0 }];
  146. groups.forEach(function (gr) {
  147. const m = mats[gr.materialIndex] || mats[0];
  148. const isFront = /FRONT/i.test(m.name);
  149. if ((side === 'FRONT') !== isFront) return;
  150. if (side === 'FRONT' ? !isFront : isFront) return;
  151. const end = gr.count;
  152. const step = Math.max(1, Math.floor(end / 4000)); // 采样即可
  153. for (let i = 0; i < end; i += step) {
  154. const vi = indexed ? g.index.getX(gr.start + i) : gr.start + i;
  155. const v = new THREE.Vector3().fromBufferAttribute(pos, vi).applyMatrix4(o.matrixWorld);
  156. if (v.x < minX) minX = v.x; if (v.x > maxX) maxX = v.x;
  157. if (v.y < minY) minY = v.y; if (v.y > maxY) maxY = v.y;
  158. hit = true;
  159. }
  160. });
  161. });
  162. if (hit) faceAspect[side] = Math.max(0.2, (maxX - minX) / Math.max(0.001, maxY - minY));
  163. });
  164. // 接触阴影(贴地柔影)
  165. const shadowC = document.createElement('canvas');
  166. shadowC.width = shadowC.height = 256;
  167. const sctx = shadowC.getContext('2d');
  168. const grd = sctx.createRadialGradient(128, 128, 8, 128, 128, 126);
  169. grd.addColorStop(0, 'rgba(30,22,10,0.42)');
  170. grd.addColorStop(0.55, 'rgba(30,22,10,0.20)');
  171. grd.addColorStop(1, 'rgba(30,22,10,0)');
  172. sctx.fillStyle = grd;
  173. sctx.fillRect(0, 0, 256, 256);
  174. const shadowTex = new THREE.CanvasTexture(shadowC);
  175. shadowMesh = new THREE.Mesh(
  176. new THREE.PlaneGeometry(size.x * scale * 2.6, size.z * scale * 5.2),
  177. new THREE.MeshBasicMaterial({ map: shadowTex, transparent: true, depthWrite: false })
  178. );
  179. shadowMesh.rotation.x = -Math.PI / 2;
  180. shadowMesh.position.y = 0.005;
  181. pivot.add(shadowMesh);
  182. pivot.add(modelGroup);
  183. currentKey = mappedKey;
  184. loadingKey = null;
  185. applyOrbit();
  186. if (done) done();
  187. if (pendingDone) { var d = pendingDone; pendingDone = null; d(); }
  188. if (onReady) onReady();
  189. }).catch(function (e) {
  190. window.__pouchGLerr = String(e && e.stack || e).slice(0, 400);
  191. if (opts.onLoadError) opts.onLoadError(e);
  192. });
  193. if (opts.onLoadLog) opts.onLoadLog(url);
  194. }
  195. /* ---------- 设计贴图 ---------- */
  196. function svgToImage(svgStr, cw, ch) {
  197. // 关键:SVG 带百分比尺寸作为 Image 加载时 Chromium 不渲染 <text>,
  198. // 必须注入显式像素尺寸;slice 改 meet 防裁切(画布底色已同设计底色)
  199. const fixed = svgStr
  200. .replace(/width="100%"\s+height="100%"/, 'width="' + cw + '" height="' + ch + '"')
  201. .replace(/preserveAspectRatio="xMidYMid slice"/, 'preserveAspectRatio="xMidYMid meet"');
  202. return new Promise(function (res, rej) {
  203. const img = new Image();
  204. img.onload = function () { res(img); };
  205. img.onerror = rej;
  206. img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(fixed);
  207. });
  208. }
  209. function drawTextElement(ctx, el, px, W, H) {
  210. // 文本用 canvas 原生绘制(SVG-as-Image 在部分环境不渲染 viewBox 内文本)
  211. const R = window.PL.render;
  212. if (!R || el.hidden) return;
  213. const size = (el.size || 12) * px;
  214. const lh = (el.lineHeight || 1.25) * size;
  215. const lines = R.textLines(el);
  216. const boxW = (el.w == null ? 60 : el.w) * px;
  217. const x0 = el.x * px, y0 = el.y * px;
  218. const anchor = el.align === 'center' ? 'center' : el.align === 'right' ? 'right' : 'left';
  219. const cx = anchor === 'center' ? x0 + boxW / 2 : anchor === 'right' ? x0 + boxW : x0;
  220. ctx.save();
  221. ctx.globalAlpha = el.opacity == null ? 1 : el.opacity;
  222. ctx.textAlign = anchor;
  223. ctx.textBaseline = 'alphabetic';
  224. const fontStackF = R.fontStack ? R.fontStack(el.font) : 'sans-serif';
  225. ctx.font = (el.italic ? 'italic ' : '') + (el.weight || 400) + ' ' + size + 'px ' + fontStackF;
  226. if ('letterSpacing' in ctx) ctx.letterSpacing = ((el.spacing || 0) * size) + 'px';
  227. const fill = el.color === 'none' ? null : (el.color || '#17140f');
  228. const hasStroke = el.stroke && el.stroke !== 'none';
  229. if (hasStroke) {
  230. ctx.strokeStyle = el.stroke;
  231. ctx.lineWidth = Math.max(el.strokeWidth || 0, (el.size || 12) * 0.045) * px;
  232. ctx.lineJoin = 'round';
  233. }
  234. lines.forEach(function (line, i) {
  235. const y = y0 + size * 0.83 + i * lh;
  236. if (fill) ctx.fillText(line, cx, y);
  237. if (hasStroke) ctx.strokeText(line, cx, y);
  238. });
  239. if ('letterSpacing' in ctx) ctx.letterSpacing = '0px';
  240. ctx.restore();
  241. }
  242. function drawSide(side, color, svgStr, designW, designH, bg, design) {
  243. // 画布比例 = 设计稿比例(UV 拉伸到模型面,印刷区域满幅)
  244. const designAspect = designW / Math.max(1, designH);
  245. const cw = 1400;
  246. const ch = Math.max(64, Math.round(cw / designAspect));
  247. let entry = texCanvas[side];
  248. if (!entry || entry.canvas.width !== cw || entry.canvas.height !== ch) {
  249. const c = document.createElement('canvas');
  250. c.width = cw; c.height = ch;
  251. const texture = new THREE.CanvasTexture(c);
  252. texture.encoding = THREE.sRGBEncoding;
  253. texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
  254. entry = { canvas: c, ctx: c.getContext('2d'), texture: texture };
  255. texCanvas[side] = entry;
  256. texTexture[side] = texture;
  257. }
  258. const ctx = entry.ctx;
  259. ctx.setTransform(1, 0, 0, 1, 0, 0);
  260. // 画布底 = 设计稿背景色(无底色时用袋色),保证整面无纸色边
  261. ctx.fillStyle = bg || color || '#e8e2d4';
  262. ctx.fillRect(0, 0, cw, ch);
  263. if (svgStr) {
  264. return svgToImage(svgStr, cw, ch).then(function (img) {
  265. try { ctx.drawImage(img, 0, 0, cw, ch); } catch (e) { window.__pouchGLerr3 = 'draw: ' + String(e); }
  266. // 文本:canvas 原生绘制(规避 SVG 文本渲染缺陷)
  267. if (design && design.elements) {
  268. const px = cw / Math.max(1, designW);
  269. design.elements.forEach(function (el) {
  270. if (el.type === 'text') drawTextElement(ctx, el, px, designW, designH);
  271. });
  272. }
  273. entry.texture.needsUpdate = true;
  274. assignTexture(side);
  275. }).catch(function (e) {
  276. window.__pouchGLerr3 = window.__pouchGLerr3 || ('img: ' + String(e).slice(0, 200));
  277. });
  278. }
  279. entry.texture.needsUpdate = true;
  280. assignTexture(side);
  281. return Promise.resolve();
  282. }
  283. function assignTexture(side) {
  284. const tex = texTexture[side];
  285. if (!tex || !materials[side]) return;
  286. if (materials[side].map !== tex) {
  287. materials[side].map = tex;
  288. materials[side].needsUpdate = true;
  289. }
  290. }
  291. function applyDesign(spec) {
  292. // spec: { color, frontSVG, backSVG, W, H }
  293. const color = spec.color || '#e8e2d4';
  294. if (materials.FRONT) materials.FRONT.color.set('#ffffff');
  295. if (materials.BACK) materials.BACK.color.set('#ffffff');
  296. function svgOf(design, W, H) {
  297. const noText = Object.assign({}, design, { elements: (design.elements || []).filter(function (e) { return e.type !== 'text'; }) });
  298. return window.PL.render.designSVG(noText, W, H);
  299. }
  300. const fd = spec.frontDesign || { elements: [] };
  301. const bd = spec.backDesign || { elements: [] };
  302. const jobs = [
  303. drawSide('FRONT', color, svgOf(fd, spec.W || 140, spec.H || 210), spec.W || 140, spec.H || 210, spec.frontBg, fd),
  304. drawSide('BACK', color, svgOf(bd, spec.W || 140, spec.H || 210), spec.W || 140, spec.H || 210, spec.backBg, bd)
  305. ];
  306. return Promise.all(jobs).catch(function (e) {
  307. window.__pouchGLerr3 = String(e && e.stack || e).slice(0, 400);
  308. });
  309. }
  310. /* ---------- 交互 ---------- */
  311. function bindPointer() {
  312. canvas.addEventListener('pointerdown', function (e) {
  313. if (e.button !== 0) return;
  314. drag = { x: e.clientX, y: e.clientY, theta: orbit.theta };
  315. moved = false;
  316. canvas.style.cursor = 'grabbing';
  317. canvas.setPointerCapture(e.pointerId);
  318. });
  319. let moved = false;
  320. canvas.addEventListener('pointermove', function (e) {
  321. if (!drag) return;
  322. const dx = e.clientX - drag.x;
  323. const dy = e.clientY - drag.y;
  324. if (Math.abs(dx) + Math.abs(dy) > 3) moved = true;
  325. orbit.theta = drag.theta - dx * 0.4;
  326. applyOrbit();
  327. flush();
  328. });
  329. canvas.addEventListener('pointerup', function (e) {
  330. if (!drag) return;
  331. drag = null;
  332. canvas.style.cursor = 'grab';
  333. try { canvas.releasePointerCapture(e.pointerId); } catch (err) {}
  334. });
  335. canvas.addEventListener('pointercancel', function () { drag = null; canvas.style.cursor = 'grab'; });
  336. // 兜底:捕获丢失/指针离开画布/在窗口任意处抬起,都强制结束拖拽
  337. window.addEventListener('pointerup', function () {
  338. if (drag) { drag = null; canvas.style.cursor = 'grab'; }
  339. });
  340. canvas.addEventListener('pointerleave', function () {
  341. if (drag) { drag = null; canvas.style.cursor = 'grab'; }
  342. });
  343. canvas.addEventListener('wheel', function (e) {
  344. e.preventDefault();
  345. e.stopPropagation();
  346. orbit.zoom = Math.max(0.55, Math.min(2.6, orbit.zoom * (e.deltaY > 0 ? 0.92 : 1.08)));
  347. applyOrbit();
  348. flush();
  349. }, { passive: false });
  350. }
  351. bindPointer();
  352. function flush() {
  353. try { renderer.render(scene, camera); } catch (e) {}
  354. }
  355. let lastFrameAt = 0;
  356. function tick() {
  357. lastFrameAt = performance.now();
  358. try { renderer.render(scene, camera); } catch (e) {}
  359. }
  360. function animate() {
  361. raf = requestAnimationFrame(animate);
  362. tick();
  363. }
  364. setInterval(function () {
  365. if (performance.now() - lastFrameAt > 320) tick();
  366. }, 84);
  367. animate();
  368. /* ---------- 对外 API ---------- */
  369. return {
  370. load: function (shapeKey, done) {
  371. const mapped = SHAPE_MAP[shapeKey] || 'pouch';
  372. if (currentKey === mapped) { if (done) done(); return; }
  373. if (loadingKey === mapped) { pendingDone = done || null; return; } // 同模型加载中:合并回调
  374. loadModel(mapped, done);
  375. },
  376. applyDesign: applyDesign,
  377. setRotation: function (deg) {
  378. orbit.theta = Number(deg) || 0;
  379. applyOrbit();
  380. flush();
  381. },
  382. getRotation: function () { return orbit.theta; },
  383. setZoom: function (z) { orbit.zoom = Math.max(0.55, Math.min(2.6, Number(z) || 1)); applyOrbit(); flush(); },
  384. resetView: function () { orbit.theta = orbitHome.theta; orbit.zoom = orbitHome.zoom; applyOrbit(); flush(); },
  385. snapshot: function () { renderer.render(scene, camera); return canvas.toDataURL('image/png'); },
  386. dispose: function () {
  387. disposed = true;
  388. cancelAnimationFrame(raf);
  389. clearModel();
  390. renderer.dispose();
  391. if (canvas.parentNode) canvas.parentNode.removeChild(canvas);
  392. },
  393. ready: function () { return !disposed && !!renderer; }
  394. };
  395. }
  396. window.PL = window.PL || {};
  397. window.PL.pouch3d = { create: create };
  398. })();