GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / solar-design-studio/202609271853-site-world/packs/body/src

Drone and 1 more file

A JavaScript module in the packs folder of GlobalGrid2050 that parses xy (`parseXY`) and calculates planar distances and angles (units: kV), covering wind, using ISO 2533.

700 lines of JavaScript from globalgrid2050, in 2 files. Topic: Solar and storage design. Section 170 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Body transform · globalgrid2050 / solar-design-studio/202609271853-site-world/packs/body/src/body.mjs lines 1–318
  2. Drone ingest · globalgrid2050 / solar-design-studio/202609271853-site-world/packs/drone/src/drone.mjs lines 1–382

Body

A JavaScript module in the packs folder of GlobalGrid2050 that runs want (`runWant`), steps len (`stepLen`) and calculates planar distances.

transformglobalgrid2050 / solar-design-studio/202609271853-site-world/packs/body/src/body.mjs · lines 1–318 of 318 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern airTimeOf (shared by 2 files)

What it does
It calculates its inputs. Defines 22 functions or classes, including apexOf, airTimeOf, runWant, dipAt, clamp.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
What it achieves
It runs want (`runWant`) and is built from the apex of helper (`apexOf`) and the air time of helper (`airTimeOf`). Body pack (world.pack.v1): how the viewer moves on foot.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/packs/body/src · JavaScript module
Uses
none found
Used by
none found
Produces
G, COYOTE_S, OMEGA, EYE, STEP_UP_M, DROP_M, TOP_GAP_M, TELEPORT_M, WALK, BOB_WALK_M, apexOf, airTimeOf
Defines here
apexOf, airTimeOf, runWant, dipAt, clamp, num, blocked, supportAt, createBody, dipNow, speed, stepLen, bobNow, place, takeOff, slide, fly, step, gait, yawOf, numbers, make
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/packs/body/src/body.mjs:1-318 · blob e74415f9d75279f37dae36aa907aaac2ffa29132 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// body pack (world.pack.v1): how the viewer moves on foot. Walk, run (Shift held), jump (Space), stand and land on
// solids, and an optional footstep camera bob (off by default). One self-contained module: no imports.
//
// The jump is a port of the world's own Walk jump (same numbers, same rules): real gravity, a tap reaching
// V0^2/2G, a held press pushing a little higher, coyote time off an edge, a press buffer before touchdown, landing on
// measured ground or on a solid's top, and a critically damped landing dip. Running is new here.
//
// Deterministic: time is the sum of the fixed steps it is given; there is no clock and no random number.
// Local metres: x east, y north, z up. The pose is the eye: feet + EYE (+ landing dip, + bob when switched on).
// Everything here is ILLUSTRATIVE: a plausible, simple model of a person moving, not a biomechanical simulation.
//
// Numbers (SI):
//   G 9.81 m/s^2 (standard gravity, rounded). V0 3.0 m/s take-off: apex V0^2/2G = 0.459 m, air time 2 V0/G = 0.612 s.
//   Held past GRACE_S (0.1 s) the legs push PUSH m/s^2 more until the predicted apex reaches MAX_APEX_M (0.60 m).
//   COYOTE_S 0.1 s: a jump still starts just after walking off an edge. BUFFER_S 0.1 s: a press just before landing
//   jumps again on touchdown. Landing dips the eye about 1.4 cm per m/s of impact (cap 6 cm), critically damped
//   (OMEGA 45 rad/s: deepest at 22 ms, within 7 % by 120 ms).
//   WALK 1.4 m/s: a preferred adult walking speed in published gait studies (for example J. Appl. Physiol. 100,
//   2006). RUN_MIN 3.5 m/s to RUN_MAX 6.0 m/s: holding run, the wanted speed builds from a jog to a run along
//   1 - exp(-t / RUN_BUILD_S). Speed follows the wanted speed as v(t) = v_want (1 - exp(-t / tau)), the exponential
//   form measured for sprint starts (Proc. R. Soc. Lond. B 102, 1927); tau here (TAU_UP 0.6 s, TAU_DOWN 0.3 s) is
//   chosen for a casual start and stop, not measured.
//   Bob (off by default): the eye dips up to BOB_WALK_M (2 cm) walking and BOB_RUN_M (4 cm) running, once per step of
//   STEP_WALK_M (0.7 m) to STEP_RUN_M (1.4 m), eased back to level when still. Chosen values, not measured.

export const G = 9.81, V0 = 3.0, GRACE_S = 0.1, PUSH = 6.0, MAX_HOLD_S = 0.35, MAX_APEX_M = 0.6;
export const COYOTE_S = 0.1, BUFFER_S = 0.1;
export const OMEGA = 45, DIP_PER_MS = 1.43, DIP_MAX_M = 0.06, SETTLE_S = 0.15;
export const EYE = 1.7, BODY = Object.freeze({ radius: 0.3, below: 1.7, above: 0.1 });
export const STEP_UP_M = 0.05;   // a top this far above the feet still counts as underfoot (no stepping onto a table)
export const DROP_M = 0.3;       // a drop this small is walked down (a kerb); a bigger one is a fall
export const TOP_GAP_M = 1e-4;   // stand this far above a solid's top, so the body never counts as inside it
export const TELEPORT_M = 5;     // the world moved the viewer further than this in one step (Find, a tour): start there
export const WALK = 1.4, RUN_MIN = 3.5, RUN_MAX = 6.0, RUN_BUILD_S = 2.0, TAU_UP = 0.6, TAU_DOWN = 0.3;
export const BOB_WALK_M = 0.02, BOB_RUN_M = 0.04, STEP_WALK_M = 0.7, STEP_RUN_M = 1.4, BOB_EASE_S = 0.2;

export const apexOf = (v = V0, g = G) => (v * v) / (2 * g);
export const airTimeOf = (v = V0, g = G) => (2 * v) / g;
// The wanted running speed after holding run for t seconds.
export const runWant = (t, lo = RUN_MIN, hi = RUN_MAX) => lo + (hi - lo) * (1 - Math.exp(-Math.max(0, t) / RUN_BUILD_S));
// The eye's landing dip (m, negative = down) t seconds after touchdown at impact speed vi.
export function dipAt(t, vi) {
  if (!(t >= 0)) return 0;
  const v0 = Math.min(DIP_PER_MS * Math.abs(vi), DIP_MAX_M * OMEGA * Math.E);
  return -v0 * t * Math.exp(-OMEGA * t);
}

