implementedProfilenative C and Wasm semantic query fixtureQualifiedcpu, wasm

7. Ask the world where things are

Engine-core task: ec-query (#12609). The module is metaverse-engine/physics/query.coax, with its oracles in metaverse-engine/tests/query-oracle.coax. The walking controller in metaverse-engine/move/player.coax asks it for the ground under your feet.

Several systems ask where things are in a realm:

  • Movement asks what is under your feet.
  • The camera asks how far back it can sit before a wall.
  • A guard asks whether it can see you.
  • The editor asks what a tap hit.
  • Placement asks whether a thing fits.

These are four queries over one set of shapes: ground, ray, overlap, and sweep. When each system writes its own version, the versions disagree. For example, a character stands on a ledge that the camera ignores, or a realm's copy of the step height drifts from the walker's. The OpenAgents Metaverse Engine gives each realm one set of colliders and one query module.

What this chapter teaches

  • How to describe a realm's colliders: a flat ground, boxes, capsules, and floors.
  • The contract of each of the four queries.
  • One definition of the ground: its height, its slope, and which surface it is.
  • How to check a query against a separate oracle that uses containment instead of formulas.

The method

A realm puts its colliders in one Colliders value, in world space (chapter 2). Then any system can ask:

  • query_ground(c, x, z, below, reach): the highest surface at or below below. query_stand asks for feet: it sets below to the feet plus the step height.
  • query_ray(c, o, d, far): the first point that the ray o + t d reaches, for t in [0, far].
  • query_overlap(c, centre, r, out): the colliders that a sphere overlaps.
  • query_sweep(c, from, r, by): the first point at which a sphere that moves from from along by touches a collider, for t in [0, 1].

The queries follow these rules:

  • Every shape is solid. A ray or sweep that starts inside a shape hits it at t = 0.
  • Ties go to the earlier collider: the ground, then the boxes, then the capsules, each in index order. The answer depends on the scene, not on the order of a search.
  • A collider with a value that isn't a number, a box whose corners are reversed, and a capsule without a radius are skipped. A partial last entry in an array is ignored.
  • The queries never change the colliders.

The rules

The optional semantic boundary is implemented in `query-filter.coax`, `query-scene.coax` and `query-fluid.coax`. It validates complete geometry, metadata and physical surfaces before selecting a consumer's world. The unfiltered APIs below retain their original permissive shape contract.

A collider has a durable ID and generation, an optional live entity handle, category bits, a physical surface ID and a solid/sensor/trigger/fluid role. Physical surfaces name friction/restitution policies, footstep and reaction classes, traversability tags and independent fluid density, buoyancy and resistance. A render material slot does not identify a physical surface.

QueryFilter selects included categories, excludes categories, ignores one exact collider generation and/or one exact entity handle, and chooses solid and sensor participation. These are query masks, separate from physical collision-pair permissions. The compatibility filter selects everything. Selection compacts shapes in source order into caller-owned QueryScratch; it keeps source metadata for mapping the result back to its durable identity. Filtering out a nearer collider therefore exposes an eligible farther one. No traversal order or equal-distance tie rule changes.

The first profile admits 256 collider records, 64 physical surfaces, 16 heightfields and 65,535 height words per field. It reuses the existing exact heightfield cell traversal. Scratch is borrowed by a selection and must not be overwritten while that selection is in use. Snapshot geometry, height views and surface tables remain retained and immutable until the owner's next publication. query_world_publish validates an inactive candidate and advances its epoch only at a later fixed tick. Failure retains the old world. Every semantic query refuses an old epoch or a stale selected entity handle.

semantic_ground, semantic_ray, semantic_clear, semantic_sweep and semantic_overlap use the selected geometry and return source identity. Overlap stages the complete answer before writing caller output; capacity or exhausted terrain work is a refusal with no successful prefix. A world without selected ground has QueryShape.none; it gains no fallback plane. Floors retain their existing ground-only query profile.

Run the shared example to see one admitted world drive movement, follow-camera body clearance, camera sight, NPC sight, material footsteps and fluid resistance. Its stable IDs 100–500 are reserved for the subsequent lifecycle/streaming integration. The verification record names the original realm adapters that still use unfiltered queries.

shell
coax/bin/coax run metaverse-engine/examples/query-world.coaxcoax/web/tool.sh metaverse-engine/tools/query-world-hosts.coax

Expected output of query-world.coax (fixture):

text
1
1074580684
1083598438
1072064102
0
2
4
9
1065353216
1073741824
0
1
1
12

The step height, the steepest slope you can stand on, and the floor pad are defined once, here. The walker reads them from this module.

jai
QUERY_STEP_UP :: STAND_STEP;     // 0.55 m: the highest top a walker steps ontoQUERY_STEEP :: STAND_STEEP;      // tan 55 degrees: a steeper surface doesn't hold youQUERY_FLOOR_PAD :: 0.15;         // how far past a floor's edge your middle may be and it holds youQUERY_BOX :: 6;                  // numbers a box: min x, y, z, max x, y, zQUERY_CAPSULE :: 7;              // numbers a capsule: one end, the other, the radiusQUERY_TOO_BIG :: 1000000.0;      // a coordinate this large is not one// A hull: QUERY_HULL_HEAD numbers (its face count F, its lowest and highest y), then F faces of// QUERY_HULL_FACE numbers (an outward normal nx, ny, nz and d: the solid is where// nx x + ny y + nz z <= d for every face). Hulls follow one another in one array.QUERY_HULL_HEAD :: 3;QUERY_HULL_FACE :: 4;QUERY_HULL_FACES_MAX :: 128;QUERY_HULL_FLAT :: 0.00006103515625;   // 2^-14: a face whose normal is this near level is a side, not a top or a bottomQUERY_HEIGHTFIELDS_MAX :: 16;QueryShape :: enum u8 { none; ground; box; capsule; floor; heightfield; hull; }QueryStatus :: enum u8 { ok; invalid; terrain; exhausted; capacity; }// A borrowed, read-only mesh. Its ground queries use the same drawn triangles as terrain.QueryHeightfield :: struct { ground: terrain.Ground; heights: [] f32; }// One realm's colliders. The arrays are the realm's own; a partial last entry is ignored.Colliders :: struct {  ground: f32;  boxes: [] f32;  capsules: [] f32;  floors: [] f32;      // STAND_FLOATS numbers each (metaverse-engine/physics/stand.coax)  heightfields: [] QueryHeightfield;  hulls: [] f32;       // convex solids, QUERY_HULL_HEAD + F * QUERY_HULL_FACE numbers each  heightfield_budget: int = height_rays.GROUND_RAY_CELLS;  // Semantic selections can contain no base surface. The compatibility  // default still supplies the realm's flat ground when it has no mesh.  ground_enabled: bool = true;  // An index over the boxes and capsules (query-near.coax), or none: with one, a query asks only  // the colliders near it, and answers as it would without.  near: [] QueryNear;}

Floors use the formats in metaverse-engine/physics/stand.coax: quads, cones, domes, and rings. Floors answer query_ground. Rays, overlaps, and sweeps cover flat ground, heightfield triangles, boxes and capsules. Chapter 8 supplies the heightfield implementation and checked work budgets.

The ground

query_ground starts from the flat fallback, or the highest valid supplied heightfield. A heightfield replaces the fallback even in a valley below it. A box's top replaces that surface if the top is no higher than below, is higher than the surface found so far, and its footprint is less than reach away. For the walker, reach is the capsule's radius, 0.3 m. A floor replaces the result if it is higher. The result says whether the surface is too steep to stand on.

jai
// The surface under (x, z): its height, its slope (dy/dx, dy/dz), whether it is too steep to// stand on, and which collider it is.QueryGround :: struct { y: f32; gx: f32; gz: f32; steep: bool; shape: QueryShape = QueryShape.ground; index: int; status: QueryStatus; }// The flat height is a fallback, not a second floor hiding a mesh's valleys. Each admitted// mesh continues its nearest edge outside its rectangle. A clamped axis has zero slope.query_base_ground :: (c: Colliders, x: f32, z: f32) -> QueryGround #effects(all) {  out := QueryGround.{y = c.ground};  if !c.ground_enabled { out = QueryGround.{y = -QUERY_TOO_BIG, shape = QueryShape.none}; }  found := false;  for i: 0..<c.heightfields.count {    field := c.heightfields[i];    q := terrain.ground_sample(field.ground, field.heights, quantities.Quantity.{value = x}, quantities.Quantity.{value = z});    if !q.ok || (found && q.height.value <= out.y) { continue; }    out = QueryGround.{y = q.height.value, gx = ifx q.clamped_x then 0.0f32 else q.gx,      gz = ifx q.clamped_z then 0.0f32 else q.gz, shape = QueryShape.heightfield, index = i};    found = true;  }  return out;}// The highest surface at (x, z) at or below `below`: the ground, a box's top whose footprint is// less than `reach` away (a walker's radius), or a floor (within QUERY_FLOOR_PAD of its edge).// A surface only as high as one already found doesn't replace it.query_ground :: (c: Colliders, x: f32, z: f32, below: f32, reach: f32) -> QueryGround #effects(all) {  if c.near.count > 0 { return query_near_ground(c, x, z, below, reach); }  out := query_base_ground(c, x, z);  for i: 0..<query_boxes(c) {    b := query_box(c, i);    if !b.ok || b.high.y > below || b.high.y <= out.y { continue; }    if query_footprint(b, x, z) < reach { out = QueryGround.{y = b.high.y, shape = QueryShape.box, index = i}; }  }  h := stand_top(c.floors, c.floors.count / STAND_FLOATS, x, z, below, f32(QUERY_FLOOR_PAD));  if h.y > out.y && query_finite(h.y) {    out = QueryGround.{y = h.y, gx = h.gx, gz = h.gz, shape = QueryShape.floor, index = h.id};  }  k := query_hull(c.hulls, 0); n := 0;  while k.ok {    t := query_hull_top(c.hulls, k, x, z);    if t.over && t.y <= below && t.y > out.y { out = QueryGround.{y = t.y, gx = t.gx, gz = t.gz, shape = QueryShape.hull, index = n}; }    k = query_hull(c.hulls, k.next); n += 1;  }  out.steep = stand_steep(StandHit.{gx = out.gx, gz = out.gz});  return out;}// What feet at `feet` stand on: the highest surface they can step onto.query_stand :: (c: Colliders, x: f32, z: f32, feet: f32, reach: f32) -> QueryGround #effects(all) {  return query_ground(c, x, z, feet + f32(QUERY_STEP_UP), reach);}// Runtime consumers refuse an incomplete scene instead of standing on a skipped mesh.// The legacy query_ground above retains its permissive malformed-shape behavior.query_ground_checked :: (c: Colliders, x: f32, z: f32, below: f32, reach: f32) -> QueryGround #effects(all) {  if !query_finite(x) || !query_finite(z) || !query_finite(below) || !query_finite(reach) || reach < 0 {    return QueryGround.{status = QueryStatus.invalid};  }  if c.heightfields.count > QUERY_HEIGHTFIELDS_MAX { return QueryGround.{status = QueryStatus.capacity}; }  if c.heightfields.count == 0 && c.ground_enabled && !query_finite(c.ground) { return QueryGround.{status = QueryStatus.invalid}; }  for i: 0..<c.heightfields.count {    field := c.heightfields[i];    sample := terrain.ground_sample(field.ground, field.heights, quantities.Quantity.{value = x}, quantities.Quantity.{value = z});    if !sample.ok { return QueryGround.{status = QueryStatus.terrain}; }  }  return query_ground(c, x, z, below, reach);}query_stand_checked :: (c: Colliders, x: f32, z: f32, feet: f32, reach: f32) -> QueryGround #effects(all) {  return query_ground_checked(c, x, z, feet + f32(QUERY_STEP_UP), reach);}

The walker's floor_under is now one call to query_stand. Every walking realm (the Grid, Everglade, Fairy Forest, the garden, Hecate's Cemetery, the realm host, and Dead Gears) reaches the ground through it:

