viewer3d.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. /**
  2. * services/viewer3d.js —— Babylon 3D 外壳查看器(实验室专用,只在 /lab 页面初始化)。
  3. * - 用 core/geometry/profile.js 的回转母线把圆件/表壳/戒指的「壳体」绕 Z 轴旋转成型
  4. * - 方件(rect)用圆角矩形挤出 + 布尔减(内腔 + 屏沉台)
  5. * - 相机:单指旋转(ArcRotate 默认)、双指缩放、双击复位
  6. * - rebuild(params) 合并到 requestAnimationFrame;dispose 释放引擎 / 场景 / 画布监听
  7. * Babylon 由调用方动态 import(window.BABYLON),见 page/lab.js 的 ensureBabylon()。
  8. */
  9. import { roundProfile, radiusAtHeight } from '../core/geometry/profile.js';
  10. import { primMesh, rotateY, isCutType, cavity, snapDrag, primDims } from '../core/geometry/solid.js';
  11. import { footprint, snapToInnerWall } from '../core/geometry/parts.js';
  12. const DEG = Math.PI / 180;
  13. /** 整数化顶点,用于 C1(位置重合)去重 */
  14. const key = (x, y, z) => `${x.toFixed(4)},${y.toFixed(4)},${z.toFixed(4)}`;
  15. /** 截面点抽样:与前一点过近的中间点省掉,保证顶点连续、不孤悬末点 */
  16. function simplify(points, minStep = 0.06) {
  17. const out = [];
  18. for (const p of points) {
  19. const q = out[out.length - 1];
  20. if (q && Math.hypot(p[0] - q[0], p[1] - q[1]) < minStep) {
  21. out[out.length - 1] = p; // 用后点替换前点:末点永远保留
  22. continue;
  23. }
  24. out.push(p);
  25. }
  26. return out;
  27. }
  28. /**
  29. * 把闭合母线 [r,z] 绕 Z 轴旋转成网格数据并做顶点缝合(去掉接缝重复顶点)。
  30. * 圆件只有右半母线 → 整圈;这里统一处理任意闭合环(含轴线段 r=0)。
  31. */
  32. export function latheMesh(BABYLON, points, segments = 96) {
  33. const positions = [], indices = [];
  34. // 每一段母线点生成一圈
  35. const cols = points.length;
  36. const grid = [];
  37. for (let i = 0; i < cols; i++) {
  38. const [r, z] = points[i];
  39. const row = [];
  40. for (let s = 0; s < segments; s++) {
  41. const a = (s / segments) * Math.PI * 2;
  42. row.push([r * Math.cos(a), r * Math.sin(a), z]);
  43. }
  44. grid.push(row);
  45. }
  46. const map = new Map();
  47. const vid = (p) => {
  48. const k = key(p[0], p[1], p[2]);
  49. let id = map.get(k);
  50. if (id === undefined) { id = positions.length / 3; positions.push(p[0], p[1], p[2]); map.set(k, id); }
  51. return id;
  52. };
  53. for (let i = 0; i < cols; i++) {
  54. const i2 = (i + 1) % cols;
  55. for (let s = 0; s < segments; s++) {
  56. const s2 = (s + 1) % segments;
  57. const a = vid(grid[i][s]), b = vid(grid[i2][s]), c = vid(grid[i2][s2]), d = vid(grid[i][s2]);
  58. // 退化三角形跳过(轴上缝合产生的重合顶点)
  59. if (a !== b && b !== c && a !== c) indices.push(a, b, c);
  60. if (a !== c && c !== d && a !== d) indices.push(a, c, d);
  61. }
  62. }
  63. const normals = [];
  64. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  65. const vd = new BABYLON.VertexData();
  66. vd.positions = positions; vd.indices = indices; vd.normals = normals;
  67. return vd;
  68. }
  69. export class ShellViewer {
  70. /**
  71. * @param {HTMLCanvasElement} canvas
  72. * @param {object} product 产品 json(shape.type / materials)
  73. */
  74. constructor(canvas, product) {
  75. const B = (this.B = window.BABYLON);
  76. if (!B) throw new Error('Babylon 未加载');
  77. this.canvas = canvas;
  78. this.product = product;
  79. this.params = { ...(product.shape?.defaults || {}) };
  80. this._raf = 0;
  81. this._disp = null;
  82. this._onUnload = () => this.dispose();
  83. /** 结构件:[{ part(parts.js 实例), mesh, base(顶点缓存), mat }] */
  84. this._parts = [];
  85. this.selUid = null;
  86. this._drv = null; // 当前拖动会话
  87. this._moveRaf = 0;
  88. this.bgPointer = null; // 点空白回调(未拖动时触发)
  89. this.onSelect = null; // 点中件回调 (uid)
  90. this.onSelectMesh = null; // 点中件回调 (uid, mesh)
  91. this.onDragEnd = null; // 拖动松手回调 (uid, {x,z})
  92. this.onPartRule = null; // 拖动结束时规则回调 (uid, at)
  93. const engine = (this.engine = new B.Engine(canvas, true, {
  94. preserveDrawingBuffer: false, stencil: true, antialias: true,
  95. powerPreference: 'high-performance',
  96. }, true));
  97. const scene = (this.scene = new B.Scene(engine));
  98. scene.clearColor = new B.Color4(0, 0, 0, 0); // 透明,露出页面底色(浅白 / 深黑)
  99. const cam = (this.camera = new B.ArcRotateCamera('cam', -Math.PI / 2 + 0.6, Math.PI / 3.1, 120, B.Vector3.Zero(), scene));
  100. cam.attachControl(canvas, true);
  101. cam.lowerRadiusLimit = 5;
  102. cam.upperRadiusLimit = 1500;
  103. cam.wheelPrecision = 3;
  104. cam.pinchPrecision = 30;
  105. cam.pinchDeltaPercentage = 0.02;
  106. cam.panningSensibility = 0; // 单指旋转,不平移(双指缩放)
  107. cam.minZ = 0.5;
  108. cam.maxZ = 4000;
  109. this._home = { alpha: cam.alpha, beta: cam.beta, radius: cam.radius, target: cam.target.clone() };
  110. // 双击复位(触屏没有 dblclick:自行识别 300ms 内两次 tap)
  111. this._tapT = 0;
  112. this._pd = (e) => {
  113. if (e.pointerType !== 'touch') return;
  114. const now = performance.now();
  115. if (now - this._tapT < 300) this.reset();
  116. this._tapT = now;
  117. };
  118. canvas.addEventListener('pointerdown', this._pd);
  119. this._dbl = () => this.reset();
  120. canvas.addEventListener('dblclick', this._dbl);
  121. this._bindPicking(canvas);
  122. const hemi = new B.HemisphericLight('hemi', new B.Vector3(0.2, 1, 0.15), scene);
  123. hemi.intensity = 0.75;
  124. hemi.groundColor = new B.Color3(0.3, 0.3, 0.33);
  125. const keyLight = new B.DirectionalLight('key', new B.Vector3(-0.7, -1, 0.6), scene);
  126. keyLight.intensity = 0.85;
  127. const rim = new B.DirectionalLight('rim', new B.Vector3(0.8, -0.2, -0.8), scene);
  128. rim.intensity = 0.35;
  129. this.engine.runRenderLoop(() => { if (this.scene) this.scene.render(); });
  130. this._resize = () => engine.resize();
  131. addEventListener('resize', this._resize);
  132. addEventListener('pagehide', this._onUnload, { once: true });
  133. if (typeof ResizeObserver !== 'undefined') {
  134. this._ro = new ResizeObserver(() => engine.resize());
  135. this._ro.observe(canvas.parentElement || canvas);
  136. }
  137. this.build();
  138. }
  139. /** 当前网格顶点/索引统计(验收用) */
  140. stats() {
  141. const m = this.mesh;
  142. if (!m) return null;
  143. let pm = 0;
  144. for (const e of this._parts || []) if (e.mesh && !e.mesh.isDisposed()) pm += e.mesh.getTotalVertices();
  145. return { positions: m.getTotalVertices(), indices: m.getTotalIndices(), parts: this._parts ? this._parts.length : 0, partVertices: pm, params: { ...this.params } };
  146. }
  147. setParams(patch) {
  148. Object.assign(this.params, patch);
  149. if (!this._raf) {
  150. this._raf = requestAnimationFrame(() => {
  151. this._raf = 0;
  152. this.build();
  153. this._onChange?.();
  154. });
  155. }
  156. }
  157. build() {
  158. const B = this.B;
  159. if (this.mesh) { this.mesh.dispose(); this.mesh = null; }
  160. try {
  161. this.mesh = this.product.shape?.type === 'rect' ? this._buildRect() : this._buildLathe();
  162. } catch (e) {
  163. console.warn('[viewer] 重建失败', e);
  164. return;
  165. }
  166. this.mesh.material = this._material();
  167. // 把模型放到地台上:包围盒最小 z → 0,水平居中
  168. const bb = this.mesh.getBoundingInfo().boundingBox;
  169. const min = bb.minimumWorld, max = bb.maximumWorld;
  170. this.mesh.position = new B.Vector3(-(min.x + max.x) / 2, -(min.y + max.y) / 2, -min.z);
  171. const size = Math.max(max.x - min.x, max.y - min.y, max.z - min.z);
  172. if (!this._framed) {
  173. this.camera.radius = size * 1.9;
  174. this.camera.target = new B.Vector3(0, 0, (max.z - min.z) / 2);
  175. camSnapshot(this.camera, this._home);
  176. this._framed = true;
  177. }
  178. if (this._parts.length) this._layoutParts();
  179. if (this.selUid) this.applySelection(this.selUid);
  180. return this.mesh;
  181. }
  182. /* =========================================================
  183. 结构件:渲染 / 选中 / 高亮 / 拖动 / 聚焦
  184. ========================================================= */
  185. /** 壳体落位包络(结构件拖动与贴壁用):圆件 {kind:'cyl',r,floor,top},方件 {kind:'rect',halfX,halfZ,floor,top} */
  186. get cav() {
  187. const c = cavity(this.product.shape?.type, this.params);
  188. this._cavCache = { ...c, h: Number(this.params.height) || 8, w: Number(this.params.dTop) || 40 };
  189. return this._cavCache;
  190. }
  191. /** 壳体渲染包围盒(世界坐标) */
  192. shellBounds() {
  193. const m = this.mesh;
  194. if (!m) return { min: new this.B.Vector3(-10, 0, -10), max: new this.B.Vector3(10, 10, 10) };
  195. const bb = m.getBoundingInfo().boundingBox;
  196. return { min: bb.minimumWorld.clone(), max: bb.maximumWorld.clone(), center: bb.centerWorld.clone() };
  197. }
  198. /** 世界坐标 → 壳体局部坐标(X 右 / Y 上 / Z 前,原点在壳底中心) */
  199. _toLocal(v) {
  200. const m = this.mesh;
  201. if (!m) return { x: v.x, y: v.y, z: v.z };
  202. const p = m.position;
  203. return { x: v.x - p.x, y: v.y - p.y, z: v.z - p.z };
  204. }
  205. /** 全量重建结构件(增删 / 改参数 / 产品切换时调用;单件量小,直接重建,不节流) */
  206. setParts(parts = []) {
  207. const B = this.B;
  208. for (const e of this._parts) if (e.mesh && !e.mesh.isDisposed()) e.mesh.dispose();
  209. this._parts = [];
  210. for (const part of parts) {
  211. let pm = null;
  212. try { pm = primMesh({ ...part.params, type: part.type }).part; } catch (e) { console.warn('[viewer] 结构件网格失败', part.uid, e); continue; }
  213. const mesh = new B.Mesh('part:' + part.uid, this.scene);
  214. const vd = new B.VertexData();
  215. vd.positions = Array.from(pm.positions);
  216. vd.indices = Array.from(pm.indices);
  217. const nrm = [];
  218. B.VertexData.ComputeNormals(vd.positions, vd.indices, nrm);
  219. vd.normals = nrm;
  220. vd.applyToMesh(mesh, false);
  221. const mat = new B.StandardMaterial('pm:' + part.uid, this.scene);
  222. const cut = isCutType(part.type);
  223. mat.diffuseColor = cut ? new B.Color3(0.98, 0.45, 0.25) : new B.Color3(0.16, 0.46, 0.9);
  224. mat.specularColor = new B.Color3(0.3, 0.3, 0.32);
  225. mat.emissiveColor = cut ? new B.Color3(0.28, 0.1, 0.04) : new B.Color3(0.04, 0.12, 0.3);
  226. if (cut) mat.alpha = 0.55;
  227. mat.backFaceCulling = false;
  228. mesh.material = mat;
  229. mesh.isPickable = true;
  230. mesh.metadata = { uid: part.uid, kind: 'part' };
  231. this._parts.push({ part, mesh, base: { positions: vd.positions, indices: vd.indices }, mat, cut });
  232. }
  233. this._layoutParts();
  234. this.applySelection(this.selUid);
  235. return this._parts;
  236. }
  237. /** 单个件的 params / at / rotY 变了:只重建这一件 */
  238. updatePart(part) {
  239. const i = this._parts.findIndex((e) => e.part.uid === part.uid);
  240. if (i < 0) return this.setParts([...this._parts.map((e) => e.part), part]);
  241. const list = this._parts.map((e) => e.part);
  242. list[i] = part;
  243. this.setParts(list);
  244. return this._parts.find((e) => e.part.uid === part.uid);
  245. }
  246. /**
  247. * 把件的局部网格(原点在件中心、Y 向上)摆到壳体坐标:
  248. * mirror(X 取反)→ 绕 Y 旋转 → 平移到 at(at.y = 件底面高度)。
  249. * 壳体相对网格有偏移 → 再统一加网格位移;结构件尺寸很小,直接烘焙进顶点后 world = identity,
  250. * 这样拖动平移、包围盒、拾取都不受父节点影响。
  251. */
  252. _layoutParts() {
  253. const B = this.B;
  254. const off = this.mesh ? this.mesh.position : new B.Vector3(0, 0, 0);
  255. for (const e of this._parts) {
  256. const part = e.part;
  257. const p = e.base.positions.slice();
  258. if (part.mirror) for (let j = 0; j < p.length; j += 3) p[j] = -p[j];
  259. const a = (Number(part.rotY) || 0) * DEG, c = Math.cos(a), s = Math.sin(a);
  260. const half = this._partHalfHeight(part);
  261. const tx = Number(part.at?.x) || 0, ty = Number(part.at?.y) || 0, tz = Number(part.at?.z) || 0;
  262. for (let j = 0; j < p.length; j += 3) {
  263. const x = p[j], y = p[j + 1], z = p[j + 2];
  264. const X = x * c + z * s, Z = -x * s + z * c;
  265. p[j] = X + tx + off.x;
  266. p[j + 1] = y + ty + half + off.y;
  267. p[j + 2] = Z + tz + off.z;
  268. }
  269. e.mesh.setVerticesData(this.B.VertexBuffer.PositionKind, p, false);
  270. e.mesh.refreshBoundingInfo();
  271. e.mesh.isVisible = part.visible !== false;
  272. }
  273. }
  274. _partHalfHeight(part) {
  275. const p = part.params || {};
  276. return Math.max(0.1, Number(p.h) || 1) / 2;
  277. }
  278. /**
  279. * 选中高亮:选中件 emissive 亮蓝 + 其余件 alpha 0.25。
  280. * uid 为空 → 恢复全部不透明、无选中色。
  281. */
  282. applySelection(uid) {
  283. this.selUid = uid || null;
  284. for (const e of this._parts) {
  285. if (!e.mesh || e.mesh.isDisposed()) continue;
  286. const sel = this.selUid && e.part.uid === this.selUid;
  287. if (this.selUid) {
  288. e.mesh.visibility = sel ? 1 : 0.25;
  289. e.mat.emissiveColor = sel ? new this.B.Color3(0.1, 0.45, 1.0) : (e.cut ? new this.B.Color3(0.28, 0.1, 0.04) : new this.B.Color3(0.02, 0.04, 0.1));
  290. } else {
  291. e.mesh.visibility = 1;
  292. e.mat.emissiveColor = e.cut ? new this.B.Color3(0.28, 0.1, 0.04) : new this.B.Color3(0.04, 0.12, 0.3);
  293. }
  294. }
  295. }
  296. /** 件中心的壳体局部坐标 */
  297. partCenter(part) {
  298. return { x: Number(part.at?.x) || 0, y: (Number(part.at?.y) || 0) + this._partHalfHeight(part), z: Number(part.at?.z) || 0 };
  299. }
  300. /** 相机聚焦到某件(壳体局部坐标),半径按件尺寸收紧 */
  301. focusPart(part) {
  302. const c = this.partCenter(part);
  303. const fp = footprint(part) * 2, h = this._partHalfHeight(part) * 2;
  304. const r = Math.max(14, Math.max(fp, h) * 3.2);
  305. const tgt = this.mesh ? this.mesh.position.clone() : this.B.Vector3.Zero();
  306. tgt.addInPlace(new this.B.Vector3(c.x, c.y, c.z));
  307. const cam = this.camera;
  308. cam.setTarget(tgt);
  309. cam.radius = Math.min(cam.upperRadiusLimit, r);
  310. }
  311. /** 回到全局视图(首次自动取景的机位) */
  312. homeView(instant = true) {
  313. const cam = this.camera;
  314. const from = { alpha: cam.alpha, beta: cam.beta, radius: cam.radius, target: cam.target.clone() };
  315. const to = this._home;
  316. if (instant) {
  317. cam.alpha = to.alpha; cam.beta = to.beta; cam.radius = to.radius; cam.target.copyFrom(to.target);
  318. return;
  319. }
  320. const B = this.B, t0 = performance.now(), dur = 320;
  321. const step = () => {
  322. const k = Math.min(1, (performance.now() - t0) / dur), e = 1 - Math.pow(1 - k, 3);
  323. cam.alpha = from.alpha + (to.alpha - from.alpha) * e;
  324. cam.beta = from.beta + (to.beta - from.beta) * e;
  325. cam.radius = from.radius + (to.radius - from.radius) * e;
  326. cam.target.copyFrom(B.Vector3.Lerp(from.target, to.target, e));
  327. if (k < 1) requestAnimationFrame(step);
  328. };
  329. requestAnimationFrame(step);
  330. }
  331. /** 拖动落点:靠内壁 1.5mm 内贴到留 0.5mm 余量;否则按 step 取整 */
  332. dragSnap(part, x, z, step = 1) {
  333. const cav = this.cav;
  334. return snapDrag(cav, { ...part.params, x, z }, x, z, step, 1.5, 0.5);
  335. }
  336. /* ---------- 拾取 / 拖动 ---------- */
  337. _pickAt(ev) {
  338. const B = this.B, scene = this.scene;
  339. if (!scene) return null;
  340. const rect = this.canvas.getBoundingClientRect();
  341. const x = ev.clientX - rect.left, y = ev.clientY - rect.top;
  342. const hit = scene.pick(x, y, (m) => m.isPickable && m.isVisible !== false && m.isEnabled(), false, scene.activeCamera);
  343. return hit && hit.hit ? hit : null;
  344. }
  345. _bindPicking(canvas) {
  346. const B = this.B;
  347. /** 水平面(世界 Y = y),拖动投影用;平面运行中不动,取 p0 预建 */
  348. this._planeAt = (y) => B.Plane.FromPositionAndNormal(new B.Vector3(0, y, 0), new B.Vector3(0, 1, 0));
  349. const down = (ev) => {
  350. if (ev.button !== undefined && ev.button > 0) return; // 只处理主键 / 单指
  351. if (this._drv) return;
  352. const hit = this._pickAt(ev);
  353. const uid = hit?.pickedMesh?.metadata?.uid;
  354. if (!uid) return; // 空白处:交给相机旋转,松手再判点空白
  355. ev.stopImmediatePropagation();
  356. ev.preventDefault();
  357. const part = this._parts.find((e) => e.part.uid === uid)?.part;
  358. if (!part) return;
  359. if (part.visible === false) return;
  360. this.camera.detachControl(); // 拖动时锁住相机
  361. const y = this.mesh.position.y + (Number(part.at?.y) || 0);
  362. const pl = this._planeAt(y);
  363. const ray = this.scene.createPickingRay(ev.clientX - canvas.getBoundingClientRect().left, ev.clientY - canvas.getBoundingClientRect().top, B.Matrix.Identity(), this.camera);
  364. const p0 = ray.intersectsPlane(pl);
  365. this._drv = {
  366. uid, part, pl, p0, moved: false,
  367. start: { x: Number(part.at?.x) || 0, z: Number(part.at?.z) || 0 },
  368. sx: ev.clientX, sy: ev.clientY,
  369. };
  370. this.onSelect?.(uid, this._parts.find((e) => e.part.uid === uid)?.mesh);
  371. const move = (e2) => this._onDragMove(e2);
  372. const up = () => { this._onDragUp(); };
  373. canvas.addEventListener('pointermove', move);
  374. canvas.addEventListener('pointerup', up);
  375. canvas.addEventListener('pointercancel', up);
  376. this._drvCleanup = () => { canvas.removeEventListener('pointermove', move); canvas.removeEventListener('pointerup', up); canvas.removeEventListener('pointercancel', up); };
  377. };
  378. // 捕获阶段:在 ArcRotateCamera 的 canvas 监听之前截停
  379. canvas.addEventListener('pointerdown', down, true);
  380. // 点空白:pointerup 时若没拖动 → 失焦选中
  381. const voidDown = (ev) => {
  382. if (ev.button !== undefined && ev.button > 0) return;
  383. this._maybeVoid = { x: ev.clientX, y: ev.clientY, t: performance.now() };
  384. };
  385. const voidUp = (ev) => {
  386. const v = this._maybeVoid; this._maybeVoid = null;
  387. if (!v || this._drv) return;
  388. if (Math.hypot(ev.clientX - v.x, ev.clientY - v.y) > 6 || performance.now() - v.t > 500) return;
  389. if (this._pickAt(ev)?.pickedMesh?.metadata?.uid) return;
  390. this.bgPointer?.();
  391. };
  392. canvas.addEventListener('pointerdown', voidDown);
  393. canvas.addEventListener('pointerup', voidUp);
  394. }
  395. _onDragMove(ev) {
  396. const d = this._drv;
  397. if (!d) return;
  398. if (!d.moved && Math.hypot(ev.clientX - d.sx, ev.clientY - d.sy) < 4) return;
  399. d.moved = true;
  400. const rect = this.canvas.getBoundingClientRect();
  401. const ray = this.scene.createPickingRay(ev.clientX - rect.left, ev.clientY - rect.top, this.B.Matrix.Identity(), this.camera);
  402. const hit = ray.intersectsPlane(d.pl);
  403. if (!hit) return;
  404. const p = this._toLocal(hit);
  405. const s = this._snapStep || 1;
  406. const q = this.dragSnap(d.part, p.x, p.z, s);
  407. if (!this._moveRaf) {
  408. this._moveRaf = requestAnimationFrame(() => {
  409. this._moveRaf = 0;
  410. if (!this._drv) return;
  411. const dr = this._drv;
  412. dr.part = { ...dr.part, at: { ...dr.part.at, x: q.x, z: q.z } };
  413. const e = this._parts.find((x) => x.part.uid === dr.uid);
  414. if (e) { e.part = dr.part; this._layoutParts(); }
  415. this.onDragMove?.(dr.uid, { x: q.x, z: q.z });
  416. });
  417. }
  418. d.last = { x: q.x, z: q.z };
  419. }
  420. _onDragUp() {
  421. const d = this._drv;
  422. this._drvCleanup?.();
  423. this._drvCleanup = null;
  424. if (this._moveRaf) { cancelAnimationFrame(this._moveRaf); this._moveRaf = 0; }
  425. this.camera.attachControl(this.canvas, true); // 松手交还相机
  426. this._drv = null;
  427. if (!d) return;
  428. if (d.moved) {
  429. const at = d.last ? { x: d.last.x, z: d.last.z } : { x: d.start.x, z: d.start.z };
  430. this.onDragEnd?.(d.uid, at);
  431. }
  432. }
  433. /** 由页面把「已选中件」的最新实例同步给 viewer(拖动后 page 侧回写) */
  434. syncPart(part) {
  435. const e = this._parts.find((x) => x.part.uid === part.uid);
  436. if (!e) return;
  437. e.part = part;
  438. this._layoutParts();
  439. }
  440. /* =========================================================
  441. 导出:STL / 截图
  442. ========================================================= */
  443. /** 收集三角面(世界坐标):壳体 + 可见结构件;onlyUid 时只取该结构件 */
  444. collectTriangles(onlyUid = null) {
  445. const tris = [];
  446. const pushMesh = (mesh, part) => {
  447. if (!mesh || mesh.isDisposed()) return;
  448. const pos = mesh.getVerticesData(this.B.VertexBuffer.PositionKind);
  449. const idx = mesh.getIndices();
  450. const wm = mesh.computeWorldMatrix(true);
  451. const n = idx ? idx.length : pos.length / 3;
  452. for (let i = 0; i < n; i += 3) {
  453. const a = new this.B.Vector3(pos[idx[i] * 3], pos[idx[i] * 3 + 1], pos[idx[i] * 3 + 2]);
  454. const b = new this.B.Vector3(pos[idx[i + 1] * 3], pos[idx[i + 1] * 3 + 1], pos[idx[i + 1] * 3 + 2]);
  455. const c = new this.B.Vector3(pos[idx[i + 2] * 3], pos[idx[i + 2] * 3 + 1], pos[idx[i + 2] * 3 + 2]);
  456. this.B.Vector3.TransformCoordinatesToRef(a, wm, a);
  457. this.B.Vector3.TransformCoordinatesToRef(b, wm, b);
  458. this.B.Vector3.TransformCoordinatesToRef(c, wm, c);
  459. const u = b.subtract(a), w = c.subtract(a);
  460. const nn = this.B.Vector3.Cross(u, w);
  461. tris.push({ a, b, c, n: nn.lengthSquared() > 1e-12 ? nn.normalize() : new this.B.Vector3(0, 1, 0), uid: part?.uid || 'shell' });
  462. }
  463. };
  464. if (onlyUid) {
  465. const e = this._parts.find((x) => x.part.uid === onlyUid);
  466. if (e) pushMesh(e.mesh, e.part);
  467. } else {
  468. pushMesh(this.mesh, null);
  469. for (const e of this._parts) if (e.mesh.isVisible) pushMesh(e.mesh, e.part);
  470. }
  471. return tris;
  472. }
  473. /** 二进制 STL(小端 float32);返回 ArrayBuffer */
  474. exportSTL(onlyUid = null) {
  475. const tris = this.collectTriangles(onlyUid);
  476. const buf = new ArrayBuffer(84 + tris.length * 50);
  477. const view = new DataView(buf);
  478. const header = 'Pocket Hardware Lab · FmodeCode';
  479. for (let i = 0; i < Math.min(80, header.length); i++) view.setUint8(i, header.charCodeAt(i));
  480. view.setUint32(80, tris.length, true);
  481. let o = 84;
  482. for (const t of tris) {
  483. view.setFloat32(o, t.n.x, true); view.setFloat32(o + 4, t.n.y, true); view.setFloat32(o + 8, t.n.z, true); o += 12;
  484. for (const v of [t.a, t.b, t.c]) { view.setFloat32(o, v.x, true); view.setFloat32(o + 4, v.y, true); view.setFloat32(o + 8, v.z, true); o += 12; }
  485. view.setUint16(o, 0, true); o += 2;
  486. }
  487. return { buffer: buf, triangles: tris.length };
  488. }
  489. /**
  490. * 截图(scale 倍分辨率):优先 Tools.CreateScreenshot(render target 离屏放大),
  491. * GPU / 无头环境下 render-target 路径会抛「ScreenshotTools」,再退到 canvas.toDataURL + 像素放大。
  492. * 返回 dataURL(image/png)或 null。
  493. */
  494. async screenshot(scale = 2) {
  495. const B = this.B;
  496. const rt = this.canvas.width;
  497. let data = await new Promise((resolve) => {
  498. let done = false;
  499. try {
  500. B.Tools.CreateScreenshot(this.engine, this.camera, { precision: scale }, (d) => { done = true; resolve(d); }, 'image/png');
  501. } catch (e) {
  502. console.warn('[viewer] 截图 render-target 不可用,改用画布像素', e?.message || e);
  503. resolve(null);
  504. }
  505. setTimeout(() => { if (!done) resolve(null); }, 1500);
  506. });
  507. if (!data) {
  508. try {
  509. this.scene.render();
  510. data = this.canvas.toDataURL('image/png');
  511. } catch (e) { console.warn('[viewer] 画布截图失败', e); return null; }
  512. if (!data || data.length < 100) return null;
  513. if (scale > 1) {
  514. const up = await scalePng(data, scale);
  515. if (up) data = up;
  516. }
  517. }
  518. void rt;
  519. return data;
  520. }
  521. _rectMaterial() {
  522. const B = this.B;
  523. const m = new B.StandardMaterial('rectMat', this.scene);
  524. m.diffuseColor = new B.Color3(0.68, 0.69, 0.71);
  525. m.specularColor = new B.Color3(0.35, 0.35, 0.35);
  526. m.specularPower = 64;
  527. m.backFaceCulling = false;
  528. return m;
  529. }
  530. _material() {
  531. const B = this.B;
  532. // StandardMaterial:漫反射 + 高光 + 边缘 Fresnel,无外部环境贴图也能看出曲面明暗
  533. const mat = new B.StandardMaterial('shellMat', this.scene);
  534. const id = this.product.materials?.[0];
  535. const alu = /^al-|^ti$/.test(id || '');
  536. mat.diffuseColor = alu ? new B.Color3(0.72, 0.73, 0.75) : new B.Color3(0.8, 0.8, 0.82);
  537. mat.specularColor = alu ? new B.Color3(0.65, 0.65, 0.68) : new B.Color3(0.22, 0.22, 0.24);
  538. mat.specularPower = alu ? 96 : 24;
  539. mat.emissiveColor = new B.Color3(0.12, 0.12, 0.13);
  540. mat.backFaceCulling = false; // 截面开放处也能看到内壁
  541. return mat;
  542. }
  543. _buildLathe() {
  544. const B = this.B;
  545. const prof = roundProfile(this.params);
  546. this.profile = prof;
  547. let pts = simplify(prof.points.filter((p) => p[0] > 1e-4));
  548. // 母线是「右半截面」,首尾都在轴上 → 首尾各补一个轴点闭合外表面
  549. if (pts.length > 2) pts = [[0, pts[0][1]], ...pts, [0, pts[pts.length - 1][1]]];
  550. const vd = latheMesh(B, pts, 112);
  551. const mesh = new B.Mesh('shell', this.scene);
  552. vd.applyToMesh(mesh, true);
  553. try {
  554. // 法线统一朝外(回转体逐段朝外法向 = 指向远离轴线的凸侧)
  555. mesh.flipFaces(latheWinding(pts) > 0);
  556. const normals = [];
  557. B.VertexData.ComputeNormals(mesh.getVerticesData(B.VertexBuffer.PositionKind), mesh.getIndices(), normals);
  558. mesh.setVerticesData(B.VertexBuffer.NormalKind, normals);
  559. } catch (e) { console.warn('[viewer] 法线修正跳过', e); }
  560. return mesh;
  561. }
  562. _buildRect() {
  563. const B = this.B;
  564. const p = this.params;
  565. const L = Math.max(4, +p.length || 40), W = Math.max(4, +p.dTop || 30), H = Math.max(2, +p.height || 8);
  566. const wall = Math.max(0.4, +p.wall || 1.5);
  567. const cap = Math.min(Math.max(0, +p.capR || 0), H / 2 - 0.3);
  568. // 圆角矩形闭合轮廓(逆时针,中心在原点)
  569. const loop = (l, w, r) => {
  570. const hw = l / 2, hh = w / 2, rr = Math.max(0.05, Math.min(r, hw - 0.05, hh - 0.05));
  571. const pts = [];
  572. const arc = (cx, cy, a0, a1) => { for (let i = 0; i <= 6; i++) { const a = a0 + (a1 - a0) * (i / 6); pts.push([cx + rr * Math.cos(a), cy + rr * Math.sin(a)]); } };
  573. arc(hw - rr, -hh + rr, -Math.PI / 2, 0);
  574. arc(hw - rr, hh - rr, 0, Math.PI / 2);
  575. arc(-hw + rr, hh - rr, Math.PI / 2, Math.PI);
  576. arc(-hw + rr, -hh + rr, Math.PI, 1.5 * Math.PI);
  577. return pts;
  578. };
  579. const outer = loop(L, W, Math.max(0, +p.cornerR || 0));
  580. const inner = loop(L - 2 * wall, W - 2 * wall, Math.max(0.5, (+p.cornerR || 0) - wall));
  581. const n = outer.length;
  582. const zTop = Math.max(0.6, H - Math.max(0.6, wall)); // 内腔顶(壳底)
  583. const zCap = zTop - cap; // 顶部圆角起点
  584. // 水平剖面 = 一串「圆角矩形环」,相邻环之间拉出面:外壁 ↑ → 顶面环带 → 内壁 ↓;底环带封底
  585. const rings = [
  586. outer.map(([x, y]) => [x, y, 0]),
  587. outer.map(([x, y]) => [x, y, zCap]),
  588. outer.map(([x, y]) => [x, y, zTop]),
  589. inner.map(([x, y]) => [x, y, zTop]),
  590. inner.map(([x, y]) => [x, y, 0]),
  591. ];
  592. const positions = [], indices = [];
  593. const add = (x, y, z) => { positions.push(x, y, z); return positions.length / 3 - 1; };
  594. const ids = rings.map((ring) => ring.map(([x, y, z]) => add(x, y, z)));
  595. void zTop;
  596. for (let r = 0; r < ids.length - 1; r++) {
  597. const A = ids[r], Bn = ids[r + 1];
  598. for (let i = 0; i < n; i++) {
  599. const j = (i + 1) % n;
  600. indices.push(A[i], A[j], Bn[j], A[i], Bn[j], Bn[i]);
  601. }
  602. }
  603. // 底环带(底面:从内环到外环)
  604. const ob = outer.map(([x, y]) => add(x, y, 0));
  605. const ib = inner.map(([x, y]) => add(x, y, 0));
  606. for (let i = 0; i < n; i++) { const j = (i + 1) % n; indices.push(ob[j], ob[i], ib[i], ob[j], ib[i], ib[j]); }
  607. const vd = new B.VertexData();
  608. vd.positions = positions; vd.indices = indices;
  609. const normals = []; B.VertexData.ComputeNormals(positions, indices, normals); vd.normals = normals;
  610. const mesh = new B.Mesh('shell', this.scene);
  611. vd.applyToMesh(mesh, true);
  612. mesh.material = this._rectMaterial();
  613. mesh.refreshBoundingInfo();
  614. return mesh;
  615. }
  616. /** 双击复位:退出选中态,相机回到首次取景 */
  617. reset(animate = false) {
  618. if (this.selUid) { this.applySelection(null); this.onSelect?.(null, null); }
  619. this.homeView(!animate);
  620. }
  621. dispose() {
  622. this._alive = false;
  623. if (this._raf) { cancelAnimationFrame(this._raf); this._raf = 0; }
  624. removeEventListener('resize', this._resize);
  625. removeEventListener('pagehide', this._onUnload);
  626. if (this._ro) { this._ro.disconnect(); this._ro = null; }
  627. if (this._dbl) this.canvas.removeEventListener('dblclick', this._dbl);
  628. if (this._pd) this.canvas.removeEventListener('pointerdown', this._pd);
  629. this._drvCleanup?.();
  630. if (this._moveRaf) cancelAnimationFrame(this._moveRaf);
  631. this._parts = [];
  632. this.selUid = null;
  633. try { this.camera?.dispose(); } catch { /* noop */ }
  634. try { this.scene?.dispose(); } catch { /* noop */ }
  635. try { this.engine?.stopRenderLoop(); this.engine?.dispose(); } catch { /* noop */ }
  636. this.mesh = null;
  637. this.scene = null;
  638. this.engine = null;
  639. this.camera = null;
  640. }
  641. }
  642. /** 母线绕轴旋转后按右手系判断三角形绕向(鞋带和 > 0 表示需翻转) */
  643. function latheWinding(pts) {
  644. let area = 0;
  645. for (let i = 0; i < pts.length; i++) {
  646. const [r0, z0] = pts[i], [r1, z1] = pts[(i + 1) % pts.length];
  647. area += r0 * z1 - r1 * z0;
  648. }
  649. return area;
  650. }
  651. function camSnapshot(cam, into) {
  652. into.alpha = cam.alpha; into.beta = cam.beta; into.radius = cam.radius;
  653. if (into.target) into.target.copyFrom(cam.target); else into.target = cam.target.clone();
  654. }
  655. /** 只用于测试半径插值导出的薄封装(避免循环依赖告警) */
  656. export { radiusAtHeight };
  657. /** 按比例把 canvas 截图 dataURL 缩放成 PNG(无头 / GPU 限制走不通时兜底) */
  658. export function scalePng(dataUrl, scale = 2) {
  659. return new Promise((resolve) => {
  660. const img = new Image();
  661. img.onload = () => {
  662. const c = document.createElement('canvas');
  663. c.width = Math.round(img.width * scale); c.height = Math.round(img.height * scale);
  664. const ctx = c.getContext('2d');
  665. ctx.imageSmoothingQuality = 'high';
  666. ctx.drawImage(img, 0, 0, c.width, c.height);
  667. resolve(c.toDataURL('image/png'));
  668. };
  669. img.onerror = () => resolve(null);
  670. img.src = dataUrl;
  671. });
  672. }