const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
const num = v => (Number.isFinite(v) ? v : 0);

// True when a body with its eye at [x, y, z] overlaps a solid box.
export function blocked([x, y, z], solids, body = BODY) {
  for (const b of solids) {
    if (x > b.min[0] - body.radius && x < b.max[0] + body.radius &&
        y > b.min[1] - body.radius && y < b.max[1] + body.radius &&
        z - body.below < b.max[2] && z + body.above > b.min[2]) return true;
  }
  return false;
}

// What the feet rest on at (x, y): the ground, or the highest solid top under the footprint that is not above the feet
// by more than STEP_UP_M.
export function supportAt(x, y, feetZ, heightAt, solids = [], radius = BODY.radius) {
  let s = num(heightAt(x, y)), onSolid = false;
  for (const b of solids) {
    if (x <= b.min[0] - radius || x >= b.max[0] + radius || y <= b.min[1] - radius || y >= b.max[1] + radius) continue;
    const top = b.max[2] + TOP_GAP_M;
    if (top > s && top <= feetZ + STEP_UP_M) { s = top; onSolid = true; }
  }
  return { z: s, onSolid };
}

// The body: pure state plus step(dt, input, heightAt, solids). input: { forward, strafe (-1..1), run, jump (held) }.
// yaw: radians from north towards east (forward is [sin yaw, cos yaw]).
export function createBody({ at = [0, 0, 0], yaw = 0, walk = WALK, runMin = RUN_MIN, runMax = RUN_MAX, bob = false } = {}) {
  let feet = [num(at[0]), num(at[1]), num(at[2])];
  let vel = [0, 0], t = 0, runT = 0, air = null, pressT = -Infinity, holding = false, dip = null;
  let jumps = 0, wasJump = false, bobOn = !!bob, dist = 0, bobAmp = 0, placed = false;
  const landings = [], events = [];

  const dipNow = () => (dip ? dipAt(t - dip.t0, dip.vi) : 0);
  const speed = () => Math.hypot(vel[0], vel[1]);
  const stepLen = () => STEP_WALK_M + (STEP_RUN_M - STEP_WALK_M) * clamp((speed() - walk) / (runMax - walk), 0, 1);
  const bobNow = () => (bobOn ? -bobAmp * (1 - Math.cos((2 * Math.PI * dist) / stepLen())) / 2 : 0);

  function place(p, heightAt, solids) {
    const guess = Number.isFinite(p[2]) ? p[2] - EYE : num(heightAt(p[0], p[1]));
    feet = [p[0], p[1], supportAt(p[0], p[1], guess, heightAt, solids).z]; vel = [0, 0]; air = null; dip = null; runT = 0; placed = true;
  }

  const takeOff = () => {
    air = { vz: V0, t0: t, feet0: feet[2], coyote: false, top: 0 };
    pressT = -Infinity; dip = null; jumps++;
    events.push({ topic: 'jumped', data: { t, speed: speed() } });
  };

  // Horizontal move by (dx, dy) at eye height z, sliding along solids; returns the new [x, y].
  function slide(dx, dy, z, solids) {
    const [x, y] = feet;
    if (!blocked([x + dx, y + dy, z], solids)) return [x + dx, y + dy];
    if (!blocked([x + dx, y, z], solids)) { vel[1] = 0; return [x + dx, y]; }
    if (!blocked([x, y + dy, z], solids)) { vel[0] = 0; return [x, y + dy]; }
    vel = [0, 0]; return [x, y];
  }

  function fly(dt, heightAt, solids) {
    const a = air, since = t - a.t0;
    let acc = -G;
    if (holding && !a.coyote && a.vz > 0 && since >= GRACE_S && since < MAX_HOLD_S && feet[2] - a.feet0 + a.vz * a.vz / (2 * G) < MAX_APEX_M) acc += PUSH;
    let vz = a.vz + acc * dt, z = feet[2] + a.vz * dt + 0.5 * acc * dt * dt;
    if (acc > -G && vz > 0) {                                           // pushing: never past MAX_APEX_M
      const over = z - a.feet0 + vz * vz / (2 * G) - MAX_APEX_M;
      if (over > 0) vz = Math.sqrt(Math.max(0, vz * vz - 2 * G * over));
    }
    const [x, y] = slide(vel[0] * dt, vel[1] * dt, z + EYE, solids);
    if (vz > 0 && blocked([x, y, z + EYE], solids)) { z = feet[2]; vz = 0; } // head against something above
    a.top = Math.max(a.top, z - a.feet0);
    const s = supportAt(x, y, Math.max(feet[2], z), heightAt, solids);
    if (vz <= 0 && z <= s.z) {                                          // touchdown on the ground or a solid top
      air = null; feet = [x, y, s.z]; dip = { t0: t + dt, vi: -vz };
      const land = { t: t + dt, airTime: t + dt - a.t0, apex: a.top, vi: -vz, onSolid: s.onSolid, feet: s.z };
      landings.push(land); if (landings.length > 8) landings.shift();
      events.push({ topic: 'landed', data: land });
    } else { a.vz = vz; feet = [x, y, z]; }
  }

  // One fixed step of dt seconds.
  function step(dt, input = {}, heightAt = () => 0, solids = []) {
    if (!placed) place([feet[0], feet[1], NaN], heightAt, solids);
    const jumpHeld = !!input.jump;
    if (jumpHeld && !wasJump) { holding = true; pressT = t; }
    if (!jumpHeld && wasJump) holding = false;
    wasJump = jumpHeld;
    if (input.yaw !== undefined && Number.isFinite(input.yaw)) yaw = input.yaw;

    // Wanted velocity from the move axes, the heading and the gait.
    const f = clamp(num(input.forward), -1, 1), sd = clamp(num(input.strafe), -1, 1), len = Math.hypot(f, sd);
    const running = !!input.run && len > 0;
    runT = running ? runT + dt : 0;
    const want = len > 0 ? (running ? runWant(runT, runMin, runMax) : walk) : 0;
    const k = len > 1 ? 1 / len : 1, s = Math.sin(yaw), c = Math.cos(yaw);
    const wx = (s * f + c * sd) * k * want, wy = (c * f - s * sd) * k * want;

    const t1 = t + dt;
    if (t1 - pressT <= BUFFER_S && (!air || (air.coyote && pressT - air.t0 <= COYOTE_S))) takeOff();
    if (air) {
      fly(dt, heightAt, solids); t = t1;
      if (!air && t - pressT <= BUFFER_S) takeOff();                    // pressed just before touchdown
      return;
    }
    // On the ground: speed eases towards the wanted velocity (exact exponential for a fixed target).
    const tau = Math.hypot(wx, wy) > speed() ? TAU_UP : TAU_DOWN, e = 1 - Math.exp(-dt / tau);
    vel[0] += (wx - vel[0]) * e; vel[1] += (wy - vel[1]) * e;
    if (!(len > 0) && speed() < 1e-3) vel = [0, 0];
    const [x0, y0] = feet;
    const [x, y] = slide(vel[0] * dt, vel[1] * dt, feet[2] + EYE, solids);
    const sup = supportAt(x, y, feet[2], heightAt, solids);               // measured ground always counts: hills are walked
    const moved = Math.hypot(x - x0, y - y0);
    t = t1;
    dist += moved;
    const amp = bobOn ? (BOB_WALK_M + (BOB_RUN_M - BOB_WALK_M) * clamp((speed() - walk) / (runMax - walk), 0, 1)) * (speed() > 0.05 ? 1 : 0) : 0;
    bobAmp += (amp - bobAmp) * (1 - Math.exp(-dt / BOB_EASE_S));
    if (bobAmp < 1e-5 && amp === 0) { bobAmp = 0; dist = 0; }
    if (feet[2] - sup.z > DROP_M + moved) {                              // walked off an edge: fall, with coyote time
      air = { vz: 0, t0: t, feet0: feet[2], coyote: true, top: 0 };
      feet = [x, y, feet[2]];
    } else feet = [x, y, sup.z];
    if (dip && t - dip.t0 > SETTLE_S) dip = null;
  }

  return {
    step,
    // Called between steps: keep the feet on what is underfoot (ground can stream in late).
    settle(heightAt = () => 0, solids = []) {
      if (!placed) { place([feet[0], feet[1], NaN], heightAt, solids); return; }
      if (air) return;
      feet[2] = supportAt(feet[0], feet[1], feet[2], heightAt, solids).z;
    },
    press() { holding = true; pressT = t; },
    release() { holding = false; },
    place,
    // Moves the body to (x, y); the next step or settle puts the feet on what is there.
    unplace(x, y) { feet = [x, y, feet[2]]; vel = [0, 0]; air = null; dip = null; pressT = -Infinity; runT = 0; placed = false; },
    setYaw(v) { if (Number.isFinite(v)) yaw = v; },
    setBob(v) { bobOn = !!v; if (!bobOn) { bobAmp = 0; dist = 0; } },
    eye: () => [feet[0], feet[1], feet[2] + EYE + dipNow() + bobNow()],
    feet: () => feet.slice(),
    speed,
    airborne: () => !!air,
    // Frames are needed while moving, in the air, while a press waits and while the eye settles after a landing.
    busy: () => speed() > 0 || !!air || t - pressT <= BUFFER_S || (!!dip && t - dip.t0 <= SETTLE_S) || bobAmp > 0,
    take: () => events.splice(0),
    state: () => ({ t, pos: feet.slice(), vel: vel.slice(), yaw, speed: speed(), runT, airborne: !!air, vz: air ? air.vz : 0, rise: air ? feet[2] - air.feet0 : 0,
      holding, jumps, dip: dipNow(), bob: bobNow(), bobOn, landings: landings.slice() })
  };
}

