jflib-gpu 0.2.1

GPU access for JFLib: an explicit API over Vulkan, WebGPU and Metal
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
// mtl_cmd -- command recording on Metal (AP6, docs/APPLE.md): CommandEncoder -> CommandBuffer
//
// An encoder records into one MTLCommandBuffer through Metal's encoders: copies and fills in a
// blit encoder, dispatches in a compute encoder, a render pass in a render encoder; switching
// kinds ends the current one.  barrier / texture_barrier end the current encoder too: Metal
// orders encoders that touch the same (hazard-tracked) resources itself, and the layouts mean
// nothing here.  Bind groups and push constants are remembered and set before the next dispatch
// or draw, at the slots the pipeline's translation gave each (group, binding) of each stage
// (shader::msl: buffers, textures, samplers; push constants at PUSH_SLOT, the bound buffer sizes
// at SIZES_SLOT).  fill_buffer runs a small kernel of its own (a blit fill takes one byte).
// The checks are those of the Vulkan backend (vk_cmd.rs); finish() returns the first misuse.

use alloc::vec::Vec;
use core::marker::PhantomData;

use crate::mtl_dev::{Device, Shared};
use crate::mtl_objc::{self as objc, Id, MTLClearColor, MTLScissorRect, MTLSize, MTLViewport, Obj, Pool, msg};
use crate::mtl_res::{PipeInner, Res, StageInfo, copy_region, encode_buffer_to_texture, encode_texture_to_buffer};
use crate::*;

#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
    Blit,
    Compute,
    Render,
}

struct Pass {
    colors: [Option<Format>; COLOR_TARGETS_MAX],
    n: usize,
    depth: Option<Format>,
    size: (u32, u32),
    // (draw_indexed_indirect_count suspends the pass for a compute pass and resumes it: what that needs)
    /// the colour views and whether the pass stores them at its end
    targets: Vec<(Obj, bool)>,
    /// the depth view, whether it is stored, whether it has stencil
    depth_target: Option<(Obj, bool, bool)>,
    viewport: Option<MTLViewport>,
    scissor: Option<MTLScissorRect>,
    vertex: [Option<(Id, u64)>; shader::msl::VERTEX_BUFFERS_MAX as usize],
}

/// records commands; finish() makes a CommandBuffer for Queue::submit
pub struct CommandEncoder<'a> {
    sh: &'a Shared,
    cb: Option<Obj>,
    enc: Option<(Obj, Kind)>,
    err: Option<GpuError>,
    pass: Option<Pass>,
    compute_pipe: Option<&'a PipeInner>,
    graphics: Option<&'a PipeInner>,
    groups: [Option<&'a BindGroup>; BIND_GROUPS_MAX as usize],
    push: [u8; PUSH_CONSTANTS_MAX as usize],
    /// the bindings must be set again before the next dispatch / draw
    dirty: bool,
    /// index buffer, its offset, 4-byte indices
    index: Option<(Id, u64, bool)>,
    /// the fence the last encoder updated when it ended: the next one waits for it
    fence: Option<Obj>,
    /// the vertex stage's sizes as last set, DRAW_INDEX_AT included (a multi-draw sets it per draw)
    vsizes: [u32; SIZES_LEN],
    _borrow: PhantomData<&'a ()>,
}

/// MTLStoreActionUnknown: a render pass's store actions are set when it ends (or is suspended)
const STORE_UNKNOWN: usize = 4;

/// the sizes buffer: one entry per resource buffer slot, then DrawIndex (shader::msl::DRAW_INDEX_AT)
const SIZES_LEN: usize = shader::msl::DRAW_INDEX_AT as usize + 1;

/// recorded commands, ready to submit (dropped unsubmitted: discarded)
pub struct CommandBuffer<'a> {
    cb: Obj,
    _borrow: PhantomData<&'a ()>,
}

impl CommandBuffer<'_> {
    pub(crate) fn into_obj(self) -> Obj {
        self.cb
    }
}

impl Device {
    /// a command encoder of the device's queue
    pub fn encoder(&self) -> Result<CommandEncoder<'_>> {
        let cb = self.sh.command_buffer()?;
        Ok(CommandEncoder {
            sh: &self.sh,
            cb: Some(cb),
            enc: None,
            err: None,
            pass: None,
            compute_pipe: None,
            graphics: None,
            groups: [None; BIND_GROUPS_MAX as usize],
            push: [0; PUSH_CONSTANTS_MAX as usize],
            dirty: true,
            index: None,
            fence: None,
            vsizes: [0; SIZES_LEN],
            _borrow: PhantomData,
        })
    }
}

impl Drop for CommandEncoder<'_> {
    fn drop(&mut self) {
        // an encoder left open would make Metal complain when the buffer goes
        self.end_encoder();
    }
}

impl<'a> CommandEncoder<'a> {
    #[inline]
    fn ok(&mut self, cond: bool, what: &'static str) -> Option<()> {
        if self.err.is_some() {
            return None;
        }
        if !cond {
            self.err = Some(GpuError::Invalid(what));
            return None;
        }
        Some(())
    }

    #[inline]
    fn outside(&mut self, what: &'static str) -> Option<()> {
        let c = self.pass.is_none();
        self.ok(c, what)
    }

    fn buf_range(&mut self, b: &Buffer, off: u64, n: u64, what: &'static str) -> Option<()> {
        let c = off.checked_add(n).is_some_and(|e| e <= b.size());
        self.ok(c, what)
    }

    fn cb(&self) -> Id {
        self.cb.as_ref().map_or(objc::NIL, |c| c.id())
    }

    /// end the open encoder; it updates a fence the next encoder waits for, so encoders run one after
    /// the other as Vulkan's barriers order them (Metal's own tracking does not see through texture
    /// views: Hi-Z pyramids read and write mips of one texture through views of their own)
    fn end_encoder(&mut self) {
        if let Some((e, k)) = self.enc.take() {
            // SAFETY: newFence returns a new fence (+1); updateFence: on the open encoder before it ends, once.
            unsafe {
                let f = Obj::new(msg!(self.sh.dev.id(), c"newFence"; Id));
                if let Some(f) = &f {
                    if k == Kind::Render {
                        msg!(e.id(), c"updateFence:afterStages:", f.id() => Id, 7usize => usize; ()); // vertex | fragment | tile
                    } else {
                        msg!(e.id(), c"updateFence:", f.id() => Id; ());
                    }
                }
                msg!(e.id(), c"endEncoding"; ());
                self.fence = f;
            }
        }
    }

