Your First Query#

This page publishes a few objects and queries them. It starts with the usual setup, where ovspatialquery reads geometry from an ovstage stage. It then publishes geometry from arrays your program supplies, first in Python and then in C. Each program runs as shown, and the output under it is what it prints.

Before You Begin#

The programs on this page need the packages that Install describes:

Program

Requirements

Python programs

The ovspatialquery wheel, ovstage 0.4, and NVIDIA Warp (warp-lang)

C program

The C SDK, CMake 3.20 or newer, and a C11 compiler

Querying an ovstage Stage#

A population is the set of objects that queries read. An ovstage population is bound to one stage and one ovstage filter. Each time you publish, it reads the selected prims’ shapes and world transforms from the stage, so your program describes no geometry itself.

The following figure shows what the program does. It loads a two-prim scene, publishes it, and casts one ray along +x:

What the program does: select prims, seal their transforms at ordinal 2, publish that ordinal, then cast a ray.

The program reads the stage, publishes it, and prints the hit:

import ovstage

from ovspatialquery import Library, RaycastQuery

SCENE = """#usda 1.0
def Xform "World"
{
    def Cube "Crate"
    {
        double size = 1
        double3 xformOp:translate = (4, 0, 0)
        uniform token[] xformOpOrder = ["xformOp:translate"]
    }
    def Sphere "Ball"
    {
        double radius = 0.5
        double3 xformOp:translate = (4, 3, 0)
        uniform token[] xformOpOrder = ["xformOp:translate"]
    }
}
"""

# ovstage seals each edit at an ordinal. Ordinal 1 holds the authored scene
# (read at time 0), ordinal 2 its computed world transforms.
stage = ovstage.Stage("first-query")
RENDERING = ovstage.PopulationDomain.RENDERING
ovstage.population.open_usd_from_string(stage, SCENE, 1, 0.0, RENDERING)
stage.advance_write_floor(ordinal=1).wait()
stage.compute_hierarchy(1, 2, ovstage.HierarchyComputationModel.DEFAULT_CPU)
stage.advance_write_floor(ordinal=2).wait()

# A population is bound to one stage and one ovstage filter:
# here, every prim under /World.
world = ovstage.Filter(
    [ovstage.Predicate("usd-path", ovstage.FilterOp.PREFIX, ["/World/"])]
)

with Library.open(require_ovstage=True) as library, library.instance() as instance:
    population = instance.ovstage(ovstage, stage).create_population(world)

    # Publish sealed ordinal 2. The version keeps that number.
    with population.enqueue_set(2) as publication:
        publication.wait()
        count = publication.fetch_population_update().object_count
    print("published", count, "prims")

    ray = population.target.raycast_closest(
        RaycastQuery(origin=(0, 0, 0), unit_direction=(1, 0, 0), max_distance=20)
    )
    # An ovstage object ID is the prim's path token.
    prim_path = ovstage.PrimPath(ray.hit.object_id)
    path = ovstage.PathDictionary(stage).path_to_string(prim_path)
    print("ray hit", path, "at distance", round(ray.hit.distance, 3), end=" ")
    print("ordinal", ray.source_ordinal)

# Destroy the stage once nothing uses it, rather than at interpreter exit.
stage.destroy()

It prints this output:

Output#
published 2 prims
ray hit /World/Crate at distance 3.5 ordinal 2

Notice the following about this program:

  1. Library.open(require_ovstage=True) loads the library and checks that it can read ovstage stages. The instance owns everything created through it. Leaving its with block closes whatever is still open, so the program needs no teardown code. An exception inside the block is the one you see.

  2. ovstage seals each edit at an ordinal, an increasing number. You publish an ordinal that ovstage has sealed, and the population’s new version keeps that number. Here that is ordinal 2, the ordinal that holds the world transforms. ovspatialquery never renumbers a source’s ordinals, and every result reports the ordinal it read in source_ordinal.

  3. Publishing is asynchronous. enqueue_set returns an operation, and wait() blocks until it is done. Queries never see a half-published version.

  4. An object ID is the prim’s path token. Wrapped in an ovstage.PrimPath, it turns back into a prim path through ovstage.PathDictionary. ovstage 0.3 has no PrimPath and takes the ID itself. A prim re-created at the same path keeps its ID.

  5. The filter selects prims by path. Only the prim types in the following table can be published. A prim of any other type that the filter matches, such as the Xform /World itself, is left out. Publishing still succeeds, and its result lists that prim with the reason UNSUPPORTED_TYPE. That is why this filter uses the prefix /World/. An empty filter selects every prim of these types.

  6. The publication result also counts what it left out. Check excluded_object_count as well as object_count, and refer to What an ovstage Population Publishes for the reasons and for how transforms apply.