jai
floor_under :: (w: World, x: f32, z: f32, feet: f32) -> StandHit #effects(all) {  g := query_ground(colliders(w), x, z, feet + w.collision.step_up, w.collision.radius);  return StandHit.{y = g.y, gx = g.gx, gz = g.gz};}

Rays

query_ray tests each shape with its own entry function and keeps the smallest t:

  • The ground is a plane that is solid below. A ray from above that points down reaches it at t = (ground - o.y) / d.y.
  • A box uses the slab method. The ray's entry is the latest of the three axes' entries, and the face it enters by gives the normal.
  • A capsule is a cylinder around the segment, plus a sphere at each end. The ray's entry is the earliest root of the three that lies on the shape.

t is in lengths of d, so a unit d gives t in metres.

jai
// Where a ray first reaches a collider: t along the direction (in its lengths), the point, the// outward normal there, and which collider. A ray that starts inside one hits it at t = 0,// with the normal facing back along the ray.QueryHit :: struct { hit: bool; t: f32; point: WorldPoint; normal: WorldPoint; shape: QueryShape; index: int = -1; status: QueryStatus; }query_height_status :: (status: height_rays.GroundRayStatus) -> QueryStatus #effects(all) {  if status == height_rays.GroundRayStatus.invalid { return QueryStatus.invalid; }  if status == height_rays.GroundRayStatus.terrain { return QueryStatus.terrain; }  if status == height_rays.GroundRayStatus.exhausted { return QueryStatus.exhausted; }  return QueryStatus.ok;}// The first t in [0, far] at which o + t d enters box low-high (slabs), and the face it enters by.QueryEntry :: struct { hit: bool; t: f32; normal: WorldPoint; }query_enter_box :: (low: WorldPoint, high: WorldPoint, o: WorldPoint, d: WorldPoint, far: f32) -> QueryEntry #effects(all) {  out: QueryEntry;  enter := -f32(QUERY_TOO_BIG); leave := f32(QUERY_TOO_BIG);  face: int; side: f32;   // the axis entered by, and the sign of its outward normal  ov := query_axes(o); dv := query_axes(d); lv := query_axes(low); hv := query_axes(high);  for k: 0..<3 {    if dv[k] == 0 {      if ov[k] < lv[k] || ov[k] > hv[k] { return out; }      continue;    }    t0 := (lv[k] - ov[k]) / dv[k]; t1 := (hv[k] - ov[k]) / dv[k];    nearer := stand_lo(t0, t1);    if nearer > enter { enter = nearer; face = k; side = -dv[k] / abs(dv[k]); }    leave = stand_lo(leave, stand_hi(t0, t1));  }  if leave < stand_hi(enter, 0) || enter > far { return out; }  out.hit = true;  if enter <= 0 { out.normal = world_scale(world_unit(d), -1); return out; }   // inside  out.t = enter;  n: [3] f32;  n[face] = side;  out.normal = world_point(n[0], n[1], n[2]);  return out;}// The first t in [0, far] at which o + t d enters the capsule a-b of radius r: its side, or a// sphere at either end.query_enter_capsule :: (a: WorldPoint, b: WorldPoint, r: f32, o: WorldPoint, d: WorldPoint, far: f32) -> QueryEntry #effects(all) {  out: QueryEntry;  gap := world_sub(o, query_nearest(a, b, o));  if world_dot(gap, gap) <= r * r { out.hit = true; out.normal = world_scale(world_unit(d), -1); return out; }  best := f32(QUERY_TOO_BIG);  // the side: o + t d at r from the axis' line, between the ends. A capsule that is one point  // (size 0), or a ray along its axis (qa 0), gives no number here, and only the ends count.  ab := world_sub(b, a); size := world_dot(ab, ab);  m := world_sub(o, a);  dp := world_sub(d, world_scale(ab, world_dot(d, ab) / size));  mp := world_sub(m, world_scale(ab, world_dot(m, ab) / size));  qa := world_dot(dp, dp); qb := world_dot(mp, dp); qc := world_dot(mp, mp) - r * r;  disc := qb * qb - qa * qc;  if disc >= 0 {    t := (-qb - sqrt(disc)) / qa;    s := (world_dot(m, ab) + t * world_dot(d, ab)) / size;    if t >= 0 && s >= 0 && s <= 1 { best = t; }  }  // the ends  ends := [2] WorldPoint.[a, b];  for e: 0..<2 {    me := world_sub(o, ends[e]);    ea := world_dot(d, d); eb := world_dot(me, d); ec := world_dot(me, me) - r * r;    ed := eb * eb - ea * ec;    if ed >= 0 {      t := (-eb - sqrt(ed)) / ea;      if t >= 0 { best = stand_lo(best, t); }    }  }  if best > far { return out; }  out.hit = true; out.t = best;  p := world_add(o, world_scale(d, best));  out.normal = world_unit(world_sub(p, query_nearest(a, b, p)));  return out;}// The first t in [0, far] at which o + t d reaches height y from above (the ground is solid below).query_enter_ground :: (y: f32, o: WorldPoint, d: WorldPoint, far: f32) -> QueryEntry #effects(all) {  out: QueryEntry;  if o.y < y { out.hit = true; out.normal = world_scale(world_unit(d), -1); return out; }  if !(d.y < 0) { return out; }  t := (y - o.y) / d.y;  if t > far { return out; }  out.hit = true; out.t = t; out.normal = world_point(0, 1, 0);  return out;}// Compare terrain times before narrowing them to the public f32 distance. Keep its// independently rounded surface point rather than reconstructing it from that distance.QuerySelection :: struct { hit: QueryHit; time: f64; }query_select :: (prior: QuerySelection, candidate: QueryHit, time: f64) -> QuerySelection #effects(all) {  if !candidate.hit || (prior.hit.hit && time >= prior.time) { return prior; }  return QuerySelection.{hit = candidate, time = time};}query_select_entry :: (prior: QuerySelection, e: QueryEntry, shape: QueryShape, index: int) -> QuerySelection #effects(all) {  return query_select(prior, QueryHit.{hit = e.hit, t = e.t, normal = e.normal, shape = shape, index = index}, f64(e.t));}query_ray :: (c: Colliders, o: WorldPoint, d: WorldPoint, far: f32) -> QueryHit #effects(all) {  if c.near.count > 0 { return query_near_ray(c, o, d, far); }  best: QuerySelection;  if !query_point_finite(o) || !query_point_finite(d) || !query_finite(far) || !(world_dot(d, d) > 0) { return QueryHit.{status = QueryStatus.invalid}; }  if c.heightfields.count > QUERY_HEIGHTFIELDS_MAX { return QueryHit.{status = QueryStatus.capacity}; }  reach := stand_hi(far, 0);  if c.heightfields.count == 0 && c.ground_enabled { best = query_select_entry(best, query_enter_ground(c.ground, o, d, reach), QueryShape.ground, 0); }  for i: 0..<c.heightfields.count {    field := c.heightfields[i];    h := height_rays.ground_ray(field.ground, field.heights, o, d, f64(reach), c.heightfield_budget);    if h.status == height_rays.GroundRayStatus.invalid { return QueryHit.{status = QueryStatus.invalid}; }    if h.status == height_rays.GroundRayStatus.terrain { return QueryHit.{status = QueryStatus.terrain}; }    if h.status == height_rays.GroundRayStatus.exhausted { return QueryHit.{status = QueryStatus.exhausted}; }    candidate := QueryHit.{hit = h.hit, t = f32(h.t), point = h.point, normal = world_point(h.normal.x, h.normal.y, h.normal.z), shape = QueryShape.heightfield, index = i};    best = query_select(best, candidate, h.t);  }  for i: 0..<query_boxes(c) {    b := query_box(c, i);    if b.ok { best = query_select_entry(best, query_enter_box(b.low, b.high, o, d, reach), QueryShape.box, i); }  }  for i: 0..<query_capsules(c) {    k := query_capsule(c, i);    if k.ok { best = query_select_entry(best, query_enter_capsule(k.a, k.b, k.r, o, d, reach), QueryShape.capsule, i); }  }  if best.hit.hit && best.hit.shape != QueryShape.heightfield { best.hit.point = world_add(o, world_scale(d, best.hit.t)); }  return best.hit;}

