xlerobot-sim / src /core /sim.js
VectorW's picture
Household tasks in the style of the BEHAVIOR Challenge; walls cut away in the view; fixes
d72771b verified
Raw History Blame Contribute Delete
4.81 kB
// The simulation core: a compiled MuJoCo model and its data, stepped in fixed control periods.
// It knows nothing about a particular robot; a robot driver (src/robots/) sets data.ctrl each period.
// The same class runs in the browser and in Node (tools/), so both step identical physics.
/** A small seeded random generator (mulberry32), for repeatable scenes. */
export function makeRng(seed) {
let a = seed >>> 0;
const next = () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
return {
next,
uniform: (lo, hi) => lo + (hi - lo) * next(),
choice: (items) => items[Math.floor(next() * items.length)],
};
}
const FREE = 0; // mjJNT_FREE
export class Sim {
/** `controlHz` sets the control period: the robot driver runs every round(1 / (controlHz * timestep)) steps. */
constructor(mujoco, model, { controlHz = 50 } = {}) {
this.mujoco = mujoco;
this.model = model;
this.data = new mujoco.MjData(model);
this.timestep = model.opt.timestep;
this.substeps = Math.max(1, Math.round(1 / (controlHz * this.timestep)));
this.controlDt = this.substeps * this.timestep;
this.steps = 0;
this.controlled = false;
this.bodyNames = Array.from({ length: model.nbody }, (_, i) => model.body(i).name);
}
dispose() {
this.data.delete();
this.model.delete();
}
get time() {
return this.data.time;
}
/** The id of a named object, or -1. `type` is "body", "joint", "geom", "site", "actuator"... */
id(type, name) {
const key = { body: "mjOBJ_BODY", joint: "mjOBJ_JOINT", geom: "mjOBJ_GEOM", site: "mjOBJ_SITE", actuator: "mjOBJ_ACTUATOR", camera: "mjOBJ_CAMERA", tendon: "mjOBJ_TENDON" }[type];
return this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj[key].value, name);
}
bodyPos(id) {
const p = this.data.xpos;
return [p[3 * id], p[3 * id + 1], p[3 * id + 2]];
}
/** The body's rotation matrix, row major. */
bodyMat(id) {
return Array.from(this.data.xmat.subarray(9 * id, 9 * id + 9));
}
/** Bodies on a free joint whose root is not in `excludeRoots`: the objects of the scene. */
freeBodies(excludeRoots = []) {
const { model } = this;
const out = [];
for (let b = 1; b < model.nbody; b++) {
const j = model.body_jntadr[b];
if (j < 0 || model.jnt_type[j] !== FREE || model.body_parentid[b] !== 0) continue;
if (excludeRoots.includes(b)) continue;
out.push({ id: b, name: this.bodyNames[b], qpos: model.jnt_qposadr[j], dof: model.jnt_dofadr[j] });
}
return out;
}
/** One physics step. */
step() {
this.mujoco.mj_step(this.model, this.data);
this.steps++;
if (this.steps % this.substeps === 0) this.controlled = false;
}
/**
* Up to `n` physics steps; `onControl(dt)` runs at the start of every control period. If it returns
* false the physics stops there (a policy is still thinking) and the next call asks again.
* Returns the number of steps taken.
*/
runSteps(n, onControl) {
for (let i = 0; i < n; i++) {
if (onControl && this.steps % this.substeps === 0 && !this.controlled) {
if (onControl(this.controlDt) === false) return i;
this.controlled = true;
}
this.step();
}
return n;
}
/** One control period: `onControl(dt)`, then its physics steps. */
tick(onControl) {
const toBoundary = (this.substeps - (this.steps % this.substeps)) % this.substeps;
for (let i = 0; i < toBoundary; i++) this.step();
if (onControl) onControl(this.controlDt);
for (let i = 0; i < this.substeps; i++) this.step();
}
/** Steps for about `seconds`, running `onControl` every period. */
run(seconds, onControl) {
this.runSteps(Math.round(seconds / this.timestep), onControl);
}
forward() {
this.mujoco.mj_forward(this.model, this.data);
}
/** The model's initial state; `setup` may change qpos and ctrl before the first forward pass. */
reset(setup) {
this.mujoco.mj_resetData(this.model, this.data);
if (setup) setup(this);
this.steps = 0;
this.controlled = false;
this.forward();
}
/** Copy of the state that `restore` puts back. */
snapshot() {
const d = this.data;
return { time: d.time, qpos: Float64Array.from(d.qpos), qvel: Float64Array.from(d.qvel), act: Float64Array.from(d.act), ctrl: Float64Array.from(d.ctrl), steps: this.steps };
}
restore(s) {
const d = this.data;
d.time = s.time;
d.qpos.set(s.qpos);
d.qvel.set(s.qvel);
d.act.set(s.act);
d.ctrl.set(s.ctrl);
d.qacc_warmstart.fill(0);
d.xfrc_applied.fill(0);
this.steps = s.steps;
this.controlled = false;
this.forward();
}
}