mujoco-rs 4.0.0+mj-3.8.0

A high-level Rust wrapper around the MuJoCo C library, with a native viewer (re-)written in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
//! Utility types and macros used throughout the crate.
use std::{marker::PhantomData, ops::{Deref, DerefMut}};
use std::sync::{Mutex, MutexGuard};
use std::ffi::c_char;

use crate::mujoco_c::{mj_version, mjVERSION_HEADER};

/// Standard size of temporary error buffers passed to MuJoCo C functions.
/// MuJoCo NUL-terminates within this size, so the effective maximum
/// message length is `ERROR_BUF_LEN - 1` characters.
pub(crate) const ERROR_BUF_LEN: usize = 100;

/// Copies an ASCII `&str` into a fixed-size `c_char` buffer, NUL-terminating and
/// zero-filling the remainder.
///
/// # Panics
/// Panics if `value` is not valid ASCII, contains an interior NUL byte,
/// or if `value` (plus NUL) does not fit in `buf`.
pub(crate) fn write_ascii_to_buf(buf: &mut [c_char], value: &str) {
    assert!(value.is_ascii(), "value must be valid ASCII");
    let c_string = std::ffi::CString::new(value).unwrap();
    let bytes = c_string.into_bytes_with_nul();
    let dest: &mut [u8] = bytemuck::cast_slice_mut(buf);
    dest[..bytes.len()].copy_from_slice(&bytes);
    dest[bytes.len()..].fill(0);
}

/// Sets or clears a bit flag based on a boolean value.
///
/// # Examples
/// ```ignore
/// let mut flags = 0i32;
/// set_flag!(flags, 0x01, true);   // sets bit 0
/// set_flag!(flags, 0x01, false);  // clears bit 0
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! set_flag {
    ($flags:expr, $mask:expr, $enabled:expr) => {
        if $enabled {
            $flags |= $mask;
        } else {
            $flags &= !$mask;
        }
    };
}

/// Creates a (start, length) tuple based on
/// lookup variables that define the mapping in MuJoCo's mjModel struct.
/// The tuple is used to create views to correct addresses in corresponding structs.
/// Format: item id, map from item id to index inside the array of all items' values,
///         number of items, maximum number of elements inside the array of all items' values
#[macro_export]
#[doc(hidden)]
macro_rules! mj_view_indices {
    ($id:expr, $addr_map:expr, $njnt:expr, $max_n:expr) => {
        {
            let start_addr = *$addr_map.add($id) as isize;
            if start_addr == -1 {
                (0, 0)
            }
            else
            {
                // Some addr maps (e.g. actuator_actadr) contain -1 for items with no
                // allocated data (stateless actuators).  Skip over those sentinels when
                // looking for the end boundary of the current range.
                let mut next_idx = $id + 1;
                let end_addr: usize = loop {
                    if next_idx >= $njnt as usize {
                        break $max_n as usize;
                    }
                    let next_addr = *$addr_map.add(next_idx) as isize;
                    if next_addr != -1 {
                        break next_addr as usize;
                    }
                    next_idx += 1;
                };
                let n = end_addr - start_addr as usize;
                (start_addr as usize, n)
            }
        }
    };
}

/// Returns the correct address mapping based on the X in nX (nq, nv, nu, ...).
#[macro_export]
#[doc(hidden)]
macro_rules! mj_model_nx_to_mapping {
    ($model_ffi:ident, nq) => {
        $model_ffi.jnt_qposadr
    };

    ($model_ffi:ident, nv) => {
        $model_ffi.jnt_dofadr
    };

    ($model_ffi:ident, nsensordata) => {
        $model_ffi.sensor_adr
    };
    ($model_ffi:ident, ntupledata) => {
        $model_ffi.tuple_adr
    };
    ($model_ffi:ident, ntexdata) => {
        $model_ffi.tex_adr
    };
    ($model_ffi:ident, nnumericdata) => {
        $model_ffi.numeric_adr
    };
    ($model_ffi:ident, nhfielddata) => {
        $model_ffi.hfield_adr
    };
    ($model_ffi:ident, na) => {
        $model_ffi.actuator_actadr
    };
    ($model_ffi:ident, nJten) => {
        $model_ffi.ten_J_rowadr
    };
}


/// Returns the correct number of items based on the X in nX (nq, nv, nu, ...).
#[macro_export]
#[doc(hidden)]
macro_rules! mj_model_nx_to_nitem {
    ($model_ffi:ident, nq) => {
        $model_ffi.njnt
    };

    ($model_ffi:ident, nv) => {
        $model_ffi.njnt
    };

    ($model_ffi:ident, nsensordata) => {
        $model_ffi.nsensor
    };
    ($model_ffi:ident, ntupledata) => {
        $model_ffi.ntuple
    };
    ($model_ffi:ident, ntexdata) => {
        $model_ffi.ntex
    };
    ($model_ffi:ident, nnumericdata) => {
        $model_ffi.nnumeric
    };
    ($model_ffi:ident, nhfielddata) => {
        $model_ffi.nhfield
    };
    ($model_ffi:ident, na) => {
        $model_ffi.nu
    };
    ($model_ffi:ident, nJten) => {
        $model_ffi.ntendon
    };
}

/// Provides a more direct view to a C array.
/// # Safety
/// This does not check if the data is valid. It is assumed
/// the correct data is given and that it doesn't get dropped before this struct.
/// This does not break Rust's checks as we create the view each
/// time from the saved pointers.
/// This should ONLY be used within a wrapper that fully encapsulates the underlying data.
#[derive(Debug)]
pub struct PointerViewMut<'d, T> {
    ptr: *mut T,
    len: usize,
    phantom: PhantomData<&'d mut ()>
}

impl<'d, T> PointerViewMut<'d, T> {
    pub(crate) const fn new(ptr: *mut T, len: usize, phantom: PhantomData<&'d mut ()>) -> Self {
        Self {ptr, len, phantom}
    }
}

/// Compares if the two views point to the same data with the same length.
impl<T> PartialEq for PointerViewMut<'_, T> {
    fn eq(&self, other: &Self) -> bool {
        self.ptr == other.ptr && self.len == other.len
    }
}

impl<T> Eq for PointerViewMut<'_, T> {}

impl<T> Deref for PointerViewMut<'_, T> {
    type Target = [T];
    fn deref(&self) -> &Self::Target {
        if self.ptr.is_null() {
            return &[];
        }
        // SAFETY: ptr is non-null (checked above), properly aligned, and points to
        // self.len initialized elements owned by the parent wrapper for lifetime 'd.
        unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
    }
}

impl<T> DerefMut for PointerViewMut<'_, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        if self.ptr.is_null() {
            return &mut [];
        }
        // SAFETY: ptr is non-null (checked above), properly aligned, points to self.len
        // initialized elements, and &mut self guarantees exclusive access.
        unsafe { std::slice::from_raw_parts_mut(self.ptr, self.len) }
    }
}