Overlaps

query_overlap writes the colliders that a sphere overlaps into out, in collider order, and returns how many there are. If out is too small, the count is still complete. A sphere that only touches a shape doesn't overlap it.

jai
QueryId :: struct { shape: QueryShape; index: int; }QueryOverlapResult :: struct { status: QueryStatus; count: int; }// The colliders a sphere overlaps (closer than its radius), in collider order: the ground,// then boxes, then capsules, each by index. It writes as many as fit in `out` and returns how// many there are.query_overlap_checked :: (c: Colliders, centre: WorldPoint, r: f32, out: [] QueryId) -> QueryOverlapResult #effects(all) {  if c.near.count > 0 { return query_near_overlap(c, centre, r, out); }  n := 0;  if !query_point_finite(centre) || !query_finite(r) || !(r > 0) { return QueryOverlapResult.{status = QueryStatus.invalid}; }  if c.heightfields.count > QUERY_HEIGHTFIELDS_MAX { return QueryOverlapResult.{status = QueryStatus.capacity}; }  // Preflight every heightfield before the first write to caller storage.  touching: [QUERY_HEIGHTFIELDS_MAX] bool;  for i: 0..<c.heightfields.count {    field := c.heightfields[i];    h := height_contacts.ground_overlap(field.ground, field.heights, centre, r, c.heightfield_budget);    status := query_height_status(h.status);    if status != QueryStatus.ok { return QueryOverlapResult.{status = status}; }    touching[i] = h.hit;  }  if c.heightfields.count == 0 && c.ground_enabled && centre.y - r < c.ground { n = query_put(out, n, QueryShape.ground, 0); }  for i: 0..<c.heightfields.count { if touching[i] { n = query_put(out, n, QueryShape.heightfield, i); } }  for i: 0..<query_boxes(c) {    b := query_box(c, i);    if !b.ok { continue; }    q := world_point(stand_clamp(centre.x, b.low.x, b.high.x), stand_clamp(centre.y, b.low.y, b.high.y), stand_clamp(centre.z, b.low.z, b.high.z));    g := world_sub(centre, q);    if world_dot(g, g) < r * r { n = query_put(out, n, QueryShape.box, i); }  }  for i: 0..<query_capsules(c) {    k := query_capsule(c, i);    if !k.ok { continue; }    g := world_sub(centre, query_nearest(k.a, k.b, centre));    if world_dot(g, g) < (r + k.r) * (r + k.r) { n = query_put(out, n, QueryShape.capsule, i); }  }  return QueryOverlapResult.{count = n};}// The legacy count API returns -1 on heightfield refusal. New consumers use the// checked result so an exhausted traversal can never be mistaken for a clear scene.query_overlap :: (c: Colliders, centre: WorldPoint, r: f32, out: [] QueryId) -> int #effects(all) {  q := query_overlap_checked(c, centre, r, out);  if q.status != QueryStatus.ok && c.heightfields.count > 0 { return -1; }  return q.count;}query_put :: (out: [] QueryId, n: int, shape: QueryShape, index: int) -> int #effects(all) {  if n < out.count { out[n] = QueryId.{shape = shape, index = index}; }  return n + 1;}

