nsi-ffi-wrap 0.9.0

FFI wrapper and macro for NSI-compliant renderers – ɴsɪ.
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
//! Optional arguments passed to methods of an ɴsɪ context.
use enum_dispatch::enum_dispatch;
use nsi_sys::*;
use std::{
    ffi::{CString, c_void},
    marker::PhantomData,
    pin::Pin,
};
use ustr::{Ustr, ustr};

// Needed for docs.
#[allow(unused_imports)]
use crate::*;

#[inline(always)]
pub(crate) fn get_c_param_vec(
    args: Option<&ArgSlice>,
) -> (i32, *const NSIParam, Vec<NSIParam>) {
    let args = match args {
        Some(args) => args
            .iter()
            .map(|arg| NSIParam {
                name: arg.name.as_char_ptr(),
                data: arg.data.as_c_ptr(),
                type_: arg.data.type_() as _,
                arraylength: arg.array_length as _,
                count: (arg.data.len() / arg.array_length) as _,
                flags: arg.flags as _,
            })
            .collect::<Vec<_>>(),
        None => Vec::new(),
    };

    (args.len() as _, args.as_ptr(), args)
}

/// A slice of (optional) arguments passed to a method of
/// [`Context`].
pub type ArgSlice<'a, 'b> = [Arg<'a, 'b>];

/// A vector of (optional) arguments passed to a method of
/// [`Context`].
pub type ArgVec<'a, 'b> = Vec<Arg<'a, 'b>>;

/// An (optional) argument passed to a method of
/// [`Context`].
#[derive(Debug, Clone)]
pub struct Arg<'a, 'b> {
    pub(crate) name: Ustr,
    pub(crate) data: ArgData<'a, 'b>,
    // Length of each element if an array type.
    pub(crate) array_length: usize,
    // Number of elements.
    pub(crate) flags: i32,
}

impl<'a, 'b> Arg<'a, 'b> {
    #[inline]
    pub fn new(name: &str, data: ArgData<'a, 'b>) -> Self {
        Arg {
            name: ustr(name),
            data,
            array_length: 1,
            flags: 0,
        }
    }

    /// Sets the length of the argument for each element.
    #[inline]
    pub fn array_len(mut self, length: usize) -> Self {
        self.array_length = length;
        self.flags |= NSIParamFlags::IsArray.bits();
        self
    }

    /// Marks this argument as having per-face granularity.
    #[inline]
    pub fn per_face(mut self) -> Self {
        self.flags |= NSIParamFlags::PerFace.bits();
        self
    }

    /// Marks this argument as having per-vertex granularity.
    #[inline]
    pub fn per_vertex(mut self) -> Self {
        self.flags |= NSIParamFlags::PerVertex.bits();
        self
    }

    /// Marks this argument as to be interpolated linearly.
    #[inline]
    pub fn linear_interpolation(mut self) -> Self {
        self.flags |= NSIParamFlags::InterpolateLinear.bits();
        self
    }
}

#[enum_dispatch(ArgData)]
pub(crate) trait ArgDataMethods {
    //const TYPE: DataType;
    fn type_(&self) -> DataType;
    fn len(&self) -> usize;
    fn as_c_ptr(&self) -> *const c_void;
}

