Files

325 lines
11 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 装配引擎纯逻辑的 Node 移植版(无浏览器依赖)。
*
* 对应源文件:
* - src/utils/normalizeKeys.ts
* - src/utils/parsePose.ts
* - src/utils/flattenSteps.ts
* - src/scene/AssemblyParts.tsx (buildPlans / collectPlacedModels / composePose)
*
* 只保留"把 assembly.json 编译成每个零件世界位姿"所需的部分:
* - 不要动画 / 扳手 / 线束 / upgrade 槽
* - resolveModel 用桩(只需要零件名,不需要真实 glb URL)
*
* 输出坐标系:Scene(Three.js Y-up),跟应用里渲染一致。
*/
import * as THREE from 'three';
// ===================================================================
// normalizeKeys
// ===================================================================
const ZERO_WIDTH_REGEX = /[​‌‍]/g;
export function normalizeKeys(obj) {
if (Array.isArray(obj)) return obj.map(normalizeKeys);
if (obj !== null && typeof obj === 'object') {
const result = {};
for (const key of Object.keys(obj)) {
result[key.replace(ZERO_WIDTH_REGEX, '')] = normalizeKeys(obj[key]);
}
return result;
}
return obj;
}
// ===================================================================
// parsePose
// ===================================================================
function stripVec3Wrapper(s) {
const trimmed = String(s).trim();
const match = trimmed.match(/^Vector3\s*\(([^)]*)\)$/i);
return match ? match[1] : trimmed;
}
function parsePoseString(s) {
const [posStr, rotStr] = s.split('|');
const [x, y, z] = stripVec3Wrapper(posStr).split(',').map(Number);
const [rx, ry, rz] = stripVec3Wrapper(rotStr ?? '0,0,0').split(',').map(Number);
return { position: [x, y, z], rotation: [rx, ry, rz] };
}
function parsePositionString(s) {
const [x, y, z] = stripVec3Wrapper(s).split(',').map(Number);
return [x, y, z];
}
function parsePoseEntry(entry) {
const [x, y, z] = stripVec3Wrapper(entry.pos).split(',').map(Number);
const [rx, ry, rz] = stripVec3Wrapper(entry.rot ?? '0,0,0').split(',').map(Number);
return { position: [x, y, z], rotation: [rx, ry, rz] };
}
function parsePositionEntry(entry) {
const [x, y, z] = stripVec3Wrapper(entry.pos).split(',').map(Number);
return [x, y, z];
}
function sortByIndex(arr) {
return arr.slice().sort((a, b) => (a.index ?? 0) - (b.index ?? 0));
}
function flattenIfNested(arr) {
const out = [];
const stack = [...arr];
while (stack.length) {
const item = stack.shift();
if (Array.isArray(item)) stack.unshift(...item);
else if (item && typeof item === 'object' && 'pos' in item) out.push(item);
}
return out;
}
export function parsePose(value) {
if (!value) return { position: [0, 0, 0], rotation: [0, 0, 0] };
if (typeof value === 'string') return parsePoseString(value);
if (Array.isArray(value) && value.length > 0) {
const entries = flattenIfNested(value);
if (entries.length === 0) return { position: [0, 0, 0], rotation: [0, 0, 0] };
return parsePoseEntry(sortByIndex(entries)[0]);
}
return { position: [0, 0, 0], rotation: [0, 0, 0] };
}
export function parsePoseList(value) {
if (!value) return [];
if (typeof value === 'string') return value.split('#').map(parsePoseString);
if (Array.isArray(value)) return sortByIndex(flattenIfNested(value)).map(parsePoseEntry);
return [];
}
export function parsePositionList(value) {
if (!value) return [];
if (typeof value === 'string') return value.split('|').map(parsePositionString);
if (Array.isArray(value)) return sortByIndex(flattenIfNested(value)).map(parsePositionEntry);
return [];
}
// ===================================================================
// flattenSteps
// ===================================================================
function walkPhaseDetail(phase, opStep, opDesc, parentKey, result) {
if (!phase || typeof phase !== 'object') return;
const p = phase;
const phaseOutput = typeof p.output === 'string' ? p.output : undefined;
if (Array.isArray(p.phases)) {
for (const stepEntry of p.phases) {
if (!stepEntry || typeof stepEntry !== 'object') continue;
const entry = stepEntry;
let identifier = '';
let description = '';
let operations = [];
let outputName;
for (const key of Object.keys(entry)) {
const value = entry[key];
if (key === 'subphase') operations = Array.isArray(value) ? value : [];
else if (key === 'output') outputName = String(value);
else if (!identifier) {
identifier = key;
description = String(value);
}
}
if (identifier) {
const namedOperations = operations.filter(
(op) => typeof op.step === 'string' && op.step.trim().length > 0,
);
if (namedOperations.length > 0) {
for (const [operationIndex, operation] of operations.entries()) {
const operationName =
typeof operation.step === 'string' && operation.step.trim().length > 0
? operation.step
: `${description}-${operationIndex + 1}`;
result.push({
identifier: operationName,
operations: [operation],
outputName,
});
}
} else {
result.push({ identifier, operations, outputName });
}
}
}
}
for (const key of Object.keys(p)) {
if (key.startsWith('phase-')) walkPhaseDetail(p[key], opStep, opDesc, key, result);
}
}
export function flattenSteps(cfg) {
const result = [];
for (const op of cfg.AllStep ?? []) {
if (!op || typeof op !== 'object') continue;
const opObj = op;
const beforeCount = result.length;
if (Array.isArray(opObj.phase)) {
for (const phaseContainer of opObj.phase) {
if (!phaseContainer || typeof phaseContainer !== 'object') continue;
for (const phaseKey of Object.keys(phaseContainer)) {
walkPhaseDetail(phaseContainer[phaseKey], '', undefined, phaseKey, result);
}
}
} else {
for (const phaseKey of Object.keys(opObj)) {
if (!phaseKey.startsWith('phase-')) continue;
const phaseDetail = opObj[phaseKey];
if (!phaseDetail || typeof phaseDetail !== 'object') continue;
walkPhaseDetail(phaseDetail, '', undefined, phaseKey, result);
}
}
if (result.length === beforeCount) {
result.push({ identifier: '', operations: [], isOpPlaceholder: true });
}
}
return result;
}
// ===================================================================
// buildPlans (移植自 AssemblyParts.tsx,去掉动画/扳手/线束/upgrade)
// ===================================================================
function modelProductStub(name) {
return { kind: 'model', name, url: name, scale: 1 };
}
function makeStepOutputName(stepOutput, entry) {
return entry.output ?? stepOutput;
}
function hasPose(value) {
return typeof value === 'string'
? value.trim().length > 0
: Array.isArray(value) && value.length > 0;
}
export function buildPlans(config, resolveModel = modelProductStub) {
const steps = flattenSteps(config);
const products = new Map();
const plans = [];
let lastBase = null;
let lastPose = { position: [0, 0, 0], rotation: [0, 0, 0] };
let instanceCounter = 0;
let finalOutput = null;
for (const [stepIndex, step] of steps.entries()) {
let planBase = null;
let planPose = null;
for (const entry of step.operations) {
const base = products.get(entry.part) ?? resolveModel(entry.part);
if (!base) continue;
planBase ??= base;
lastBase = base;
if (hasPose(entry.pose) && base.kind !== 'assembly') {
planPose = parsePose(entry.pose);
lastPose = planPose;
}
// line 动作:沿用 base 作为 output,不产生子件
if (entry.action === 'line') {
const outputName = makeStepOutputName(step.outputName, entry);
if (outputName) products.set(outputName, base);
continue;
}
const subName = entry.subpart;
const subProduct = subName ? products.get(subName) ?? resolveModel(subName) : null;
const poses = parsePoseList(entry.subpartpose);
const positions = parsePositionList(entry.assemblypos);
const count = Math.min(entry.subpartnum ?? 0, poses.length, positions.length);
const fixedChildren = [];
if (subProduct && count > 0) {
for (let i = 0; i < count; i++) {
const rotation = poses[i].rotation;
fixedChildren.push({
id: `inst${instanceCounter++}`,
product: subProduct,
position: positions[i],
rotation,
scale: 1,
});
}
}
const outputName = makeStepOutputName(step.outputName, entry);
if (outputName) {
products.set(
outputName,
fixedChildren.length > 0
? { kind: 'assembly', name: outputName, base, children: fixedChildren }
: base,
);
finalOutput = outputName;
}
}
if (planBase ?? lastBase) {
plans.push({
id: `${step.identifier}-${stepIndex}`,
base: planBase ?? lastBase,
partPose: planPose ?? lastPose,
stepIndex,
});
}
}
return { plans, products, finalOutput };
}
// ===================================================================
// collectPlacedModels / composePose
// ===================================================================
const UNIT_SCALE = new THREE.Vector3(1, 1, 1);
export function composePose(parent, local) {
const parentMatrix = new THREE.Matrix4().compose(
new THREE.Vector3(...parent.position),
new THREE.Quaternion().setFromEuler(new THREE.Euler(...parent.rotation, 'XYZ')),
UNIT_SCALE,
);
const localMatrix = new THREE.Matrix4().compose(
new THREE.Vector3(...local.position),
new THREE.Quaternion().setFromEuler(new THREE.Euler(...local.rotation, 'XYZ')),
UNIT_SCALE,
);
const world = parentMatrix.multiply(localMatrix);
const pos = new THREE.Vector3();
const quat = new THREE.Quaternion();
world.decompose(pos, quat, new THREE.Vector3());
const euler = new THREE.Euler().setFromQuaternion(quat, 'XYZ');
return {
position: [pos.x, pos.y, pos.z],
rotation: [euler.x, euler.y, euler.z],
};
}
export function collectPlacedModels(product, basePose, idPrefix = '') {
if (product.kind === 'model') {
return [
{
id: `${idPrefix}${product.name}`,
name: product.name,
position: basePose.position,
rotation: basePose.rotation,
},
];
}
const out = [];
out.push(...collectPlacedModels(product.base, basePose, idPrefix));
for (const child of product.children) {
const childWorldPose = composePose(basePose, {
position: child.position,
rotation: child.rotation,
});
out.push(...collectPlacedModels(child.product, childWorldPose, `${idPrefix}${child.id}/`));
}
return out;
}
/** 取"某一步装配完成后"的所有零件世界位姿(对应 assembledModelsAtStep) */
export function assembledModelsAtStep(plans, stepIndex, config) {
const plan = plans[stepIndex];
if (!plan) return [];
const base = collectPlacedModels(plan.base, plan.partPose);
return base;
}