Files
vibemake/js/urdf-paths.js
T

105 lines
4.3 KiB
JavaScript

const dirname = (path) => path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '';
function normalize(path) {
const out = [];
for (const seg of path.split('/')) {
if (!seg || seg === '.') continue;
if (seg === '..') {
if (!out.length) return null;
out.pop();
} else out.push(seg);
}
return out.join('/');
}
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('/') || '.';
}
function localPath(filename, mainPath) {
const value = String(filename).trim();
const pkg = value.match(/^package:\/\/[^/]+\/(.*)$/i);
if (pkg) return normalize(pkg[1]);
if (/^https?:\/\//i.test(value) || /^(data|blob):/i.test(value)) return null;
if (/^file:\/\//i.test(value)) return normalize(value.replace(/^file:\/+/i, ''));
return normalize(value.startsWith('/') ? value.slice(1) : `${dirname(mainPath)}/${value}`);
}
export function meshUrlCandidates(base, url) {
const value = String(url);
const root = String(base).replace(/\/+$/, '');
const prefix = `${root}/`;
if (!value.startsWith(prefix)) return [value];
const path = value.slice(prefix.length).split(/[?#]/, 1)[0];
const parts = path.split('/');
if (parts.some((part) => !part || part === '.' || part === '..')) return [value];
const resourceIndex = parts.findIndex((part, index) => index > 1 && (part === 'meshes' || part === 'qb_meshes'));
const rootResource = parts[0] === 'robots' && resourceIndex > 1
? `${root}/${parts.slice(resourceIndex).join('/')}`
: null;
// Older uploads can retain source directories that are absent from the OSS batch.
const fallbacks = parts.slice(1, 9).map((_, i) => `${root}/${parts.slice(i + 1).join('/')}`);
return [...new Set([rootResource, value, ...fallbacks].filter(Boolean))];
}
// Resolve references against the uploaded file manifest. A unique suffix match
// handles URDFs that retain their source workspace prefix after upload.
export function resolveUrdfResourcePath(filename, mainPath, availablePaths) {
const target = localPath(filename, mainPath);
if (!target) return null;
const available = [...new Set(availablePaths.map(normalize).filter(Boolean))];
let match = available.includes(target) ? target : null;
if (!match) {
const targetParts = target.split('/');
let bestScore = 1;
let best = [];
for (const path of available) {
const parts = path.split('/');
let score = 0;
while (score < targetParts.length && score < parts.length
&& targetParts[targetParts.length - score - 1] === parts[parts.length - score - 1]) score++;
if (score > bestScore) { bestScore = score; best = [path]; }
else if (score === bestScore && score > 1) best.push(path);
}
if (bestScore > 1 && best.length === 1) match = best[0];
else if (bestScore <= 1) {
const basename = targetParts.at(-1);
const sameName = available.filter((path) => path.split('/').at(-1) === basename);
if (sameName.length === 1) match = sameName[0];
}
}
return match ? relative(dirname(mainPath), match) : null;
}
export async function normalizeUrdfEntries(entries) {
const main = entries.find((entry) => /\.urdf$/i.test(entry.relativePath));
if (!main || typeof DOMParser === 'undefined' || typeof XMLSerializer === 'undefined' || typeof File === 'undefined') return entries;
const source = await main.file.text();
const doc = new DOMParser().parseFromString(source, 'application/xml');
if (doc.getElementsByTagName('parsererror').length) return entries;
const paths = entries.map((entry) => entry.relativePath);
let changed = false;
doc.querySelectorAll('mesh[filename], texture[filename]').forEach((node) => {
const filename = node.getAttribute('filename');
const resolved = resolveUrdfResourcePath(filename, main.relativePath, paths);
if (resolved && resolved !== filename) {
node.setAttribute('filename', resolved);
changed = true;
}
});
if (!changed) return entries;
const file = new File([new XMLSerializer().serializeToString(doc)], main.file.name, {
type: main.file.type || 'application/xml',
lastModified: main.file.lastModified,
});
return entries.map((entry) => entry === main ? { ...entry, file } : entry);
}