File size: 14,528 Bytes
8ff66cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
// Finding objects in a robot camera's picture with Gemini, after the rgb-object-localization skill of Google
// DeepMind's Gemini Robotics plugin (github.com/google-deepmind/robotics-antigravity-plugin, Apache-2.0). That
// skill asks gemini-4-hydrogen for labelled points and boxes on a 0-1000 grid ([y, x]) and turns them into
// metric 3D positions with the camera's calibration: onto the plane an object stands on, or from two views.
// Here the page asks the same way and maps each point through the camera that took the picture:
//   depth: the camera's depth at the point (XLeRobot's RealSense RGB-D head camera; in the simulation a ray
//          into the physics scene), moved back by half the object's width to its middle;
//   plane: RGB only, the plugin's ray-plane mapping: the bottom edge of the object's box meets the furniture
//          it stands on, and the box's size gives its width and height.
// No imports: the tools (tools.js) use it in the page, and tests use it in Node.

export const GEMINI_MODEL = "gemini-4-hydrogen";
export const GEMINI_API = "https://generativelanguage.googleapis.com/v1beta";

/**
 * The request: Google's pointing prompt for robotics (Gemini Robotics-ER, whose skills Gemini 4 Hydrogen has)
 * with the box the plugin's skill asks for too.
 */
export function locatePrompt(query, max = 8) {
  return `Point to no more than ${max} items in the image that match: ${query}. The label returned should be an identifying name for the object detected. The answer should follow the json format: [{"point": <point>, "box_2d": <box>, "label": <label>}, ...]. The points are in [y, x] format and the boxes in [ymin, xmin, ymax, xmax] format, normalized to 0-1000. Each point is on its object, near the middle of what is visible of it. List the best match first, and answer [] if nothing in the image matches.`;
}

const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : typeof v === "string" && v.trim() && Number.isFinite(Number(v)) ? Number(v) : null);

/**
 * Detections from a model's answer or a caller's list: [{label, point: [y, x], box?: [ymin, xmin, ymax, xmax]}]
 * on the 0-1000 grid. Accepts a JSON string (in a code fence or not) or an array; drops what is not a detection.
 */
export function parseDetections(answer, max = 20) {
  let list = answer;
  if (typeof answer === "string") {
    const text = answer.replace(/^\s*```(?:json)?\s*/i, "").replace(/\s*```\s*$/, "");
    try {
      list = JSON.parse(text);
    } catch {
      const m = text.match(/\[[\s\S]*\]/);
      if (!m) return [];
      try {
        list = JSON.parse(m[0]);
      } catch {
        return [];
      }
    }
  }
  if (list && !Array.isArray(list) && typeof list === "object") list = list.objects ?? list.detections ?? list.items ?? [list];
  if (!Array.isArray(list)) return [];
  const out = [];
  for (const d of list) {
    if (!d || typeof d !== "object") continue;
    const box = Array.isArray(d.box_2d ?? d.box) ? (d.box_2d ?? d.box).map(num) : null;
    const goodBox = box && box.length === 4 && box.every((v) => v !== null) ? [Math.min(box[0], box[2]), Math.min(box[1], box[3]), Math.max(box[0], box[2]), Math.max(box[1], box[3])].map((v) => clamp(v, 0, 1000)) : null;
    let point = Array.isArray(d.point) && d.point.length >= 2 ? [num(d.point[0]), num(d.point[1])] : null;
    if (!point || point.some((v) => v === null)) point = goodBox ? [(goodBox[0] + goodBox[2]) / 2, (goodBox[1] + goodBox[3]) / 2] : null;
    if (!point) continue;
    out.push({ label: String(d.label ?? d.name ?? "object").slice(0, 60), point: point.map((v) => clamp(v, 0, 1000)), ...(goodBox ? { box: goodBox } : {}) });
    if (out.length >= max) break;
  }
  return out;
}

/**
 * Ask Gemini where `query` is in a picture (a JPEG data URL). `thinking` is the model's thinking level
 * ("low", as the plugin's skill uses it, or "high" for clutter). Resolves with {detections, model}.
 */