Sweeps

A sphere of radius r touches a shape when its centre reaches the shape grown by r. So query_sweep casts a ray from the centre against grown shapes:

  • The ground, raised by r.
  • A capsule, with its radius increased by r.
  • A box grown by r. This shape has rounded edges and corners. It is the union of three boxes, each grown by r along one axis, and twelve capsules of radius r, one along each edge. The capsules' end spheres cover the corners.
jai
// A sphere of radius r moving from `from` by `by` first touches a collider at t in [0, 1]: the// ray from its centre against each collider grown by r. A box grown by r is three boxes, each// grown by r along one axis, and its twelve edges as capsules of radius r.query_enter_grown_box :: (low: WorldPoint, high: WorldPoint, r: f32, o: WorldPoint, d: WorldPoint, far: f32) -> QueryEntry #effects(all) {  best: QueryEntry;  for k: 0..<3 {    g: [3] f32;    g[k] = r;    gl := world_point(low.x - g[0], low.y - g[1], low.z - g[2]);    gh := world_point(high.x + g[0], high.y + g[1], high.z + g[2]);    best = query_sooner(best, query_enter_box(gl, gh, o, d, far));  }  for e: 0..<12 {    k := e / 4;   // the edges along x, then y, then z    u := f32(e % 2); v := f32((e / 2) % 2);    a := query_corner(low, high, k, u, v, 0); b := query_corner(low, high, k, u, v, 1);    best = query_sooner(best, query_enter_capsule(a, b, r, o, d, far));  }  return best;}// An end of the edge along axis k, at the low (0) or high (1) side of each other axis.query_corner :: (low: WorldPoint, high: WorldPoint, k: int, u: f32, v: f32, end: int) -> WorldPoint #effects(all) {  side := [3] f32.[0, 0, 0];  side[k] = f32(end);  side[(k + 1) % 3] = u; side[(k + 2) % 3] = v;  return world_point(low.x + (high.x - low.x) * side[0], low.y + (high.y - low.y) * side[1], low.z + (high.z - low.z) * side[2]);}query_sooner :: (a: QueryEntry, b: QueryEntry) -> QueryEntry #effects(all) {  if !b.hit || (a.hit && b.t >= a.t) { return a; }  return b;}query_sweep :: (c: Colliders, from: WorldPoint, r: f32, by: WorldPoint) -> QueryHit #effects(all) {  if c.near.count > 0 { return query_near_sweep(c, from, r, by); }  best: QuerySelection;  if !query_point_finite(from) || !query_point_finite(by) || !query_finite(r) || !(r > 0) { return QueryHit.{status = QueryStatus.invalid}; }  if c.heightfields.count > QUERY_HEIGHTFIELDS_MAX { return QueryHit.{status = QueryStatus.capacity}; }  if !(world_dot(by, by) > 0) {    // not moving: a touch at 0, or none    hits: [1] QueryId;    q := query_overlap_checked(c, from, r, hits[..]);    if q.status != QueryStatus.ok { return QueryHit.{status = q.status}; }    if q.count == 0 { return best.hit; }    return QueryHit.{hit = true, point = from, normal = world_point(0, 1, 0), shape = hits[0].shape, index = hits[0].index};  }  if c.heightfields.count == 0 && c.ground_enabled { best = query_select_entry(best, query_enter_ground(c.ground + r, from, by, 1), QueryShape.ground, 0); }  for i: 0..<c.heightfields.count {    field := c.heightfields[i];    h := height_contacts.ground_sweep(field.ground, field.heights, from, r, by, c.heightfield_budget);    status := query_height_status(h.status);    if status != QueryStatus.ok { return QueryHit.{status = status}; }    candidate := QueryHit.{hit = h.hit, t = f32(h.t), point = h.point, normal = world_point(h.normal.x, h.normal.y, h.normal.z), shape = QueryShape.heightfield, index = i};    best = query_select(best, candidate, h.t);  }  for i: 0..<query_boxes(c) {    b := query_box(c, i);    if b.ok { best = query_select_entry(best, query_enter_grown_box(b.low, b.high, r, from, by, 1), QueryShape.box, i); }  }  for i: 0..<query_capsules(c) {    k := query_capsule(c, i);    if k.ok { best = query_select_entry(best, query_enter_capsule(k.a, k.b, k.r + r, from, by, 1), QueryShape.capsule, i); }  }  if best.hit.hit && best.hit.shape != QueryShape.heightfield { best.hit.point = world_add(from, world_scale(by, best.hit.t)); }  return best.hit;}

