Skip to content

Ray Tracing

Ray generation and voxel traversal for the carving pipeline, in two modules. The main kernels use a DDA (Digital Differential Analyzer) that steps each ray through the voxel grid and adds to a per-voxel volume in a single pass.

ray_tracing.py builds and traces the rays:

  • trace_and_score_dda: traces a batch of rays and adds each ray's weight to every voxel it crosses (weighted modes). Runs on CUDA or on Warp's CPU backend.
  • trace_and_count_dda: the same traversal, adding a count of 1 per ray (time-based and tilted_plane).
  • trace_point_access_dda: stops each ray at the first occupied voxel and adds its weight to its test point's accessible or blocked weight (test_point_access_evaluation).
  • follow_mass_behind_skin_dda: the skin rule, which keeps a test surface's skin voxels with the mass behind them.
  • generate_sky_patch_rays / generate_sun_rays: expand sample points × directions into flat ray arrays (origins + directions), keeping only directions the surface faces.
  • auto_batch_size: picks a ray batch size from the free GPU memory, to avoid out-of-memory errors on large scenes.

warp_kernels.py sets up Warp and holds every Warp kernel of the package (the DDA kernels above and the parity voxelizer that voxelization.voxelize_solid_warp launches), so Warp compiles and caches them as one module:

  • dda_backend_available: whether the Warp DDA backend can run on a device.
  • require_dda_backend: raises WarpBackendUnavailableError, naming the reason, when it cannot. Ray tracing has no other backend; every carver calls this first.
  • warmup_kernels: precompiles the Warp kernels (urbansolarcarver warmup).

Rays are processed in batches. With ray_batch_size: 0 (the default) the batch size comes from auto_batch_size; set a positive value to fix it.

urbansolarcarver.ray_tracing

UrbanSolarCarver: ray generation and voxel grid traversal

This module builds rays (sample point to sky patch, or sample point to sun, keeping only directions the surface faces) and traces them through the voxel grid for the carving pipeline.

Rays are traced with the DDA (digital differential analyzer, Amanatides & Woo 1987) Warp kernels of :mod:warp_kernels, launched here, on CUDA or on Warp's CPU backend. The fused wrappers (:func:trace_and_score_dda, :func:trace_and_count_dda) add each ray's weight or a count of 1 directly into a per-voxel volume, so no list of hits is stored; :func:trace_point_access_dda adds each ray's weight to its test point when it reaches no occupied voxel. :func:mesh_blocks_rays tests rays against the context and terrain meshes (a Warp BVH) instead of the grid. In the sky-patch modes the wrappers can take a :class:SkySubRays: each ray then stands for several jittered sub-rays over its patch, whose directions the kernels compute, so the sub-rays are never stored (:func:mesh_blocks_sky_sub_rays is their context test). There is no other tracer: when Warp cannot run, the carvers raise WarpBackendUnavailableError (see :func:warp_kernels.require_dda_backend).

The coordinate conventions are those of :mod:warp_kernels.

SkySubRays

Bases: NamedTuple

How the kernels split each sky-patch ray into jittered sub-rays.

Ray r becomes the side**2 threads r * side**2 + k, each tracing the direction :func:sky_patches.sub_ray_directions gives and carrying 1 / side**2 of the patch weight; the sub-rays the surface does not face are skipped. Pass None instead to trace each ray's own direction (the patch centre).

SkySubRayBlocking

Bases: NamedTuple

What the context and terrain block of the sky sub-rays (:func:mesh_blocks_sky_sub_rays).

trace_and_score_dda(min_corner, scale, resolution, origins, ray_dirs, patch_ids, patch_weights, scores, ray_length, point_ids=None, point_weights=None, surface_normals=None, occupancy=None, sub_rays=None, skip=None, incidence=False)

Trace rays with the Warp DDA kernel and add each ray's weight to every voxel it visits, directly into scores.

Runs on CUDA or the Warp CPU backend. On CPU, do not let parallel calls write into the same scores tensor (see the note above _DDAState).

Parameters:

Name Type Description Default
min_corner tuple of float

World-space (x, y, z) of the grid's lower corner.

required
scale float