export async function geminiLocate({ apiKey, image, query, model = GEMINI_MODEL, thinking = "low", max = 8, signal, fetchImpl = globalThis.fetch }) {
  if (!apiKey) throw new Error("no Gemini API key");
  const data = String(image).replace(/^data:[^,]*,/, "");
  const response = await fetchImpl(`${GEMINI_API}/models/${encodeURIComponent(model)}:generateContent`, {
    method: "POST",
    headers: { "Content-Type": "application/json", "x-goog-api-key": apiKey },
    body: JSON.stringify({
      contents: [{ role: "user", parts: [{ inlineData: { mimeType: "image/jpeg", data } }, { text: locatePrompt(query, max) }] }],
      generationConfig: { responseMimeType: "application/json", thinkingConfig: { thinkingLevel: thinking } },
    }),
    signal,
  });
  if (!response.ok) {
    let detail = "";
    try {
      const body = await response.json();
      detail = body.error?.message ?? JSON.stringify(body);
    } catch {
      detail = await response.text().catch(() => "");
    }
    const hint = response.status === 400 && /api key/i.test(detail) ? " (check the Gemini API key)" : response.status === 429 ? " (the key's quota or rate limit)" : "";
    throw new Error(`Gemini ${response.status}: ${String(detail).slice(0, 240)}${hint}`);
  }
  const body = await response.json();
  const parts = body.candidates?.[0]?.content?.parts ?? [];
  const text = parts.filter((p) => !p.thought && typeof p.text === "string").map((p) => p.text).join("");
  if (!text) throw new Error(`Gemini returned no answer${body.candidates?.[0]?.finishReason ? ` (${body.candidates[0].finishReason})` : ""}`);
  return { detections: parseDetections(text, max), model: body.modelVersion ?? model };
}

// ---------------------------------------------------------------------------------------------------------
// From the picture to the world. A camera frame is {matrix, fovy, aspect, width, height}: matrix is the
// camera-to-world transform as 16 numbers, column-major (three.js's matrixWorld.elements), looking along -z
// with +y up; fovy is the vertical field of view in degrees.

const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
const add = (a, b, s = 1) => [a[0] + s * b[0], a[1] + s * b[1], a[2] + s * b[2]];
const norm = (a) => Math.hypot(a[0], a[1], a[2]);
const unit = (a) => {
  const n = norm(a) || 1;
  return [a[0] / n, a[1] / n, a[2] / n];
};

/** The ray from the camera through a picture point [y, x] (0-1000): {origin, dir} in the world. */
export function pixelRay(frame, [y, x]) {
  const e = frame.matrix;
  const t = Math.tan((frame.fovy * Math.PI) / 360);
  const nx = x / 500 - 1;
  const ny = 1 - y / 500;
  const c = [nx * t * frame.aspect, ny * t, -1];
  const dir = unit([e[0] * c[0] + e[4] * c[1] + e[8] * c[2], e[1] * c[0] + e[5] * c[1] + e[9] * c[2], e[2] * c[0] + e[6] * c[1] + e[10] * c[2]]);
  return { origin: [e[12], e[13], e[14]], dir };
}

/** Where a world point appears in the picture: [y, x] on the 0-1000 grid, or null behind the camera. */
export function projectPoint(frame, p) {
  const e = frame.matrix;
  const d = sub(p, [e[12], e[13], e[14]]);
  // the camera's axes are the matrix's columns: x right, y up, z back
  const xc = e[0] * d[0] + e[1] * d[1] + e[2] * d[2];
  const yc = e[4] * d[0] + e[5] * d[1] + e[6] * d[2];
  const zc = e[8] * d[0] + e[9] * d[1] + e[10] * d[2];
  if (zc >= 0) return null;
  const t = Math.tan((frame.fovy * Math.PI) / 360);
  return [(1 - yc / (-zc * t)) * 500, (xc / (-zc * t * frame.aspect) + 1) * 500];
}