/// A variant describing data passed to the renderer.
///
/// # Lifetimes
/// Lifetime `'a` is for any tuple or array type as these are
/// passed as references and only need to live as long as the
/// function call where they get passed.
///
/// Lifetime `'b` is for the arbitrary reference type. This is
/// pegged to the lifetime of the [`Context`](crate::context::Context).
/// Use this to pass arbitrary Rust data through the FFI boundary.
#[enum_dispatch]
#[derive(Debug, Clone)]
pub enum ArgData<'a, 'b> {
    /// Single [`f32`] value.
    F32,
    /// An [`f32`] slice.
    F32Slice(F32Slice<'a>),
    /// Single [`f64`] value.
    F64,
    /// An [`f64`] slice.
    F64Slice(F64Slice<'a>),
    /// Single [`i32`] value.
    I32,
    /// An [`i32`] slice.
    I32Slice(I32Slice<'a>),
    /// Single [`i64`] value.
    I64,
    /// An [`i64`] slice.
    I64Slice(I64Slice<'a>),
    /// A [`String`].
    String(String),
    /// A [`String`] slice.
    StringSlice(StringSlice),
    /// Color in linear space, given as a red, green, blue triplet
    /// of [`f32`] values; usually in the range `0..1`.
    Color(Color<'a>),
    /// A flat [`f32`] slice of colors (`len % 3 == 0`).
    ColorSlice(ColorSlice<'a>),
    /// Point, given as three [`f32`] values.
    Point(Point<'a>),
    /// A flat [`f32`] slice of points (`len % 3 == 0`).
    PointSlice(PointSlice<'a>),
    /// Vector, given as three [`f32`] values.
    Vector(Vector<'a>),
    /// A flat [`f32`] slice of vectors (`len % 3 == 0`).
    VectorSlice(VectorSlice<'a>),
    /// Normal vector, given as three [`f32`] values.
    Normal(Normal<'a>),
    /// A flat [`f32`] slice of normals (`len % 3 == 0`).
    NormalSlice(NormalSlice<'a>),
    /// Row-major, 4×4 transformation matrix, given as 16 [`f32`] values.
    MatrixF32(MatrixF32<'a>),
    /// A flat [`f32`] slice of matrices (`len % 16 == 0`).
    MatrixF32Slice(MatrixF32Slice<'a>),
    /// Row-major, 4×4 transformation matrix, given as 16 [`f64`] values.
    MatrixF64(MatrixF64<'a>),
    /// A flat [`f64`] slice of matrices (`len % 16 == 0`).
    MatrixF64Slice(MatrixF64Slice<'a>),
    /// A slice of 4-component f32 points (xyzw).
    /// Wire-side: a flat `NSITypeFloat` slice of `4 * N` floats — the
    /// renderer groups them by attribute semantics. Use the
    /// [`point4_f32_slice!`][crate::point4_f32_slice] macro to keep
    /// `&[[f32; 4]]` ergonomics in Rust while the FFI sees the flat
    /// layout.
    Point4F32Slice(Point4F32Slice<'a>),
    /// Reference *with* lifetime guarantees.
    ///
    /// This gets converted to a raw pointer when passed
    /// through the FFI boundary.
    ///
    /// ```
    /// # use nsi_ffi_wrap as nsi;
    /// let ctx = nsi::Context::new(None).unwrap();
    ///
    /// // Lots of scene setup omitted ...
    ///
    /// // Setup a custom output driver and send
    /// // a payload to it through the FFI boundary.
    /// ctx.create("driver", nsi::OUTPUT_DRIVER, None);
    /// ctx.connect("driver", None, "beauty", "outputdrivers", None);
    ///
    /// struct Payload {
    ///     some_data: u32,
    /// }
    ///
    /// // Must use heap allocation for stable address
    /// let payload = Box::new(Payload { some_data: 42 });
    /// ctx.set_attribute(
    ///     "driver",
    ///     &[
    ///         nsi::string!("drivername", "custom_driver"),
    ///         // Payload gets sent as raw pointer through
    ///         // the FFI boundary. The Box ensures stable address.
    ///         nsi::reference!("payload", &payload),
    ///     ],
    /// );
    ///
    /// // We need to explicitly call drop here as
    /// // ctx's lifetime is pegged to that of payload.
    /// drop(ctx);
    /// ```
    Reference(Reference<'b>),
    /// A [`Reference`] slice.
    ReferenceSlice(ReferenceSlice<'b>),
    /// A callback.
    Callback(Callback<'b>),
}

macro_rules! nsi_data_def {
    ($type: ty, $name: ident, $nsi_type: expr) => {
        /// See [`ArgData`] for details.
        #[derive(Debug, Clone, PartialEq)]
        pub struct $name {
            data: $type,
        }

        impl $name {
            pub fn new(data: $type) -> Self {
                Self { data }
            }
        }

        impl ArgDataMethods for $name {
            fn type_(&self) -> DataType {
                $nsi_type
            }

            fn len(&self) -> usize {
                1
            }

            fn as_c_ptr(&self) -> *const c_void {
                &self.data as *const $type as _
            }
        }
    };
}

macro_rules! nsi_data_array_def {
    ($type: ty, $name: ident, $nsi_type: expr) => {
        /// See [`ArgData`] for details.
        #[derive(Debug, Clone, PartialEq)]
        pub struct $name<'a> {
            data: &'a [$type],
        }

        impl<'a> $name<'a> {
            pub fn new(data: &'a [$type]) -> Self {
                //debug_assert_eq!(0, data.len() % $nsi_type.elemensize());
                Self { data }
            }
        }

        impl<'a> ArgDataMethods for $name<'a> {
            fn type_(&self) -> DataType {
                $nsi_type
            }

            fn len(&self) -> usize {
                self.data.len() // / $nsi_type.elemensize()
            }

            fn as_c_ptr(&self) -> *const c_void {
                self.data.as_ptr() as _
            }
        }
    };
}

macro_rules! nsi_tuple_data_array_def {
    ($type: ty, $name: ident, $nsi_type: expr, $len: expr ) => {
        /// See [`ArgData`] for details.
        #[derive(Debug, Clone, PartialEq)]
        pub struct $name<'a> {
            data: &'a [[$type; $len]],
        }

        impl<'a> $name<'a> {
            pub fn new(data: &'a [[$type; $len]]) -> Self {
                //debug_assert_eq!(0, data.len() % $nsi_type.elemensize());
                Self { data }
            }
        }

        impl<'a> ArgDataMethods for $name<'a> {
            fn type_(&self) -> DataType {
                $nsi_type
            }

            fn len(&self) -> usize {
                self.data.len() // / $nsi_type.elemensize()
            }

            fn as_c_ptr(&self) -> *const c_void {
                self.data.as_ptr() as _
            }
        }
    };
}

macro_rules! nsi_tuple_data_def {
    ($type: tt, $len: expr, $name: ident, $nsi_type: expr) => {
        /// See [`ArgData`] for details.
        #[derive(Debug, Clone, PartialEq)]
        pub struct $name<'a> {
            data: &'a [$type; $len],
        }

        impl<'a> $name<'a> {
            pub fn new(data: &'a [$type; $len]) -> Self {
                Self { data }
            }
        }

        impl<'a> ArgDataMethods for $name<'a> {
            fn type_(&self) -> DataType {
                $nsi_type
            }

            fn len(&self) -> usize {
                1
            }

            fn as_c_ptr(&self) -> *const c_void {
                self.data.as_ptr() as _
            }
        }
    };
}

nsi_data_def!(f32, F32, DataType::F32);
nsi_data_def!(f64, F64, DataType::F64);
nsi_data_def!(i32, I32, DataType::I32);
nsi_data_def!(i64, I64, DataType::I64);

/// See [`ArgData`] for details.
/// A reference to data that will be passed through FFI.
///
/// # Safety
/// The referenced data must outlive the NSI context that uses this reference.
/// The data must remain at a stable memory address.
///
/// This type now properly enforces pinning by requiring heap-allocated data
/// through Box, Arc, or similar types that guarantee stable addresses.
#[derive(Debug, Clone)]
pub struct Reference<'a> {
    data: *const c_void,
    _marker: PhantomData<&'a ()>,
}

// SAFETY: Reference only contains a pointer and doesn't dereference it.
// The actual safety depends on the lifetime parameter being correct.
unsafe impl Send for Reference<'static> {}
unsafe impl Sync for Reference<'static> {}

/// Trait for types that can be safely converted to a Reference.
/// This is implemented only for types that guarantee stable memory addresses.
pub trait StableDeref<'a> {
    /// Get a stable pointer to the data
    fn stable_deref(&self) -> *const c_void;
}

impl<'a, T: ?Sized> StableDeref<'a> for &'a Box<T> {
    fn stable_deref(&self) -> *const c_void {
        self.as_ref() as *const T as *const c_void
    }
}

impl<'a, T: ?Sized> StableDeref<'a> for &'a Arc<T> {
    fn stable_deref(&self) -> *const c_void {
        self.as_ref() as *const T as *const c_void
    }
}

impl<'a, T: ?Sized> StableDeref<'a> for &'a Pin<Box<T>> {
    fn stable_deref(&self) -> *const c_void {
        self.as_ref().get_ref() as *const T as *const c_void
    }
}

use std::sync::Arc;

impl<'a> Reference<'a> {
    /// Create a reference from any type that implements StableDeref.
    /// This includes &Box<T>, &Arc<T>, and &Pin<Box<T>>.
    pub fn new<S: StableDeref<'a>>(data: S) -> Self {
        let ptr = data.stable_deref();
        debug_assert!(!ptr.is_null(), "Reference created with null pointer");

        Self {
            data: ptr,
            _marker: PhantomData,
        }
    }

    /// Create a reference from a Box.
    ///
    /// Box guarantees a stable heap address, making it safe for FFI.
    #[allow(clippy::borrowed_box)]
    pub fn from_box<T: ?Sized>(data: &'a Box<T>) -> Self {
        let ptr = data.as_ref() as *const T as *const c_void;
        debug_assert!(!ptr.is_null(), "Reference created with null pointer");

        Self {
            data: ptr,
            _marker: PhantomData,
        }
    }

    /// Create a reference from an Arc.
    ///
    /// Arc guarantees a stable heap address, making it safe for FFI.
    pub fn from_arc<T: ?Sized>(data: &'a Arc<T>) -> Self {
        let ptr = data.as_ref() as *const T as *const c_void;
        debug_assert!(!ptr.is_null(), "Reference created with null pointer");

        Self {
            data: ptr,
            _marker: PhantomData,
        }
    }

    /// Create a reference from a pinned Box.
    ///
    /// This is the safest option as it guarantees the data cannot be moved.
    pub fn from_pin_box<T: ?Sized>(data: &'a Pin<Box<T>>) -> Self {
        let ptr = data.as_ref().get_ref() as *const T as *const c_void;
        debug_assert!(!ptr.is_null(), "Reference created with null pointer");

        Self {
            data: ptr,
            _marker: PhantomData,
        }
    }

    /// Create a reference from data with a stable address.
    ///
    /// # Safety
    /// The caller must guarantee that `data` has a stable address for its entire
    /// lifetime. This is automatically true for:
    /// - Heap allocated types (Box, Arc, Vec's data, String's data)
    /// - Static data
    /// - Pinned data
    ///
    /// This is NOT safe for:
    /// - Stack allocated data that might move
    /// - Data inside collections that might reallocate
    pub unsafe fn from_stable<T: ?Sized>(data: &'a T) -> Self {
        let ptr = data as *const T as *const c_void;
        debug_assert!(!ptr.is_null(), "Reference created with null pointer");

        Self {
            data: ptr,
            _marker: PhantomData,
        }
    }

    /// Create a reference from a raw pointer.
    ///
    /// # Safety
    /// The caller must ensure that:
    /// 1. The pointer is valid and non-null
    /// 2. The pointed-to data outlives 'a
    /// 3. The data won't be moved or freed while this reference exists
    pub unsafe fn from_ptr(ptr: *const c_void) -> Self {
        debug_assert!(!ptr.is_null(), "Reference created with null pointer");
        Self {
            data: ptr,
            _marker: PhantomData,
        }
    }
}

impl<'a> ArgDataMethods for Reference<'a> {
    fn type_(&self) -> DataType {
        DataType::Reference
    }

    fn len(&self) -> usize {
        1
    }

    fn as_c_ptr(&self) -> *const c_void {
        self.data
    }
}

pub trait CallbackPtr {
    #[doc(hidden)]
    #[allow(clippy::wrong_self_convention)]
    fn to_ptr(self) -> *const c_void;
}

unsafe impl Send for Callback<'static> {}
unsafe impl Sync for Callback<'static> {}

/// See [`ArgData`] for details.
#[derive(Debug, Clone)]
pub struct Callback<'a> {
    data: *const c_void,
    _marker: PhantomData<&'a mut ()>,
}

impl<'a> Callback<'a> {
    pub fn new<T: CallbackPtr>(data: T) -> Self {
        Self {
            data: data.to_ptr(),
            _marker: PhantomData,
        }
    }
}

impl<'a> ArgDataMethods for Callback<'a> {
    fn type_(&self) -> DataType {
        DataType::Reference
    }

    fn len(&self) -> usize {
        1
    }

    fn as_c_ptr(&self) -> *const c_void {
        self.data
    }
}

/// See [`ArgData`] for details.
#[derive(Debug, Clone)]
pub struct String {
    #[allow(dead_code)]
    data: CString,
    // The FFI API needs a pointer to a C string.
    pointer: *const c_void,
}

unsafe impl Send for String {}
unsafe impl Sync for String {}

impl String {
    pub fn new<T: Into<Vec<u8>>>(data: T) -> Self {
        let data = CString::new(data).unwrap();
        let pointer = data.as_ptr() as _;

        String { data, pointer }
    }
}

impl ArgDataMethods for String {
    fn type_(&self) -> DataType {
        DataType::String
    }

    fn len(&self) -> usize {
        1
    }

    fn as_c_ptr(&self) -> *const c_void {
        &self.pointer as *const *const c_void as _
    }
}

nsi_data_array_def!(f32, F32Slice, DataType::F32);
nsi_data_array_def!(f64, F64Slice, DataType::F64);
nsi_data_array_def!(i32, I32Slice, DataType::I32);
nsi_data_array_def!(i64, I64Slice, DataType::I64);
nsi_tuple_data_array_def!(f32, ColorSlice, DataType::Color, 3);
nsi_tuple_data_array_def!(f32, PointSlice, DataType::Point, 3);
nsi_tuple_data_array_def!(f32, VectorSlice, DataType::Vector, 3);
nsi_tuple_data_array_def!(f32, NormalSlice, DataType::Normal, 3);
nsi_tuple_data_array_def!(f32, MatrixF32Slice, DataType::MatrixF32, 16);
nsi_tuple_data_array_def!(f64, MatrixF64Slice, DataType::MatrixF64, 16);

/// Slice of weighted (rational) homogeneous 4-component f32 control points
/// — backing for [`point4_f32_slice!`][crate::point4_f32_slice] (NURBS
/// rational positions `Pw`, RGBA-style colour-with-alpha attributes, etc.).
///
/// On the wire this is a flat `NSITypeFloat` slice — the renderer infers
/// the 4-component grouping from the attribute name (`Pw`). The wrapper
/// exists so callers can keep the natural `&[[f32; 4]]` shape in Rust
/// while the FFI sees `4 * N` flat floats.
#[derive(Debug, Clone, PartialEq)]
pub struct Point4F32Slice<'a> {
    data: &'a [[f32; 4]],
}

impl<'a> Point4F32Slice<'a> {
    pub fn new(data: &'a [[f32; 4]]) -> Self {
        Self { data }
    }
}

impl<'a> ArgDataMethods for Point4F32Slice<'a> {
    fn type_(&self) -> DataType {
        DataType::F32
    }

    /// Total flat `f32` count = `4 * number-of-points`. With the
    /// default `arraylength = 1` the renderer receives that many
    /// scalar floats and groups them by attribute semantics.
    fn len(&self) -> usize {
        self.data.len() * 4
    }

    fn as_c_ptr(&self) -> *const c_void {
        self.data.as_ptr() as _
    }
}

/// See [`ArgData`] for details.
#[derive(Debug, Clone)]
pub struct ReferenceSlice<'a> {
    data: Vec<*const c_void>,
    _marker: PhantomData<&'a ()>,
}

unsafe impl Send for ReferenceSlice<'static> {}
unsafe impl Sync for ReferenceSlice<'static> {}

impl<'a> ReferenceSlice<'a> {
    pub fn new<T>(data: &'a [&'a T]) -> Self {
        debug_assert_eq!(0, data.len() % DataType::Reference.elemensize());

        Self {
            data: data.iter().map(|r| r as *const _ as _).collect(),
            _marker: PhantomData,
        }
    }
}

impl<'a> ArgDataMethods for ReferenceSlice<'a> {
    fn type_(&self) -> DataType {
        DataType::Reference
    }

    fn len(&self) -> usize {
        self.data.len() / DataType::Reference.elemensize()
    }

    fn as_c_ptr(&self) -> *const c_void {
        self.data.as_ptr() as _
    }
}

/// See [`ArgData`] for details.
#[derive(Debug, Clone)]
pub struct StringSlice {
    #[allow(dead_code)]
    data: Vec<CString>,
    pointer: Vec<*const c_void>,
}

unsafe impl Send for StringSlice {}
unsafe impl Sync for StringSlice {}

impl StringSlice {
    pub fn new<T: Into<Vec<u8>> + Copy>(data: &[T]) -> Self {
        let data = data
            .iter()
            .map(|s| CString::new(*s).unwrap())
            .collect::<Vec<_>>();
        let pointer = data.iter().map(|s| s.as_ptr() as _).collect();

        StringSlice { data, pointer }
    }
}

impl ArgDataMethods for StringSlice {
    fn type_(&self) -> DataType {
        DataType::String
    }

    fn len(&self) -> usize {
        self.pointer.len()
    }

    fn as_c_ptr(&self) -> *const c_void {
        self.pointer.as_ptr() as _
    }
}

nsi_tuple_data_def!(f32, 3, Color, DataType::Color);
nsi_tuple_data_def!(f32, 3, Point, DataType::Point);
nsi_tuple_data_def!(f32, 3, Vector, DataType::Vector);
nsi_tuple_data_def!(f32, 3, Normal, DataType::Normal);
nsi_tuple_data_def!(f32, 16, MatrixF32, DataType::MatrixF32);
nsi_tuple_data_def!(f64, 16, MatrixF64, DataType::MatrixF64);

/// Identifies an [`Arg`]’s data type.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[repr(i32)]
pub(crate) enum DataType {
    /// A single [`f32`] value.
    F32 = NSIType::F32 as _,
    /// A single [`f64`] value.
    F64 = NSIType::F64 as _,
    /// Single [`i32`] value.
    I32 = NSIType::I32 as _,
    /// Single [`i64`] value.
    I64 = NSIType::I64 as _,
    /// A [`String`].
    String = NSIType::String as _,
    /// Color, given as three [`f32`] values,
    /// usually in the range `0..1`. Red would e.g. be `[1.0, 0.0,
    /// 0.0]. Assumed to be in a linear color space.`
    Color = NSIType::Color as _,
    /// Point, given as three [`f32`] values.
    Point = NSIType::Point as _,
    /// Vector, given as three [`f32`] values.
    Vector = NSIType::Vector as _,
    /// Normal vector, given as three [`f32`] values.
    Normal = NSIType::Normal as _,
    /// Transformation matrix, given as 16 [`f32`] values.
    MatrixF32 = NSIType::MatrixF32 as _,
    /// Transformation matrix, given as 16 [`f64`] values.
    MatrixF64 = NSIType::MatrixF64 as _,
    /// Raw (`*const T`) pointer.
    Reference = NSIType::Pointer as _,
}

impl DataType {
    /// Returns the number of components of the resp. type.
    #[inline]
    pub(crate) fn elemensize(&self) -> usize {
        match self {
            DataType::F32 => 1,
            DataType::F64 => 1,
            DataType::I32 => 1,
            DataType::I64 => 1,
            DataType::String => 1,
            DataType::Color => 3,
            DataType::Point => 3,
            DataType::Vector => 3,
            DataType::Normal => 3,
            DataType::MatrixF32 => 16,
            DataType::MatrixF64 => 16,
            DataType::Reference => 1,
        }
    }
}

/// Create a [`F32`] argument.
///
/// Name accepts a string literal (escape hatch) or a typed
/// [`Attribute<f32>`](crate::Attribute) / [`Parameter<f32>`](crate::Parameter)
/// constant (compile-time type-checked).
#[macro_export]
macro_rules! f32 {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::F32::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<f32> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::F32::new($value)),
        )
    }};
}

/// Create a [`F32Slice`] array argument.
///
/// Name accepts a string literal or a typed
/// [`Attribute<[f32]>`](crate::Attribute) constant.
#[macro_export]
macro_rules! f32_slice {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::F32Slice::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<[f32]> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::F32Slice::new($value)),
        )
    }};
}

