Query Services

Use a query to inspect the world owned by a GravitasWorldContext. A raycast checks a line segment, a sweep moves a shape along a segment, and an overlap checks a shape at a pose. Choose the service by the dimensions you need to query.

Quick Read

Two 3D spheres on layer 0 are centered at x = 0 and x = 2. Cast a ray along the X axis from x = -2 to x = 4 to see both obstacles in travel order. The configured context must already contain both colliders in active grid coverage. Reuse the caller-owned list when running the query again.

using FixedMathSharp;
using Gravitas.Queries;
using Gravitas.Support;
using SwiftCollections;

Vector3d start = new(-2, 0, 0);
Vector3d end = new(4, 0, 0);
var mask = PhysicsLayerMask.FromLayer(0);
var hits = new SwiftList<Physics3DHit>();
int count = context.Query3D.RaycastAll(
    start, end, mask, hits);

count is 2. The list contains the sphere at x = 0 first and the sphere at x = 2 second. Use Query3D.Raycast if you only need the nearest hit.

flowchart TB
    accTitle: One ray, two obstacle hits
    accDescr: A ray travels along X from minus 2 to 4. The closest hit is the sphere centered at 0. The all-hit query lists that sphere first and the sphere centered at 2 second.
    Ray["Ray from x = -2 to x = 4"]
    Ray -->|"Raycast"| Closest["Sphere at x = 0"]
    Ray -->|"RaycastAll"| Both["Sphere at x = 0<br/>Then sphere at x = 2"]
To inspect Use
3D colliders context.Query3D
2D colliders in the X/Z plane context.Query2D
Cross-dimensional sweep hits context.QueryMixed
Surfaces that can physically support a 2D collider context.Query2D.QuerySupport

The services share collision broad-phase data. General geometry queries select targets through query filters. Physical 2D support also applies the source collider's collision policy. See layer masks, physical 2D support, and batching for the corresponding contracts. The Query Reference lists the full API and reducer behavior.

Public Surface

3D Queries

Family Closest hit All hits
Raycast Query3D.Raycast(...) Query3D.RaycastAll(...)
Swept sphere Query3D.SweepSphere(...) Query3D.SweepSphereAll(...)
Registered convex source sweeps SweepCapsule, SweepCuboid, SweepCylinder, SweepCone, SweepConvexMesh, SweepCompound matching *All overloads
Cone volume Query3D.OverlapCone(...) Query3D.OverlapConeAll(...)
X/Z projected-circle overlap OverlapCircle, OverlapCircleInDirection OverlapCircleAll

Concave-mesh cone overlap reduces every candidate through FixedMathSharp's full-domain FixedTriangle contract. Stable AB, BC, CA boundary candidates and the exact face-interior candidate are compared before final hit narrowing, so a cone section wholly contained by a large triangle is not dependent on an edge crossing or an axis/face intersection. Equal-distance mesh hits retain triangle index order, and the warmed query path remains allocation-free. The query keeps the world-space cone and the triangle's authored rigid frame separate; an apex that cannot fit in mesh-local scalar coordinates is not a reason to miss a hit.

The 3D projected-circle family classifies the complete X/Z projection of each supported collider. Query Y is ignored. Exact containment is a zero-distance overlap; positive separations retain an exact direction witness even when the public Q32.32 distance and offset round to zero. Hits keep a real 3D ContactAnchor, and point materialization remains explicit through Physics3DHit.TryGetPoint(...). Candidate discovery uses the collision service's partition-synchronized planar index, so configured world height does not multiply query cost. As with other partition-backed 3D queries, a collider must own at least one active-grid partition to be discoverable.

Sphere sweeps against cuboids transform the authored center chord into cuboid local space and delegate to FixedMathSharp's exact spherical-box dilation. Planar faces, rounded edges, and spherical corners therefore share one full-domain first-distance contract; the older sharp expanded-box proxy is not used for queries, compound cuboid parts, grounding, or CCD.

Mesh raycasts and swept-sphere queries solve against one committed local geometry snapshot. Non-uniform scale publishes scaled vertices and their matching face normals together; query workers consume those cached values without recomputing normals or allocating per triangle. Authored vertices remain the source for later scale transactions, not query-plane authority.

2D Queries

Family Closest hit All hits
Circle overlap Query2D.OverlapCircle(...) Query2D.OverlapCircleAll(...)
AABB overlap Query2D.OverlapAabb(...) Query2D.OverlapAabbAll(...)
Convex polygon overlap Query2D.OverlapPolygon(...) Query2D.OverlapPolygonAll(...)
Segment raycast Query2D.Raycast(...) Query2D.RaycastAll(...)
Swept circle Query2D.SweepCircle(...) Query2D.SweepCircleAll(...)

