hapi_rs/lib.rs
1#![doc(html_logo_url = "https://media.sidefx.com/uploads/products/engine/engine_orange.svg")]
2#![allow(clippy::cast_sign_loss, clippy::missing_errors_doc)]
3//! # Rust bindings to Houdini Engine C API.
4//!
5//! Official HAPI [documentation](https://www.sidefx.com/docs/hengine/) is bundled under
6//! `engine_docs/www.sidefx.com/docs/hengine/` for offline reference.
7//!
8//! Check out the [examples](https://github.com/alexxbb/hapi-rs/tree/main/lib/examples):
9//!
10//! `cargo run --example ...`
11//!
12//! ## Building and running
13//!
14//! **HFS** environment variable must be set for the build script to link to Houdini libraries.
15//!
16//! For runtime discovery of Houdini libraries there are several options:
17//!
18//! ### Mac & Linux
19//!
20//! **Option 1**
21//!
22//! Build with RPATH via the `RUSTFLAGS` variable:
23//! ```bash
24//! RUSTFLAGS="-C link-args=-Wl,-rpath,/path/to/hfs/dsolib" cargo build
25//! ```
26//! **Option 2**
27//!
28//! Add a cargo config file to your project: `.cargo/config`
29//!```text
30//! [target.'cfg(target_os = "linux")']
31//! rustflags = ["-C", "link-arg=-Wl,-rpath=/opt/hfs/21.0.440/dsolib"]
32//! [target.x86_64-apple-darwin]
33//! rustflags = ["-C",
34//! "link-arg=-Wl,-rpath,/Applications/Houdini/Current/Frameworks/Houdini.framework/Versions/Current/Libraries",
35//! ]
36//!```
37//! **Option 3**
38//!
39//! At runtime via env variables: `$LD_LIBRARY_PATH` on Linux and `$DYLD_LIBRARY_PATH` on macOS.
40//!
41//! ### Windows
42//! `$HFS` must be set for building.
43//! Runtime Houdini libraries have to be in `$PATH`, e.g. add `$HFS/bin`.
44//!
45//! ## Architectural overview
46//! `hapi-rs` mirrors the Houdini Engine C API (HAPI) while providing more idiomatic Rust ergonomics:
47//! - Every `HAPI_*` struct becomes a dedicated Rust wrapper with `get_*`, `set_*`, and `with_*` helpers
48//! (for example `HAPI_NodeInfo` -> [`node::NodeInfo`], `HAPI_GeoInfo` -> [`geometry::GeoInfo`]).
49//! - Enums drop the `HAPI_` prefix and use concise variant names while preserving the C ordering so that
50//! official documentation can be cross-referenced easily.
51//! - Most structs implement [`Default`] and expose builder-like methods to keep initialization readable.
52//! - String conversions are centralized in [`stringhandle`] to hide `HAPI_StringHandle` management and to
53//! provide iterators that either keep data as `CString` or eagerly convert to `String` when needed.
54//! - [`asset`], [`session`], [`node`], [`geometry`], [`attribute`], [`parameter`], [`material`], [`volume`],
55//! and [`pdg`] modules roughly follow the sections from the Houdini Engine manual so that the mental model
56//! stays close to the C API.
57//! - Raw HAPI symbols remain accessible through [`raw`], the bindgen-generated module re-exported for
58//! advanced integrations when you need to drop straight to the C API.
59//!
60//! ## Sessions and servers
61//! The [`session::Session`] type encapsulates a live connection to Houdini Engine. Internally it stores an
62//! `Arc<SessionInner>` so cloning a session is cheap and the connection stays alive until the last clone is
63//! dropped. Houdini guarantees that a single session handle can be used concurrently; consequently the Rust
64//! wrapper is [`Send`] + [`Sync`] and only falls back to a private [`parking_lot::ReentrantMutex`] when HAPI
65//! needs serialized calls. Dropping the last clone closes the session. Optional HAPI scene cleanup is disabled
66//! by default and can be enabled with [`session::SessionOptions::cleanup`] when orderly Houdini-side teardown
67//! is required. A server started by the crate is then reaped when
68//! `auto_close` is enabled; borrowed servers and servers configured with `auto_close = false` remain owned
69//! by their caller.
70//!
71//! [`session::simple_session`] bootstraps a Thrift shared-memory server via [`session::new_thrift_session`]
72//! and [`server::ServerOptions::shared_memory_with_defaults`]. You can override transports, buffer sizes,
73//! environment variables, or timeouts with [`server::ServerOptions`]—see `lib/examples/setup_server.rs` for
74//! an advanced configuration.
75//!
76//! License preference can be set with [`server::ServerOptions::with_license_preference`].
77//!
78//! Sessions expose helpers that map closely to the HAPI entry points:
79//! - [`session::Session::load_asset_file`] returns an [`asset::AssetLibrary`] so you can instantiate HDAs.
80//! - [`session::Session::create_node`], [`session::Session::node_builder`], and
81//! [`session::Session::create_input_node`] for editable geometry inputs.
82//! - [`session::Session::set_server_var`] / [`session::Session::get_server_var`] variable APIs.
83//! - [`session::Session::cook`] reports [`session::CookResult`] when you run in threaded mode.
84//!
85//! ```no_run
86//! use hapi_rs::session::simple_session;
87//! use std::path::PathBuf;
88//!
89//! fn main() -> hapi_rs::Result<()> {
90//! let session = simple_session().unwrap();
91//! assert!(session.is_valid());
92//! let hda = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../otls/hapi_geo.hda");
93//! let library = session.load_asset_file(&hda)?;
94//! let node = library.try_create_first()?;
95//! node.cook_blocking()?;
96//! Ok(())
97//! }
98//! ```
99//!
100//! ## `HoudiniNode` and node APIs
101//! HAPI node ids become [`node::NodeHandle`], a lightweight wrapper that you often receive when traversing
102//! networks. Call [`node::NodeHandle::to_node`] to promote the handle into a [`node::HoudiniNode`], which
103//! stores the handle, [`node::NodeInfo`], and the owning [`session::Session`]. `HoudiniNode` is also
104//! [`Clone`] + [`Send`] + [`Sync`] so you can keep references across threads or store them inside higher
105//! level abstractions such as [`geometry::Geometry`] or [`pdg::TopNode`].
106//!
107//! Nodes expose the most commonly used HAPI functionality:
108//! - [`node::HoudiniNode::cook_blocking`] / [`node::HoudiniNode::cook_with_options`] forward to
109//! `HAPI_CookNode` and integrate with [`session::Session::cook`] for threaded servers.
110//! - [`node::HoudiniNode::geometry`] returns a [`geometry::Geometry`] for SOP nodes or follows the display flag
111//! when called on OBJ nodes.
112//! - [`node::HoudiniNode::parameters`] retrieves strongly-typed [`parameter::Parameter`] values.
113//! - Networking helpers such as [`node::HoudiniNode::get_children_by_type`] or [`node::ManagerNode`] mirror
114//! the C API utilities.
115//! - File IO helpers ([`node::HoudiniNode::save_to_file`], [`node::HoudiniNode::load_from_file`]) keep the
116//! naming/parsing identical to HAPI.
117//!
118//! For complete node-network demos see `lib/examples/node_networks.rs` (wiring SOPs), `lib/examples/node_errors.rs`
119//! (reading cook errors), and `lib/examples/live_session.rs` (re-using an existing Houdini session).
120//!
121//! ## Geometry workflow
122//! [`geometry::Geometry`] represents SOP outputs and wraps [`geometry::GeoInfo`] so you get immediate access to
123//! element counts, part metadata, group names, or material assignments. When you create a node from
124//! `../otls/hapi_geo.hda`, [`node::HoudiniNode::geometry`] either returns the SOP node directly or finds the
125//! display child for OBJ nodes. [`session::Session::create_input_node`] and
126//! [`session::Session::create_input_curve_node`] expose editable SOP nodes if you want to push points back
127//! into Houdini.
128//!
129//! Each geometry is composed of [`geometry::PartInfo`] entries (points, meshes, curves, packed primitives, …).
130//! Use [`geometry::Geometry::partitions`] or [`geometry::Geometry::part_info`] to explore them, then rely on
131//! helpers such as [`geometry::Geometry::get_materials`] to inspect [`geometry::Materials`]. Materials can be
132//! promoted to [`material::Material`] for texture extraction—`lib/examples/materials.rs` shows how to render
133//! maps from `../otls/sesi/SideFX_spaceship.hda`.
134//!
135//! The curve and group APIs map directly to HAPI (`get_curve_counts`, `get_group_names`, etc.); see
136//! `lib/examples/object_geos_parts.rs` and `lib/examples/curve_output.rs` for in-depth geometry traversals.
137//!
138//! ```no_run
139//! use hapi_rs::{
140//! geometry::PartType,
141//! session::simple_session,
142//! };
143//! use std::path::PathBuf;
144//!
145//! fn main() -> hapi_rs::Result<()> {
146//! let session = simple_session().unwrap();
147//! let hda = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../otls/hapi_geo.hda");
148//! let library = session.load_asset_file(&hda)?;
149//! let node = library.try_create_first()?;
150//! node.cook_blocking()?;
151//! let geometry = node.geometry()?.expect("SOP geometry");
152//! let mesh = geometry
153//! .partitions()?
154//! .into_iter()
155//! .find(|part| part.part_type() == PartType::Mesh)
156//! .expect("mesh part");
157//! assert!(mesh.point_count() > 0);
158//! Ok(())
159//! }
160//! ```
161//! Some underlying C structs don't provide a direct way of creating them or they might not provide methods
162//! for modifying them, due to this crate's attempt for proper data encapsulation, minimizing noise and improving safety.
163//! Structs that you **do** need the ability to create, implement [Default] and some implement a `Builder Pattern` with convenient `with_` and `set_` methods:
164//! ```rust
165//! use hapi_rs::geometry::{PartInfo, PartType};
166//! let part_info = PartInfo::default()
167//! .with_part_type(PartType::Mesh)
168//! .with_face_count(6);
169//! ```
170//!
171//! ## Typed attribute access
172//! [`attribute::Attribute`] uses a Rust primitive and a shape marker to encode HAPI storage. For example,
173//! [`attribute::Attribute<f32, attribute::Fixed>`] is an ordinary fixed-tuple float attribute, while
174//! [`attribute::Attribute<i32, attribute::Jagged>`] is an integer array attribute. Strings and JSON dictionaries
175//! use [`attribute::StringAttribute`] and [`attribute::DictionaryAttribute`] with the same shape markers.
176//!
177//! Use [`geometry::Geometry::get_attribute`] when storage is unknown; it returns the exhaustive
178//! [`attribute::AnyAttribute`] enum. The checked numeric, string, and dictionary lookup methods return typed
179//! handles and report a storage mismatch rather than relying on downcasting. Creation follows the same model:
180//! numeric storage is derived from the Rust primitive and shape, so the `storage` field in
181//! [`geometry::AttributeInfo`] does not need to be selected by the caller.
182//!
183//! Every handle stores its node, part, owner, and name. Select the part during lookup or creation; subsequent
184//! `get` and `set` calls use that identity and transfer the complete attribute. Fixed handles also provide
185//! element-based range reads and writes. Fixed writes require exactly `count * tuple_size` values. Jagged writes
186//! use [`attribute::JaggedArrayData`], which rejects negative sizes,
187//! overflow, or a size total that differs from the flattened data length. Operations use cached metadata and do
188//! not make a hidden `GetAttributeInfo` call. Call `refresh()` or reacquire a handle after a cook that may have
189//! changed its count, tuple size, array element total, storage, or part layout.
190//!
191//! ```no_run
192//! use hapi_rs::{
193//! attribute::{Attribute, AnyAttribute, Fixed, Jagged, JaggedArrayData},
194//! geometry::{AttributeInfo, AttributeOwner, PartType},
195//! session::simple_session,
196//! };
197//! use std::path::PathBuf;
198//!
199//! fn main() -> hapi_rs::Result<()> {
200//! let session = simple_session().unwrap();
201//! let hda = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../otls/hapi_geo.hda");
202//! let library = session.load_asset_file(&hda)?;
203//! let node = library.try_create_first()?;
204//! node.cook_blocking()?;
205//! let geometry = node.geometry()?.expect("SOP geometry");
206//! let part = geometry
207//! .partitions()?
208//! .into_iter()
209//! .find(|info| info.part_type() == PartType::Mesh)
210//! .expect("mesh part");
211//! let positions = geometry
212//! .get_numeric_attribute::<f32, Fixed>(part.part_id(), AttributeOwner::Point, "P")?
213//! .expect("P attribute");
214//! let values = positions.get()?;
215//! assert!(!values.is_empty());
216//!
217//! if let Some(attribute) = geometry.get_attribute(part.part_id(), AttributeOwner::Point, "P")? {
218//! match attribute {
219//! AnyAttribute::Float(position) => assert_eq!(position.part_id(), part.part_id()),
220//! other => panic!("unexpected P storage: {:?}", other.storage()),
221//! }
222//! }
223//!
224//! let mut info = AttributeInfo::default();
225//! info.set_owner(AttributeOwner::Point);
226//! info.set_tuple_size(1);
227//! info.set_count(part.point_count());
228//! let weights = geometry.add_numeric_attribute::<f32, Fixed>("rs_weight", part.part_id(), info)?;
229//! let fill = vec![1.0f32; part.point_count() as usize];
230//! weights.set(&fill)?;
231//!
232//! let arrays = JaggedArrayData::new(vec![1_i32, 2, 3], vec![2, 1])?;
233//! assert_eq!(arrays.iter().collect::<Vec<_>>(), vec![&[1, 2][..], &[3][..]]);
234//! let _: Option<Attribute<i32, Jagged>> = geometry
235//! .get_numeric_attribute(part.part_id(), AttributeOwner::Point, "neighbors")?;
236//! Ok(())
237//! }
238//! ```
239//!
240//! With the `async-cooking` feature, import `AsyncAttributeAccess` for numeric reads and writes, or the write-only
241//! string extension traits for string and dictionary writes. String reads remain synchronous so HAPI handles can
242//! be resolved immediately. The returned `AsyncJob` owns every allocation visible to HAPI; consume it with
243//! `wait`. Dropping an active job warns and intentionally leaks only its FFI backing allocation to avoid
244//! use-after-free. The raw HAPI attribute async API is experimental and is not used by SideFX's Unity or Unreal
245//! integrations.
246//!
247//! ## Parameters and UI metadata
248//! [`parameter::Parameter`] is an enum that covers all `HAPI_ParmType` values, while
249//! [`parameter::ParmBaseTrait`] exposes shared helpers (`name`, `label`, `size`, etc.). Matching on `Parameter`
250//! gives you access to strongly typed wrappers such as [`parameter::FloatParameter`],
251//! [`parameter::IntParameter`], [`parameter::StringParameter`], or button/toggle helpers. You can inspect menu
252//! metadata, manipulate multiparms, attach expressions/animation curves, or call [`parameter::IntParameter::press_button`]
253//! for script callbacks. [`parameter::ParmInfo`] mirrors `HAPI_ParmInfo` for low-level needs.
254//!
255//! Always cook an HDA before touching its parameters so that defaults are initialized. The snippet below uses
256//! `../otls/hapi_parms.hda`, the same file leveraged by `lib/examples/parameters.rs`, and demonstrates how to
257//! branch on parameter types. For more elaborate formatting of menu values see that example; it prints a table
258//! of every parameter on the asset.
259//!
260//! ```no_run
261//! use hapi_rs::{
262//! parameter::{ParmBaseTrait, Parameter},
263//! session::simple_session,
264//! };
265//! use std::path::PathBuf;
266//!
267//! fn main() -> hapi_rs::Result<()> {
268//! let session = simple_session().unwrap();
269//! let hda = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../otls/hapi_parms.hda");
270//! let library = session.load_asset_file(&hda)?;
271//! let node = library.try_create_first()?;
272//! node.cook_blocking()?;
273//! if let Parameter::Float(color) = node.parameter("color")? {
274//! color.set_array([0.25, 0.5, 0.75])?;
275//! assert_eq!(color.size(), 3);
276//! }
277//! if let Parameter::Int(toggle) = node.parameter("toggle")? {
278//! let next = if toggle.get(0)? == 0 { 1 } else { 0 };
279//! toggle.set(0, next)?;
280//! }
281//! if let Parameter::String(path) = node.parameter("op_path")? {
282//! if let Some(target) = path.get_value_as_node()? {
283//! assert!(target.is_valid(&node.session)?);
284//! }
285//! }
286//! Ok(())
287//! }
288//! ```
289//!
290//! ## Error handling and diagnostics
291//! Every public API returns [`Result`], an alias for `std::result::Result<T, [``HapiError``]>`.
292//! `HapiError::Hapi` stores the [`errors::HapiResultCode`] plus an optional server message fetched through
293//! [`session::Session::get_status_string`]. Additional context strings accumulate automatically when you call
294//! `.context(...)` / `.with_context(...)` using the helper methods defined in the `errors` module, making it
295//! easier to track which operation failed (for example `geometry::Geometry::get_attribute` annotates the
296//! attribute name and owner).
297//!
298//! Other variants (null-byte, UTF-8, IO, internal) map directly to common Rust errors. When a cook happens in
299//! threaded mode, methods return [`session::CookResult`] so you can inspect the cook-state message even if the
300//! original call succeeded. `lib/examples/node_errors.rs` demonstrates how to read verbose cook logs and status
301//! codes, while `lib/examples/materials.rs` shows how to propagate file IO errors during texture extraction.
302//!
303//! String-heavy APIs such as parameter values or attribute names rely on [`stringhandle::StringArray`] to batch
304//! conversions and mirror `HAPI_StringHandle` semantics. Use [`session::Session::get_string`] or
305//! [`session::Session::get_string_batch`] if you need direct access, or prefer the higher-level helpers where
306//! possible.
307
308pub mod asset;
309pub mod attribute;
310pub mod geometry;
311pub mod material;
312pub mod node;
313pub mod cop;
314pub mod parameter;
315pub mod server;
316pub mod session;
317pub mod stringhandle;
318pub mod volume;
319pub mod pdg;
320mod errors;
321mod utils;
322mod ffi;
323
324pub use errors::{HapiError, HapiResult, HapiResultCode, Result};
325pub use ffi::enums;
326pub use ffi::raw;
327
328/// Houdini version this library was build upon
329#[derive(Debug)]
330pub struct HoudiniVersion {
331 pub major: u32,
332 pub minor: u32,
333 pub build: u32,
334 pub patch: u32,
335}
336
337/// Engine version this library was build upon
338#[derive(Debug)]
339pub struct EngineVersion {
340 pub major: u32,
341 pub minor: u32,
342 pub api: u32,
343}
344
345/// Houdini version this library was build upon
346pub const HOUDINI_VERSION: HoudiniVersion = HoudiniVersion {
347 major: raw::HAPI_VERSION_HOUDINI_MAJOR,
348 minor: raw::HAPI_VERSION_HOUDINI_MINOR,
349 build: raw::HAPI_VERSION_HOUDINI_BUILD,
350 patch: raw::HAPI_VERSION_HOUDINI_PATCH,
351};
352
353/// Engine version this library was build upon
354pub const ENGINE_VERSION: EngineVersion = EngineVersion {
355 major: raw::HAPI_VERSION_HOUDINI_ENGINE_MAJOR,
356 minor: raw::HAPI_VERSION_HOUDINI_ENGINE_MINOR,
357 api: raw::HAPI_VERSION_HOUDINI_ENGINE_API,
358};