// ---------------------------------------------------------------- the pack

let api = null, on = true, body = null, cfg = {}, lastCtx = null, adopt = 'first', lastEmit = null, typed = { forward: 0, strafe: 0, run: false }, jumpTicks = 0;
const gait = b => (b.airborne() ? 'in the air' : b.speed() < 0.05 ? 'standing' : b.speed() > (cfg.walk ?? WALK) + 0.3 ? 'running' : 'walking');
const yawOf = dir => (Array.isArray(dir) && Math.hypot(dir[0], dir[1]) > 1e-9 ? Math.atan2(dir[0], dir[1]) : undefined);
const numbers = a => a.map(Number);

function make() {
  const c = cfg;
  body = createBody({
    at: Array.isArray(c.at) ? c.at : [0, 0, 0], yaw: Number.isFinite(c.yaw) ? c.yaw : 0,
    walk: Number.isFinite(c.walk) ? c.walk : WALK, runMin: Number.isFinite(c.runMin) ? c.runMin : RUN_MIN,
    runMax: Number.isFinite(c.runMax) ? c.runMax : RUN_MAX, bob: c.bob === true
  });
  lastCtx = null; adopt = Array.isArray(c.at) ? 'teleport' : 'first';
}

export default {
  id: 'body',
  init(a) {
    api = a;
    const c = a.config || {};
    cfg = {};
    if (Array.isArray(c.at) && c.at.length >= 2 && c.at.slice(0, 2).every(Number.isFinite)) cfg.at = [c.at[0], c.at[1], NaN];
    for (const k of ['yaw', 'walk', 'runMin', 'runMax']) if (Number.isFinite(c[k]) && (k === 'yaw' || c[k] > 0)) cfg[k] = c[k];
    if (!(cfg.runMin > (cfg.walk ?? WALK))) delete cfg.runMin;
    if (!(cfg.runMax >= (cfg.runMin ?? RUN_MIN))) delete cfg.runMax;
    if (c.bob === true) cfg.bob = true;
    if (c.input && typeof c.input === 'object') typed = { forward: clamp(num(c.input.forward), -1, 1), strafe: clamp(num(c.input.strafe), -1, 1), run: !!c.input.run };
    make();
    a.events.on('world/toggle', () => {});
  },
  setEnabled(v) { on = !!v; if (!on) { typed = { forward: 0, strafe: 0, run: false }; jumpTicks = 0; } },
  // One fixed step. ctx: { pos, dir, heightAt, solids?, input? }. The world's held keys come in ctx.input
  // ({ forward, strafe, run, jump }); without it, the typed commands drive the body.
  step(dt, ctx = {}) {
    if (!body) return;
    const heightAt = typeof ctx.heightAt === 'function' ? ctx.heightAt : () => 0;
    const solids = Array.isArray(ctx.solids) ? ctx.solids : [];
    // The world moved the viewer itself (Find, a tour, the first step): start from there.
    const p = Array.isArray(ctx.pos) && ctx.pos.slice(0, 3).every(Number.isFinite) ? ctx.pos : null;
    if (p && (adopt === 'first' || (lastCtx && Math.hypot(p[0] - lastCtx[0], p[1] - lastCtx[1]) > TELEPORT_M &&
        Math.hypot(p[0] - body.feet()[0], p[1] - body.feet()[1]) > TELEPORT_M))) { body.place([p[0], p[1], p[2]], heightAt, solids); adopt = 'teleport'; }
    if (p) lastCtx = p.slice(0, 3);
    const i = ctx.input && typeof ctx.input === 'object' ? ctx.input : typed;
    const input = { forward: i.forward, strafe: i.strafe, run: !!i.run, jump: !!i.jump || jumpTicks > 0, yaw: yawOf(ctx.dir) };
    if (jumpTicks > 0) jumpTicks--;
    const before = body.state();
    body.step(dt, input, heightAt, solids);
    if (api) {
      for (const e of body.take()) api.events.emit(e.topic, e.data);
      const eye = body.eye(), st = body.state();
      if (!lastEmit || Math.hypot(eye[0] - lastEmit[0], eye[1] - lastEmit[1], eye[2] - lastEmit[2]) > 1e-6 || st.airborne !== before.airborne) {
        lastEmit = eye;
        api.events.emit('pose', { pos: eye, yaw: st.yaw, speed: st.speed, gait: gait(body), airborne: st.airborne });
      }
    }
  },
  active() {
    if (!on || !body) return false;
    return body.busy() || typed.forward !== 0 || typed.strafe !== 0 || jumpTicks > 0;
  },
  hud() {
    if (!body) return [];
    const s = body.state(), g = gait(body);
    const lines = [{ id: 'gait', text: `${g}, ${s.speed.toFixed(1)} m/s${s.bobOn ? ', bob on' : ''}` }];
    if (s.airborne) lines.push({ id: 'jump', text: `jump ${s.rise.toFixed(2)} m, rising ${s.vz.toFixed(1)} m/s` });
    else if (s.landings.length) { const l = s.landings.at(-1); lines.push({ id: 'jump', text: `last jump ${l.apex.toFixed(2)} m high, ${l.airTime.toFixed(2)} s in the air` }); }
    return lines;
  },
  commands() {
    return [
      {
        verb: 'jump',
        run(args) {
          const w = (args[0] || '').toLowerCase();
          if (!w) { body.press(); body.release(); return `jump (${apexOf().toFixed(2)} m on level ground)`; }
          if (w === 'high') { jumpTicks = Math.round(MAX_HOLD_S / (api?.fixedDt || 1 / 60)); return `jump, held for ${MAX_APEX_M.toFixed(2)} m`; }
          throw Error('jump, or jump high (held for the full push)');
        }
      },
      {
        verb: 'run',
        run(args) {
          const w = (args[0] || '').toLowerCase();
          if (w === 'on' || (w === '' && !typed.run)) typed.run = true;
          else if (w === 'off' || w === '') typed.run = false;
          else throw Error('run, run on or run off');
          return typed.run ? `running: ${RUN_MIN}-${RUN_MAX} m/s while moving` : `walking: ${cfg.walk ?? WALK} m/s`;
        }
      },
      {
        verb: 'body',
        run(args) {
          const w = (args[0] || '').toLowerCase();
          if (!w) { const s = body.state(); return `${gait(body)} ${s.speed.toFixed(1)} m/s at ${s.pos.map(v => v.toFixed(1)).join(' ')} m`; }
          if (w === 'move') {
            const [f, s] = numbers(args.slice(1, 3));
            if (!Number.isFinite(f) || (args[2] !== undefined && !Number.isFinite(s))) throw Error('body move needs numbers from -1 to 1: body move 1  ·  body move 0 -1');
            typed.forward = clamp(f, -1, 1); typed.strafe = clamp(num(s), -1, 1);
            return `moving ${typed.forward} forward, ${typed.strafe} right`;
          }
          if (w === 'stop') { typed.forward = 0; typed.strafe = 0; typed.run = false; return 'stopping'; }
          if (w === 'bob') {
            const v = (args[1] || '').toLowerCase();
            if (v !== 'on' && v !== 'off') throw Error('body bob on or body bob off');
            body.setBob(v === 'on'); return `footstep bob ${v}`;
          }
          if (w === 'at') {
            const [x, y] = numbers(args.slice(1, 3));
            if (!Number.isFinite(x) || !Number.isFinite(y)) throw Error('body at needs two numbers in local metres: body at 10 20');
            body.unplace(x, y); adopt = 'teleport'; lastCtx = null;
            return `standing at ${x} ${y} m`;
          }
          throw Error('body, body move <forward> [right], body stop, body bob on|off or body at <x> <y>');
        }
      }
    ];
  },
  dispose() { api = null; body = null; lastCtx = null; adopt = 'first'; lastEmit = null; typed = { forward: 0, strafe: 0, run: false }; jumpTicks = 0; }
};

