mln-rs-runtime 0.0.13

Part of mln-rs, a Rust port of the MapLibre Native map rendering core. Depend on mln-rs instead.
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
//! A render target built on the thread that renders: a [`RenderTarget`]'s
//! device and surface made into the backend's objects, which belong to that
//! thread.
//!
//! [`RenderTarget`]: super::RenderTarget

// The matches over the backends' enums list a variant per backend that the
// build's features and target have, so whether their `_` arm is unreachable,
// and whether a `let` of one variant is irrefutable, depends on the build.
#![allow(
    unreachable_patterns,
    irrefutable_let_patterns,
    reason = "the backends' variants depend on the build's features and target"
)]
#![cfg_attr(
    target_family = "wasm",
    expect(
        unused_macros,
        unused_imports,
        reason = "the browser build has only canvases' backends, and none of the targets that the others make"
    )
)]

use std::rc::Rc;
use std::sync::Arc;

use mln_gfx::{ConsumerSync, ExportKind, ExportedFrame, ExportedRing, FrameTarget, RendererBackend, SyncKind, Window};
use mln_util::error::Error;
use mln_util::image::PremultipliedImage;
use mln_util::size::Size;

use super::target::{
    BorrowedRing, Device, DeviceOptions, FrameTexture, RingKind, Surface, SurfaceKind, SurfaceOverlay,
};

/// Frames read back: an offscreen target.
trait Offscreen: FrameTarget {
    fn resize(&self, size: Size);
    fn read_image(&self) -> Result<PremultipliedImage, Error>;
}

/// Frames presented: a surface target.
trait Presenting: FrameTarget {
    fn resize(&self, size: Size);
}

#[cfg(all(feature = "metal", target_vendor = "apple"))]
impl Borrowed for mln_mtl::BorrowedTarget {
    fn select(&self, slot: usize) {
        mln_mtl::BorrowedTarget::select(self, slot);
    }
    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
        mln_mtl::BorrowedTarget::release(self, slot, consumer)
    }
    fn discard(&self, slot: usize) {
        mln_mtl::BorrowedTarget::discard(self, slot);
    }
    fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error> {
        let RingKind::Metal(textures) = ring.kind else {
            return Err(Error::unsupported("a ring of Metal textures takes Metal textures only"));
        };
        mln_mtl::BorrowedTarget::replace(self, textures).map(pending)
    }
    fn take_pending(&self) -> Pending {
        pending(mln_mtl::BorrowedTarget::take_pending(self))
    }
}

#[cfg(all(feature = "metal", target_vendor = "apple"))]
impl PendingReads for mln_mtl::PendingReads {
    fn poll(&mut self) -> bool {
        mln_mtl::PendingReads::poll(self)
    }
}

/// Frames given back to the host: a ring of its textures.
trait Borrowed: FrameTarget {
    fn select(&self, slot: usize);
    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error>;
    fn discard(&self, slot: usize);
    /// Renders into `ring` from now on, and returns the host's reads of the
    /// textures that it let go of.
    fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error>;
    /// Takes the host's reads of the textures that they still wait for, for
    /// the ring to wait for before it lets go of them. A target that waits
    /// for the host's reads as it takes each texture back has none.
    fn take_pending(&self) -> Pending {
        None
    }
}

/// The host's reads of textures that a ring let go of, which the session
/// waits for before the release or replacement completes. Dropping it stops
/// waiting.
pub(crate) trait PendingReads {
    /// Whether every read ended, which it checks without blocking.
    fn poll(&mut self) -> bool;
}

/// The host's reads that a ring waits for, if any.
pub(crate) type Pending = Option<Box<dyn PendingReads>>;

/// `reads`, unless they ended already.
#[cfg(any(
    all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))),
    all(feature = "metal", target_vendor = "apple"),
    all(feature = "d3d12", windows)
))]
fn pending(mut reads: impl PendingReads + 'static) -> Pending {
    (!reads.poll()).then(|| -> Box<dyn PendingReads> { Box::new(reads) })
}

#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
impl Borrowed for mln_vulkan::BorrowedTarget {
    fn select(&self, slot: usize) {
        mln_vulkan::BorrowedTarget::select(self, slot);
    }
    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
        mln_vulkan::BorrowedTarget::release(self, slot, consumer)
    }
    fn discard(&self, slot: usize) {
        mln_vulkan::BorrowedTarget::discard(self, slot);
    }
    fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error> {
        let RingKind::Vulkan(images) = ring.kind else {
            return Err(Error::unsupported("a ring of Vulkan images takes Vulkan images only"));
        };
        mln_vulkan::BorrowedTarget::replace(self, images).map(pending)
    }
    fn take_pending(&self) -> Pending {
        pending(mln_vulkan::BorrowedTarget::take_pending(self))
    }
}

#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
impl PendingReads for mln_vulkan::PendingReads {
    fn poll(&mut self) -> bool {
        mln_vulkan::PendingReads::poll(self)
    }
}

