1use 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
27pub const ABI_VERSION: u32 = 2;
31
32pub const VTABLE_SYMBOL: &[u8] = b"ruxla_vec_env_vtable";
35
36#[repr(C)]
40#[derive(Debug)]
41pub struct VTable {
42 pub abi_version: u32,
44 pub num_modules: extern "C" fn() -> usize,
46 pub module_name: extern "C" fn(i: usize, len: *mut usize) -> *const u8,
48 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 pub destroy: unsafe extern "C" fn(env: *mut c_void),
58 pub describe: unsafe extern "C" fn(env: *const c_void, len: *mut usize) -> *const u8,
61 pub num_envs: unsafe extern "C" fn(env: *const c_void) -> usize,
63 pub num_threads: unsafe extern "C" fn(env: *const c_void) -> usize,
65 pub set_num_threads: unsafe extern "C" fn(env: *mut c_void, threads: usize),
67 pub reset: unsafe extern "C" fn(env: *mut c_void, has_seed: bool, seed: i64),
69 pub obs_into: unsafe extern "C" fn(env: *const c_void, out: *mut f32, len: usize),
71 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 pub legal_action_masks:
92 unsafe extern "C" fn(env: *const c_void, out: *mut bool, len: usize) -> bool,
93 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
110pub trait DynVecEnv: Send + Sync {
113 fn describe(&self) -> Value;
115 fn num_envs(&self) -> usize;
117 fn num_threads(&self) -> usize;
119 fn set_num_threads(&mut self, threads: usize);
121 fn reset(&mut self, seed: Option<i64>);
123 fn obs_into(&self, out: &mut [f32]);
125 fn step_into(&mut self, actions: Actions<'_>, out: StepBuffers<'_>);
127 fn legal_action_masks(&self, out: &mut [bool]) -> bool;
129 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
188fn 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#[derive(Debug)]
202pub struct Make {
203 pub num_envs: usize,
205 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
216struct 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
224struct 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 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 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
267unsafe fn handle<'a>(env: *const c_void) -> &'a Handle {
273 unsafe { &*env.cast::<Handle>() }
275}
276
277unsafe fn handle_mut<'a>(env: *mut c_void) -> &'a mut Handle {
284 unsafe { &mut *env.cast::<Handle>() }
286}
287
288unsafe extern "C" fn destroy(env: *mut c_void) {
289 if !env.is_null() {
290 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 let h = unsafe { handle(env) };
298 unsafe { *len = h.description.len() };
300 h.description.as_ptr()
301}
302
303unsafe extern "C" fn num_envs(env: *const c_void) -> usize {
304 unsafe { handle(env) }.env.num_envs()
306}
307
308unsafe extern "C" fn num_threads(env: *const c_void) -> usize {
309 unsafe { handle(env) }.env.num_threads()
311}
312
313unsafe extern "C" fn set_num_threads(env: *mut c_void, threads: usize) {
314 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 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 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 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 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
388unsafe fn actions_from_raw<'a>(
395 kind: u32,
396 actions: *const c_void,
397 len: usize,
398 dim: usize,
399) -> Actions<'a> {
400 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 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
439pub 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#[macro_export]
453macro_rules! export_vec_envs {
454 () => {
455 #[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#[derive(Debug, thiserror::Error)]
472#[non_exhaustive]
473pub enum DylibError {
474 #[error("cannot load {path}: {message}")]
476 Load {
477 path: String,
479 message: String,
481 },
482 #[error("{path} has ABI version {found}; this build reads version {ABI_VERSION}")]
484 Version {
485 path: String,
487 found: u32,
489 },
490 #[error("no environment `{module}` in the library; it has {modules:?}")]
492 UnknownModule {
493 module: String,
495 modules: Vec<String>,
497 },
498}
499
500#[derive(Clone, Debug)]
502pub struct Library {
503 _lib: Arc<libloading::Library>,
505 vtable: &'static VTable,
506}
507
508impl Library {
509 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 let lib = unsafe { libloading::Library::new(path) }.map_err(err)?;
529 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 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 String::from_utf8_lossy(unsafe { std::slice::from_raw_parts(p, len) }).into_owned()
558 })
559 .collect()
560 }
561
562 pub fn create(
569 &self,
570 module: &str,
571 num_envs: usize,
572 seed: i64,
573 ) -> Result<LibVecEnv, DylibError> {
574 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 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#[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
624unsafe impl Send for LibVecEnv {}
628unsafe impl Sync for LibVecEnv {}
630
631impl LibVecEnv {
632 pub fn name(&self) -> &str {
634 &self.name
635 }
636 pub fn num_actions(&self) -> usize {
638 self.num_actions
639 }
640 pub fn obs_shape(&self) -> &[usize] {
642 &self.obs_shape
643 }
644 pub fn action_space(&self) -> &ActionSpace {
646 &self.action_space
647 }
648 pub fn num_envs(&self) -> usize {
650 unsafe { (self.lib.vtable.num_envs)(self.ptr) }
652 }
653 pub fn num_threads(&self) -> usize {
655 unsafe { (self.lib.vtable.num_threads)(self.ptr) }
657 }
658 pub fn set_num_threads(&mut self, threads: usize) {
660 unsafe { (self.lib.vtable.set_num_threads)(self.ptr, threads.max(1)) }
662 }
663 pub fn reset(&mut self, seed: Option<i64>) {
665 unsafe { (self.lib.vtable.reset)(self.ptr, seed.is_some(), seed.unwrap_or(0)) }
667 }
668 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 unsafe { (self.lib.vtable.obs_into)(self.ptr, out.as_mut_ptr(), out.len()) }
681 }
682 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 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 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 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 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 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 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 unsafe { (self.lib.vtable.destroy)(self.ptr) }
802 }
803}
804
805#[macro_export]
809macro_rules! include_envs {
810 () => {
811 include!(concat!(env!("OUT_DIR"), "/ruxla_envs.rs"));
812 };
813}