Mixed Queries

Family Closest hit All hits
3D sphere against embedded 2D slabs QueryMixed.SweepSphereAgainst2D(...) QueryMixed.SweepSphereAgainst2DAll(...)
2D circle slab against 3D colliders QueryMixed.SweepCircleAgainst3D(...) QueryMixed.SweepCircleAgainst3DAll(...)

Query2D and Query3D stay dimension-local and never report cross-dimensional hits. Mixed queries are always explicit.

Mixed sphere/slab reducers retain the selected embedded-2D boundary as a semantic point anchor. A valid far-domain witness is not re-queried through a public closest-point API merely because its Euclidean distance cannot fit in Fixed64; compound parts are ranked by exact squared anchor distance with stable authored-order ties. Query families that actually return a scalar distance still fail that final conversion honestly rather than saturating it.

Segment-based circle and sphere raycasts and sweeps solve and rank physical distance along the authored segment directly. They retain the original chord through root ordering and hit reconstruction, so a long segment cannot collapse spatially distinct hits through an intermediate normalized parameter. This does not change FixedMathSharp's separate FixedRay and FixedRay2d contracts: those primitives continue to return ordinary ray parameters, which are physical distances only when their direction is normalized.

The normalized Direction on a hit describes travel; segment detection and CCD advancement retain the original endpoints. Finite box and triangle features are admitted before rounding the reported distance, and triangle surface witnesses round directly from the geometric intersection. Exact grazing remains a query hit without becoming a closing constraint that blocks CCD.

Query Geometry Admission

Query sources share the inclusive 4,096-world-unit conservative reach ceiling exposed by ColliderSettings.MaximumGeometryReach and its 2D counterpart. Circle and sphere queries use their radius. AABB queries measure their prepared half-extents, retaining nearest-even half-size rounding. World-polygon queries measure every vertex about the exact arithmetic vertex mean; rounding that mean first cannot hide an excess at the boundary. A finite cone uses its centered collider enclosure, including its length and end radius. Mixed circle slabs include both planar radius and physical Y half-thickness.

Oversized sources throw ArgumentException before tracing, diagnostics, counters or direct result-buffer mutation. Existing zero-radius and degenerate-query rules remain specific to each API. Ray length and swept travel are separate from source size; long travel and ordinary geometry near scalar world limits remain supported under their existing representability rules.

Explicit mixed queries also validate active 2D target slabs before indexing them, including in TwoD, ThreeD and Both modes. Pure 2D geometry remains independent of unused thickness. Inactive targets and degenerate sweeps do not require a mixed envelope that the query will not use.

Numeric source-size limits are checked across a batch before outputs are cleared or written. Other failures encountered while executing a request, including invalid registered-source state or a live target slab, retain the completed prefix and leave later output slots/ranges untouched. Batches do not roll back completed requests.

Hit Witnesses

Physics3DHit, Physics2DHit, and PhysicsMixedHit retain surface witnesses as rigid-frame anchors with separate local feature terms. Classification, distance, ordering, diagnostics, and deterministic replay do not require an absolute point to be representable. The familiar Point, Point3D, and Point2D properties remain convenient for ordinary coordinates, but throw InvalidOperationException when the conceptual witness lies outside the Fixed64 scalar range. Use TryGetPoint, TryGetPoint3D, or TryGetPoint2D when a query may approach a scalar face. Returning false from a witness materialization method does not invalidate the query hit.

Initial Contact With a Solid Primitive

A sphere sweep against a solid 3D primitive, or a mixed circle-slab sweep against that primitive, retains the actual target boundary for a contained start. The normal uses the target's outward surface direction, independently of travel, so CCD permits escape and rejects motion deeper into the target. Equal nearest features keep the primitive's geometric order; coincident sphere centers use world +X; capsule centerline ties use rotated local +X. Exterior edge and apex contacts retain the separating direction from the closest feature toward the source center. Mixed slab witnesses clamp their vertical offset to the slab's caps without requiring the target witness's other coordinates to be representable.

Initial Contact With a Mesh

A sphere sweep against a 3D mesh treats its triangles as two-sided surfaces, including convex meshes and convex-mesh compound parts. An initially touching or overlapping triangle reports zero travel distance and retains the target's closest surface anchor. Its normal points from that anchor toward the sphere center, so face, edge, and vertex contacts keep their geometric side regardless of travel or triangle winding. Only an exactly coincident center and anchor uses the selected triangle's authored face normal. Equal nearest features keep triangle index order, and compound parts keep authored order. CCD preserves this normal when rejecting separating or tangent initial contacts; grounding can therefore distinguish overhead surfaces from upward support.

