File size: 12,237 Bytes
9d9352a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import * as THREE from "three";
import { OrbitControls } from "./vendor/OrbitControls.js";
import { Viewer } from "./viewer.js";

const $ = (s) => document.querySelector(s);
const qs = new URLSearchParams(location.search);

// ---------- language ----------
const STR = {
  en: {
    title: "Luna in your browser",
    sub: "The LimX Luna humanoid (HU_L04) from its official MuJoCo model. Play back a dance from the BeyondMimic reference motions, or pose every joint yourself.",
    dance: "Dance", pose: "Pose", play: "Play", pause: "Pause", speed: "Speed", stand: "Stand pose", fromDance: "From dance",
    loading: "Loading the robot model from Hugging Face…", error: "Could not load the model:", sources: "Source",
    note: "Kinematic replay of the reference motion, not a running policy.",
    legL: "Left leg", legR: "Right leg", waist: "Waist", head: "Head", armL: "Left arm", armR: "Right arm",
    keysDance: "Space play / pause · ← → step", keysPose: "Drag a slider, or click it and use the arrow keys",
  },
  zh: {
    title: "在浏览器里看 Luna",
    sub: "逐际动力 Luna 人形机器人(HU_L04),使用官方 MuJoCo 模型。可以回放 BeyondMimic 参考动作里的一段舞蹈,也可以自己调每个关节。",
    dance: "舞蹈", pose: "摆姿势", play: "播放", pause: "暂停", speed: "速度", stand: "站立姿势", fromDance: "取舞蹈当前帧",
    loading: "正在从 Hugging Face 加载机器人模型…", error: "模型加载失败:", sources: "来源",
    note: "这是参考动作的运动学回放,不是在运行策略。",
    legL: "左腿", legR: "右腿", waist: "腰", head: "头", armL: "左臂", armR: "右臂",
    keysDance: "空格 播放 / 暂停 · ← → 逐帧", keysPose: "拖动滑块,或点选后用方向键微调",
  },
};
let lang = qs.get("lang") || ((navigator.language || "").toLowerCase().startsWith("zh") ? "zh" : "en");
function applyLang() {
  document.documentElement.lang = lang === "zh" ? "zh-CN" : "en";
  document.querySelectorAll("[data-t]").forEach((el) => { el.textContent = STR[lang][el.dataset.t]; });
  $("#lang").textContent = lang === "zh" ? "EN" : "中文";
  $("#play").textContent = STR[lang][playing ? "pause" : "play"];
}
let playing = true;
$("#lang").onclick = () => { lang = lang === "zh" ? "en" : "zh"; applyLang(); };
applyLang();

// ---------- three.js scene ----------
const renderer = new THREE.WebGLRenderer({ canvas: $("#view"), antialias: true, preserveDrawingBuffer: !!qs.get("shot") });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xeef1f5);
scene.fog = new THREE.Fog(0xeef1f5, 10, 26);
const camera = new THREE.PerspectiveCamera(40, 1, 0.05, 100);
camera.up.set(0, 0, 1); camera.position.set(2.6, -2.2, 1.4);
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0, 0.75); controls.enableDamping = true; controls.minDistance = 0.8; controls.maxDistance = 8;
controls.maxPolarAngle = Math.PI * 0.49; controls.enablePan = false;
controls.addEventListener("change", () => { redraw = true; });

scene.add(new THREE.HemisphereLight(0xffffff, 0xb9c2cc, 1.5));
const sun = new THREE.DirectionalLight(0xffffff, 2.3);
sun.position.set(2, -3, 5); sun.castShadow = true; sun.shadow.mapSize.set(2048, 2048);
Object.assign(sun.shadow.camera, { left: -2, right: 2, top: 2, bottom: -2, near: 0.5, far: 15 });
scene.add(sun, sun.target);
{
  const c = document.createElement("canvas"); c.width = c.height = 512; const g = c.getContext("2d");
  g.fillStyle = "#f7f8fa"; g.fillRect(0, 0, 512, 512);
  g.strokeStyle = "#d9dee5"; g.lineWidth = 2;
  for (let i = 0; i <= 512; i += 128) { g.beginPath(); g.moveTo(i, 0); g.lineTo(i, 512); g.moveTo(0, i); g.lineTo(512, i); g.stroke(); }
  g.strokeStyle = "#b8c0cb"; g.lineWidth = 4; g.strokeRect(0, 0, 512, 512);
  const tex = new THREE.CanvasTexture(c); tex.wrapS = tex.wrapT = THREE.RepeatWrapping; tex.repeat.set(50, 50);
  tex.anisotropy = 8; tex.colorSpace = THREE.SRGBColorSpace;
  const floor = new THREE.Mesh(new THREE.PlaneGeometry(200, 200), new THREE.MeshStandardMaterial({ map: tex, roughness: 0.95 }));
  floor.receiveShadow = true; scene.add(floor);
}
function resize() {
  const w = innerWidth, h = innerHeight; renderer.setSize(w, h, false);
  camera.aspect = w / h; camera.fov = w < 640 ? (document.body.dataset.mode === "pose" ? 72 : 55) : 40;
  // on a phone the joint panel covers the lower part of the screen in pose mode: draw the robot higher
  const lift = w < 640 && document.body.dataset.mode === "pose" ? 0.1 * h : 0;
  if (lift) camera.setViewOffset(w, h, 0, lift, w, h); else camera.clearViewOffset();
  camera.updateProjectionMatrix();
}
addEventListener("resize", () => { resize(); redraw = true; }); resize();