Drone

A JavaScript module in the packs folder of GlobalGrid2050 that parses xy (`parseXY`) and calculates planar distances and angles (units: kV), covering wind, using ISO 2533.

ingestglobalgrid2050 / solar-design-studio/202609271853-site-world/packs/drone/src/drone.mjs · lines 1–382 of 414 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern corner (shared by 2 files)

What it does
Defines 24 functions or classes, including clamp, num, terminalSpeed, windVector, footprint.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: wind.
What it achieves
It parses xy (`parseXY`) and is built from the clamp step (`clamp`) and the num step (`num`). Drone pack (world.pack.v1, kind vehicle). A light multirotor model for our 3D worlds: thrust, quadratic drag and wind as a parameter, hover hold, height above the ground model, speed limits, a legal-height note, go-to.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/packs/drone/src · JavaScript module
Uses
none found
Used by
none found
Produces
DEFAULTS, LEGAL_NOTE, AERIAL_VIEW, terminalSpeed, windVector, footprint, planSurvey, createDrone
Defines here
clamp, num, terminalSpeed, windVector, footprint, planSurvey, toU, toXY, createDrone, wanted, toward, reset, batch, seg, here, heading, aglAt, parseXY, legal, status, emit, corner, lift, need
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/packs/drone/src/drone.mjs:1-382 · blob 4c820cdcad2c518ff68c200b68df33f253993347 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// Drone pack (world.pack.v1, kind vehicle). A light multirotor model for our 3D worlds: thrust, quadratic drag and wind
// as a parameter, hover hold, height above the ground model, speed limits, a legal-height note, go-to, orbit and
// survey modes (a lawnmower pattern over a boundary with front and side overlap), and the camera footprint on the ground.
// The world's aerial view is the "view" mode: the viewer is the drone, and this pack reports its height and footprint.
//
// ILLUSTRATIVE. The flight model is a point mass with a tilt-limited thrust vector and a PI velocity controller.
// It is not a model of any particular aircraft, and nothing here is flight planning or legal advice.
// Self-contained: no imports. Deterministic: fixed steps only, no clock, no random numbers.