Edge length of the cubic grid in meters.

required
resolution int

Voxels per axis.

required
origins (Tensor, shape(R, 3))

Ray start points and unit directions.

required
ray_dirs (Tensor, shape(R, 3))

Ray start points and unit directions.

required
patch_ids (Tensor, shape(R))

Sky patch index per ray.

required
patch_weights (Tensor, shape(P))

Weight per sky patch.

required
scores (Tensor, shape(resolution ** 3))

Flat contiguous float32 score volume, modified in place.

required
ray_length float

Maximum distance traced along each ray, in meters (directions must be unit length for this to be a distance).

required
point_ids (Tensor, shape(R))

Sample-point index per ray; required by point_weights and surface_normals.

None
point_weights (Tensor, shape(num_points))

Weight per sample point in [0, 1] (per-ray weight = patch_weight × point_weight; edge_taper design constraint).

None
surface_normals (Tensor, shape(num_points, 3))

Normal of each ray's source surface. When given, only voxels that lie entirely in front of that surface are scored; voxels behind it or crossed by its plane (the surface's own mass and skin) are not.

None
occupancy (Tensor, shape(resolution ** 3) or (res, res, res))

Max volume occupancy (nonzero = occupied); requires surface_normals. When given, a voxel crossed by the source surface's plane is scored too if the voxel behind it (see :func:follow_mass_behind_skin_dda) is empty or outside the grid: the surface's building is then not part of the max volume, so the voxel is not its skin.

None
sub_rays SkySubRays

Trace sub_rays.count jittered sub-rays per ray instead of its direction, each with that share of the patch weight; requires surface_normals. None (default) traces ray_dirs.

None
skip Tensor

uint8, one entry per traced ray (R, or R * sub_rays.count): rays whose entry is nonzero are not traced (the context blocks them).

None
incidence bool

Multiply each ray's weight by cos θ, the cosine between its traced direction (the sub-ray's, with sub_rays) and its source surface's normal; requires surface_normals.

False

Raises:

Type Description
ValueError

If scores is not a contiguous float32 tensor (Warp would then write into a copy), if point_ids is given with neither point_weights nor surface_normals, or if either of those is given without point_ids, or if occupancy is given without surface_normals, or sub_rays or incidence without surface_normals, or skip of another length.

trace_point_access_dda(min_corner, scale, resolution, origins, ray_dirs, patch_ids, patch_weights, access, ray_length, occupancy, point_ids, point_weights=None, surface_normals=None, skin_occupancy=None, sub_rays=None, incidence=False)

Trace rays until the first occupied voxel and add each ray's weight to its sample point's accessible or blocked weight in access.

The grid and ray arguments are those of :func:trace_and_score_dda, including the note on parallel CPU calls; voxels count under the same front-face and skin rules.

Parameters:

Name Type Description Default
access (Tensor, shape(2 * num_points))

Flat contiguous float64, modified in place: the accessible weight of each sample point, then the blocked weight of each.

required
occupancy (Tensor, shape(resolution ** 3) or (res, res, res))

The occupancy grid to evaluate (nonzero = occupied).

required
point_ids (Tensor, shape(R))

Sample-point index per ray, below access.numel() // 2.

required
skin_occupancy Tensor

The max volume the skin rule reads (whether a skin voxel has mass behind it), as in scoring; default occupancy. Pass the max volume when occupancy is a carved envelope.

None
sub_rays SkySubRays

As in :func:trace_and_score_dda: a sub-ray the surface does not face counts as neither accessible nor blocked.

None
incidence bool

As in :func:trace_and_score_dda.

False

Raises:

Type Description
ValueError

If access is not a contiguous float64 tensor of even length, or incidence is given without surface_normals.

trace_and_count_dda(min_corner, scale, resolution, origins, ray_dirs, counts, ray_length, point_ids=None, surface_normals=None, occupancy=None)

Trace rays with the Warp DDA kernel and add 1 to counts for every voxel each ray visits, in place.

The grid and ray arguments are the same as in :func:trace_and_score_dda, including the note on parallel CPU calls.

Parameters:

Name Type Description Default
counts (Tensor, shape(resolution ** 3))