An ovstage population publishes these Universal Scene Description (USD) prim types:

USD Prim

Published As

Cube

box

Sphere

sphere

Capsule

capsule

Mesh

triangle mesh, queried as its authored faces whatever its subdivisionScheme

Mesh with PhysicsMeshCollisionAPI and physics:approximation = "convexHull"

the convex hull a PhysX simulation of it collides with

Querying Geometry from Arrays#

When the geometry does not live in an ovstage stage, an explicit population holds geometry your program describes in arrays. It is declared in its own header, ovspatialquery_explicit.h. Compared with the program in Querying an ovstage Stage, you supply what ovstage supplied:

Aspect

ovstage Population

Explicit Population

Shapes

read from each prim

registered once as definitions, each with an ID you choose

Object IDs

prim path tokens

any 64-bit values you choose

Poses

world transforms read from the stage

a translation and an xyzw rotation per object

Ordinals

the ovstage ordinal you publish

any nonnegative value you choose, greater than the previous publication’s

The next program publishes two boxes and a sphere and queries them three ways: a ray, a sphere swept along a line, and an overlap test. The following figure shows what it computes:

What the program computes, drawn to scale from above.

The program publishes the three objects and runs the three queries:

import warp as wp

from ovspatialquery import (
    GeometryType,
    Library,
    OverlapQuery,
    RaycastQuery,
    Sphere,
    SphereSweepQuery,
)

wp.config.log_level = wp.LOG_WARNING  # skip Warp's start-up banner
CPU = "cpu"  # this program keeps its input arrays on the CPU

# The instance owns everything created through it and closes it when the block ends.
with Library.open() as library, library.instance() as instance:
    adapter = instance.explicit()

    # 1. Register shapes once: definition 1 is a 1 x 1 x 1 box,
    #    definition 2 a sphere of radius 0.5. Every column is a Warp array;
    #    finish() waits for the operation and closes it.
    adapter.register_boxes(
        definition_values=wp.array([1], dtype=wp.uint64, device=CPU),
        half_extents=wp.array([[0.5, 0.5, 0.5]], dtype=wp.float64, device=CPU),
    ).finish()
    adapter.register_spheres(
        definition_values=wp.array([2], dtype=wp.uint64, device=CPU),
        radii=wp.array([0.5], dtype=wp.float64, device=CPU),
    ).finish()

    # 2. Place three objects and publish them as ordinal 1.
    population = adapter.create_population()
    with population.enqueue_set(
        1,
        object_values=wp.array([10, 11, 12], dtype=wp.uint64, device=CPU),
        geometry_types=wp.array(
            [GeometryType.BOX, GeometryType.BOX, GeometryType.SPHERE],
            dtype=wp.int32,
            device=CPU,
        ),
        geometry_values=wp.array([1, 1, 2], dtype=wp.uint64, device=CPU),
        translations=wp.array(
            [[4.0, 0, 0], [8, 0, 0], [4, 3, 0]], dtype=wp.float64, device=CPU
        ),
        rotations_xyzw=wp.array([[0.0, 0, 0, 1]] * 3, dtype=wp.float32, device=CPU),
    ) as publication:
        publication.wait()
        count = publication.fetch_population_update().object_count
    print("published", count, "objects")

    target = population.target  # the head of this population

    # 3a. A ray along +x stops on the first box's surface.
    ray = target.raycast_closest(
        RaycastQuery(origin=(0, 0, 0), unit_direction=(1, 0, 0), max_distance=20)
    )
    hit = ray.hit
    print("ray hit", hit.object_id, "at distance", round(hit.distance, 3), end=" ")
    print("ordinal", ray.source_ordinal)

    # 3b. A sphere of radius 0.5 swept along y = 3 reaches the sphere object.
    sweep = target.sweep_sphere_closest(
        SphereSweepQuery(
            center=(0, 3, 0), radius=0.5, unit_direction=(1, 0, 0), max_distance=20
        )
    )
    hit = sweep.hit
    center = tuple(round(v, 3) for v in hit.query_position)
    print("sweep hit", hit.object_id, "at distance", round(hit.distance, 3), end=" ")
    print("with its center at", center)

    # 3c. Does anything overlap a sphere around the second box?
    overlap = target.overlap_any(OverlapQuery(Sphere(center=(8, 1, 0), radius=0.75)))
    print("overlap", overlap.hit.object_id if overlap.hit else None)