The first version grew each of the three boxes along two axes instead of one. That shape has square edges, so a sphere that passed close to an edge hit it early. The sweep oracle found the error on its fourth random scene: the sweep reported a touch at t = 0.330, and marching found the first touch at t = 0.840.

An example

The example metaverse-engine/examples/four-questions.coax asks all four questions about one scene:

jai
#load "../physics/query.coax";#import "Basic";// One scene and the four questions: a 0.5 m step and a 0.6 m wall on the ground, and a post// (a capsule). Feet step onto the step but not the wall, a ray finds the wall's face, a sphere// set down by the post overlaps it, and a ball thrown at the wall touches it short of its face.main :: () {  boxes := [12] f32.[0, 0, 0, 1, 0.5, 1,   2, 0, 0, 3, 0.6, 1];  posts := [7] f32.[5, 0, 0.5, 5, 2, 0.5, 0.25];  c := Colliders.{boxes = boxes[..], capsules = posts[..]};  for x: [3] f32.[0.5, 2.5, 4] {    g := query_stand(c, x, 0.5, 0, 0.3);    print("stand at x %: y %, on %, index %\n", x, g.y, g.shape, g.index);  }  h := query_ray(c, world_point(-1, 0.3, 0.5), world_point(1, 0, 0), 10);  print("ray along +x: t %, on %, index %, normal (%, %, %)\n", h.t, h.shape, h.index, h.normal.x, h.normal.y, h.normal.z);  got: [4] QueryId;  n := query_overlap(c, world_point(5.4, 1, 0.5), 0.2, got[..]);  print("overlap by the post: % (%, index %)\n", n, got[0].shape, got[0].index);  s := query_sweep(c, world_point(1.5, 2, 0.5), 0.1, world_point(0.5, -2, 0));  print("sweep of a 0.1 m ball: t %, centre (%, %), on %, index %\n", s.t, s.point.x, s.point.y, s.shape, s.index);}
shell
coax/bin/coax run metaverse-engine/examples/four-questions.coax
text
stand at x 0.5: y 0.5, on box, index 0
stand at x 2.5: y 0.0, on ground, index 0
stand at x 4.0: y 0.0, on ground, index 0
ray along +x: t 1.0, on box, index 0, normal (-1.0, 0.0, 0.0)
overlap by the post: 1 (capsule, index 0)
sweep of a 0.1 m ball: t 0.79999995, centre (1.9, 0.4000001), on box, index 1

