File size: 13,389 Bytes
d72771b
 
 
 
e0daa77
 
 
85e0fe1
60f575d
 
 
 
d72771b
85e0fe1
d72771b
e0daa77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d72771b
e0daa77
 
 
d72771b
e0daa77
d72771b
e0daa77
d72771b
 
 
e0daa77
 
 
 
85e0fe1
 
 
 
 
 
 
 
e0daa77
 
 
 
 
 
d72771b
e0daa77
d72771b
 
 
 
 
 
 
e0daa77
 
 
 
 
 
 
 
 
d72771b
 
e0daa77
d72771b
e0daa77
d72771b
e0daa77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d72771b
e0daa77
 
 
 
 
 
 
85e0fe1
 
 
 
 
d72771b
 
 
85e0fe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0daa77
 
 
 
60f575d
e0daa77
 
 
60f575d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0daa77
 
 
 
 
 
 
 
60f575d
e0daa77
 
 
 
 
d72771b
e0daa77
 
d72771b
e0daa77
d72771b
e0daa77
 
 
 
60f575d
 
 
 
e0daa77
 
60f575d
 
 
 
d72771b
 
e0daa77
60f575d
 
 
 
 
 
 
e0daa77
 
d72771b
e0daa77
 
 
 
 
 
 
 
 
 
d72771b
 
 
e0daa77
d72771b
e0daa77
d72771b
 
 
 
 
 
60f575d
 
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
272
273
274
// A scripted demonstrator for household tasks (household.js): it works through the goal's literals with
// the robot's skills, as the BEHAVIOR Challenge's human demonstrations show each task can be done. For
// `ontop` and `inside` it picks the object up (driving to it if it is out of reach) and puts it on or in
// the target (driving there): on a surface at a free spot the arms reach, next to what a `nextto` literal
// for it names; into a container, let go over its opening. With both hands: when another object goes to
// the same place or near it, the other hand picks that one up too before the robot goes there, so one trip
// carries two (of the objects a hand holds securely: light ones, not balls). A switch is pressed until it is as
// the goal says; a drawer or door is opened or closed by its pull (src/robots/fixtures.js), and one that
// something is taken out of or put into is opened first, with both hands free, and shut as soon as the
// goal wants it shut and nothing more comes out of it or goes in (taken out, the object goes on in one hand
// while the other shuts it). Literals that hold are skipped; a second round retries what failed.
import { GRASP, approach, glide, graspPlan, objectInfo, pick, place, press } from "../robots/skills.js";
import { show } from "./bddl.js";
import { moveFixture, openTarget } from "../robots/fixtures.js";

/** Two places this close (m) are one trip for two objects. */
const SAME_TRIP = 1.2;

/**
 * Whether an object is held well enough to stay in one hand while the other picks something up or puts
 * it down: light (at most 100 g) and not a ball. A heavier one (a juice box, a yogurt pot, a full bottle)
 * creeps along the fingers and tilts over a long carry, and a ball (an apple, an orange) held at two
 * points rolls out as the base turns; those go on their own.
 */
function secure(household, id) {
  const { model } = household.sim;
  let ball = true;
  for (let g = model.body_geomadr[id]; g < model.body_geomadr[id] + model.body_geomnum[id]; g++) {
    if ((model.geom_contype[g] || model.geom_conaffinity[g]) && model.geom_type[g] !== 2) ball = false;
  }
  return !ball && model.body_mass[id] <= 0.1 + 1e-9;
}

/**
 * Do an episode's task (a generator for the skill runner). `log(text)` hears what it is doing;
 * `bothHands: false` carries one object at a time. Stops when the episode ends (the goal holds, or time
 * is up).
 */
export function* solve(household, episode, { log = () => {}, bothHands = true } = {}) {
  const objects = episode.task.problem.objects;
  const holds = (goal) => household.check(goal.expr, objects);
  for (let round = 0; round < 2 && !episode.outcome; round++) {
    for (const goal of episode.goals) {
      if (episode.outcome) break;
      if (holds(goal)) continue;
      const job = jobOf(household, episode, goal);
      // another object for the other hand, going to the same place or near it
      const partner = job && bothHands ? partnerFor(household, episode, job, holds) : null;
      if (job) {
        // what it is in, or goes in, opened first (both hands free)
        const opened = yield* openFor(household, job, partner, log);
        if (!opened.ok) {
          log(`${goal.label}: ${opened.message}`);
          continue;
        }
      }
      if (partner) {
        log(`${goal.label}, and ${partner.goal.label}`);
        const [ra, rb] = yield* carryTwo(household, job, partner);
        log(`${goal.label}: ${ra.message}${rb ? `; ${partner.goal.label}: ${rb.message}` : ""}`);
        continue;
      }
      log(goal.label);
      const r = job ? yield* move(household, job) : yield* achieve(household, goal.expr);
      log(`${goal.label}: ${r.message}`);
    }
  }
  const s = episode.evaluate();
  return { ok: s.success, message: `${s.satisfied} of ${s.total} goal conditions hold` };
}