    /// a new encoder waits for the fence of the one before it
    fn wait_fence(&self, e: Id, k: Kind) {
        if let Some(f) = &self.fence {
            // SAFETY: waitForFence: on a new open encoder; the fence was updated by an earlier encoder of
            // this command buffer.
            unsafe {
                if k == Kind::Render {
                    msg!(e, c"waitForFence:beforeStages:", f.id() => Id, 7usize => usize; ());
                } else {
                    msg!(e, c"waitForFence:", f.id() => Id; ());
                }
            }
        }
    }

    /// the open encoder of kind k (a new one after ending another kind)
    fn encoder(&mut self, k: Kind) -> Option<Id> {
        if let Some((e, kind)) = &self.enc {
            if *kind == k {
                return Some(e.id());
            }
        }
        self.end_encoder();
        let _pool = Pool::new();
        let cb = self.cb();
        // SAFETY: blitCommandEncoder / computeCommandEncoder of the command buffer (autoreleased,
        // retained inside the pool); no other encoder is open.
        let e = unsafe {
            match k {
                Kind::Blit => msg!(cb, c"blitCommandEncoder"; Id),
                _ => msg!(cb, c"computeCommandEncoder"; Id),
            }
        };
        let Some(e) = Obj::retained(e) else {
            self.err.get_or_insert(GpuError::OutOfMemory);
            return None;
        };
        let id = e.id();
        self.wait_fence(id, k);
        self.enc = Some((e, k));
        self.dirty = true;
        Some(id)
    }

    // ------------------------------------------------------------ copies

    pub fn copy_buffer(&mut self, src: &'a Buffer, src_off: u64, dst: &'a Buffer, dst_off: u64, size: u64) {
        if self.outside("copy_buffer inside a render pass").is_none()
            || self.buf_range(src, src_off, size, "copy_buffer: source range").is_none()
            || self.buf_range(dst, dst_off, size, "copy_buffer: destination range").is_none()
            || size == 0
        {
            return;
        }
        let Some(b) = self.encoder(Kind::Blit) else { return };
        // SAFETY: an open blit encoder; ranges checked.
        unsafe {
            msg!(b, c"copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:", src.0.h.id() => Id, src_off as usize => usize,
                 dst.0.h.id() => Id, dst_off as usize => usize, size as usize => usize; ());
        }
    }

    /// fill size bytes at offset with a 32-bit value (both multiples of 4)
    pub fn fill_buffer(&mut self, buf: &'a Buffer, offset: u64, size: u64, value: u32) {
        if self.outside("fill_buffer inside a render pass").is_none()
            || self.ok(offset % 4 == 0 && size % 4 == 0 && size > 0, "fill_buffer: offset and size multiples of 4").is_none()
            || self.buf_range(buf, offset, size, "fill_buffer: range").is_none()
        {
            return;
        }
        let bytes = value.to_le_bytes();
        if bytes.iter().all(|&b| b == bytes[0]) {
            let Some(b) = self.encoder(Kind::Blit) else { return };
            let range = objc::NSRange { location: offset as usize, length: size as usize };
            // SAFETY: an open blit encoder; range checked.
            unsafe { msg!(b, c"fillBuffer:range:value:", buf.0.h.id() => Id, range => objc::NSRange, bytes[0] => u8; ()) };
            return;
        }
        let Some(state) = self.fill_state() else { return };
        let Some(c) = self.encoder(Kind::Compute) else { return };
        let words = (size / 4) as u32;
        let args = [value, words];
        let groups = words.div_ceil(64) as usize;
        // SAFETY: an open compute encoder with the fill kernel: word i < words of the buffer from
        // offset gets the value (the buffer's length is a whole number of words).
        unsafe {
            msg!(c, c"setComputePipelineState:", state => Id; ());
            msg!(c, c"setBuffer:offset:atIndex:", buf.0.h.id() => Id, offset as usize => usize, 0usize => usize; ());
            msg!(c, c"setBytes:length:atIndex:", args.as_ptr() as *const core::ffi::c_void => *const core::ffi::c_void, 8usize => usize, 1usize => usize; ());
            msg!(c, c"dispatchThreadgroups:threadsPerThreadgroup:", MTLSize { w: groups, h: 1, d: 1 } => MTLSize,
                 MTLSize { w: 64, h: 1, d: 1 } => MTLSize; ());
        }
        self.dirty = true;
    }

    /// the fill kernel's pipeline (compiled once per device)
    fn fill_state(&mut self) -> Option<Id> {
        let mut f = self.sh.fill.lock();
        if f.is_none() {
            let src = "#include <metal_stdlib>\nusing namespace metal;\n\
                       kernel void jf_fill(device uint* b [[buffer(0)]], constant uint2& a [[buffer(1)]], uint i [[thread_position_in_grid]]) {\n\
                       if (i < a.y) { b[i] = a.x; }\n}\n";
            let made = crate::mtl_res::compile(self.sh, src).ok().and_then(|lib| {
                let _pool = Pool::new();
                let name = objc::nsstring("jf_fill")?;
                // SAFETY: newFunctionWithName: / newComputePipelineStateWithFunction:error: on live
                // objects (+1 results or nil).
                unsafe {
                    let func = Obj::new(msg!(lib.id(), c"newFunctionWithName:", name.id() => Id; Id))?;
                    let mut err: Id = objc::NIL;
                    Obj::new(msg!(self.sh.dev.id(), c"newComputePipelineStateWithFunction:error:", func.id() => Id, &mut err => *mut Id; Id))
                }
            });
            *f = made;
        }
        let id = f.as_ref().map(|o| o.id());
        drop(f);
        if id.is_none() {
            self.err.get_or_insert(GpuError::Failed(0));
        }
        id
    }