The feet stand on the 0.5 m step, but not on the 0.6 m wall. The ray reaches the step's face at x = 0. The ball's centre stops 0.1 m short of the wall's face at x = 2.

Checks

The oracles don't use the formulas in query.coax. They test whether a point is inside each shape, read straight from the colliders' arrays. To find a ray's first hit, an oracle marches along the ray in 2 cm steps, and then halves the last step 40 times. A sweep's oracle does the same with a sphere. Each random scene has a ground, three boxes, and three capsules. The query must agree with the oracle on whether there is a hit, on which collider it is, and on t to within 1 mm. Rays and sweeps each run 48 scenes, in three checks of 16, so each check stays inside the compile-time step budget.

jai
// Two rays into scene `seed`: each first hit is where marching by containment first finds a// collider, within a millimetre, and is the same collider; the normal faces the ray and points// out of the solid it hit.oracle_rays :: (seed: int) {  r := [1] OracleDraw.[OracleDraw.{rng = seed * 7919 + 12345}];  s := oracle_scene(r[..]);  c := Colliders.{ground = s.ground, boxes = s.boxes[..], capsules = s.capsules[..]};  for k: 0..<2 {    o := oracle_point(r[..]);    d := world_unit(world_sub(oracle_point(r[..]), o));    if k == 1 && seed % 3 == 0 { d = world_unit(world_point(d.x, abs(d.y) + 0.1, d.z)); }   // some rays up: they may reach nothing    q := query_ray(c, o, d, 10);    m := oracle_march(c, o, d, 0, 10, 0.02);    #assert q.hit == m.found.hit;    if q.hit {      #assert abs(q.t - m.t) <= 0.001 && q.shape == m.found.shape && q.index == m.found.index;      #assert world_distance(q.point, world_add(o, world_scale(d, q.t))).value < 0.0001;      #assert abs(world_dot(q.normal, q.normal) - 1) < 0.001;      if q.t > 0 {        #assert world_dot(q.normal, d) < 0;        #assert oracle_inside(c, q.shape, q.index, world_sub(q.point, world_scale(q.normal, 0.01)));        #assert !oracle_inside(c, q.shape, q.index, world_add(q.point, world_scale(q.normal, 0.01)));      } else {        #assert world_distance(q.normal, world_scale(d, -1)).value < 0.0001;      }    }  }}