Flat contiguous int32 hit-count volume, modified in place.

required
point_ids optional

Per-ray sample-point index and per-point surface normal; when both are given, voxels behind the ray's source surface are not counted. point_ids alone is accepted and ignored.

None
surface_normals optional

Per-ray sample-point index and per-point surface normal; when both are given, voxels behind the ray's source surface are not counted. point_ids alone is accepted and ignored.

None
occupancy Tensor

Max volume occupancy; skin voxels with nothing behind them are counted, as in :func:trace_and_score_dda.

None

Raises:

Type Description
ValueError

If counts is not a contiguous int32 tensor, or surface_normals is given without point_ids, or occupancy without surface_normals.

follow_mass_behind_skin_dda(min_corner, scale, resolution, origins, ray_dirs, point_ids, surface_normals, occupancy, values, ray_length, patch_ids=None, sub_rays=None, skip=None)

Return values with every own-skin voxel raised to the value of the voxel behind it.

A voxel the source surface's plane passes through is that surface's skin. When the skin voxel and the voxel behind it are both occupied, the skin belongs to the mass behind the surface: its own rays do not count it, but it must not outlast that mass. So each skin voxel a ray visits takes the maximum of its value and the value of the voxel behind it (counts: removed when the mass behind is removed; scores: never below the mass behind).

The voxel behind a skin voxel is found by stepping from the skin voxel's centre one cell length at a time against the surface normal, up to three steps, until the voxel containing the stepped point lies wholly behind the plane.

Parameters:

Name Type Description Default
min_corner Tuple[float, float, float]

As in :func:trace_and_count_dda; pass the same rays.

required
scale Tuple[float, float, float]

As in :func:trace_and_count_dda; pass the same rays.

required
resolution Tuple[float, float, float]

As in :func:trace_and_count_dda; pass the same rays.

required
origins Tuple[float, float, float]

As in :func:trace_and_count_dda; pass the same rays.

required
ray_dirs Tuple[float, float, float]

As in :func:trace_and_count_dda; pass the same rays.

required
ray_length Tuple[float, float, float]

As in :func:trace_and_count_dda; pass the same rays.

required
point_ids (Tensor, shape(R))

Sample-point index per ray.

required
surface_normals (Tensor, shape(num_points, 3))

Unit normal of each sample point's surface.

required
occupancy Tensor

Max volume occupancy, resolution**3 voxels (nonzero = occupied).

required
values (Tensor, shape(resolution ** 3))

Finished int32 counts or float32 scores; not modified.

required
patch_ids optional

As in :func:trace_and_score_dda; pass the ones the scores were traced with. patch_ids is required with sub_rays.

None
sub_rays optional

As in :func:trace_and_score_dda; pass the ones the scores were traced with. patch_ids is required with sub_rays.

None
skip optional

As in :func:trace_and_score_dda; pass the ones the scores were traced with. patch_ids is required with sub_rays.

None

Returns:

Type Description
Tensor

A new flat tensor like values.

Raises:

Type Description
ValueError

If values is not int32 or float32.

mesh_blocks_rays(blocking, origins, directions, point_ids, surface_normals, max_t, origin_offset=0.01, min_hit=0.001)

Which rays hit the context or terrain mesh within max_t.

Parameters:

Name Type Description Default
blocking BlockingMesh

The context and terrain meshes, in the frame of origins.

required
origins (Tensor, shape(R, 3))

Ray start points (the test points) and unit directions.

required
directions (Tensor, shape(R, 3))

Ray start points (the test points) and unit directions.

required
point_ids (Tensor, shape(R))

Test point of each ray, an index into surface_normals.

required
surface_normals (Tensor, shape(P, 3))