/// Create a [`F64`] precision argument.
///
/// Name accepts a string literal or a typed
/// [`Attribute<f64>`](crate::Attribute) constant.
#[macro_export]
macro_rules! f64 {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::F64::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<f64> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::F64::new($value)),
        )
    }};
}

/// Create a [`F64Slice`] precision array argument.
///
/// Name accepts a string literal or a typed
/// [`Attribute<[f64]>`](crate::Attribute) constant.
#[macro_export]
macro_rules! f64_slice {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::F64Slice::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<[f64]> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::F64Slice::new($value)),
        )
    }};
}

/// Create a [`I32`] argument.
///
/// Name accepts a string literal or a typed
/// [`Attribute<i32>`](crate::Attribute) constant.
#[macro_export]
macro_rules! i32 {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::I32::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<i32> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::I32::new($value)),
        )
    }};
}

/// Create a [`I32Slice`] array argument.
///
/// Name accepts a string literal or a typed
/// [`Attribute<[i32]>`](crate::Attribute) constant.
#[macro_export]
macro_rules! i32_slice {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::I32Slice::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<[i32]> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::I32Slice::new($value)),
        )
    }};
}

/// Create a [`I64`] argument.
///
/// Name accepts a string literal or a typed
/// [`Attribute<i64>`](crate::Attribute) constant.
#[macro_export]
macro_rules! i64 {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::I64::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<i64> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::I64::new($value)),
        )
    }};
}