#[cfg(all(feature = "d3d12", windows))]
impl Borrowed for mln_d3d12::BorrowedTarget {
    fn select(&self, slot: usize) {
        mln_d3d12::BorrowedTarget::select(self, slot);
    }
    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
        mln_d3d12::BorrowedTarget::release(self, slot, consumer)
    }
    fn discard(&self, slot: usize) {
        mln_d3d12::BorrowedTarget::discard(self, slot);
    }
    fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error> {
        let RingKind::D3d12(textures) = ring.kind else {
            return Err(Error::unsupported("a ring of D3D12 textures takes D3D12 textures only"));
        };
        mln_d3d12::BorrowedTarget::replace(self, textures).map(pending)
    }
    fn take_pending(&self) -> Pending {
        pending(mln_d3d12::BorrowedTarget::take_pending(self))
    }
}

#[cfg(all(feature = "d3d12", windows))]
impl PendingReads for mln_d3d12::PendingReads {
    fn poll(&mut self) -> bool {
        mln_d3d12::PendingReads::poll(self)
    }
}

/// Frames queued for the host: a ring of the target's own images, which it
/// exports.
trait Exported: FrameTarget {
    fn select(&self, slot: usize);
    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error>;
    fn discard(&self, slot: usize);
    fn resize(&self, size: Size, held: &[usize]) -> Result<bool, Error>;
    fn size(&self) -> Size;
    fn image(&self, slot: usize) -> Option<ExportedFrame>;
}

macro_rules! exported {
    ($type:ty) => {
        impl Exported for $type {
            fn select(&self, slot: usize) {
                <$type>::select(self, slot);
            }
            fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
                <$type>::release(self, slot, consumer)
            }
            fn discard(&self, slot: usize) {
                <$type>::discard(self, slot);
            }
            fn resize(&self, size: Size, held: &[usize]) -> Result<bool, Error> {
                <$type>::resize(self, size, held)
            }
            fn size(&self) -> Size {
                <$type>::size(self)
            }
            fn image(&self, slot: usize) -> Option<ExportedFrame> {
                <$type>::image(self, slot)
            }
        }
    };
}

#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
exported!(mln_vulkan::ExportedTarget);
#[cfg(all(feature = "metal", target_vendor = "apple"))]
exported!(mln_mtl::ExportedTarget);
#[cfg(all(feature = "gl", unix, not(target_vendor = "apple")))]
exported!(mln_gl::ExportedTarget);
#[cfg(all(feature = "d3d12", windows))]
exported!(mln_d3d12::ExportedTarget);

macro_rules! offscreen {
    ($type:ty) => {
        impl Offscreen for $type {
            fn resize(&self, size: Size) {
                <$type>::resize(self, size);
            }
            fn read_image(&self) -> Result<PremultipliedImage, Error> {
                <$type>::read_image(self)
            }
        }
    };
}

macro_rules! presenting {
    ($type:ty) => {
        impl Presenting for $type {
            fn resize(&self, size: Size) {
                <$type>::resize(self, size);
            }
        }
    };
}

#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
offscreen!(mln_webgpu::OffscreenTarget);
#[cfg(feature = "webgpu")]
presenting!(mln_webgpu::SurfaceTarget);
#[cfg(all(feature = "metal", target_vendor = "apple"))]
offscreen!(mln_mtl::OffscreenTarget);
#[cfg(all(feature = "metal", target_vendor = "apple"))]
presenting!(mln_mtl::SurfaceTarget);
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
offscreen!(mln_vulkan::OffscreenTarget);
#[cfg(all(feature = "d3d12", windows))]
offscreen!(mln_d3d12::OffscreenTarget);
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
presenting!(mln_vulkan::SurfaceTarget);
#[cfg(all(feature = "d3d12", windows))]
presenting!(mln_d3d12::SurfaceTarget);
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
offscreen!(mln_gl::OffscreenTarget);
#[cfg(all(feature = "gl", any(windows, all(unix, not(target_vendor = "apple")))))]
presenting!(mln_gl::SurfaceTarget);
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
presenting!(mln_gl::HostSurfaceTarget);
#[cfg(all(feature = "gl", target_family = "wasm"))]
presenting!(mln_gl::CanvasTarget);

#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
impl Borrowed for mln_webgpu::BorrowedTarget {
    fn select(&self, slot: usize) {
        mln_webgpu::BorrowedTarget::select(self, slot);
    }
    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
        mln_webgpu::BorrowedTarget::release(self, slot, consumer)
    }
    fn discard(&self, slot: usize) {
        mln_webgpu::BorrowedTarget::discard(self, slot);
    }
    fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error> {
        let RingKind::WebGpu(textures) = ring.kind else {
            return Err(Error::unsupported("a ring of WebGPU textures takes WebGPU textures only"));
        };
        mln_webgpu::BorrowedTarget::replace(self, textures).map(|()| None)
    }
}

#[cfg(all(feature = "gl", not(target_family = "wasm")))]
impl Borrowed for mln_gl::BorrowedTarget {
    fn select(&self, slot: usize) {
        mln_gl::BorrowedTarget::select(self, slot);
    }
    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
        mln_gl::BorrowedTarget::release(self, slot, consumer)
    }
    fn discard(&self, slot: usize) {
        mln_gl::BorrowedTarget::discard(self, slot);
    }
    fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error> {
        let RingKind::Gl(textures) = ring.kind else {
            return Err(Error::unsupported("a ring of OpenGL textures takes OpenGL textures only"));
        };
        mln_gl::BorrowedTarget::replace(self, textures).map(|()| None)
    }
}

