1c837766cd
Add backend-driven assembly and simulation experiences, MAKE branding, mobile rendering budgets and desktop-only CAD/PCB routes. Improve logo loading progress, document image recovery and URDF request handling; include dev packaging and regression coverage.
123 lines
6.0 KiB
JavaScript
123 lines
6.0 KiB
JavaScript
// Xacro 支持:上传 URDF 文件夹时,如果里面只有 .xacro 没有 .urdf,在浏览器里把 xacro 展开成 URDF,
|
||
// 生成的 .urdf 和原文件一起上传(后端和 3D 显示都只认 URDF)。
|
||
// - 主文件:没有被其他 xacro 引用的那个(优先 *.urdf.xacro)
|
||
// - $(find 包名) / package://包名/:按文件夹里 package.xml 的 <name> 找到包所在目录,换成相对路径
|
||
// - xacro:arg 用默认值;不支持需要 ROS 环境的写法(比如 $(env …)、调用 Python 的表达式)
|
||
import { XacroParser } from 'xacro-parser';
|
||
|
||
const isXacro = (p) => /\.xacro$/i.test(p);
|
||
const dirname = (p) => (p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : '');
|
||
|
||
function normalize(path) {
|
||
const out = [];
|
||
for (const seg of path.split('/')) {
|
||
if (!seg || seg === '.') continue;
|
||
if (seg === '..') out.pop(); else out.push(seg);
|
||
}
|
||
return out.join('/');
|
||
}
|
||
|
||
// 从 a 目录到 b 文件的相对路径
|
||
function relative(fromDir, to) {
|
||
const a = fromDir ? fromDir.split('/') : [];
|
||
const b = to.split('/');
|
||
while (a.length && b.length > 1 && a[0] === b[0]) { a.shift(); b.shift(); }
|
||
return [...a.map(() => '..'), ...b].join('/') || '.';
|
||
}
|
||
|
||
// 包名 → 包在文件夹里的目录
|
||
async function findPackages(entries) {
|
||
const map = new Map();
|
||
for (const e of entries.filter((x) => /(^|\/)package\.xml$/i.test(x.relativePath))) {
|
||
const name = (await e.file.text()).match(/<name>\s*([^<\s]+)\s*<\/name>/)?.[1];
|
||
if (name) map.set(name, dirname(e.relativePath));
|
||
}
|
||
return map;
|
||
}
|
||
|
||
function packageDir(pkgs, name, entries) {
|
||
if (pkgs.has(name)) return pkgs.get(name);
|
||
// 没有 package.xml:找同名目录,找不到就当成文件夹根目录
|
||
const dir = entries.map((e) => e.relativePath.split('/')).find((segs) => segs.slice(0, -1).includes(name));
|
||
return dir ? dir.slice(0, dir.indexOf(name) + 1).join('/') : '';
|
||
}
|
||
|
||
// 文件夹里需要转换时返回主 xacro 的路径;不需要(已有 .urdf 或没有 xacro)返回 null
|
||
export function mainXacro(entries) {
|
||
if (entries.some((e) => /\.urdf$/i.test(e.relativePath))) return null;
|
||
const xacros = entries.filter((e) => isXacro(e.relativePath));
|
||
if (!xacros.length) return null;
|
||
return { candidates: xacros.map((e) => e.relativePath) };
|
||
}
|
||
|
||
async function pickMain(entries, texts) {
|
||
const xacros = entries.filter((e) => isXacro(e.relativePath)).map((e) => e.relativePath);
|
||
const included = new Set();
|
||
for (const p of xacros) {
|
||
for (const m of texts.get(p).matchAll(/<xacro:include\s+filename="([^"]+)"/g)) {
|
||
const f = m[1].replace(/\$\(find\s+[^)]+\)\//, '').split('/').pop();
|
||
xacros.filter((x) => x.split('/').pop() === f).forEach((x) => included.add(x));
|
||
}
|
||
}
|
||
let roots = xacros.filter((p) => !included.has(p) && /<robot[\s>]/.test(texts.get(p)));
|
||
if (roots.length > 1) roots = roots.filter((p) => /\.urdf\.xacro$/i.test(p)).length ? roots.filter((p) => /\.urdf\.xacro$/i.test(p)) : roots;
|
||
if (roots.length > 1) roots.sort((a, b) => (texts.get(b).match(/<xacro:include/g) || []).length - (texts.get(a).match(/<xacro:include/g) || []).length);
|
||
if (!roots.length) throw new Error('找到了 .xacro 文件,但没有找到描述整个机器人的主文件(含 <robot> 且没有被其他文件引用)');
|
||
return roots[0];
|
||
}
|
||
|
||
// 把 xacro 展开成 URDF,返回加上了生成 .urdf 的新清单
|
||
export async function expandXacro(entries) {
|
||
if (!mainXacro(entries)) return { entries, converted: null };
|
||
const byPath = new Map(entries.map((e) => [e.relativePath, e.file]));
|
||
const texts = new Map();
|
||
for (const e of entries.filter((x) => isXacro(x.relativePath))) texts.set(e.relativePath, await e.file.text());
|
||
const main = await pickMain(entries, texts);
|
||
const pkgs = await findPackages(entries);
|
||
|
||
const parser = new XacroParser();
|
||
parser.workingPath = dirname(main);
|
||
parser.inOrder = true;
|
||
parser.requirePrefix = true;
|
||
parser.localProperties = true;
|
||
// $(find 包名) → 包目录(/ 开头,表示文件夹根目录下的路径)
|
||
parser.rospackCommands = {
|
||
find: (name) => `/${packageDir(pkgs, name, entries)}`.replace(/\/$/, '') || '/', // 以 / 开头当作文件夹根目录下的绝对路径
|
||
};
|
||
parser.getFileContents = async (path) => {
|
||
const key = normalize(path.replace(/^file:\/\//, ''));
|
||
const file = byPath.get(key) || [...byPath.entries()].find(([k]) => k.endsWith('/' + key))?.[1];
|
||
if (!file) throw new Error(`xacro 引用的文件不在文件夹里:${path}`);
|
||
return file.text();
|
||
};
|
||
|
||
let xml;
|
||
try {
|
||
xml = await parser.parse(texts.get(main));
|
||
} catch (err) {
|
||
throw new Error(`xacro 转换失败(${main}):${err.message || err}`);
|
||
}
|
||
|
||
// 生成的 URDF 放在主 xacro 旁边;网格路径(package:// 和 $(find) 展开后的路径)改成相对这个 URDF 的路径
|
||
const outPath = main.replace(/\.urdf\.xacro$/i, '.urdf').replace(/\.xacro$/i, '.urdf');
|
||
const outDir = dirname(outPath);
|
||
xml.querySelectorAll('mesh[filename]').forEach((el) => {
|
||
let f = el.getAttribute('filename');
|
||
const pkg = f.match(/^package:\/\/([^/]+)\/(.*)$/);
|
||
if (pkg) f = normalize(`${packageDir(pkgs, pkg[1], entries)}/${pkg[2]}`);
|
||
else if (/^file:\/\//i.test(f)) f = normalize(f.replace(/^file:\/+/i, '')); // file://$(find 包)/… 展开后是 file:///…,按文件夹根目录处理
|
||
else if (/^https?:/i.test(f)) return;
|
||
else f = normalize(f.startsWith('/') ? f.slice(1) : `${dirname(main)}/${f}`);
|
||
// 文件夹里找不到原路径时,按文件名找一个
|
||
if (!byPath.has(f)) {
|
||
const name = f.split('/').pop();
|
||
const hit = [...byPath.keys()].find((k) => k.split('/').pop() === name);
|
||
if (hit) f = hit;
|
||
}
|
||
el.setAttribute('filename', relative(outDir, f));
|
||
});
|
||
const text = '<?xml version="1.0"?>\n<!-- 由 make 从 ' + main + ' 自动生成 -->\n' + new XMLSerializer().serializeToString(xml.documentElement);
|
||
const file = new File([text], outPath.split('/').pop(), { type: 'application/xml' });
|
||
return { entries: [...entries, { file, relativePath: outPath }], converted: { from: main, to: outPath } };
|
||
}
|