/// Create a [`I64Slice`] array argument.
///
/// Name accepts a string literal or a typed
/// [`Attribute<[i64]>`](crate::Attribute) constant.
#[macro_export]
macro_rules! i64_slice {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::I64Slice::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<[i64]> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::I64Slice::new($value)),
        )
    }};
}

/// Create a [`Color`] argument.
///
/// Name accepts a string literal or a typed
/// [`Attribute<Color3F32>`](crate::Attribute) constant.
#[macro_export]
macro_rules! color {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::Color::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<$crate::Color3F32> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::Color::new($value)),
        )
    }};
}

/// Create a [`ColorSlice`] array argument.
///
/// Name accepts a string literal or a typed
/// [`Attribute<[Color3F32]>`](crate::Attribute) constant.
#[macro_export]
macro_rules! color_slice {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::ColorSlice::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<[$crate::Color3F32]> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::ColorSlice::new($value)),
        )
    }};
}

/// Create a [`Point`] argument.
///
/// Name accepts a string literal or a typed
/// [`Attribute<Point3F32>`](crate::Attribute) constant.
#[macro_export]
macro_rules! point {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::Point::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<$crate::Point3F32> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::Point::new($value)),
        )
    }};
}

/// Create a [`PointSlice`] array argument.
///
/// First argument may be either:
/// * a string literal (escape hatch — no static check), or
/// * a typed name constant of type [`Attribute<[Point3F32]>`](crate::Attribute) /
///   [`Parameter<[Point3F32]>`](crate::Parameter) (compile-time type-checked).
#[macro_export]
macro_rules! point_slice {
    // String-literal name -- legacy / escape hatch (no type check).
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::PointSlice::new($value)))
    };
    // Typed Attribute<[Point3F32]> path -- compile-time type-checked.
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<[$crate::Point3F32]> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::PointSlice::new($value)),
        )
    }};
}