/// A backend, by its type.
#[derive(Clone)]
enum Backend {
    #[cfg(feature = "webgpu")]
    WebGpu(Rc<mln_webgpu::RendererBackend>),
    #[cfg(all(feature = "metal", target_vendor = "apple"))]
    Metal(Rc<mln_mtl::RendererBackend>),
    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
    Vulkan(Rc<mln_vulkan::RendererBackend>),
    #[cfg(all(feature = "d3d12", windows))]
    D3d12(Rc<mln_d3d12::RendererBackend>),
    #[cfg(feature = "gl")]
    Gl(Rc<mln_gl::RendererBackend>),
}

impl Backend {
    fn as_dyn(&self) -> Rc<dyn RendererBackend> {
        match *self {
            #[cfg(feature = "webgpu")]
            Backend::WebGpu(ref backend) => Rc::<mln_webgpu::RendererBackend>::clone(backend),
            #[cfg(all(feature = "metal", target_vendor = "apple"))]
            Backend::Metal(ref backend) => Rc::<mln_mtl::RendererBackend>::clone(backend),
            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
            Backend::Vulkan(ref backend) => Rc::<mln_vulkan::RendererBackend>::clone(backend),
            #[cfg(all(feature = "d3d12", windows))]
            Backend::D3d12(ref backend) => Rc::<mln_d3d12::RendererBackend>::clone(backend),
            #[cfg(feature = "gl")]
            Backend::Gl(ref backend) => Rc::<mln_gl::RendererBackend>::clone(backend),
        }
    }