It prints this output:

Output#
published 3 objects
ray hit 10 at distance 3.5 ordinal 1
sweep hit 12 at distance 3.0 with its center at (3.0, 3.0, 0.0)
overlap 11

Notice the following about this program:

  1. A registration returns an operation too. finish() waits for it and closes it, raising if it failed. A with block does the same for an operation whose result you fetch first, such as the publication.

  2. Every column is passed by keyword, named as in the C tables. A column is any array with __dlpack__, and this guide uses Warp arrays. A wrong dtype, shape, or device raises ValueError naming the column before anything reaches the library.

  3. Queries are exact by default: they stop on an object’s surface. Pass precision=QueryPrecision.BOUNDS_CANDIDATE for the cheaper bounding-box answer. For the difference, refer to Result Types.

  4. A sweep hit reports two points: position, on the object it touched, and query_position, where the moving shape’s center was at contact.

Querying from C#

The C API is the same model with explicit structs. The C program publishes one box from arrays, as the explicit Python program does, and casts the same ray at it. The following figure shows its scene:

The C program: one box, one ray.

The program checks every call and prints the hit:

#include <dlpack/dlpack.h>
#include <ovspatialquery/ovspatialquery.h>
#include <ovspatialquery/ovspatialquery_explicit.h>

#include <stdint.h>
#include <stdio.h>

/* The shape and packed strides of a one-row column. */
typedef struct
{
    int32_t ndim;
    int64_t shape[2];
    int64_t strides[2];
} layout_t;

static layout_t SCALAR = {1, {1}, {1}};
static layout_t VEC3 = {2, {1, 3}, {3, 1}};
static layout_t VEC4 = {2, {1, 4}, {4, 1}};

/* Every input is a DLPack tensor on the CPU, copied when the call is admitted. */
static ovspatialquery_input_array_t input(void* data, DLDataType dtype, layout_t* layout)
{
    ovspatialquery_input_array_t array = {0};
    array.tensor.data = data;
    array.tensor.device = (DLDevice){kDLCPU, 0};
    array.tensor.ndim = layout->ndim;
    array.tensor.dtype = dtype;
    array.tensor.shape = layout->shape;
    array.tensor.strides = layout->strides;
    array.ownership = OVSPATIALQUERY_INPUT_COPIED_ON_SUBMISSION;
    return array;
}

static const DLDataType U64 = {kDLUInt, 64, 1};
static const DLDataType I32 = {kDLInt, 32, 1};
static const DLDataType F64 = {kDLFloat, 64, 1};
static const DLDataType F32 = {kDLFloat, 32, 1};

/* Print why the last call on this thread failed. */
static int failed(void)
{
    ovspatialquery_string_t error = ovspatialquery_get_last_error();
    fprintf(stderr, "failed: %.*s\n", (int)error.length, error.ptr);
    return 0;
}

static int ok(ovspatialquery_result_t result)
{
    return result.status == OVSPATIALQUERY_API_SUCCESS || failed();
}

/* Wait for asynchronous work, then release its operation ID. */
static int finish(ovspatialquery_instance_handle_t instance,
                  ovspatialquery_enqueue_result_t admitted)
{
    if (admitted.status != OVSPATIALQUERY_API_SUCCESS)
        return failed();
    ovspatialquery_op_wait_result_t waited = {0};
    if (!ok(ovspatialquery_wait_op(instance, admitted.op_id,
                                   OVSPATIALQUERY_TIMEOUT_INFINITE, &waited)))
        return 0;
    if (waited.state != OVSPATIALQUERY_OP_COMPLETED)
    {
        ovspatialquery_string_t error =
            ovspatialquery_get_last_op_error(instance, admitted.op_id);
        fprintf(stderr, "operation failed: %.*s\n", (int)error.length, error.ptr);
        ovspatialquery_destroy_op(instance, &admitted.op_id);
        return 0;
    }
    return ok(ovspatialquery_destroy_op(instance, &admitted.op_id));
}