/// Create a slice-of-4-component-f32-points argument.
///
/// Wraps a `&[[f32; 4]]` (e.g. weighted homogeneous control points
/// `Pw` for NURBS, RGBA colour-with-alpha attributes, or any other
/// 4-float-per-element vertex datum) and sends it as a **flat**
/// `NSITypeFloat` slice — the renderer groups the floats into
/// 4-tuples by attribute name, analogous to how `uknot`/`vknot` are
/// flat float slices.
///
/// Name accepts:
/// * a string literal (escape hatch — no static check), or
/// * a typed name constant of type
///   [`Attribute<[Point4F32]>`](crate::Attribute) / [`Parameter<[Point4F32]>`](crate::Parameter)
///   (compile-time type-checked, e.g. [`WEIGHTED_POSITION`](crate::WEIGHTED_POSITION)).
#[macro_export]
macro_rules! point4_f32_slice {
    // String-literal name — legacy / escape hatch (no type check).
    ($name: literal, $value: expr) => {
        nsi::Arg::new(
            $name,
            nsi::ArgData::from(nsi::Point4F32Slice::new($value)),
        )
    };
    // Typed Attribute<[Point4F32]> path — compile-time type-checked.
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<[$crate::Point4F32]> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::Point4F32Slice::new($value)),
        )
    }};
}