    /// A backend on `device`, for offscreen targets and the surfaces that
    /// the device's backend makes on it.
    #[cfg_attr(
        not(any(
            feature = "gl",
            all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))),
            all(feature = "d3d12", windows)
        )),
        expect(clippy::unnecessary_wraps, reason = "only Vulkan, D3D12 and OpenGL backends can fail to start")
    )]
    fn new(device: &Device) -> Result<Backend, Error> {
        match *device {
            #[cfg(feature = "webgpu")]
            Device::WebGpu(ref device) => Ok(Backend::WebGpu(Rc::new(mln_webgpu::RendererBackend::new(device)))),
            #[cfg(all(feature = "metal", target_vendor = "apple"))]
            Device::Metal(ref device) => Ok(Backend::Metal(Rc::new(mln_mtl::RendererBackend::new(device)))),
            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
            Device::Vulkan(ref device) => Ok(Backend::Vulkan(Rc::new(mln_vulkan::RendererBackend::new(device)?))),
            #[cfg(all(feature = "d3d12", windows))]
            Device::D3d12(ref device) => Ok(Backend::D3d12(Rc::new(
                mln_d3d12::RendererBackend::new(device).map_err(|error| Error::native(error.to_string()))?,
            ))),
            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
            Device::Gl(ref device) => Ok(Backend::Gl(Rc::new(mln_gl::RendererBackend::new(device)?))),
            #[cfg(all(feature = "gl", target_family = "wasm"))]
            Device::WebGl => {
                Err(Error::unsupported("WebGL2 renders only into a canvas, with the canvas's own context"))
            }
        }
    }

    /// A target on the backend that renders into `ring`, handing frames over
    /// with sync of the kind `producer`.
    fn borrowed(&self, ring: BorrowedRing, producer: SyncKind) -> Result<Box<dyn Borrowed>, Error> {
        match (self, ring.kind) {
            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
            (Backend::Vulkan(backend), RingKind::Vulkan(images)) => {
                Ok(Box::new(mln_vulkan::BorrowedTarget::new(Rc::clone(backend), images, producer)?))
            }
            #[cfg(all(feature = "metal", target_vendor = "apple"))]
            (Backend::Metal(backend), RingKind::Metal(textures)) => {
                Ok(Box::new(mln_mtl::BorrowedTarget::new(Rc::clone(backend), textures, producer)?))
            }
            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
            (Backend::WebGpu(backend), RingKind::WebGpu(textures)) => {
                Ok(Box::new(mln_webgpu::BorrowedTarget::new(Rc::clone(backend), textures, producer)?))
            }
            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
            (Backend::Gl(backend), RingKind::Gl(textures)) => {
                Ok(Box::new(mln_gl::BorrowedTarget::new(Rc::clone(backend), textures, producer)?))
            }
            #[cfg(all(feature = "d3d12", windows))]
            (Backend::D3d12(backend), RingKind::D3d12(textures)) => {
                Ok(Box::new(mln_d3d12::BorrowedTarget::new(Rc::clone(backend), textures, producer)?))
            }
            _ => {
                let _ = producer;
                Err(Error::unsupported("the session's backend renders into no ring of this kind"))
            }
        }
    }

    /// A target on the backend that renders into a ring of `ring.depth`
    /// images of `size` pixels, which it exports as `kind`, and hands frames
    /// over with sync of the kind `producer`.
    fn exported(
        &self,
        device: &Device,
        ring: &ExportedRing,
        kind: ExportKind,
        size: Size,
        producer: SyncKind,
    ) -> Result<Box<dyn Exported>, Error> {
        match self {
            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
            Backend::Vulkan(backend) => {
                Ok(Box::new(mln_vulkan::ExportedTarget::new(Rc::clone(backend), ring, kind, size, producer)?))
            }
            #[cfg(all(feature = "metal", target_vendor = "apple"))]
            Backend::Metal(backend) => {
                Ok(Box::new(mln_mtl::ExportedTarget::new(Rc::clone(backend), ring, kind, size, producer)?))
            }
            #[cfg(all(feature = "gl", unix, not(target_vendor = "apple")))]
            Backend::Gl(backend) => {
                // Irrefutable in a build with OpenGL alone, which has no other
                // kind of device, and refutable in one with other backends.
                let Device::Gl(device) = device else {
                    return Err(Error::unsupported("an OpenGL backend renders on an OpenGL device"));
                };
                Ok(Box::new(mln_gl::ExportedTarget::new(Rc::clone(backend), device, ring, kind, size, producer)?))
            }
            #[cfg(all(feature = "d3d12", windows))]
            Backend::D3d12(backend) => {
                Ok(Box::new(mln_d3d12::ExportedTarget::new(Rc::clone(backend), ring, kind, size, producer)?))
            }
            _ => {
                let _ = (device, ring, kind, size, producer);
                Err(Error::unsupported("the session's backend exports no ring"))
            }
        }
    }

    /// An offscreen target of `size` pixels on the backend: none in the
    /// browser, which renders into canvases.
    #[cfg(target_family = "wasm")]
    #[expect(clippy::unused_self, reason = "the other builds' targets are of the backend")]
    fn offscreen(&self, _size: Size) -> Result<Box<dyn Offscreen>, Error> {
        Err(Error::unsupported("the browser build renders into canvases only"))
    }

    /// An offscreen target of `size` pixels on the backend.
    #[cfg(not(target_family = "wasm"))]
    #[expect(clippy::unnecessary_wraps, reason = "the browser build's fails")]
    fn offscreen(&self, size: Size) -> Result<Box<dyn Offscreen>, Error> {
        Ok(match *self {
            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
            Backend::WebGpu(ref backend) => Box::new(mln_webgpu::OffscreenTarget::new(Rc::clone(backend), size)),
            #[cfg(all(feature = "metal", target_vendor = "apple"))]
            Backend::Metal(ref backend) => Box::new(mln_mtl::OffscreenTarget::new(Rc::clone(backend), size)),
            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
            Backend::Vulkan(ref backend) => Box::new(mln_vulkan::OffscreenTarget::new(Rc::clone(backend), size)),
            #[cfg(all(feature = "d3d12", windows))]
            Backend::D3d12(ref backend) => Box::new(mln_d3d12::OffscreenTarget::new(Rc::clone(backend), size)),
            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
            Backend::Gl(ref backend) => Box::new(mln_gl::OffscreenTarget::new(Rc::clone(backend), size)),
        })
    }

    /// A target on the backend that presents to `surface`, at `size`
    /// pixels, with `overlay` drawn over its frames. Fails with
    /// `Unsupported` when only a backend of the target's own can present to
    /// it: see [`surface_backend`].
    fn surface(
        &self,
        surface: Surface,
        overlay: Option<SurfaceOverlay>,
        size: Size,
    ) -> Result<Box<dyn Presenting>, Error> {
        match (self, surface.kind) {
            #[cfg(feature = "webgpu")]
            (Backend::WebGpu(backend), kind) => {
                #[cfg(target_family = "wasm")]
                let format = match &kind {
                    SurfaceKind::WebCanvas { format: Some(format), .. } => Some(match format {
                        super::target::CanvasFormat::Bgra8Unorm => wgpu::TextureFormat::Bgra8Unorm,
                        super::target::CanvasFormat::Rgba8Unorm => wgpu::TextureFormat::Rgba8Unorm,
                        super::target::CanvasFormat::Rgba16Float => wgpu::TextureFormat::Rgba16Float,
                    }),
                    _ => None,
                };
                #[cfg(not(target_family = "wasm"))]
                let format = None;
                let target = webgpu_surface(backend, kind)?;
                let options = mln_webgpu::SurfaceOptions { format, ..mln_webgpu::SurfaceOptions::default() };
                let target = mln_webgpu::SurfaceTarget::new(Rc::clone(backend), target, size, options)?;
                target.set_overlay(overlay_of(overlay, |overlay| match overlay {
                    SurfaceOverlay::WebGpu(overlay) => Ok(overlay),
                    other => Err(other),
                })?);
                Ok(Box::new(target))
            }
            #[cfg(all(feature = "metal", target_vendor = "apple"))]
            (Backend::Metal(backend), SurfaceKind::MetalLayer(layer)) => {
                let target = mln_mtl::SurfaceTarget::new(backend, layer, size, true);
                target.set_overlay(overlay_of(overlay, |overlay| match overlay {
                    SurfaceOverlay::Metal(overlay) => Ok(overlay),
                    other => Err(other),
                })?);
                Ok(Box::new(target))
            }
            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
            (Backend::Vulkan(backend), SurfaceKind::Window(window)) => {
                let target = mln_vulkan::SurfaceTarget::new(Rc::clone(backend), window, size, true)?;
                target.set_overlay(vulkan_overlay(overlay)?);
                Ok(Box::new(target))
            }
            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
            (Backend::Vulkan(backend), SurfaceKind::Vulkan(surface)) => {
                let target = mln_vulkan::SurfaceTarget::on_host_surface(Rc::clone(backend), surface, size, true)?;
                target.set_overlay(vulkan_overlay(overlay)?);
                Ok(Box::new(target))
            }
            #[cfg(all(feature = "d3d12", windows))]
            (Backend::D3d12(backend), SurfaceKind::Window(window)) => {
                let overlay = d3d12_overlay(overlay)?;
                let target = mln_d3d12::SurfaceTarget::new(Rc::clone(backend), window, size)?;
                target.set_overlay(overlay);
                Ok(Box::new(target))
            }
            #[cfg(all(feature = "d3d12", windows))]
            (Backend::D3d12(backend), SurfaceKind::D3d12Composition { composition, thread }) => {
                if composition.is_swap_chain_panel() && thread != std::thread::current().id() {
                    return Err(Error::unsupported(
                        "a SwapChainPanel takes its swap chain on its UI thread, which made the surface: attach it \
                         with Driver::CallerThread, serviced there",
                    ));
                }
                let overlay = d3d12_overlay(overlay)?;
                let target = mln_d3d12::SurfaceTarget::for_composition(Rc::clone(backend), composition, size)?;
                target.set_overlay(overlay);
                Ok(Box::new(target))
            }
            _ => {
                let _ = (size, overlay);
                Err(Error::unsupported("the session's backend presents to no surface of this kind"))
            }
        }
    }
}