/// Provides a read-only view to a C array with explicit unsafe mutable access.
/// # Safety
/// This does not check if the data is valid. It is assumed
/// the correct data is given and that it doesn't get dropped before this struct.
/// Mutable access is only available via [`PointerViewUnsafeMut::as_mut_slice`],
/// where the caller must uphold Rust aliasing and validity guarantees.
/// This should ONLY be used within a wrapper that fully encapsulates the underlying data.
#[derive(Debug)]
pub struct PointerViewUnsafeMut<'d, T> {
    ptr: *mut T,
    len: usize,
    phantom: PhantomData<&'d mut ()>
}

impl<'d, T> PointerViewUnsafeMut<'d, T> {
    pub(crate) const fn new(ptr: *mut T, len: usize, phantom: PhantomData<&'d mut ()>) -> Self {
        Self { ptr, len, phantom }
    }

    /// Returns a mutable slice over the underlying data.
    ///
    /// # Safety
    /// Caller must ensure that:
    /// - `self.ptr` points to `self.len` properly aligned and initialized `T` values (or is null with `len == 0`);
    /// - no other references (shared or mutable) to overlapping memory are alive while the returned slice is used;
    /// - written values preserve Rust type validity and MuJoCo invariants.
    pub unsafe fn as_mut_slice(&mut self) -> &mut [T] {
        if self.ptr.is_null() {
            return &mut [];
        }
        // SAFETY: caller upholds aliasing and validity guarantees (documented above).
        // ptr is non-null (checked above) and points to self.len elements.
        unsafe { std::slice::from_raw_parts_mut(self.ptr, self.len) }
    }
}

/// Compares if the two views point to the same data with the same length.
impl<T> PartialEq for PointerViewUnsafeMut<'_, T> {
    fn eq(&self, other: &Self) -> bool {
        self.ptr == other.ptr && self.len == other.len
    }
}

impl<T> Eq for PointerViewUnsafeMut<'_, T> {}

impl<T> Deref for PointerViewUnsafeMut<'_, T> {
    type Target = [T];
    fn deref(&self) -> &Self::Target {
        if self.ptr.is_null() {
            return &[];
        }
        // SAFETY: ptr is non-null (checked above), properly aligned, and points to
        // self.len initialized elements owned by the parent wrapper for lifetime 'd.
        unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
    }
}

/// Provides a more direct view to a C array.
/// # Safety
/// This does not check if the data is valid. It is assumed
/// the correct data is given and that it doesn't get dropped before this struct.
/// This does not break Rust's checks as we create the view each
/// time from the saved pointers.
/// This should ONLY be used within a wrapper that fully encapsulates the underlying data.
#[derive(Debug)]
pub struct PointerView<'d, T> {
    ptr: *const T,
    len: usize,
    phantom: PhantomData<&'d ()>
}

impl<'d, T> PointerView<'d, T> {
    pub(crate) const fn new(ptr: *const T, len: usize, phantom: PhantomData<&'d ()>) -> Self {
        Self {ptr, len, phantom}
    }
}

/// Compares if the two views point to the same data with the same length.
impl<T> PartialEq for PointerView<'_, T> {
    fn eq(&self, other: &Self) -> bool {
        self.ptr == other.ptr && self.len == other.len
    }
}

impl<T> Eq for PointerView<'_, T> {}

impl<T> Deref for PointerView<'_, T> {
    type Target = [T];
    fn deref(&self) -> &Self::Target {
        if self.ptr.is_null() {
            return &[];
        }
        // SAFETY: ptr is non-null (checked above), properly aligned, and points to
        // self.len initialized elements owned by the parent wrapper for lifetime 'd.
        unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
    }
}

/***************************/
//  Evaluation helper macro
/***************************/
/// When @eval is given false, ignore the given contents.
/// In other cases, expand the given contents.
#[macro_export]
#[doc(hidden)]
macro_rules! eval_or_expand {
    (@eval $(true)? { $($data:tt)* } ) => { $($data)* };
    (@eval false { $($data:tt)* } ) => {};
}

/**************************************************************************************************/
// View creation for MjData and MjModel
/**************************************************************************************************/

/// Constructs a view struct by mapping fields to their corresponding locations in `$data`.
///
/// - `$field` list uses `$ptr_view` (read-write in `ViewMut`, read-only in `View`).
/// - `$field_ro` list uses `$ptr_view_ro` (`PointerViewUnsafeMut` in `ViewMut`, `PointerView` in `View`).
/// - `$opt_field` list uses `$ptr_view`, wrapped in `Option`.
///
/// # Safety
/// Caller must ensure the data pointers remain valid for the lifetime of the view.
#[macro_export]
#[doc(hidden)]
macro_rules! view_creator {
    (
        $self:expr, $view:ident, $data:expr,
        [$($([$prefix_field:ident])? $field:ident : $type_:ty $([$force:ident])?),*],
        [$($([$prefix_field_ro:ident])? $field_ro:ident : $type_ro:ty $([$force_ro:ident])?),*],
        [$($([$prefix_opt_field:ident])? $opt_field:ident : $type_opt:ty $([$force_opt:ident])?),*],
        $ptr_view:expr,
        $ptr_view_ro:expr
    ) => {
        paste::paste! {
            unsafe {
                $view {
                    $(
                        $field: $ptr_view(
                            $crate::maybe_force_cast!($data.[<$($prefix_field)? $field>].add($self.$field.0), $type_ $(, $force)?),
                            $self.$field.1,
                            std::marker::PhantomData
                        ),
                    )*
                    $(
                        $field_ro: $ptr_view_ro(
                            $crate::maybe_force_cast!($data.[<$($prefix_field_ro)? $field_ro>].add($self.$field_ro.0), $type_ro $(, $force_ro)?),
                            $self.$field_ro.1,
                            std::marker::PhantomData
                        ),
                    )*
                    $(
                        $opt_field: if $self.$opt_field.1 > 0 {
                            Some($ptr_view(
                                $crate::maybe_force_cast!($data.[<$($prefix_opt_field)? $opt_field>].add($self.$opt_field.0), $type_opt $(, $force_opt)?),
                                $self.$opt_field.1,
                                std::marker::PhantomData
                            ))
                        } else {
                            None
                        },
                    )*
                }
            }
        }
    };
}


