-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
_api.py
3644 lines (3147 loc) · 150 KB
/
_api.py
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
"""
WGPU backend implementation based on wgpu-native.
The wgpu-native project (https://github.com/gfx-rs/wgpu-native) is a Rust
library based on wgpu-core, which wraps Metal, Vulkan, DX12, and more.
It compiles to a dynamic library exposing a C-API, accompanied by a C
header file. We wrap this using cffi, which uses the header file to do
most type conversions for us.
This module is maintained using a combination of manual code and
automatically inserted code. In short, the codegen utility inserts
new methods and checks plus annotates all structs and C api calls.
Read the codegen/readme.md for more information.
"""
# Allow using class names in type annotations, before the class is defined. Py3.7+
from __future__ import annotations
import os
import logging
from weakref import WeakKeyDictionary
from typing import List, Dict, Union, Optional
from ... import classes, flags, enums, structs
from ..._coreutils import str_flag_to_int
from ._ffi import ffi, lib
from ._mappings import cstructfield2enum, enummap, enum_str2int, enum_int2str
from ._helpers import (
get_wgpu_instance,
get_surface_id_from_info,
get_memoryview_from_address,
get_memoryview_and_address,
to_snake_case,
ErrorHandler,
WgpuAwaitable,
SafeLibCalls,
)
logger = logging.getLogger("wgpu")
# The API is pretty well defined
__all__ = classes.__all__.copy()
# %% Helper functions and objects
# The 'optional' value is used as the default value for certain optional arguments, see the comment in _classes.py for details.
optional = None
def check_can_use_sync_variants():
if False: # placeholder, let's implement a little wgpu config thingy
raise RuntimeError("Disallowed use of '_sync' API.")
# Object to be able to bind the lifetime of objects to other objects
_refs_per_struct = WeakKeyDictionary()
# Some enum keys need a shortcut
_cstructfield2enum_alt = {
"load_op": "LoadOp",
"store_op": "StoreOp",
"depth_store_op": "StoreOp",
"stencil_store_op": "StoreOp",
}
def new_struct_p(ctype, **kwargs):
"""Create a pointer to an ffi struct. Provides a flatter syntax
and converts our string enums to int enums needed in C. The passed
kwargs are also bound to the lifetime of the new struct.
"""
assert ctype.endswith(" *")
struct_p = _new_struct_p(ctype, **kwargs)
_refs_per_struct[struct_p] = kwargs
return struct_p
# Some kwargs may be other ffi objects, and some may represent
# pointers. These need special care because them "being in" the
# current struct does not prevent them from being cleaned up by
# Python's garbage collector. Keeping hold of these objects in the
# calling code is painful and prone to missing cases, so we solve
# the issue here. We cannot attach an attribute to the struct directly,
# so we use a global WeakKeyDictionary. Also see issue #52.
def new_struct(ctype, **kwargs):
"""Create an ffi value struct. The passed kwargs are also bound
to the lifetime of the new struct.
"""
assert not ctype.endswith("*")
struct_p = _new_struct_p(ctype + " *", **kwargs)
struct = struct_p[0]
_refs_per_struct[struct] = kwargs
return struct
def _new_struct_p(ctype, **kwargs):
struct_p = ffi.new(ctype)
for key, val in kwargs.items():
if isinstance(val, str) and isinstance(getattr(struct_p, key), int):
# An enum - these are ints in C, but str in our public API
if key in _cstructfield2enum_alt:
structname = _cstructfield2enum_alt[key]
else:
structname = cstructfield2enum[ctype.strip(" *")[4:] + "." + key]
ival = enummap[structname + "." + val]
setattr(struct_p, key, ival)
else:
setattr(struct_p, key, val)
return struct_p
def _tuple_from_tuple_or_dict(ob, fields, defaults=()):
"""Given a tuple/list/dict, return a tuple. Also checks tuple size.
>> # E.g.
>> _tuple_from_tuple_or_dict({"x": 1, "y": 2}, ("x", "y"))
(1, 2)
>> _tuple_from_tuple_or_dict([1, 2], ("x", "y"))
(1, 2)
If defaults are given, it will be the default values. If the length of defaults is
shorter than the length of fields, it gives the default values for the final args.
Other arguments are still required.
>> _tuple_from_tuple_or_dict({"x": 1}, ("x", "y"), (2,))
(1, 2)
>> _tuple_from_tuple_or_dict([], ("x", "y"), (1, 2))
(1, 2)
"""
error_msg = "Expected tuple/key/dict with fields: {}"
required = len(fields) - len(defaults)
if isinstance(ob, (list, tuple)):
fields_len = len(fields)
ob_len = len(ob)
if ob_len == fields_len:
# Optimize for this fast case
return tuple(ob)
elif required <= ob_len < fields_len:
defaults_needed = fields_len - ob_len
return tuple((*ob, *defaults[-defaults_needed:]))
else:
raise ValueError(error_msg.format(", ".join(fields)))
elif isinstance(ob, dict):
if any(key not in fields for key in ob):
raise ValueError("Unexpected key in {}".format(ob))
try:
return tuple(
(
ob.get(key, defaults[index - required])
if index >= required
else ob[key]
)
for index, key in enumerate(fields)
)
except KeyError:
raise ValueError(error_msg.format(", ".join(fields))) from None
else:
raise TypeError(error_msg.format(", ".join(fields)))
def _tuple_from_extent3d(size):
return _tuple_from_tuple_or_dict(
# required, 1, 1
size,
("width", "height", "depth_or_array_layers"),
(1, 1),
)
def _tuple_from_origin3d(destination):
fields = destination.get("origin", (0, 0, 0))
# Each field individually is 0 if not specified
return _tuple_from_tuple_or_dict(fields, "xyz", (0, 0, 0))
def _tuple_from_color(rgba):
return _tuple_from_tuple_or_dict(rgba, "rgba")
def _get_override_constant_entries(field):
constants = field.get("constants")
if not constants:
return ffi.NULL, []
c_constant_entries = []
for key, value in constants.items():
assert isinstance(key, (str, int))
assert isinstance(value, (int, float, bool))
# H: nextInChain: WGPUChainedStruct *, key: char *, value: float
c_constant_entry = new_struct(
"WGPUConstantEntry",
key=to_c_string(str(key)),
value=float(value),
# not used: nextInChain
)
c_constant_entries.append(c_constant_entry)
# We need to return and hold onto c_constant_entries in order to prevent the C
# strings from being GC'ed.
c_constants = ffi.new("WGPUConstantEntry[]", c_constant_entries)
return c_constants, c_constant_entries
def to_c_string(string: str):
return ffi.new("char []", string.encode())
def to_c_string_or_null(string: Optional[str]):
return ffi.NULL if string is None else ffi.new("char []", string.encode())
_empty_label = ffi.new("char []", b"")
def to_c_label(label):
"""Get the C representation of a label."""
if not label:
return _empty_label
else:
return to_c_string(label)
def feature_flag_to_feature_names(flag):
"""Convert a feature flags into a tuple of names."""
feature_names = {} # import this from mappings?
features = []
for i in range(32):
val = int(2**i)
if flag & val:
features.append(feature_names.get(val, val))
return tuple(sorted(features))
def check_struct(struct_name, d):
"""Check that all keys in the given dict exist in the corresponding struct."""
valid_keys = set(getattr(structs, struct_name))
invalid_keys = set(d.keys()).difference(valid_keys)
if invalid_keys:
raise ValueError(f"Invalid keys in {struct_name}: {invalid_keys}")
def _get_limits(id: int, device: bool = False, adapter: bool = False):
"""Gets the limits for a device or an adapter"""
assert device + adapter == 1 # exactly one is set
# H: chain: WGPUChainedStructOut, limits: WGPUNativeLimits
c_supported_limits_extras = new_struct_p(
"WGPUSupportedLimitsExtras *",
# not used: chain
# not used: limits
)
c_supported_limits_extras.chain.sType = lib.WGPUSType_SupportedLimitsExtras
# H: nextInChain: WGPUChainedStructOut *, limits: WGPULimits
c_supported_limits = new_struct_p(
"WGPUSupportedLimits *",
nextInChain=ffi.cast("WGPUChainedStructOut *", c_supported_limits_extras),
# not used: limits
)
if adapter:
# H: WGPUBool f(WGPUAdapter adapter, WGPUSupportedLimits * limits)
libf.wgpuAdapterGetLimits(id, c_supported_limits)
else:
# H: WGPUBool f(WGPUDevice device, WGPUSupportedLimits * limits)
libf.wgpuDeviceGetLimits(id, c_supported_limits)
key_value_pairs = [
(to_snake_case(name, "-"), getattr(c_limits, name))
for c_limits in (c_supported_limits.limits, c_supported_limits_extras.limits)
for name in dir(c_limits)
]
limits = dict(sorted(key_value_pairs))
return limits
def _get_features(id: int, device: bool = False, adapter: bool = False):
"""Gets the features for a device or an adapter"""
assert device + adapter == 1 # exactly one of them is set
if adapter:
# H: WGPUBool f(WGPUAdapter adapter, WGPUFeatureName feature)
has_feature = lambda feature: libf.wgpuAdapterHasFeature(id, feature)
else:
# H: WGPUBool f(WGPUDevice device, WGPUFeatureName feature)
has_feature = lambda feature: libf.wgpuDeviceHasFeature(id, feature)
features = set()
# Standard features
for f in sorted(enums.FeatureName):
if f in [
"clip-distances",
"dual-source-blending",
"texture-compression-bc-sliced-3d",
]:
continue # not supported by wgpu-native yet
if has_feature(enummap[f"FeatureName.{f}"]):
features.add(f)
# Native features
for name, feature_id in enum_str2int["NativeFeature"].items():
if has_feature(feature_id):
features.add(name)
return features
error_handler = ErrorHandler(logger)
libf = SafeLibCalls(lib, error_handler)
# %% The API
class GPU(classes.GPU):
def request_adapter_sync(
self,
*,
power_preference: enums.PowerPreference = None,
force_fallback_adapter: bool = False,
canvas=None,
):
"""Sync version of ``request_adapter_async()``.
This is the implementation based on wgpu-native.
"""
check_can_use_sync_variants()
awaitable = self._request_adapter(
power_preference=power_preference,
force_fallback_adapter=force_fallback_adapter,
canvas=canvas,
)
return awaitable.sync_wait()
async def request_adapter_async(
self,
*,
power_preference: enums.PowerPreference = None,
force_fallback_adapter: bool = False,
canvas=None,
):
"""Create a `GPUAdapter`, the object that represents an abstract wgpu
implementation, from which one can request a `GPUDevice`.
This is the implementation based on wgpu-native.
Arguments:
power_preference (PowerPreference): "high-performance" or "low-power".
force_fallback_adapter (bool): whether to use a (probably CPU-based)
fallback adapter.
canvas : The canvas that the adapter should be able to render to. This can typically
be left to None. If given, the object must implement ``WgpuCanvasInterface``.
"""
awaitable = self._request_adapter(
power_preference=power_preference,
force_fallback_adapter=force_fallback_adapter,
canvas=canvas,
) # no-cover
return await awaitable
def _request_adapter(
self, *, power_preference=None, force_fallback_adapter=False, canvas=None
):
# ----- Surface ID
# Get surface id that the adapter must be compatible with. If we
# don't pass a valid surface id, there is no guarantee we'll be
# able to create a surface texture for it (from this adapter).
surface_id = ffi.NULL
if canvas is not None:
surface_id = canvas.get_context()._surface_id # can still be NULL
# ----- Select backend
# Try to read the WGPU_BACKEND_TYPE environment variable to see
# if a backend should be forced.
force_backend = os.getenv("WGPU_BACKEND_TYPE", "").strip()
backend = enum_str2int["BackendType"]["Undefined"]
if force_backend:
try:
backend = enum_str2int["BackendType"][force_backend]
except KeyError:
logger.warning(
f"Invalid value for WGPU_BACKEND_TYPE: '{force_backend}'.\n"
f"Valid values are: {list(enum_str2int['BackendType'].keys())}"
)
else:
logger.warning(f"Forcing backend: {force_backend} ({backend})")
# ----- Request adapter
# H: nextInChain: WGPUChainedStruct *, compatibleSurface: WGPUSurface, powerPreference: WGPUPowerPreference, backendType: WGPUBackendType, forceFallbackAdapter: WGPUBool/int
struct = new_struct_p(
"WGPURequestAdapterOptions *",
compatibleSurface=surface_id,
powerPreference=power_preference or "high-performance",
forceFallbackAdapter=bool(force_fallback_adapter),
backendType=backend,
# not used: nextInChain
)
awaitable_result = {}
@ffi.callback("void(WGPURequestAdapterStatus, WGPUAdapter, char *, void *)")
def callback(status, result, message, userdata):
if status != 0:
msg = "-" if message == ffi.NULL else ffi.string(message).decode()
awaitable_result["error"] = f"Request adapter failed ({status}): {msg}"
else:
awaitable_result["result"] = result
def poll_func():
pass # actually does not need a poll func at the moment
def finalizer(adapter_id):
return self._create_adapter(adapter_id)
# H: void f(WGPUInstance instance, WGPURequestAdapterOptions const * options, WGPUInstanceRequestAdapterCallback callback, void * userdata)
libf.wgpuInstanceRequestAdapter(get_wgpu_instance(), struct, callback, ffi.NULL)
return WgpuAwaitable(
"request_adapter", awaitable_result, callback, poll_func, finalizer
)
def enumerate_adapters_sync(self):
"""Sync version of ``enumerate_adapters_async()``.
This is the implementation based on wgpu-native.
"""
check_can_use_sync_variants()
return self._enumerate_adapters()
async def enumerate_adapters_async(self):
"""Get a list of adapter objects available on the current system.
This is the implementation based on wgpu-native.
"""
return self._enumerate_adapters()
def _enumerate_adapters(self):
# The first call is to get the number of adapters, and the second call
# is to get the actual adapters. Note that the second arg (now NULL) can
# be a `WGPUInstanceEnumerateAdapterOptions` to filter by backend.
instance = get_wgpu_instance()
# H: size_t f(WGPUInstance instance, WGPUInstanceEnumerateAdapterOptions const * options, WGPUAdapter * adapters)
count = libf.wgpuInstanceEnumerateAdapters(instance, ffi.NULL, ffi.NULL)
adapters = ffi.new("WGPUAdapter[]", count)
# H: size_t f(WGPUInstance instance, WGPUInstanceEnumerateAdapterOptions const * options, WGPUAdapter * adapters)
libf.wgpuInstanceEnumerateAdapters(instance, ffi.NULL, adapters)
return [self._create_adapter(adapter) for adapter in adapters]
def _create_adapter(self, adapter_id):
# ----- Get adapter info
# H: nextInChain: WGPUChainedStructOut *, vendor: char *, architecture: char *, device: char *, description: char *, backendType: WGPUBackendType, adapterType: WGPUAdapterType, vendorID: int, deviceID: int
c_info = new_struct_p(
"WGPUAdapterInfo *",
# not used: nextInChain
# not used: vendor
# not used: architecture
# not used: device
# not used: description
# not used: backendType
# not used: adapterType
# not used: vendorID
# not used: deviceID
)
# H: void f(WGPUAdapter adapter, WGPUAdapterInfo * info)
libf.wgpuAdapterGetInfo(adapter_id, c_info)
def to_py_str(key):
char_p = getattr(c_info, key)
if char_p:
return ffi.string(char_p).decode(errors="ignore")
return ""
# Populate a dict according to the WebGPU spec: https://gpuweb.github.io/gpuweb/#gpuadapterinfo
# And add all other info we get from wgpu-native too.
# note: device is human readable. description is driver-description; usually more cryptic, or empty.
adapter_info = {
# Spec
"vendor": to_py_str("vendor"),
"architecture": to_py_str("architecture"),
"device": to_py_str("device"),
"description": to_py_str("description"),
# Extra
"vendor_id": int(c_info.vendorID),
"device_id": int(c_info.deviceID),
"adapter_type": enum_int2str["AdapterType"].get(
c_info.adapterType, "unknown"
),
"backend_type": enum_int2str["BackendType"].get(
c_info.backendType, "unknown"
),
}
# Allow Rust to release its string objects
# H: void f(WGPUAdapterInfo adapterInfo)
libf.wgpuAdapterInfoFreeMembers(c_info[0])
# ----- Get adapter limits and features
limits = _get_limits(adapter_id, adapter=True)
features = _get_features(adapter_id, adapter=True)
# ----- Done
return GPUAdapter(adapter_id, features, limits, adapter_info)
# Instantiate API entrypoint
gpu = GPU()
class GPUCanvasContext(classes.GPUCanvasContext):
# The way this works, is that the context must first be configured.
# Then a texture can be obtained, which can be written to, and then it
# can be presented. The lifetime of the texture is between
# get_current_texture() and present(). We keep track of the texture so
# we can give meaningful errors/warnings on invalid use, rather than
# the more cryptic Rust panics.
def __init__(self, canvas):
super().__init__(canvas)
# Obtain the surface id. The lifetime is of the surface is bound
# to the lifetime of this context object.
if self._present_info["method"] == "screen":
self._surface_id = get_surface_id_from_info(self._present_info)
else: # method == "image"
self._surface_id = ffi.NULL
def _get_capabilities_screen(self, adapter):
adapter_id = adapter._internal
surface_id = self._surface_id
assert surface_id
minimal_capabilities = {
"usages": flags.TextureUsage.RENDER_ATTACHMENT,
"formats": [
enums.TextureFormat.bgra8unorm_srgb,
enums.TextureFormat.bgra8unorm,
],
"alpha_modes": enums.CanvasAlphaMode.opaque,
"present_modes": ["fifo"],
}
# H: nextInChain: WGPUChainedStructOut *, usages: WGPUTextureUsageFlags/int, formatCount: int, formats: WGPUTextureFormat *, presentModeCount: int, presentModes: WGPUPresentMode *, alphaModeCount: int, alphaModes: WGPUCompositeAlphaMode *
c_capabilities = new_struct_p(
"WGPUSurfaceCapabilities *",
# not used: nextInChain
# not used: usages
# not used: formatCount
# not used: formats
# not used: presentModeCount
# not used: presentModes
# not used: alphaModeCount
# not used: alphaModes
)
# H: void f(WGPUSurface surface, WGPUAdapter adapter, WGPUSurfaceCapabilities * capabilities)
libf.wgpuSurfaceGetCapabilities(surface_id, adapter_id, c_capabilities)
# Convert to Python.
capabilities = {}
# When the surface is found not to be compatible, the fields below may
# be null pointers. This probably means that the surface won't work,
# and trying to use it will result in an error (or Rust panic). Since
# I'm not sure what the best time/place to error would be, we pretend
# that everything is fine here, and populate the fields with values
# that wgpu-core claims are guaranteed to exist on any (compatible)
# surface.
capabilities["usages"] = c_capabilities.usages
if c_capabilities.formats:
capabilities["formats"] = formats = []
for i in range(c_capabilities.formatCount):
int_val = c_capabilities.formats[i]
formats.append(enum_int2str["TextureFormat"][int_val])
else:
capabilities["formats"] = minimal_capabilities["formats"]
if c_capabilities.alphaModes:
capabilities["alpha_modes"] = alpha_modes = []
for i in range(c_capabilities.alphaModeCount):
int_val = c_capabilities.alphaModes[i]
str_val = enum_int2str["CompositeAlphaMode"][int_val]
alpha_modes.append(str_val.lower())
else:
capabilities["alpha_modes"] = minimal_capabilities["alpha_modes"]
if c_capabilities.presentModes:
capabilities["present_modes"] = present_modes = []
for i in range(c_capabilities.presentModeCount):
int_val = c_capabilities.presentModes[i]
str_val = enum_int2str["PresentMode"][int_val]
present_modes.append(str_val.lower())
else:
capabilities["present_modes"] = minimal_capabilities["present_modes"]
# H: void f(WGPUSurfaceCapabilities surfaceCapabilities)
libf.wgpuSurfaceCapabilitiesFreeMembers(c_capabilities[0])
return capabilities
def _configure_screen(
self,
*,
device,
format,
usage,
view_formats,
color_space,
tone_mapping,
alpha_mode,
):
capabilities = self._get_capabilities(device.adapter)
# Convert to C values
c_view_formats = ffi.NULL
if view_formats:
view_formats_list = [enummap["TextureFormat." + x] for x in view_formats]
c_view_formats = ffi.new("WGPUTextureFormat []", view_formats_list)
# Lookup alpha mode, needs explicit conversion because enum names mismatch
c_alpha_mode = getattr(lib, f"WGPUCompositeAlphaMode_{alpha_mode.capitalize()}")
# The color_space is not used for now
color_space # noqa - not used yet
check_struct("CanvasToneMapping", tone_mapping)
tone_mapping_mode = tone_mapping.get("mode", "standard")
tone_mapping_mode # noqa - not used yet
# Select the present mode to determine vsync behavior.
# * https://docs.rs/wgpu/latest/wgpu/enum.PresentMode.html
# * https://github.com/pygfx/wgpu-py/issues/256
#
# Fifo: Wait for vsync, with a queue of ± 3 frames.
# FifoRelaxed: Like fifo but less lag and more tearing? aka adaptive vsync.
# Mailbox: submit without queue, but present on vsync. Not always available.
# Immediate: no queue, no waiting, with risk of tearing, vsync off.
#
# In general Fifo gives the best result, but sometimes people want to
# benchmark something and get the highest FPS possible. Note
# that we've observed rate limiting regardless of setting this
# to Immediate, depending on OS or being on battery power.
if getattr(self._get_canvas(), "_vsync", True):
present_mode_pref = ["fifo", "mailbox"]
else:
present_mode_pref = ["immediate", "mailbox", "fifo"]
present_modes = [
p for p in present_mode_pref if p in capabilities["present_modes"]
]
present_mode = (present_modes or capabilities["present_modes"])[0]
c_present_mode = getattr(lib, f"WGPUPresentMode_{present_mode.capitalize()}")
# Prepare config object
# H: nextInChain: WGPUChainedStruct *, device: WGPUDevice, format: WGPUTextureFormat, usage: WGPUTextureUsageFlags/int, viewFormatCount: int, viewFormats: WGPUTextureFormat *, alphaMode: WGPUCompositeAlphaMode, width: int, height: int, presentMode: WGPUPresentMode
self._wgpu_config = new_struct_p(
"WGPUSurfaceConfiguration *",
device=device._internal,
format=format,
usage=usage,
viewFormatCount=len(view_formats),
viewFormats=c_view_formats,
alphaMode=c_alpha_mode,
width=0,
height=0,
presentMode=c_present_mode,
# not used: nextInChain
)
def _configure_screen_real(self, width, height):
# If a texture is still active, better release it first
self._drop_texture()
# Set the size
self._wgpu_config.width = width
self._wgpu_config.height = height
if width <= 0 or height <= 0:
raise RuntimeError(
"Cannot configure canvas that has no pixels ({width}x{height})."
)
# Configure, and store the config if we did not error out
if self._surface_id:
# H: void f(WGPUSurface surface, WGPUSurfaceConfiguration const * config)
libf.wgpuSurfaceConfigure(self._surface_id, self._wgpu_config)
def _unconfigure_screen(self):
if self._surface_id:
# H: void f(WGPUSurface surface)
libf.wgpuSurfaceUnconfigure(self._surface_id)
def _create_texture_screen(self):
surface_id = self._surface_id
# Reconfigure when the canvas has resized.
# On some systems (Windows+Qt) this is not necessary, because
# the texture status would be Outdated below, resulting in a
# reconfigure. But on others (e.g. glfwf) the texture size does
# not have to match the window size, apparently. The downside
# for doing this check on the former systems, is that errors
# get logged, which would not be there if we did not
# pre-emptively reconfigure. These log entries are harmless but
# annoying, and I currently don't know how to prevent them
# elegantly. See issue #352
old_size = (self._wgpu_config.width, self._wgpu_config.height)
new_size = tuple(self._get_canvas().get_physical_size())
if old_size != new_size:
self._configure_screen_real(*new_size)
# Try to obtain a texture.
# `If it fails, depending on status, we reconfigure and try again.
# H: texture: WGPUTexture, suboptimal: WGPUBool/int, status: WGPUSurfaceGetCurrentTextureStatus
surface_texture = new_struct_p(
"WGPUSurfaceTexture *",
# not used: texture
# not used: suboptimal
# not used: status
)
for attempt in [1, 2]:
# H: void f(WGPUSurface surface, WGPUSurfaceTexture * surfaceTexture)
libf.wgpuSurfaceGetCurrentTexture(surface_id, surface_texture)
status = surface_texture.status
texture_id = surface_texture.texture
if status == lib.WGPUSurfaceGetCurrentTextureStatus_Success:
break # success
if texture_id:
# H: void f(WGPUTexture texture)
libf.wgpuTextureRelease(texture_id)
if attempt == 1 and status in [
lib.WGPUSurfaceGetCurrentTextureStatus_Timeout,
lib.WGPUSurfaceGetCurrentTextureStatus_Outdated,
lib.WGPUSurfaceGetCurrentTextureStatus_Lost,
]:
# Configure and try again.
# On Window+Qt this happens e.g. when the window has resized
# (status==Outdated), but also when moving the window from one
# monitor to another with different scale-factor.
logger.info(f"Re-configuring canvas context ({status}).")
self._configure_screen_real(*new_size)
else:
# WGPUSurfaceGetCurrentTextureStatus_OutOfMemory
# WGPUSurfaceGetCurrentTextureStatus_DeviceLost
# Or if this is the second attempt.
raise RuntimeError(f"Cannot get surface texture ({status}).")
# I don't expect this to happen, but let's check just in case.
if not texture_id:
raise RuntimeError("Cannot get surface texture (no texture)")
# Things look good, but texture may still be suboptimal, whatever that means
if surface_texture.suboptimal:
logger.warning("The surface texture is suboptimal.")
# Wrap it in a Python texture object
# But we can also read them from the texture
# H: uint32_t f(WGPUTexture texture)
width = libf.wgpuTextureGetWidth(texture_id)
# H: uint32_t f(WGPUTexture texture)
height = libf.wgpuTextureGetHeight(texture_id)
# H: uint32_t f(WGPUTexture texture)
depth = libf.wgpuTextureGetDepthOrArrayLayers(texture_id)
# H: uint32_t f(WGPUTexture texture)
mip_level_count = libf.wgpuTextureGetMipLevelCount(texture_id)
# H: uint32_t f(WGPUTexture texture)
sample_count = libf.wgpuTextureGetSampleCount(texture_id)
# H: WGPUTextureDimension f(WGPUTexture texture)
c_dim = libf.wgpuTextureGetDimension(texture_id) # -> to string
dimension = enum_int2str["TextureDimension"][c_dim]
# H: WGPUTextureFormat f(WGPUTexture texture)
c_format = libf.wgpuTextureGetFormat(texture_id)
format = enum_int2str["TextureFormat"][c_format]
# H: WGPUTextureUsageFlags f(WGPUTexture texture)
usage = libf.wgpuTextureGetUsage(texture_id)
label = ""
# Cannot yet set label, because it's not implemented in wgpu-native
# label = "surface-texture"
# H: void f(WGPUTexture texture, char const * label)
# libf.wgpuTextureSetLabel(texture_id, to_c_label(label))
tex_info = {
"size": (width, height, depth),
"mip_level_count": mip_level_count,
"sample_count": sample_count,
"dimension": dimension,
"format": format,
"usage": usage,
}
device = self._config["device"]
return GPUTexture(label, texture_id, device, tex_info)
def _present_screen(self):
# H: void f(WGPUSurface surface)
libf.wgpuSurfacePresent(self._surface_id)
def _release(self):
self._drop_texture()
if self._surface_id is not None and libf is not None:
self._surface_id, surface_id = None, self._surface_id
if surface_id: # is not NULL
# H: void f(WGPUSurface surface)
libf.wgpuSurfaceRelease(surface_id)
class GPUObjectBase(classes.GPUObjectBase):
def _release(self):
if self._internal is not None and libf is not None:
self._internal, internal = None, self._internal
# H: void wgpuDeviceRelease(WGPUDevice device)
# H: void wgpuBufferRelease(WGPUBuffer buffer)
# H: void wgpuTextureRelease(WGPUTexture texture)
# H: void wgpuTextureViewRelease(WGPUTextureView textureView)
# H: void wgpuSamplerRelease(WGPUSampler sampler)
# H: void wgpuBindGroupLayoutRelease(WGPUBindGroupLayout bindGroupLayout)
# H: void wgpuBindGroupRelease(WGPUBindGroup bindGroup)
# H: void wgpuPipelineLayoutRelease(WGPUPipelineLayout pipelineLayout)
# H: void wgpuShaderModuleRelease(WGPUShaderModule shaderModule)
# H: void wgpuComputePipelineRelease(WGPUComputePipeline computePipeline)
# H: void wgpuRenderPipelineRelease(WGPURenderPipeline renderPipeline)
# H: void wgpuCommandBufferRelease(WGPUCommandBuffer commandBuffer)
# H: void wgpuCommandEncoderRelease(WGPUCommandEncoder commandEncoder)
# H: void wgpuComputePassEncoderRelease(WGPUComputePassEncoder computePassEncoder)
# H: void wgpuRenderPassEncoderRelease(WGPURenderPassEncoder renderPassEncoder)
# H: void wgpuRenderBundleEncoderRelease(WGPURenderBundleEncoder renderBundleEncoder)
# H: void wgpuQueueRelease(WGPUQueue queue)
# H: void wgpuRenderBundleRelease(WGPURenderBundle renderBundle)
# H: void wgpuQuerySetRelease(WGPUQuerySet querySet)
function = type(self)._release_function
function(internal)
class GPUAdapterInfo(classes.GPUAdapterInfo):
pass
class GPUAdapter(classes.GPUAdapter):
def request_device_sync(
self,
*,
label: str = "",
required_features: List[enums.FeatureName] = [],
required_limits: Dict[str, int] = {},
default_queue: structs.QueueDescriptor = {},
):
check_can_use_sync_variants()
if default_queue:
check_struct("QueueDescriptor", default_queue)
awaitable = self._request_device(
label, required_features, required_limits, default_queue, ""
)
return awaitable.sync_wait()
async def request_device_async(
self,
*,
label: str = "",
required_features: List[enums.FeatureName] = [],
required_limits: Dict[str, int] = {},
default_queue: structs.QueueDescriptor = {},
):
if default_queue:
check_struct("QueueDescriptor", default_queue)
awaitable = self._request_device(
label,
required_features=required_features,
required_limits=required_limits,
default_queue=default_queue,
trace_path="",
)
return await awaitable
def _request_device(
self,
label: str,
required_features: List[enums.FeatureName],
required_limits: Dict[str, int],
default_queue: structs.QueueDescriptor,
trace_path: str,
):
# ---- Handle features
assert isinstance(required_features, (tuple, list, set))
c_features = set()
for f in required_features:
if isinstance(f, str):
f = f.replace("_", "-")
f = to_snake_case(f, "-")
i = enummap.get(f"FeatureName.{f}", None)
if i is None:
i = enum_str2int["NativeFeature"].get(f, None)
if i is None:
raise KeyError(f"Unknown feature: '{f}'")
c_features.add(i)
else:
raise TypeError("Features must be given as str.")
c_features = sorted(c_features) # makes it a list
# ----- Set limits
# H: chain: WGPUChainedStruct, limits: WGPUNativeLimits
c_required_limits_extras = new_struct_p(
"WGPURequiredLimitsExtras *",
# not used: chain
# not used: limits
)
c_required_limits_extras.chain.sType = lib.WGPUSType_RequiredLimitsExtras
# H: nextInChain: WGPUChainedStruct *, limits: WGPULimits
c_required_limits = new_struct_p(
"WGPURequiredLimits *",
nextInChain=ffi.cast("WGPUChainedStruct*", c_required_limits_extras),
# not used: limits
)
c_limits = c_required_limits.limits
c_limits_extras = c_required_limits_extras.limits
def canonicalize_limit_name(name):
if name in self._limits:
return name
if "_" in name:
alt_name = name.replace("_", "-")
if alt_name in self._limits:
return alt_name
alt_name = to_snake_case(name, "-")
if alt_name in self._limits:
return alt_name
raise KeyError(f"Unknown limit name '{name}'")
if required_limits:
assert isinstance(required_limits, dict)
required_limits = {
canonicalize_limit_name(key): value
for key, value in required_limits.items()
}
else:
# If required_limits isn't set, set it to self._limits. This is the same as
# setting it to {}, but the loop below goes just a little bit faster.
required_limits = self._limits
for limit in (c_limits, c_limits_extras):
for key in dir(limit):
snake_key = to_snake_case(key, "-")
# Use the value in required_limits if it exists. Otherwise, the old value
try:
value = required_limits[snake_key]
except KeyError:
value = self._limits[snake_key]
setattr(limit, key, value)
# ---- Set queue descriptor
# Note that the default_queue arg is a descriptor (dict for QueueDescriptor), but is currently empty :)
check_struct("QueueDescriptor", {})
# H: nextInChain: WGPUChainedStruct *, label: char *
queue_struct = new_struct(
"WGPUQueueDescriptor",
label=to_c_label("default_queue"),
# not used: nextInChain
)
# ----- Compose device descriptor extras
c_trace_path = ffi.NULL
if trace_path: # no-cover
c_trace_path = to_c_string(trace_path)
# H: chain: WGPUChainedStruct, tracePath: char *
extras = new_struct_p(
"WGPUDeviceExtras *",
tracePath=c_trace_path,
# not used: chain
)
extras.chain.sType = lib.WGPUSType_DeviceExtras
# ----- Device lost
@ffi.callback("void(WGPUDeviceLostReason, char *, void *)")
def device_lost_callback(c_reason, c_message, userdata):
reason = enum_int2str["DeviceLostReason"].get(c_reason, "Unknown")
message = ffi.string(c_message).decode(errors="ignore")
msg = f"The WGPU device was lost ({reason}):\n{message}"
# This is afaik an error that cannot usually be attributed to a specific call,
# so we cannot raise it as an error. We log it instead.
# WebGPU provides (promise-based) API for user-code to handle the error.
# We might want to do something similar, once we have async figured out.
error_handler.log_error(msg)