/// The overlay of the backend that `own` picks out of `overlay`. Fails with
/// `Unsupported` for another backend's.
#[cfg_attr(
    not(any(
        feature = "webgpu",
        all(feature = "metal", target_vendor = "apple"),
        all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))),
        all(feature = "d3d12", windows),
        all(feature = "gl", any(windows, all(unix, not(target_vendor = "apple")))),
    )),
    expect(dead_code, reason = "a build without a backend that takes overlays uses none")
)]
fn overlay_of<T>(
    overlay: Option<SurfaceOverlay>,
    own: impl FnOnce(SurfaceOverlay) -> Result<T, SurfaceOverlay>,
) -> Result<Option<T>, Error> {
    overlay
        .map(own)
        .transpose()
        .map_err(|_| Error::unsupported("the surface's overlay is for another backend than the session's"))
}

#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
fn vulkan_overlay(overlay: Option<SurfaceOverlay>) -> Result<Option<Box<dyn mln_vulkan::Overlay>>, Error> {
    overlay_of(overlay, |overlay| match overlay {
        SurfaceOverlay::Vulkan(overlay) => Ok(overlay),
        other => Err(other),
    })
}

#[cfg(all(feature = "d3d12", windows))]
fn d3d12_overlay(overlay: Option<SurfaceOverlay>) -> Result<Option<Box<dyn mln_d3d12::Overlay>>, Error> {
    overlay_of(overlay, |overlay| match overlay {
        SurfaceOverlay::D3d12(overlay) => Ok(overlay),
        other => Err(other),
    })
}

/// A wgpu surface of `kind`, made with the instance of `backend`'s device
/// where the host didn't make it.
#[cfg(feature = "webgpu")]
fn webgpu_surface(backend: &mln_webgpu::RendererBackend, kind: SurfaceKind) -> Result<wgpu::Surface<'static>, Error> {
    let instance = || {
        backend
            .device()
            .instance()
            .ok_or_else(|| Error::invalid_argument("the session's device has no instance to make a surface with"))
    };
    let made = match kind {
        #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
        SurfaceKind::Wgpu(surface) => return Ok(surface),
        SurfaceKind::Window(window) => instance()?.create_surface(window),
        #[cfg(target_family = "wasm")]
        SurfaceKind::WebCanvas { canvas, .. } => {
            use wasm_bindgen::JsCast as _;
            let target = match canvas.dyn_into::<web_sys::OffscreenCanvas>() {
                Ok(canvas) => wgpu::SurfaceTarget::OffscreenCanvas(canvas),
                Err(canvas) => wgpu::SurfaceTarget::Canvas(canvas.unchecked_into()),
            };
            instance()?.create_surface(target)
        }
        #[cfg(all(feature = "metal", target_vendor = "apple"))]
        SurfaceKind::MetalLayer(_) => return Err(Error::unsupported("a Metal layer presents on a Metal device")),
        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
        SurfaceKind::Vulkan(_) => return Err(Error::unsupported("a Vulkan surface presents on a Vulkan device")),
        #[cfg(all(feature = "gl", not(target_family = "wasm")))]
        SurfaceKind::Gl(_) => return Err(Error::unsupported("an EGL surface presents on an OpenGL device")),
        #[cfg(all(feature = "d3d12", windows))]
        SurfaceKind::D3d12Composition { .. } => {
            return Err(Error::unsupported("a composition swap chain presents on a D3D12 device"));
        }
    };
    made.map_err(|error| Error::native(format!("can't make a surface on the window: {error}")))
}