/// Create a [`Vector`] argument.
///
/// Name accepts a string literal or a typed
/// [`Attribute<Vector3F32>`](crate::Attribute) constant.
#[macro_export]
macro_rules! vector {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::Vector::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<$crate::Vector3F32> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::Vector::new($value)),
        )
    }};
}

/// Create a [`VectorSlice`] array argument.
///
/// Name accepts a string literal or a typed
/// [`Attribute<[Vector3F32]>`](crate::Attribute) constant.
#[macro_export]
macro_rules! vector_slice {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::VectorSlice::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<[$crate::Vector3F32]> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::VectorSlice::new($value)),
        )
    }};
}

/// Create a [`Normal`] argument.
///
/// Name accepts a string literal or a typed
/// [`Attribute<Normal3F32>`](crate::Attribute) constant.
#[macro_export]
macro_rules! normal {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::Normal::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<$crate::Normal3F32> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::Normal::new($value)),
        )
    }};
}

/// Create a [`NormalSlice`] array argument.
///
/// Name accepts a string literal or a typed
/// [`Attribute<[Normal3F32]>`](crate::Attribute) constant.
#[macro_export]
macro_rules! normal_slice {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::NormalSlice::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<[$crate::Normal3F32]> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::NormalSlice::new($value)),
        )
    }};
}