int main(void)
{
    /* 1. One instance holds the budgets for everything created through it. */
    ovspatialquery_instance_desc_t desc = {
        .operation_capacity = 8,
        .max_cpu_concurrency = 2,
        .host_byte_budget = UINT64_C(64) << 20,
    };
    ovspatialquery_instance_handle_t instance = OVSPATIALQUERY_INVALID_INSTANCE;
    if (!ok(ovspatialquery_create_instance(&desc, &instance)))
        return 1;

    /* 2. Register definition 1: a box with half extents 0.5. */
    uint64_t definition = 1;
    double half_extent[3] = {0.5, 0.5, 0.5};

    ovspatialquery_input_array_t ids = input(&definition, U64, &SCALAR);
    ovspatialquery_input_array_t extents = input(half_extent, F64, &VEC3);
    const ovspatialquery_box_definition_table_t boxes = {&ids, &extents};
    if (!finish(instance, ovspatialquery_enqueue_box_registration(instance, &boxes)))
        return 1;

    /* 3. Place object 10 at x = 4 and publish it as ordinal 1. */
    const ovspatialquery_population_desc_t population_desc = {
        .retained_ordinal_capacity = 2,
    };
    ovspatialquery_population_handle_t population = OVSPATIALQUERY_INVALID_POPULATION;
    if (!ok(ovspatialquery_create_explicit_population(instance, &population_desc,
                                                      &population)))
        return 1;

    uint64_t object = 10;
    int32_t type = OVSPATIALQUERY_GEOMETRY_BOX;
    double translation[3] = {4.0, 0.0, 0.0};
    float rotation[4] = {0.0f, 0.0f, 0.0f, 1.0f}; /* x, y, z, w */

    ovspatialquery_input_array_t objects = input(&object, U64, &SCALAR);
    ovspatialquery_input_array_t types = input(&type, I32, &SCALAR);
    ovspatialquery_input_array_t geometries = input(&definition, U64, &SCALAR);
    ovspatialquery_input_array_t translations = input(translation, F64, &VEC3);
    ovspatialquery_input_array_t rotations = input(rotation, F32, &VEC4);
    const ovspatialquery_explicit_population_set_t set = {
        .target_ordinal = 1,
        .instances = {&objects, &types, &geometries, &translations, &rotations},
    };
    if (!finish(instance, ovspatialquery_enqueue_explicit_population_set(
                              instance, population, &set)))
        return 1;

    /* 4. Cast a ray along +x at the head, asking for the exact surface. */
    ovspatialquery_raycast_desc_t ray = {
        .common.target.target.kind = OVSPATIALQUERY_TARGET_POPULATION,
        .common.target.target.handle.population = population,
        .common.target.ordinal.kind = OVSPATIALQUERY_ORDINAL_HEAD,
        .common.precision = OVSPATIALQUERY_QUERY_EXACT,
        .ray.unit_direction = {1.0f, 0.0f, 0.0f},
        .ray.max_distance = 20.0,
    };
    ovspatialquery_raycast_single_result_t found = {0};
    if (!ok(ovspatialquery_raycast_closest_sync(instance, &ray, &found)))
        return 1;

    if (found.has_hit && found.hit.truth == OVSPATIALQUERY_HIT_EXACT_SURFACE)
    {
        const ovspatialquery_raycast_exact_hit_t* hit = &found.hit.data.exact;
        printf("ray hit %llu at distance %.3f, ordinal %lld\n",
               (unsigned long long)hit->identity.object_id.value, hit->distance,
               (long long)found.source_ordinal);
    }

    /* 5. Destroy in reverse order; each call returns BUSY while something still
     * uses the object. */
    const ovspatialquery_geometry_ref_t box = {OVSPATIALQUERY_GEOMETRY_BOX, 1};
    ovspatialquery_destroy_population(instance, population);
    ovspatialquery_destroy_geometry_definition(instance, box);
    ovspatialquery_destroy_instance(instance);
    return 0;
}

It prints this output:

Output#
ray hit 10 at distance 3.500, ordinal 1

Notice the following about this program:

  1. Every call returns a status, and ovspatialquery_get_last_error() explains the last failure on the calling thread. The program’s ok() prints it.

  2. The instance is the same object as Python’s Instance. It owns everything created through it, within the operation capacity and byte budgets it is created with.

  3. Every input column is a DLPack tensor. Here each one is copied when the call is admitted, so the arrays can live on the stack.

  4. Asynchronous calls return an operation ID. The program waits for each operation and then destroys it, which frees the instance’s slot for the next one.

Next Steps#

To continue, read these pages:

  • Concepts explains populations, versions, views, and results.

  • Batches explains how to run many rays per call on the CPU or on a CUDA device.