/**
 * What moving an object takes for a goal literal: {goal, name, pred, target, near}, or null for a literal
 * that is not about where an object is (a switch).
 */
function jobOf(household, episode, goal) {
  const expr = goal.expr;
  if (expr[0] === "not") return null;
  const [pred, a, b] = expr;
  if (pred === "ontop" || pred === "inside") {
    // a `nextto` literal for the same object says where on the surface
    const near = episode.goals.map((g) => g.expr).find((e) => e[0] === "nextto" && e[1] === a)?.[2] ?? null;
    return { goal, name: a, pred, target: b, near };
  }
  if (pred === "nextto") {
    const support = household.supportOf(b);
    return support ? { goal, name: a, pred: "ontop", target: support.name, near: b } : null;
  }
  return null;
}

/**
 * A second job to do with the other hand on the same trip: a later goal not holding yet, for another
 * object that is free, graspable and held well (as the first must be), going to the same place or near
 * it; of those, the one whose object is nearest the first.
 */
function partnerFor(household, episode, job, holds) {
  const { sim } = household;
  const first = household.entities[job.name];
  if (household.heldBy(first.id) || !secure(household, first.id)) return null;
  const busy = ["left", "right"].some((s) => household.busy(s));
  if (busy) return null; // a hand is taken already
  const there = household.targetPoint(job.target);
  const from = sim.bodyPos(first.id);
  let best = null;
  for (const goal of episode.goals.slice(episode.goals.indexOf(job.goal) + 1)) {
    if (holds(goal)) continue;
    const other = jobOf(household, episode, goal);
    if (!other || other.name === job.name) continue;
    const obj = household.entities[other.name];
    if (household.heldBy(obj.id) || objectInfo(sim, obj.id).width > GRASP.maxWidth || !secure(household, obj.id)) continue;
    const p = household.targetPoint(other.target);
    if (Math.hypot(p[0] - there[0], p[1] - there[1]) > SAME_TRIP) continue;
    const q = sim.bodyPos(obj.id);
    const d = Math.hypot(q[0] - from[0], q[1] - from[1]);
    if (!best || d < best.d) best = { job: other, d };
  }
  return best ? { ...best.job } : null;
}

function* achieve(household, expr) {
  const neg = expr[0] === "not";
  const [pred, a] = neg ? expr[1] : expr;
  if (pred === "toggled_on") return yield* toggle(household, a);
  if (pred === "open") {
    const e = household.entities[a];
    if (!e?.fixture) return { ok: false, message: `the ${e?.label ?? a} does not open` };
    return yield* moveFixture(household.robot, e.fixture, neg ? 0 : openTarget(e.fixture), { what: `the ${e.label}` });
  }
  return { ok: false, message: `no skill for ${show(expr)}` };
}

/**
 * Open what a job's object is in, and what it goes in (and the partner's), if they open and are shut, so
 * the hands are free for the pull. Returns {ok, message}.
 */
function* openFor(household, job, partner, log) {
  const names = new Set();
  for (const j of [job, partner].filter(Boolean)) {
    const into = household.entities[j.target];
    if (into?.fixture) names.add(j.target);
    // the container the object is in now
    for (const [name, e] of Object.entries(household.entities)) if (e.fixture && household.holds("inside", [j.name, name])) names.add(name);
  }
  for (const name of names) {
    const e = household.entities[name];
    if (household.holds("open", [name])) continue;
    log(`opening the ${e.label}`);
    const r = yield* moveFixture(household.robot, e.fixture, openTarget(e.fixture), { what: `the ${e.label}` });
    if (!r.ok) return { ok: false, message: `could not open the ${e.label}: ${r.message}` };
  }
  return { ok: true };
}

/** One object to where it goes. */
function* move(household, job) {
  const got = yield* fetch(household, job);
  if (!got.ok) return got;
  yield* shutBehind(household, job);
  return yield* deliver(household, job, got);
}

/**
 * Once an object is out of a drawer or door that the goal wants shut, and no other goal still needs
 * something out of it or into it, shut it with the free hand before going on.
 */
function* shutBehind(household, job) {
  const episode = household.episode;
  if (!episode) return;
  const objects = episode.task.problem.objects;
  for (const [name, e] of Object.entries(household.entities)) {
    // not what this object is going into
    if (!e.fixture || job.target === name || !household.holds("open", [name])) continue;
    const wanted = episode.goals.some((g) => g.expr[0] === "not" && g.expr[1][0] === "open" && g.expr[1][1] === name);
    if (!wanted) continue;
    // still needed: an object in it that has to come out, or one that has to go in
    const needed = episode.goals.some((g) => {
      if (household.check(g.expr, objects)) return false;
      const other = jobOf(household, episode, g);
      if (!other || other.name === job.name) return false;
      return other.target === name || household.holds("inside", [other.name, name]);
    });
    if (needed || ["left", "right"].every((s) => household.busy(s))) continue;
    yield* moveFixture(household.robot, e.fixture, 0, { what: `the ${e.label}` });
  }
}