/// Create a [`MatrixF32`] row-major, 4×4 transformation matrix argument.
/// The matrix is given as 16 [`f32`] values.
///
/// Name accepts a string literal or a typed
/// [`Attribute<Matrix4F32>`](crate::Attribute) constant.
#[macro_export]
macro_rules! matrix_f32 {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::MatrixF32::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<$crate::Matrix4F32> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::MatrixF32::new($value)),
        )
    }};
}

/// Create a [`MatrixF32Slice`] row-major, 4×4 transformation matrices argument.
/// Each matrix is given as 16 [`f32`] values.
///
/// Name accepts a string literal or a typed
/// [`Attribute<[Matrix4F32]>`](crate::Attribute) constant.
#[macro_export]
macro_rules! matrix_f32_slice {
    ($name: literal, $value: expr) => {
        nsi::Arg::new(
            $name,
            nsi::ArgData::from(nsi::MatrixF32Slice::new($value)),
        )
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<[$crate::Matrix4F32]> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::MatrixF32Slice::new($value)),
        )
    }};
}

/// Create a [`MatrixF64`] row-major, 4×4 transformation matrix argument.
/// The matrix is given as 16 [`f64`] values.
///
/// # Examples
///
/// ```
/// # use nsi_ffi_wrap as nsi;
/// # let ctx = nsi::Context::new(None).unwrap();
/// // Setup a transform node.
/// ctx.create("xform", nsi::TRANSFORM, None);
/// ctx.connect("xform", None, nsi::ROOT, "objects", None);
///
/// // Translate 5 units along z-axis.
/// ctx.set_attribute(
///     "xform",
///     &[nsi::matrix_f64!(
///         "transformationmatrix",
///         &[
///             1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 5., 1.,
///         ]
///     )],
/// );
/// ```
#[macro_export]
macro_rules! matrix_f64 {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::MatrixF64::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<$crate::Matrix4F64> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::MatrixF64::new($value)),
        )
    }};
}