These mesh sweeps test triangle proximity, not solid-volume containment: a sphere wholly inside a closed mesh without touching its triangles is not an initial hit.

Translational convex-source mesh sweeps also retain geometric normals for initial contacts, independently of travel and winding. They resolve the actual source leaf and target triangle or hull before reporting a compound owner. Separated contacts inside the query tolerance retain their closest-feature normal unless exact geometry certifies an actual filled face contact. A face witness requires both a source support projected onto the finite trusted surface domain and contact with the triangle that admits that projection. Trusted domains include mixed winding, subdivision and nonconvex patches; holes and notches retain their empty geometry. A touching exposed edge or vertex keeps its separating axis.

This prevents covered triangle seams from blocking tangent motion without substituting an infinite plane at the real perimeter. Convex mesh targets retain solid-volume containment. For cylinder, cone and circle-slab sources, the initial normal selects the smallest exit projection among hull face axes; it does not promise a global minimum translation including edge axes. CCD rejects separating and tangent initial contacts before reducing triangle and compound hits, so a nonblocking first feature cannot hide a blocking sibling. Public equal-distance hits retain their existing authored feature order.

When GJK reports an initial intersection, the mesh hit requires a normal resolved by complete contact geometry or certified by exact support intervals; a bounded GJK intersection alone cannot establish that contact.

Certified Planar Mesh Patches

An ordinary, initially separated convex-source sweep may treat a whole concave mesh as one support-mapped surface when its existing topology certificate proves a filled convex coplanar patch. This requires a finite reference-center chord crossing and all mesh triangles in the BVH candidate set. Mesh sources are eligible, but the crossing only selects an attempt: GJK still tests their actual hull, without assuming its inspection center lies inside. Initial contacts, declared surface admission, local triangle subsets and uncertified domains retain triangle selection. The patch uses the authored geometry frame and finite boundary, with the existing query tolerances and raw-distance hit ordering.

Ordinary sphere sweeps can likewise replace a whole certified convex coplanar patch with its finite corner fan, retaining their analytic kernels. Replacement fan faces accept admitted nonzero geometry without the generic triangle helper's squared-area epsilon; authored fallback keeps its existing predicate.

An ordinary mixed circle-slab cast can use one carrier triangle when its motion is exactly aligned with the plane's X/Z normal and its supporting-cap center chord crosses the finite patch. This certifies that the first whole-plane contact belongs to the target. The existing analytic carrier sweep supplies the distance; the finite chord crossing supplies paired final rounded witnesses and the geometric plane normal. Cap selection uses the exact vertical sign before normal rounding. TOI rounding can leave a small separation at the stored time. Oblique, rim-only and tangential casts retain authored selection; a declined carrier kernel also falls through to it.

Both paths retain the authored geometry frame and scale, require disjoint initial bounds and all triangles admitted by the BVH, and preserve candidate counts as admitted authored triangles. Identity-sensitive CCD/supplier admission retains authored triangles. Repeated identical ordered triangles may reuse the immediately preceding analytic result within one ordinary query; every authored index still participates in distance/index reduction. Equivalent triangulations and these patch paths need not select identical valid physical witnesses; mixed face normals can also differ from the legacy center-to-witness direction. Replay comparisons across versions must account for these result-field changes.

Initial Contact in 2D

A 2D circle sweep that starts touching or overlapping a target reports zero travel distance but still retains the target's surface witness, not the probe's starting center. It preserves the anchor even when that point cannot be materialized. At coincident circle centers, the deterministic fallback is world +X. When a circle probe lies on a capsule's centerline, the fallback is the capsule's local +X radial side, rotated with the capsule. The witness and outward normal describe the same side of the target.

A 2D ray starting inside or on a supported shape reports zero travel distance and the ray start as its point. That point identifies the initial overlap and may lie inside the target. Its outward normal comes from point/shape separation geometry: box and polygon face normals, circle radial normals, and capsule normals from the nearest axis point. Travel direction does not change this normal. Equal convex separation depths retain geometric feature order; coincident circle centers use world +X, and capsule centerline starts use local +X rotated with the capsule. Unsupported custom shapes produce no ray hit.

Compounds retain their existing reduction: equal-distance part hits keep the first authored part and report the compound owner. Closest and all-hit query ordering across colliders still uses distance, then collider ID.

Continuous Static Surface Queries