/**
 * Two objects on one trip: the first in one hand, the second in the other, then each where it goes. If
 * the second cannot be picked up, the first goes on its own (the second is tried again later).
 */
function* carryTwo(household, a, b) {
  const ga = yield* fetch(household, a);
  if (!ga.ok) return [ga, null];
  const gb = yield* fetch(household, b, ga.side === "left" ? "right" : "left");
  yield* shutBehind(household, a);
  const ra = yield* deliver(household, a, ga);
  const rb = gb.ok ? yield* deliver(household, b, gb) : gb;
  return [ra, rb];
}

/**
 * Pick an object up (unless a gripper has it), with `side` or the free arm, driving to it if it is out of
 * reach; two tries. Returns {ok, side, from} (from: where it stood, to put it back).
 */
function* fetch(household, job, side) {
  const { robot, sim } = household;
  const obj = household.entities[job.name];
  const holding = household.heldBy(obj.id);
  if (holding) return { ok: true, side: holding, from: null };
  const busy = ["left", "right"].find((s) => household.busy(s));
  // the other arm if this one could not put it where it goes, last time
  const arm = side ?? (busy ? (busy === "left" ? "right" : "left") : household.otherArm?.[job.name]);
  // into a fridge: rather the arm that reaches in past its door
  const prefer = arm ? undefined : (household.reachingArm(job.target) ?? undefined);
  let last = null;
  for (let attempt = 0; attempt < 2; attempt++) {
    let drove = null;
    if (prefer || graspPlan(robot, obj.id, arm).reason) {
      drove = yield* approach(robot, obj.id, { side: arm, prefer });
      if (!drove.ok) return { ok: false, message: `could not get to the ${obj.label}: ${drove.message}` };
    }
    const info = objectInfo(sim, obj.id);
    const from = [info.center[0], info.center[1], info.bottom];
    // in a fridge or a drawer: the hand draws it out toward the robot before the base moves
    const inside = Object.entries(household.entities).some(([n, e]) => e.fixture && household.holds("inside", [job.name, n]));
    const got = yield* pick(robot, obj.id, { side: arm ?? drove?.side ?? graspPlan(robot, obj.id).side });
    if (got.ok && inside) {
      const t = robot.arms[got.side].target;
      yield* glide(robot, got.side, [{ to: { ...t, x: Math.max(0.08, t.x - 0.1) }, duration: 0.8 }], { settle: 0.1 });
    }
    if (got.ok) return { ok: true, side: got.side, from };
    last = got;
  }
  return { ok: false, message: `could not pick up the ${obj.label}: ${last?.message}` };
}

/**
 * Put a held object where its job says, trying another spot if the base cannot get to where an arm
 * reaches one; if it cannot go there, back where it was.
 */
function* deliver(household, job, { side, from }) {
  const { robot } = household;
  const obj = household.entities[job.name];
  let done = null;
  const avoid = [];
  for (let attempt = 0; attempt < 3; attempt++) {
    const spot = household.placeTarget(job.name, job.pred, job.target, { near: job.near, from: robot.pose(), avoid });
    if (!spot) {
      done ??= { ok: false, message: `no free spot ${job.pred === "inside" ? "in" : "on"} the ${household.entities[job.target].label}` };
      break;
    }
    done = yield* place(robot, side, robot.toRobot(spot.world), obj.id, { slack: spot.slack, onto: spot.onto ?? null, drop: Boolean(spot.drop) });
    if (done.ok || spot.drop || spot.onto !== undefined || !/no clear spot to stand/.test(done.message) || !household.heldBy(obj.id)) break;
    avoid.push(spot.world);
  }
  // nowhere to stand for this arm (a fridge's shelf beside its open door): next time, the other arm
  if (!done.ok && /no clear spot to stand/.test(done.message)) (household.otherArm ??= {})[job.name] = side === "left" ? "right" : "left";
  if (!done.ok && from && household.heldBy(obj.id)) {
    const back = yield* place(robot, side, robot.toRobot(from), obj.id);
    return { ok: false, message: `${done.message}; put it back${back.ok ? "" : ` (${back.message})`}` };
  }
  return done;
}

/** Press a switch's button once. */
function* toggle(household, name) {
  const e = household.entities[name];
  const was = e.on;
  const r = yield* press(household.robot, household.buttonTop(e));
  if (!r.ok) return r;
  return e.on !== was ? { ok: true, message: `switched the ${e.label} ${e.on ? "on" : "off"}` } : { ok: false, message: `pressed it, but the ${e.label} stayed ${e.on ? "on" : "off"}` };
}