Files
vibemake/scripts/generate-numbered-assembly.mjs
T

236 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Offline: only validated JSON is consumed by the existing community viewer.
import { createHash } from 'node:crypto';
import { copyFileSync, readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { parseArgs } from 'node:util';
import { strict as assert } from 'node:assert';
import { NodeIO } from '@gltf-transform/core';
import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
import draco from 'draco3dgltf';
import { BufferAttribute, BufferGeometry, Matrix4, Quaternion, Vector3 } from 'three';
import { assetUrl, validateEmbeddedGlb, validatePackage, MAX_PACKAGE_JSON_BYTES } from '../js/experience-packages.js';
import { bindAssemblyFiles, resourceIndex } from '../js/project-resources.js';
import { numberedInput } from './lib/numbered-parts.mjs';
import { numberedPartId, numberedSchedule } from './lib/numbered-schedule.mjs';
import { collider } from './lib/assembly-axis-planner.mjs';
import { planEntry, planGroupEntry } from './lib/numbered-axis.mjs';
import { hexInstallation, measureHexKey, measurePhillips, namedToolInstallation } from './lib/numbered-tool.mjs';
const hash = data => createHash('sha256').update(data).digest('hex');
const clean = a => a.map(x=>Math.abs(x)<1e-14?0:x);
function rigidMeshes(doc, label) {
const r = doc.getRoot(), scene = r.getDefaultScene() ?? r.listScenes()[0], nodes = [];
assert.ok(scene && !r.listAnimations().length, `${label}:需要静态装配场景`);
scene.traverse(n=>{
if (!n.getMesh()) return;
assert.ok(!n.getSkin() && !n.getWeights().length && n.getMesh().listPrimitives().every(p=>!p.listTargets().length && p.getMode()===4), `${label}:仅支持刚性三角网格`);
nodes.push(n);
});
return nodes;
}
function geometry(mesh) {
const pos=[], idx=[], xyz=[];
for (const p of mesh.listPrimitives()) {
const a=p.getAttribute('POSITION'), i=p.getIndices(), base=pos.length/3;
assert.ok(a?.getType()==='VEC3','网格缺少三维顶点');
for(let n=0;n<a.getCount();n++) {
a.getElement(n,xyz); assert.ok(xyz.every(Number.isFinite),'无效顶点'); pos.push(...xyz);
}
const indices=i?.getArray() ?? Array.from({length:a.getCount()},(_,n)=>n);
assert.ok(indices.length%3===0 && indices.every(n=>n>=0 && n<a.getCount()),'无效三角面');
for(const index of indices) idx.push(base+index);
}
assert.ok(idx.length,'空网格');
const g=new BufferGeometry();
g.setAttribute('position',new BufferAttribute(new Float32Array(pos),3));
g.setIndex(new BufferAttribute(new Uint32Array(idx),1));
return g;
}
// Triangle comparison ignores primitive order, winding, indexing and material splits.
// Use exact decoded float32 coordinates: differing exports need explicit review.
function surface(g) {
const pos=g.attributes.position.array, arr=g.index.array, keys=[], vertex=[];
for (let i=0;i<pos.length;i+=3) vertex.push(pos[i]+','+pos[i+1]+','+pos[i+2]);
for (let i=0;i<arr.length;i+=3) keys.push([vertex[arr[i]],vertex[arr[i+1]],vertex[arr[i+2]]].sort().join(';'));
return hash(keys.sort().join('\n'));
}
function pose(source,target,label) {
assert.ok(Math.abs(source.determinant())>1e-15, `${label}:不可逆的分件坐标`);
const m=target.clone().multiply(source.clone().invert());
const p=new Vector3(),q=new Quaternion(),s=new Vector3();
m.decompose(p,q,s); q.normalize();
const r=new Matrix4().compose(p,q,s);
assert.ok(s.toArray().every(x=>x>0) && m.elements.every((x,i)=>Math.abs(x-r.elements[i])<1e-6),`${label}:当前播放器不支持此镜像或剪切变换`);
return { position:p.toArray(),quaternion:q.toArray(),scale:s.toArray() };
}
export async function generate(root, dest, log=console.log, options={}) {
root=path.resolve(root); dest=path.resolve(dest);
const destRel=path.relative(root,dest);
assert.ok(destRel==='..' || destRel.startsWith('..'+path.sep) || path.isAbsolute(destRel),'输出请放在输入目录以外');
assert.ok(!existsSync(dest),'输出目录已存在,请选择新的目录');
const {whole,parts:ordered}=numberedInput(root, options);
const groupNumbers=[...new Set(ordered.map(p=>p.group.number))];
const finalGroup=options.finalGroup === 'last' ? groupNumbers.at(-1) : options.finalGroup;
const grouped=finalGroup !== undefined;
if (grouped) assert.ok(groupNumbers.length > 1 && finalGroup===groupNumbers.at(-1), '分组总装至少需要两个编号部位目录,最后一个目录放总装散件');
if (grouped) assert.ok(ordered.every(item => !item.subgroup && !item.group.revealAll && !item.revealAll), '含小组件或 # 标记的目录请使用按目录和标记装配模式');
const schedule=!grouped && ordered.some(item=>item.revealAll || item.group.revealAll) ? numberedSchedule(ordered) : null;
const io=new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({'draco3d.decoder':await draco.createDecoderModule()});
const read=async name=>{
const bytes=readFileSync(path.resolve(root,name));
validateEmbeddedGlb(bytes.buffer.slice(bytes.byteOffset,bytes.byteOffset+bytes.length));
return {doc:await io.readBinary(bytes),bytes};
};
const ref=await read(whole), allNodes=rigidMeshes(ref.doc,whole);
const wholeOnly=new Set(options.wholeOnlyNodes ?? []);
const nodes=allNodes.filter(node=>!wholeOnly.has(node.getName()));
assert.equal(allNodes.length-nodes.length,wholeOnly.size,'整机专用网格名称缺失或重复');
assert.equal(nodes.length,ordered.length,`整机有 ${nodes.length} 个网格实例,零件文件有 ${ordered.length} 个`);
const byName=new Map(nodes.map(n=>[n.getName(),n]));
assert.ok(byName.size===nodes.length && !byName.has(''),'整机网格节点需要唯一的名称');
const title=path.parse(whole).name;
const raw={schemaVersion:1,kind:'assembly',unit:'meter',title:title+' · 分步装配',displayQuaternion:[0,0,0,1],files:[],parts:[],steps:[]};
const tools=new Map();
for (const [type, filenameOnDisk] of Object.entries(options.namedTools ?? (options.hexKey ? {hex:options.hexKey} : {}))) {
const filename=path.basename(filenameOnDisk);
assert.ok(/\.glb$/i.test(filename) && ordered.every(item => item.path !== filename), '请选择名称与分件不同的工具 GLB');
const {doc,bytes}=await read(path.resolve(filenameOnDisk));
const meshes=rigidMeshes(doc,filename).map(node => geometry(node.getMesh()).applyMatrix4(new Matrix4().fromArray(node.getWorldMatrix())));
const measure=type==='phillips' ? measurePhillips : measureHexKey;
tools.set(type,{ ...measure(meshes,filename), source:filenameOnDisk, file:{path:filename,bytes:bytes.length,sha256:hash(bytes)} });
}
if (grouped) {
raw.playback='grouped-v1';
raw.groups=groupNumbers.slice(0,-1).map(n=>({id:`group-${n}`,label:ordered.find(p=>p.group.number===n).group.path,parts:[]}));
}
if (schedule) { raw.playback='scoped-v1'; raw.groups=schedule.groups; }
const records=[], installed=[], used=new Set(), surfaceCache=new Map();
const groupColliders=new Map();
let joined=false, groupStart=0, scopeStart=0, isolatedStart, previousGroup, previousDirectory;
for (const item of ordered) {
const id=numberedPartId(item), action=schedule?.actions.get(id);
for (const join of action?.joins ?? []) {
const moving=groupColliders.get(join.groupId);
const visible=new Set(join.visibleParts), members=new Set(join.parts);
const obstacles=installed.filter(part=>visible.has(part.id) && !members.has(part.id));
const result=planGroupEntry(moving,obstacles);
raw.steps.push({...join,installOffset:clean(result.offset),pathStatus:result.presentationOnly?'presentation':'checked'});
records.push({id:join.id,label:join.label,groupId:join.groupId,...result});
log(`部件合装 ${join.label}:${result.status}`);
}
if (grouped && item.group.number===finalGroup && !joined) {
const obstacles=[];
for (const group of raw.groups) {
const moving=groupColliders.get(group.id);
const result=planGroupEntry(moving,obstacles);
const step={id:`join-${group.id}`,type:'join',groupId:group.id,label:`${finalGroup} 总装 · 合装${group.label}`,parts:group.parts,installOffset:clean(result.offset),
pathStatus:result.presentationOnly?'presentation':'checked'};
raw.steps.push(step);
records.push({id:step.id,label:step.label,groupId:group.id,...result});
obstacles.push(...moving);
log(`部件合装 ${group.label}:${result.status}`);
}
joined=true;
}
const {doc,bytes}=await read(item.path), loose=rigidMeshes(doc,item.path);
assert.equal(loose.length,1,`${item.path}:每个分件 GLB 应包含一个网格实例,可含多种材质`);
const n=loose[0], target=byName.get(n.getName()) ?? byName.get(item.stem) ?? byName.get(item.name);
assert.ok(target && !used.has(target),`${item.path}:未找到唯一整机实例(分件节点 ${n.getName()}),请核对名称`);
used.add(target);
const local=geometry(n.getMesh()), refMesh=target.getMesh();
if(!surfaceCache.has(refMesh)) surfaceCache.set(refMesh,surface(geometry(refMesh)));
assert.equal(surface(local),surfaceCache.get(refMesh),`${item.path}:与整机实例的解码网格不一致`);
const world=new Matrix4().fromArray(target.getWorldMatrix());
const sourceMatrix=new Matrix4().fromArray(n.getWorldMatrix());
const placement=pose(sourceMatrix,world,item.path);
const moving=collider(id,local.clone().applyMatrix4(world));
const group=raw.groups?.find(g=>g.id===`group-${item.group.number}`);
if (item.group.number!==previousGroup) groupStart=installed.length;
if (item.directory!==previousDirectory) {
scopeStart=item.subgroup==='finish' ? groupStart : installed.length;
isolatedStart=undefined;
}
isolatedStart=item.isolated ? isolatedStart ?? installed.length : undefined;
const start=isolatedStart ?? (item.revealAll || item.group.revealAll ? 0 : scopeStart);
const visibleSet=action && new Set(action.visibleParts);
const previous=visibleSet ? installed.filter(part=>visibleSet.has(part.id)) : isolatedStart !== undefined || !grouped ? installed.slice(start)
: group ? (groupColliders.get(group.id) ?? []) : installed;
const toolType=options.selectTool ? options.selectTool(item.name) : /内六角|socket[ -]head|hex[ -]socket|allen/i.test(item.name) ? 'hex' : undefined;
const tool=tools.get(toolType);
const result=planEntry(moving,local,world,previous,item.name,tool && options.selectTool ? {fastener:true} : undefined);
const toolMatch=tool && (options.selectTool ? namedToolInstallation : hexInstallation)(local,sourceMatrix,placement,result,tool);
previousGroup=item.group.number;
previousDirectory=item.directory;
const visibleParts=action?.visibleParts ?? ((grouped ? item.isolated : start > 0) ? [...previous.map(part=>part.id), id] : undefined);
if (group) {
const members=groupColliders.get(group.id) ?? [];
members.push(moving); groupColliders.set(group.id,members);
if (!schedule) group.parts.push(id);
}
installed.push(moving);
const label=[item.directory,item.stepLabel ?? item.number,item.name].filter(Boolean).join(' · ');
raw.files.push({path:item.path,bytes:bytes.length,sha256:hash(bytes)});
raw.parts.push({id,file:item.path,...placement,installOffset:clean(toolMatch?.offset ?? result.offset),...(result.headDirection?{focusDirection:result.headDirection}:{}),
...(toolMatch?.installation ? {installation:toolMatch.installation} : {})});
raw.steps.push({id:`step-${id.slice(2)}`,label,parts:[id],...(group?{groupId:group.id}:{}),
...(visibleParts ? {visibleParts} : {})});
records.push({id,label,file:item.path,wholeNode:target.getName(),...result,
...(toolMatch ? {toolMatch:{type:toolType,matched:!!toolMatch.installation, reason:toolMatch.reason, acrossFlats:toolMatch.acrossFlats,
docking:toolMatch.docking, presentationOffset:toolMatch.offset && !Math.hypot(...result.offset) ? toolMatch.offset : undefined}} : {})});
log(`${installed.length}/${ordered.length} ${label}:${result.status}`);
}
const toolCount=raw.parts.filter(part=>part.installation).length;
const usedToolIds=new Set(raw.parts.flatMap(part=>part.installation ? [part.installation.toolId] : []));
const usedTools=[...tools.values()].filter(tool=>usedToolIds.has(tool.config.id));
if (toolCount) {
raw.tools=usedTools.map(tool=>tool.config);
raw.files.push(...usedTools.map(tool=>tool.file));
}
const uri='https://assembly.invalid/steps.json';
const pkg=validatePackage(raw,'assembly',uri);
const assemblyOptions={assembly:true};
bindAssemblyFiles(pkg.files,resourceIndex(raw.files.map(f=>({relativePath:f.path,sizeBytes:f.bytes,url:assetUrl(f.path,uri,assemblyOptions)})),assemblyOptions));
let manifest=JSON.stringify(raw,null,2)+'\n';
if (Buffer.byteLength(manifest)>MAX_PACKAGE_JSON_BYTES) manifest=JSON.stringify(raw)+'\n';
assert.ok(Buffer.byteLength(manifest)<=MAX_PACKAGE_JSON_BYTES,'步骤超过播放器 JSON 大小限制');
const review=records.filter(r=>r.status.startsWith('review'));
mkdirSync(dest,{recursive:true});
writeFileSync(path.join(dest,title+'-装配步骤.json'),manifest,{flag:'wx'});
const report={whole,wholeSha256:hash(ref.bytes),steps:raw.steps.length,partCount:ordered.length,groups:raw.groups?.length ?? 0,needReview:review.length,seatingToleranceMeters:0.00015,
...(tools.size ? {tool:{file:usedTools.map(tool=>tool.file.path).join('、'), matched:toolCount,
skipped:records.filter(record=>record.toolMatch && !record.toolMatch.matched).length,
note:options.selectTool?'按给定命名规则选工具。头部表面对接和补充位移用于演示,工具及螺丝的旋转扫掠空间未核对。':'六角孔与工具尺寸、工作轴已匹配的步骤可播放拧入。工具和螺丝旋转时的扫掠空间未检查。'}} : {}),
...(wholeOnly.size ? {wholeOnlyNodes:[...wholeOnly]} : {}),
extraBefore:options.extraBefore ?? null,
counts:records.reduce((all,r)=>{all[r.status]=(all[r.status] ?? 0)+1;return all;},{}),
visualFits:'visual-thread-fit 检查完整头部通道和带径向余量的螺杆。visual-bore-axis 检查完整头部通道和半径为螺杆一半的孔芯。这两类仅用于轴向演示。',
note:'仅检查已装件与当前零件直线平移的网格表面;未检查末端 0.15 mm 配合、旋转、工具及真实装配工艺。',
review:review.map(r=>({step:r.id,label:r.label,file:r.file,reason:r.status})),records};
mkdirSync(path.join(dest,'核对记录'));
writeFileSync(path.join(dest,'核对记录','轴向检查.json'),JSON.stringify(report,null,2)+'\n');
writeFileSync(path.join(dest,'核对记录','待核对步骤.txt'),`以下 ${review.length} 步无法确认无碰撞的直线插入通路。普通零件原位显示;部件合装保留就位演示动画,但不是已经证明无碰撞的真实安装路线。\n\n`+review.map(r=>`${r.label}\n ${r.file ?? '整组部件合装'}\n ${r.status==='review-head'?'未能可靠区分螺丝头尾':'候选轴向受阻或检查未能确认'}\n`).join('\n'));
if (toolCount) {
mkdirSync(path.join(dest,'工具模型'));
for (const tool of usedTools) copyFileSync(tool.source,path.join(dest,'工具模型',tool.file.path));
}
const fits=(report.counts['visual-thread-fit'] ?? 0)+(report.counts['visual-bore-axis'] ?? 0);
writeFileSync(path.join(dest,'上传说明.txt'),`整机模型单独上传 ${whole}。\n零件模型选择 ${root},保留全部编号部位子目录、文件名。\n拼装步骤只上传 ${title}-装配步骤.json。\n${toolCount?`把工具模型目录里的 ${report.tool.file} 放到零件上传目录根层,与分件一同上传。\n`:''}${schedule?`需要部署支持 scoped-v1 的新版前端。遇到 # 时按编号逐组移入此前完成的大组件,再安装当前散件;连续 # 不重复合装。\n`:''}${grouped?`需要部署支持 grouped-v1 的新版前端。前 ${raw.groups.length} 组分别展示;第 ${finalGroup} 组前先合装这些部件,再安装该文件夹的零件。\n`:''}共 ${ordered.length} 个零件、${raw.steps.length} 个播放步骤,${fits} 步是螺丝沿孔轴展示,${review.length} 步需人工复核。未核验的轴向动画仅用于展示,具体步号请看核对记录。\n原 GLB 几何、材质、颜色未修改。\n`);
return report;
}
if (pathToFileURL(path.resolve(process.argv[1] ?? '.')).href===import.meta.url) {
try {
const {values,positionals:[root,out]}=parseArgs({allowPositionals:true,options:{reference:{type:'string'},'final-group':{type:'string'},'extra-before':{type:'string'},'hex-key':{type:'string'}}});
assert.ok(root && out,'用法:npm run assembly:generate -- "分组 GLB 目录" "新的输出目录" [--reference "整机.glb"] [--final-group 8]');
const options={reference:values.reference,hexKey:values['hex-key']};
if (values['extra-before']) {
options.extraBefore=values['extra-before']==='end'?'end':Number(values['extra-before']);
assert.ok(options.extraBefore==='end'||Number.isSafeInteger(options.extraBefore)&&options.extraBefore>0,'附加件参数格式:--extra-before 步号,或 --extra-before end');
}
if(values['final-group']) options.finalGroup=Number(values['final-group']);
const r=await generate(root,out,console.log,options);
console.log(`完成:${path.resolve(out)}(${r.steps} 步,${r.needReview} 步需复核)`);
}
catch (err){console.error(err.message);process.exitCode=1;}
}