/// Generates a lookup method `$type_(&self, name: &str) -> Option<Mj{Type}{InfoType}Info>` on
/// a wrapper.
///
/// The returned `Info` struct stores the name, id, and index ranges needed to
/// create views into the corresponding `MjData` or `MjModel` arrays.
///
/// # Entry formats
///
/// - **Fixed stride**: `attr: N`: index range is `(id * N, N)`.
/// - **FFI stride** (with optional multiplier): `attr: ffi_field (* k)`: stride taken from
///   `model.ffi_field`, optionally scaled by `k`.
/// - **Dynamic range**: `attr: nXXX (* k)`: start and length resolved via [`mj_view_indices!`],
///   where `nXXX` is the major-dimension field (e.g. `nhfielddata`, `ntexdata`).
///   The optional `* k` is a stride multiplier: each logical unit occupies `k` flat elements,
///   so both the start offset and the length are scaled by `k`. Use this when the target array
///   stores `k` flat values per logical unit (e.g. `dof_dampingpoly (nv × mjNPOLY)` viewed as
///   a flat `MjtNum` slice: offset = `dof_start * mjNPOLY`, length = `n_dofs * mjNPOLY`).
#[doc(hidden)]
#[macro_export]
macro_rules! info_method {
    ($info_type:ident, $ffi:expr, $type_:ident, [$($attr:ident: $len:expr),*], [$($attr_ffi:ident: $len_ffi:ident $(* $multiplier:expr)?),*], [$($attr_dyn:ident: $ffi_len_dyn:ident $(* $offset_mult:expr)?),*]) => {
        paste::paste! {
            #[doc = concat!(
                "Returns a [`", stringify!([<Mj $type_:camel $info_type Info>]), "`] for the named ", stringify!($type_), ", ",
                "containing the indices required to create views into [`Mj", stringify!($info_type), "`] arrays.\n\n",
                "Call [`view`](", stringify!([<Mj $type_:camel $info_type Info>]), "::view) or ",
                "[`try_view`](", stringify!([<Mj $type_:camel $info_type Info>]), "::try_view) on the result to obtain the actual view.\n\n",
                "# Panics\n",
                "Panics if `name` contains a `\\0` byte."
            )]
            #[allow(non_snake_case)]
            pub fn $type_(&self, name: &str) -> Option<[<Mj $type_:camel $info_type Info>]> {
                let c_name = CString::new(name).unwrap();
                let ffi = self.$ffi;
                let id = unsafe { mj_name2id(ffi, MjtObj::[<mjOBJ_ $type_:upper>] as i32, c_name.as_ptr()) };
                if id == -1 {
                    return None;
                }

                let id = id as usize;
                $(
                    let $attr = (id * $len, $len);
                )*
                $(
                    let $attr_ffi = (id * ffi.$len_ffi as usize $( * $multiplier)*, ffi.$len_ffi as usize $( * $multiplier)*);
                )*
                $(
                    let (dyn_start, dyn_len) = unsafe { mj_view_indices!(
                        id,
                        mj_model_nx_to_mapping!(ffi, $ffi_len_dyn),
                        mj_model_nx_to_nitem!(ffi, $ffi_len_dyn),
                        ffi.$ffi_len_dyn
                    ) };
                    let $attr_dyn = (dyn_start $(* $offset_mult)?, dyn_len $(* $offset_mult)?);
                )*

                let model_signature = ffi.signature;
                Some([<Mj $type_:camel $info_type Info>] { name: name.to_string(), id, model_signature, $($attr,)* $($attr_ffi,)* $($attr_dyn),* })
            }
        }
    }
}


