Files

146 lines
9.0 KiB
JavaScript

import { DoubleSide, Matrix4, Quaternion, Ray, Vector3 } from 'three';
import { MeshBVH } from 'three-mesh-bvh';
import { screwHead } from './numbered-axis.mjs';
const workAxis = new Vector3(0, 0, -1);
const angles = Array.from({ length: 72 }, (_, index) => index * Math.PI / 36);
const meshPoints = meshes => meshes.flatMap(mesh => {
const vertices = mesh.getAttribute('position');
return Array.from({ length: vertices.count }, (_, index) => new Vector3().fromBufferAttribute(vertices, index));
});
function capHull(points) {
const sorted = points.sort((a, b) => a.x - b.x || a.y - b.y);
const half = vertices => {
const result = [];
for (const point of vertices) {
while (result.length >= 2) {
const [a, b] = result.slice(-2);
const turn = (b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x);
if (turn > 1e-12) break;
result.pop();
}
result.push(point);
}
return result.slice(0, -1);
};
return [...half(sorted), ...half(sorted.reverse())];
}
// Supported key exports point the working end down local Z. Verify the six
// vertices at the tip before using its center and measured across-flats size.
export function measureHexKey(meshes, file) {
const points = meshPoints(meshes);
const endZ = points.reduce((min, point) => Math.min(min, point.z), Infinity);
const cap = new Map(points.filter(point => Math.abs(point.z - endZ) < 1e-7)
.map(point => [`${point.x.toFixed(7)},${point.y.toFixed(7)}`, point]));
const corners = capHull([...cap.values()]);
if (corners.length !== 6) throw new Error('扳手 GLB 的工作端须朝局部 -Z,末端须有完整的六角截面');
const tip = corners.reduce((center, point) => center.add(point), new Vector3()).divideScalar(6);
const flatCenters = corners.map((point, index) => point.clone().add(corners[(index + 1) % 6]).multiplyScalar(.5).sub(tip));
const radii = flatCenters.map(point => point.length());
const radius = Math.min(...radii);
if (radius <= 0 || Math.max(...radii) > radius * 1.03 || corners.some(point =>
Math.abs(point.distanceTo(tip) / radius - 2 / Math.sqrt(3)) > .04)) {
throw new Error('扳手工作端的六角尺寸无法确认');
}
return { config: { id: 'hex-key', file, tipPosition: tip.toArray(), tipAxis: workAxis.toArray() },
flatDirection: flatCenters[0].normalize(), acrossFlats: radius * 2 };
}
export function measurePhillips(meshes, file) {
const points = meshPoints(meshes);
const z = points.reduce((min, point) => Math.min(min, point.z), Infinity);
const cap = points.filter(point => point.z - z < 1e-7);
const tip = cap.reduce((center, point) => center.add(point), new Vector3()).divideScalar(cap.length);
tip.z = z;
const end = points.filter(point => point.z - z <= .0026);
const acrossFlats = 2 * end.reduce((max, point) => Math.max(max, Math.hypot(point.x-tip.x,point.y-tip.y)), 0);
if (cap.length < 3 || !(acrossFlats > 0)) throw new Error('十字扳手 GLB 的工作端无法确认');
return { config: { id: 'phillips', file, tipPosition: tip.toArray(), tipAxis: workAxis.toArray() }, acrossFlats };
}
export function hexInstallation(local, sourceMatrix, placement, result, tool, { scaleToSocket = false } = {}) {
if (!['clear-to-seating', 'visual-thread-fit', 'visual-bore-axis'].includes(result.status)) return { reason: '安装方向未确认' };
const sourceScale = new Vector3().setFromMatrixScale(sourceMatrix).toArray();
if (sourceMatrix.determinant() <= 0 || [sourceScale, placement.scale].some(scale => Math.max(...scale) - Math.min(...scale) > Math.max(...scale) * 1e-6)) {
return { reason: '零件缩放不适合拧转' };
}
const head = screwHead(local);
if (!head) return { reason: '螺丝头方向不明确' };
const outward = head.vector;
const inward = outward.clone().negate();
const face = local.boundingBox.getCenter(new Vector3());
const axisIndex = outward.toArray().findIndex(value => value !== 0);
face.setComponent(axisIndex, (outward.getComponent(axisIndex) > 0 ? local.boundingBox.max : local.boundingBox.min).getComponent(axisIndex));
local.clearGroups();
const bvh = new MeshBVH(local);
const margin = .0002 / sourceScale[0];
const floor = bvh.raycastFirst(new Ray(face.clone().addScaledVector(outward, margin), inward), DoubleSide);
const depth = (floor?.distance ?? 0) - margin;
if (depth < .00025 / sourceScale[0]) return { reason: '未找到螺丝头内的沉孔' };
const center = face.clone().addScaledVector(inward, Math.min(depth * .5, .001 / sourceScale[0]));
const x = new Vector3().crossVectors(inward, axisIndex === 0 ? new Vector3(0, 1, 0) : new Vector3(1, 0, 0)).normalize();
const y = new Vector3().crossVectors(inward, x);
const samples = angles.map(angle => {
const ray = x.clone().multiplyScalar(Math.cos(angle)).addScaledVector(y, Math.sin(angle));
const hit = bvh.raycastFirst(new Ray(center, ray), DoubleSide);
return { ray, hit };
});
if (samples.some(sample => !sample.hit?.face)) return { reason: '六角孔壁不完整' };
const nearest = samples.reduce((a, b) => a.hit.distance < b.hit.distance ? a : b);
const flat = nearest.hit.face.normal.clone().projectOnPlane(inward).normalize();
if (flat.dot(nearest.ray) < 0) flat.negate();
const radius = nearest.hit.distance * flat.dot(nearest.ray);
if (!(radius > 0)) return { reason: '六角孔尺寸无法确认' };
const normals = Array.from({ length: 6 }, (_, index) => flat.clone().applyAxisAngle(inward, index * Math.PI / 3));
if (samples.some(({ ray, hit }) => Math.abs(hit.distance * Math.max(...normals.map(normal => normal.dot(ray))) / radius - 1) > .06)) {
return { reason: '沉孔轮廓与六角不匹配' };
}
const acrossFlats = 2 * radius * sourceScale[0];
if (!scaleToSocket && (tool.acrossFlats > acrossFlats * 1.005 || tool.acrossFlats < acrossFlats * .85)) return { reason: '扳手尺寸与六角孔不匹配', acrossFlats };
const axis = inward.transformDirection(sourceMatrix);
const partFlat = flat.transformDirection(sourceMatrix);
const toolBasis = new Matrix4().makeBasis(tool.flatDirection, new Vector3().crossVectors(workAxis, tool.flatDirection), workAxis);
const socketBasis = new Matrix4().makeBasis(partFlat, new Vector3().crossVectors(axis, partFlat), axis);
const toolQuaternion = new Quaternion().setFromRotationMatrix(socketBasis.multiply(toolBasis.invert())).normalize();
const travel = Math.min(.0012, Math.hypot(...result.offset) / placement.scale[0]);
if (travel < .00001) return { reason: '拧入行程不足' };
return { acrossFlats, installation: { type: 'screw', toolId: tool.config.id, axis: axis.toArray(),
socketPosition: center.applyMatrix4(sourceMatrix).toArray(), toolQuaternion: toolQuaternion.toArray(),
...(scaleToSocket ? {toolScale: Math.min(10, Math.max(.1, acrossFlats * .95 / tool.acrossFlats))} : {}),
direction: 'clockwise', turns: 3, travel } };
}
// These supplied instructions specify the tool by name. Where the export has
// no usable socket, place the bit at the head face for the display animation.
export function namedToolInstallation(local, sourceMatrix, placement, result, tool) {
const sourceScale = new Vector3().setFromMatrixScale(sourceMatrix).toArray();
if (sourceMatrix.determinant() <= 0 || [sourceScale, placement.scale].some(scale =>
Math.max(...scale) - Math.min(...scale) > Math.max(...scale) * 1e-6)) return { reason: '零件缩放不适合拧转' };
const head = screwHead(local);
if (!head || !result.headDirection) return { reason: '螺丝头方向不明确' };
// An unverified full insertion route should not be used for display. Keep
// the screw at the seating point while the selected tool demonstrates a turn.
const offset = Math.hypot(...result.offset) > 0 ? result.offset : result.headDirection.map(v => v * .00015);
const travel = Math.min(.0012, Math.hypot(...offset) / placement.scale[0]);
if (travel < .00001) return { reason: '拧入行程不足' };
if (tool.config.id === 'hex-key') {
const measured = hexInstallation(local, sourceMatrix, placement, { ...result, status: 'clear-to-seating', offset }, tool, { scaleToSocket: true });
if (measured.installation) return { ...measured, offset, docking: 'socket' };
}
const outward = head.vector;
const axisIndex = outward.toArray().findIndex(value => value !== 0);
const bounds = local.boundingBox;
const face = bounds.getCenter(new Vector3());
face.setComponent(axisIndex, (outward.getComponent(axisIndex) > 0 ? bounds.max : bounds.min).getComponent(axisIndex));
const size = bounds.getSize(new Vector3()).toArray().filter((_, index) => index !== axisIndex);
const toolScale = Math.min(10, Math.max(.1, Math.min(...size) * sourceScale[0] * .5 / tool.acrossFlats));
const axis = outward.clone().negate().transformDirection(sourceMatrix);
return { offset, docking: 'head-face', installation: { type:'screw', toolId:tool.config.id, axis:axis.toArray(),
socketPosition:face.applyMatrix4(sourceMatrix).toArray(), toolQuaternion:new Quaternion().setFromUnitVectors(workAxis,axis).toArray(),
toolScale, direction:'clockwise', turns:3, travel } };
}