forked from godotengine/godot-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binding_generator.py
1760 lines (1399 loc) · 65.2 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 print_file_list(api_filepath, output_dir, headers=False, sources=False):
api = {}
end = ";"
with open(api_filepath) as api_file:
api = json.load(api_file)
include_gen_folder = Path(output_dir) / "gen" / "include" / "godot_cpp"
source_gen_folder = Path(output_dir) / "gen" / "src"
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:
print(str(header_filename.as_posix()), end=end)
if sources:
print(str(source_filename.as_posix()), end=end)
for engine_class in api["classes"]:
# TODO: Properly setup this singleton since it conflicts with ClassDB in the bindings.
if engine_class["name"] == "ClassDB":
continue
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:
print(str(header_filename.as_posix()), end=end)
if sources:
print(str(source_filename.as_posix()), end=end)
utility_functions_header_path = include_gen_folder / "variant" / "utility_functions.hpp"
utility_functions_source_path = source_gen_folder / "variant" / "utility_functions.cpp"
global_constants_header_path = include_gen_folder / "classes" / "global_constants.hpp"
if headers:
print(str(utility_functions_header_path.as_posix()), end=end)
print(str(global_constants_header_path.as_posix()), end=end)
if sources:
print(str(utility_functions_source_path.as_posix()), end=end)
def generate_bindings(api_filepath, use_template_get_node, output_dir="."):
api = None
target_dir = Path(output_dir) / "gen"
with open(api_filepath) as api_file:
api = json.load(api_file)
shutil.rmtree(target_dir, ignore_errors=True)
target_dir.mkdir(parents=True)
generate_global_constants(api, target_dir)
generate_builtin_bindings(api, target_dir, "float_64")
generate_engine_classes_bindings(api, target_dir, use_template_get_node)
generate_utility_functions(api, target_dir)
builtin_classes = []
# Key is class name, value is boolean where True means the class is refcounted.
engine_classes = {}
singletons = []
def generate_builtin_bindings(api, output_dir, build_config):
global builtin_classes
include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "variant"
source_gen_folder = Path(output_dir) / "src" / "variant"
include_gen_folder.mkdir(parents=True, exist_ok=True)
source_gen_folder.mkdir(parents=True, exist_ok=True)
# 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") 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:
# FIXME Temporary workaround for incorrect JSON
if operator["right_type"] == "Nil":
used_classes.add("Variant")
elif 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)
with header_filename.open("w+") as header_file:
header_file.write(generate_builtin_class_header(builtin_api, size, used_classes, fully_used_classes))
with source_filename.open("w+") 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+") 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("")
for builtin in builtin_classes:
builtin_header.append(f"#include <godot_cpp/variant/{camel_to_snake(builtin)}.hpp>")
builtin_header.append("")
builtin_header.append("#endif // ! GODOT_CPP_BUILTIN_TYPES_HPP")
builtin_header_file.write("\n".join(builtin_header))
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/variant/char_string.hpp>")
for include in fully_used_classes:
result.append(f"#include <godot_cpp/{get_include_path(include)}>")
if len(fully_used_classes) > 0:
result.append("")
result.append(f"#include <godot/gdnative_interface.h>")
result.append("")
result.append("namespace godot {")
result.append("")
for type_name in used_classes:
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(
f"\t_FORCE_INLINE_ GDNativeTypePtr ptr() const {{ return const_cast<uint8_t (*)[{snake_class_name}_SIZE]>(&opaque); }}"
)
result.append("")
result.append("\tfriend class Variant;")
result.append("")
result.append("\tstatic struct _MethodBindings {")
if "constructors" in builtin_api:
for constructor in builtin_api["constructors"]:
result.append(f'\t\tGDNativePtrConstructor constructor_{constructor["index"]};')
if builtin_api["has_destructor"]:
result.append("\t\tGDNativePtrDestructor destructor;")
if "methods" in builtin_api:
for method in builtin_api["methods"]:
result.append(f'\t\tGDNativePtrBuiltInMethod method_{method["name"]};')
if "members" in builtin_api:
for member in builtin_api["members"]:
result.append(f'\t\tGDNativePtrSetter member_{member["name"]}_setter;')
result.append(f'\t\tGDNativePtrGetter member_{member["name"]}_getter;')
if "indexing_return_type" in builtin_api:
result.append(f"\t\tGDNativePtrIndexedSetter indexed_setter;")
result.append(f"\t\tGDNativePtrIndexedGetter indexed_getter;")
if "is_keyed" in builtin_api and builtin_api["is_keyed"]:
result.append(f"\t\tGDNativePtrKeyedSetter keyed_setter;")
result.append(f"\t\tGDNativePtrKeyedGetter keyed_getter;")
result.append(f"\t\tGDNativePtrKeyedChecker keyed_checker;")
if "operators" in builtin_api:
for operator in builtin_api["operators"]:
if "right_type" in operator:
result.append(
f'\t\tGDNativePtrOperatorEvaluator operator_{get_operator_id_name(operator["name"])}_{operator["right_type"]};'
)
else:
result.append(f'\t\tGDNativePtrOperatorEvaluator operator_{get_operator_id_name(operator["name"])};')
result.append("\t} _method_bindings;")
result.append("")
result.append("\tstatic void init_bindings();")
result.append("")
result.append("public:")
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} &&other);")
# Special cases.
if class_name == "String" or class_name == "StringName" or class_name == "NodePath":
result.append(f"\t{class_name}(const char *from);")
result.append(f"\t{class_name}(const wchar_t *from);")
result.append(f"\t{class_name}(const char16_t *from);")
result.append(f"\t{class_name}(const char32_t *from);")
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<class... 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"])} '
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("\tCharString utf8() const;")
result.append("\tCharString ascii() const;")
result.append("\tChar16String utf16() const;")
result.append("\tChar32String utf32() const;")
result.append("\tCharWideString wide_string() const;")
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 operator["name"] not in ["in", "xor"]:
if "right_type" in operator:
result.append(
f'\t{correct_type(operator["return_type"])} operator{operator["name"]}({type_for_parameter(operator["right_type"])}other) const;'
)
else:
result.append(
f'\t{correct_type(operator["return_type"])} operator{operator["name"].replace("unary", "")}() const;'
)
# Copy assignment.
if copy_constructor_index >= 0:
result.append(f"\t{class_name} &operator=(const {class_name} &other);")
# Move assignment.
result.append(f"\t{class_name} &operator=({class_name} &&other);")
# Special cases.
if class_name == "String":
result.append("String &operator=(const char *p_str);")
result.append("String &operator=(const wchar_t *p_str);")
result.append("String &operator=(const char16_t *p_str);")
result.append("String &operator=(const char32_t *p_str);")
result.append("bool operator==(const char *p_str) const;")
result.append("bool operator==(const wchar_t *p_str) const;")
result.append("bool operator==(const char16_t *p_str) const;")
result.append("bool operator==(const char32_t *p_str) const;")
result.append("bool operator!=(const char *p_str) const;")
result.append("bool operator!=(const wchar_t *p_str) const;")
result.append("bool operator!=(const char16_t *p_str) const;")
result.append("bool operator!=(const char32_t *p_str) const;")
result.append(f"\tconst char32_t &operator[](int p_index) const;")
result.append(f"\tchar32_t &operator[](int p_index);")
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 + f" &operator[](int p_index) const;")
result.append(f"\t" + return_type + f" &operator[](int p_index);")
result.append("};")
if class_name == "String":
result.append("")
result.append("bool operator==(const char *p_chr, const String &p_str);")
result.append("bool operator==(const wchar_t *p_chr, const String &p_str);")
result.append("bool operator==(const char16_t *p_chr, const String &p_str);")
result.append("bool operator==(const char32_t *p_chr, const String &p_str);")
result.append("bool operator!=(const char *p_chr, const String &p_str);")
result.append("bool operator!=(const wchar_t *p_chr, const String &p_str);")
result.append("bool operator!=(const char16_t *p_chr, const String &p_str);")
result.append("bool operator!=(const char32_t *p_chr, const String &p_str);")
result.append("String operator+(const char *p_chr, const String &p_str);")
result.append("String operator+(const wchar_t *p_chr, const String &p_str);")
result.append("String operator+(const char16_t *p_chr, const String &p_str);")
result.append("String operator+(const char32_t *p_chr, const String &p_str);")
result.append("")
result.append("} // namespace godot")
result.append(f"#endif // ! {header_guard}")
return "\n".join(result)
def generate_builtin_class_source(builtin_api, size, used_classes, fully_used_classes):
result = []
class_name = builtin_api["name"]
snake_class_name = camel_to_snake(class_name)
enum_type_name = f"GDNATIVE_VARIANT_TYPE_{snake_class_name.upper()}"
add_header(f"{snake_class_name}.cpp", result)
result.append("")
result.append(f"#include <godot_cpp/variant/{snake_class_name}.hpp>")
result.append("")
result.append("#include <godot_cpp/core/binder_common.hpp>")
result.append("")
result.append("#include <godot_cpp/godot.hpp>")
result.append("")
# Only used since the "fully used" is included in header already.
for include in used_classes:
result.append(f"#include <godot_cpp/{get_include_path(include)}>")
if len(used_classes) > 0:
result.append("")
result.append("#include <godot_cpp/core/builtin_ptrcall.hpp>")
result.append("")
result.append("#include <utility>")
result.append("")
result.append("namespace godot {")
result.append("")
result.append(f"{class_name}::_MethodBindings {class_name}::_method_bindings;")
result.append("")
result.append(f"void {class_name}::init_bindings() {{")
if "constructors" in builtin_api:
for constructor in builtin_api["constructors"]:
result.append(
f'\t_method_bindings.constructor_{constructor["index"]} = internal::interface->variant_get_ptr_constructor({enum_type_name}, {constructor["index"]});'
)
if builtin_api["has_destructor"]:
result.append(
f"\t_method_bindings.destructor = internal::interface->variant_get_ptr_destructor({enum_type_name});"
)
if "methods" in builtin_api:
for method in builtin_api["methods"]:
# TODO: Add error check for hash mismatch.
result.append(
f'\t_method_bindings.method_{method["name"]} = internal::interface->variant_get_ptr_builtin_method({enum_type_name}, "{method["name"]}", {method["hash"]});'
)
if "members" in builtin_api:
for member in builtin_api["members"]:
result.append(
f'\t_method_bindings.member_{member["name"]}_setter = internal::interface->variant_get_ptr_setter({enum_type_name}, "{member["name"]}");'
)
result.append(
f'\t_method_bindings.member_{member["name"]}_getter = internal::interface->variant_get_ptr_getter({enum_type_name}, "{member["name"]}");'
)
if "indexing_return_type" in builtin_api:
result.append(
f"\t_method_bindings.indexed_setter = internal::interface->variant_get_ptr_indexed_setter({enum_type_name});"
)
result.append(
f"\t_method_bindings.indexed_getter = internal::interface->variant_get_ptr_indexed_getter({enum_type_name});"
)
if "is_keyed" in builtin_api and builtin_api["is_keyed"]:
result.append(
f"\t_method_bindings.keyed_setter = internal::interface->variant_get_ptr_keyed_setter({enum_type_name});"
)
result.append(
f"\t_method_bindings.keyed_getter = internal::interface->variant_get_ptr_keyed_getter({enum_type_name});"
)
result.append(
f"\t_method_bindings.keyed_checker = internal::interface->variant_get_ptr_keyed_checker({enum_type_name});"
)
if "operators" in builtin_api:
for operator in builtin_api["operators"]:
if "right_type" in operator:
result.append(
f'\t_method_bindings.operator_{get_operator_id_name(operator["name"])}_{operator["right_type"]} = internal::interface->variant_get_ptr_operator_evaluator(GDNATIVE_VARIANT_OP_{get_operator_id_name(operator["name"]).upper()}, {enum_type_name}, GDNATIVE_VARIANT_TYPE_{camel_to_snake(operator["right_type"]).upper()});'
)
else:
result.append(
f'\t_method_bindings.operator_{get_operator_id_name(operator["name"])} = internal::interface->variant_get_ptr_operator_evaluator(GDNATIVE_VARIANT_OP_{get_operator_id_name(operator["name"]).upper()}, {enum_type_name}, GDNATIVE_VARIANT_TYPE_NIL);'
)
result.append("}")
result.append("")
copy_constructor_index = -1
if "constructors" in builtin_api:
for constructor in builtin_api["constructors"]:
method_signature = f"{class_name}::{class_name}("
if "arguments" in constructor:
method_signature += make_function_parameters(
constructor["arguments"], include_default=False, for_builtin=True
)
method_signature += ") {"
result.append(method_signature)
method_call = (
f'\tinternal::_call_builtin_constructor(_method_bindings.constructor_{constructor["index"]}, &opaque'
)
if "arguments" in constructor:
if len(constructor["arguments"]) == 1 and constructor["arguments"][0]["type"] == class_name:
copy_constructor_index = constructor["index"]
method_call += ", "
arguments = []
for argument in constructor["arguments"]:
(encode, arg_name) = get_encoded_arg(
argument["name"],
argument["type"],
argument["meta"] if "meta" in argument else None,
)
result += encode
arguments.append(arg_name)
method_call += ", ".join(arguments)
method_call += ");"
result.append(method_call)
result.append("}")
result.append("")
# Move constructor.
result.append(f"{class_name}::{class_name}({class_name} &&other) {{")
result.append("\tstd::swap(opaque, other.opaque);")
result.append("}")
result.append("")
if builtin_api["has_destructor"]:
result.append(f"{class_name}::~{class_name}() {{")
result.append("\t_method_bindings.destructor(&opaque);")
result.append("}")
result.append("")
method_list = []
if "methods" in builtin_api:
for method in builtin_api["methods"]:
method_list.append(method["name"])
if "is_vararg" in method and method["is_vararg"]:
# Done in the header because of the template.
continue
method_signature = make_signature(class_name, method, for_builtin=True)
result.append(method_signature + "{")
method_call = "\t"
if "return_type" in method:
method_call += f'return internal::_call_builtin_method_ptr_ret<{correct_type(method["return_type"])}>('
else:
method_call += f"internal::_call_builtin_method_ptr_no_ret("
method_call += f'_method_bindings.method_{method["name"]}, '
if "is_static" in method and method["is_static"]:
method_call += "nullptr"
else:
method_call += "(GDNativeTypePtr)&opaque"
if "arguments" in method:
arguments = []
method_call += ", "
for argument in method["arguments"]:
(encode, arg_name) = get_encoded_arg(
argument["name"],
argument["type"],
argument["meta"] if "meta" in argument else None,
)
result += encode
arguments.append(arg_name)
method_call += ", ".join(arguments)
method_call += ");"
result.append(method_call)
result.append("}")
result.append("")
if "members" in builtin_api:
for member in builtin_api["members"]:
if f'get_{member["name"]}' not in method_list:
result.append(f'{correct_type(member["type"])} {class_name}::get_{member["name"]}() const {{')
result.append(
f'\treturn internal::_call_builtin_ptr_getter<{correct_type(member["type"])}>(_method_bindings.member_{member["name"]}_getter, (const GDNativeTypePtr)&opaque);'
)
result.append("}")
if f'set_{member["name"]}' not in method_list:
result.append(f'void {class_name}::set_{member["name"]}({type_for_parameter(member["type"])}value) {{')
(encode, arg_name) = get_encoded_arg("value", member["type"], None)
result += encode
result.append(
f'\t_method_bindings.member_{member["name"]}_setter((const GDNativeTypePtr)&opaque, (const GDNativeTypePtr){arg_name});'
)
result.append("}")
result.append("")
if "operators" in builtin_api:
for operator in builtin_api["operators"]:
if operator["name"] not in ["in", "xor"]:
if "right_type" in operator:
result.append(
f'{correct_type(operator["return_type"])} {class_name}::operator{operator["name"]}({type_for_parameter(operator["right_type"])}other) const {{'
)
(encode, arg_name) = get_encoded_arg("other", operator["right_type"], None)
result += encode
result.append(
f'\treturn internal::_call_builtin_operator_ptr<{correct_type(operator["return_type"])}>(_method_bindings.operator_{get_operator_id_name(operator["name"])}_{operator["right_type"]}, (const GDNativeTypePtr)&opaque, (const GDNativeTypePtr){arg_name});'
)
result.append("}")
else:
result.append(
f'{correct_type(operator["return_type"])} {class_name}::operator{operator["name"].replace("unary", "")}() const {{'
)
result.append(
f'\treturn internal::_call_builtin_operator_ptr<{correct_type(operator["return_type"])}>(_method_bindings.operator_{get_operator_id_name(operator["name"])}, (const GDNativeTypePtr)&opaque, (const GDNativeTypePtr)nullptr);'
)
result.append("}")
result.append("")
# Copy assignment.
if copy_constructor_index >= 0:
result.append(f"{class_name} &{class_name}::operator=(const {class_name} &other) {{")
if builtin_api["has_destructor"]:
result.append("\t_method_bindings.destructor(&opaque);")
(encode, arg_name) = get_encoded_arg(
"other",
class_name,
None,
)
result += encode
result.append(
f"\tinternal::_call_builtin_constructor(_method_bindings.constructor_{copy_constructor_index}, &opaque, {arg_name});"
)
result.append("\treturn *this;")
result.append("}")
result.append("")
# Move assignment.
result.append(f"{class_name} &{class_name}::operator=({class_name} &&other) {{")
result.append("\tstd::swap(opaque, other.opaque);")
result.append("\treturn *this;")
result.append("}")
result.append("")
result.append("} //namespace godot")
return "\n".join(result)
def generate_engine_classes_bindings(api, output_dir, use_template_get_node):
global engine_classes
global singletons
include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
source_gen_folder = Path(output_dir) / "src" / "classes"
include_gen_folder.mkdir(parents=True, exist_ok=True)
source_gen_folder.mkdir(parents=True, exist_ok=True)
# First create map of classes and singletons.
for class_api in api["classes"]:
# TODO: Properly setup this singleton since it conflicts with ClassDB in the bindings.
if class_api["name"] == "ClassDB":
continue
engine_classes[class_api["name"]] = class_api["is_refcounted"]
for native_struct in api["native_structures"]:
engine_classes[native_struct["name"]] = False
for singleton in api["singletons"]:
singletons.append(singleton["name"])
for class_api in api["classes"]:
# TODO: Properly setup this singleton since it conflicts with ClassDB in the bindings.
if class_api["name"] == "ClassDB":
continue
# Check used classes for header include.
used_classes = set()
fully_used_classes = set()
class_name = class_api["name"]
header_filename = include_gen_folder / (camel_to_snake(class_api["name"]) + ".hpp")
source_filename = source_gen_folder / (camel_to_snake(class_api["name"]) + ".cpp")
if "methods" in class_api:
for method in class_api["methods"]:
if "arguments" in method:
for argument in method["arguments"]:
type_name = argument["type"]
if type_name.endswith("*"):
type_name = type_name[:-1]
if is_included(type_name, class_name):
if is_enum(type_name):
fully_used_classes.add(get_enum_class(type_name))
elif "default_value" in argument:
fully_used_classes.add(type_name)
else:
used_classes.add(type_name)
if is_refcounted(type_name):
fully_used_classes.add("Ref")
if "return_value" in method:
type_name = method["return_value"]["type"]
if type_name.endswith("*"):
type_name = type_name[:-1]
if is_included(type_name, class_name):
if is_enum(type_name):
fully_used_classes.add(get_enum_class(type_name))
elif is_variant(type_name):
fully_used_classes.add(type_name)
else:
used_classes.add(type_name)
if is_refcounted(type_name):
fully_used_classes.add("Ref")
if "members" in class_api:
for member in class_api["members"]:
if is_included(member["type"], class_name):
if is_enum(member["type"]):
fully_used_classes.add(get_enum_class(member["type"]))
else:
used_classes.add(member["type"])
if is_refcounted(member["type"]):
fully_used_classes.add("Ref")
if "inherits" in class_api:
if is_included(class_api["inherits"], class_name):
fully_used_classes.add(class_api["inherits"])
if is_refcounted(class_api["name"]):
fully_used_classes.add("Ref")
else:
fully_used_classes.add("Wrapped")
for type_name in fully_used_classes:
if type_name in used_classes:
used_classes.remove(type_name)
with header_filename.open("w+") as header_file:
header_file.write(
generate_engine_class_header(class_api, used_classes, fully_used_classes, use_template_get_node)
)
with source_filename.open("w+") as source_file:
source_file.write(
generate_engine_class_source(class_api, used_classes, fully_used_classes, use_template_get_node)
)
for native_struct in api["native_structures"]:
struct_name = native_struct["name"]
snake_struct_name = camel_to_snake(struct_name)
header_filename = include_gen_folder / (snake_struct_name + ".hpp")
result = []
add_header(f"{snake_struct_name}.hpp", result)
header_guard = f"GODOT_CPP_{snake_struct_name.upper()}_HPP"
result.append(f"#ifndef {header_guard}")
result.append(f"#define {header_guard}")
result.append("")
result.append("namespace godot {")
result.append("")
result.append(f"struct {struct_name} {{")
for field in native_struct["format"].split(","):
result.append(f"\t{field};")
result.append("};")
result.append("")
result.append("} // namespace godot")
result.append("")
result.append(f"#endif // ! {header_guard}")
with header_filename.open("w+") as header_file:
header_file.write("\n".join(result))
def generate_engine_class_header(class_api, used_classes, fully_used_classes, use_template_get_node):
global singletons
result = []
class_name = class_api["name"]
snake_class_name = camel_to_snake(class_name).upper()
is_singleton = class_name in singletons
add_header(f"{snake_class_name.lower()}.hpp", result)
header_guard = f"GODOT_CPP_{snake_class_name}_HPP"
result.append(f"#ifndef {header_guard}")
result.append(f"#define {header_guard}")
result.append("")
for included in fully_used_classes:
result.append(f"#include <godot_cpp/{get_include_path(included)}>")
if len(fully_used_classes) > 0:
result.append("")
if class_name != "Object":
result.append("#include <godot_cpp/core/class_db.hpp>")
result.append("")
result.append("#include <type_traits>")
result.append("")
result.append("namespace godot {")
result.append("")
for type_name in used_classes:
result.append(f"class {type_name};")
if len(used_classes) > 0:
result.append("")
inherits = class_api["inherits"] if "inherits" in class_api else "Wrapped"
result.append(f"class {class_name} : public {inherits} {{")
result.append(f"\tGDNATIVE_CLASS({class_name}, {inherits})")
result.append("")
result.append("public:")
# Constructor override, since parent Wrapped has protected constructor.
result.append(f"\t{class_name}() = default;")
result.append("")
if "enums" in class_api:
for enum_api in class_api["enums"]:
result.append(f'\tenum {enum_api["name"]} {{')
for value in enum_api["values"]:
result.append(f'\t\t{value["name"]} = {value["value"]},')
result.append("\t};")
result.append("")
if is_singleton:
result.append(f"\tstatic {class_name} *get_singleton();")
result.append("")
if "methods" in class_api:
for method in class_api["methods"]:
if method["is_virtual"]:
# Will be done later.
continue
vararg = "is_vararg" in method and method["is_vararg"]
method_signature = "\t"
if vararg:
method_signature += "private: "
method_signature += make_signature(
class_name, method, for_header=True, use_template_get_node=use_template_get_node
)
result.append(method_signature + ";")
if vararg:
# Add templated version.
result += make_varargs_template(method)
# Virtuals now.
for method in class_api["methods"]:
if not method["is_virtual"]:
continue
method_signature = "\t"
method_signature += make_signature(
class_name, method, for_header=True, use_template_get_node=use_template_get_node
)
result.append(method_signature + ";")
result.append("protected:")
result.append("\ttemplate <class T>")
result.append("\tstatic void register_virtuals() {")
if class_name != "Object":
result.append(f"\t\t{inherits}::register_virtuals<T>();")
if "methods" in class_api:
for method in class_api["methods"]:
if not method["is_virtual"]:
continue
method_name = escape_identifier(method["name"])
result.append(
f"\t\tif constexpr (!std::is_same_v<decltype(&{class_name}::{method_name}),decltype(&T::{method_name})>) {{"
)
result.append(f"\t\t\tBIND_VIRTUAL_METHOD(T, {method_name});")
result.append("\t\t}")
result.append("\t}")
result.append("")
result.append("public:")
# Special cases.
if class_name == "Object":
result.append("")
result.append("\ttemplate<class T>")
result.append("\tstatic T *cast_to(Object *p_object);")
result.append("\tvirtual ~Object() = default;")
elif use_template_get_node and class_name == "Node":
result.append("\ttemplate<class T>")
result.append(
"\tT *get_node(const NodePath &p_path) const { return Object::cast_to<T>(get_node_internal(p_path)); }"
)
result.append("")
result.append("};")
result.append("")
result.append("} // namespace godot")
result.append(f"#endif // ! {header_guard}")
return "\n".join(result)
def generate_engine_class_source(class_api, used_classes, fully_used_classes, use_template_get_node):
global singletons
result = []
class_name = class_api["name"]
snake_class_name = camel_to_snake(class_name)
inherits = class_api["inherits"] if "inherits" in class_api else "Wrapped"
is_singleton = class_name in singletons
add_header(f"{snake_class_name}.cpp", result)
result.append(f"#include <godot_cpp/classes/{snake_class_name}.hpp>")
result.append("")
result.append(f"#include <godot_cpp/core/engine_ptrcall.hpp>")
result.append(f"#include <godot_cpp/core/error_macros.hpp>")