/** Pixels per metre at one metre: the focal length in pixels of a picture `height` pixels high. */
const focalPx = (frame) => frame.height / 2 / Math.tan((frame.fovy * Math.PI) / 360);

/**
 * A ray into the physics scene: the first geom it meets, skipping the robot's own (the head camera sits inside
 * the head's shell) and, with staticOnly, everything that moves (objects, doors, drawers). Resolves to
 * {point, distance, normal, body (id), name (the body's)} or null.
 */
export function castRay(sim, robotRoot, origin, dir, { staticOnly = false, range = 8 } = {}) {
  const { mujoco: mj, model, data } = sim;
  const gid = new mj.IntBuffer(1);
  const nrm = new mj.DoubleBuffer(3);
  try {
    let p = origin.slice();
    let travelled = 0;
    for (let k = 0; k < 24 && travelled < range; k++) {
      const d = mj.mj_ray(model, data, p, dir, null, true, -1, gid, nrm);
      if (d < 0) return null;
      const g = gid.GetView()[0];
      const b = model.geom_bodyid[g];
      travelled += d;
      const skip = model.body_rootid[b] === robotRoot || (staticOnly && model.body_weldid[b] !== 0);
      if (!skip) {
        if (travelled > range) return null;
        const n = Array.from(nrm.GetView());
        return { point: add(origin, dir, travelled), distance: travelled, normal: n, body: b, name: mj.mj_id2name(model, mj.mjtObj.mjOBJ_BODY.value, b) ?? `body ${b}` };
      }
      p = add(origin, dir, travelled + 1e-3);
      travelled += 1e-3;
    }
    return null;
  } finally {
    gid.delete();
    nrm.delete();
  }
}

/**
 * A detection's position in the world: {world, how, surface?} or {world: null, reason}. `cast(origin, dir,
 * options)` is castRay bound to the scene.
 */
export function mapDetection(frame, det, method, cast) {
  const f = focalPx(frame);
  const boxPx = det.box ? { w: ((det.box[3] - det.box[1]) / 1000) * frame.width, h: ((det.box[2] - det.box[0]) / 1000) * frame.height } : null;
  if (method === "depth") {
    // The depth at the point and at four around it inside the box, the middle one of them: a point at the edge
    // of a small object can pass it and meet the wall behind.
    const ray = pixelRay(frame, det.point);
    const [y, x] = det.point;
    const dy = det.box ? (det.box[2] - det.box[0]) / 5 : 0;
    const dx = det.box ? (det.box[3] - det.box[1]) / 5 : 0;
    const spots = det.box ? [[y, x], [y - dy, x], [y + dy, x], [y, x - dx], [y, x + dx]] : [[y, x]];
    const ranges = spots
      .map(([sy, sx]) => [clamp(sy, det.box?.[0] ?? 0, det.box?.[2] ?? 1000), clamp(sx, det.box?.[1] ?? 0, det.box?.[3] ?? 1000)])
      .map((s) => pixelRay(frame, s))
      .map((r) => cast(r.origin, r.dir)?.distance)
      .filter((d) => d !== undefined)
      .sort((a, b) => a - b);
    if (!ranges.length) return { world: null, reason: "no depth at that point (nothing within 8 m)" };
    const range = ranges[Math.floor((ranges.length - 1) / 2)];
    // The depth is the near surface: the middle of the object lies about half its width further along the ray.
    const width = boxPx ? (boxPx.w * range) / f : 0.05;
    return { world: add(ray.origin, ray.dir, range + Math.min(0.04, width / 2)), how: "depth", width_m: width };
  }
  // plane: where the bottom of the box meets the furniture (static geoms only: the map of the room); at the
  // front edge of a counter the ray can pass the top and meet its side, so a little higher up the box then.
  let ray = null;
  let hit = null;
  for (const up of det.box ? [0, 0.05, 0.12, 0.2] : [0]) {
    const bottom = det.box ? [det.box[2] - up * (det.box[2] - det.box[0]), (det.box[1] + det.box[3]) / 2] : det.point;
    ray = pixelRay(frame, bottom);
    hit = cast(ray.origin, ray.dir, { staticOnly: true });
    if (!hit || hit.normal[2] >= 0.7) break;
  }
  if (!hit) return { world: null, reason: "the ray meets no furniture or floor" };
  if (hit.normal[2] < 0.7) return { world: null, reason: `the ray meets the ${hit.name.replace(/_/g, " ")}, not a surface to stand on` };
  if (!boxPx) {
    // a point only: the plane at the support's height plus 3 cm (about half a small object's height)
    const r = pixelRay(frame, det.point);
    const z = hit.point[2] + 0.03;
    if (r.dir[2] > -1e-3) return { world: null, reason: "the ray does not come down to the surface" };
    return { world: add(r.origin, r.dir, (z - r.origin[2]) / r.dir[2]), how: "plane", surface: hit.name, surface_z: hit.point[2] };
  }
  // The box's bottom edge is the object's front foot. Its width and height in metres follow from the range;
  // the picture's height of the box is the front's height foreshortened plus the top's depth (taken as the width).
  const range = hit.distance;
  const width = (boxPx.w * range) / f;
  const across = (boxPx.h * range) / f;
  const down = Math.asin(clamp(-ray.dir[2], -1, 1)); // how far the ray looks down
  const height = clamp((across - width * Math.sin(down)) / Math.max(0.2, Math.cos(down)), 0.01, 0.6);
  const flat = unit([ray.dir[0], ray.dir[1], 0]);
  const world = add(add(hit.point, flat, width / 2), [0, 0, 1], height / 2);
  return { world, how: "plane", surface: hit.name, surface_z: hit.point[2], width_m: width, height_m: height };
}

