DronePilot / worker.js
edgarmoreau's picture
SkyJEPA task card: write the goals and costs, a 5.6k-param world model flies them in the browser
c6f6a31 verified
Raw History Blame Contribute Delete
1.79 kB
// The drone's brain runs here, off the page's thread: the SkyJEPA world model, MPPI, the nerve and the card's costs.
// The page only draws and edits the card.
import { loadModel } from "./core/model.js";
import { Course } from "./core/course.js";
let course = null, running = false, speed = 1, timer = null;
const post = (type, data = {}) => postMessage({ type, ...data });
async function init(card) {
const json = await (await fetch("./core/model.json")).json();
course = new Course(loadModel(json), card, 0);
post("frame", course.frame());
post("ready");
}
function loop() {
timer = null;
if (!running || !course) return;
const t0 = performance.now();
const f = course.step();
post("frame", f);
if (f.done) { running = false; post("running", { on: false, done: true, crashed: f.crashed }); return; }
const wall = performance.now() - t0, budget = speed === 0 ? 0 : 50 / speed; // 0.05 s of flight per tick
timer = setTimeout(loop, Math.max(0, budget - wall));
}
onmessage = ({ data: d }) => {
if (d.type === "init") return void init(d.card);
if (!course) return;
switch (d.type) {
case "run":
if (d.on && course.done) course.reset();
running = d.on; post("running", { on: running });
if (running && !timer) loop();
break;
case "speed": speed = d.v; break;
case "samples": course.setSamples(d.n); break;
case "card": {
const startMoved = JSON.stringify(course.card.start) !== JSON.stringify(d.card.start);
course.setCard(d.card);
if (!running && (startMoved || course.t === 0)) course.reset();
if (!running) post("frame", course.frame());
break;
}
case "reset": running = false; course.reset(); post("running", { on: false }); post("frame", course.frame()); break;
}
};