    /// buffer data -> a texture region
    pub fn copy_buffer_to_texture(&mut self, src: &'a Buffer, layout: DataLayout, dst: TextureRegion<'a>) {
        if self.outside("copy inside a render pass").is_none() {
            return;
        }
        let c = copy_region(&dst, &layout, src.size());
        let ok = c.is_ok() && dst.texture.usage().contains(TextureUsage::COPY_DST);
        if self.ok(ok, "copy_buffer_to_texture: region, data layout or COPY_DST usage").is_none() {
            return;
        }
        let Ok(c) = c else { return };
        let Some(b) = self.encoder(Kind::Blit) else { return };
        encode_buffer_to_texture(b, src.0.h.id(), layout.offset, &c, &dst);
    }

    /// a texture region -> buffer data
    pub fn copy_texture_to_buffer(&mut self, src: TextureRegion<'a>, dst: &'a Buffer, layout: DataLayout) {
        if self.outside("copy inside a render pass").is_none() {
            return;
        }
        let c = copy_region(&src, &layout, dst.size());
        let ok = c.is_ok() && src.texture.usage().contains(TextureUsage::COPY_SRC);
        if self.ok(ok, "copy_texture_to_buffer: region, data layout or COPY_SRC usage").is_none() {
            return;
        }
        let Ok(c) = c else { return };
        let Some(b) = self.encoder(Kind::Blit) else { return };
        encode_texture_to_buffer(b, dst.0.h.id(), layout.offset, &c, &src);
    }

    // ------------------------------------------------------------ barriers

    /// the accesses `before` finish before the `after` ones: the next command starts a new encoder
    pub fn barrier(&mut self, _before: Access, _after: Access) {
        if self.outside("barrier inside a render pass").is_none() {
            return;
        }
        self.end_encoder();
    }

    pub fn texture_barrier(&mut self, tex: &'a Texture, before: Layout, after: Layout) {
        self.texture_barrier_range(tex, 0, tex.mips(), 0, tex.layers(), before, after);
    }

    #[allow(clippy::too_many_arguments)]
    pub fn texture_barrier_range(&mut self, tex: &'a Texture, base_mip: u32, mips: u32, base_layer: u32, layers: u32,
                                 _before: Layout, after: Layout) {
        if self.outside("texture_barrier inside a render pass").is_none()
            || self.ok(mips > 0 && layers > 0 && base_mip.checked_add(mips).is_some_and(|e| e <= tex.mips())
                           && base_layer.checked_add(layers).is_some_and(|e| e <= tex.layers()),
                       "texture_barrier: range outside the texture").is_none()
            || self.ok(after != Layout::Undefined, "texture_barrier: Undefined is no destination").is_none()
        {
            return;
        }
        self.end_encoder();
    }

    // ------------------------------------------------------------ compute

    pub fn set_compute_pipeline(&mut self, p: &'a ComputePipeline) {
        if self.outside("set_compute_pipeline inside a render pass").is_none() {
            return;
        }
        self.compute_pipe = Some(&p.0);
        self.dirty = true;
    }