/// Generates `Info`, `ViewMut`, and `View` types for a named MuJoCo object, along with
/// `view`, `try_view`, `view_mut`, and `try_view_mut` methods on the `Info` type.
///
/// # Field lists
///
/// - **`[rw fields]`**: read-write: `PointerViewMut` in `ViewMut`, `PointerView` in `View`.
/// - **`[ro fields]`**: read as `PointerViewUnsafeMut` in `ViewMut` (unsafe to mutate), `PointerView` in `View`.
/// - **`[opt fields]`**: optional read-write: `Option<PointerViewMut>` / `Option<PointerView>`.
///
/// # Field entry syntax
///
/// ```text
/// [prefix_] field_name : ElementType [force]
/// ```
///
/// - `[prefix_]`: optional prefix prepended to the FFI field name (e.g. `[actuator_]`).
/// - `[force]`: emit a forced pointer cast via [`maybe_force_cast!`] (needed when the Rust
///   element type differs from the C array element type, e.g. `f64` -> `[f64; 3]`).
#[doc(hidden)]
#[macro_export]
macro_rules! info_with_view {
    (
        $info_type:ident, $name:ident,
        [$($([$prefix_attr:ident])? $attr:ident: $type_:ty $([$force:ident])?),*],
        [$($([$prefix_attr_ro:ident])? $attr_ro:ident: $type_ro:ty $([$force_ro:ident])?),*],
        [$($([$prefix_opt_attr:ident])? $opt_attr:ident: $type_opt:ty $([$force_opt:ident])?),*]
        $(,$generics:ty: $bound:ty)?
    ) => {
        paste::paste! {
            #[doc = "Index ranges required to create views into [`Mj" $info_type "`] arrays for a " $name "."]
            #[allow(non_snake_case)]
            #[derive(Debug, Clone)]
            pub struct [<Mj $name:camel $info_type Info>] {
                /// Name of the element.
                pub name: String,
                /// Index of the element.
                pub id: usize,
                model_signature: u64,
                $(
                    $attr: (usize, usize),
                )*
                $(
                    $attr_ro: (usize, usize),
                )*
                $(
                    $opt_attr: (usize, usize),
                )*
            }

            impl [<Mj $name:camel $info_type Info>] {
                /// Returns the model signature this `Info` was created from.
                pub fn model_signature(&self) -> u64 {
                    self.model_signature
                }

                #[doc = concat!(
                    "Returns a mutable view into the [`Mj", stringify!($info_type), "`] arrays for this ", stringify!($name), ".\n\n",
                    "Fields listed as read-only use [`PointerViewUnsafeMut`](crate::util::PointerViewUnsafeMut): ",
                    "read is safe, mutation requires [`as_mut_slice`](crate::util::PointerViewUnsafeMut::as_mut_slice) and `unsafe`.\n\n",
                    "# Errors\n",
                    "Returns [`SignatureMismatch`](", stringify!([<Mj $info_type Error>]), "::SignatureMismatch) if `",
                    stringify!($info_type), "` was built from a different model than this `Info`."
                )]
                pub fn try_view_mut<'p $(, $generics: $bound)?>(&self, [<$info_type:lower>]: &'p mut [<Mj $info_type>]$(<$generics>)?) -> Result<[<Mj $name:camel $info_type ViewMut>]<'p>, $crate::error::[<Mj $info_type Error>]> {
                    let destination_signature = [<$info_type:lower>].signature();
                    if self.model_signature != destination_signature {
                        return Err($crate::error::[<Mj $info_type Error>]::SignatureMismatch {
                            source: self.model_signature,
                            destination: destination_signature,
                        });
                    }
                    Ok(view_creator!(self, [<Mj $name:camel $info_type ViewMut>], [<$info_type:lower>].ffi(),
                        [$($([$prefix_attr])? $attr : $type_ $([$force])?),*],
                        [$($([$prefix_attr_ro])? $attr_ro : $type_ro $([$force_ro])?),*],
                        [$($([$prefix_opt_attr])? $opt_attr : $type_opt $([$force_opt])?),*],
                        $crate::util::PointerViewMut::new,
                        $crate::util::PointerViewUnsafeMut::new))
                }

                #[doc = concat!(
                    "Returns a mutable view into the [`Mj", stringify!($info_type), "`] arrays for this ", stringify!($name), ".\n\n",
                    "Fields listed as read-only use [`PointerViewUnsafeMut`](crate::util::PointerViewUnsafeMut): ",
                    "read is safe, mutation requires [`as_mut_slice`](crate::util::PointerViewUnsafeMut::as_mut_slice) and `unsafe`.\n\n",
                    "# Panics\n",
                    "Panics if `", stringify!($info_type), "` was built from a different model than this `Info`. ",
                    "Use [`try_view_mut`](Self::try_view_mut) to handle this as a `Result`."
                )]
                pub fn view_mut<'p $(, $generics: $bound)?>(&self, [<$info_type:lower>]: &'p mut [<Mj $info_type>]$(<$generics>)?) -> [<Mj $name:camel $info_type ViewMut>]<'p> {
                    self.try_view_mut([<$info_type:lower>]).unwrap_or_else(|_| panic!("model signature mismatch"))
                }

                #[doc = concat!(
                    "Returns an immutable view into the [`Mj", stringify!($info_type), "`] arrays for this ", stringify!($name), ".\n\n",
                    "# Errors\n",
                    "Returns [`SignatureMismatch`](", stringify!([<Mj $info_type Error>]), "::SignatureMismatch) if `",
                    stringify!($info_type), "` was built from a different model than this `Info`."
                )]
                pub fn try_view<'p $(, $generics: $bound)?>(&self, [<$info_type:lower>]: &'p [<Mj $info_type>]$(<$generics>)?) -> Result<[<Mj $name:camel $info_type View>]<'p>, $crate::error::[<Mj $info_type Error>]> {
                    let destination_signature = [<$info_type:lower>].signature();
                    if self.model_signature != destination_signature {
                        return Err($crate::error::[<Mj $info_type Error>]::SignatureMismatch {
                            source: self.model_signature,
                            destination: destination_signature,
                        });
                    }
                    Ok(view_creator!(self, [<Mj $name:camel $info_type View>], [<$info_type:lower>].ffi(),
                        [$($([$prefix_attr])? $attr : $type_ $([$force])?),*],
                        [$($([$prefix_attr_ro])? $attr_ro : $type_ro $([$force_ro])?),*],
                        [$($([$prefix_opt_attr])? $opt_attr : $type_opt $([$force_opt])?),*],
                        $crate::util::PointerView::new,
                        $crate::util::PointerView::new))
                }

                #[doc = concat!(
                    "Returns an immutable view into the [`Mj", stringify!($info_type), "`] arrays for this ", stringify!($name), ".\n\n",
                    "# Panics\n",
                    "Panics if `", stringify!($info_type), "` was built from a different model than this `Info`. ",
                    "Use [`try_view`](Self::try_view) to handle this as a `Result`."
                )]
                pub fn view<'p $(, $generics: $bound)?>(&self, [<$info_type:lower>]: &'p [<Mj $info_type>]$(<$generics>)?) -> [<Mj $name:camel $info_type View>]<'p> {
                    self.try_view([<$info_type:lower>]).unwrap_or_else(|_| panic!("model signature mismatch"))
                }
            }

            #[doc = "Mutable view into [`Mj" $info_type "`] arrays for a " $name ".\n\n"
                    "Read-write fields are [`PointerViewMut`](crate::util::PointerViewMut); "
                    "read-only fields are [`PointerViewUnsafeMut`](crate::util::PointerViewUnsafeMut), "
                    "which require [`as_mut_slice`](crate::util::PointerViewUnsafeMut::as_mut_slice) and explicit `unsafe` to mutate."]
            #[allow(non_snake_case)]
            #[derive(Debug)]
            pub struct [<Mj $name:camel $info_type ViewMut>]<'d> {
                $(
                    #[doc = concat!("Mutable view of `", stringify!($attr), "`.")]
                    pub $attr: $crate::util::PointerViewMut<'d, $type_>,
                )*
                $(
                    #[doc = concat!("Read-only view of `", stringify!($attr_ro), "`. Requires `unsafe` for mutation.")]
                    pub $attr_ro: $crate::util::PointerViewUnsafeMut<'d, $type_ro>,
                )*
                $(
                    #[doc = concat!("Optional mutable view of `", stringify!($opt_attr), "`.")]
                    pub $opt_attr: Option<$crate::util::PointerViewMut<'d, $type_opt>>,
                )*
            }

            impl [<Mj $name:camel $info_type ViewMut>]<'_> {
                /// Zeroes all read-write fields. Read-only fields are left unchanged.
                pub fn zero(&mut self) {
                    $(
                        self.$attr.fill(bytemuck::Zeroable::zeroed());
                    )*
                    $(
                        if let Some(x) = &mut self.$opt_attr {
                            x.fill(bytemuck::Zeroable::zeroed());
                        }
                    )*
                }
            }

            #[doc = "Immutable view into [`Mj" $info_type "`] arrays for a " $name "."]
            #[allow(non_snake_case)]
            #[derive(Debug)]
            pub struct [<Mj $name:camel $info_type View>]<'d> {
                $(
                    #[doc = concat!("View of `", stringify!($attr), "`.")]
                    pub $attr: $crate::util::PointerView<'d, $type_>,
                )*
                $(
                    #[doc = concat!("View of `", stringify!($attr_ro), "`.")]
                    pub $attr_ro: $crate::util::PointerView<'d, $type_ro>,
                )*
                $(
                    #[doc = concat!("Optional view of `", stringify!($opt_attr), "`.")]
                    pub $opt_attr: Option<$crate::util::PointerView<'d, $type_opt>>,
                )*
            }
        }
    };
}