The course check runs the walker over a 0.5 m ledge. The walker runs, jumps onto the ledge, lands, walks across, and walks off the far side. The states are the same, bit for bit, whether the realm passes walls alone, or the same walls among far bodies and floors. When the ledge is a floor instead of a box, the states are the same until you walk off. You drop off the floor first, because a floor holds you while your middle is within 0.15 m of its edge, and a box's top holds you while your capsule is over it.

jai
#test "jumping onto, landing on and walking off a ledge is the same in every realm" {  ledge := [6] f32.[-2, 0, 1.5, 2, 0.5, 3.5];  among := [12] f32.[-2, 0, 1.5, 2, 0.5, 3.5,   40, 0, 40, 41, 3, 41];  bodies := [7] f32.[-40, 0, -40, -40, 1.5, -40, 0.4];  floors: [2 * STAND_FLOATS] f32;  stand_put_box(floors[..], 0, 30, 30, 34, 34, 1);  as_floor: [STAND_FLOATS] f32;  stand_put_box(as_floor[..], 0, -2, 1.5, 2, 3.5, 0.5);  a: World; a.walls = ledge[..];  b: World; b.walls = among[..]; b.bodies = bodies[..]; b.floors = floors[..];  c: World; c.floors = as_floor[..];  pa := held(walk_place(0, 0, 0, 0), 0, 1, false);  pb := pa; pc := pa;  landed := -1; off_a := -1; off_c := -1;  for i: 0..<220 {    jump := i == 12;    pa = step(a, walk_input(pa, 0, 1, 0, 0, false, jump, 0, 0), STEP);    pb = step(b, walk_input(pb, 0, 1, 0, 0, false, jump, 0, 0), STEP);    pc = step(c, walk_input(pc, 0, 1, 0, 0, false, jump, 0, 0), STEP);    #assert same_step(pa, pb) && pa.body.pos.y == pb.body.pos.y && pa.body.pos.z == pb.body.pos.z;    if landed < 0 && i > 12 && pa.body.on_ground { landed = i; #assert pa.body.pos.y == 0.5 && pa.body.pos.z > 2; }    if off_a < 0 && landed >= 0 && !pa.body.on_ground { off_a = i; }    if off_c < 0 && landed >= 0 && !pc.body.on_ground { off_c = i; }    if off_c < 0 { #assert same_step(pa, pc) && pa.body.pos.y == pc.body.pos.y; }  }  // it landed on the ledge, walked off it, and came down on the ground: the floor first  #assert landed > 12 && off_a > landed && off_c > landed && off_c < off_a;  #assert pa.body.on_ground && pc.body.on_ground && pa.body.pos.y == 0 && pc.body.pos.y == 0 && pa.body.pos.z > 6;  // a realm whose ground is not at 0 stands you on it, and on the ledge's top over it  higher: World; higher.ground = 0.25; higher.walls = ledge[..];  #assert floor_at(higher, 0, 0, 0.25) == 0.25 && floor_at(higher, 0, 2, 0.25) == 0.5 && floor_at(higher, 0, 2, -1) == 0.25;}
shell
coax/bin/coax test metaverse-engine/physics/query.coax --librarycoax/bin/coax mutate metaverse-engine/physics/query.coax --library --root-onlycoax/bin/coax test metaverse-engine/move/player.coax --library