/// A backend of the target's own on `device` and a target that presents to
/// `surface` with `overlay` drawn over its frames, for the backends whose
/// context or device is made for the window: Vulkan's, whose instance and
/// device take the window's surface extensions, and OpenGL ES's, whose
/// context is of the window's display.
fn surface_backend(
    device: &Device,
    surface: Surface,
    overlay: Option<SurfaceOverlay>,
    size: Size,
) -> Result<(Backend, Box<dyn Presenting>), Error> {
    match (device, surface.kind) {
        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
        (Device::Vulkan(device), SurfaceKind::Window(window)) => {
            let overlay = vulkan_overlay(overlay)?;
            let (backend, target) = mln_vulkan::SurfaceTarget::with_backend(device, window, size, true)?;
            target.set_overlay(overlay);
            Ok((Backend::Vulkan(backend), Box::new(target)))
        }
        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
        (Device::Vulkan(device), kind @ SurfaceKind::Vulkan(_)) => {
            let backend = Backend::Vulkan(Rc::new(mln_vulkan::RendererBackend::presenting(device)?));
            let target = backend.surface(Surface { kind }, overlay, size)?;
            Ok((backend, target))
        }
        #[cfg(all(feature = "gl", not(target_family = "wasm")))]
        (Device::Gl(device), SurfaceKind::Gl(host)) => {
            if overlay.is_some() {
                return Err(Error::unsupported("a host's EGL surface takes no overlay"));
            }
            let (backend, target) = mln_gl::HostSurfaceTarget::with_backend(device, host, size)?;
            Ok((Backend::Gl(backend), Box::new(target)))
        }
        #[cfg(all(feature = "gl", any(windows, all(unix, not(target_vendor = "apple")))))]
        (Device::Gl(_), SurfaceKind::Window(window)) => {
            let overlay = overlay_of(overlay, |overlay| match overlay {
                SurfaceOverlay::Gl(overlay) => Ok(overlay),
                other => Err(other),
            })?;
            let (backend, target) = mln_gl::SurfaceTarget::with_backend(window, size, true)?;
            target.set_overlay(overlay);
            Ok((Backend::Gl(backend), Box::new(target)))
        }
        #[cfg(all(feature = "gl", target_family = "wasm"))]
        (Device::WebGl, SurfaceKind::WebCanvas { canvas, .. }) => {
            use wasm_bindgen::JsCast as _;
            // WebGL draws no overlay.
            let canvas = match canvas.dyn_into::<web_sys::OffscreenCanvas>() {
                Ok(canvas) => mln_gl::WebCanvas::Offscreen(canvas),
                Err(canvas) => mln_gl::WebCanvas::Element(canvas.unchecked_into()),
            };
            let (backend, target) = mln_gl::CanvasTarget::with_backend(canvas, size)?;
            Ok((Backend::Gl(backend), Box::new(target)))
        }
        (_, kind) => {
            let backend = Backend::new(device)?;
            let target = backend.surface(Surface { kind }, overlay, size)?;
            Ok((backend, target))
        }
    }
}

enum Frames {
    Offscreen(Box<dyn Offscreen>),
    /// `None` once the surface is released.
    Presenting(Option<Box<dyn Presenting>>),
    /// `target` is `None` once the ring is released.
    Borrowed {
        target: Option<Box<dyn Borrowed>>,
        producer: SyncKind,
    },
    Exported(Box<dyn Exported>),
}

/// A render target built on this thread: the backend that a renderer draws
/// with, on the target's device, and the frames it draws into.
pub struct LocalTarget {
    device: Device,
    backend: Backend,
    frames: Frames,
    /// The window that a surface target presents to, if it presents to one.
    window: Option<Arc<dyn Window>>,
}

impl LocalTarget {
    /// An offscreen target of `size` pixels on `device`, or on a device that
    /// [`Device::new`] makes when that is `None`.
    ///
    /// Fails as [`Device::new`] does, and with the backend's error when it
    /// can't render on the device.
    pub fn offscreen(device: Option<Device>, size: Size) -> Result<LocalTarget, Error> {
        let device = match device {
            Some(device) => device,
            None => Device::new(DeviceOptions::default())?,
        };
        let backend = Backend::new(&device)?;
        let frames = Frames::Offscreen(backend.offscreen(size)?);
        Ok(LocalTarget { device, backend, frames, window: None })
    }