#[doc(hidden)]
#[macro_export]
macro_rules! getter_setter {
    (get, [$($([$ffi:ident])? $name:ident $(+ $symbol:tt)?: bool; $comment:expr);* $(;)?]) => {paste::paste!{
        $(
            #[doc = concat!("Check ", $comment)]
            pub fn [<$name:camel:snake $($symbol)?>](&self) -> bool {
                self$(.$ffi())?.$name == 1
            }
        )*
    }};

    (get, [$($([$ffi:ident $(,$ffi_mut:ident)?])? $((allow_mut = $cfg_mut:literal))? $name:ident $(+ $symbol:tt)?: & $type:ty; $comment:expr);* $(;)?]) => {paste::paste!{
        $(
            #[doc = concat!("Return an immutable reference to ", $comment)]
            pub fn [<$name:camel:snake $($symbol)?>](&self) -> &$type {
                &self$(.$ffi())?.$name
            }

            $crate::eval_or_expand! {
                @eval $($cfg_mut)? {
                    #[doc = concat!("Return a mutable reference to ", $comment)]
                    pub fn [<$name:camel:snake _mut>](&mut self) -> &mut $type {
                        #[allow(unused_unsafe)]
                        unsafe { &mut self$(.$($ffi_mut())?)?.$name }
                    }
                }
            }
        )*
    }};

    (get, [$($([$ffi:ident])? $name:ident $(+ $symbol:tt)?: $type:ty; $comment:expr);* $(;)?]) => {paste::paste!{
        $(
            #[doc = concat!("Return value of ", $comment)]
            pub fn [<$name:camel:snake $($symbol)?>](&self) -> $type {
                self$(.$ffi())?.$name.into()
            }
        )*
    }};

    (set, [$($([$ffi_mut:ident])? $name:ident: $type:ty; $comment:expr);* $(;)?]) => {
        paste::paste!{ 
            $(
                #[doc = concat!("Set ", $comment)]
                pub fn [<set_ $name:camel:snake>](&mut self, value: $type) {
                    #[allow(unused_unsafe)]
                    unsafe { self$(.$ffi_mut())?.$name = value.into() };
                }
            )*
        }
    };

    /* Enum conversion */
    (force!, get, [$($([$ffi:ident])? $name:ident $(+ $symbol:tt)? : $type:ty; $comment:expr);* $(;)?]) => {paste::paste!{
        $(
            #[doc = concat!("Return value of ", $comment)]
            pub fn [<$name:camel:snake $($symbol)?>](&self) -> $type {
                unsafe { $crate::util::force_cast(self$(.$ffi())?.$name) }
            }
        )*
    }};

    (force!, set, [$($([$ffi_mut:ident])? $name:ident: $type:ty; $comment:expr);* $(;)?]) => {
        paste::paste!{ 
            $(
                #[doc = concat!("Set ", $comment)]
                pub fn [<set_ $name:camel:snake>](&mut self, value: $type) {
                    #[allow(unused_unsafe)]
                    unsafe { self$(.$ffi_mut())?.$name = $crate::util::force_cast(value) };
                }
            )*
        }
    };

    /* Builder pattern */
    (force!, with, [$($([$ffi_mut:ident])? $name:ident: $type:ty; $comment:expr);* $(;)?]) => {
        paste::paste!{ 
            $(
                #[doc = concat!("Builder method for setting ", $comment)]
                pub fn [<with_ $name:camel:snake>](mut self, value: $type) -> Self {
                    #[allow(unused_unsafe)]
                    unsafe { self$(.$ffi_mut())?.$name = $crate::util::force_cast(value) };
                    self
                }
            )*
        }
    };

    (force!, [&] with, [$($([$ffi_mut:ident])? $name:ident: $type:ty; $comment:expr);* $(;)?]) => {
        paste::paste!{ 
            $(
                #[doc = concat!("Builder method for setting ", $comment)]
                pub fn [<with_ $name:camel:snake>](&mut self, value: $type) -> &mut Self {
                    #[allow(unused_unsafe)]
                    unsafe { self$(.$ffi_mut())?.$name = $crate::util::force_cast(value) };
                    self
                }
            )*
        }
    };

    (with, [$($([$ffi_mut:ident])? $name:ident: $type:ty; $comment:expr);* $(;)?]) => {
        paste::paste!{ 
            $(
                #[doc = concat!("Builder method for setting ", $comment)]
                pub fn [<with_ $name:camel:snake>](mut self, value: $type) -> Self {
                    #[allow(unused_unsafe)]
                    unsafe { self$(.$ffi_mut())?.$name = value.into() };
                    self
                }
            )*
        }
    };

    ([&] with, [$($([$ffi_mut:ident])? $name:ident: $type:ty; $comment:expr);* $(;)?]) => {
        paste::paste!{ 
            $(
                #[doc = concat!("Builder method for setting ", $comment)]
                pub fn [<with_ $name:camel:snake>](&mut self, value: $type) -> &mut Self {
                    #[allow(unused_unsafe)]
                    unsafe { self$(.$ffi_mut())?.$name = value.into() };
                    self
                }
            )*
        }
    };
    
    /* Handling of optional arguments */
    /* Enum pass */
    (force!, get, set, [ $($([$ffi: ident, $ffi_mut:ident])? $name:ident $(+ $symbol:tt)? : $type:ty ; $comment:expr );* $(;)?]) => {
        $crate::getter_setter!(force!, get, [ $($([$ffi])? $name $(+ $symbol)? : $type ; $comment );* ]);
        $crate::getter_setter!(force!, set, [ $($([$ffi_mut])? $name : $type ; $comment );* ]);
    };

    (get, set, [ $($([$ffi: ident, $ffi_mut:ident])? $name:ident $(+ $symbol:tt)? : bool ; $comment:expr );* $(;)?]) => {
        $crate::getter_setter!(get, [ $($([$ffi])? $name $(+ $symbol)? : bool ; $comment );* ]);
        $crate::getter_setter!(set, [ $($([$ffi_mut])? $name : bool ; $comment );* ]);
    };

    (get, set, [ $($([$ffi: ident, $ffi_mut:ident])? $name:ident $(+ $symbol:tt)? : $type:ty ; $comment:expr );* $(;)?]) => {
        $crate::getter_setter!(get, [ $($([$ffi])? $name $(+ $symbol)? : $type ; $comment );* ]);
        $crate::getter_setter!(set, [ $($([$ffi_mut])? $name : $type ; $comment );* ]);
    };

    /* Builder pattern */
    ($([$token:tt])? with, get, set, [ $($([$ffi: ident, $ffi_mut:ident])? $name:ident $(+ $symbol:tt)? : bool ; $comment:expr );* $(;)?]) => {
        $crate::getter_setter!(get, [ $($([$ffi])? $name $(+ $symbol)? : bool ; $comment );* ]);
        $crate::getter_setter!(set, [ $($([$ffi_mut])? $name : bool ; $comment );* ]);
        $crate::getter_setter!($([$token])? with, [ $($([$ffi_mut])? $name : bool ; $comment );* ]);
    };

    ($([$token:tt])? with, get, set, [ $($([$ffi: ident, $ffi_mut:ident])? $name:ident $(+ $symbol:tt)? : $type:ty ; $comment:expr );* $(;)?]) => {
        $crate::getter_setter!(get, [ $($([$ffi])? $name $(+ $symbol)?: $type ; $comment );* ]);
        $crate::getter_setter!(set, [ $($([$ffi_mut])? $name : $type ; $comment );* ]);
        $crate::getter_setter!($([$token])? with, [ $($([$ffi_mut])? $name : $type ; $comment );* ]);
    };

    (force!, $([$token:tt])? with, get, set, [ $($([$ffi: ident, $ffi_mut:ident])? $name:ident $(+ $symbol:tt)? : $type:ty ; $comment:expr );* $(;)?]) => {
        $crate::getter_setter!(force!, get, [$($([$ffi])? $name $(+ $symbol)? : $type ; $comment );* ]);
        $crate::getter_setter!(force!, set, [$($([$ffi_mut])? $name : $type ; $comment );* ]);
        $crate::getter_setter!(force!, $([$token])? with, [$($([$ffi_mut])? $name : $type ; $comment );* ]);
    };

    ($([$token:tt])? with, get, [$( $([$ffi: ident, $ffi_mut:ident])? $((allow_mut = $allow_mut:literal))? $name:ident $(+ $symbol:tt)? : & $type:ty ; $comment:expr );* $(;)?]) => {
        $crate::getter_setter!(get, [ $($([$ffi, $ffi_mut])? $((allow_mut = $allow_mut))? $name $(+ $symbol)? : & $type ; $comment );* ]);
        $crate::getter_setter!($([$token])? with, [ $( $([$ffi_mut])? $name : $type ; $comment );* ]);
    };
}


#[doc(hidden)]
#[macro_export]
/// Constructs builder methods.
macro_rules! builder_setters {
    ($($name:ident: $type:ty $(where $generic_type:ident: $generic:path)?; $comment:expr);* $(;)?) => {
        $(
            #[doc = concat!("Set ", $comment)]
            pub fn $name$(<$generic_type: $generic>)?(mut self, value: $type) -> Self {
                self.$name = value.into();
                self
            }
        )*
    };
}