Static-surface membership preserves each member as a separate query target. All-hit queries can report several members of one surface; closest-hit ordering still uses the ordinary distance and collider identity rules. Membership does not merge hits or fill holes, and an initially overlapping sweep still reports zero travel distance. Physical CCD admission uses the validated finite surface domain to distinguish covered joins from real rims. Query-grounded bodies invalidate dependent support when membership, geometry, or eligibility changes.

Common Usage

The following integration excerpt assumes a configured context, query input values, and a host PublishWorldPoint callback:

using Gravitas.Queries;
using Gravitas.Support;
using SwiftCollections;

PhysicsLayerMask mask = PhysicsLayerMask.FromLayer(0);

bool hit = context.Query3D.Raycast(
    origin,
    direction,
    maxDistance,
    out Physics3DHit rayHit,
    mask);

SwiftList<Physics2DHit> hits2D = new();
int hitCount2D = context.Query2D.RaycastAll(
    start2D,
    end2D,
    mask,
    hits2D);

SwiftList<PhysicsMixedHit> mixedHits = new();
int mixedHitCount = context.QueryMixed.SweepSphereAgainst2DAll(
    origin,
    origin + direction * maxDistance,
    radius,
    mask,
    mixedHits,
    excludedCollider: null);

if (hit && rayHit.TryGetPoint(out Vector3d worldPoint))
{
    PublishWorldPoint(worldPoint);
}

All-hit methods clear the caller-provided list, write sorted hits, and return the hit count.

Services release candidate references when a query completes and internal batch hit references after copying each request's results, including exceptional exits. Reusable storage retains its capacity. Replacing caller-owned results releases the previous populated slots; the returned hits remain owned by the caller until that buffer is cleared, replaced, or released.

Batch Pattern

Use a batch when several sensors issue the same kind of query in one frame. Keep the request array and output buffers for reuse across frames. A request range points into the shared hit list and keeps each sensor's results together. See a two-ray example for how the ranges index the output.

PhysicsRaycast3DRequest[] requests = new PhysicsRaycast3DRequest[agentCount];
Physics3DHit[] closestHits = new Physics3DHit[agentCount];
SwiftList<Physics3DHit> allHits = new(agentCount * 4);
PhysicsQueryHitRange[] ranges = new PhysicsQueryHitRange[agentCount];

for (int i = 0; i < agentCount; i++)
{
    requests[i] = new PhysicsRaycast3DRequest(
        sensorOrigins[i],
        sensorTargets[i],
        mask);
}

int closestHitCount = context.Query3D.RaycastBatch(requests, closestHits);
int allHitCount = context.Query3D.RaycastAllBatch(requests, allHits, ranges);

for (int requestIndex = 0; requestIndex < agentCount; requestIndex++)
{
    PhysicsQueryHitRange range = ranges[requestIndex];
    for (int hitIndex = 0; hitIndex < range.Count; hitIndex++)
    {
        Physics3DHit queryHit = allHits[range.Start + hitIndex];
        // Consume this request's sorted hits.
    }
}

Request order is preserved in closest-hit output and all-hit ranges. Hits inside each request keep the same deterministic ordering as the matching single-query API.

Physical 2D Support

Use Query2D.QuerySupport between complete fixed steps when a controller needs the nearest surface that can physically support its registered collider. The circle travels opposite Up; the request normalizes that nonzero direction. Radius and distance must be positive, including distances as small as one raw fixed-point unit. MinimumNormalDot is an inclusive threshold in (0, 1].

This partial integration snippet assumes an initialized SolidBody2D body and its owning context. Probe placement is controller policy, not inferred from the body's shape:

using FixedMathSharp;
using Gravitas.Queries;
using Gravitas.Support;

var probe = new Physics2DSupportQuery(
    source: body.Collider,
    center: body.Position,
    radius: Fixed64.Half,
    up: Vector2d.Forward,
    distance: Fixed64.One,
    minimumNormalDot: Fixed64.Half,
    layers: PhysicsLayerMask.All);

Physics2DSupportQueryStatus status = context.Query2D.QuerySupport(probe, out var support);

Found returns a target-surface Physics2DHit, not the probe center, along with SampledFrame and IsCurrentLifetime. The lifetime check rejects default, removed, reset, and recycled registrations; it does not certify that a moving surface still occupies its sampled position. NoSupport means the complete probe found no eligible surface. WorldNotReady and Unrepresentable are not evidence of empty space; all non-Found results clear the hit. Invalid request arguments or a source not actively registered in this context throw.

Support includes bodyless, static, and kinematic targets, but excludes triggers and dynamic carriers. It respects both colliders' physical ignore masks, the layer matrix, hierarchy, linked-joint exclusions, and the query include mask. Normal filtering happens before compound-part selection, so a wall cannot hide an eligible floor part. Ties use distance, owner ID, then authored part order.