// robot meshes, built from the compiled MuJoCo model (visual geoms are group 1)
function buildRobot(v) {
  const { model } = v; const geoms = [];
  const verts = model.mesh_vert, faces = model.mesh_face;
  for (let g = 0; g < model.ngeom; g++) {
    if (model.geom_group[g] !== 1 || model.geom_dataid[g] < 0) continue;
    const m = model.geom_dataid[g];
    const va = model.mesh_vertadr[m], vn = model.mesh_vertnum[m], fa = model.mesh_faceadr[m], fn = model.mesh_facenum[m];
    const geo = new THREE.BufferGeometry();
    geo.setAttribute("position", new THREE.BufferAttribute(Float32Array.from(verts.subarray(va * 3, (va + vn) * 3)), 3));
    geo.setIndex(Array.from(faces.subarray(fa * 3, (fa + fn) * 3)));
    const flat = geo.toNonIndexed(); flat.computeVertexNormals();
    const r = model.geom_rgba;
    const mesh = new THREE.Mesh(flat, new THREE.MeshStandardMaterial({ color: new THREE.Color(r[g * 4], r[g * 4 + 1], r[g * 4 + 2]), roughness: 0.45, metalness: 0.15 }));
    mesh.castShadow = true; mesh.matrixAutoUpdate = false; scene.add(mesh);
    geoms.push([g, mesh]);
  }
  return geoms;
}
function syncRobot(v, geoms) {
  const xp = v.data.geom_xpos, xm = v.data.geom_xmat;
  for (const [g, mesh] of geoms) {
    const p = g * 3, r = g * 9;
    mesh.matrix.set(xm[r], xm[r + 1], xm[r + 2], xp[p], xm[r + 3], xm[r + 4], xm[r + 5], xp[p + 1], xm[r + 6], xm[r + 7], xm[r + 8], xp[p + 2], 0, 0, 0, 1);
  }
}

// ---------- state ----------
let redraw = true;
let viewer = null, geoms = null, mode = "dance", t = 0, speed = 1, pose = null, dirty = true;
const GROUPS = [
  ["legL", /^left_(hip|knee|ankle)/], ["legR", /^right_(hip|knee|ankle)/], ["waist", /^waist/], ["head", /^head/],
  ["armL", /^left_(shoulder|elbow|wrist)/], ["armR", /^right_(shoulder|elbow|wrist)/],
];
const label = (n) => n.replace(/^(left|right)_/, "").replace(/_joint$/, "").replace(/_/g, " ");
const deg = (r) => `${(r * 180 / Math.PI).toFixed(0)}°`;

function buildSliders() {
  const box = $("#sliders"); box.textContent = "";
  for (const [key, re] of GROUPS) {
    const sec = document.createElement("details"); sec.open = key === "armL" || key === "armR";
    const sum = document.createElement("summary"); sum.dataset.t = key; sum.textContent = STR[lang][key]; sec.append(sum);
    viewer.joints.forEach((j, i) => {
      if (!re.test(j.name)) return;
      const row = document.createElement("label"); row.className = "row";
      const name = document.createElement("span"); name.textContent = label(j.name);
      const val = document.createElement("output");
      const s = document.createElement("input"); Object.assign(s, { type: "range", min: j.lo, max: j.hi, step: 0.001 });
      s.dataset.i = i; s.setAttribute("aria-label", j.name);
      s.oninput = () => { pose[i] = +s.value; val.textContent = deg(pose[i]); dirty = true; };
      row.append(name, val, s); sec.append(row);
    });
    box.append(sec);
  }
}
function refreshSliders() {
  document.querySelectorAll("#sliders input").forEach((s) => { const i = +s.dataset.i; s.value = pose[i]; s.previousSibling.textContent = deg(pose[i]); });
}
function currentJoints() { return viewer.joints.map((j) => viewer.data.qpos[j.qadr]); }
function clampPose(q) { return q.map((v, i) => Math.max(viewer.joints[i].lo, Math.min(viewer.joints[i].hi, v))); }