/// Helper macro for conditionally generating `# Safety` docs on mutable array slice methods.
/// When `unsafe` is passed (method is unsafe), includes the safety section.
/// When no `unsafe` is passed (method is safe), only generates the basic doc.
#[doc(hidden)]
#[macro_export]
macro_rules! array_mut_doc {
    (unsafe, $doc:literal) => {
        concat!("Mutable slice of the ", $doc, " array.\n\n# Safety\n\nDirect mutation of this array bypasses MuJoCo's internal consistency checks. The caller must ensure that all values written remain valid for MuJoCo's internal state.")
    };
    ($doc:literal) => {
        concat!("Mutable slice of the ", $doc, " array.")
    };
}

/// A macro for creating a slice over a raw array of dynamic size (given by some other variable in $len_accessor).
/// Syntax: attribute: <optional pre-transformations (e.g., `as_ptr as_mut_ptr`)> &[datatype; documentation string;
/// code to access the length attribute, appearing after `self.`]
/// Syntax for arrays whose size is a sum from some length array:
///     summed {
///         ...
///         attribute: &[datatype; documentation; [
///                 size multiplier;
///                 (code to access the length array, appearing after self);
///                 (code to access the length array's length, appearing after self)
///             ]
///         ],
///         ...
///     }
///
#[doc(hidden)]
#[macro_export]
macro_rules! array_slice_dyn {
    // Arrays that are of scalar variable size
    ($($(($unsafe_mut:ident))? $name:ident: $($as_ptr:ident $as_mut_ptr:ident)? &[$type:ty $([$force:ident])?; $doc:literal; $($len_accessor:tt)*]),*) => {
        paste::paste! {
            $(
                #[doc = concat!("Immutable slice of the ", $doc," array.")]
                pub fn [<$name:camel:snake>](&self) -> &[$type] {
                    let length = self.$($len_accessor)* as usize;
                    let ptr = $crate::maybe_force_cast!(self.ffi().$name$(.$as_ptr())?, $type $(, $force)?);
                    if ptr.is_null() || length == 0 {
                        return &[];
                    }
                    unsafe { std::slice::from_raw_parts(ptr, length) }
                }

                #[doc = $crate::array_mut_doc!($($unsafe_mut,)? $doc)]
                pub $($unsafe_mut)? fn [<$name:camel:snake _mut>](&mut self) -> &mut [$type] {
                    let length = self.$($len_accessor)* as usize;
                    let ptr = $crate::maybe_force_cast!(unsafe { self.ffi_mut().$name$(.$as_mut_ptr())? }, $type $(, $force)?);
                    if ptr.is_null() || length == 0 {
                        return &mut [];
                    }
                    unsafe { std::slice::from_raw_parts_mut(ptr, length) }
                }
            )*
        }
    };

    // Arrays that are of summed variable size
    (summed { $( $(($unsafe_mut:ident))? $name:ident: &[$type:ty; $doc:literal; [$multiplier:literal ; ($($len_array:tt)*) ; ($($len_array_length:tt)*)]]),* }) => {
        paste::paste! {
            $(
                #[doc = concat!("Immutable slice of the ", $doc," array.")]
                pub fn [<$name:camel:snake>](&self) -> &[[$type; $multiplier]] {
                    let length_array_length = self.$($len_array_length)* as usize;
                    let data_ptr = self.ffi().$name;
                    let length_ptr = self.$($len_array)*;
                    if data_ptr.is_null() || length_ptr.is_null() || length_array_length == 0 {
                        return &[];
                    }

                    let length = unsafe { std::slice::from_raw_parts(
                        length_ptr,
                        length_array_length
                    ).iter().map(|&x| x as u32).sum::<u32>() as usize };

                    if length == 0 {
                        return &[];
                    }

                    unsafe { std::slice::from_raw_parts($crate::maybe_force_cast!(data_ptr, [$type; $multiplier], force), length) }
                }
                
                #[doc = $crate::array_mut_doc!($($unsafe_mut,)? $doc)]
                pub $($unsafe_mut)? fn [<$name:camel:snake _mut>](&mut self) -> &mut [[$type; $multiplier]] {
                    let length_array_length = self.$($len_array_length)* as usize;
                    let data_ptr = unsafe { self.ffi_mut().$name };
                    let length_ptr = self.$($len_array)*;
                    if data_ptr.is_null() || length_ptr.is_null() || length_array_length == 0 {
                        return &mut [];
                    }

                    let length = unsafe { std::slice::from_raw_parts(
                        length_ptr,
                        length_array_length
                    ).iter().map(|&x| x as u32).sum::<u32>() as usize };

                    if length == 0 {
                        return &mut [];
                    }

                    unsafe { std::slice::from_raw_parts_mut($crate::maybe_force_cast!(data_ptr, [$type; $multiplier], force), length) }
                }
            )*
        }
    };

    // Arrays whose second dimension is dependent on some variable
    (sublen_dep {$( $(($unsafe_mut:ident))? $name:ident: $($as_ptr:ident $as_mut_ptr:ident)? &[[$type:ty; $($inner_len_accessor:tt)*] $([$force:ident])?; $doc:literal; $($len_accessor:tt)*]),*}) => {
        paste::paste! {
            $(
                #[doc = concat!("Immutable slice of the ", $doc," array.")]
                pub fn [<$name:camel:snake>](&self) -> &[$type] {
                    let length = self.$($len_accessor)* as usize * (self.$($inner_len_accessor)*) as usize;
                    let ptr = $crate::maybe_force_cast!(self.ffi().$name$(.$as_ptr())?, $type $(, $force)?);
                    if ptr.is_null() || length == 0 {
                        return &[];
                    }

                    unsafe { std::slice::from_raw_parts(ptr, length) }
                }

                #[doc = $crate::array_mut_doc!($($unsafe_mut,)? $doc)]
                pub $($unsafe_mut)? fn [<$name:camel:snake _mut>](&mut self) -> &mut [$type] {
                    let length = self.$($len_accessor)* as usize * (self.$($inner_len_accessor)*) as usize;
                    let ptr = $crate::maybe_force_cast!(unsafe { self.ffi_mut().$name$(.$as_mut_ptr())? }, $type $(, $force)?);
                    if ptr.is_null() || length == 0 {
                        return &mut [];
                    }
                    unsafe { std::slice::from_raw_parts_mut(ptr, length) }
                }
            )*
        }
    };
}

