-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgen_c.py
1350 lines (1117 loc) · 40.5 KB
/
gen_c.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
import json
import enum
import sys
import math
from pathlib import Path
from typing import Any, Optional
from dataclasses import dataclass
from types import SimpleNamespace
from itertools import chain, tee, filterfalse
def partition(predicate, iterable):
"""Partition entries into false entries and true entries.
If *predicate* is slow, consider wrapping it with functools.lru_cache().
"""
# partition(is_odd, range(10)) → 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = tee(iterable)
return filterfalse(predicate, t1), filter(predicate, t2)
@dataclass
class Constant:
name: str
value: str
doc: str
@dataclass
class Typedef:
name: str
doc: str
type: str
@dataclass
class EnumEntry:
name: str
doc: str
value: Optional[str]
@dataclass
class Enum:
name: str
doc: str
entries: list[EnumEntry]
extended: bool
@dataclass
class BitflagEntry:
name: str
doc: str
value: str
value_combination: list[str]
@dataclass
class Bitflag:
name: str
doc: str
entries: list[BitflagEntry]
extended: bool
class PointerType(enum.StrEnum):
MUTABLE = "mutable"
IMMUTABLE = "immutable"
@dataclass
class ParameterType:
name: str
doc: str
type: str
pointer: Optional[PointerType]
optional: bool
@dataclass
class Callback:
name: str
doc: str
style: str
args: list[ParameterType]
@dataclass
class Function:
name: str
doc: str
returns: ParameterType
args: list[ParameterType]
returns_async: list[ParameterType]
@dataclass
class Struct:
name: str
type: str
doc: str
free_members: bool
members: list[ParameterType]
@dataclass
class Object:
name: str
doc: str
methods: list[Function]
extended: bool
namespace: str
@dataclass
class Spec:
copyright: str
name: str
enum_prefix: str
constants: list[Constant]
# currently empty
typedefs: list[Typedef]
enums: list[Enum]
bitflags: list[Bitflag]
structs: list[Struct]
callbacks: list[Callback]
functions: list[Function]
objects: list[Object]
function_types: list[Function]
def load_spec(path: Path) -> Spec:
with open(path, "r") as f:
return json.load(f, object_hook=lambda d: SimpleNamespace(**d))
def gen_enum(entry: Enum) -> str:
output = f"""
@value
struct {entry.name.title().replace('_','')}:
\"\"\"
{entry.doc.strip()}
\"\"\"
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __ne__(self, rhs: Self) -> Bool:
return self.value != rhs.value
"""
for i, e in enumerate(entry.entries):
ename = e.name.lower()
if entry.name == "texture_view_dimension" or entry.name == "texture_dimension":
ename = ename[::-1]
output += f" alias {ename} = Self({e.value if hasattr(e, 'value') else i})\n"
output += f' """{e.doc.strip()}"""\n'
output += """\n fn format_to(self, inout f: Formatter):\n"""
for i, e in enumerate(entry.entries):
ename = e.name.lower()
if entry.name == "texture_view_dimension" or entry.name == "texture_dimension":
ename = ename[::-1]
output += f"""
{"" if i == 0 else "el"}if self == Self.{ename}:
f.write("{ename}")
"""
return output
def gen_bitflag(entry: Bitflag) -> str:
output = f"""
@value
struct {entry.name.title().replace('_','')}:
\"\"\"
{entry.doc.strip()}
\"\"\"
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __ne__(self, rhs: Self) -> Bool:
return self.value != rhs.value
fn __xor__(self, rhs: Self) -> Self:
return self.value ^ rhs.value
fn __and__(self, rhs: Self) -> Self:
return self.value & rhs.value
fn __or__(self, rhs: Self) -> Self:
return self.value | rhs.value
fn __invert__(self) -> Self:
return ~self.value
"""
for i, e in enumerate(entry.entries):
if hasattr(e, "value_combination"):
combination = " | ".join(f"Self.{val}" for val in e.value_combination)
output += f" alias {e.name.lower()} = {combination}\n"
else:
output += f" alias {e.name.lower()} = Self({int(math.pow(2, int(e.value) if hasattr(e, 'value') else i - 1 ))})\n"
output += f' """{e.doc.strip()}"""\n'
return output
def gen_constant(entry: Constant) -> str:
match entry.value:
case "uint32_max":
val = "UInt32.MAX"
case "uint64_max":
val = "UInt64.MAX"
case "usize_max":
val = "UInt.MAX"
case _:
val = entry.value
return f"""
alias {entry.name.upper()} = {val}
\"\"\"
{entry.doc.strip()}
\"\"\"
"""
def sanitize_name(name: str, object_pointer:bool=True,struct_pointer:bool=False) -> str:
if name.startswith("enum."):
return name.removeprefix("enum.").title().replace("_", "")
elif name.startswith("bitflag."):
return name.removeprefix("bitflag.").title().replace("_", "")
elif name.startswith("struct."):
if struct_pointer:
n = name.removeprefix("struct.").title().replace("_", "")
return f"UnsafePointer[WGPU{n}]"
else:
return "WGPU" + name.removeprefix("struct.").title().replace("_", "")
elif name.startswith("function_type."):
return name.removeprefix("function_type.").title().replace("_", "")
elif name.startswith("object."):
if object_pointer:
n = name.removeprefix("object.").title().replace("_", "")
return f"WGPU{n}"
else:
return name.removeprefix("object.").title().replace("_", "")
elif name == "string":
return "UnsafePointer[Int8]"
elif name == "uint32":
return "UInt32"
elif name == "uint16":
return "UInt16"
elif name == "int16":
return "Int16"
elif name == "uint64":
return "UInt64"
elif name == "int32":
return "Int32"
elif name == "int64":
return "Int64"
elif name == "bool":
return "Bool"
elif name == "float32":
return "Float32"
elif name == "float64":
return "Float64"
elif name == "usize":
return "UInt"
elif name == "c_void":
return "UnsafePointer[NoneType]"
else:
return name
def gen_parameter_type(entry: ParameterType,*, default_assign: bool = False, type_only: bool = False, object_pointer: bool = True, struct_pointer: bool = False, in_function: bool = False) -> str:
ty = sanitize_name(entry.type, object_pointer=object_pointer, struct_pointer=struct_pointer)
if hasattr(entry, "pointer"):
if "array<" in entry.type:
ty = sanitize_name(entry.type.removeprefix("array<").removesuffix(">"), object_pointer=object_pointer, struct_pointer=struct_pointer)
# ty = f"Span[{ty}]"
ty = f"UnsafePointer[{ty}]"
else:
ty = f"{ty}"
if type_only:
if in_function and entry.type.startswith("array<"):
return f"Int32, {ty}"
return ty
res = f"""{entry.name}: {ty}"""
if in_function and entry.type.startswith("array<"):
res = f"{entry.name[:-1]}_count: Int{' = Int()' if hasattr(entry, 'optional') else ''}, {res}"
if hasattr(entry, "optional") and default_assign:
res = f"{res} = {ty}()"
return res
def gen_function(entry: Function, contains_self: bool = False, type: Optional[str] = None,prefix: Optional[str]=None) -> str:
args = entry.args if hasattr(entry,"args") else []
args_ordered = partition(lambda x : hasattr(x, "optional"), args)
params_pre_opt = ", ".join(gen_parameter_type(e, default_assign=True, in_function=True) for e in args_ordered[0])
params_post_opt = ", ".join(gen_parameter_type(e, default_assign=True, in_function=True) for e in args_ordered[1])
params_no_default = ", ".join(gen_parameter_type(e, type_only=True, struct_pointer=True, in_function=True) for e in args)
if hasattr(entry, "returns_async"):
ret_async = entry.returns_async
if args:
params_no_default += ","
cb_params = ", ".join(gen_parameter_type(e, default_assign=True, type_only=True, struct_pointer=True, in_function=True) for e in ret_async)
cb_params += ", UnsafePointer[NoneType]"
cb_params_arg = ", ".join(gen_parameter_type(e, default_assign=True, object_pointer=True, type_only=True, struct_pointer=True, in_function=True) for e in ret_async)
cb_params_arg += ", UnsafePointer[NoneType]"
params_no_default += f"fn({cb_params}) -> None, UnsafePointer[NoneType]"
params = ", ".join(a for a in [params_pre_opt, f"callback: fn({cb_params_arg}) -> None, user_data: UnsafePointer[NoneType]", params_post_opt] if a)
else:
params = ", ".join(a for a in [params_pre_opt, params_post_opt] if a)
ret_async = None
if contains_self:
params = f"handle: WGPU{type}, {params}"
if type:
params_no_default = f"WGPU{type}, {params_no_default}"
try:
ret = gen_parameter_type(entry.returns, type_only=True, object_pointer=True)
ret_ptr = gen_parameter_type(entry.returns, type_only=True, object_pointer=True)
except:
ret = "None"
ret_ptr = "None"
call_args = ", ".join(f"UnsafePointer.address_of({e.name})" if e.type.startswith("struct") else (f"{e.name[:-1]}_count, {e.name}" if e.type.startswith("array<") else e.name) for e in args)
if contains_self:
call_args = f"handle, {call_args}"
if ret_async:
if args:
call_args += ","
call_args += "callback, user_data"
return f"""
var _wgpu{type or ""}{entry.name.title().replace("_","")} = _wgpu.get_function[fn({params_no_default}) -> {ret_ptr}]("wgpu{type or ""}{entry.name.title().replace("_","")}")
fn {prefix + '_' if prefix else ''}{entry.name}({params}) -> {ret}:
\"\"\"
{entry.doc.strip()}
\"\"\"
return _wgpu{type or ""}{entry.name.title().replace("_","")}({call_args})
"""
def gen_callback(entry: Callback):
args = entry.args if hasattr(entry,"args") else []
params_no_default = ", ".join(gen_parameter_type(e, type_only=True, in_function=True) for e in args)
call_args = ", ".join(e.name for e in args)
return f"\nalias {entry.name}_callback = fn({params_no_default}) -> None\n"
def gen_object(entry: Object) -> str:
name = entry.name.title().replace('_','')
output = f"""
struct _{name}Impl:
pass
alias WGPU{name} = UnsafePointer[_{name}Impl]
fn {entry.name}_release(handle: WGPU{name}):
_wgpu.get_function[fn(UnsafePointer[_{name}Impl]) -> None]("wgpu{name}Release")(handle)
"""
for method in entry.methods:
output += gen_function(method,type=name,contains_self=True,prefix=entry.name)
return output
def gen_struct(entry: Struct) -> str:
output = f"""
@value
struct WGPU{entry.name.title().replace('_','')}:
\"\"\"
{entry.doc.strip()}
\"\"\"
"""
if entry.type == "base_in":
output += " var next_in_chain: UnsafePointer[ChainedStruct]\n"
elif entry.type == "base_out":
output += " var next_in_chain: UnsafePointer[ChainedStructOut]\n"
elif entry.type == "extension_in":
output += " var chain: ChainedStruct\n"
elif entry.type == "extension_out":
output += " var chain: ChainedStructOut\n"
members = entry.members if hasattr(entry, "members") else []
for member in members:
if member.type.startswith("function_type."):
output += f" var {member.name}: UnsafePointer[NoneType]\n"
elif member.type.startswith("array<"):
output += f" var {member.name[:-1]}_count: Int\n"
output += f" var {gen_parameter_type(member, struct_pointer=False)}\n"
else:
output += f" var {gen_parameter_type(member, struct_pointer=hasattr(member, 'pointer'))}\n"
output += "\n fn __init__(inout self,\n"
if entry.type == "base_in":
output += " next_in_chain: UnsafePointer[ChainedStruct] = UnsafePointer[ChainedStruct](),\n"
elif entry.type == "base_out":
output += " next_in_chain: UnsafePointer[ChainedStructOut] = UnsafePointer[ChainedStructOut](),\n"
elif entry.type == "extension_in":
output += " chain: ChainedStruct = ChainedStruct(),\n"
elif entry.type == "extension_out":
output += " chain: ChainedStructOut = ChainedStructOut()\n"
for member in members:
if member.type.startswith("enum.") or member.type.startswith("bitflag."):
ty = gen_parameter_type(member,type_only=True)
output += f"\n {member.name}: {ty} = {ty}(0),\n"
elif member.type == "bool":
output += f"\n {member.name}: Bool = False,"
elif member.type.startswith("function_type."):
output += f"\n {member.name}: UnsafePointer[NoneType] = UnsafePointer[NoneType](),\n"
elif member.type.startswith("array<"):
ty = gen_parameter_type(member,type_only=True, struct_pointer=False)
output += f"\n {member.name[:-1]}_count: Int = Int(),\n"
output += f"\n {member.name}: {ty} = {ty}(),\n"
else:
ty = gen_parameter_type(member,type_only=True, struct_pointer=hasattr(member, "pointer"))
owned = "owned " if member.type.startswith("struct.") and not hasattr(member, 'pointer') else ""
output += f"\n {owned}{member.name}: {ty} = {ty}(),\n"
output += " ):\n"
if entry.type == "base_in":
output += " self.next_in_chain = next_in_chain\n"
elif entry.type == "base_out":
output += " self.next_in_chain = next_in_chain\n"
elif entry.type == "extension_in":
output += " self.chain = chain\n"
elif entry.type == "extension_out":
output += " self.chain = chain\n"
for member in members:
take = '^' if member.type.startswith('struct') and not hasattr(member, 'pointer') else ''
if member.type.startswith("array<"):
output += f" self.{member.name[:-1]}_count = {member.name[:-1]}_count\n"
output += f" self.{member.name} = {member.name}{take}\n"
return output
def gen_function_type(entry: Function) -> str:
cb_params_arg = ", ".join(gen_parameter_type(e, default_assign=True, object_pointer=True, type_only=True, struct_pointer=True) for e in entry.args)
cb_params_arg += ", UnsafePointer[NoneType]"
return f"alias {entry.name.title().replace('_', '')} = fn({cb_params_arg}) -> None\n"
if __name__ == "__main__":
spec_path = Path.cwd() / (sys.argv[1])
spec = load_spec(spec_path)
enums = "\n".join(gen_enum(e) for e in spec.enums)
enums += """
# WGPU SPECIFIC ENUMS
@value
struct NativeSType:
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __ne__(self, rhs: Self) -> Bool:
return self.value != rhs.value
# Start at 0003 since that's allocated range for wgpu-native
alias device_extras = Self(0x00030001)
alias required_limits_extras = Self(0x00030002)
alias pipeline_layout_extras = Self(0x00030003)
alias shader_module_glsl_descriptor = Self(0x00030004)
alias supported_limits_extras = Self(0x00030005)
alias instance_extras = Self(0x00030006)
alias bind_group_entry_extras = Self(0x00030007)
alias bind_group_layout_entry_extras = Self(0x00030008)
alias query_set_descriptor_extras = Self(0x00030009)
alias surface_configuration_extras = Self(0x0003000A)
@value
struct NativeFeature:
var value: Int
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __ne__(self, rhs: Self) -> Bool:
return self.value != rhs.value
alias push_constants = Self(0x00030001)
alias texture_adapter_specific_format_features = Self(0x00030002)
alias multi_draw_indirect = Self(0x00030003)
alias multi_draw_indirect_count = Self(0x00030004)
alias vertex_writable_storage = Self(0x00030005)
alias texture_binding_array = Self(0x00030006)
alias sampled_texture_and_storage_buffer_array_non_uniform_indexing = Self(
0x00030007
)
alias pipeline_statistics_query = Self(0x00030008)
alias storage_resource_binding_array = Self(0x00030009)
alias partially_bound_binding_array = Self(0x0003000A)
alias texture_format_16_bit_norm = Self(0x0003000B)
alias texture_compression_astc_hdr = Self(0x0003000C)
# TODO: requires wgpu.h api change
# alias timestamp_query_inside_passes = Self(0x0003000D)
alias mappable_primary_buffers = Self(0x0003000E)
alias buffer_binding_array = Self(0x0003000F)
alias uniform_buffer_and_storage_texture_array_non_uniform_indexing = Self(
0x00030010
)
# TODO: requires wgpu.h api change
# alias address_mode_clamp_to_zero = Self(0x00030011)
# alias address_mode_clamp_to_border = Self(0x00030012)
# alias polygon_mode_line = Self(0x00030013)
# alias polygon_mode_point = Self(0x00030014)
# alias conservative_rasterization = Self(0x00030015)
# alias clear_texture = Self(0x00030016)
# alias spirv_shader_passthrough = Self(0x00030017)
# alias multiview = Self(0x00030018)
alias vertex_attribute_64_bit = Self(0x00030019)
alias texture_format_nv_12 = Self(0x0003001A)
alias ray_tracing_acceleration_structure = Self(0x0003001B)
alias ray_query = Self(0x0003001C)
alias shader_f64 = Self(0x0003001D)
alias shader_i16 = Self(0x0003001E)
alias shader_primitive_index = Self(0x0003001F)
alias shader_early_depth_test = Self(0x00030020)
@value
struct LogLevel:
var value: Int
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __ne__(self, rhs: Self) -> Bool:
return self.value != rhs.value
alias off = Self(0x00000000)
alias error = Self(0x00000001)
alias warn = Self(0x00000002)
alias info = Self(0x00000003)
alias debug = Self(0x00000004)
alias trace = Self(0x00000005)
@value
struct NativeTextureFormat:
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __ne__(self, rhs: Self) -> Bool:
return self.value != rhs.value
# From Features::TEXTURE_FORMAT_16BIT_NORM
alias r_16_unorm = Self(0x00030001)
alias r_16_snorm = Self(0x00030002)
alias rg_16_unorm = Self(0x00030003)
alias rg_16_snorm = Self(0x00030004)
alias rgba_16_unorm = Self(0x00030005)
alias rgba_16_snorm = Self(0x00030006)
# From Features::TEXTURE_FORMAT_NV12
alias nv_12 = Self(0x00030007)
"""
with open("wgpu/enums.mojo", "w+") as f:
f.write(enums)
structs = "\n".join(gen_struct(e) for e in spec.structs)
bitflags = "\n".join(gen_bitflag(e) for e in spec.bitflags)
bitflags += """
# WGPU SPECIFIC BITFLAGS
@value
struct InstanceBackend:
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __ne__(self, rhs: Self) -> Bool:
return self.value != rhs.value
fn __xor__(self, rhs: Self) -> Self:
return self.value ^ rhs.value
fn __and__(self, rhs: Self) -> Self:
return self.value & rhs.value
fn __or__(self, rhs: Self) -> Self:
return self.value | rhs.value
fn __invert__(self) -> Self:
return ~self.value
alias all = Self(0x00000000)
alias vulkan = Self(1 << 0)
alias gl = Self(1 << 1)
alias metal = Self(1 << 2)
alias dx12 = Self(1 << 3)
alias dx11 = Self(1 << 4)
alias browser_webgpu = Self(1 << 5)
alias primary = Self.vulkan | Self.metal | Self.dx12 | Self.browser_webgpu
alias secondary = Self.gl | Self.dx11
@value
struct InstanceFlag:
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __ne__(self, rhs: Self) -> Bool:
return self.value != rhs.value
fn __xor__(self, rhs: Self) -> Self:
return self.value ^ rhs.value
fn __and__(self, rhs: Self) -> Self:
return self.value & rhs.value
fn __or__(self, rhs: Self) -> Self:
return self.value | rhs.value
fn __invert__(self) -> Self:
return ~self.value
alias default = Self(0x00000000)
alias debug = Self(1 << 0)
alias validation = Self(1 << 1)
alias discard_hal_labels = Self(1 << 2)
@value
struct Dx12Compiler:
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __ne__(self, rhs: Self) -> Bool:
return self.value != rhs.value
fn __xor__(self, rhs: Self) -> Self:
return self.value ^ rhs.value
fn __and__(self, rhs: Self) -> Self:
return self.value & rhs.value
fn __or__(self, rhs: Self) -> Self:
return self.value | rhs.value
fn __invert__(self) -> Self:
return ~self.value
alias undefined = Self(0x00000000)
alias fxc = Self(0x00000001)
alias dxc = Self(0x00000002)
@value
struct Gles3MinorVersion:
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __ne__(self, rhs: Self) -> Bool:
return self.value != rhs.value
fn __xor__(self, rhs: Self) -> Self:
return self.value ^ rhs.value
fn __and__(self, rhs: Self) -> Self:
return self.value & rhs.value
fn __or__(self, rhs: Self) -> Self:
return self.value | rhs.value
fn __invert__(self) -> Self:
return ~self.value
alias automatic = Self(0x00000000)
alias version0 = Self(0x00000001)
alias version1 = Self(0x00000002)
alias version2 = Self(0x00000003)
@value
struct PipelineStatisticName:
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __ne__(self, rhs: Self) -> Bool:
return self.value != rhs.value
fn __xor__(self, rhs: Self) -> Self:
return self.value ^ rhs.value
fn __and__(self, rhs: Self) -> Self:
return self.value & rhs.value
fn __or__(self, rhs: Self) -> Self:
return self.value | rhs.value
fn __invert__(self) -> Self:
return ~self.value
alias vertex_shader_invocations = Self(0x00000000)
alias clipper_invocations = Self(0x00000001)
alias clipper_primitives_out = Self(0x00000002)
alias fragment_shader_invocations = Self(0x00000003)
alias compute_shader_invocations = Self(0x00000004)
@value
struct NativeQueryType:
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __ne__(self, rhs: Self) -> Bool:
return self.value != rhs.value
fn __xor__(self, rhs: Self) -> Self:
return self.value ^ rhs.value
fn __and__(self, rhs: Self) -> Self:
return self.value & rhs.value
fn __or__(self, rhs: Self) -> Self:
return self.value | rhs.value
fn __invert__(self) -> Self:
return ~self.value
alias pipeline_statistics = Self(0x00030000)
"""
with open("wgpu/bitflags.mojo", "w+") as f:
f.write(bitflags)
constants = "\n".join(gen_constant(e) for e in spec.constants)
with open("wgpu/constants.mojo", "w+") as f:
f.write(constants)
functions = "\n".join(gen_function(e) for e in spec.functions)
objects = "\n".join(gen_object(e) for e in spec.objects)
function_types = "\n".join(gen_function_type(e) for e in spec.function_types)
output = """
from sys import ffi
from utils import Span
from .enums import *
from .bitflags import *
from .constants import *
var _wgpu = ffi.DLHandle("libwgpu_native.dylib", ffi.RTLD.LAZY)
@value
struct ChainedStruct:
var next: UnsafePointer[Self]
var s_type: SType
fn __init__(inout self, next: UnsafePointer[Self] = UnsafePointer[Self](), s_type: SType = SType.invalid):
self.next = next
self.s_type = s_type
@value
struct ChainedStructOut:
var next: UnsafePointer[Self]
var s_type: SType
fn __init__(inout self, next: UnsafePointer[Self] = UnsafePointer[Self](), s_type: SType = SType.invalid):
self.next = next
self.s_type = s_type
"""
output += "\n".join([objects, structs, functions, function_types])
output += """
# WGPU SPECIFIC DEFS
@value
struct WGPUInstanceExtras:
var chain: ChainedStruct
var backends: InstanceBackend
var flags: InstanceFlag
var dx12_shader_compiler: Dx12Compiler
var gl_es_3_minor_version: Gles3MinorVersion
var dxil_path: UnsafePointer[Int8]
var dxc_path: UnsafePointer[Int8]
fn __init__(
inout self,
chain: ChainedStruct = ChainedStruct(),
backends: InstanceBackend = InstanceBackend.all,
flags: InstanceFlag = InstanceFlag.default,
dx12_shader_compiler: Dx12Compiler = Dx12Compiler.undefined,
gl_es_3_minor_version: Gles3MinorVersion = Gles3MinorVersion.automatic,
dxil_path: UnsafePointer[Int8] = UnsafePointer[Int8](),
dxc_path: UnsafePointer[Int8] = UnsafePointer[Int8](),
):
self.chain = chain
self.backends = backends
self.flags = flags
self.dx12_shader_compiler = dx12_shader_compiler
self.gl_es_3_minor_version = gl_es_3_minor_version
self.dxil_path = dxil_path
self.dxc_path = dxc_path
@value
struct WGPUDeviceExtras:
var chain: ChainedStruct
var trace_path: UnsafePointer[Int8]
fn __init__(
inout self,
chain: ChainedStruct = ChainedStruct(),
trace_path: UnsafePointer[Int8] = UnsafePointer[Int8](),
):
self.chain = chain
self.trace_path = trace_path
@value
struct WGPUNativeLimits:
var max_push_constant_size: UInt32
var max_non_sampler_bindings: UInt32
fn __init__(
inout self,
max_push_constant_size: UInt32 = 0,
max_non_sampler_bindings: UInt32 = 0,
):
self.max_push_constant_size = max_push_constant_size
self.max_non_sampler_bindings = max_non_sampler_bindings
@value
struct WGPURequiredLimitsExtras:
var chain: ChainedStruct
var limits: WGPUNativeLimits
fn __init__(
inout self,
chain: ChainedStruct = ChainedStruct(),
limits: WGPUNativeLimits = WGPUNativeLimits(),
):
self.chain = chain
self.limits = limits
@value
struct WGPUSupportedLimitsExtras:
var chain: ChainedStruct
var limits: WGPUNativeLimits
fn __init__(
inout self,
chain: ChainedStruct = ChainedStruct(),
limits: WGPUNativeLimits = WGPUNativeLimits(),
):
self.chain = chain
self.limits = limits
@value
struct WGPUPushConstantRange:
var stages: ShaderStage
var start: UInt32
var end: UInt32
fn __init__(
inout self,
stages: ShaderStage = ShaderStage.none,
start: UInt32 = 0,
end: UInt32 = 0,
):
self.stages = stages
self.start = start
self.end = end
@value
struct WGPUPipelineLayoutExtras:
var chain: ChainedStruct
var push_constant_range_count: Int
var push_constant_ranges: UnsafePointer[WGPUPushConstantRange]
fn __init__(
inout self,
chain: ChainedStruct = ChainedStruct(),
push_constant_range_count: Int = 0,
push_constant_ranges: UnsafePointer[
WGPUPushConstantRange
] = UnsafePointer[WGPUPushConstantRange](),
):
self.chain = chain
self.push_constant_range_count = push_constant_range_count
self.push_constant_ranges = push_constant_ranges
alias WGPUSubmissionIndex = UInt64
@value
struct WGPUWrappedSubmissionIndex:
var queue: WGPUQueue
var submission_index: WGPUSubmissionIndex
fn __init__(
inout self,
queue: WGPUQueue = WGPUQueue(),
submission_index: WGPUSubmissionIndex = WGPUSubmissionIndex(),
):
self.queue = queue
self.submission_index = submission_index
@value
struct WGPUShaderDefine:
var name: UnsafePointer[Int8]
var value: UnsafePointer[Int8]
fn __init__(
inout self,
name: UnsafePointer[Int8] = UnsafePointer[Int8](),
value: UnsafePointer[Int8] = UnsafePointer[Int8](),
):
self.name = name
self.value = value
@value
struct WGPUShaderModuleGLSLDescriptor:
var chain: ChainedStruct
var stage: ShaderStage
var code: UnsafePointer[Int8]
var define_count: UInt32
var defines: UnsafePointer[WGPUShaderDefine]
fn __init__(
inout self,
chain: ChainedStruct = ChainedStruct(),
stage: ShaderStage = ShaderStage.none,
code: UnsafePointer[Int8] = UnsafePointer[Int8](),
define_count: UInt32 = 0,
defines: UnsafePointer[WGPUShaderDefine] = UnsafePointer[
WGPUShaderDefine
](),
):
self.chain = chain
self.stage = stage
self.code = code
self.define_count = define_count
self.defines = defines
@value
struct WGPURegistryReport:
var num_allocated: Int
var num_kept_from_user: Int
var num_released_from_user: Int
var num_error: Int
var element_size: Int
fn __init__(
inout self,
num_allocated: Int = 0,
num_kept_from_user: Int = 0,
num_released_from_user: Int = 0,
num_error: Int = 0,
element_size: Int = 0,
):
self.num_allocated = num_allocated
self.num_kept_from_user = num_kept_from_user
self.num_released_from_user = num_released_from_user
self.num_error = num_error
self.element_size = element_size
@value
struct WGPUHubReport:
var adapters: WGPURegistryReport
var devices: WGPURegistryReport
var queues: WGPURegistryReport
var pipeline_layouts: WGPURegistryReport
var shader_modules: WGPURegistryReport
var bind_group_layouts: WGPURegistryReport
var bind_groups: WGPURegistryReport
var command_buffers: WGPURegistryReport
var render_bundles: WGPURegistryReport
var render_pipelines: WGPURegistryReport
var compute_pipelines: WGPURegistryReport
var query_sets: WGPURegistryReport
var buffers: WGPURegistryReport
var textures: WGPURegistryReport
var texture_views: WGPURegistryReport
var samplers: WGPURegistryReport
fn __init__(
inout self,
adapters: WGPURegistryReport = WGPURegistryReport(),
devices: WGPURegistryReport = WGPURegistryReport(),
queues: WGPURegistryReport = WGPURegistryReport(),
pipeline_layouts: WGPURegistryReport = WGPURegistryReport(),
shader_modules: WGPURegistryReport = WGPURegistryReport(),
bind_group_layouts: WGPURegistryReport = WGPURegistryReport(),
bind_groups: WGPURegistryReport = WGPURegistryReport(),
command_buffers: WGPURegistryReport = WGPURegistryReport(),