File size: 6,142 Bytes
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
// Fetching for the page: registries, robots (XML + one gzip mesh pack), environments, and the
// WebAssembly runtimes shipped as .wasm.gz. The Space's static host sends files uncompressed and
// redirects each request, so few, pre-compressed files load fastest.
import loadMujoco from "@mujoco/mujoco";
import mujocoWasmUrl from "@mujoco/mujoco/mujoco.wasm?url";
import ortWasmUrl from "onnxruntime-web/ort-wasm-simd-threaded.wasm?url";
import { gunzip, unpack } from "../meshpack.js";

/** Fetch a file, reporting bytes as they arrive: onBytes(received, total). */
export async function download(url, onBytes = () => {}) {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`${url}: HTTP ${response.status}`);
  const total = Number(response.headers.get("content-length")) || 0;
  if (!response.body) {
    const bytes = new Uint8Array(await response.arrayBuffer());
    onBytes(bytes.length, total);
    return bytes;
  }
  const reader = response.body.getReader();
  const chunks = [];
  let received = 0;
  for (;;) {
    const { done, value } = await reader.read();
    if (done) break;
    chunks.push(value);
    received += value.length;
    onBytes(received, total);
  }
  const bytes = new Uint8Array(received);
  let at = 0;
  for (const chunk of chunks) {
    bytes.set(chunk, at);
    at += chunk.length;
  }
  return bytes;
}

export const text = async (url) => new TextDecoder().decode(await download(url));
export const json = async (url) => JSON.parse(await text(url));

/** Progress over several downloads with expected sizes: track(key, bytes) -> report(fraction). */
export function progress(expected, report) {
  const got = Object.fromEntries(Object.keys(expected).map((k) => [k, 0]));
  return (key) => (bytes, total) => {
    got[key] = bytes;
    if (total) expected[key] = total;
    const sum = (o) => Object.values(o).reduce((a, b) => a + b, 0);
    report(Math.min(0.99, sum(got) / sum(expected)));
  };
}

/** MuJoCo's WebAssembly module, from mujoco.wasm.gz in the build (the plain .wasm on the dev server). */
export async function mujocoModule(onBytes) {
  const binary = await wasmFile(mujocoWasmUrl, onBytes);
  return loadMujoco({ wasmBinary: binary.buffer });
}

const isWasm = (b) => b.length > 4 && b[0] === 0 && b[1] === 0x61 && b[2] === 0x73 && b[3] === 0x6d;

/** A WebAssembly file from `${url}.gz` (the build), else `url` (the dev server answers .gz with its page). */
async function wasmFile(url, onBytes) {
  try {
    const binary = await gunzip(await download(`${url}.gz`, onBytes));
    if (isWasm(binary)) return binary;
  } catch {
    // no .gz: the dev server
  }
  return download(url, onBytes);
}

/**
 * A built-in robot: robot.json, its XML, objects XML and meshes as [file, bytes] pairs, and for a robot
 * driven by a policy (robot.json "policy") the policy's config and the URL of its ONNX file.
 */
export async function fetchRobot(base, id, onBytes) {
  const dir = `${base}robots/${id}/`;
  const meta = await json(`${dir}robot.json`);
  const [xml, objectsXml, index, packed, policyConfig] = await Promise.all([
    text(`${dir}${meta.xml}`),
    meta.objects ? text(`${dir}${meta.objects}`) : null,
    json(`${dir}meshes.json`),
    download(`${dir}meshes.pack.gz`, onBytes),
    meta.policy ? json(`${dir}${meta.policy.config}`) : null,
  ]);
  const policyUrl = meta.policy ? `${dir}${meta.policy.onnx}` : null;
  return { meta, name: id, xml, objectsXml, meshes: unpack(await gunzip(packed), index), policyConfig, policyUrl };
}

/**
 * A robot folder chosen by the user, as MuJoCo-GS-Web takes it: a robot XML (the one named like the
 * folder, else the largest; XML with "object" in its name holds objects), meshes under assets/ or
 * meshes/. Other XML files come along for <include>.
 */
export async function readRobotFolder(files) {
  const xmls = [];
  let objectsXml = null;
  let folder = null;
  const meshes = [];
  for (const file of files) {
    const path = file.webkitRelativePath || file.name;
    const parts = path.split("/");
    if (parts.length > 1) folder ??= parts[0];
    const name = parts[parts.length - 1];
    if (name.toLowerCase().endsWith(".xml")) {
      const content = await file.text();
      if (name.toLowerCase().includes("object")) objectsXml = content;
      else xmls.push({ name, content });
    } else if (/(^|\/)(assets|meshes?)\//.test(path)) {
      meshes.push([path.split(/(?:^|\/)(?:assets|meshes?)\//).pop(), new Uint8Array(await file.arrayBuffer())]);
    }
  }
  const robots = xmls.filter((x) => !/^scene/i.test(x.name));
  const main = robots.find((x) => folder && x.name.toLowerCase() === `${folder.toLowerCase()}.xml`) ?? robots.sort((a, b) => b.content.length - a.content.length)[0];
  if (!main) throw new Error("No robot XML in the folder (scene*.xml and *object*.xml are not robots)");
  const id = (folder ?? "robot").replace(/[^A-Za-z0-9_-]/g, "_");
  // The robot's top-level bodies: everything under them is drawn and treated as the robot.
  const doc = new DOMParser().parseFromString(main.content, "text/xml");
  const roots = [...(doc.querySelector("worldbody")?.children ?? [])].filter((e) => e.tagName === "body" && e.getAttribute("name")).map((e) => e.getAttribute("name"));
  const extraFiles = xmls.filter((x) => x !== main).map((x) => [x.name, x.content]);
  return { meta: { id, name: folder ?? "Uploaded robot", controller: "generic", roots, cameras: {} }, name: id, xml: main.content, objectsXml, meshes, extraFiles };
}

/**
 * ONNX Runtime Web, with its WebAssembly binary from the build's .wasm.gz (the plain .wasm in dev).
 * Loaded once: the pick policy and the walking policy share it (`onBytes` reports the first load).
 */
let ortLoading = null;
export function onnxRuntime(onBytes) {
  ortLoading ??= (async () => {
    const ort = await import("onnxruntime-web/wasm");
    ort.env.wasm.wasmBinary = await wasmFile(ortWasmUrl, onBytes);
    ort.env.wasm.numThreads = 1; // the static host is not cross-origin isolated: no SharedArrayBuffer threads
    return ort;
  })();
  ortLoading.catch(() => (ortLoading = null)); // try again next time
  return ortLoading;
}