/// Generates getter and setter methods for converting between Rust's &str type and C's char arrays.
///
/// # Safety
/// The generated getters blindly interpret a `char` array as a C string; the
/// array must be NUL-terminated and contain valid UTF-8. Setters validate
/// ASCII encoding and will **panic** if the value exceeds the buffer length.
/// The macro works by first specifying the methods to create (get = getter, set = setter) --- c_str_as_str_method {get, set, {...}} ---
/// and then providing the rest of the parameters.
/// 
/// The rest of the parameters are recursive and are as follows:
/// - ffi (optional): name of the method that returns some lower-level struct,
///                   which contains the actual attributes we want to read;
/// - name: the attribute name;
/// - sub_index_name: sub_index_type (optional): creates an additional parameter which indexes the `name` array
///                   in order to get a sub-array
///                   (e.g., `name` could be `[[i8; 100]; 10]` and we wish to get `[i8; 100]`);
/// - comment: the documentation comment to insert as the methods documentation.
/// 
#[doc(hidden)]
#[macro_export]
macro_rules! c_str_as_str_method {
    (get {$($([$ffi:ident])? $name:ident $([$sub_index_name:ident: $sub_index_type:ty])?; $comment:literal; )*}) => {
        $(
            #[doc = concat!("Returns ", $comment, "\n\n# Panics", "\nPanics if the buffer has no NUL terminator or if the resulting string contains invalid UTF-8.")]
            pub fn $name(&self $(, $sub_index_name: $sub_index_type)? ) -> &str {
                let bytes: &[u8] = bytemuck::cast_slice(&self$(.$ffi())?.$name$([$sub_index_name])?[..]);
                std::ffi::CStr::from_bytes_until_nul(bytes)
                    .expect("no NUL terminator in C string buffer")
                    .to_str().unwrap()
            }
        )*
    };

    (set {$($([$ffi:ident])? $name:ident $([$sub_index_name:ident: $sub_index_type:ty])?; $comment:literal; )*}) => {paste::paste!{
        $(
            #[doc = concat!("Sets ", $comment, "\n\n# Panics", "\nPanics when `", stringify!($name), "` contains invalid ASCII, an interior NUL byte, or is too long.")]
            pub fn [<set_ $name>](&mut self, $($sub_index_name: $sub_index_type,)? $name: &str) {
                $crate::util::write_ascii_to_buf(
                    &mut self$(.$ffi())?.$name$([$sub_index_name])?,
                    $name,
                );
            }
        )*
    }};

    (with {$($([$ffi:ident])? $name:ident $([$sub_index_name:ident: $sub_index_type:ty])?; $comment:literal; )*}) => {paste::paste!{
        $(
            #[doc = concat!("Builder method for setting ", $comment, "\n\n# Panics", "\nPanics when `", stringify!($name), "` contains invalid ASCII, an interior NUL byte, or is too long.")]
            pub fn [<with_ $name>](mut self, $($sub_index_name: $sub_index_type,)? $name: &str) -> Self {
                $crate::util::write_ascii_to_buf(
                    &mut self$(.$ffi())?.$name$([$sub_index_name])?,
                    $name,
                );
                self
            }
        )*
    }};

    // Mixed patterns
    (with, get, set {$($other:tt)*}) => {
        $crate::c_str_as_str_method!(get {$($other)*});
        $crate::c_str_as_str_method!(set {$($other)*});
        $crate::c_str_as_str_method!(with {$($other)*});
    };

    (get, set {$($other:tt)*}) => {
        $crate::c_str_as_str_method!(get {$($other)*});
        $crate::c_str_as_str_method!(set {$($other)*});
    };

    (with, set {$($other:tt)*}) => {
        $crate::c_str_as_str_method!(set {$($other)*});
        $crate::c_str_as_str_method!(with {$($other)*});
    };

    (with, get {$($other:tt)*}) => {
        $crate::c_str_as_str_method!(get {$($other)*});
        $crate::c_str_as_str_method!(with {$($other)*});
    };
}

/// assert_eq!, but with tolerance for floating point rounding.
#[doc(hidden)]
#[macro_export]
macro_rules! assert_relative_eq {
    ($a:expr, $b:expr, epsilon = $eps:expr) => {{
        let (a, b, eps) = ($a as f64, $b as f64, $eps as f64);
        assert!((a - b).abs() <= eps, "left={:?} right={:?} eps={:?}", a, b, eps);
    }};
}


/// Tries to cast $value into requested type.
/// # Panics
/// Panics if the cast fails.
#[doc(hidden)]
#[macro_export]
macro_rules! cast_mut_info {
    ($value:expr $(, $debug_expr:expr)?) => {
        {
            match bytemuck::checked::try_cast_mut($value) {
                Ok(v) => v,
                Err(e) => {
                    let evaluated = format!("{:?}", $value);
                    #[allow(unused)]
                    let mut debug_info = String::new();
                    $(
                        debug_info = format!(" (debug info: '{} = {}')", stringify!($debug_expr), $debug_expr);
                    )?

                    panic!(
                        "failed to cast expression '{}', which evaluates to '{}' into requested type (error: {})\
                         {debug_info} --- \
                         most likely you have a bug in your program.",
                        stringify!($value), evaluated, e
                    );
                }
            }
        }
    };
}

/// Asserts that the MuJoCo version used matches
/// the one MuJoCo-rs was compiled with.
///
/// # Panics
/// Panics if the linked MuJoCo library version does not match
/// the version MuJoCo-rs was compiled against.
pub fn assert_mujoco_version() {
    // SAFETY: mj_version() is a pure query function with no side effects; safe to call at any
    // time after the library is loaded.
    let linked_version = unsafe { mj_version() as u32 };
    let mujoco_rs_version_string = option_env!("CARGO_PKG_VERSION").unwrap_or_else(|| "unknown+mj-unknown");
    assert_eq!(
        linked_version, mjVERSION_HEADER,
        "linked MuJoCo version value ({linked_version}) does not match expected version value ({mjVERSION_HEADER}), \
        with which MuJoCo-rs {mujoco_rs_version_string} FFI bindings were generated.",
    );
}


/// Forcefully casts a value of type `T` to type `U`.
/// Performs compile-time size and alignment checks, but does **not** guarantee
/// that the bit patterns are compatible.
///
/// # Safety
/// The bit pattern of `val` must be a valid representation for type `U`;
/// otherwise the behavior is undefined.
#[inline(always)]
pub unsafe fn force_cast<T, U>(val: T) -> U {
    const {
        // The underlying type should be the same in representation.
        assert!(std::mem::size_of::<T>() == std::mem::size_of::<U>());
        assert!(std::mem::align_of::<T>() == std::mem::align_of::<U>());
    }
    #[repr(C)]
    union Transmuter<T, U> {
        from: std::mem::ManuallyDrop<T>,
        to: std::mem::ManuallyDrop<U>,
    }
    // SAFETY: size and alignment equality is verified by the const assertions above; the caller
    // guarantees bit-pattern validity (see # Safety).
    unsafe { std::mem::ManuallyDrop::into_inner(Transmuter { from: std::mem::ManuallyDrop::new(val) }.to) }
}


/// Asserts at compile time that casting from `Src` to `Dst` is
/// size-and-alignment compatible.
///
/// The target element size must be a multiple of the source element size
/// (covers both same-size type conversions and array-grouping casts like
/// `*const f64` to `*const [f64; 3]`), and the source and target alignments
/// must be equal.
///
/// The pointer argument is only used for type inference of `Src`; it is
/// never dereferenced.
#[inline(always)]
pub const fn assert_ptr_cast_valid<Src, Dst>(_ptr: *const Src) {
    const {
        assert!(std::mem::size_of::<Dst>().is_multiple_of(std::mem::size_of::<Src>()),
            "ptr cast: target size must be a multiple of source size");

        // The underlying type should have the same alignment. This is for converting
        // between e.g. *f64 to *[f64; 3].
        assert!(std::mem::align_of::<Src>() == std::mem::align_of::<Dst>(),
            "ptr cast: source alignment must be == target alignment");
    }
}