    /// A target of `size` pixels that presents to `surface`, with `overlay`
    /// drawn over its frames, on `device` or, when that is `None`, on the
    /// device the surface's kind takes
    /// ([`RenderTarget::Surface`](super::RenderTarget::Surface)).
    ///
    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a
    /// surface that the host made without the host's device, with
    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) for a window or
    /// surface without an area to present to, such as a minimized window,
    /// with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the device
    /// can't present to the surface or draw the overlay, and with the error
    /// of the device or the window's surface.
    pub fn surface(
        surface: Surface,
        overlay: Option<SurfaceOverlay>,
        device: Option<Device>,
        size: Size,
    ) -> Result<LocalTarget, Error> {
        surface.check_area()?;
        let window = surface.host_window();
        let device = match device {
            Some(device) => device,
            None => default_surface_device(&surface)?,
        };
        let (backend, target) = surface_backend(&device, surface, overlay, size)?;
        Ok(LocalTarget { device, backend, frames: Frames::Presenting(Some(target)), window })
    }

    /// A target of `size` pixels on `device` that renders into the host's
    /// `ring`, and hands each frame over with sync of the kind `producer`.
    ///
    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the
    /// device can't render into the ring with `producer`, and with the
    /// backend's error.
    pub fn borrowed(device: Device, ring: BorrowedRing, producer: SyncKind) -> Result<LocalTarget, Error> {
        let backend = Backend::new(&device)?;
        let frames = Frames::Borrowed { target: Some(backend.borrowed(ring, producer)?), producer };
        Ok(LocalTarget { device, backend, frames, window: None })
    }

    /// A target on `device` that renders into a ring of `ring.depth` images
    /// of `size` pixels, which it exports as `kind`, one that
    /// [`Device::export_plan`] picked, and hands each frame over with sync of
    /// the kind `producer`.
    ///
    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the
    /// device can't export `kind` or hand frames over with `producer`, and
    /// with the backend's error.
    pub fn exported(
        device: Device,
        ring: &ExportedRing,
        kind: ExportKind,
        size: Size,
        producer: SyncKind,
    ) -> Result<LocalTarget, Error> {
        let backend = Backend::new(&device)?;
        let frames = Frames::Exported(backend.exported(&device, ring, kind, size, producer)?);
        Ok(LocalTarget { device, backend, frames, window: None })
    }

    /// The device the target renders on.
    #[must_use]
    pub fn device(&self) -> &Device {
        &self.device
    }

    /// The backend that renderers drawing into the target draw with.
    #[must_use]
    pub fn backend(&self) -> Rc<dyn RendererBackend> {
        self.backend.as_dyn()
    }

    /// The frames to draw into, or `None` while a surface target has no
    /// surface.
    #[must_use]
    pub fn frames(&self) -> Option<&dyn FrameTarget> {
        match &self.frames {
            Frames::Offscreen(target) => Some(&**target),
            Frames::Presenting(target) => target.as_deref().map(|target| -> &dyn FrameTarget { target }),
            Frames::Borrowed { target, .. } => target.as_deref().map(|target| -> &dyn FrameTarget { target }),
            Frames::Exported(target) => Some(&**target),
        }
    }

    /// Whether the target can take a frame as far as its window says: it
    /// presents to no window, or to one with an area to present to
    /// ([`mln_gfx::window::has_area`]).
    #[must_use]
    pub fn window_has_area(&self) -> bool {
        self.window.as_deref().is_none_or(mln_gfx::window::has_area)
    }

    /// Whether frames are presented to a window or surface.
    #[must_use]
    pub fn is_presenting(&self) -> bool {
        matches!(self.frames, Frames::Presenting(_))
    }

    /// Whether frames go to the host in images of the target's own.
    #[must_use]
    pub fn is_exported(&self) -> bool {
        matches!(self.frames, Frames::Exported(_))
    }

    /// Whether frames go to the host's ring.
    #[must_use]
    pub fn is_borrowed(&self) -> bool {
        matches!(self.frames, Frames::Borrowed { .. })
    }

    /// Whether the target is a ring that let go of its textures.
    #[must_use]
    pub fn ring_released(&self) -> bool {
        matches!(self.frames, Frames::Borrowed { target: None, .. })
    }

    fn ring(&self) -> Result<&dyn Borrowed, Error> {
        match &self.frames {
            Frames::Borrowed { target: Some(target), .. } => Ok(&**target),
            Frames::Borrowed { target: None, .. } => Err(Error::invalid_state("the ring was released")),
            _ => Err(Error::unsupported("the target has no ring")),
        }
    }

    /// Has the next frame render into the ring's texture at `slot`.
    pub fn select_slot(&self, slot: usize) -> Result<(), Error> {
        if let Frames::Exported(target) = &self.frames {
            target.select(slot);
            return Ok(());
        }
        self.ring()?.select(slot);
        Ok(())
    }

    /// The host gave the ring's texture at `slot` back: the next frame
    /// rendered into it waits for `consumer`.
    pub fn release_slot(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
        if let Frames::Exported(target) = &self.frames {
            return target.release(slot, consumer);
        }
        self.ring()?.release(slot, consumer)
    }

    /// The host gave up the ring's texture at `slot`, which the target
    /// renders into no more.
    pub fn discard_slot(&self, slot: usize) -> Result<(), Error> {
        if let Frames::Exported(target) = &self.frames {
            target.discard(slot);
            return Ok(());
        }
        self.ring()?.discard(slot);
        Ok(())
    }

    /// The size in pixels of an exported ring's images, or `None` for
    /// another target.
    #[must_use]
    pub fn exported_size(&self) -> Option<Size> {
        match &self.frames {
            Frames::Exported(target) => Some(target.size()),
            _ => None,
        }
    }

    /// Renders an exported ring's next frames into images of `size` pixels.
    /// The frames that the host holds, at `held` slots, keep their images.
    /// Returns whether the ring has new images, which it doesn't when they
    /// have `size` already.
    ///
    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
    /// target that isn't an exported ring, and with the backend's error, when
    /// the ring keeps its images.
    pub fn resize_exported(&self, size: Size, held: &[usize]) -> Result<bool, Error> {
        match &self.frames {
            Frames::Exported(target) => target.resize(size, held),
            _ => Err(Error::unsupported("the target exports no ring")),
        }
    }

    /// The exported image of the frame at `slot`, of the size it has.
    #[must_use]
    pub fn exported_texture(&self, slot: usize) -> Option<FrameTexture> {
        match &self.frames {
            Frames::Exported(target) => target.image(slot).map(|frame| FrameTexture::exported(frame, &self.device)),
            _ => None,
        }
    }

    /// Renders into `ring` from now on, in place of the ring's textures, and
    /// returns the host's reads of the textures that it let go of, which the
    /// host may use once they end.
    ///
    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
    /// target that isn't a ring, or a ring of another format, and with the
    /// backend's error.
    pub(crate) fn set_ring(&mut self, ring: BorrowedRing) -> Result<Pending, Error> {
        match &mut self.frames {
            Frames::Borrowed { target: Some(target), .. } => target.replace(ring),
            Frames::Borrowed { target, producer } => {
                *target = Some(self.backend.borrowed(ring, *producer)?);
                Ok(None)
            }
            _ => Err(Error::unsupported("the target has no ring")),
        }
    }

    /// Whether frames are read back rather than presented.
    #[must_use]
    pub fn is_offscreen(&self) -> bool {
        matches!(self.frames, Frames::Offscreen(_))
    }

    /// Draws the next frame at `size` pixels.
    pub fn resize(&self, size: Size) {
        match &self.frames {
            Frames::Offscreen(target) => target.resize(size),
            Frames::Presenting(Some(target)) => target.resize(size),
            Frames::Presenting(None) | Frames::Borrowed { .. } | Frames::Exported(_) => {}
        }
    }

    /// The last frame's pixels.
    ///
    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
    /// target that presents its frames, with
    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) before a frame, and
    /// with [`ErrorKind::Native`](mln_util::ErrorKind) where the backend
    /// reads nothing back.
    pub fn read_image(&self) -> Result<PremultipliedImage, Error> {
        match &self.frames {
            Frames::Offscreen(target) => target.read_image(),
            Frames::Presenting(_) => Err(Error::unsupported("a surface session can't read its frames back")),
            Frames::Borrowed { .. } | Frames::Exported(_) => {
                Err(Error::unsupported("a ring's frames are the host's to read"))
            }
        }
    }

    /// Lets go of a surface target's surface, or of a ring's textures, and
    /// returns the host's reads of the textures, which the host may use once
    /// they end. The backend stays.
    pub(crate) fn release_surface(&mut self) -> Pending {
        match &mut self.frames {
            Frames::Presenting(target) => {
                drop(target.take());
                self.window = None;
                None
            }
            Frames::Borrowed { target, .. } => target.take().and_then(|target| target.take_pending()),
            Frames::Offscreen(_) | Frames::Exported(_) => None,
        }
    }

    /// Presents to `surface` at `size` pixels from now on, with `overlay`
    /// drawn over its frames, in place of the surface the target has, if
    /// any: on the same backend where it can present to `surface`, and on a
    /// new one of the device otherwise, which the target then returns true
    /// for, and which draws no overlay. A renderer on the old backend has to
    /// be made again on the new one.
    ///
    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for an
    /// offscreen target or when the device can't present to `surface`, and
    /// as [`surface`](Self::surface) does. The target then keeps what it
    /// had.
    pub fn set_surface(
        &mut self,
        surface: Surface,
        overlay: Option<SurfaceOverlay>,
        size: Size,
    ) -> Result<bool, Error> {
        if !matches!(self.frames, Frames::Presenting(_)) {
            return Err(Error::unsupported("only a surface target presents to another surface"));
        }
        surface.check_area()?;
        let window = surface.host_window();
        let retry = surface.clone_window();
        let (new_backend, target) = match self.backend.surface(surface, overlay, size) {
            Ok(target) => (false, target),
            Err(error) if error.kind == mln_util::ErrorKind::Unsupported => {
                let surface = retry.ok_or(error)?;
                let (backend, target) = surface_backend(&self.device, surface, None, size)?;
                self.backend = backend;
                (true, target)
            }
            Err(error) => return Err(error),
        };
        self.frames = Frames::Presenting(Some(target));
        self.window = window;
        Ok(new_backend)
    }
}