/// Create a [`MatrixF64Slice`] row-major, 4×4 transformation matrices argument.
/// Each matrix is given as 16 [`f64`] values.
///
/// Name accepts a string literal or a typed
/// [`Attribute<[Matrix4F64]>`](crate::Attribute) constant.
#[macro_export]
macro_rules! matrix_f64_slice {
    ($name: literal, $value: expr) => {
        nsi::Arg::new(
            $name,
            nsi::ArgData::from(nsi::MatrixF64Slice::new($value)),
        )
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<[$crate::Matrix4F64]> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::MatrixF64Slice::new($value)),
        )
    }};
}

/// Create a [`String`] argument.
///
/// # Examples
///
/// ```
/// # use nsi_ffi_wrap as nsi;
/// // Create rendering context.
/// let ctx =
///     nsi::Context::new(Some(&[nsi::string!("streamfilename", "stdout")]))
///         .expect("Could not create NSI context.");
/// ```
#[macro_export]
macro_rules! string {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::String::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<&'static str> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::String::new($value)),
        )
    }};
}

/// Create a [`String`] array argument.
///
/// # Examples
///
/// ```
/// # use nsi_ffi_wrap as nsi;
/// # let ctx = nsi::Context::new(None).unwrap();
/// // One of these is not an actor:
/// ctx.set_attribute(
///     "dummy",
///     &[nsi::string_slice!(
///         "actors",
///         &["Klaus Kinski", "Giorgio Moroder", "Rainer Brandt"]
///     )],
/// );
/// ```
#[macro_export]
macro_rules! string_slice {
    ($name: literal, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::StringSlice::new($value)))
    };
    ($name: path, $value: expr) => {{
        const __ATTR_CHECK: $crate::Attribute<[&'static str]> = $name;
        nsi::Arg::new(
            __ATTR_CHECK.name(),
            nsi::ArgData::from(nsi::StringSlice::new($value)),
        )
    }};
}

/// Create a [`Reference`] argument.
///
/// This macro accepts:
/// - `&Box<T>` - ReferenceSlice to boxed data
/// - `&Arc<T>` - ReferenceSlice to Arc'd data  
/// - `&Pin<Box<T>>` - ReferenceSlice to pinned boxes
///
/// For other types with stable addresses, use `reference_stable!` instead.
#[macro_export]
macro_rules! reference {
    ($name: tt, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::Reference::new($value)))
    };
}

/// Create a [`Reference`] argument from data with a stable address.
///
/// # Safety
/// You must ensure the data has a stable address (heap allocated, static, etc.)
/// and won't be moved for the lifetime of the reference.
#[macro_export]
macro_rules! reference_stable {
    ($name: tt, $value: expr) => {
        nsi::Arg::new(
            $name,
            nsi::ArgData::from(unsafe { nsi::Reference::from_stable($value) }),
        )
    };
}

/// Create a [`Reference`] array argument.
#[macro_export]
macro_rules! reference_slice {
    ($name: tt, $value: expr) => {
        nsi::Arg::new(
            $name,
            nsi::ArgData::from(nsi::ReferenceSlice::new($value)),
        )
    };
}

/// Create a [`Callback`] argument.
#[macro_export]
macro_rules! callback {
    ($name: tt, $value: expr) => {
        nsi::Arg::new($name, nsi::ArgData::from(nsi::Callback::new($value)))
    };
}