/// Conditionally casts a raw pointer to `$type` with compile-time
/// size and alignment checks.  When the `force` token is absent the
/// pointer is returned as-is.
#[doc(hidden)]
#[macro_export]
macro_rules! maybe_force_cast {
    ($ptr:expr, $type:ty) => { $ptr };
    ($ptr:expr, $type:ty, force) => {{
        let ptr = $ptr;
        $crate::util::assert_ptr_cast_valid::<_, $type>(ptr as *const _);
        ptr.cast::<$type>()
    }};
}


/* Utility traits */
/// Locks a synchronization primitive and resets its poison status.
/// This is useful on locations that don't need any special handling
/// after a thread panicked while holding a mutex lock.
pub trait LockUnpoison<T> {
    /// Locks the synchronization primitive, resetting its poison status if necessary.
    fn lock_unpoison(&self) -> MutexGuard<'_, T>;
}

/// Implements automatic unpoisoning on the [`Mutex`].
impl<T> LockUnpoison<T> for Mutex<T> {
    fn lock_unpoison(&self) -> MutexGuard<'_, T> {
        match self.lock() {
            Ok(lock) => lock,
            Err(e) => {
                self.clear_poison();
                e.into_inner()
            }
        }
    }
}

#[cfg(feature = "viewer")]
/// Performs a three-way merge of a value.
///
/// Given three versions of a value (`self`, `other`, `other_prev`), the merge
/// updates `self` when `other` has changed relative to `other_prev`, then
/// writes the resolved value back into both `other` and `other_prev` so the
/// next call starts from a consistent baseline.
pub(crate) trait ThreeWayMerge {
    /// Merges `other` into `self` using `other_prev` as the baseline.
    fn merge(&mut self, other: &mut Self, other_prev: &mut Self);
}

#[cfg(feature = "viewer")]
impl<T: Copy + PartialEq> ThreeWayMerge for T {
    #[inline]
    fn merge(&mut self, other: &mut Self, other_prev: &mut Self) {
        if *other != *other_prev {
            *self = *other;
        }

        *other = *self;
        *other_prev = *other;
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Mutex};
    use std::ffi::c_char;
    use super::LockUnpoison;

    /// Verifies that `lock_unpoison` recovers a poisoned mutex and preserves the inner value.
    #[test]
    fn test_lock_unpoison_recovers_poisoned_mutex() {
        let mutex = Arc::new(Mutex::new(42_i32));
        let mutex_clone = Arc::clone(&mutex);

        // Panic while holding the lock to poison it.
        let _ = std::panic::catch_unwind(move || {
            let _guard = mutex_clone.lock().unwrap();
            panic!("intentional panic to poison mutex");
        });

        // The mutex must be poisoned now.
        assert!(mutex.lock().is_err(), "mutex should be poisoned");

        // lock_unpoison must recover the lock and preserve the value.
        let value = *mutex.lock_unpoison();
        assert_eq!(value, 42, "inner value must be preserved after unpoison");

        // After unpoison, regular lock must succeed.
        assert!(mutex.lock().is_ok(), "mutex should no longer be poisoned");
    }

    /// Exercises the three "dead" combination arms of `getter_setter!` (arms 11, 12, 13)
    /// by instantiating each on a minimal dummy struct.
    ///
    /// - Arm 11: `(force!, get, set, [...])` -- force-cast getter + setter.
    /// - Arm 12: `(get, set, [... : bool ...])` -- bool getter (field `== 1`) + setter.
    /// - Arm 13: `(get, set, [... : $type ...])` -- `.into()` getter + setter.
    #[test]
    fn test_getter_setter_dead_arms_11_12_13() {
        struct ArmEleven { x: i32, y: i32 }
        impl ArmEleven {
            crate::getter_setter!(force!, get, set, [x: i32; "x field."; y: i32; "y field.";]);
        }

        struct ArmTwelve { flag: i32 }
        impl ArmTwelve {
            crate::getter_setter!(get, set, [flag: bool; "flag field.";]);
        }

        struct ArmThirteen { count: i32 }
        impl ArmThirteen {
            crate::getter_setter!(get, set, [count: i32; "count field.";]);
        }

        let mut arm11 = ArmEleven { x: 3, y: 7 };
        assert_eq!(arm11.x(), 3);
        assert_eq!(arm11.y(), 7);
        arm11.set_x(9);
        assert_eq!(arm11.x(), 9);
        arm11.set_y(10);
        assert_eq!(arm11.y(), 10);

        let mut arm12 = ArmTwelve { flag: 1 };
        assert!(arm12.flag());
        arm12.set_flag(false);
        assert!(!arm12.flag());

        let mut arm13 = ArmThirteen { count: 5 };
        assert_eq!(arm13.count(), 5);
        arm13.set_count(10);
        assert_eq!(arm13.count(), 10);
    }

    /// Tests both arms of `cast_mut_info!`: without and with the optional debug expression.
    #[test]
    fn test_cast_mut_info_both_arms() {
        let mut val: [u8; 4] = [7, 0, 0, 0];

        // Without debug expression.
        let r: &mut [u8; 4] = crate::cast_mut_info!(&mut val);
        r[0] = 42;
        assert_eq!(val[0], 42);

        // With debug expression.
        let idx: usize = 0;
        let r2: &mut [u8; 4] = crate::cast_mut_info!(&mut val, idx);
        r2[0] = 99;
        assert_eq!(val[0], 99);
    }

    /// Tests the three combination arms of `c_str_as_str_method!` that are never
    /// used in production code: `(get, set)` (arm 5), `(with, set)` (arm 6),
    /// and `(with, get)` (arm 7).
    #[test]
    fn test_c_str_as_str_method_combination_arms() {
        // arm 5: (get, set) -- getter + setter, no builder.
        struct GetSet { name: [c_char; 16] }
        impl GetSet {
            crate::c_str_as_str_method!(get, set { name; "name."; });
        }

        // arm 6: (with, set) -- setter + builder, no getter.
        struct WithSet { label: [c_char; 16] }
        impl WithSet {
            crate::c_str_as_str_method!(with, set { label; "label."; });
        }

        // arm 7: (with, get) -- getter + builder, no setter.
        struct WithGet { title: [c_char; 16] }
        impl WithGet {
            crate::c_str_as_str_method!(with, get { title; "title."; });
        }

        // arm 5: set then get.
        let mut gs = GetSet { name: [0; 16] };
        gs.set_name("hello");
        assert_eq!(gs.name(), "hello");

        // arm 6: with_ builder; raw bytes confirm the write.
        let ws = WithSet { label: [0; 16] }.with_label("world");
        let bytes: &[u8] = bytemuck::cast_slice(&ws.label[..]);
        assert!(bytes.starts_with(b"world\0"), "with_label did not write label");
        // arm 6 setter path.
        let mut ws2 = WithSet { label: [0; 16] };
        ws2.set_label("bye");
        let bytes2: &[u8] = bytemuck::cast_slice(&ws2.label[..]);
        assert!(bytes2.starts_with(b"bye\0"), "set_label did not write label");

        // arm 7: with_ builder then getter.
        let wg = WithGet { title: [0; 16] }.with_title("foo");
        assert_eq!(wg.title(), "foo");
    }
}