const G = 9.80665;                 // standard gravity, m/s^2
const RHO = 1.225;                 // air density at sea level in the ISO 2533 standard atmosphere, kg/m^3
const DEG = Math.PI / 180;

// Defaults. Every one is an assumption for an illustrative small multirotor and can be set in the world's pin config.
export const DEFAULTS = Object.freeze({
  mass: 1.2,            // kg
  cda: 0.03,            // drag coefficient x frontal area, m^2
  thrustRatio: 2.0,     // maximum thrust / weight
  maxTilt: 35,          // degrees from level
  maxSpeed: 15,         // horizontal speed limit, m/s
  climb: 5,             // m/s
  descent: 3,           // m/s
  hold: 30,             // default hover height above the ground, m
  ceiling: 120,         // legal height note, m above the surface (see LEGAL_NOTE)
  wind: [0, 0],         // [speed m/s, direction it blows FROM in degrees, 0 = north (+y), 90 = east (+x)]
  camera: { hfov: 73.7, vfov: 53.1, px: 5472 }, // nadir camera: fields of view in degrees, image width in pixels
  overlap: { front: 75, side: 65 },            // survey overlap, %
  skids: 0.15           // m from the centre down to the landing skids
});

export const LEGAL_NOTE = 'UK drone code, open category: keep below 120 m (400 ft) above the surface; check current rules';

// The world's own aerial view, which this pack takes over as its "view" mode (same speeds and clearance).
export const AERIAL_VIEW = Object.freeze({ speed: 25, slow: 5, clearance: 0.3 });

const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
const num = v => { const n = Number(v); return Number.isFinite(n) ? n : NaN; };

// Top horizontal speed in still air when thrust is tilt-limited: the horizontal thrust m g tan(tilt) equals drag
// 0.5 rho CdA v^2. The same figure is the strongest steady wind the drone can hold station in.
export function terminalSpeed(p = DEFAULTS) {
  return Math.sqrt((2 * p.mass * G * Math.tan(p.maxTilt * DEG)) / (RHO * p.cda));
}

// Wind [speed, from degrees] as a velocity vector (the air moves TOWARDS from + 180).
export function windVector([speed, from]) {
  const a = from * DEG;
  return [-speed * Math.sin(a), -speed * Math.cos(a), 0];
}

// Ground footprint of a nadir camera at height h above flat ground: 2 h tan(fov / 2) each way.
export function footprint(h, cam = DEFAULTS.camera) {
  const w = 2 * h * Math.tan((cam.hfov * DEG) / 2), l = 2 * h * Math.tan((cam.vfov * DEG) / 2);
  return { w, l, gsd: w / cam.px }; // gsd: metres of ground per pixel across the image
}

// Lawnmower survey over a boundary polygon [[x, y], ...]. Lanes run along the longest edge; lane spacing is the
// footprint width times (1 - side overlap); photo spacing along a lane is the footprint length times (1 - front overlap).
export function planSurvey(boundary, { height = DEFAULTS.hold, camera = DEFAULTS.camera, overlap = DEFAULTS.overlap, maxLanes = 400 } = {}) {
  if (!Array.isArray(boundary) || boundary.length < 3) throw Error('a survey boundary needs at least three corners');
  const fp = footprint(height, camera);
  const spacing = fp.w * (1 - overlap.side / 100), photoStep = fp.l * (1 - overlap.front / 100);
  if (!(spacing > 0) || !(photoStep > 0)) throw Error('overlap must be below 100%');
  let best = 0, ang = 0;
  for (let i = 0; i < boundary.length; i++) {
    const [ax, ay] = boundary[i], [bx, by] = boundary[(i + 1) % boundary.length];
    const d = Math.hypot(bx - ax, by - ay);
    if (d > best) { best = d; ang = Math.atan2(by - ay, bx - ax); }
  }
  const c = Math.cos(ang), s = Math.sin(ang);
  const toU = ([x, y]) => [x * c + y * s, -x * s + y * c];      // u along the lanes, v across them
  const toXY = (u, v) => [u * c - v * s, u * s + v * c];
  const poly = boundary.map(toU);
  let vmin = Infinity, vmax = -Infinity;
  for (const [, v] of poly) { vmin = Math.min(vmin, v); vmax = Math.max(vmax, v); }
  const lanes = [], n = Math.max(1, Math.ceil((vmax - vmin) / spacing));
  if (n > maxLanes) throw Error(`the survey needs ${n} lanes, more than ${maxLanes}; fly higher or lower the side overlap`);
  const first = vmin + ((vmax - vmin) - (n - 1) * spacing) / 2;  // centre the lanes over the boundary
  for (let k = 0; k < n; k++) {
    const v = first + k * spacing, xs = [];
    for (let i = 0; i < poly.length; i++) {
      const [u1, v1] = poly[i], [u2, v2] = poly[(i + 1) % poly.length];
      if ((v1 <= v && v < v2) || (v2 <= v && v < v1)) xs.push(u1 + ((v - v1) / (v2 - v1)) * (u2 - u1));
    }
    xs.sort((a, b) => a - b);
    for (let j = 0; j + 1 < xs.length; j += 2) lanes.push({ v, u0: xs[j], u1: xs[j + 1] });
  }
  const waypoints = [];
  let length = 0, photos = 0;
  lanes.forEach((l, k) => {
    const [a, b] = k % 2 ? [l.u1, l.u0] : [l.u0, l.u1];
    waypoints.push(toXY(a, l.v), toXY(b, l.v));
    length += Math.abs(l.u1 - l.u0);
    photos += Math.floor(Math.abs(l.u1 - l.u0) / photoStep) + 1;
  });
  for (let i = 1; i < waypoints.length; i += 2) if (waypoints[i + 1]) length += Math.hypot(waypoints[i + 1][0] - waypoints[i][0], waypoints[i + 1][1] - waypoints[i][1]);
  return { heading: ang, spacing, photoStep, lanes: lanes.length, waypoints, length, photos, footprint: fp, height, overlap: { ...overlap } };
}