/// The device a surface renders on without the host's: the native one where
/// its backend takes the surface's kind.
fn default_surface_device(surface: &Surface) -> Result<Device, Error> {
    match surface.kind {
        SurfaceKind::Window(_) if cfg!(target_vendor = "apple") => {
            Device::with_backend(super::target::BackendType::WebGPU, DeviceOptions::default())
        }
        SurfaceKind::Window(_) => Device::new(DeviceOptions::default()),
        #[cfg(all(feature = "metal", target_vendor = "apple"))]
        SurfaceKind::MetalLayer(_) => Device::with_backend(super::target::BackendType::Metal, DeviceOptions::default()),
        #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
        SurfaceKind::Wgpu(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
        SurfaceKind::Vulkan(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
        #[cfg(all(feature = "gl", not(target_family = "wasm")))]
        SurfaceKind::Gl(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
        #[cfg(all(feature = "d3d12", windows))]
        SurfaceKind::D3d12Composition { .. } => {
            Device::with_backend(super::target::BackendType::D3D12, DeviceOptions::default())
        }
        // A WebGPU build asked the browser for a device before the build.
        #[cfg(all(target_family = "wasm", feature = "gl"))]
        SurfaceKind::WebCanvas { .. } => Ok(Device::WebGl),
        #[cfg(all(target_family = "wasm", not(feature = "gl")))]
        SurfaceKind::WebCanvas { .. } => Err(Error::invalid_state("the browser's WebGPU device isn't there yet")),
    }
}