Skip to main content

ruxla_env/
dylib.rs

1//! Compiled vector environments in shared libraries, behind a C ABI.
2//!
3//! A crate of environments compiled ahead of time (with `ruxla-build`) can
4//! be built as a `cdylib` that exports them with [`export_vec_envs!`](crate::export_vec_envs); a
5//! program built separately (with another compiler or other versions of the
6//! ruxla crates, such as the Python extension) then loads the library with
7//! [`Library::open`] and steps its environments through [`LibVecEnv`]. Only
8//! the table of `extern "C"` functions of [`VTable`] crosses the boundary,
9//! checked by [`ABI_VERSION`].
10//!
11//! ```ignore
12//! // lib.rs of a crate with `crate-type = ["cdylib"]` and a build script that
13//! // calls `ruxla_build::Builder::new(dir).compile()`:
14//! ruxla_env::include_envs!();
15//! ruxla_env::export_vec_envs!();
16//! ```
17
18use std::ffi::c_void;
19use std::path::Path;
20use std::sync::{Arc, OnceLock};
21
22use serde_json::{Value, json};
23
24use crate::compiled::CompiledEnv;
25use crate::{ActionSpace, Actions, CompiledVecEnv, StepBuffers};
26
27/// The version of [`VTable`]; a library with another version is rejected.
28///
29/// Version 2 added [`VTable::step_without_final`].
30pub const ABI_VERSION: u32 = 2;
31
32/// The name of the function that a library exports: it returns the
33/// library's [`VTable`].
34pub const VTABLE_SYMBOL: &[u8] = b"ruxla_vec_env_vtable";
35
36/// The functions of a library of compiled vector environments. The
37/// environments are opaque pointers made by `create` and freed by
38/// `destroy`; strings are UTF-8 bytes with their length.
39#[repr(C)]
40#[derive(Debug)]
41pub struct VTable {
42    /// [`ABI_VERSION`] of the library.
43    pub abi_version: u32,
44    /// The number of environments (modules) in the library.
45    pub num_modules: extern "C" fn() -> usize,
46    /// The name of module `i`, with its length in `len`.
47    pub module_name: extern "C" fn(i: usize, len: *mut usize) -> *const u8,
48    /// Creates `num_envs` environments of a module and resets them, or
49    /// returns null for an unknown module.
50    pub create: unsafe extern "C" fn(
51        module: *const u8,
52        len: usize,
53        num_envs: usize,
54        seed: i64,
55    ) -> *mut c_void,
56    /// Frees environments made by `create`.
57    pub destroy: unsafe extern "C" fn(env: *mut c_void),
58    /// A JSON description of the environments (`name`, `num_actions`,
59    /// `obs_shape`, `action_space`), valid while they live.
60    pub describe: unsafe extern "C" fn(env: *const c_void, len: *mut usize) -> *const u8,
61    /// The number of environments.
62    pub num_envs: unsafe extern "C" fn(env: *const c_void) -> usize,
63    /// The number of threads that step them.
64    pub num_threads: unsafe extern "C" fn(env: *const c_void) -> usize,
65    /// Changes the number of threads.
66    pub set_num_threads: unsafe extern "C" fn(env: *mut c_void, threads: usize),
67    /// Starts new episodes (from `seed` if `has_seed`).
68    pub reset: unsafe extern "C" fn(env: *mut c_void, has_seed: bool, seed: i64),
69    /// Writes the observations (`len` floats).
70    pub obs_into: unsafe extern "C" fn(env: *const c_void, out: *mut f32, len: usize),
71    /// Steps every environment: the actions are `kind` 0 (discrete,
72    /// `i32`), 1 (multi-discrete, `i32`, `dim` per environment), or 2
73    /// (continuous, `f32`, `dim` per environment), `len` elements at
74    /// `actions`; the outputs are `num_envs` rewards and flags and
75    /// `obs_len` floats of observations and final observations.
76    pub step: unsafe extern "C" fn(
77        env: *mut c_void,
78        kind: u32,
79        actions: *const c_void,
80        len: usize,
81        dim: usize,
82        obs: *mut f32,
83        reward: *mut f32,
84        terminated: *mut bool,
85        truncated: *mut bool,
86        final_obs: *mut f32,
87        obs_len: usize,
88    ),
89    /// Writes the legal action masks (`len` flags) and returns `true`, or
90    /// returns `false` if the environment has none.
91    pub legal_action_masks:
92        unsafe extern "C" fn(env: *const c_void, out: *mut bool, len: usize) -> bool,
93    /// Steps every environment as `step` does, without the final
94    /// observations (the environments do not compute them): the outputs are
95    /// `num_envs` rewards and flags and `obs_len` floats of observations.
96    pub step_without_final: unsafe extern "C" fn(
97        env: *mut c_void,
98        kind: u32,
99        actions: *const c_void,
100        len: usize,
101        dim: usize,
102        obs: *mut f32,
103        reward: *mut f32,
104        terminated: *mut bool,
105        truncated: *mut bool,
106        obs_len: usize,
107    ),
108}
109
110/// A compiled vector environment behind a trait object, as the library
111/// side keeps it.
112pub trait DynVecEnv: Send + Sync {
113    /// The environment.
114    fn describe(&self) -> Value;
115    /// The number of environments.
116    fn num_envs(&self) -> usize;
117    /// The number of threads.
118    fn num_threads(&self) -> usize;
119    /// Changes the number of threads.
120    fn set_num_threads(&mut self, threads: usize);
121    /// Starts new episodes.
122    fn reset(&mut self, seed: Option<i64>);
123    /// Writes the observations.
124    fn obs_into(&self, out: &mut [f32]);
125    /// Steps every environment.
126    fn step_into(&mut self, actions: Actions<'_>, out: StepBuffers<'_>);
127    /// Writes the legal action masks, if any.
128    fn legal_action_masks(&self, out: &mut [bool]) -> bool;
129    /// Steps every environment without the final observations.
130    fn step_without_final(
131        &mut self,
132        actions: Actions<'_>,
133        obs: &mut [f32],
134        reward: &mut [f32],
135        terminated: &mut [bool],
136        truncated: &mut [bool],
137    );
138}
139
140impl<C> DynVecEnv for CompiledVecEnv<C>
141where
142    C: CompiledEnv,
143    C::State: Send,
144    C::Obs: Send,
145{
146    fn describe(&self) -> Value {
147        let env = self.env();
148        json!({
149            "name": env.name(),
150            "num_actions": env.num_actions(),
151            "obs_shape": env.obs_shape(),
152            "action_space": action_space_json(&env.action_space()),
153        })
154    }
155    fn num_envs(&self) -> usize {
156        CompiledVecEnv::num_envs(self)
157    }
158    fn num_threads(&self) -> usize {
159        CompiledVecEnv::num_threads(self)
160    }
161    fn set_num_threads(&mut self, threads: usize) {
162        CompiledVecEnv::set_num_threads(self, threads);
163    }
164    fn reset(&mut self, seed: Option<i64>) {
165        CompiledVecEnv::reset(self, seed);
166    }
167    fn obs_into(&self, out: &mut [f32]) {
168        CompiledVecEnv::obs_into(self, out);
169    }
170    fn step_into(&mut self, actions: Actions<'_>, out: StepBuffers<'_>) {
171        CompiledVecEnv::step_into_actions(self, actions, out);
172    }
173    fn legal_action_masks(&self, out: &mut [bool]) -> bool {
174        CompiledVecEnv::legal_action_masks_into(self, out)
175    }
176    fn step_without_final(
177        &mut self,
178        actions: Actions<'_>,
179        obs: &mut [f32],
180        reward: &mut [f32],
181        terminated: &mut [bool],
182        truncated: &mut [bool],
183    ) {
184        CompiledVecEnv::step_into_without_final(self, actions, obs, reward, terminated, truncated);
185    }
186}
187
188/// An action space as JSON (the form of the exported manifests).
189fn action_space_json(space: &ActionSpace) -> Value {
190    match space {
191        ActionSpace::Discrete(n) => json!({"kind": "discrete", "n": n}),
192        ActionSpace::MultiDiscrete(nvec) => json!({"kind": "multi_discrete", "nvec": nvec}),
193        ActionSpace::Box { low, high, shape } => {
194            json!({"kind": "box", "low": low, "high": high, "shape": shape})
195        }
196    }
197}
198
199/// The visitor of [`export_vec_envs!`](crate::export_vec_envs): makes the vector environment of a
200/// compiled environment.
201#[derive(Debug)]
202pub struct Make {
203    /// The number of environments.
204    pub num_envs: usize,
205    /// The seed.
206    pub seed: i64,
207}
208
209impl crate::compiled::Visitor for Make {
210    type Output = Box<dyn DynVecEnv>;
211    fn visit<E: CompiledEnv + Clone + 'static>(&mut self, _module: &str, env: &E) -> Self::Output {
212        Box::new(CompiledVecEnv::new(env.clone(), self.num_envs, self.seed))
213    }
214}
215
216/// The modules and the factory of a library (set by [`vtable`]).
217struct Registry {
218    modules: &'static [&'static str],
219    make: fn(&str, usize, i64) -> Option<Box<dyn DynVecEnv>>,
220}
221
222static REGISTRY: OnceLock<Registry> = OnceLock::new();
223
224/// The environments behind a handle, with their description.
225struct Handle {
226    env: Box<dyn DynVecEnv>,
227    description: String,
228}
229
230fn registry() -> &'static Registry {
231    REGISTRY
232        .get()
233        .expect("ruxla_env::dylib::vtable was not called")
234}
235
236extern "C" fn num_modules() -> usize {
237    registry().modules.len()
238}
239
240extern "C" fn module_name(i: usize, len: *mut usize) -> *const u8 {
241    let name = registry().modules.get(i).copied().unwrap_or("");
242    // SAFETY: the caller passes a valid pointer for the length (the ABI).
243    unsafe { *len = name.len() };
244    name.as_ptr()
245}
246
247unsafe extern "C" fn create(
248    module: *const u8,
249    len: usize,
250    num_envs: usize,
251    seed: i64,
252) -> *mut c_void {
253    // SAFETY: the caller passes `len` bytes at `module` (the ABI).
254    let bytes = unsafe { std::slice::from_raw_parts(module, len) };
255    let Ok(name) = std::str::from_utf8(bytes) else {
256        return std::ptr::null_mut();
257    };
258    match (registry().make)(name, num_envs, seed) {
259        Some(env) => {
260            let description = env.describe().to_string();
261            Box::into_raw(Box::new(Handle { env, description })).cast()
262        }
263        None => std::ptr::null_mut(),
264    }
265}
266
267/// The handle behind a pointer of `create`.
268///
269/// # Safety
270///
271/// `env` must come from `create` and not be destroyed.
272unsafe fn handle<'a>(env: *const c_void) -> &'a Handle {
273    // SAFETY: guaranteed by the caller.
274    unsafe { &*env.cast::<Handle>() }
275}
276
277/// The handle behind a pointer of `create`, mutably.
278///
279/// # Safety
280///
281/// `env` must come from `create`, not be destroyed, and not be used
282/// elsewhere during the call.
283unsafe fn handle_mut<'a>(env: *mut c_void) -> &'a mut Handle {
284    // SAFETY: guaranteed by the caller.
285    unsafe { &mut *env.cast::<Handle>() }
286}
287
288unsafe extern "C" fn destroy(env: *mut c_void) {
289    if !env.is_null() {
290        // SAFETY: `env` comes from `Box::into_raw` in `create` (the ABI).
291        drop(unsafe { Box::from_raw(env.cast::<Handle>()) });
292    }
293}
294
295unsafe extern "C" fn describe(env: *const c_void, len: *mut usize) -> *const u8 {
296    // SAFETY: the caller passes a live handle and a valid pointer (the ABI).
297    let h = unsafe { handle(env) };
298    // SAFETY: as above.
299    unsafe { *len = h.description.len() };
300    h.description.as_ptr()
301}
302
303unsafe extern "C" fn num_envs(env: *const c_void) -> usize {
304    // SAFETY: the caller passes a live handle (the ABI).
305    unsafe { handle(env) }.env.num_envs()
306}
307
308unsafe extern "C" fn num_threads(env: *const c_void) -> usize {
309    // SAFETY: the caller passes a live handle (the ABI).
310    unsafe { handle(env) }.env.num_threads()
311}
312
313unsafe extern "C" fn set_num_threads(env: *mut c_void, threads: usize) {
314    // SAFETY: the caller passes a live handle, used only here (the ABI).
315    unsafe { handle_mut(env) }.env.set_num_threads(threads);
316}
317
318unsafe extern "C" fn reset(env: *mut c_void, has_seed: bool, seed: i64) {
319    // SAFETY: the caller passes a live handle, used only here (the ABI).
320    unsafe { handle_mut(env) }
321        .env
322        .reset(has_seed.then_some(seed));
323}
324
325unsafe extern "C" fn obs_into(env: *const c_void, out: *mut f32, len: usize) {
326    // SAFETY: the caller passes a live handle and `len` writable floats.
327    let (h, out) = unsafe { (handle(env), std::slice::from_raw_parts_mut(out, len)) };
328    h.env.obs_into(out);
329}
330
331unsafe extern "C" fn step(
332    env: *mut c_void,
333    kind: u32,
334    actions: *const c_void,
335    len: usize,
336    dim: usize,
337    obs: *mut f32,
338    reward: *mut f32,
339    terminated: *mut bool,
340    truncated: *mut bool,
341    final_obs: *mut f32,
342    obs_len: usize,
343) {
344    // SAFETY: the caller passes a live handle used only here, `len` actions
345    // of the type of `kind`, and buffers of `num_envs` and `obs_len`
346    // elements (the ABI).
347    unsafe {
348        let h = handle_mut(env);
349        let n = h.env.num_envs();
350        let actions = actions_from_raw(kind, actions, len, dim);
351        let out = StepBuffers {
352            obs: std::slice::from_raw_parts_mut(obs, obs_len),
353            reward: std::slice::from_raw_parts_mut(reward, n),
354            terminated: std::slice::from_raw_parts_mut(terminated, n),
355            truncated: std::slice::from_raw_parts_mut(truncated, n),
356            final_obs: std::slice::from_raw_parts_mut(final_obs, obs_len),
357        };
358        h.env.step_into(actions, out);
359    }
360}
361
362unsafe extern "C" fn step_without_final(
363    env: *mut c_void,
364    kind: u32,
365    actions: *const c_void,
366    len: usize,
367    dim: usize,
368    obs: *mut f32,
369    reward: *mut f32,
370    terminated: *mut bool,
371    truncated: *mut bool,
372    obs_len: usize,
373) {
374    // SAFETY: as in `step`, without the final observations.
375    unsafe {
376        let h = handle_mut(env);
377        let n = h.env.num_envs();
378        h.env.step_without_final(
379            actions_from_raw(kind, actions, len, dim),
380            std::slice::from_raw_parts_mut(obs, obs_len),
381            std::slice::from_raw_parts_mut(reward, n),
382            std::slice::from_raw_parts_mut(terminated, n),
383            std::slice::from_raw_parts_mut(truncated, n),
384        );
385    }
386}
387
388/// The actions of `step`: `len` elements at `actions` of the type of `kind`.
389///
390/// # Safety
391///
392/// `actions` must point to `len` readable elements of the type of `kind`
393/// (`i32` for 0 and 1, `f32` otherwise) that outlive the result.
394unsafe fn actions_from_raw<'a>(
395    kind: u32,
396    actions: *const c_void,
397    len: usize,
398    dim: usize,
399) -> Actions<'a> {
400    // SAFETY: guaranteed by the caller.
401    unsafe {
402        match kind {
403            0 => Actions::Discrete(std::slice::from_raw_parts(actions.cast::<i32>(), len)),
404            1 => Actions::MultiDiscrete {
405                data: std::slice::from_raw_parts(actions.cast::<i32>(), len),
406                dim,
407            },
408            _ => Actions::Continuous {
409                data: std::slice::from_raw_parts(actions.cast::<f32>(), len),
410                dim,
411            },
412        }
413    }
414}
415
416unsafe extern "C" fn legal_action_masks(env: *const c_void, out: *mut bool, len: usize) -> bool {
417    // SAFETY: the caller passes a live handle and `len` writable flags.
418    let (h, out) = unsafe { (handle(env), std::slice::from_raw_parts_mut(out, len)) };
419    h.env.legal_action_masks(out)
420}
421
422static VTABLE: VTable = VTable {
423    abi_version: ABI_VERSION,
424    num_modules,
425    module_name,
426    create,
427    destroy,
428    describe,
429    num_envs,
430    num_threads,
431    set_num_threads,
432    reset,
433    obs_into,
434    step,
435    legal_action_masks,
436    step_without_final,
437};
438
439/// The table of a library with `modules`, made by `make` (called by
440/// [`export_vec_envs!`](crate::export_vec_envs)).
441pub fn vtable(
442    modules: &'static [&'static str],
443    make: fn(&str, usize, i64) -> Option<Box<dyn DynVecEnv>>,
444) -> &'static VTable {
445    REGISTRY.get_or_init(|| Registry { modules, make });
446    &VTABLE
447}
448
449/// Exports the environments of the code of [`include_envs!`](crate::include_envs)
450/// (`MODULES` and `visit` in scope) from a `cdylib` through the C ABI of this
451/// module.
452#[macro_export]
453macro_rules! export_vec_envs {
454    () => {
455        /// The C ABI of the library's environments (`ruxla_env::dylib`).
456        #[unsafe(no_mangle)]
457        pub extern "C" fn ruxla_vec_env_vtable() -> *const $crate::dylib::VTable {
458            fn make(
459                module: &str,
460                num_envs: usize,
461                seed: i64,
462            ) -> ::core::option::Option<::std::boxed::Box<dyn $crate::dylib::DynVecEnv>> {
463                visit(module, &mut $crate::dylib::Make { num_envs, seed })
464            }
465            $crate::dylib::vtable(MODULES, make)
466        }
467    };
468}
469
470/// An error of [`Library::open`] or [`Library::create`].
471#[derive(Debug, thiserror::Error)]
472#[non_exhaustive]
473pub enum DylibError {
474    /// The library could not be loaded or has no table.
475    #[error("cannot load {path}: {message}")]
476    Load {
477        /// The library.
478        path: String,
479        /// The loader's message.
480        message: String,
481    },
482    /// The library has another ABI version.
483    #[error("{path} has ABI version {found}; this build reads version {ABI_VERSION}")]
484    Version {
485        /// The library.
486        path: String,
487        /// Its version.
488        found: u32,
489    },
490    /// The library has no such module.
491    #[error("no environment `{module}` in the library; it has {modules:?}")]
492    UnknownModule {
493        /// The requested module.
494        module: String,
495        /// The library's modules.
496        modules: Vec<String>,
497    },
498}
499
500/// A loaded library of compiled vector environments.
501#[derive(Clone, Debug)]
502pub struct Library {
503    // Kept loaded while environments of the library live.
504    _lib: Arc<libloading::Library>,
505    vtable: &'static VTable,
506}
507
508impl Library {
509    /// Loads a library that exports [`VTABLE_SYMBOL`].
510    ///
511    /// # Errors
512    ///
513    /// Returns an error if the library cannot be loaded, has no table, or
514    /// has another ABI version.
515    ///
516    /// # Safety
517    ///
518    /// Loading runs the library's initialization code, and the library must
519    /// implement the ABI of this module (one built with
520    /// [`export_vec_envs!`](crate::export_vec_envs)).
521    pub unsafe fn open(path: impl AsRef<Path>) -> Result<Self, DylibError> {
522        let path = path.as_ref();
523        let err = |e: libloading::Error| DylibError::Load {
524            path: path.display().to_string(),
525            message: e.to_string(),
526        };
527        // SAFETY: the caller accepts running the library's initializers.
528        let lib = unsafe { libloading::Library::new(path) }.map_err(err)?;
529        // SAFETY: the symbol has the type of `export_vec_envs!`, and the
530        // table it returns is a static of the library, which stays loaded as
531        // long as `lib` (kept in `Library`).
532        let vtable: &'static VTable = unsafe {
533            let f = lib
534                .get::<extern "C" fn() -> *const VTable>(VTABLE_SYMBOL)
535                .map_err(err)?;
536            &*f()
537        };
538        if vtable.abi_version != ABI_VERSION {
539            return Err(DylibError::Version {
540                path: path.display().to_string(),
541                found: vtable.abi_version,
542            });
543        }
544        Ok(Self {
545            _lib: Arc::new(lib),
546            vtable,
547        })
548    }
549
550    /// The modules of the library.
551    pub fn modules(&self) -> Vec<String> {
552        (0..(self.vtable.num_modules)())
553            .map(|i| {
554                let mut len = 0;
555                let p = (self.vtable.module_name)(i, &mut len);
556                // SAFETY: the library returns `len` bytes of a static string.
557                String::from_utf8_lossy(unsafe { std::slice::from_raw_parts(p, len) }).into_owned()
558            })
559            .collect()
560    }
561
562    /// Creates `num_envs` environments of `module` and resets them, with the
563    /// keys of [`CompiledVecEnv::new`].
564    ///
565    /// # Errors
566    ///
567    /// Returns an error if the library has no such module.
568    pub fn create(
569        &self,
570        module: &str,
571        num_envs: usize,
572        seed: i64,
573    ) -> Result<LibVecEnv, DylibError> {
574        // SAFETY: the ABI: `len` bytes at `module`.
575        let ptr = unsafe { (self.vtable.create)(module.as_ptr(), module.len(), num_envs, seed) };
576        if ptr.is_null() {
577            return Err(DylibError::UnknownModule {
578                module: module.to_string(),
579                modules: self.modules(),
580            });
581        }
582        let mut len = 0;
583        // SAFETY: `ptr` is a live handle; the description lives with it.
584        let description = unsafe {
585            let p = (self.vtable.describe)(ptr, &mut len);
586            String::from_utf8_lossy(std::slice::from_raw_parts(p, len)).into_owned()
587        };
588        let d: Value = serde_json::from_str(&description).unwrap_or(Value::Null);
589        let obs_shape: Vec<usize> = d["obs_shape"]
590            .as_array()
591            .map(|a| {
592                a.iter()
593                    .filter_map(|x| x.as_u64().map(|x| x as usize))
594                    .collect()
595            })
596            .unwrap_or_default();
597        let action_space =
598            crate::jax_env::action_space(&d["action_space"]).unwrap_or(ActionSpace::Discrete(0));
599        Ok(LibVecEnv {
600            lib: self.clone(),
601            ptr,
602            name: d["name"].as_str().unwrap_or(module).to_string(),
603            num_actions: d["num_actions"].as_u64().unwrap_or(0) as usize,
604            obs_len: obs_shape.iter().product(),
605            obs_shape,
606            action_space,
607        })
608    }
609}
610
611/// Vector environments of a [`Library`], with the operations of
612/// [`CompiledVecEnv`].
613#[derive(Debug)]
614pub struct LibVecEnv {
615    lib: Library,
616    ptr: *mut c_void,
617    name: String,
618    num_actions: usize,
619    obs_shape: Vec<usize>,
620    obs_len: usize,
621    action_space: ActionSpace,
622}
623
624// SAFETY: the handle owns a `Box<dyn DynVecEnv>` (`Send + Sync`) in the
625// library; `&self` methods only read it and `&mut self` methods are
626// exclusive, as for the boxed environment itself.
627unsafe impl Send for LibVecEnv {}
628// SAFETY: as above.
629unsafe impl Sync for LibVecEnv {}
630
631impl LibVecEnv {
632    /// The environment's name.
633    pub fn name(&self) -> &str {
634        &self.name
635    }
636    /// The number of discrete actions (0 for continuous actions).
637    pub fn num_actions(&self) -> usize {
638        self.num_actions
639    }
640    /// The shape of one observation.
641    pub fn obs_shape(&self) -> &[usize] {
642        &self.obs_shape
643    }
644    /// The actions.
645    pub fn action_space(&self) -> &ActionSpace {
646        &self.action_space
647    }
648    /// The number of environments.
649    pub fn num_envs(&self) -> usize {
650        // SAFETY: `ptr` is live while `self` is.
651        unsafe { (self.lib.vtable.num_envs)(self.ptr) }
652    }
653    /// The number of threads that step the environments.
654    pub fn num_threads(&self) -> usize {
655        // SAFETY: as above.
656        unsafe { (self.lib.vtable.num_threads)(self.ptr) }
657    }
658    /// Changes the number of threads.
659    pub fn set_num_threads(&mut self, threads: usize) {
660        // SAFETY: as above, used only here (`&mut self`).
661        unsafe { (self.lib.vtable.set_num_threads)(self.ptr, threads.max(1)) }
662    }
663    /// Starts new episodes (see [`CompiledVecEnv::reset`]).
664    pub fn reset(&mut self, seed: Option<i64>) {
665        // SAFETY: as above.
666        unsafe { (self.lib.vtable.reset)(self.ptr, seed.is_some(), seed.unwrap_or(0)) }
667    }
668    /// Writes the observations.
669    ///
670    /// # Panics
671    ///
672    /// Panics if `out` does not hold `num_envs * obs_len` floats.
673    pub fn obs_into(&self, out: &mut [f32]) {
674        assert_eq!(
675            out.len(),
676            self.num_envs() * self.obs_len,
677            "observation buffer"
678        );
679        // SAFETY: as above; `out` has the length checked above.
680        unsafe { (self.lib.vtable.obs_into)(self.ptr, out.as_mut_ptr(), out.len()) }
681    }
682    /// Steps every environment (see [`CompiledVecEnv::step_into_actions`]).
683    ///
684    /// # Panics
685    ///
686    /// Panics if a buffer has the wrong length.
687    pub fn step_into(&mut self, actions: Actions<'_>, out: StepBuffers<'_>) {
688        let n = self.num_envs();
689        assert!(
690            out.reward.len() == n
691                && out.terminated.len() == n
692                && out.truncated.len() == n
693                && out.obs.len() == n * self.obs_len
694                && out.final_obs.len() == n * self.obs_len,
695            "step buffers"
696        );
697        let (kind, ptr, len, dim) = self.raw_actions(actions, n);
698        // SAFETY: `ptr` is live and used only here; the actions and the
699        // buffers have the lengths checked above.
700        unsafe {
701            (self.lib.vtable.step)(
702                self.ptr,
703                kind,
704                ptr,
705                len,
706                dim,
707                out.obs.as_mut_ptr(),
708                out.reward.as_mut_ptr(),
709                out.terminated.as_mut_ptr(),
710                out.truncated.as_mut_ptr(),
711                out.final_obs.as_mut_ptr(),
712                out.obs.len(),
713            )
714        }
715    }
716    /// Steps every environment without the final observations (see
717    /// [`CompiledVecEnv::step_into_without_final`]).
718    ///
719    /// # Panics
720    ///
721    /// Panics if the number or kind of actions is wrong, or a buffer has the
722    /// wrong length.
723    pub fn step_into_without_final(
724        &mut self,
725        actions: Actions<'_>,
726        obs: &mut [f32],
727        reward: &mut [f32],
728        terminated: &mut [bool],
729        truncated: &mut [bool],
730    ) {
731        let n = self.num_envs();
732        assert!(
733            reward.len() == n
734                && terminated.len() == n
735                && truncated.len() == n
736                && obs.len() == n * self.obs_len,
737            "step buffers"
738        );
739        let (kind, ptr, len, dim) = self.raw_actions(actions, n);
740        // SAFETY: `ptr` is live and used only here; the actions and the
741        // buffers have the lengths checked above.
742        unsafe {
743            (self.lib.vtable.step_without_final)(
744                self.ptr,
745                kind,
746                ptr,
747                len,
748                dim,
749                obs.as_mut_ptr(),
750                reward.as_mut_ptr(),
751                terminated.as_mut_ptr(),
752                truncated.as_mut_ptr(),
753                obs.len(),
754            )
755        }
756    }
757
758    /// The actions as the ABI passes them, `(kind, ptr, len, dim)`, checked
759    /// against the action space and the `n` environments.
760    fn raw_actions(&self, actions: Actions<'_>, n: usize) -> (u32, *const c_void, usize, usize) {
761        let (kind, ptr, len, dim): (u32, *const c_void, usize, usize) = match actions {
762            Actions::Discrete(a) => (0, a.as_ptr().cast(), a.len(), 1),
763            Actions::MultiDiscrete { data, dim } => (1, data.as_ptr().cast(), data.len(), dim),
764            Actions::Continuous { data, dim } => (2, data.as_ptr().cast(), data.len(), dim),
765        };
766        assert_eq!(len, n * dim, "one action per environment");
767        let matches = match (&self.action_space, kind) {
768            (ActionSpace::Discrete(_), 0) => true,
769            (ActionSpace::MultiDiscrete(nvec), 1) => nvec.len() == dim,
770            (ActionSpace::Box { shape, .. }, 2) => shape.iter().product::<usize>() == dim,
771            _ => false,
772        };
773        assert!(
774            matches,
775            "actions of the wrong kind for {:?}",
776            self.action_space
777        );
778        (kind, ptr, len, dim)
779    }
780
781    /// Writes the legal action masks and returns `true`, or returns `false`
782    /// if the environment has none.
783    ///
784    /// # Panics
785    ///
786    /// Panics if `out` does not hold `num_envs` masks over the joint actions.
787    pub fn legal_action_masks_into(&self, out: &mut [bool]) -> bool {
788        assert_eq!(
789            out.len(),
790            self.num_envs() * self.action_space.mask_len(),
791            "a mask buffer of the wrong size"
792        );
793        // SAFETY: `ptr` is live; `out` is writable for its length.
794        unsafe { (self.lib.vtable.legal_action_masks)(self.ptr, out.as_mut_ptr(), out.len()) }
795    }
796}
797
798impl Drop for LibVecEnv {
799    fn drop(&mut self) {
800        // SAFETY: `ptr` came from `create` and is freed once, here.
801        unsafe { (self.lib.vtable.destroy)(self.ptr) }
802    }
803}
804
805/// Includes the environments that `ruxla-build` compiled in the build script
806/// (`$OUT_DIR/ruxla_envs.rs`): a module per environment, `MODULES`,
807/// `DATA_DIR`, and `visit`.
808#[macro_export]
809macro_rules! include_envs {
810    () => {
811        include!(concat!(env!("OUT_DIR"), "/ruxla_envs.rs"));
812    };
813}