Expand description
Safe Rust bindings to Embree 3.13.5, Intel’s high-performance ray-tracing kernels.
This crate is a thin unsafe FFI wrapper whose one job is to turn Embree’s
raw pointers and C callbacks into a memory-safe Rust API: callback closures
are heap-owned and reached through a lock-free per-geometry table; geometry
mutation is gated by the GeometryBuilder / Geometry typestate; and
Scene is a non-Clone unique owner of its handle (share a committed one
across threads with Arc<Scene>).
§Overview
Deviceis the entry point. From it you create aScene, a geometry builder (Device::create_geometry), or a standalone BVH (Device::create_bvh).- Configure a
GeometryBuilder(buffers, callbacks),commitit to a shareable read-onlyGeometry, attach it to aScene, and commit the scene. - Query the scene with
Scene::intersect/Scene::occluded(single rays), their4/8/16-wide packet variants, the stream APIs, orScene::point_query; find scene-vs-scene candidate pairs withScene::collide.
§Quick start
use embree3::{BufferUsage, Device, Format, GeometryKind, IntersectContext, Ray, RayHit};
let device = Device::new().unwrap();
let mut scene = device.create_scene().unwrap();
// One triangle.
let mut tri = device.create_geometry(GeometryKind::TRIANGLE).unwrap();
tri.set_new_buffer::<[f32; 3]>(BufferUsage::VERTEX, 0, Format::FLOAT3, 3 * 4, 3)
.unwrap()
.copy_from_slice(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]);
tri.set_new_buffer::<[u32; 3]>(BufferUsage::INDEX, 0, Format::UINT3, 3 * 4, 1)
.unwrap()
.copy_from_slice(&[[0, 1, 2]]);
let tri = tri.commit();
scene.attach_geometry(&tri);
scene.commit();
// Trace one ray at it.
let mut ctx = IntersectContext::coherent();
let mut rayhit = RayHit::from(Ray::segment(
[0.25, 0.25, -1.0],
[0.0, 0.0, 1.0],
0.0,
f32::INFINITY,
));
scene.intersect(&mut ctx, &mut rayhit);
assert!(rayhit.hit.is_valid());§Documentation
Rust doc can be found here. Embree documentation can be found here. See the examples/ for some example applications using the bindings.
§Intentionally unwrapped embree functions
A few embree C entry points are deliberately not exposed, because a safer or more idiomatic Rust mechanism already covers them. Reach for the alternative listed here:
| embree C function | Use instead | Why |
|---|---|---|
rtcNewSharedBuffer | GeometryBuilder::set_shared_buffer | App-owned, zero-copy data is bound through a real &'buf [u8] borrow, so the compiler enforces “the data outlives the geometry”. The C buffer object exists to share a raw pointer across bindings, which a Rust reference already does, so it adds no capability. |
rtcSetGeometryPointQueryFunction | Scene::point_query | Its callback receives no per-geometry pointer (only the scene query’s userPtr), so it cannot host a capturing closure. Branch on geomID inside the Scene::point_query closure for per-geometry logic. |
rtcGetSceneDevice | Scene::device | The scene already tracks (and hands back) its Device; the raw getter would only duplicate it. |
rtcSetDeviceProperty | (none) | Embree exposes no public writable device properties (the only settable ones are hidden internal debug integers), so a wrapper would reject every public DeviceProperty. Use Device::get_property for the read-only queries. |
rtcRetainBVH | (none) | Bvh is a non-Clone build target (the build result borrows it exclusively), so there is never a second handle to retain; rtcReleaseBVH runs once in Drop. |
rtcRetainScene | Arc<Scene> | Scene is a non-Clone unique owner of its handle (so &mut Scene stays exclusive for mutation/commit); share a committed scene with Arc<Scene>. There is never a second handle to retain, and rtcReleaseScene runs once in Drop. |
Two further functions, rtcGetGeometryUserData and rtcRetainGeometry, are
not exposed because the crate’s geometry ownership model (an internal Arc
plus a lock-free callback table) supersedes them; no user action is needed.
§Panics in callbacks
User closures registered as embree callbacks (geometry
intersect/occluded/bounds/filter/displacement, the scene progress monitor,
point queries, the BVH builder, and Scene::collide) run behind embree’s
non-unwinding extern "C" ABI. A panic that escapes such a callback
aborts the process – Rust turns an unwind that reaches a non--unwind
extern "C" boundary into an abort, so this is defined behavior, not UB.
The hot per-ray/per-primitive trampolines therefore call the closure
directly (no per-call catch_unwind landing pad). Handle recoverable errors
inside the closure (e.g. record them in captured state); do not rely on
catching a panic across a query.
Modules§
- packet
- Ray packet types and traits.
- stream
- Ray stream types in SOA layout.
- sys
- Automatically generated bindings to the Embree C API.
Structs§
- Aligned
Array - 16 bytes aligned with known size at compile time.
- Aligned
Vector - Utility for making specifically aligned vector.
- Allocator
- Per-callback-thread bump allocator over the BVH arena
(
rtcThreadLocalAlloc).!Send + !Sync: valid only on its current callback thread. - Buffer
- Handle to a buffer managed by Embree.
- Buffer
Layout - Layout of a geometry buffer binding: how embree reads the bound bytes.
Carried by every binding and reported by
Geometry::get_buffer. - Buffer
View - A read-only view into mapped buffer.
- Buffer
View Mut - A write-only view into mapped buffer.
- Build
Config - Build settings.
DefaultreproducesrtcDefaultBuildArguments. - Bvh
- A reference-counted standalone BVH (
RTCBVH). Build target forBvh::build_scoped. - BvhResult
- Result of a build, valid only inside the generative scope. Branded by
'id. - Child
Bounds - Checked accessor over embree’s
RTCBounds*array. References borrow the view (the bounds may live in callback-local storage). - Children
- Checked, view-scoped accessor over embree’s
void**child array. - Config
- Embree device configuration.
- Device
- Handle to an Embree device.
- Geometry
- The committed, shareable phase of an Embree geometry.
- Geometry
Builder - The mutable build/edit phase of an Embree geometry.
- HitN
- Hit packet of runtime size.
- HitNp
- A hit stream in SoA format.
- Instance
Geometry Builder - Typed
GeometryBuilderfor a fixed geometry kind. Build via itsDeref/DerefMuttoGeometryBuilder, thencommitto a shareableGeometry. - Interpolate
Input - The arguments for the
Geometry::interpolatefunction. - InterpolateN
Input - The arguments for the
Geometry::interpolate_nfunction. - Interpolate
Output - The output of the
Geometry::interpolateandGeometry::interpolate_nfunctions in structure of array (SOA) layout. - Intersect
Context Ext - Extended intersection context with additional ray query specific data.
- Intersect
FunctionN Args - Arguments handed to a user-geometry intersect callback registered via
GeometryBuilder::set_intersect_function. - Intersect
Lane - A single active lane of an intersect callback’s packet, yielded by
IntersectFunctionNArgs::for_each_active_lane. Its index is already known in-range and active, so the per-lane operations take no index argument. - NodePtr
- Opaque, generatively branded handle to an arena node.
Copy, pointer-sized, and not dereferenceable except throughBvhResult::resolveinside the build scope. - Occluded
FunctionN Args - Arguments handed to a user-geometry occluded callback registered via
GeometryBuilder::set_occluded_function. The occlusion analogue ofIntersectFunctionNArgs: there is no hit buffer in the packet, so on survival mark the lane occluded withset_occluded. - Occluded
Lane - A single active lane of an occluded callback’s packet, yielded by
OccludedFunctionNArgs::for_each_active_lane. Its index is already known in-range and active. - Quad
Mesh Builder - Typed
GeometryBuilderfor a fixed geometry kind. Build via itsDeref/DerefMuttoGeometryBuilder, thencommitto a shareableGeometry. - RayHitN
- Combined ray and hit packet of runtime size.
- RayHit
Np - RayN
- Ray packet of runtime size.
- RayNp
- A ray stream stored in SoA format.
- Scene
- A scene containing various geometries.
- SoAHit
Iter - SoAHit
Iter Mut - SoAHit
Ref - SoAHit
RefMut - SoARay
Iter - SoARay
Iter Mut - SoARay
Ref - SoARay
RefMut - Triangle
Mesh Builder - Typed
GeometryBuilderfor a fixed geometry kind. Build via itsDeref/DerefMuttoGeometryBuilder, thencommitto a shareableGeometry. - User
Geometry Builder - Typed
GeometryBuilderfor a fixed geometry kind. Build via itsDeref/DerefMuttoGeometryBuilder, thencommitto a shareableGeometry. - Valid
MaskN - A per-lane validity mask for the packet query methods (
intersect{4,8,16},occluded{4,8,16},point_query{4,8,16}): each lane isValidMask::Valid(-1) orValidMask::Invalid(0).Nis the packet width. - ValidityN
- Struct holding data for validity masks used in the callback function set by
GeometryBuilder::set_intersect_filter_function,GeometryBuilder::set_occluded_filter_function,GeometryBuilder::set_intersect_functionandGeometryBuilder::set_occluded_function. - ValidityN
Iter - Shared iterator over a
ValidityN’s lanes, yielding each lane’s flag. - ValidityN
Iter Mut - Mutable iterator over a
ValidityN’s lanes. Likestd::slice::IterMut, it owns the raw pointer and aPhantomData<&'b mut i32>borrow rather than theValidityN, and yields&'b mut i32tied to that borrow – so a yielded reference cannot outlive the iterator’s borrow of theValidityN(which would otherwise let safe code alias a lane). - Vertices
- Struct holding data for a set of vertices in SoA layout.
This is used as a parameter to the callback function set by
GeometryBuilder::set_displacement_function. - Vertices
Iter Mut - Mutable iterator over a geometry’s
Vertices, yielding each vertex in turn.
Enums§
- Buffer
Source - The data source bound to a geometry buffer slot.
- CbKind
- Identifies one of a geometry’s callback slots.
- Frequency
Level - Frequency level of the application.
- Isa
- Instruction Set Architecture.
- Valid
Mask - Validity mask value for rays or hits in the filter functions.
See
ValidityN.
Constants§
- INVALID_
ID - The invalid ID for Embree intersection results (e.g.
Hit::geomID,Hit::primID, etc.)
Traits§
- AsIntersect
Context - Trait for extended intersection context enabling passing of additional ray-query specific data.
- Buffer
Data - Types that may safely alias the raw bytes of an embree buffer when mapping
it as
[Self]. - BvhBuilder
- Materializes embree’s BVH topology into a caller-defined node layout.
- BvhNode
- Marker for a type that may live in the BVH arena.
- HitPacket
- Represents a packet of hits.
- RayHit
Packet - Represents a packet of ray/hit pairs.
- RayPacket
- Represents a packet of rays.
- SoAHit
- Per-lane accessors for a hit packet in structure-of-arrays (SoA) layout.
- SoARay
- Per-lane accessors for a ray packet in structure-of-arrays (SoA) layout.
- User
Data - Marker trait for types usable as callback user data: geometry callback user
data (bound via
GeometryBuilder’s_owned/_borrowedcallback setters) or point-query user data (Scene::point_query).
Functions§
- enable_
ftz_ and_ daz - Set the flush zero and denormals modes from Embrees’s perf. recommendations
<https://embree.github.io/api.html#performance-recommendations>.
Type Aliases§
- Bounds
- An axis-aligned bounding box, given by its
loweranduppercorners. Returned byScene::get_boundsand filled in by user-geometry bounds callbacks. - Buffer
Size - Non-zero integer type used to describe the size of a buffer.
- Buffer
Usage - Defines the type of slots to assign data buffers to.
- Build
Flags - Flags controlling a standalone BVH build (e.g. dynamic / refittable). See
BuildConfig. - Build
Primitive - Primitives that can be used to build a BVH.
- Build
Quality - Speed-vs-quality trade-off for a scene or BVH build (see
Scene::set_build_qualityandBuildConfig). - Collision
- A candidate colliding primitive pair reported by
Scene::collide: thegeomID/primIDof one primitive in each scene. It is a potentially-intersecting pair from a leaf pair reached during broad-phase traversal; embree does not test the bounds before reporting, so the pair’s bounds need not overlap and the callback must narrow-phase. - Curve
Flags - Per-segment flags for curve geometries (e.g. neighbor joins).
- Device
Property - A queryable, read-only device property (see
Device::get_property). - Error
- An Embree error code. Returned by fallible operations and reported through
the device error callback; see
Device::get_error. - Format
- The element format of a data buffer, e.g.
Format::FLOAT3for vertex positions orFormat::UINT3for a triangle index. - Geometry
Kind - The type of a geometry, used to determine which geometry type to create.
- Hit
- New type alias for
sys::RTCHitthat provides some convenience methods. - Hit4
- A hit packet of size 4.
- Hit8
- A hit packet of size 8.
- Hit16
- A hit packet of size 16.
- Intersect
Context - Per ray-query intersection context.
- Intersect
Context Flags - Flags on an
IntersectContextselecting the traversal mode (e.g. coherent vs incoherent ray distributions). - Linear
Bounds - Linear (motion-blur) bounds: the axis-aligned bounding box at the start
(
bounds0) and end (bounds1) of the scene’s time range. SeeScene::get_linear_bounds. - Point
Query - Object used to traverses the BVH and calls a user defined callback function for each primitive of the scene that intersects the query domain.
- Point
Query4 - A SoA packet of 4 point queries (see
Scene::point_query4). - Point
Query8 - A SoA packet of 8 point queries (see
Scene::point_query8). - Point
Query16 - A SoA packet of 16 point queries (see
Scene::point_query16). - Point
Query Context - A stack which stores the IDs and instance transformations during a BVH traversal for a point query.
- Quaternion
Decomposition - Structure that represents a quaternion decomposition of an affine transformation.
- Ray
- New type alias for
sys::RTCRaythat provides some convenience methods. - Ray4
- A ray packet of size 4.
- Ray8
- A ray packet of size 8.
- Ray16
- A ray packet of size 16.
- RayHit
- New type alias for
sys::RTCRayHitthat provides some convenience methods. - RayHit4
- A ray/hit packet of size 4.
- RayHit8
- A ray/hit packet of size 8.
- RayHit16
- A ray/hit packet of size 16.
- Scene
Flags - Scene-level flags (e.g.
DYNAMIC,ROBUST,COMPACT); seeScene::set_flags. - Subdivision
Mode - Subdivision mode for subdivision-surface geometries (how the limit surface is evaluated near boundaries and creases).