The original scene checks and the heightfield suites cover:

  • the ground: step height, footprint reach, ties, and broken boxes;
  • floors: height, slope, steepness, the floor pad, and floors against boxes;
  • rays against closed forms: faces, end spheres, starts inside, far, and inputs that aren't a ray;
  • overlaps and sweeps against closed forms: rounded edges, touching at the start, a sphere that doesn't move, and bad input;
  • exact boundaries: infinite and very large numbers, flat and inside-out boxes, touching without overlapping, ties at an edge, tangent rays, and a hit at exactly far;
  • sweeps into each of a box's six faces and twelve edges;
  • the ray, sweep, and overlap oracles over random scenes.

The current root-only mutation gate kills all 388 mutants in the query module. Its scope is separate from the ground, ray and sphere-contact gates recorded in chapter 8. The boundary checks include f32 inputs that distinguish a side root at exactly zero, a capsule axis endpoint and equal face/edge times; they also distinguish terrain hits whose full times differ although their public f32 distances are equal.

New runtime consumers use query_ground_checked, query_stand_checked and query_overlap_checked. QueryStatus distinguishes bad input, malformed terrain, exhausted work and excessive capacity from a successful miss. Every heightfield is checked before an overlap writes any IDs. Ground's legacy permissive query continues to skip malformed shapes for trusted callers.

Further realm migration

Chapter 8 adds heightfield ground to all four queries and moves the legacy terrain sampler onto the shared implementation. The remaining realm migration (chapter 64) includes the four terrain realms' floor-relative adapters, their older ray helpers, Everglade's wall-filter step constants and moving metaverse-engine/physics/stand.coax into the engine. Rays against floor shapes for roof and rubble picking remain outside this query profile.

The shared follow camera already reads these colliders. It retains its published box/body clearance rules and uses a checked sphere sweep for heightfields. A grid index can come later; indexed and unindexed queries must give the same answer.

Dependencies

This chapter uses world space from chapter 2. Collider IDs that survive spawn and despawn come from chapter 6. These are the minimum teaching prerequisites. The physics part later adds its own broad and narrow phases (chapter 20, chapter 21), which must agree with these queries on shared shapes. From Coax, R12 frames and R15 strict math come later (Coax roadmap). For background, see the game-engine systems inventory, sections 14 and 26.