Datasets:
Download tool/lib/common.mjs from codepawl/asset-index: direct link, hf CLI and curl.
- Browser
- Download file 8.31 kB
-
https://huggingface.co/datasets/codepawl/asset-index/resolve/main/tool/lib/common.mjs
- Command line
-
hf download hf://datasets/codepawl/asset-index/tool/lib/common.mjs
-
curl -L -o common.mjs https://huggingface.co/datasets/codepawl/asset-index/resolve/main/tool/lib/common.mjs
8.31 kB
| // Shared pieces of the pack pipeline: the manifest, the run folders, per-item stage state, timings and child processes. | |
| import fs from 'node:fs'; | |
| import os from 'node:os'; | |
| import path from 'node:path'; | |
| import { spawn } from 'node:child_process'; | |
| import { fileURLToPath } from 'node:url'; | |
| export const TOOLS_FOLDER = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); | |
| // Machine paths come from the environment; set them for your machine (see README). | |
| export const ENGINE_ROOT = process.env.ENGINE_ROOT ?? path.resolve(TOOLS_FOLDER, '..', '67js'); | |
| export const CHROME_PATH = process.env.CHROME_PATH ?? 'chrome'; | |
| export const BLENDER_PATH = process.env.BLENDER_PATH ?? 'blender'; | |
| export const TOKTX_PATH = process.env.TOKTX_PATH ?? 'toktx'; | |
| export const GIT_BASH = process.env.GIT_BASH ?? 'bash'; | |
| // Optional GPU queue script: set GPU_LOCK to a script that takes a command and runs it when the GPU is free. | |
| export const GPU_LOCK = process.env.GPU_LOCK ?? ''; | |
| // Every tier the optimize stage knows, with the folder it writes into inside the pack. | |
| export const TIER_FOLDERS = { | |
| web: 'objects', | |
| ktx2: 'objects_ktx2', | |
| lod: 'lods', | |
| mobile: 'mobile', | |
| engine: 'engine', | |
| collision: 'collision', | |
| // Written by a converter, not by optimize: the mocap retarget puts each clip's source skeleton here. | |
| skeleton: 'skeleton', | |
| }; | |
| export const GODOT_PATH = process.env.GODOT_PATH ?? 'godot'; | |
| export function readManifest(manifestPath) { | |
| const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); | |
| for (const field of ['name', 'repository', 'source', 'licence', 'converter', 'output']) { | |
| if (!manifest[field]) throw new Error(`manifest ${manifestPath} has no "${field}"`); | |
| } | |
| manifest.tiers ??= {}; | |
| manifest.manifestPath = path.resolve(manifestPath); | |
| return manifest; | |
| } | |
| export function runFolders(manifest) { | |
| const root = path.resolve(manifest.output); | |
| const folders = { | |
| root, | |
| pack: path.join(root, 'pack'), | |
| work: path.join(root, 'work'), | |
| raw: path.join(root, 'work', 'raw'), | |
| state: path.join(root, '_state'), | |
| space: path.join(root, 'space'), | |
| notes: path.join(root, 'notes'), | |
| }; | |
| for (const folder of Object.values(folders)) fs.mkdirSync(folder, { recursive: true }); | |
| return folders; | |
| } | |
| export function tierPath(folders, tier, id, suffix = '') { | |
| return path.join(folders.pack, TIER_FOLDERS[tier], id, `${id}${suffix}.glb`); | |
| } | |
| // Per-item state: one JSON line per finished item in _state/<stage>.jsonl. A stage skips ids already recorded as ok, | |
| // so a stopped run picks up where it left off and a rerun only redoes failures. | |
| export class StageState { | |
| constructor(folders, stage) { | |
| this.filePath = path.join(folders.state, `${stage}.jsonl`); | |
| this.records = new Map(); | |
| if (fs.existsSync(this.filePath)) { | |
| for (const line of fs.readFileSync(this.filePath, 'utf8').split('\n')) { | |
| if (!line.trim()) continue; | |
| const record = JSON.parse(line); | |
| this.records.set(record.id, record); | |
| } | |
| } | |
| } | |
| isDone(id) { | |
| return this.records.get(id)?.ok === true; | |
| } | |
| save(record) { | |
| this.records.set(record.id, record); | |
| fs.appendFileSync(this.filePath, JSON.stringify(record) + '\n'); | |
| } | |
| okRecords() { | |
| return [...this.records.values()].filter((record) => record.ok); | |
| } | |
| } | |
| export function readItems(folders) { | |
| const itemsPath = path.join(folders.state, 'items.jsonl'); | |
| if (!fs.existsSync(itemsPath)) throw new Error('no items yet: run the convert stage first'); | |
| return fs.readFileSync(itemsPath, 'utf8').split('\n').filter(Boolean).map((line) => JSON.parse(line)); | |
| } | |
| export function readJsonLines(filePath) { | |
| if (!fs.existsSync(filePath)) return []; | |
| return fs.readFileSync(filePath, 'utf8').split('\n').filter(Boolean).map((line) => JSON.parse(line)); | |
| } | |
| // Records each stage's wall time per run in _state/timings.jsonl, so the report can name the slowest stage. | |
| export function recordTiming(folders, stage, seconds, detail = {}) { | |
| const line = { stage, seconds: Number(seconds.toFixed(1)), finished: new Date().toISOString(), ...detail }; | |
| fs.appendFileSync(path.join(folders.state, 'timings.jsonl'), JSON.stringify(line) + '\n'); | |
| } | |
| // Fills {name} placeholders in a converter command from the values given. | |
| export function fillCommand(template, values) { | |
| return template.map((part) => part.replace(/\{(\w+)\}/g, (match, key) => (key in values ? String(values[key]) : match))); | |
| } | |
| // Python runs through uv with the packages the manifest or stage asks for, isolated (-I) so a downloaded file named | |
| // like a module can never be imported. | |
| export function pythonCommand(scriptPath, scriptArguments, packages = []) { | |
| const withFlags = packages.flatMap((name) => ['--with', name]); | |
| return ['uv', ['run', '--no-project', ...withFlags, 'python', '-I', scriptPath, ...scriptArguments]]; | |
| } | |
| // Starts a child at below-normal priority and resolves with its output. Rejects on a non-zero exit unless allowFailure. | |
| export function runCommand(command, commandArguments, { allowFailure = false, quiet = true, environment = {}, workingFolder } = {}) { | |
| return new Promise((resolve, reject) => { | |
| const child = spawn(command, commandArguments, { | |
| cwd: workingFolder, | |
| env: { ...process.env, PYTHONIOENCODING: 'utf-8', ...environment }, | |
| windowsHide: true, | |
| }); | |
| try { | |
| os.setPriority(child.pid, os.constants.priority.PRIORITY_BELOW_NORMAL); | |
| } catch { | |
| // The child may already have exited. | |
| } | |
| let standardOutput = ''; | |
| let standardError = ''; | |
| child.stdout.on('data', (chunk) => { | |
| standardOutput += chunk; | |
| if (!quiet) process.stdout.write(chunk); | |
| }); | |
| child.stderr.on('data', (chunk) => { | |
| standardError += chunk; | |
| if (!quiet) process.stderr.write(chunk); | |
| }); | |
| child.on('error', reject); | |
| child.on('close', (code) => { | |
| const result = { code, standardOutput, standardError }; | |
| if (code !== 0 && !allowFailure) { | |
| reject(new Error(`${command} ${commandArguments.slice(0, 6).join(' ')} exited ${code}: ${standardError.slice(-800)}`)); | |
| } else { | |
| resolve(result); | |
| } | |
| }); | |
| }); | |
| } | |
| // Runs a node script that drives the GPU (headless Chrome) through the optional GPU_LOCK queue script, as a light job. | |
| export function runOnGpu(scriptPath, scriptArguments, options = {}) { | |
| const nodePath = process.execPath.replaceAll('\\', '/'); | |
| // Without a GPU queue script on this machine, run the job directly. | |
| if (!GPU_LOCK || !fs.existsSync(GPU_LOCK)) return runCommand(nodePath, [scriptPath, ...scriptArguments.map(String)], options); | |
| return runCommand(GIT_BASH, [GPU_LOCK, nodePath, scriptPath, ...scriptArguments.map(String)], { | |
| ...options, | |
| environment: { GPU_LOCK_WEIGHT: 'light', ...options.environment }, | |
| }); | |
| } | |
| export function lastJsonLine(text) { | |
| const lines = text.trim().split('\n').reverse(); | |
| for (const line of lines) { | |
| if (line.trim().startsWith('{')) return JSON.parse(line); | |
| } | |
| return null; | |
| } | |
| export function jsonLines(text) { | |
| return text.split('\n').filter((line) => line.trim().startsWith('{')).map((line) => JSON.parse(line)); | |
| } | |
| // Runs jobs with a fixed number of workers. Each job is an async function. | |
| export async function runPool(jobs, concurrency, onProgress) { | |
| let nextIndex = 0; | |
| let finished = 0; | |
| const results = []; | |
| async function worker() { | |
| while (nextIndex < jobs.length) { | |
| const index = nextIndex++; | |
| results[index] = await jobs[index](); | |
| finished += 1; | |
| onProgress?.(finished, jobs.length); | |
| } | |
| } | |
| await Promise.all(Array.from({ length: Math.min(concurrency, jobs.length) }, worker)); | |
| return results; | |
| } | |
| export function megabytes(byteCount) { | |
| return byteCount >= 1e9 ? `${(byteCount / 1e9).toFixed(2)} GB` : `${(byteCount / 1e6).toFixed(1)} MB`; | |
| } | |
| export function folderBytes(folder) { | |
| if (!fs.existsSync(folder)) return { bytes: 0, files: 0 }; | |
| let bytes = 0; | |
| let files = 0; | |
| for (const entry of fs.readdirSync(folder, { recursive: true, withFileTypes: true })) { | |
| if (!entry.isFile()) continue; | |
| bytes += fs.statSync(path.join(entry.parentPath, entry.name)).size; | |
| files += 1; | |
| } | |
| return { bytes, files }; | |
| } | |
| export function workerCount(fraction = 0.5) { | |
| return Math.max(1, Math.floor(os.availableParallelism() * fraction)); | |
| } | |