| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723 |
- /**
- * services/viewer3d.js —— Babylon 3D 外壳查看器(实验室专用,只在 /lab 页面初始化)。
- * - 用 core/geometry/profile.js 的回转母线把圆件/表壳/戒指的「壳体」绕 Z 轴旋转成型
- * - 方件(rect)用圆角矩形挤出 + 布尔减(内腔 + 屏沉台)
- * - 相机:单指旋转(ArcRotate 默认)、双指缩放、双击复位
- * - rebuild(params) 合并到 requestAnimationFrame;dispose 释放引擎 / 场景 / 画布监听
- * Babylon 由调用方动态 import(window.BABYLON),见 page/lab.js 的 ensureBabylon()。
- */
- import { roundProfile, radiusAtHeight } from '../core/geometry/profile.js';
- import { primMesh, rotateY, isCutType, cavity, snapDrag, primDims } from '../core/geometry/solid.js';
- import { footprint, snapToInnerWall } from '../core/geometry/parts.js';
- const DEG = Math.PI / 180;
- /** 整数化顶点,用于 C1(位置重合)去重 */
- const key = (x, y, z) => `${x.toFixed(4)},${y.toFixed(4)},${z.toFixed(4)}`;
- /** 截面点抽样:与前一点过近的中间点省掉,保证顶点连续、不孤悬末点 */
- function simplify(points, minStep = 0.06) {
- const out = [];
- for (const p of points) {
- const q = out[out.length - 1];
- if (q && Math.hypot(p[0] - q[0], p[1] - q[1]) < minStep) {
- out[out.length - 1] = p; // 用后点替换前点:末点永远保留
- continue;
- }
- out.push(p);
- }
- return out;
- }
- /**
- * 把闭合母线 [r,z] 绕 Z 轴旋转成网格数据并做顶点缝合(去掉接缝重复顶点)。
- * 圆件只有右半母线 → 整圈;这里统一处理任意闭合环(含轴线段 r=0)。
- */
- export function latheMesh(BABYLON, points, segments = 96) {
- const positions = [], indices = [];
- // 每一段母线点生成一圈
- const cols = points.length;
- const grid = [];
- for (let i = 0; i < cols; i++) {
- const [r, z] = points[i];
- const row = [];
- for (let s = 0; s < segments; s++) {
- const a = (s / segments) * Math.PI * 2;
- row.push([r * Math.cos(a), r * Math.sin(a), z]);
- }
- grid.push(row);
- }
- const map = new Map();
- const vid = (p) => {
- const k = key(p[0], p[1], p[2]);
- let id = map.get(k);
- if (id === undefined) { id = positions.length / 3; positions.push(p[0], p[1], p[2]); map.set(k, id); }
- return id;
- };
- for (let i = 0; i < cols; i++) {
- const i2 = (i + 1) % cols;
- for (let s = 0; s < segments; s++) {
- const s2 = (s + 1) % segments;
- const a = vid(grid[i][s]), b = vid(grid[i2][s]), c = vid(grid[i2][s2]), d = vid(grid[i][s2]);
- // 退化三角形跳过(轴上缝合产生的重合顶点)
- if (a !== b && b !== c && a !== c) indices.push(a, b, c);
- if (a !== c && c !== d && a !== d) indices.push(a, c, d);
- }
- }
- const normals = [];
- BABYLON.VertexData.ComputeNormals(positions, indices, normals);
- const vd = new BABYLON.VertexData();
- vd.positions = positions; vd.indices = indices; vd.normals = normals;
- return vd;
- }
- export class ShellViewer {
- /**
- * @param {HTMLCanvasElement} canvas
- * @param {object} product 产品 json(shape.type / materials)
- */
- constructor(canvas, product) {
- const B = (this.B = window.BABYLON);
- if (!B) throw new Error('Babylon 未加载');
- this.canvas = canvas;
- this.product = product;
- this.params = { ...(product.shape?.defaults || {}) };
- this._raf = 0;
- this._disp = null;
- this._onUnload = () => this.dispose();
- /** 结构件:[{ part(parts.js 实例), mesh, base(顶点缓存), mat }] */
- this._parts = [];
- this.selUid = null;
- this._drv = null; // 当前拖动会话
- this._moveRaf = 0;
- this.bgPointer = null; // 点空白回调(未拖动时触发)
- this.onSelect = null; // 点中件回调 (uid)
- this.onSelectMesh = null; // 点中件回调 (uid, mesh)
- this.onDragEnd = null; // 拖动松手回调 (uid, {x,z})
- this.onPartRule = null; // 拖动结束时规则回调 (uid, at)
- const engine = (this.engine = new B.Engine(canvas, true, {
- preserveDrawingBuffer: false, stencil: true, antialias: true,
- powerPreference: 'high-performance',
- }, true));
- const scene = (this.scene = new B.Scene(engine));
- scene.clearColor = new B.Color4(0, 0, 0, 0); // 透明,露出页面底色(浅白 / 深黑)
- const cam = (this.camera = new B.ArcRotateCamera('cam', -Math.PI / 2 + 0.6, Math.PI / 3.1, 120, B.Vector3.Zero(), scene));
- cam.attachControl(canvas, true);
- cam.lowerRadiusLimit = 5;
- cam.upperRadiusLimit = 1500;
- cam.wheelPrecision = 3;
- cam.pinchPrecision = 30;
- cam.pinchDeltaPercentage = 0.02;
- cam.panningSensibility = 0; // 单指旋转,不平移(双指缩放)
- cam.minZ = 0.5;
- cam.maxZ = 4000;
- this._home = { alpha: cam.alpha, beta: cam.beta, radius: cam.radius, target: cam.target.clone() };
- // 双击复位(触屏没有 dblclick:自行识别 300ms 内两次 tap)
- this._tapT = 0;
- this._pd = (e) => {
- if (e.pointerType !== 'touch') return;
- const now = performance.now();
- if (now - this._tapT < 300) this.reset();
- this._tapT = now;
- };
- canvas.addEventListener('pointerdown', this._pd);
- this._dbl = () => this.reset();
- canvas.addEventListener('dblclick', this._dbl);
- this._bindPicking(canvas);
- const hemi = new B.HemisphericLight('hemi', new B.Vector3(0.2, 1, 0.15), scene);
- hemi.intensity = 0.75;
- hemi.groundColor = new B.Color3(0.3, 0.3, 0.33);
- const keyLight = new B.DirectionalLight('key', new B.Vector3(-0.7, -1, 0.6), scene);
- keyLight.intensity = 0.85;
- const rim = new B.DirectionalLight('rim', new B.Vector3(0.8, -0.2, -0.8), scene);
- rim.intensity = 0.35;
- this.engine.runRenderLoop(() => { if (this.scene) this.scene.render(); });
- this._resize = () => engine.resize();
- addEventListener('resize', this._resize);
- addEventListener('pagehide', this._onUnload, { once: true });
- if (typeof ResizeObserver !== 'undefined') {
- this._ro = new ResizeObserver(() => engine.resize());
- this._ro.observe(canvas.parentElement || canvas);
- }
- this.build();
- }
- /** 当前网格顶点/索引统计(验收用) */
- stats() {
- const m = this.mesh;
- if (!m) return null;
- let pm = 0;
- for (const e of this._parts || []) if (e.mesh && !e.mesh.isDisposed()) pm += e.mesh.getTotalVertices();
- return { positions: m.getTotalVertices(), indices: m.getTotalIndices(), parts: this._parts ? this._parts.length : 0, partVertices: pm, params: { ...this.params } };
- }
- setParams(patch) {
- Object.assign(this.params, patch);
- if (!this._raf) {
- this._raf = requestAnimationFrame(() => {
- this._raf = 0;
- this.build();
- this._onChange?.();
- });
- }
- }
- build() {
- const B = this.B;
- if (this.mesh) { this.mesh.dispose(); this.mesh = null; }
- try {
- this.mesh = this.product.shape?.type === 'rect' ? this._buildRect() : this._buildLathe();
- } catch (e) {
- console.warn('[viewer] 重建失败', e);
- return;
- }
- this.mesh.material = this._material();
- // 把模型放到地台上:包围盒最小 z → 0,水平居中
- const bb = this.mesh.getBoundingInfo().boundingBox;
- const min = bb.minimumWorld, max = bb.maximumWorld;
- this.mesh.position = new B.Vector3(-(min.x + max.x) / 2, -(min.y + max.y) / 2, -min.z);
- const size = Math.max(max.x - min.x, max.y - min.y, max.z - min.z);
- if (!this._framed) {
- this.camera.radius = size * 1.9;
- this.camera.target = new B.Vector3(0, 0, (max.z - min.z) / 2);
- camSnapshot(this.camera, this._home);
- this._framed = true;
- }
- if (this._parts.length) this._layoutParts();
- if (this.selUid) this.applySelection(this.selUid);
- return this.mesh;
- }
- /* =========================================================
- 结构件:渲染 / 选中 / 高亮 / 拖动 / 聚焦
- ========================================================= */
- /** 壳体落位包络(结构件拖动与贴壁用):圆件 {kind:'cyl',r,floor,top},方件 {kind:'rect',halfX,halfZ,floor,top} */
- get cav() {
- const c = cavity(this.product.shape?.type, this.params);
- this._cavCache = { ...c, h: Number(this.params.height) || 8, w: Number(this.params.dTop) || 40 };
- return this._cavCache;
- }
- /** 壳体渲染包围盒(世界坐标) */
- shellBounds() {
- const m = this.mesh;
- if (!m) return { min: new this.B.Vector3(-10, 0, -10), max: new this.B.Vector3(10, 10, 10) };
- const bb = m.getBoundingInfo().boundingBox;
- return { min: bb.minimumWorld.clone(), max: bb.maximumWorld.clone(), center: bb.centerWorld.clone() };
- }
- /** 世界坐标 → 壳体局部坐标(X 右 / Y 上 / Z 前,原点在壳底中心) */
- _toLocal(v) {
- const m = this.mesh;
- if (!m) return { x: v.x, y: v.y, z: v.z };
- const p = m.position;
- return { x: v.x - p.x, y: v.y - p.y, z: v.z - p.z };
- }
- /** 全量重建结构件(增删 / 改参数 / 产品切换时调用;单件量小,直接重建,不节流) */
- setParts(parts = []) {
- const B = this.B;
- for (const e of this._parts) if (e.mesh && !e.mesh.isDisposed()) e.mesh.dispose();
- this._parts = [];
- for (const part of parts) {
- let pm = null;
- try { pm = primMesh({ ...part.params, type: part.type }).part; } catch (e) { console.warn('[viewer] 结构件网格失败', part.uid, e); continue; }
- const mesh = new B.Mesh('part:' + part.uid, this.scene);
- const vd = new B.VertexData();
- vd.positions = Array.from(pm.positions);
- vd.indices = Array.from(pm.indices);
- const nrm = [];
- B.VertexData.ComputeNormals(vd.positions, vd.indices, nrm);
- vd.normals = nrm;
- vd.applyToMesh(mesh, false);
- const mat = new B.StandardMaterial('pm:' + part.uid, this.scene);
- const cut = isCutType(part.type);
- mat.diffuseColor = cut ? new B.Color3(0.98, 0.45, 0.25) : new B.Color3(0.16, 0.46, 0.9);
- mat.specularColor = new B.Color3(0.3, 0.3, 0.32);
- mat.emissiveColor = cut ? new B.Color3(0.28, 0.1, 0.04) : new B.Color3(0.04, 0.12, 0.3);
- if (cut) mat.alpha = 0.55;
- mat.backFaceCulling = false;
- mesh.material = mat;
- mesh.isPickable = true;
- mesh.metadata = { uid: part.uid, kind: 'part' };
- this._parts.push({ part, mesh, base: { positions: vd.positions, indices: vd.indices }, mat, cut });
- }
- this._layoutParts();
- this.applySelection(this.selUid);
- return this._parts;
- }
- /** 单个件的 params / at / rotY 变了:只重建这一件 */
- updatePart(part) {
- const i = this._parts.findIndex((e) => e.part.uid === part.uid);
- if (i < 0) return this.setParts([...this._parts.map((e) => e.part), part]);
- const list = this._parts.map((e) => e.part);
- list[i] = part;
- this.setParts(list);
- return this._parts.find((e) => e.part.uid === part.uid);
- }
- /**
- * 把件的局部网格(原点在件中心、Y 向上)摆到壳体坐标:
- * mirror(X 取反)→ 绕 Y 旋转 → 平移到 at(at.y = 件底面高度)。
- * 壳体相对网格有偏移 → 再统一加网格位移;结构件尺寸很小,直接烘焙进顶点后 world = identity,
- * 这样拖动平移、包围盒、拾取都不受父节点影响。
- */
- _layoutParts() {
- const B = this.B;
- const off = this.mesh ? this.mesh.position : new B.Vector3(0, 0, 0);
- for (const e of this._parts) {
- const part = e.part;
- const p = e.base.positions.slice();
- if (part.mirror) for (let j = 0; j < p.length; j += 3) p[j] = -p[j];
- const a = (Number(part.rotY) || 0) * DEG, c = Math.cos(a), s = Math.sin(a);
- const half = this._partHalfHeight(part);
- const tx = Number(part.at?.x) || 0, ty = Number(part.at?.y) || 0, tz = Number(part.at?.z) || 0;
- for (let j = 0; j < p.length; j += 3) {
- const x = p[j], y = p[j + 1], z = p[j + 2];
- const X = x * c + z * s, Z = -x * s + z * c;
- p[j] = X + tx + off.x;
- p[j + 1] = y + ty + half + off.y;
- p[j + 2] = Z + tz + off.z;
- }
- e.mesh.setVerticesData(this.B.VertexBuffer.PositionKind, p, false);
- e.mesh.refreshBoundingInfo();
- e.mesh.isVisible = part.visible !== false;
- }
- }
- _partHalfHeight(part) {
- const p = part.params || {};
- return Math.max(0.1, Number(p.h) || 1) / 2;
- }
- /**
- * 选中高亮:选中件 emissive 亮蓝 + 其余件 alpha 0.25。
- * uid 为空 → 恢复全部不透明、无选中色。
- */
- applySelection(uid) {
- this.selUid = uid || null;
- for (const e of this._parts) {
- if (!e.mesh || e.mesh.isDisposed()) continue;
- const sel = this.selUid && e.part.uid === this.selUid;
- if (this.selUid) {
- e.mesh.visibility = sel ? 1 : 0.25;
- 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));
- } else {
- e.mesh.visibility = 1;
- 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);
- }
- }
- }
- /** 件中心的壳体局部坐标 */
- partCenter(part) {
- return { x: Number(part.at?.x) || 0, y: (Number(part.at?.y) || 0) + this._partHalfHeight(part), z: Number(part.at?.z) || 0 };
- }
- /** 相机聚焦到某件(壳体局部坐标),半径按件尺寸收紧 */
- focusPart(part) {
- const c = this.partCenter(part);
- const fp = footprint(part) * 2, h = this._partHalfHeight(part) * 2;
- const r = Math.max(14, Math.max(fp, h) * 3.2);
- const tgt = this.mesh ? this.mesh.position.clone() : this.B.Vector3.Zero();
- tgt.addInPlace(new this.B.Vector3(c.x, c.y, c.z));
- const cam = this.camera;
- cam.setTarget(tgt);
- cam.radius = Math.min(cam.upperRadiusLimit, r);
- }
- /** 回到全局视图(首次自动取景的机位) */
- homeView(instant = true) {
- const cam = this.camera;
- const from = { alpha: cam.alpha, beta: cam.beta, radius: cam.radius, target: cam.target.clone() };
- const to = this._home;
- if (instant) {
- cam.alpha = to.alpha; cam.beta = to.beta; cam.radius = to.radius; cam.target.copyFrom(to.target);
- return;
- }
- const B = this.B, t0 = performance.now(), dur = 320;
- const step = () => {
- const k = Math.min(1, (performance.now() - t0) / dur), e = 1 - Math.pow(1 - k, 3);
- cam.alpha = from.alpha + (to.alpha - from.alpha) * e;
- cam.beta = from.beta + (to.beta - from.beta) * e;
- cam.radius = from.radius + (to.radius - from.radius) * e;
- cam.target.copyFrom(B.Vector3.Lerp(from.target, to.target, e));
- if (k < 1) requestAnimationFrame(step);
- };
- requestAnimationFrame(step);
- }
- /** 拖动落点:靠内壁 1.5mm 内贴到留 0.5mm 余量;否则按 step 取整 */
- dragSnap(part, x, z, step = 1) {
- const cav = this.cav;
- return snapDrag(cav, { ...part.params, x, z }, x, z, step, 1.5, 0.5);
- }
- /* ---------- 拾取 / 拖动 ---------- */
- _pickAt(ev) {
- const B = this.B, scene = this.scene;
- if (!scene) return null;
- const rect = this.canvas.getBoundingClientRect();
- const x = ev.clientX - rect.left, y = ev.clientY - rect.top;
- const hit = scene.pick(x, y, (m) => m.isPickable && m.isVisible !== false && m.isEnabled(), false, scene.activeCamera);
- return hit && hit.hit ? hit : null;
- }
- _bindPicking(canvas) {
- const B = this.B;
- /** 水平面(世界 Y = y),拖动投影用;平面运行中不动,取 p0 预建 */
- this._planeAt = (y) => B.Plane.FromPositionAndNormal(new B.Vector3(0, y, 0), new B.Vector3(0, 1, 0));
- const down = (ev) => {
- if (ev.button !== undefined && ev.button > 0) return; // 只处理主键 / 单指
- if (this._drv) return;
- const hit = this._pickAt(ev);
- const uid = hit?.pickedMesh?.metadata?.uid;
- if (!uid) return; // 空白处:交给相机旋转,松手再判点空白
- ev.stopImmediatePropagation();
- ev.preventDefault();
- const part = this._parts.find((e) => e.part.uid === uid)?.part;
- if (!part) return;
- if (part.visible === false) return;
- this.camera.detachControl(); // 拖动时锁住相机
- const y = this.mesh.position.y + (Number(part.at?.y) || 0);
- const pl = this._planeAt(y);
- const ray = this.scene.createPickingRay(ev.clientX - canvas.getBoundingClientRect().left, ev.clientY - canvas.getBoundingClientRect().top, B.Matrix.Identity(), this.camera);
- const p0 = ray.intersectsPlane(pl);
- this._drv = {
- uid, part, pl, p0, moved: false,
- start: { x: Number(part.at?.x) || 0, z: Number(part.at?.z) || 0 },
- sx: ev.clientX, sy: ev.clientY,
- };
- this.onSelect?.(uid, this._parts.find((e) => e.part.uid === uid)?.mesh);
- const move = (e2) => this._onDragMove(e2);
- const up = () => { this._onDragUp(); };
- canvas.addEventListener('pointermove', move);
- canvas.addEventListener('pointerup', up);
- canvas.addEventListener('pointercancel', up);
- this._drvCleanup = () => { canvas.removeEventListener('pointermove', move); canvas.removeEventListener('pointerup', up); canvas.removeEventListener('pointercancel', up); };
- };
- // 捕获阶段:在 ArcRotateCamera 的 canvas 监听之前截停
- canvas.addEventListener('pointerdown', down, true);
- // 点空白:pointerup 时若没拖动 → 失焦选中
- const voidDown = (ev) => {
- if (ev.button !== undefined && ev.button > 0) return;
- this._maybeVoid = { x: ev.clientX, y: ev.clientY, t: performance.now() };
- };
- const voidUp = (ev) => {
- const v = this._maybeVoid; this._maybeVoid = null;
- if (!v || this._drv) return;
- if (Math.hypot(ev.clientX - v.x, ev.clientY - v.y) > 6 || performance.now() - v.t > 500) return;
- if (this._pickAt(ev)?.pickedMesh?.metadata?.uid) return;
- this.bgPointer?.();
- };
- canvas.addEventListener('pointerdown', voidDown);
- canvas.addEventListener('pointerup', voidUp);
- }
- _onDragMove(ev) {
- const d = this._drv;
- if (!d) return;
- if (!d.moved && Math.hypot(ev.clientX - d.sx, ev.clientY - d.sy) < 4) return;
- d.moved = true;
- const rect = this.canvas.getBoundingClientRect();
- const ray = this.scene.createPickingRay(ev.clientX - rect.left, ev.clientY - rect.top, this.B.Matrix.Identity(), this.camera);
- const hit = ray.intersectsPlane(d.pl);
- if (!hit) return;
- const p = this._toLocal(hit);
- const s = this._snapStep || 1;
- const q = this.dragSnap(d.part, p.x, p.z, s);
- if (!this._moveRaf) {
- this._moveRaf = requestAnimationFrame(() => {
- this._moveRaf = 0;
- if (!this._drv) return;
- const dr = this._drv;
- dr.part = { ...dr.part, at: { ...dr.part.at, x: q.x, z: q.z } };
- const e = this._parts.find((x) => x.part.uid === dr.uid);
- if (e) { e.part = dr.part; this._layoutParts(); }
- this.onDragMove?.(dr.uid, { x: q.x, z: q.z });
- });
- }
- d.last = { x: q.x, z: q.z };
- }
- _onDragUp() {
- const d = this._drv;
- this._drvCleanup?.();
- this._drvCleanup = null;
- if (this._moveRaf) { cancelAnimationFrame(this._moveRaf); this._moveRaf = 0; }
- this.camera.attachControl(this.canvas, true); // 松手交还相机
- this._drv = null;
- if (!d) return;
- if (d.moved) {
- const at = d.last ? { x: d.last.x, z: d.last.z } : { x: d.start.x, z: d.start.z };
- this.onDragEnd?.(d.uid, at);
- }
- }
- /** 由页面把「已选中件」的最新实例同步给 viewer(拖动后 page 侧回写) */
- syncPart(part) {
- const e = this._parts.find((x) => x.part.uid === part.uid);
- if (!e) return;
- e.part = part;
- this._layoutParts();
- }
- /* =========================================================
- 导出:STL / 截图
- ========================================================= */
- /** 收集三角面(世界坐标):壳体 + 可见结构件;onlyUid 时只取该结构件 */
- collectTriangles(onlyUid = null) {
- const tris = [];
- const pushMesh = (mesh, part) => {
- if (!mesh || mesh.isDisposed()) return;
- const pos = mesh.getVerticesData(this.B.VertexBuffer.PositionKind);
- const idx = mesh.getIndices();
- const wm = mesh.computeWorldMatrix(true);
- const n = idx ? idx.length : pos.length / 3;
- for (let i = 0; i < n; i += 3) {
- const a = new this.B.Vector3(pos[idx[i] * 3], pos[idx[i] * 3 + 1], pos[idx[i] * 3 + 2]);
- const b = new this.B.Vector3(pos[idx[i + 1] * 3], pos[idx[i + 1] * 3 + 1], pos[idx[i + 1] * 3 + 2]);
- const c = new this.B.Vector3(pos[idx[i + 2] * 3], pos[idx[i + 2] * 3 + 1], pos[idx[i + 2] * 3 + 2]);
- this.B.Vector3.TransformCoordinatesToRef(a, wm, a);
- this.B.Vector3.TransformCoordinatesToRef(b, wm, b);
- this.B.Vector3.TransformCoordinatesToRef(c, wm, c);
- const u = b.subtract(a), w = c.subtract(a);
- const nn = this.B.Vector3.Cross(u, w);
- tris.push({ a, b, c, n: nn.lengthSquared() > 1e-12 ? nn.normalize() : new this.B.Vector3(0, 1, 0), uid: part?.uid || 'shell' });
- }
- };
- if (onlyUid) {
- const e = this._parts.find((x) => x.part.uid === onlyUid);
- if (e) pushMesh(e.mesh, e.part);
- } else {
- pushMesh(this.mesh, null);
- for (const e of this._parts) if (e.mesh.isVisible) pushMesh(e.mesh, e.part);
- }
- return tris;
- }
- /** 二进制 STL(小端 float32);返回 ArrayBuffer */
- exportSTL(onlyUid = null) {
- const tris = this.collectTriangles(onlyUid);
- const buf = new ArrayBuffer(84 + tris.length * 50);
- const view = new DataView(buf);
- const header = 'Pocket Hardware Lab · FmodeCode';
- for (let i = 0; i < Math.min(80, header.length); i++) view.setUint8(i, header.charCodeAt(i));
- view.setUint32(80, tris.length, true);
- let o = 84;
- for (const t of tris) {
- 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;
- 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; }
- view.setUint16(o, 0, true); o += 2;
- }
- return { buffer: buf, triangles: tris.length };
- }
- /**
- * 截图(scale 倍分辨率):优先 Tools.CreateScreenshot(render target 离屏放大),
- * GPU / 无头环境下 render-target 路径会抛「ScreenshotTools」,再退到 canvas.toDataURL + 像素放大。
- * 返回 dataURL(image/png)或 null。
- */
- async screenshot(scale = 2) {
- const B = this.B;
- const rt = this.canvas.width;
- let data = await new Promise((resolve) => {
- let done = false;
- try {
- B.Tools.CreateScreenshot(this.engine, this.camera, { precision: scale }, (d) => { done = true; resolve(d); }, 'image/png');
- } catch (e) {
- console.warn('[viewer] 截图 render-target 不可用,改用画布像素', e?.message || e);
- resolve(null);
- }
- setTimeout(() => { if (!done) resolve(null); }, 1500);
- });
- if (!data) {
- try {
- this.scene.render();
- data = this.canvas.toDataURL('image/png');
- } catch (e) { console.warn('[viewer] 画布截图失败', e); return null; }
- if (!data || data.length < 100) return null;
- if (scale > 1) {
- const up = await scalePng(data, scale);
- if (up) data = up;
- }
- }
- void rt;
- return data;
- }
- _rectMaterial() {
- const B = this.B;
- const m = new B.StandardMaterial('rectMat', this.scene);
- m.diffuseColor = new B.Color3(0.68, 0.69, 0.71);
- m.specularColor = new B.Color3(0.35, 0.35, 0.35);
- m.specularPower = 64;
- m.backFaceCulling = false;
- return m;
- }
- _material() {
- const B = this.B;
- // StandardMaterial:漫反射 + 高光 + 边缘 Fresnel,无外部环境贴图也能看出曲面明暗
- const mat = new B.StandardMaterial('shellMat', this.scene);
- const id = this.product.materials?.[0];
- const alu = /^al-|^ti$/.test(id || '');
- mat.diffuseColor = alu ? new B.Color3(0.72, 0.73, 0.75) : new B.Color3(0.8, 0.8, 0.82);
- mat.specularColor = alu ? new B.Color3(0.65, 0.65, 0.68) : new B.Color3(0.22, 0.22, 0.24);
- mat.specularPower = alu ? 96 : 24;
- mat.emissiveColor = new B.Color3(0.12, 0.12, 0.13);
- mat.backFaceCulling = false; // 截面开放处也能看到内壁
- return mat;
- }
- _buildLathe() {
- const B = this.B;
- const prof = roundProfile(this.params);
- this.profile = prof;
- let pts = simplify(prof.points.filter((p) => p[0] > 1e-4));
- // 母线是「右半截面」,首尾都在轴上 → 首尾各补一个轴点闭合外表面
- if (pts.length > 2) pts = [[0, pts[0][1]], ...pts, [0, pts[pts.length - 1][1]]];
- const vd = latheMesh(B, pts, 112);
- const mesh = new B.Mesh('shell', this.scene);
- vd.applyToMesh(mesh, true);
- try {
- // 法线统一朝外(回转体逐段朝外法向 = 指向远离轴线的凸侧)
- mesh.flipFaces(latheWinding(pts) > 0);
- const normals = [];
- B.VertexData.ComputeNormals(mesh.getVerticesData(B.VertexBuffer.PositionKind), mesh.getIndices(), normals);
- mesh.setVerticesData(B.VertexBuffer.NormalKind, normals);
- } catch (e) { console.warn('[viewer] 法线修正跳过', e); }
- return mesh;
- }
- _buildRect() {
- const B = this.B;
- const p = this.params;
- const L = Math.max(4, +p.length || 40), W = Math.max(4, +p.dTop || 30), H = Math.max(2, +p.height || 8);
- const wall = Math.max(0.4, +p.wall || 1.5);
- const cap = Math.min(Math.max(0, +p.capR || 0), H / 2 - 0.3);
- // 圆角矩形闭合轮廓(逆时针,中心在原点)
- const loop = (l, w, r) => {
- const hw = l / 2, hh = w / 2, rr = Math.max(0.05, Math.min(r, hw - 0.05, hh - 0.05));
- const pts = [];
- 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)]); } };
- arc(hw - rr, -hh + rr, -Math.PI / 2, 0);
- arc(hw - rr, hh - rr, 0, Math.PI / 2);
- arc(-hw + rr, hh - rr, Math.PI / 2, Math.PI);
- arc(-hw + rr, -hh + rr, Math.PI, 1.5 * Math.PI);
- return pts;
- };
- const outer = loop(L, W, Math.max(0, +p.cornerR || 0));
- const inner = loop(L - 2 * wall, W - 2 * wall, Math.max(0.5, (+p.cornerR || 0) - wall));
- const n = outer.length;
- const zTop = Math.max(0.6, H - Math.max(0.6, wall)); // 内腔顶(壳底)
- const zCap = zTop - cap; // 顶部圆角起点
- // 水平剖面 = 一串「圆角矩形环」,相邻环之间拉出面:外壁 ↑ → 顶面环带 → 内壁 ↓;底环带封底
- const rings = [
- outer.map(([x, y]) => [x, y, 0]),
- outer.map(([x, y]) => [x, y, zCap]),
- outer.map(([x, y]) => [x, y, zTop]),
- inner.map(([x, y]) => [x, y, zTop]),
- inner.map(([x, y]) => [x, y, 0]),
- ];
- const positions = [], indices = [];
- const add = (x, y, z) => { positions.push(x, y, z); return positions.length / 3 - 1; };
- const ids = rings.map((ring) => ring.map(([x, y, z]) => add(x, y, z)));
- void zTop;
- for (let r = 0; r < ids.length - 1; r++) {
- const A = ids[r], Bn = ids[r + 1];
- for (let i = 0; i < n; i++) {
- const j = (i + 1) % n;
- indices.push(A[i], A[j], Bn[j], A[i], Bn[j], Bn[i]);
- }
- }
- // 底环带(底面:从内环到外环)
- const ob = outer.map(([x, y]) => add(x, y, 0));
- const ib = inner.map(([x, y]) => add(x, y, 0));
- 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]); }
- const vd = new B.VertexData();
- vd.positions = positions; vd.indices = indices;
- const normals = []; B.VertexData.ComputeNormals(positions, indices, normals); vd.normals = normals;
- const mesh = new B.Mesh('shell', this.scene);
- vd.applyToMesh(mesh, true);
- mesh.material = this._rectMaterial();
- mesh.refreshBoundingInfo();
- return mesh;
- }
- /** 双击复位:退出选中态,相机回到首次取景 */
- reset(animate = false) {
- if (this.selUid) { this.applySelection(null); this.onSelect?.(null, null); }
- this.homeView(!animate);
- }
- dispose() {
- this._alive = false;
- if (this._raf) { cancelAnimationFrame(this._raf); this._raf = 0; }
- removeEventListener('resize', this._resize);
- removeEventListener('pagehide', this._onUnload);
- if (this._ro) { this._ro.disconnect(); this._ro = null; }
- if (this._dbl) this.canvas.removeEventListener('dblclick', this._dbl);
- if (this._pd) this.canvas.removeEventListener('pointerdown', this._pd);
- this._drvCleanup?.();
- if (this._moveRaf) cancelAnimationFrame(this._moveRaf);
- this._parts = [];
- this.selUid = null;
- try { this.camera?.dispose(); } catch { /* noop */ }
- try { this.scene?.dispose(); } catch { /* noop */ }
- try { this.engine?.stopRenderLoop(); this.engine?.dispose(); } catch { /* noop */ }
- this.mesh = null;
- this.scene = null;
- this.engine = null;
- this.camera = null;
- }
- }
- /** 母线绕轴旋转后按右手系判断三角形绕向(鞋带和 > 0 表示需翻转) */
- function latheWinding(pts) {
- let area = 0;
- for (let i = 0; i < pts.length; i++) {
- const [r0, z0] = pts[i], [r1, z1] = pts[(i + 1) % pts.length];
- area += r0 * z1 - r1 * z0;
- }
- return area;
- }
- function camSnapshot(cam, into) {
- into.alpha = cam.alpha; into.beta = cam.beta; into.radius = cam.radius;
- if (into.target) into.target.copyFrom(cam.target); else into.target = cam.target.clone();
- }
- /** 只用于测试半径插值导出的薄封装(避免循环依赖告警) */
- export { radiusAtHeight };
- /** 按比例把 canvas 截图 dataURL 缩放成 PNG(无头 / GPU 限制走不通时兜底) */
- export function scalePng(dataUrl, scale = 2) {
- return new Promise((resolve) => {
- const img = new Image();
- img.onload = () => {
- const c = document.createElement('canvas');
- c.width = Math.round(img.width * scale); c.height = Math.round(img.height * scale);
- const ctx = c.getContext('2d');
- ctx.imageSmoothingQuality = 'high';
- ctx.drawImage(img, 0, 0, c.width, c.height);
- resolve(c.toDataURL('image/png'));
- };
- img.onerror = () => resolve(null);
- img.src = dataUrl;
- });
- }
|