Outward unit normal of each test point. Each ray starts origin_offset off its test surface along it, and hits closer than min_hit are ignored, so a test surface lying on a context face (a neighbour's facade) is not blocked by that face.

required

Returns:

Type Description
Tensor

(R,) bool on the device of origins, True where the ray is blocked.

mesh_blocks_sky_sub_rays(blocking, origins, patch_ids, point_ids, surface_normals, sub_rays, patch_weights, max_t, point_weights=None, origin_offset=0.01, min_hit=0.001, incidence=False)

:func:mesh_blocks_rays for the sky sub-rays of sub_rays.

Each ray of origins, patch_ids and point_ids stands for sub_rays.count sub-rays, tested one thread each in launches of about 16 million. Returns each sub-ray's status and, per test point, how many sub-rays it faces and their weight (patch_weights[patch] / count, times point_weights when given, times cos θ to the point's normal with incidence), and how much of that the mesh blocks.

sky_sub_ray_directions(point_ids, patch_ids, sub_rays)

The (R * count, 3) float32 sub-ray directions the kernels trace for these rays, on their device.

The same directions as :func:sky_patches.sub_ray_directions, computed by the kernels' own function (float32). Includes the sub-rays the surface does not face.

generate_sky_patch_rays(pts, norms, patch_dirs, device, facing_margin=0.0)

One ray per (sample point, sky patch) pair whose patch the surface faces.

A ray is kept only where dot(normal, patch direction) > -facing_margin: with the default 0, where the surface faces the patch centre; with sky sub-rays, :func:sky_patches.patch_facing_margin keeps every patch the surface faces in part.

The rays are ordered by patch, then by sample point, so the threads that run together trace one direction from neighbouring points and visit nearby voxels; on the GPU this keeps the voxel arrays in the cache (on the District example, tracing took a quarter of the time it took with the rays ordered by point).

Parameters:

Name Type Description Default
pts ndarray(P, 3)

Sample points and their outward unit normals.

required
norms ndarray(P, 3)

Sample points and their outward unit normals.

required
patch_dirs Tensor(V, 3)

Unit directions of the sky patches.

required
device device

Device for the returned tensors.

required
facing_margin float

See above; 0 or more.

0.0

Returns:

Name Type Description
origins (R, 3) ray start points (the sample points)
ray_dirs (R, 3) unit ray directions
patch_ids (R,) sky patch index of each ray
point_idx (R,) sample point index of each ray

generate_sun_rays(points_3d, point_normals, sun_directions, device, return_point_idx=False)

Build one ray per (sample point, sun direction) pair that the surface faces, i.e. where dot(normal, sun direction) > 0.

Args: points_3d: (P,3) NumPy array of sample points on the surface. point_normals:(P,3) NumPy array of normals at each sample point. sun_directions:(S,3) NumPy array of unit vectors pointing toward the sun. They are used as ray directions unchanged, so they must be unit length for ray_length to be a distance. device: Torch device for the returned tensors. return_point_idx: also return the source sample-point index per ray.

Returns: ray_origins: (R,3) float32 tensor of ray start points. ray_directions:(R,3) float32 tensor of ray direction vectors. point_idx: (R,) int64 source sample-point index per ray, only when return_point_idx is True.

Raises: ValueError: if the arrays are not (N,3) or the normals do not match the points.

auto_batch_size(device, *, vram_fraction=0.6, fallback=300000)

Choose a ray batch size from the free GPU memory.

The budget is vram_fraction of free VRAM (video memory). The fused DDA kernels accumulate into the voxel grid and keep no hit lists, so a batch only adds its slice of the ray inputs: 96 bytes per ray (see the comment in the code). The result is at least 10,000 and at most 5,000,000 rays.

Returns fallback on CPU or if VRAM cannot be queried.

Parameters:

Name Type Description Default
device device

Target compute device.

required
vram_fraction float

Fraction of free VRAM to budget for ray tracing (default 0.6).

0.6
fallback int

Batch size when VRAM cannot be queried (default 300K).

300000

Returns:

Type Description
int

Recommended ray batch size.

urbansolarcarver.warp_kernels

UrbanSolarCarver: Warp setup and kernels