Discovery uses the existing 2D physics index at world Y = 0, independently of the actor's host Y. As with other indexed queries, targets must be represented by physical grid cells. Candidate buffers are reused but may grow; this is a synchronous query without a hard work or allocation ceiling.

Grid Changes And Query Readiness

At stable between-frame boundaries, both dimensional indexes reconcile grid replacement and sparse-cell changes before sampling. Reconciliation rebinds committed geometry; it does not publish pending authored shape edits. Relevant world changes are combined into one refresh, while ordinary queries and obstacle-only events do not trigger a registry-wide rebuild. Callback-deferred 2D partition updates finish at the completed fixed-step boundary.

After LateSimulate() returns, both dimensional indexes include final positional corrections from pure and mixed response. Both physics services coalesce correction membership updates through service/body publication flags. 3D publishes geometry after response and retained-contact bookkeeping to preserve the solver's contact snapshots. 2D updates geometry immediately for recovery, then publishes membership before collision distribution, an indexed 2D query, or successful step completion. A pending correction can therefore trigger a body scan during an internal 2D query; ordinary post-step queries already have current membership. Raycasts, sweeps, overlaps, and batch or explicit mixed queries after completion sample the completed body pose.

Candidate Ordering

Pure 2D gathering visits partition memberships directly, deduplicates collider IDs and sorts the final candidate buffer by collider ID. Intermediate partition and member-copy sorts are unnecessary for that final order. Three-dimensional ray/sweep partition gathering already traverses memberships directly. The separate planar candidate-index rebuild still uses sorted member copies. Closest-hit reducers and all-hit output sorting retain their existing contracts in every dimension.

When Physical Support Can Be Queried

Do not sample physical support during Simulate/LateSimulate, their open transaction, or a grid-change callback whose committed change has not reached the context. QuerySupport returns WorldNotReady at those boundaries.

Layer Mask Semantics

Queries accept PhysicsLayerMask layerMask as an include mask:

  • PhysicsLayerMask.FromLayer(layer) includes one layer.
  • PhysicsLayerMask.FromLayers(...) includes several layers.
  • PhysicsLayerMask.All includes every layer.
  • PhysicsLayerMask.None includes no layers.

Use PhysicsLayer for a collider's single collision/filter layer and PhysicsLayerMask for query or ground-check filters.

General geometry query services do not apply LSCollider.IgnoredCollisionLayers or LSCollider2D.IgnoredCollisionLayers. Those masks are physical collider-to-collider filters for collision pairs, CCD, and grounding/support. Those queries report whatever the caller's include mask, trigger flag, and explicit excluded-collider arguments select.

Hit Data

Hit type Used by Key fields
Physics3DHit Query3D Collider, Body, Point, Normal, Distance, Direction
Physics2DHit Query2D Collider, Body, Point, Normal, Distance
PhysicsMixedHit QueryMixed Collider3D, Collider2D, Body3D, Body2D, Point3D, Point2D, Normal3DTo2D, source-oriented normals, ReducerKind, Distance, Direction3D

Distance is a query-family metric. Raycasts and sweeps report source travel, which is not generally the distance from the source origin to the retained surface witness. Contained overlap probes can report zero while their anchor remains on the target boundary. Cone-volume queries use axial distance for ordering. Interpret the value through the API that produced it; measuring the witness offset is not a general check of hit distance.

Static/bodyless hits can have a collider with a null body.

PhysicsMixedHit.Normal3DTo2D follows the mixed contact invariant: it points from the 3D side toward the embedded 2D volume. Source-oriented normals are provided so CCD helpers do not need to reinterpret that invariant.

An initially overlapping mixed circle/mesh sweep reports distance zero and a finite representative contact from the same surface geometry as discrete mixed collision. Its normal is independent of the requested sweep direction. A single hit describes one retained constraint; its normal does not establish a whole-mesh escape for a nonconvex surface.

Reentrancy

Query services keep mutable buffers on the service instance. Do not run multiple queries concurrently against the same context service. The design matches a single-threaded deterministic lockstep loop.

Hosts that need parallel query workloads should use separate contexts or add an explicit caller-owned query job/state design with tests and benchmarks.

Rules That Matter

  • Keep 2D, 3D, and mixed query services explicit.
  • Keep all-hit buffers caller-owned.
  • Preserve deterministic hit ordering.
  • Use query include masks for general geometry filtering; physical support also applies the source collider's collision policy.
  • Keep mesh-source boundaries explicit.
  • Treat ReducerKind as part of mixed query truth.
  • Add benchmarks when query candidate gathering, reducer math, batching, or hit ordering changes.

Source Map