function setMode(m) {
  if (m === mode) return;
  if (m === "pose") { pose = clampPose(currentJoints()); refreshSliders(); }
  mode = m; dirty = true; followFrom = null;
  document.body.dataset.mode = m; resize(); redraw = true;
  document.querySelectorAll("#modes button").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.mode === m)));
}
document.querySelectorAll("#modes button").forEach((b) => { b.onclick = () => setMode(b.dataset.mode); });
function setPlaying(p) { playing = p; $("#play").textContent = STR[lang][p ? "pause" : "play"]; $("#play").classList.toggle("active", p); }
$("#play").onclick = () => setPlaying(!playing);
$("#time").oninput = (e) => { t = +e.target.value; dirty = true; };
$("#time").onpointerdown = () => { wasPlaying = playing; setPlaying(false); };
$("#time").onpointerup = () => { if (wasPlaying) setPlaying(true); };
let wasPlaying = false;
document.querySelectorAll("#speeds button").forEach((b) => {
  b.onclick = () => { speed = +b.dataset.v; document.querySelectorAll("#speeds button").forEach((x) => x.setAttribute("aria-pressed", String(x === b))); };
});
$("#stand").onclick = () => { pose = clampPose(viewer.firstFrame()); refreshSliders(); dirty = true; };
$("#fromDance").onclick = () => { viewer.setMotionTime(t); pose = clampPose(currentJoints()); refreshSliders(); dirty = true; };
addEventListener("keydown", (e) => {
  if (!viewer || mode !== "dance" || e.target.closest?.("input, button, a, summary")) return;
  if (e.code === "Space") { e.preventDefault(); setPlaying(!playing); }
  if (e.code === "ArrowLeft" || e.code === "ArrowRight") { e.preventDefault(); setPlaying(false); t = Math.max(0, Math.min(viewer.duration, t + (e.code === "ArrowLeft" ? -1 : 1) / viewer.motion.fps)); dirty = true; }
});

// camera: keep the same offset to the robot, following its base over the floor
let followFrom = null;
function follow() {
  const [x, y] = viewer.basePos();
  if (followFrom) { const dx = x - followFrom[0], dy = y - followFrom[1]; camera.position.x += dx; camera.position.y += dy; controls.target.x += dx; controls.target.y += dy; }
  else { const ox = camera.position.x - controls.target.x, oy = camera.position.y - controls.target.y; controls.target.set(x, y, 0.75); camera.position.x = x + ox; camera.position.y = y + oy; }
  followFrom = [x, y];
  sun.position.set(x + 2, y - 3, 5); sun.target.position.set(x, y, 0);
}
const fmt = (s) => `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, "0")}`;

async function main() {
  const setProgress = (f) => { $("#bar").style.width = `${(f * 100).toFixed(0)}%`; };
  try {
    viewer = await Viewer.create({ base: qs.get("base") || undefined, onProgress: setProgress });
  } catch (e) {
    console.error(e); $("#loading p").textContent = `${STR[lang].error} ${e.message}`; $("#loading").classList.add("err"); return;
  }
  window.__viewer = viewer;
  geoms = buildRobot(viewer); buildSliders();
  pose = clampPose(viewer.firstFrame());
  $("#time").max = viewer.duration; $("#dur").textContent = fmt(viewer.duration);
  if (qs.get("t")) { t = +qs.get("t"); setPlaying(false); }
  if (qs.get("mode") === "pose") setMode("pose");
  setPlaying(playing);
  $("#loading").hidden = true; document.body.classList.add("ready");

  let last = performance.now();
  const frame = (now) => {
    requestAnimationFrame(frame);
    const dt = Math.min(0.1, (now - last) / 1000); last = now;
    if (mode === "dance") {
      if (playing) { t += dt * speed; if (t > viewer.duration) t = 0; dirty = true; }
      if (dirty) { viewer.setMotionTime(t); $("#time").value = t; $("#now").textContent = fmt(t); }
    } else if (dirty) viewer.setJoints(pose);
    let draw = controls.update() || redraw;
    if (dirty) { syncRobot(viewer, geoms); follow(); dirty = false; draw = true; }
    // draw only when something moved, so a paused robot costs no GPU time
    if (draw) { renderer.render(scene, camera); redraw = false; }
  };
  requestAnimationFrame(frame);
}
main();