Initializes NVIDIA Warp, tells whether its exact DDA backend can run on a device (:func:dda_backend_available), precompiles the kernels (:func:warmup_kernels), and defines every Warp kernel of the package:

  • the DDA traversal (digital differential analyzer, Amanatides & Woo 1987): one thread per ray, stepping from voxel to voxel and visiting every voxel the ray crosses exactly once, with fused kernels that add each ray's weight or a count of 1 directly into a per-voxel volume, the first-hit kernel of the test point access evaluation and the kernel of the skin rule; in the sky-patch modes a thread can trace one of several jittered sub-rays of a sky patch, whose direction it computes itself (see the note above _lowbias32);
  • the parity voxelizer used by :func:voxelization.voxelize_solid_warp;
  • the ground heights of a terrain mesh and the voxel centres on the context's surface, used by :mod:context_geometry, and the any-hit test of rays against the context and terrain meshes (:func:ray_tracing.mesh_blocks_rays);
  • the mesh visibility kernel of the sun and sky check (:mod:solar_check), which traces rays against a triangle mesh's BVH (wp.Mesh) instead of the voxel grid, and its test of which points lie inside a mesh.

All kernels live in this one module on purpose: Warp compiles a Python module as one unit and caches it on disk by module, so :func:warmup_kernels compiles them all at once. The kernels exist only when Warp imports and initializes (_warp_available). Their launch wrappers are in :mod:ray_tracing, :mod:voxelization and :mod:solar_check.

References

Amanatides, J. & Woo, A. (1987). "A Fast Voxel Traversal Algorithm for Ray Tracing." Eurographics '87, pp. 3-10.

Coordinate conventions
  • World to grid: grid_idx = floor((world_pt - origin) / cell_size)
  • Cell size: cell_size = scale / resolution (meters per voxel)
  • Flat index: x * resolution**2 + y * resolution + z (row-major, C order)
  • floor maps a point to the voxel that contains it; rounding would shift every index by half a voxel.

warmup_kernels(device=None)

Compile (or load from the on-disk cache) this module's Warp kernels for device now instead of on first use.

Warp compiles all kernels in a module on the first launch. This costs roughly 3-10 s once per machine, device and code version; afterwards the compiled binaries load from Warp's disk cache in milliseconds. Calling this during installation (setup_env.py), at daemon startup, or via usc warmup moves that cost to a moment where the user already expects to wait, so the first carving run is not slowed by it.

Parameters:

Name Type Description Default
device device | str | None

Target device. None resolves like cfg.device='auto': CUDA when available, else the Warp CPU backend.

None

Returns:

Type Description
bool

True if the kernels are ready on the device (compiled or cached); False if Warp is unavailable or compilation failed. When only the precompilation failed, the kernels compile on first use instead.

dda_backend_available(device)

True if the Warp DDA backend can run on device: Warp initialised and, for the CPU, Warp's CPU backend can compile kernels.

require_dda_backend(device)

Raise WarpBackendUnavailableError unless the Warp DDA backend can run on device. Ray tracing has no other backend; the error says why Warp cannot run and how to repair the installation.

mesh_visible_weight_kernel(mesh_id, has_mesh, mesh_tolerance, clip_id, has_clip, clip_tolerance, blocking_id, has_blocking, blocking_tolerance, points, normals, directions, values, use_cosine, sub_side, patch_cells, patch_ids, d_start, d_end, origin_offset, min_hit, max_t, out)

Add the value of every direction in [d_start, d_end) that a test point faces and sees past the mesh and the blocking meshes.

One thread per test point. With sub_side > 1, direction k is sub-ray k % sub_side**2 of patch patch_ids[k], drawn for test point i as the carving draws it (_sky_sub_ray_direction, see the note above _lowbias32). A ray is blocked where it is inside the mesh's solid and, with a clip solid, inside the clip solid too: the mesh then counts only where it overlaps the clip (a carved envelope that bulges past the maximum volume blocks nothing outside it). The blocking meshes block wherever the ray meets them. Inside and outside follow the faces' orientation (closed meshes with outward normals); a start inside is judged by :func:_check_start, with each mesh's own tolerance.

points_inside_mesh_kernel(mesh_id, points, max_distance, inside)

Whether each point lies inside a mesh's solid, by the generalised winding number (above one half inside). A probe ray would meet the faces where two bodies touch (the floors of a massing, stacked on each other, or its bays side by side) at the same distance and take either; the winding number counts every face, so touching bodies each count once, and small gaps in a mesh that is not quite closed are bridged.