// One drone: state plus a deterministic fixed step. Pure apart from its own state; the entry below wraps one.
export function createDrone(cfg = {}) {
  const p = { ...DEFAULTS, ...cfg, camera: { ...DEFAULTS.camera, ...(cfg.camera || {}) }, overlap: { ...DEFAULTS.overlap, ...(cfg.overlap || {}) } };
  const d = {
    p,
    pos: [0, 0, p.skids], vel: [0, 0, 0], thrust: [0, 0, 0], integ: [0, 0],
    mode: 'idle', airborne: false, hold: p.hold, target: null, orbit: null, survey: null, wp: 0,
    speedLimit: Math.min(p.maxSpeed, terminalSpeed(p)), steps: 0, t: 0, saturated: false, agl: 0, ground: 0
  };

  d.launch = (x, y, ground = 0) => {
    d.pos = [x, y, ground + p.skids]; d.vel = [0, 0, 0]; d.integ = [0, 0];
    d.airborne = true; d.mode = 'hover'; d.target = [x, y];
  };

  // The velocity this mode asks for, horizontal [vx, vy] in m/s.
  function wanted() {
    const [x, y] = d.pos, lim = d.speedLimit;
    const toward = ([tx, ty], stopAt = true) => {
      const dx = tx - x, dy = ty - y, r = Math.hypot(dx, dy);
      if (r < 1e-9) return [0, 0, r];
      const brake = G * Math.tan(p.maxTilt * DEG) * 0.5;       // plan to stop on half the available deceleration
      const v = stopAt ? Math.min(lim, Math.sqrt(2 * brake * r), 1.2 * r) : lim;
      return [(dx / r) * v, (dy / r) * v, r];
    };
    if (d.mode === 'hover' || d.mode === 'land' || d.mode === 'goto') { const [vx, vy] = toward(d.target); return [vx, vy]; }
    if (d.mode === 'orbit') {
      const { c, r, dir } = d.orbit, dx = x - c[0], dy = y - c[1], rr = Math.hypot(dx, dy) || 1e-9;
      const ux = dx / rr, uy = dy / rr, v = Math.min(lim, d.orbit.speed);
      const radial = clamp(1.0 * (r - rr), -lim, lim);
      return [-uy * v * dir + ux * radial, ux * v * dir + uy * radial];
    }
    if (d.mode === 'survey') {
      const wps = d.survey.waypoints, w = wps[d.wp];
      const last = d.wp === wps.length - 1;
      const [vx, vy, r] = toward(w, last);
      if (r < 1.0) { if (last) { d.mode = 'hover'; d.target = [x, y]; } else d.wp++; }
      return [vx, vy];
    }
    return [0, 0];
  }

  d.step = (dt, heightAt = () => 0) => {
    if (!d.airborne) return;
    d.steps++; d.t += dt;
    const m = p.mass, tmax = p.thrustRatio * m * G, tanT = Math.tan(p.maxTilt * DEG);
    const ground = heightAt(d.pos[0], d.pos[1]);
    const g0 = Number.isFinite(ground) ? ground : d.ground;
    d.ground = g0;
    // Vertical: hold height above the ground model; land: descend to the skids.
    const zWant = d.mode === 'land' ? g0 + p.skids - 1 : g0 + d.hold;
    const vzWant = clamp(1.2 * (zWant - d.pos[2]), -p.descent, p.climb);
    const [vxWant, vyWant] = wanted();
    // PI velocity controller. The integral learns the wind; it stops growing while the thrust is saturated.
    const kv = 2.5, ki = 0.8;
    const ex = vxWant - d.vel[0], ey = vyWant - d.vel[1];
    if (!d.saturated) { d.integ[0] += ex * dt; d.integ[1] += ey * dt; }
    const ax = kv * ex + ki * d.integ[0], ay = kv * ey + ki * d.integ[1];
    const az = 3.0 * (vzWant - d.vel[2]);
    // Thrust: vertical first, then the horizontal part within the tilt and total thrust limits.
    let tz = clamp(m * (G + az), 0, tmax * Math.cos(p.maxTilt * DEG));
    let tx = m * ax, ty = m * ay;
    const th = Math.hypot(tx, ty), thMax = Math.min(tz * tanT, Math.sqrt(Math.max(0, tmax * tmax - tz * tz)));
    d.saturated = th > thMax;
    if (d.saturated) { tx *= thMax / th; ty *= thMax / th; }
    d.thrust = [tx, ty, tz];
    // Forces: thrust, quadratic drag on the air-relative velocity, weight.
    const w = windVector(p.wind);
    const rx = d.vel[0] - w[0], ry = d.vel[1] - w[1], rz = d.vel[2] - w[2], rv = Math.hypot(rx, ry, rz);
    const k = 0.5 * RHO * p.cda * rv;
    const a = [(tx - k * rx) / m, (ty - k * ry) / m, (tz - k * rz) / m - G];
    // Semi-implicit Euler.
    for (let i = 0; i < 3; i++) { d.vel[i] += a[i] * dt; d.pos[i] += d.vel[i] * dt; }
    const floor = heightAt(d.pos[0], d.pos[1]);
    const gz = (Number.isFinite(floor) ? floor : g0) + p.skids;
    if (d.pos[2] < gz) {
      d.pos[2] = gz;
      if (d.vel[2] < 0) d.vel[2] = 0;
      if (d.mode === 'land') { d.airborne = false; d.mode = 'idle'; d.vel = [0, 0, 0]; d.integ = [0, 0]; }
    }
    d.agl = d.pos[2] - (Number.isFinite(floor) ? floor : g0);
  };

  d.hspeed = () => Math.hypot(d.vel[0], d.vel[1]);
  d.tilt = () => Math.atan2(Math.hypot(d.thrust[0], d.thrust[1]), d.thrust[2]) / DEG;
  return d;
}

// ---------------------------------------------------------------- the entry the world loads

const RING = 12, ARM = 0.35, ROTOR = 0.14;
const C_BODY = [0.95, 0.95, 0.98, 1], C_ROTOR = [0.55, 0.8, 1, 0.9], C_STICK = [1, 0.8, 0.3, 0.7];
const C_PATH = [0.45, 1, 0.6, 0.8], C_FOOT = [1, 0.55, 0.25, 0.9], C_TRAIL = [0.8, 0.8, 1, 0.45];
const TRAIL = 120, TRAIL_EVERY = 15;   // one trail point every 0.25 s, 30 s of trail

