-
-
Notifications
You must be signed in to change notification settings - Fork 576
/
binding_generator.py
3053 lines (2486 loc) · 116 KB
/
binding_generator.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
#!/usr/bin/env python
import json
import re
import shutil
from pathlib import Path
def generate_mod_version(argcount, const=False, returns=False):
s = """
#define MODBIND$VER($RETTYPE m_name$ARG) \\
virtual $RETVAL _##m_name($FUNCARGS) $CONST override; \\
"""
sproto = str(argcount)
if returns:
sproto += "R"
s = s.replace("$RETTYPE", "m_ret, ")
s = s.replace("$RETVAL", "m_ret")
else:
s = s.replace("$RETTYPE", "")
s = s.replace("$RETVAL", "void")
if const:
sproto += "C"
s = s.replace("$CONST", "const")
else:
s = s.replace("$CONST", "")
s = s.replace("$VER", sproto)
argtext = ""
funcargs = ""
for i in range(argcount):
if i > 0:
funcargs += ", "
argtext += ", m_type" + str(i + 1)
funcargs += "m_type" + str(i + 1) + " arg" + str(i + 1)
if argcount:
s = s.replace("$ARG", argtext)
s = s.replace("$FUNCARGS", funcargs)
else:
s = s.replace("$ARG", "")
s = s.replace("$FUNCARGS", funcargs)
return s
def generate_wrappers(target):
max_versions = 12
txt = """
#ifndef GDEXTENSION_WRAPPERS_GEN_H
#define GDEXTENSION_WRAPPERS_GEN_H
"""
for i in range(max_versions + 1):
txt += "\n/* Module Wrapper " + str(i) + " Arguments */\n"
txt += generate_mod_version(i, False, False)
txt += generate_mod_version(i, False, True)
txt += generate_mod_version(i, True, False)
txt += generate_mod_version(i, True, True)
txt += "\n#endif\n"
with open(target, "w", encoding="utf-8") as f:
f.write(txt)
def generate_virtual_version(argcount, const=False, returns=False):
s = """#define GDVIRTUAL$VER($RET m_name $ARG)\\
::godot::StringName _gdvirtual_##m_name##_sn = #m_name;\\
template <bool required>\\
_FORCE_INLINE_ bool _gdvirtual_##m_name##_call($CALLARGS) $CONST {\\
if (::godot::internal::gdextension_interface_object_has_script_method(_owner, &_gdvirtual_##m_name##_sn)) { \\
GDExtensionCallError ce;\\
$CALLSIARGS\\
::godot::Variant ret;\\
::godot::internal::gdextension_interface_object_call_script_method(_owner, &_gdvirtual_##m_name##_sn, $CALLSIARGPASS, &ret, &ce);\\
if (ce.error == GDEXTENSION_CALL_OK) {\\
$CALLSIRET\\
return true;\\
}\\
}\\
if (required) {\\
ERR_PRINT_ONCE("Required virtual method " + get_class() + "::" + #m_name + " must be overridden before calling.");\\
$RVOID\\
}\\
return false;\\
}\\
_FORCE_INLINE_ bool _gdvirtual_##m_name##_overridden() const {\\
return ::godot::internal::gdextension_interface_object_has_script_method(_owner, &_gdvirtual_##m_name##_sn); \\
}\\
_FORCE_INLINE_ static ::godot::MethodInfo _gdvirtual_##m_name##_get_method_info() {\\
::godot::MethodInfo method_info;\\
method_info.name = #m_name;\\
method_info.flags = $METHOD_FLAGS;\\
$FILL_METHOD_INFO\\
return method_info;\\
}
"""
sproto = str(argcount)
method_info = ""
if returns:
sproto += "R"
s = s.replace("$RET", "m_ret,")
s = s.replace("$RVOID", "(void)r_ret;") # If required, may lead to uninitialized errors
method_info += "method_info.return_val = ::godot::GetTypeInfo<m_ret>::get_class_info();\\\n"
method_info += "\t\tmethod_info.return_val_metadata = ::godot::GetTypeInfo<m_ret>::METADATA;"
else:
s = s.replace("$RET ", "")
s = s.replace("\t\t\t$RVOID\\\n", "")
if const:
sproto += "C"
s = s.replace("$CONST", "const")
s = s.replace("$METHOD_FLAGS", "::godot::METHOD_FLAG_VIRTUAL | ::godot::METHOD_FLAG_CONST")
else:
s = s.replace("$CONST ", "")
s = s.replace("$METHOD_FLAGS", "::godot::METHOD_FLAG_VIRTUAL")
s = s.replace("$VER", sproto)
argtext = ""
callargtext = ""
callsiargs = ""
callsiargptrs = ""
if argcount > 0:
argtext += ", "
callsiargs = f"::godot::Variant vargs[{argcount}] = {{ "
callsiargptrs = f"\t\t\tconst ::godot::Variant *vargptrs[{argcount}] = {{ "
for i in range(argcount):
if i > 0:
argtext += ", "
callargtext += ", "
callsiargs += ", "
callsiargptrs += ", "
argtext += f"m_type{i + 1}"
callargtext += f"m_type{i + 1} arg{i + 1}"
callsiargs += f"::godot::Variant(arg{i + 1})"
callsiargptrs += f"&vargs[{i}]"
if method_info:
method_info += "\\\n\t\t"
method_info += f"method_info.arguments.push_back(::godot::GetTypeInfo<m_type{i + 1}>::get_class_info());\\\n"
method_info += f"\t\tmethod_info.arguments_metadata.push_back(::godot::GetTypeInfo<m_type{i + 1}>::METADATA);"
if argcount:
callsiargs += " };\\\n"
callsiargptrs += " };"
s = s.replace("$CALLSIARGS", callsiargs + callsiargptrs)
s = s.replace("$CALLSIARGPASS", f"(const GDExtensionConstVariantPtr *)vargptrs, {argcount}")
else:
s = s.replace("\t\t\t$CALLSIARGS\\\n", "")
s = s.replace("$CALLSIARGPASS", "nullptr, 0")
if returns:
if argcount > 0:
callargtext += ", "
callargtext += "m_ret &r_ret"
s = s.replace("$CALLSIRET", "r_ret = ::godot::VariantCaster<m_ret>::cast(ret);")
else:
s = s.replace("\t\t\t\t$CALLSIRET\\\n", "")
s = s.replace(" $ARG", argtext)
s = s.replace("$CALLARGS", callargtext)
if method_info:
s = s.replace("$FILL_METHOD_INFO", method_info)
else:
s = s.replace("\t\t$FILL_METHOD_INFO\\\n", method_info)
return s
def generate_virtuals(target):
max_versions = 12
txt = """/* THIS FILE IS GENERATED DO NOT EDIT */
#ifndef GDEXTENSION_GDVIRTUAL_GEN_H
#define GDEXTENSION_GDVIRTUAL_GEN_H
"""
for i in range(max_versions + 1):
txt += f"/* {i} Arguments */\n\n"
txt += generate_virtual_version(i, False, False)
txt += generate_virtual_version(i, False, True)
txt += generate_virtual_version(i, True, False)
txt += generate_virtual_version(i, True, True)
txt += "#endif // GDEXTENSION_GDVIRTUAL_GEN_H\n"
with open(target, "w", encoding="utf-8") as f:
f.write(txt)
def get_file_list(api_filepath, output_dir, headers=False, sources=False, profile_filepath=""):
api = {}
files = []
with open(api_filepath, encoding="utf-8") as api_file:
api = json.load(api_file)
build_profile = parse_build_profile(profile_filepath, api)
core_gen_folder = Path(output_dir) / "gen" / "include" / "godot_cpp" / "core"
include_gen_folder = Path(output_dir) / "gen" / "include" / "godot_cpp"
source_gen_folder = Path(output_dir) / "gen" / "src"
files.append(str((core_gen_folder / "ext_wrappers.gen.inc").as_posix()))
files.append(str((core_gen_folder / "gdvirtual.gen.inc").as_posix()))
for builtin_class in api["builtin_classes"]:
if is_pod_type(builtin_class["name"]):
continue
if is_included_type(builtin_class["name"]):
continue
header_filename = include_gen_folder / "variant" / (camel_to_snake(builtin_class["name"]) + ".hpp")
source_filename = source_gen_folder / "variant" / (camel_to_snake(builtin_class["name"]) + ".cpp")
if headers:
files.append(str(header_filename.as_posix()))
if sources:
files.append(str(source_filename.as_posix()))
for engine_class in api["classes"]:
# Generate code for the ClassDB singleton under a different name.
if engine_class["name"] == "ClassDB":
engine_class["name"] = "ClassDBSingleton"
engine_class["alias_for"] = "ClassDB"
header_filename = include_gen_folder / "classes" / (camel_to_snake(engine_class["name"]) + ".hpp")
source_filename = source_gen_folder / "classes" / (camel_to_snake(engine_class["name"]) + ".cpp")
if headers:
files.append(str(header_filename.as_posix()))
if sources and is_class_included(engine_class["name"], build_profile):
files.append(str(source_filename.as_posix()))
for native_struct in api["native_structures"]:
struct_name = native_struct["name"]
if struct_name == "ObjectID":
continue
snake_struct_name = camel_to_snake(struct_name)
header_filename = include_gen_folder / "classes" / (snake_struct_name + ".hpp")
if headers:
files.append(str(header_filename.as_posix()))
if headers:
for path in [
include_gen_folder / "variant" / "builtin_types.hpp",
include_gen_folder / "variant" / "builtin_binds.hpp",
include_gen_folder / "variant" / "utility_functions.hpp",
include_gen_folder / "variant" / "variant_size.hpp",
include_gen_folder / "variant" / "builtin_vararg_methods.hpp",
include_gen_folder / "classes" / "global_constants.hpp",
include_gen_folder / "classes" / "global_constants_binds.hpp",
include_gen_folder / "core" / "version.hpp",
]:
files.append(str(path.as_posix()))
if sources:
utility_functions_source_path = source_gen_folder / "variant" / "utility_functions.cpp"
files.append(str(utility_functions_source_path.as_posix()))
return files
def print_file_list(api_filepath, output_dir, headers=False, sources=False, profile_filepath=""):
print(*get_file_list(api_filepath, output_dir, headers, sources, profile_filepath), sep=";", end=None)
def parse_build_profile(profile_filepath, api):
if profile_filepath == "":
return {}
print("Using feature build profile: " + profile_filepath)
with open(profile_filepath, encoding="utf-8") as profile_file:
profile = json.load(profile_file)
api_dict = {}
parents = {}
children = {}
for engine_class in api["classes"]:
api_dict[engine_class["name"]] = engine_class
parent = engine_class.get("inherits", "")
child = engine_class["name"]
parents[child] = parent
if parent == "":
continue
children[parent] = children.get(parent, [])
children[parent].append(child)
# Parse methods dependencies
deps = {}
reverse_deps = {}
for name, engine_class in api_dict.items():
ref_cls = set()
for method in engine_class.get("methods", []):
rtype = method.get("return_value", {}).get("type", "")
args = [a["type"] for a in method.get("arguments", [])]
if rtype in api_dict:
ref_cls.add(rtype)
elif is_enum(rtype) and get_enum_class(rtype) in api_dict:
ref_cls.add(get_enum_class(rtype))
for arg in args:
if arg in api_dict:
ref_cls.add(arg)
elif is_enum(arg) and get_enum_class(arg) in api_dict:
ref_cls.add(get_enum_class(arg))
deps[engine_class["name"]] = set(filter(lambda x: x != name, ref_cls))
for acls in ref_cls:
if acls == name:
continue
reverse_deps[acls] = reverse_deps.get(acls, set())
reverse_deps[acls].add(name)
included = []
front = list(profile.get("enabled_classes", []))
if front:
# These must always be included
front.append("WorkerThreadPool")
front.append("ClassDB")
front.append("ClassDBSingleton")
while front:
cls = front.pop()
if cls in included:
continue
included.append(cls)
parent = parents.get(cls, "")
if parent:
front.append(parent)
for rcls in deps.get(cls, set()):
if rcls in included or rcls in front:
continue
front.append(rcls)
excluded = []
front = list(profile.get("disabled_classes", []))
while front:
cls = front.pop()
if cls in excluded:
continue
excluded.append(cls)
front += children.get(cls, [])
for rcls in reverse_deps.get(cls, set()):
if rcls in excluded or rcls in front:
continue
front.append(rcls)
if included and excluded:
print(
"WARNING: Cannot specify both 'enabled_classes' and 'disabled_classes' in build profile. 'disabled_classes' will be ignored."
)
return {
"enabled_classes": included,
"disabled_classes": excluded,
}
def scons_emit_files(target, source, env):
profile_filepath = env.get("build_profile", "")
if profile_filepath and not Path(profile_filepath).is_absolute():
profile_filepath = str((Path(env.Dir("#").abspath) / profile_filepath).as_posix())
files = [env.File(f) for f in get_file_list(str(source[0]), target[0].abspath, True, True, profile_filepath)]
env.Clean(target, files)
env["godot_cpp_gen_dir"] = target[0].abspath
return files, source
def scons_generate_bindings(target, source, env):
generate_bindings(
str(source[0]),
env["generate_template_get_node"],
"32" if "32" in env["arch"] else "64",
env["precision"],
env["godot_cpp_gen_dir"],
)
return None
def generate_bindings(api_filepath, use_template_get_node, bits="64", precision="single", output_dir="."):
api = None
target_dir = Path(output_dir) / "gen"
with open(api_filepath, encoding="utf-8") as api_file:
api = json.load(api_file)
shutil.rmtree(target_dir, ignore_errors=True)
target_dir.mkdir(parents=True)
real_t = "double" if precision == "double" else "float"
print("Built-in type config: " + real_t + "_" + bits)
generate_global_constants(api, target_dir)
generate_version_header(api, target_dir)
generate_global_constant_binds(api, target_dir)
generate_builtin_bindings(api, target_dir, real_t + "_" + bits)
generate_engine_classes_bindings(api, target_dir, use_template_get_node)
generate_utility_functions(api, target_dir)
CLASS_ALIASES = {
"ClassDB": "ClassDBSingleton",
}
builtin_classes = []
# Key is class name, value is boolean where True means the class is refcounted.
engine_classes = {}
# Type names of native structures
native_structures = []
singletons = []
def generate_builtin_bindings(api, output_dir, build_config):
global builtin_classes
core_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "core"
include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "variant"
source_gen_folder = Path(output_dir) / "src" / "variant"
core_gen_folder.mkdir(parents=True, exist_ok=True)
include_gen_folder.mkdir(parents=True, exist_ok=True)
source_gen_folder.mkdir(parents=True, exist_ok=True)
generate_wrappers(core_gen_folder / "ext_wrappers.gen.inc")
generate_virtuals(core_gen_folder / "gdvirtual.gen.inc")
# Store types beforehand.
for builtin_api in api["builtin_classes"]:
if is_pod_type(builtin_api["name"]):
continue
builtin_classes.append(builtin_api["name"])
builtin_sizes = {}
for size_list in api["builtin_class_sizes"]:
if size_list["build_configuration"] == build_config:
for size in size_list["sizes"]:
builtin_sizes[size["name"]] = size["size"]
break
# Create a file for Variant size, since that class isn't generated.
variant_size_filename = include_gen_folder / "variant_size.hpp"
with variant_size_filename.open("+w", encoding="utf-8") as variant_size_file:
variant_size_source = []
add_header("variant_size.hpp", variant_size_source)
header_guard = "GODOT_CPP_VARIANT_SIZE_HPP"
variant_size_source.append(f"#ifndef {header_guard}")
variant_size_source.append(f"#define {header_guard}")
variant_size_source.append(f'#define GODOT_CPP_VARIANT_SIZE {builtin_sizes["Variant"]}')
variant_size_source.append(f"#endif // ! {header_guard}")
variant_size_file.write("\n".join(variant_size_source))
for builtin_api in api["builtin_classes"]:
if is_pod_type(builtin_api["name"]):
continue
if is_included_type(builtin_api["name"]):
continue
size = builtin_sizes[builtin_api["name"]]
header_filename = include_gen_folder / (camel_to_snake(builtin_api["name"]) + ".hpp")
source_filename = source_gen_folder / (camel_to_snake(builtin_api["name"]) + ".cpp")
# Check used classes for header include
used_classes = set()
fully_used_classes = set()
class_name = builtin_api["name"]
if "constructors" in builtin_api:
for constructor in builtin_api["constructors"]:
if "arguments" in constructor:
for argument in constructor["arguments"]:
if is_included(argument["type"], class_name):
if "default_value" in argument and argument["type"] != "Variant":
fully_used_classes.add(argument["type"])
else:
used_classes.add(argument["type"])
if "methods" in builtin_api:
for method in builtin_api["methods"]:
if "arguments" in method:
for argument in method["arguments"]:
if is_included(argument["type"], class_name):
if "default_value" in argument and argument["type"] != "Variant":
fully_used_classes.add(argument["type"])
else:
used_classes.add(argument["type"])
if "return_type" in method:
if is_included(method["return_type"], class_name):
used_classes.add(method["return_type"])
if "members" in builtin_api:
for member in builtin_api["members"]:
if is_included(member["type"], class_name):
used_classes.add(member["type"])
if "indexing_return_type" in builtin_api:
if is_included(builtin_api["indexing_return_type"], class_name):
used_classes.add(builtin_api["indexing_return_type"])
if "operators" in builtin_api:
for operator in builtin_api["operators"]:
if "right_type" in operator:
if is_included(operator["right_type"], class_name):
used_classes.add(operator["right_type"])
for type_name in fully_used_classes:
if type_name in used_classes:
used_classes.remove(type_name)
used_classes = list(used_classes)
used_classes.sort()
fully_used_classes = list(fully_used_classes)
fully_used_classes.sort()
with header_filename.open("w+", encoding="utf-8") as header_file:
header_file.write(generate_builtin_class_header(builtin_api, size, used_classes, fully_used_classes))
with source_filename.open("w+", encoding="utf-8") as source_file:
source_file.write(generate_builtin_class_source(builtin_api, size, used_classes, fully_used_classes))
# Create a header with all builtin types for convenience.
builtin_header_filename = include_gen_folder / "builtin_types.hpp"
with builtin_header_filename.open("w+", encoding="utf-8") as builtin_header_file:
builtin_header = []
add_header("builtin_types.hpp", builtin_header)
builtin_header.append("#ifndef GODOT_CPP_BUILTIN_TYPES_HPP")
builtin_header.append("#define GODOT_CPP_BUILTIN_TYPES_HPP")
builtin_header.append("")
includes = []
for builtin in builtin_classes:
includes.append(f"godot_cpp/variant/{camel_to_snake(builtin)}.hpp")
includes.sort()
for include in includes:
builtin_header.append(f"#include <{include}>")
builtin_header.append("")
builtin_header.append("#endif // ! GODOT_CPP_BUILTIN_TYPES_HPP")
builtin_header_file.write("\n".join(builtin_header))
# Create a header with bindings for builtin types.
builtin_binds_filename = include_gen_folder / "builtin_binds.hpp"
with builtin_binds_filename.open("w+", encoding="utf-8") as builtin_binds_file:
builtin_binds = []
add_header("builtin_binds.hpp", builtin_binds)
builtin_binds.append("#ifndef GODOT_CPP_BUILTIN_BINDS_HPP")
builtin_binds.append("#define GODOT_CPP_BUILTIN_BINDS_HPP")
builtin_binds.append("")
builtin_binds.append("#include <godot_cpp/variant/builtin_types.hpp>")
builtin_binds.append("")
for builtin_api in api["builtin_classes"]:
if is_included_type(builtin_api["name"]):
if "enums" in builtin_api:
for enum_api in builtin_api["enums"]:
builtin_binds.append(f"VARIANT_ENUM_CAST({builtin_api['name']}::{enum_api['name']});")
builtin_binds.append("")
builtin_binds.append("#endif // ! GODOT_CPP_BUILTIN_BINDS_HPP")
builtin_binds_file.write("\n".join(builtin_binds))
# Create a header to implement all builtin class vararg methods and be included in "variant.hpp".
builtin_vararg_methods_header = include_gen_folder / "builtin_vararg_methods.hpp"
builtin_vararg_methods_header.open("w+").write(
generate_builtin_class_vararg_method_implements_header(api["builtin_classes"])
)
def generate_builtin_class_vararg_method_implements_header(builtin_classes):
result = []
add_header("builtin_vararg_methods.hpp", result)
header_guard = "GODOT_CPP_BUILTIN_VARARG_METHODS_HPP"
result.append(f"#ifndef {header_guard}")
result.append(f"#define {header_guard}")
result.append("")
for builtin_api in builtin_classes:
if "methods" not in builtin_api:
continue
class_name = builtin_api["name"]
for method in builtin_api["methods"]:
if not method["is_vararg"]:
continue
result += make_varargs_template(
method, "is_static" in method and method["is_static"], class_name, False, True
)
result.append("")
result.append(f"#endif // ! {header_guard}")
return "\n".join(result)
def generate_builtin_class_header(builtin_api, size, used_classes, fully_used_classes):
result = []
class_name = builtin_api["name"]
snake_class_name = camel_to_snake(class_name).upper()
header_guard = f"GODOT_CPP_{snake_class_name}_HPP"
add_header(f"{snake_class_name.lower()}.hpp", result)
result.append(f"#ifndef {header_guard}")
result.append(f"#define {header_guard}")
result.append("")
result.append("#include <godot_cpp/core/defs.hpp>")
result.append("")
# Special cases.
if class_name == "String":
result.append("#include <godot_cpp/classes/global_constants.hpp>")
result.append("#include <godot_cpp/variant/char_string.hpp>")
result.append("#include <godot_cpp/variant/char_utils.hpp>")
result.append("")
if class_name == "PackedStringArray":
result.append("#include <godot_cpp/variant/string.hpp>")
result.append("")
if class_name == "PackedColorArray":
result.append("#include <godot_cpp/variant/color.hpp>")
result.append("")
if class_name == "PackedVector2Array":
result.append("#include <godot_cpp/variant/vector2.hpp>")
result.append("")
if class_name == "PackedVector3Array":
result.append("#include <godot_cpp/variant/vector3.hpp>")
result.append("")
if class_name == "PackedVector4Array":
result.append("#include <godot_cpp/variant/vector4.hpp>")
result.append("")
if is_packed_array(class_name):
result.append("#include <godot_cpp/core/error_macros.hpp>")
result.append("#include <initializer_list>")
result.append("")
if class_name == "Array":
result.append("#include <godot_cpp/variant/array_helpers.hpp>")
result.append("")
if class_name == "Callable":
result.append("#include <godot_cpp/variant/callable_custom.hpp>")
result.append("")
if len(fully_used_classes) > 0:
includes = []
for include in fully_used_classes:
if include == "TypedArray":
includes.append("godot_cpp/variant/typed_array.hpp")
elif include == "TypedDictionary":
includes.append("godot_cpp/variant/typed_dictionary.hpp")
else:
includes.append(f"godot_cpp/{get_include_path(include)}")
includes.sort()
for include in includes:
result.append(f"#include <{include}>")
result.append("")
result.append("#include <gdextension_interface.h>")
result.append("")
result.append("namespace godot {")
result.append("")
for type_name in used_classes:
if is_struct_type(type_name):
result.append(f"struct {type_name};")
else:
result.append(f"class {type_name};")
if len(used_classes) > 0:
result.append("")
result.append(f"class {class_name} {{")
result.append(f"\tstatic constexpr size_t {snake_class_name}_SIZE = {size};")
result.append(f"\tuint8_t opaque[{snake_class_name}_SIZE] = {{}};")
result.append("")
result.append("\tfriend class Variant;")
if class_name == "String":
result.append("\tfriend class StringName;")
result.append("")
result.append("\tstatic struct _MethodBindings {")
result.append("\t\tGDExtensionTypeFromVariantConstructorFunc from_variant_constructor;")
if "constructors" in builtin_api:
for constructor in builtin_api["constructors"]:
result.append(f'\t\tGDExtensionPtrConstructor constructor_{constructor["index"]};')
if builtin_api["has_destructor"]:
result.append("\t\tGDExtensionPtrDestructor destructor;")
if "methods" in builtin_api:
for method in builtin_api["methods"]:
result.append(f'\t\tGDExtensionPtrBuiltInMethod method_{method["name"]};')
if "members" in builtin_api:
for member in builtin_api["members"]:
result.append(f'\t\tGDExtensionPtrSetter member_{member["name"]}_setter;')
result.append(f'\t\tGDExtensionPtrGetter member_{member["name"]}_getter;')
if "indexing_return_type" in builtin_api:
result.append("\t\tGDExtensionPtrIndexedSetter indexed_setter;")
result.append("\t\tGDExtensionPtrIndexedGetter indexed_getter;")
if "is_keyed" in builtin_api and builtin_api["is_keyed"]:
result.append("\t\tGDExtensionPtrKeyedSetter keyed_setter;")
result.append("\t\tGDExtensionPtrKeyedGetter keyed_getter;")
result.append("\t\tGDExtensionPtrKeyedChecker keyed_checker;")
if "operators" in builtin_api:
for operator in builtin_api["operators"]:
if "right_type" in operator:
result.append(
f'\t\tGDExtensionPtrOperatorEvaluator operator_{get_operator_id_name(operator["name"])}_{operator["right_type"]};'
)
else:
result.append(f'\t\tGDExtensionPtrOperatorEvaluator operator_{get_operator_id_name(operator["name"])};')
result.append("\t} _method_bindings;")
result.append("")
result.append("\tstatic void init_bindings();")
result.append("\tstatic void _init_bindings_constructors_destructor();")
result.append("")
result.append(f"\t{class_name}(const Variant *p_variant);")
result.append("")
result.append("public:")
result.append(
f"\t_FORCE_INLINE_ GDExtensionTypePtr _native_ptr() const {{ return const_cast<uint8_t(*)[{snake_class_name}_SIZE]>(&opaque); }}"
)
copy_constructor_index = -1
if "constructors" in builtin_api:
for constructor in builtin_api["constructors"]:
method_signature = f"\t{class_name}("
if "arguments" in constructor:
method_signature += make_function_parameters(
constructor["arguments"], include_default=True, for_builtin=True
)
if len(constructor["arguments"]) == 1 and constructor["arguments"][0]["type"] == class_name:
copy_constructor_index = constructor["index"]
method_signature += ");"
result.append(method_signature)
# Move constructor.
result.append(f"\t{class_name}({class_name} &&p_other);")
# Special cases.
if class_name == "String" or class_name == "StringName" or class_name == "NodePath":
if class_name == "StringName":
result.append(f"\t{class_name}(const char *p_from, bool p_static = false);")
else:
result.append(f"\t{class_name}(const char *p_from);")
result.append(f"\t{class_name}(const wchar_t *p_from);")
result.append(f"\t{class_name}(const char16_t *p_from);")
result.append(f"\t{class_name}(const char32_t *p_from);")
if class_name == "Callable":
result.append("\tCallable(CallableCustom *p_custom);")
result.append("\tCallableCustom *get_custom() const;")
if "constants" in builtin_api:
axis_constants_count = 0
for constant in builtin_api["constants"]:
# Special case: Vector3.Axis is the only enum in the bindings.
# It's technically not supported by Variant but works for direct access.
if class_name == "Vector3" and constant["name"].startswith("AXIS"):
if axis_constants_count == 0:
result.append("\tenum Axis {")
result.append(f'\t\t{constant["name"]} = {constant["value"]},')
axis_constants_count += 1
if axis_constants_count == 3:
result.append("\t};")
else:
result.append(f'\tstatic const {correct_type(constant["type"])} {constant["name"]};')
if builtin_api["has_destructor"]:
result.append(f"\t~{class_name}();")
method_list = []
if "methods" in builtin_api:
for method in builtin_api["methods"]:
method_list.append(method["name"])
vararg = method["is_vararg"]
if vararg:
result.append("\ttemplate <typename... Args>")
method_signature = "\t"
if "is_static" in method and method["is_static"]:
method_signature += "static "
if "return_type" in method:
method_signature += f'{correct_type(method["return_type"])}'
if not method_signature.endswith("*"):
method_signature += " "
else:
method_signature += "void "
method_signature += f'{method["name"]}('
method_arguments = []
if "arguments" in method:
method_arguments = method["arguments"]
method_signature += make_function_parameters(
method_arguments, include_default=True, for_builtin=True, is_vararg=vararg
)
method_signature += ")"
if method["is_const"]:
method_signature += " const"
method_signature += ";"
result.append(method_signature)
# Special cases.
if class_name == "String":
result.append("\tstatic String utf8(const char *p_from, int64_t p_len = -1);")
result.append("\tError parse_utf8(const char *p_from, int64_t p_len = -1);")
result.append("\tstatic String utf16(const char16_t *p_from, int64_t p_len = -1);")
result.append(
"\tError parse_utf16(const char16_t *p_from, int64_t p_len = -1, bool p_default_little_endian = true);"
)
result.append("\tCharString utf8() const;")
result.append("\tCharString ascii() const;")
result.append("\tChar16String utf16() const;")
result.append("\tChar32String utf32() const;")
result.append("\tCharWideString wide_string() const;")
result.append("\tstatic String num_real(double p_num, bool p_trailing = true);")
result.append("\tError resize(int64_t p_size);")
if "members" in builtin_api:
for member in builtin_api["members"]:
if f'get_{member["name"]}' not in method_list:
result.append(f'\t{correct_type(member["type"])} get_{member["name"]}() const;')
if f'set_{member["name"]}' not in method_list:
result.append(f'\tvoid set_{member["name"]}({type_for_parameter(member["type"])}value);')
if "operators" in builtin_api:
for operator in builtin_api["operators"]:
if is_valid_cpp_operator(operator["name"]):
if "right_type" in operator:
result.append(
f'\t{correct_type(operator["return_type"])} operator{get_operator_cpp_name(operator["name"])}({type_for_parameter(operator["right_type"])}p_other) const;'
)
else:
result.append(
f'\t{correct_type(operator["return_type"])} operator{get_operator_cpp_name(operator["name"])}() const;'
)
# Copy assignment.
if copy_constructor_index >= 0:
result.append(f"\t{class_name} &operator=(const {class_name} &p_other);")
# Move assignment.
result.append(f"\t{class_name} &operator=({class_name} &&p_other);")
# Special cases.
if class_name == "String":
result.append("\tString &operator=(const char *p_str);")
result.append("\tString &operator=(const wchar_t *p_str);")
result.append("\tString &operator=(const char16_t *p_str);")
result.append("\tString &operator=(const char32_t *p_str);")
result.append("\tbool operator==(const char *p_str) const;")
result.append("\tbool operator==(const wchar_t *p_str) const;")
result.append("\tbool operator==(const char16_t *p_str) const;")
result.append("\tbool operator==(const char32_t *p_str) const;")
result.append("\tbool operator!=(const char *p_str) const;")
result.append("\tbool operator!=(const wchar_t *p_str) const;")
result.append("\tbool operator!=(const char16_t *p_str) const;")
result.append("\tbool operator!=(const char32_t *p_str) const;")
result.append("\tString operator+(const char *p_str);")
result.append("\tString operator+(const wchar_t *p_str);")
result.append("\tString operator+(const char16_t *p_str);")
result.append("\tString operator+(const char32_t *p_str);")
result.append("\tString operator+(char32_t p_char);")
result.append("\tString &operator+=(const String &p_str);")
result.append("\tString &operator+=(char32_t p_char);")
result.append("\tString &operator+=(const char *p_str);")
result.append("\tString &operator+=(const wchar_t *p_str);")
result.append("\tString &operator+=(const char32_t *p_str);")
result.append("\tconst char32_t &operator[](int64_t p_index) const;")
result.append("\tchar32_t &operator[](int64_t p_index);")
result.append("\tconst char32_t *ptr() const;")
result.append("\tchar32_t *ptrw();")
if class_name == "Array":
result.append("\ttemplate <typename... Args>")
result.append("\tstatic Array make(Args... p_args) {")
result.append("\t\treturn helpers::append_all(Array(), p_args...);")
result.append("\t}")
if is_packed_array(class_name):
return_type = correct_type(builtin_api["indexing_return_type"])
if class_name == "PackedByteArray":
return_type = "uint8_t"
elif class_name == "PackedInt32Array":
return_type = "int32_t"
elif class_name == "PackedFloat32Array":
return_type = "float"
result.append(f"\tconst {return_type} &operator[](int64_t p_index) const;")
result.append(f"\t{return_type} &operator[](int64_t p_index);")
result.append(f"\tconst {return_type} *ptr() const;")
result.append(f"\t{return_type} *ptrw();")
iterators = """
struct Iterator {
_FORCE_INLINE_ $TYPE &operator*() const {
return *elem_ptr;
}
_FORCE_INLINE_ $TYPE *operator->() const { return elem_ptr; }
_FORCE_INLINE_ Iterator &operator++() {
elem_ptr++;
return *this;
}
_FORCE_INLINE_ Iterator &operator--() {
elem_ptr--;
return *this;
}
_FORCE_INLINE_ bool operator==(const Iterator &b) const { return elem_ptr == b.elem_ptr; }
_FORCE_INLINE_ bool operator!=(const Iterator &b) const { return elem_ptr != b.elem_ptr; }
Iterator($TYPE *p_ptr) { elem_ptr = p_ptr; }
Iterator() {}
Iterator(const Iterator &p_it) { elem_ptr = p_it.elem_ptr; }
private:
$TYPE *elem_ptr = nullptr;
};
struct ConstIterator {
_FORCE_INLINE_ const $TYPE &operator*() const {
return *elem_ptr;
}
_FORCE_INLINE_ const $TYPE *operator->() const { return elem_ptr; }
_FORCE_INLINE_ ConstIterator &operator++() {
elem_ptr++;
return *this;
}
_FORCE_INLINE_ ConstIterator &operator--() {
elem_ptr--;
return *this;
}
_FORCE_INLINE_ bool operator==(const ConstIterator &b) const { return elem_ptr == b.elem_ptr; }
_FORCE_INLINE_ bool operator!=(const ConstIterator &b) const { return elem_ptr != b.elem_ptr; }
ConstIterator(const $TYPE *p_ptr) { elem_ptr = p_ptr; }
ConstIterator() {}
ConstIterator(const ConstIterator &p_it) { elem_ptr = p_it.elem_ptr; }
private:
const $TYPE *elem_ptr = nullptr;
};
_FORCE_INLINE_ Iterator begin() {
return Iterator(ptrw());
}
_FORCE_INLINE_ Iterator end() {
return Iterator(ptrw() + size());
}
_FORCE_INLINE_ ConstIterator begin() const {