    fn current(&mut self) -> Option<&'a PipeInner> {
        let p = if self.pass.is_some() { self.graphics } else { self.compute_pipe };
        self.ok(p.is_some(), "bind group / push constants before a pipeline")?;
        p
    }

    /// bind group g (= @group(g)) of the current pipeline's layout
    pub fn set_bind_group(&mut self, index: u32, group: &'a BindGroup) {
        let Some(p) = self.current() else { return };
        let fits = p.layout.0.groups.get(index as usize).is_some_and(|l| alloc::sync::Arc::ptr_eq(&l.0, &group.0.layout));
        if self.ok(fits, "set_bind_group: the group's layout differs from the pipeline layout's").is_none() {
            return;
        }
        self.groups[index as usize] = Some(group);
        self.dirty = true;
    }

    /// push constants at offset (bytes) for the current pipeline
    pub fn push_constants<T: Pod>(&mut self, offset: u32, data: &[T]) {
        let Some(p) = self.current() else { return };
        let bytes = bytes_of(data);
        let n = bytes.len() as u32;
        let fits = offset % 4 == 0 && n % 4 == 0 && n > 0 && offset.checked_add(n).is_some_and(|e| e <= p.layout.0.push);
        if self.ok(fits, "push_constants: range outside the layout's (multiples of 4)").is_none() {
            return;
        }
        self.push[offset as usize..(offset + n) as usize].copy_from_slice(bytes);
        self.dirty = true;
    }

    /// set a stage's bindings on the open encoder: stage 0 compute, 1 vertex, 2 fragment
    fn bind(&mut self, e: Id, info: &StageInfo, stage: u32) -> Option<()> {
        use shader::msl::SlotKind;
        let (buf, tex, smp, bytes) = match stage {
            0 => (c"setBuffer:offset:atIndex:", c"setTexture:atIndex:", c"setSamplerState:atIndex:", c"setBytes:length:atIndex:"),
            1 => (c"setVertexBuffer:offset:atIndex:", c"setVertexTexture:atIndex:", c"setVertexSamplerState:atIndex:", c"setVertexBytes:length:atIndex:"),
            _ => (c"setFragmentBuffer:offset:atIndex:", c"setFragmentTexture:atIndex:", c"setFragmentSamplerState:atIndex:", c"setFragmentBytes:length:atIndex:"),
        };
        // (DrawIndex 0: a single draw; a multi-draw sets each draw's own, set_draw_index)
        let mut sizes = [0u32; SIZES_LEN];
        for s in &info.slots {
            let g = self.groups.get(s.set as usize).copied().flatten();
            let r = g.and_then(|g| g.0.res.iter().find(|r| r.0 == s.binding)).map(|r| r.1.clone());
            let Some(r) = r else {
                self.ok(false, "dispatch / draw: a bind group the pipeline uses is not set")?;
                return None;
            };
            // SAFETY: an open encoder of the matching kind; the objects are alive (the group holds
            // them, the command buffer retains them); the slot indices come from the translation.
            unsafe {
                match (s.kind, r) {
                    (SlotKind::Buffer, Res::Buf(b, off, range)) => {
                        let f: unsafe extern "C" fn(Id, objc::Sel, Id, usize, usize) = core::mem::transmute(objc::objc_msgSend as *const ());
                        f(e, objc::sel(buf), b.id(), off as usize, s.index as usize);
                        if let Some(x) = sizes.get_mut(s.index as usize) {
                            *x = range.min(u32::MAX as u64) as u32;
                        }
                    }
                    (SlotKind::Texture, Res::Tex(t)) => {
                        let f: unsafe extern "C" fn(Id, objc::Sel, Id, usize) = core::mem::transmute(objc::objc_msgSend as *const ());
                        f(e, objc::sel(tex), t.id(), s.index as usize);
                    }
                    (SlotKind::Sampler, Res::Smp(sm)) => {
                        let f: unsafe extern "C" fn(Id, objc::Sel, Id, usize) = core::mem::transmute(objc::objc_msgSend as *const ());
                        f(e, objc::sel(smp), sm.id(), s.index as usize);
                    }
                    (SlotKind::Buffer, Res::Table(tb)) => {
                        // a Bindless table: its argument buffer, and what it holds made resident for this encoder
                        let f: unsafe extern "C" fn(Id, objc::Sel, Id, usize, usize) = core::mem::transmute(objc::objc_msgSend as *const ());
                        f(e, objc::sel(buf), tb.buf.id(), 0, s.index as usize);
                        if let Some(x) = sizes.get_mut(s.index as usize) {
                            *x = tb.len.min(u32::MAX as u64) as u32;
                        }
                        if tb.usage != 0 {
                            let ids: Vec<Id> = tb.keep.lock().iter().flatten().map(|o| o.id()).collect();
                            if !ids.is_empty() {
                                if stage == 0 {
                                    msg!(e, c"useResources:count:usage:", ids.as_ptr() => *const Id, ids.len() => usize, tb.usage => usize; ());
                                } else {
                                    msg!(e, c"useResources:count:usage:stages:", ids.as_ptr() => *const Id, ids.len() => usize, tb.usage => usize,
                                         stage as usize => usize; ()); // MTLRenderStageVertex 1, Fragment 2
                                }
                            }
                        }
                    }
                    _ => {
                        self.ok(false, "a bound resource's kind differs from the shader's")?;
                    }
                }
            }
        }
        let setb = |data: *const u8, n: usize, at: u32| {
            // SAFETY: setBytes copies n bytes from data at once.
            unsafe {
                let f: unsafe extern "C" fn(Id, objc::Sel, *const u8, usize, usize) = core::mem::transmute(objc::objc_msgSend as *const ());
                f(e, objc::sel(bytes), data, n, at as usize);
            }
        };
        if info.push {
            setb(self.push.as_ptr(), self.push.len(), shader::msl::PUSH_SLOT);
        }
        if info.sizes {
            setb(sizes.as_ptr() as *const u8, core::mem::size_of_val(&sizes), shader::msl::SIZES_SLOT);
        }
        if stage == 1 {
            self.vsizes = sizes;
        }
        Some(())
    }

    /// (multi-draws) the vertex stage reads DrawIndex: the next draw's index into the sizes buffer
    fn set_draw_index(&mut self, e: Id, i: u32) {
        let reads = self.graphics.and_then(|p| p.stages[0].as_ref()).is_some_and(|v| v.draw_index);
        if !reads || self.vsizes[shader::msl::DRAW_INDEX_AT as usize] == i {
            return;
        }
        self.vsizes[shader::msl::DRAW_INDEX_AT as usize] = i;
        // SAFETY: the open render encoder; setVertexBytes copies the sizes at once.
        unsafe {
            msg!(e, c"setVertexBytes:length:atIndex:", self.vsizes.as_ptr() as *const core::ffi::c_void => *const core::ffi::c_void,
                 core::mem::size_of_val(&self.vsizes) => usize, shader::msl::SIZES_SLOT as usize => usize; ());
        }
    }

    fn prepare_dispatch(&mut self) -> Option<(Id, [u32; 3])> {
        let p = self.compute_pipe?;
        let c = self.encoder(Kind::Compute)?;
        if self.dirty {
            // SAFETY: an open compute encoder; the state is alive (the pipeline is borrowed).
            unsafe { msg!(c, c"setComputePipelineState:", p.state.id() => Id; ()) };
            let info = p.stages[0].as_ref()?;
            self.bind(c, info, 0)?;
            self.dirty = false;
        }
        Some((c, p.stages[0].as_ref()?.workgroup))
    }

    pub fn dispatch(&mut self, x: u32, y: u32, z: u32) {
        let m = self.sh.limits.max_compute_workgroups;
        let ok = self.pass.is_none() && self.compute_pipe.is_some() && x <= m[0] && y <= m[1] && z <= m[2];
        if self.ok(ok, "dispatch: no compute pipeline, inside a pass or too many workgroups").is_none() {
            return;
        }
        if x == 0 || y == 0 || z == 0 {
            return;
        }
        let Some((c, wg)) = self.prepare_dispatch() else { return };
        // SAFETY: an open compute encoder with pipeline and bindings set.
        unsafe {
            msg!(c, c"dispatchThreadgroups:threadsPerThreadgroup:", MTLSize { w: x as usize, h: y as usize, d: z as usize } => MTLSize,
                 MTLSize { w: wg[0] as usize, h: wg[1] as usize, d: wg[2] as usize } => MTLSize; ());
        }
    }

    /// workgroup counts (3 x u32) from buf at offset
    pub fn dispatch_indirect(&mut self, buf: &'a Buffer, offset: u64) {
        let ok = self.pass.is_none() && self.compute_pipe.is_some() && buf.usage().contains(BufferUsage::INDIRECT) && offset % 4 == 0
            && offset.checked_add(12).is_some_and(|e| e <= buf.size());
        if self.ok(ok, "dispatch_indirect: pipeline, INDIRECT usage, offset or range").is_none() {
            return;
        }
        let Some((c, wg)) = self.prepare_dispatch() else { return };
        // SAFETY: as in dispatch; range checked.
        unsafe {
            msg!(c, c"dispatchThreadgroupsWithIndirectBuffer:indirectBufferOffset:threadsPerThreadgroup:", buf.0.h.id() => Id,
                 offset as usize => usize, MTLSize { w: wg[0] as usize, h: wg[1] as usize, d: wg[2] as usize } => MTLSize; ());
        }
    }

    // ------------------------------------------------------------ render passes

    pub fn begin_render(&mut self, desc: &RenderPassDesc<'_, 'a>) {
        if self.outside("begin_render inside a render pass").is_none() {
            return;
        }
        let n = desc.color.len();
        if self.ok(n <= self.sh.limits.max_color_targets as usize && (n > 0 || desc.depth.is_some()),
                   "begin_render: no attachments or too many").is_none()
        {
            return;
        }
        let first = desc.color.first().map(|c| c.view).or(desc.depth.map(|d| d.view));
        let Some(first) = first else { return };
        let (w, h) = first.size();
        let single = |v: &TextureView| v.0.mips == 1 && v.0.layers == 1 && v.size() == (w, h);
        let colors_ok = desc.color.iter().all(|c| {
            single(c.view) && c.view.usage().contains(TextureUsage::COLOR_TARGET) && c.after != Layout::Undefined
        });
        let depth_ok = desc.depth.is_none_or(|d| {
            single(d.view) && d.view.usage().contains(TextureUsage::DEPTH_TARGET) && d.after != Layout::Undefined
        });
        if self.ok(colors_ok && depth_ok, "begin_render: attachments (one mip and layer, equal sizes, usage)").is_none() {
            return;
        }
        self.end_encoder();
        let load = |l: Load| -> usize {
            match l {
                Load::Keep => 1,
                Load::Clear => 2,
                Load::Discard => 0,
            }
        };
        let mut colors = [None; COLOR_TARGETS_MAX];
        for (i, c) in desc.color.iter().enumerate() {
            colors[i] = Some(c.view.format());
        }
        let targets: Vec<(Obj, bool)> = desc.color.iter().map(|c| (c.view.0.h.clone(), c.store)).collect();
        let depth_target = desc.depth.map(|d| (d.view.0.h.clone(), d.store, d.view.format().has_stencil()));
        let color_loads: Vec<(usize, MTLClearColor)> = desc.color.iter()
            .map(|c| (load(c.load), MTLClearColor { r: c.clear[0] as f64, g: c.clear[1] as f64, b: c.clear[2] as f64, a: c.clear[3] as f64 }))
            .collect();
        let depth_load = desc.depth.map(|d| (load(d.load), d.clear as f64, if d.load == Load::Keep { 1usize } else { 2 }));
        let Some(e) = self.render_encoder(&targets, &depth_target, &color_loads, depth_load) else { return };
        self.wait_fence(e.id(), Kind::Render);
        self.enc = Some((e, Kind::Render));
        self.pass = Some(Pass { colors, n, depth: desc.depth.map(|d| d.view.format()), size: (w, h), targets, depth_target,
                                viewport: None, scissor: None, vertex: [None; shader::msl::VERTEX_BUFFERS_MAX as usize] });
        self.graphics = None;
        self.index = None;
        self.dirty = true;
    }

    /// a render encoder on the attachments: color_loads (load action, clear colour) per target, depth_load (load action,
    /// clear depth, stencil load action); store actions are left open (MTLStoreActionUnknown) for store_actions
    fn render_encoder(&mut self, targets: &[(Obj, bool)], depth: &Option<(Obj, bool, bool)>, color_loads: &[(usize, MTLClearColor)],
                      depth_load: Option<(usize, f64, usize)>) -> Option<Obj> {
        let _pool = Pool::new();
        let cb = self.cb();
        // SAFETY: a render pass descriptor (autoreleased, inside the pool) set up with live views;
        // the render encoder is retained.
        let e = unsafe {
            let rp: Id = msg!(objc::class(c"MTLRenderPassDescriptor"), c"renderPassDescriptor"; Id);
            let cas: Id = msg!(rp, c"colorAttachments"; Id);
            for (i, (view, _)) in targets.iter().enumerate() {
                let ca: Id = msg!(cas, c"objectAtIndexedSubscript:", i => usize; Id);
                msg!(ca, c"setTexture:", view.id() => Id; ());
                let (l, cc) = color_loads.get(i).copied().unwrap_or((1, MTLClearColor::default()));
                msg!(ca, c"setLoadAction:", l => usize; ());
                msg!(ca, c"setStoreAction:", STORE_UNKNOWN => usize; ());
                msg!(ca, c"setClearColor:", cc => MTLClearColor; ());
            }
            if let Some((view, _, stencil)) = depth {
                let (l, clear, sl) = depth_load.unwrap_or((1, 1.0, 1));
                let da: Id = msg!(rp, c"depthAttachment"; Id);
                msg!(da, c"setTexture:", view.id() => Id; ());
                msg!(da, c"setLoadAction:", l => usize; ());
                msg!(da, c"setStoreAction:", STORE_UNKNOWN => usize; ());
                msg!(da, c"setClearDepth:", clear => f64; ());
                if *stencil {
                    let sa: Id = msg!(rp, c"stencilAttachment"; Id);
                    msg!(sa, c"setTexture:", view.id() => Id; ());
                    msg!(sa, c"setLoadAction:", sl => usize; ());
                    msg!(sa, c"setStoreAction:", STORE_UNKNOWN => usize; ());
                }
            }
            Obj::retained(msg!(cb, c"renderCommandEncoderWithDescriptor:", rp => Id; Id))
        };
        if e.is_none() {
            self.err.get_or_insert(GpuError::OutOfMemory);
        }
        e
    }

    /// the open render encoder's store actions: the pass's own (end), or all kept (suspended for a compute pass)
    fn store_actions(&mut self, keep_all: bool) {
        let e = self.render_enc();
        let Some(p) = &self.pass else { return };
        let act = |store: bool| if keep_all || store { 1usize } else { 0 };
        // SAFETY: the open render encoder, whose store actions were left open (MTLStoreActionUnknown).
        unsafe {
            for (i, (_, store)) in p.targets.iter().enumerate() {
                msg!(e, c"setColorStoreAction:atIndex:", act(*store) => usize, i => usize; ());
            }
            if let Some((_, store, stencil)) = &p.depth_target {
                msg!(e, c"setDepthStoreAction:", act(*store) => usize; ());
                if *stencil {
                    msg!(e, c"setStencilStoreAction:", act(*store) => usize; ());
                }
            }
        }
    }

    /// (draw_indexed_indirect_count) the pass ends with everything stored, to go on after a compute pass
    fn suspend_render(&mut self) {
        self.store_actions(true);
        self.end_encoder();
    }

    /// the suspended pass goes on: a new render encoder that loads what the last one stored, with the state set again
    fn resume_render(&mut self) -> Option<Id> {
        let (targets, depth) = {
            let p = self.pass.as_ref()?;
            (p.targets.clone(), p.depth_target.clone())
        };
        self.end_encoder();
        let e = self.render_encoder(&targets, &depth, &[], None)?;
        self.wait_fence(e.id(), Kind::Render);
        let id = e.id();
        self.enc = Some((e, Kind::Render));
        let p = self.pass.as_ref()?;
        // SAFETY: the new render encoder; the pipeline's states and the vertex buffers are alive (borrowed for 'a).
        unsafe {
            if let Some(g) = self.graphics {
                msg!(id, c"setRenderPipelineState:", g.state.id() => Id; ());
                if let Some(ds) = &g.depth_state {
                    msg!(id, c"setDepthStencilState:", ds.id() => Id; ());
                }
                msg!(id, c"setCullMode:", g.cull => usize; ());
                msg!(id, c"setFrontFacingWinding:", g.winding => usize; ());
            }
            if let Some(vp) = p.viewport {
                msg!(id, c"setViewport:", vp => MTLViewport; ());
            }
            if let Some(r) = p.scissor {
                msg!(id, c"setScissorRect:", r => MTLScissorRect; ());
            }
            for (slot, vb) in p.vertex.iter().enumerate() {
                if let Some((b, off)) = vb {
                    msg!(id, c"setVertexBuffer:offset:atIndex:", *b => Id, *off as usize => usize, shader::msl::vertex_slot(slot as u32) as usize => usize; ());
                }
            }
        }
        self.dirty = true;
        Some(id)
    }

    pub fn end_render(&mut self) {
        if self.pass.is_none() {
            self.ok(false, "end_render without begin_render");
            return;
        }
        self.store_actions(false);
        self.pass = None;
        self.end_encoder();
    }

    fn render_enc(&self) -> Id {
        match &self.enc {
            Some((e, Kind::Render)) => e.id(),
            _ => objc::NIL,
        }
    }

    pub fn set_render_pipeline(&mut self, p: &'a RenderPipeline) {
        let fits = self.pass.as_ref().is_some_and(|pass| {
            pass.n == p.0.ncolor && pass.colors[..pass.n] == p.0.colors[..pass.n] && pass.depth == p.0.depth
        });
        if self.ok(fits, "set_render_pipeline: outside a pass or target formats differ").is_none() {
            return;
        }
        self.graphics = Some(&p.0);
        let e = self.render_enc();
        // SAFETY: the open render encoder; the states are alive (the pipeline is borrowed).
        unsafe {
            msg!(e, c"setRenderPipelineState:", p.0.state.id() => Id; ());
            if let Some(ds) = &p.0.depth_state {
                msg!(e, c"setDepthStencilState:", ds.id() => Id; ());
            }
            msg!(e, c"setCullMode:", p.0.cull => usize; ());
            msg!(e, c"setFrontFacingWinding:", p.0.winding => usize; ());
        }
        self.dirty = true;
    }

    /// the viewport in pixels from the top left (depth range min ..= max)
    pub fn set_viewport(&mut self, x: f32, y: f32, w: f32, h: f32, min_depth: f32, max_depth: f32) {
        if self.ok(self.pass.is_some() && w > 0.0 && h > 0.0, "set_viewport: outside a pass or empty").is_none() {
            return;
        }
        let vp = MTLViewport { x: x as f64, y: y as f64, w: w as f64, h: h as f64, znear: min_depth as f64, zfar: max_depth as f64 };
        if let Some(p) = &mut self.pass {
            p.viewport = Some(vp);
        }
        // SAFETY: the open render encoder.
        unsafe { msg!(self.render_enc(), c"setViewport:", vp => MTLViewport; ()) };
    }

    pub fn set_scissor(&mut self, x: u32, y: u32, w: u32, h: u32) {
        if self.ok(self.pass.is_some(), "set_scissor outside a pass").is_none() {
            return;
        }
        // Metal wants the rectangle inside the target (Vulkan clips it)
        let Some((tw, th)) = self.pass.as_ref().map(|p| p.size) else { return };
        let (x0, y0) = (x.min(tw), y.min(th));
        let (x1, y1) = (x.saturating_add(w).min(tw), y.saturating_add(h).min(th));
        let r = MTLScissorRect { x: x0 as usize, y: y0 as usize, w: (x1 - x0) as usize, h: (y1 - y0) as usize };
        if let Some(p) = &mut self.pass {
            p.scissor = Some(r);
        }
        // SAFETY: the open render encoder.
        unsafe { msg!(self.render_enc(), c"setScissorRect:", r => MTLScissorRect; ()) };
    }

    pub fn set_vertex_buffer(&mut self, slot: u32, buf: &'a Buffer, offset: u64) {
        let ok = self.pass.is_some() && buf.usage().contains(BufferUsage::VERTEX) && offset < buf.size()
            && slot < self.sh.limits.max_vertex_buffers;
        if self.ok(ok, "set_vertex_buffer: outside a pass, VERTEX usage or offset").is_none() {
            return;
        }
        if let Some(p) = &mut self.pass {
            p.vertex[slot as usize] = Some((buf.0.h.id(), offset));
        }
        // SAFETY: the open render encoder; the vertex buffer slots lie above the resources'.
        unsafe {
            msg!(self.render_enc(), c"setVertexBuffer:offset:atIndex:", buf.0.h.id() => Id, offset as usize => usize,
                 shader::msl::vertex_slot(slot) as usize => usize; ());
        }
    }

    pub fn set_index_buffer(&mut self, buf: &'a Buffer, offset: u64, format: IndexFormat) {
        let size = if format == IndexFormat::U16 { 2 } else { 4 };
        let ok = self.pass.is_some() && buf.usage().contains(BufferUsage::INDEX) && offset % size == 0 && offset < buf.size();
        if self.ok(ok, "set_index_buffer: outside a pass, INDEX usage or offset").is_none() {
            return;
        }
        self.index = Some((buf.0.h.id(), offset, format == IndexFormat::U32));
    }

    fn can_draw(&mut self, indexed: bool) -> Option<Id> {
        let ok = self.pass.is_some() && self.graphics.is_some() && (!indexed || self.index.is_some());
        self.ok(ok, "draw: outside a pass, without a render pipeline or index buffer")?;
        let e = self.render_enc();
        if self.dirty {
            let p = self.graphics?;
            if let Some(v) = &p.stages[0] {
                self.bind(e, v, 1)?;
            }
            if let Some(f) = &p.stages[1] {
                self.bind(e, f, 2)?;
            }
            self.dirty = false;
        }
        Some(e)
    }

    fn prim(&self) -> usize {
        self.graphics.map_or(3, |p| p.prim)
    }

    pub fn draw(&mut self, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) {
        let Some(e) = self.can_draw(false) else { return };
        if vertices == 0 || instances == 0 {
            return;
        }
        // SAFETY: the open render encoder with pipeline and bindings set.
        unsafe {
            msg!(e, c"drawPrimitives:vertexStart:vertexCount:instanceCount:baseInstance:", self.prim() => usize,
                 first_vertex as usize => usize, vertices as usize => usize, instances as usize => usize, first_instance as usize => usize; ());
        }
    }

    pub fn draw_indexed(&mut self, indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32) {
        let Some(e) = self.can_draw(true) else { return };
        if indices == 0 || instances == 0 {
            return;
        }
        let Some((ib, off, wide)) = self.index else { return };
        let size = if wide { 4 } else { 2 };
        // SAFETY: as in draw, with an index buffer.
        unsafe {
            msg!(e, c"drawIndexedPrimitives:indexCount:indexType:indexBuffer:indexBufferOffset:instanceCount:baseVertex:baseInstance:",
                 self.prim() => usize, indices as usize => usize, wide as usize => usize, ib => Id,
                 (off + first_index as u64 * size) as usize => usize, instances as usize => usize, base_vertex as isize => isize,
                 first_instance as usize => usize; ());
        }
    }

    fn indirect_ok(&mut self, buf: &Buffer, offset: u64, bytes: u64) -> Option<()> {
        let ok = buf.usage().contains(BufferUsage::INDIRECT) && offset % 4 == 0 && offset.checked_add(bytes).is_some_and(|e| e <= buf.size());
        self.ok(ok, "indirect: INDIRECT usage, offset (multiple of 4) or range")
    }

    /// one draw: vertex count, instance count, first vertex, first instance (4 x u32)
    pub fn draw_indirect(&mut self, buf: &'a Buffer, offset: u64) {
        if self.indirect_ok(buf, offset, 16).is_none() {
            return;
        }
        let Some(e) = self.can_draw(false) else { return };
        // SAFETY: as in draw; range checked (MTLDrawPrimitivesIndirectArguments is Vulkan's layout).
        unsafe {
            msg!(e, c"drawPrimitives:indirectBuffer:indirectBufferOffset:", self.prim() => usize, buf.0.h.id() => Id, offset as usize => usize; ());
        }
    }

    /// one indexed draw: index count, instance count, first index, base vertex (i32), first instance
    pub fn draw_indexed_indirect(&mut self, buf: &'a Buffer, offset: u64) {
        if self.indirect_ok(buf, offset, 20).is_none() {
            return;
        }
        let Some(e) = self.can_draw(true) else { return };
        let Some((ib, off, wide)) = self.index else { return };
        // SAFETY: as above (MTLDrawIndexedPrimitivesIndirectArguments is Vulkan's layout).
        unsafe {
            msg!(e, c"drawIndexedPrimitives:indexType:indexBuffer:indexBufferOffset:indirectBuffer:indirectBufferOffset:", self.prim() => usize,
                 wide as usize => usize, ib => Id, off as usize => usize, buf.0.h.id() => Id, offset as usize => usize; ());
        }
    }

    /// count indexed draws, stride bytes apart (Features::multi_draw_indirect, level Voll): Metal has no
    /// multi-draw, so a loop of single indirect draws in this encoder; DrawIndex is each one's index
    pub fn draw_indexed_indirect_multi(&mut self, buf: &'a Buffer, offset: u64, count: u32, stride: u32) {
        let ok = self.sh.features.multi_draw_indirect && stride >= 20 && stride % 4 == 0 && count > 0
            && count <= self.sh.limits.max_draw_indirect_count;
        if self.ok(ok, "draw_indexed_indirect_multi: needs multi_draw_indirect, stride >= 20").is_none()
            || self.indirect_ok(buf, offset, (count as u64 - 1) * stride as u64 + 20).is_none()
        {
            return;
        }
        let Some(e) = self.can_draw(true) else { return };
        let Some((ib, off, wide)) = self.index else { return };
        for i in 0..count {
            self.set_draw_index(e, i);
            // SAFETY: as in draw_indexed_indirect; the range of every draw was checked above.
            unsafe {
                msg!(e, c"drawIndexedPrimitives:indexType:indexBuffer:indexBufferOffset:indirectBuffer:indirectBufferOffset:", self.prim() => usize,
                     wide as usize => usize, ib => Id, off as usize => usize, buf.0.h.id() => Id, (offset + i as u64 * stride as u64) as usize => usize; ());
            }
        }
        self.set_draw_index(e, 0);
    }

    /// up to max_count indexed draws, their number (u32) read from count_buf at count_offset (level Voll:
    /// Features::draw_indirect_count).  Metal has no such draw: the pass is suspended for a compute pass that copies
    /// the max_count draws and sets the instances of those at and after the count to 0, then goes on (everything
    /// stored and loaded again, the state set again) and draws all max_count of them (docs/APPLE.md AP6g)
    pub fn draw_indexed_indirect_count(&mut self, buf: &'a Buffer, offset: u64, count_buf: &'a Buffer, count_offset: u64,
                                       max_count: u32, stride: u32) {
        let ok = self.sh.features.draw_indirect_count && stride >= 20 && stride % 4 == 0 && max_count > 0
            && max_count <= self.sh.limits.max_draw_indirect_count;
        if self.ok(ok, "draw_indexed_indirect_count: needs level Voll, stride >= 20").is_none()
            || self.indirect_ok(buf, offset, (max_count as u64 - 1) * stride as u64 + 20).is_none()
            || self.indirect_ok(count_buf, count_offset, 4).is_none()
            || self.can_draw(true).is_none()
        {
            return;
        }
        let Some(state) = self.count_state() else { return };
        let bytes = max_count as u64 * 20;
        // SAFETY: newBufferWithLength:options: returns a new private buffer (+1) or nil; the command buffer keeps
        // what its encoders use until it finished.
        let Some(draws) = Obj::new(unsafe { msg!(self.sh.dev.id(), c"newBufferWithLength:options:", bytes as usize => usize, 32usize => usize; Id) }) else {
            self.err.get_or_insert(GpuError::OutOfMemory);
            return;
        };
        self.suspend_render();
        let Some(c) = self.encoder(Kind::Compute) else { return };
        let args = [max_count, stride / 4, 0, 0];
        // SAFETY: an open compute encoder with the count kernel: thread i < max_count copies draw i (5 words, stride
        // apart from offset, range checked above) to draws[i] and clears its instance count at or after the count.
        unsafe {
            msg!(c, c"setComputePipelineState:", state => Id; ());
            msg!(c, c"setBuffer:offset:atIndex:", buf.0.h.id() => Id, offset as usize => usize, 0usize => usize; ());
            msg!(c, c"setBuffer:offset:atIndex:", count_buf.0.h.id() => Id, count_offset as usize => usize, 1usize => usize; ());
            msg!(c, c"setBuffer:offset:atIndex:", draws.id() => Id, 0usize => usize, 2usize => usize; ());
            msg!(c, c"setBytes:length:atIndex:", args.as_ptr() as *const core::ffi::c_void => *const core::ffi::c_void, 16usize => usize, 3usize => usize; ());
            msg!(c, c"dispatchThreadgroups:threadsPerThreadgroup:", MTLSize { w: max_count.div_ceil(64) as usize, h: 1, d: 1 } => MTLSize,
                 MTLSize { w: 64, h: 1, d: 1 } => MTLSize; ());
        }
        let Some(e) = self.resume_render() else { return };
        let Some(e) = self.can_draw(true).filter(|x| *x == e) else { return };
        let Some((ib, off, wide)) = self.index else { return };
        for i in 0..max_count {
            self.set_draw_index(e, i);
            // SAFETY: as in draw_indexed_indirect; draws holds max_count draws of 20 bytes.
            unsafe {
                msg!(e, c"drawIndexedPrimitives:indexType:indexBuffer:indexBufferOffset:indirectBuffer:indirectBufferOffset:", self.prim() => usize,
                     wide as usize => usize, ib => Id, off as usize => usize, draws.id() => Id, (i as u64 * 20) as usize => usize; ());
            }
        }
        self.set_draw_index(e, 0);
    }

    /// the count kernel's pipeline (compiled once per device)
    fn count_state(&mut self) -> Option<Id> {
        let mut f = self.sh.count.lock();
        if f.is_none() {
            let src = "#include <metal_stdlib>\nusing namespace metal;\n\
                       kernel void jf_count(device const uint* src [[buffer(0)]], device const uint* cnt [[buffer(1)]],\n\
                       device uint* dst [[buffer(2)]], constant uint4& a [[buffer(3)]], uint i [[thread_position_in_grid]]) {\n\
                       if (i >= a.x) { return; }\n\
                       device const uint* s = src + i * a.y;\n\
                       for (uint k = 0; k < 5; k++) { dst[i * 5 + k] = s[k]; }\n\
                       if (i >= cnt[0]) { dst[i * 5 + 1] = 0; }\n}\n";
            let made = crate::mtl_res::compile(self.sh, src).ok().and_then(|lib| {
                let _pool = Pool::new();
                let name = objc::nsstring("jf_count")?;
                // SAFETY: newFunctionWithName: / newComputePipelineStateWithFunction:error: on live objects (+1 results or nil).
                unsafe {
                    let func = Obj::new(msg!(lib.id(), c"newFunctionWithName:", name.id() => Id; Id))?;
                    let mut err: Id = objc::NIL;
                    Obj::new(msg!(self.sh.dev.id(), c"newComputePipelineStateWithFunction:error:", func.id() => Id, &mut err => *mut Id; Id))
                }
            });
            *f = made;
        }
        let id = f.as_ref().map(|o| o.id());
        drop(f);
        if id.is_none() {
            self.err.get_or_insert(GpuError::Failed(0));
        }
        id
    }

    // ------------------------------------------------------------ timestamps

    pub fn reset_timestamps(&mut self, _ts: &'a Timestamps, _first: u32, _n: u32) {
        self.ok(false, "reset_timestamps: inside a pass or range");
    }

    pub fn timestamp(&mut self, _ts: &'a Timestamps, _i: u32) {
        self.ok(false, "timestamp: index outside the set, or no timestamps on this queue");
    }

    // ------------------------------------------------------------ end

    /// the recorded commands, or the first misuse
    pub fn finish(mut self) -> Result<CommandBuffer<'a>> {
        if self.pass.is_some() {
            self.ok(false, "finish inside a render pass");
        }
        self.end_encoder();
        if let Some(e) = self.err {
            return Err(e);
        }
        let cb = self.cb.take().ok_or(GpuError::Invalid("finish twice"))?;
        Ok(CommandBuffer { cb, _borrow: PhantomData })
    }
}