let api = null, on = true, drone = null, cfg = {}, heightAt = () => 0, viewer = [0, 0, 1.7], viewing = false;
let planVersion = 0, trail = [], cache = new Map(), lastPose = -1;

function reset() {
  drone = createDrone(cfg); trail = []; planVersion++; cache = new Map(); lastPose = -1;
}

function batch(key, version, color, origin, fill, segs) {
  const hit = cache.get(key);
  if (hit && hit.version === version) return hit;
  const positions = new Float32Array(segs * 6);
  let i = 0;
  const seg = (a, b) => { positions.set([a[0] - origin[0], a[1] - origin[1], a[2] - origin[2], b[0] - origin[0], b[1] - origin[1], b[2] - origin[2]], i); i += 6; };
  fill(seg);
  const b = { key, version, color, origin, positions: i === positions.length ? positions : positions.slice(0, i) };
  cache.set(key, b);
  return b;
}

// Where the drone is for drawing and the HUD: the simulated drone, or the viewer in view mode.
function here() {
  if (viewing) return viewer;
  return drone.pos;
}

function heading() {
  if (drone.mode === 'survey') return drone.survey.heading;
  const s = drone.hspeed();
  return s > 0.5 ? Math.atan2(drone.vel[1], drone.vel[0]) : 0;
}

function aglAt(p) { const g = heightAt(p[0], p[1]); return Number.isFinite(g) ? p[2] - g : NaN; }

function parseXY(args, i, what) {
  const x = num(args[i]), y = num(args[i + 1]);
  if (!Number.isFinite(x) || !Number.isFinite(y)) throw Error(`${what} needs two numbers in local metres`);
  return [x, y];
}

function legal(h) {
  if (h > drone.p.ceiling) throw Error(`${h} m is above the ${drone.p.ceiling} m height note (${LEGAL_NOTE})`);
  if (h < 2) throw Error('hold at least 2 m above the ground');
  return h;
}

function status() {
  const p = here(), a = aglAt(p);
  return `drone ${viewing ? 'view' : drone.mode} at ${p[0].toFixed(1)} ${p[1].toFixed(1)} m, ${Number.isFinite(a) ? a.toFixed(1) : '?'} m above ground, ` +
    `${drone.hspeed().toFixed(1)} m/s, limit ${drone.speedLimit.toFixed(1)} m/s (illustrative)`;
}

function emit(topic, payload) { try { api?.events.emit(topic, payload); } catch (e) { api?.log?.(`drone: ${e.message}`); } }