// ---------------------------------------------------------------------------------------------------------
// The picture with the detections drawn on it (in the browser), for the person watching and for models that see.

const COLORS = ["#ffcc00", "#00d0ff", "#ff5c8a", "#7cff6b", "#ff9a3c", "#b18cff", "#ffffff", "#3cffd6"];

export async function annotate(image, detections) {
  if (typeof document === "undefined") return image;
  const img = new Image();
  img.src = image;
  await img.decode();
  const canvas = document.createElement("canvas");
  canvas.width = img.naturalWidth;
  canvas.height = img.naturalHeight;
  const ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);
  const sx = canvas.width / 1000;
  const sy = canvas.height / 1000;
  ctx.lineWidth = Math.max(2, canvas.width / 320);
  ctx.font = `bold ${Math.round(canvas.width / 40)}px system-ui, sans-serif`;
  detections.forEach((d, k) => {
    const color = COLORS[k % COLORS.length];
    ctx.strokeStyle = color;
    ctx.fillStyle = color;
    if (d.box) ctx.strokeRect(d.box[1] * sx, d.box[0] * sy, (d.box[3] - d.box[1]) * sx, (d.box[2] - d.box[0]) * sy);
    const [y, x] = d.point;
    ctx.beginPath();
    ctx.arc(x * sx, y * sy, Math.max(4, canvas.width / 110), 0, 2 * Math.PI);
    ctx.fill();
    ctx.strokeStyle = "#000";
    ctx.lineWidth = 1.5;
    ctx.stroke();
    ctx.lineWidth = Math.max(2, canvas.width / 320);
    const text = `${k + 1} ${d.label}`;
    const tx = clamp(x * sx + 8, 2, canvas.width - ctx.measureText(text).width - 4);
    const ty = clamp((d.box ? d.box[0] * sy : y * sy) - 6, 16, canvas.height - 4);
    ctx.strokeStyle = "rgba(0,0,0,0.75)";
    ctx.lineWidth = 4;
    ctx.strokeText(text, tx, ty);
    ctx.fillText(text, tx, ty);
    ctx.lineWidth = Math.max(2, canvas.width / 320);
  });
  return canvas.toDataURL("image/jpeg", 0.85);
}