export default {
  id: 'drone',
  init(a) {
    api = a;
    const c = a.config || {};
    cfg = {};
    for (const k of ['mass', 'cda', 'thrustRatio', 'maxTilt', 'maxSpeed', 'climb', 'descent', 'hold', 'ceiling', 'skids']) {
      if (Number.isFinite(c[k]) && c[k] > 0) cfg[k] = c[k];
    }
    if (cfg.ceiling > 120) cfg.ceiling = 120;   // the note never loosens past the open-category figure
    if (Array.isArray(c.wind) && c.wind.length === 2 && c.wind.every(Number.isFinite)) cfg.wind = [Math.max(0, c.wind[0]), c.wind[1]];
    if (c.camera && typeof c.camera === 'object') cfg.camera = c.camera;
    if (c.overlap && typeof c.overlap === 'object') cfg.overlap = c.overlap;
    reset();
    if (Array.isArray(c.launch) && c.launch.length === 2 && c.launch.every(Number.isFinite)) drone.launch(c.launch[0], c.launch[1], 0);
    a.events.on('world/pose', ({ pos } = {}) => { if (Array.isArray(pos) && pos.length === 3) viewer = [...pos]; });
  },
  setEnabled(v) { on = !!v; if (!on && drone) { viewing = false; } },
  step(dt, ctx = {}) {
    if (typeof ctx.heightAt === 'function') heightAt = ctx.heightAt;
    if (!drone.airborne) return;
    drone.step(dt, heightAt);
    if (drone.steps % TRAIL_EVERY === 0) { trail.push([...drone.pos]); if (trail.length > TRAIL) trail.shift(); }
    if (drone.steps % 6 === 0 && drone.steps !== lastPose) {
      lastPose = drone.steps;
      emit('pose', { pos: [...drone.pos], vel: [...drone.vel], agl: drone.agl, mode: drone.mode });
    }
  },
  active() { return on && !!drone && drone.airborne && !viewing; },
  lines(ctx = {}) {
    if (typeof ctx.heightAt === 'function') heightAt = ctx.heightAt;
    if (viewing && Array.isArray(ctx.pos)) viewer = [...ctx.pos];
    const out = [], p = here(), v = `${drone.steps}|${p.join(',')}|${viewing}|${ctx.groundVersion ?? ''}`;
    const g = heightAt(p[0], p[1]), gz = Number.isFinite(g) ? g : 0;
    if (!viewing) {
      const o = [...p];
      out.push(batch('body', v, C_BODY, o, seg => {
        seg([p[0] - ARM, p[1] - ARM, p[2]], [p[0] + ARM, p[1] + ARM, p[2]]);
        seg([p[0] - ARM, p[1] + ARM, p[2]], [p[0] + ARM, p[1] - ARM, p[2]]);
      }, 2));
      out.push(batch('rotors', v, C_ROTOR, o, seg => {
        for (const [sx, sy] of [[1, 1], [1, -1], [-1, 1], [-1, -1]]) {
          const cx = p[0] + sx * ARM, cy = p[1] + sy * ARM;
          for (let i = 0; i < RING; i++) {
            const a0 = (i / RING) * 2 * Math.PI, a1 = ((i + 1) / RING) * 2 * Math.PI;
            seg([cx + ROTOR * Math.cos(a0), cy + ROTOR * Math.sin(a0), p[2] + 0.04], [cx + ROTOR * Math.cos(a1), cy + ROTOR * Math.sin(a1), p[2] + 0.04]);
          }
        }
      }, 4 * RING));
    }
    // Height stick from the drone down to the ground model.
    out.push(batch('stick', v, C_STICK, [p[0], p[1], gz], seg => seg([p[0], p[1], gz], [p[0], p[1], p[2]]), 1));
    // Camera footprint on the ground (nadir camera, sized from the height above the ground under the drone).
    const agl = p[2] - gz;
    if (agl > 1) {
      const f = footprint(agl, drone.p.camera), hd = heading(), c = Math.cos(hd), s = Math.sin(hd);
      const corner = (u, w) => { const x = p[0] + u * c - w * s, y = p[1] + u * s + w * c, h = heightAt(x, y); return [x, y, (Number.isFinite(h) ? h : gz) + 0.05]; };
      const q = [corner(f.l / 2, f.w / 2), corner(-f.l / 2, f.w / 2), corner(-f.l / 2, -f.w / 2), corner(f.l / 2, -f.w / 2)];
      out.push(batch('footprint', v, C_FOOT, [p[0], p[1], gz], seg => { for (let i = 0; i < 4; i++) seg(q[i], q[(i + 1) % 4]); }, 4));
    }
    // The plan: survey lanes or orbit circle, at flying height over the ground.
    const pv = `${planVersion}|${ctx.groundVersion ?? ''}`;
    const lift = (x, y) => { const h = heightAt(x, y); return [x, y, (Number.isFinite(h) ? h : gz) + drone.hold]; };
    if (!viewing && drone.mode === 'survey') {
      const w = drone.survey.waypoints, o = lift(w[0][0], w[0][1]);
      out.push(batch('plan', pv, C_PATH, o, seg => { for (let i = 0; i + 1 < w.length; i++) seg(lift(...w[i]), lift(...w[i + 1])); }, w.length - 1));
    } else if (!viewing && drone.mode === 'orbit') {
      const { c, r } = drone.orbit, n = 64, o = lift(c[0], c[1]);
      out.push(batch('plan', pv, C_PATH, o, seg => {
        for (let i = 0; i < n; i++) {
          const a0 = (i / n) * 2 * Math.PI, a1 = ((i + 1) / n) * 2 * Math.PI;
          seg(lift(c[0] + r * Math.cos(a0), c[1] + r * Math.sin(a0)), lift(c[0] + r * Math.cos(a1), c[1] + r * Math.sin(a1)));
        }
      }, n));
    }
    if (!viewing && trail.length > 1) {
      out.push(batch('trail', `${drone.steps - (drone.steps % TRAIL_EVERY)}|${trail.length}`, C_TRAIL, trail[0], seg => {
        for (let i = 0; i + 1 < trail.length; i++) seg(trail[i], trail[i + 1]);
      }, trail.length - 1));
    }
    return out;
  },
  hud() {
    const p = here(), a = aglAt(p), dp = drone.p;
    const mode = viewing ? 'view' : drone.mode;
    let what = `drone ${mode}, ${drone.hspeed().toFixed(1)} m/s, limit ${drone.speedLimit.toFixed(0)} m/s`;
    if (!viewing && drone.mode === 'survey') what += `, leg ${drone.wp}/${drone.survey.waypoints.length - 1}`;
    const over = Number.isFinite(a) && a > dp.ceiling;
    const height = `${Number.isFinite(a) ? a.toFixed(1) : '?'} m above ground` + (over ? `, ABOVE ${dp.ceiling} m note` : `, note ${dp.ceiling} m`);
    const holdable = terminalSpeed(dp);
    const wind = `wind ${dp.wind[0].toFixed(1)} m/s from ${dp.wind[1].toFixed(0)} deg, tilt ${drone.tilt().toFixed(0)} deg` +
      (dp.wind[0] > holdable ? ', too strong to hold' : '');
    const f = footprint(Math.max(0, Number.isFinite(a) ? a : 0), dp.camera);
    const foot = `footprint ${f.w.toFixed(0)} x ${f.l.toFixed(0)} m, ${(f.gsd * 100).toFixed(1)} cm/px, overlap ${dp.overlap.front}/${dp.overlap.side}%`;
    return [{ id: 'mode', text: what }, { id: 'height', text: height }, { id: 'wind', text: wind }, { id: 'camera', text: foot }];
  },
  commands() {
    return [{
      verb: 'drone',
      run(args) {
        const w = (args[0] || 'status').toLowerCase(), dp = drone.p;
        const need = () => { if (!drone.airborne) throw Error('launch first: drone launch'); };
        if (w === 'status') return status();
        if (w === 'launch') {
          const [x, y] = args.length >= 3 ? parseXY(args, 1, 'drone launch') : [viewer[0], viewer[1]];
          const g = heightAt(x, y);
          viewing = false; trail = []; drone.launch(x, y, Number.isFinite(g) ? g : 0);
          return `drone launched at ${x.toFixed(1)} ${y.toFixed(1)} m, climbing to ${drone.hold} m above ground (illustrative)`;
        }
        if (w === 'land') { need(); drone.mode = 'land'; drone.target = [drone.pos[0], drone.pos[1]]; planVersion++; return 'drone landing'; }
        if (w === 'hover') { need(); drone.mode = 'hover'; drone.target = [drone.pos[0], drone.pos[1]]; planVersion++; return 'drone holding position'; }
        if (w === 'hold') {
          const h = num(args[1]);
          if (!Number.isFinite(h)) throw Error('drone hold <metres above ground>, for example drone hold 50');
          drone.hold = legal(h); return `drone holds ${h} m above the ground model`;
        }
        if (w === 'goto') { need(); drone.target = parseXY(args, 1, 'drone goto'); drone.mode = 'goto'; planVersion++; return `drone flying to ${drone.target.join(' ')} m`; }
        if (w === 'speed') {
          const s = num(args[1]);
          if (!(s > 0)) throw Error('drone speed <m/s>, for example drone speed 8');
          const cap = Math.min(dp.maxSpeed, terminalSpeed(dp));
          drone.speedLimit = Math.min(s, cap);
          return `drone speed limit ${drone.speedLimit.toFixed(1)} m/s` + (s > cap ? ` (capped at ${cap.toFixed(1)} m/s)` : '');
        }
        if (w === 'wind') {
          const s = num(args[1]), from = num(args[2] ?? 0);
          if (!(s >= 0) || !Number.isFinite(from)) throw Error('drone wind <m/s> <from degrees>, for example drone wind 8 270');
          dp.wind = [s, ((from % 360) + 360) % 360];
          const hold = terminalSpeed(dp);
          return `wind ${s} m/s from ${dp.wind[1]} deg` + (s > hold ? `; above the ${hold.toFixed(1)} m/s this drone can hold against` : '');
        }
        if (w === 'orbit') {
          need();
          const c = parseXY(args, 1, 'drone orbit'), r = num(args[3]), sp = args[4] === undefined ? 5 : num(args[4]);
          if (!(r >= 5)) throw Error('drone orbit <x> <y> <radius m, at least 5> [speed m/s]');