-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathlib_utils_gen_dd3d_api.py
More file actions
2437 lines (2043 loc) · 94 KB
/
lib_utils_gen_dd3d_api.py
File metadata and controls
2437 lines (2043 loc) · 94 KB
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 python3
# There are several macros here that you need to use to mark functions, classes, and enums for adding them to the Native API.
#
# NAPI_CLASS_REF - before the keyword "class" for a RefCounted, e.g.: NAPI_CLASS_REF class DebugDraw3DConfig
# NAPI_CLASS_SINGLETON - before the keyword "class" for a singleton, e.g.: NAPI_CLASS_SINGLETON class DebugDraw3D
# NAPI_ENUM - before the keyword “enum” for enums with explicit constant types, e.g.: NAPI_ENUM enum PointType : uint32_t
# It is not necessary to explicitly specify enum values; the generator will attempt to substitute them automatically.
# NAPI - used to mark functions.
# NSELF_RETURN - should be used immediately after "NAPI" instead of the return type "void",
# and the function name should end with "_selfreturn", for example: NAPI NSELF_RETURN set_thickness_selfreturn(real_t _value)
#
# Arguments of the function with Ref<godot::T> or godot::Ref<godot::T> is used for Godot types
# and Ref<T> is for DD3D classes
#
# All Packed*Arrays are not available in the Native API. StringName, NodePath, Array and Dictionary too.
# If you need to pass an array to the Native API, then you need to:
# 1) add the suffix "_c" to the functions,
# 2) replace the argument with the supported array type with two separate arguments with the same name
# but different suffixes ("_data" and "_size") and pointer and "uint64_t" types.
# Example before:
# static void draw_lines(const godot::PackedVector3Array &lines, const real_t &duration = 0)
# after:
# NAPI static void draw_lines_c(const godot::Vector3 * lines_data, const uint64_t &lines_size, const real_t &duration = 0)
# If you need to pass a string to the Native API,
# then you also need to add the suffix "_c" and replace "String" with "char*" and add the suffix "_string" to the argument name.
# Example before:
# void set_text(godot::String key, real_t duration = -1)
# after:
# NAPI void set_text_c(const char* key_string, real_t duration = -1)
# In this case, the string will be converted to a utf8 char array.
#
# The API may differ depending on the flags passed in `env`. Some features may also be disabled depending on C++ compilation flags.
# Currently, this script directly supports the following flags:
# `precision`
from SCons.Script.SConscript import SConsEnvironment
import os, shutil, json, re, hashlib, copy
import lib_utils
def dev_print(line: str):
if False:
print(line)
def trace_print(line: str):
if False:
print(line)
default_colors_map = {
"Colors::empty_color": "godot::Color(0, 0, 0, 0)",
"Colors::white_smoke": "godot::Color(0.96f, 0.96f, 0.96f, 1.0f)",
}
allowed_enum_types = [
"char",
"short",
"int",
"uint8_t",
"uint16_t",
"uint32_t",
"uint64_t",
"int8_t",
"int16_t",
"int32_t",
"int64_t",
]
basic_godot_types = [
"godot::Vector2",
"godot::Vector2i",
"godot::Rect2",
"godot::Rect2i",
"godot::Vector3",
"godot::Vector3i",
"godot::Transform2D",
"godot::Vector4",
"godot::Vector4i",
"godot::Plane",
"godot::Quaternion",
"godot::AABB",
"godot::Basis",
"godot::Transform3D",
"godot::Projection",
"godot::Color",
#
# Restricted
"godot::Variant",
"godot::RID",
"godot::ObjectID",
"godot::Callable",
"godot::Signal",
"godot::Dictionary",
"godot::Array",
]
basic_to_trivial_types = {
"godot::Quaternion": "DD3DShared::CQuaternion",
"godot::Projection": "DD3DShared::CProjection",
}
disallowed_godot_types = [
"godot::Variant",
"godot::RID",
"godot::ObjectID",
"godot::Callable",
"godot::Signal",
"godot::Dictionary",
"godot::Array",
]
basic_types_to_arrays = {
"char": "godot::String",
"uint8_t": "godot::PackedByteArray",
"int32_t": "godot::PackedInt32Array",
"int64_t": "godot::PackedInt64Array",
"float": "godot::PackedFloat32Array",
"double": "godot::PackedFloat64Array",
"godot::Vector2": "godot::PackedVector2Array",
"godot::Vector3": "godot::PackedVector3Array",
"godot::Color": "godot::PackedColorArray",
"godot::Vector4": "godot::PackedVector4Array",
}
godot_array_types = [
"StringName",
"NodePath",
"PackedByteArray",
"PackedInt32Array",
"PackedInt64Array",
"PackedFloat32Array",
"PackedFloat64Array",
"PackedStringArray",
"PackedVector2Array",
"PackedVector3Array",
"PackedColorArray",
"PackedVector4Array",
"String",
]
class DefineContext:
default_defines: set = []
active_defines: set = []
if_blocks: list = []
def __init__(self, env: SConsEnvironment):
# use only defines, not macros
self.default_defines = [
d for d in env["CPPDEFINES"] if (re.search(r"\w+", d)[0] == d if type(d) is not tuple else False)
]
self.active_defines = set(self.default_defines)
trace_print(f"Global defines: {self.default_defines}")
def reset(self):
self.active_defines = set(self.default_defines)
if_blocks: list = []
def parse_line(self, line: str) -> bool:
stripped_line: str = line.strip()
if stripped_line.startswith("#define "):
def_line = line[len("#define ") :]
split = def_line.split(" ")
if def_line == re.search(r"\w+", split[0])[0]:
trace_print(f"\tFound define: {def_line}")
self.active_defines.add(def_line)
return False
# TODO: support #if
# TODO: support #elif
if stripped_line.startswith("#ifdef ") or stripped_line.startswith("#ifndef "):
is_inverted = stripped_line.startswith("#ifndef ")
if_name = stripped_line[: stripped_line.find(" ")]
define_name = stripped_line[stripped_line.find(" ") + 1 :]
is_defined = define_name in self.active_defines
self.if_blocks.append(not is_defined if is_inverted else is_defined)
if self.if_blocks[-1]:
trace_print(
f"\tFound {if_name} with '{define_name}', which is {'active' if is_defined else 'inactive'}: next lines will be parsed."
)
else:
trace_print(
f"\tFound {if_name} with '{define_name}', which is {'active' if is_defined else 'inactive'}: next lines will be ignored."
)
return False
if stripped_line.startswith("#if "):
self.if_blocks.append("ignored")
trace_print("\tFound #if. Ignoring...")
return False
if stripped_line.startswith("#else"):
if self.if_blocks[-1] == "ignored":
return False
self.if_blocks[-1] = not self.if_blocks[-1]
trace_print(
f"\tFound #else: inverting the last if block: {'next lines will be parsed.' if self.if_blocks[-1] else 'next lines will be ignored.'}"
)
return False
if stripped_line.startswith("#endif"):
self.if_blocks.pop()
trace_print(f"\tFound #endif: removing the last if block.")
if len(self.if_blocks):
if self.if_blocks[-1] != "ignored":
trace_print(
"\t\tNext lines will be parsed." if self.if_blocks[-1] else "\t\tNext lines will be ignored."
)
return False
if len(self.if_blocks):
val = self.if_blocks[-1]
if val == "ignored":
return True
return val
return True
def line(arr: list, txt: str = "", indent: int = 0):
arr.append("\t" * indent + txt)
def insert_lines_at_mark(lines: list, mark: str, insert_lines: list):
insert_index = -1
for idx, line in enumerate(lines):
if line.endswith(mark):
insert_index = idx
break
lines.pop(insert_index)
lines[insert_index:insert_index] = insert_lines
def split_text_into_lines(text) -> list:
return text.replace("\r\n", "\n").replace("\r", "\n").split("\n")
def is_need_trivial_c_conversion(t: str):
prefix = ""
type = t
if type.startswith("const"):
prefix = "const "
type = type.removeprefix("const ").strip()
if type in basic_to_trivial_types:
return (True, basic_to_trivial_types[type], prefix)
return (False, t, "")
def get_trivial_c_type(t: str) -> str:
(res, type, prefix) = is_need_trivial_c_conversion(t)
return prefix + type
def get_cpp_types_static_asserts() -> list:
asserts = []
for t in basic_godot_types:
if t not in disallowed_godot_types:
(res, type, prefix) = is_need_trivial_c_conversion(t)
if res:
asserts.append(f"// Original type - {t}")
asserts.append(f"static_assert(std::is_standard_layout_v<{prefix + type}>);")
asserts.append(f"static_assert(std::is_trivially_copyable_v<{prefix + type}>);")
asserts.append("")
return asserts
####################################
####################################
## api.json
####################################
####################################
def get_api_functions(env: SConsEnvironment, headers: list) -> dict:
classes = {}
def_ctx: DefineContext = DefineContext(env)
for header in headers:
print(f"Parsing {header} ...")
lines = split_text_into_lines(lib_utils.read_all_text(header, True))
lines = [line.strip() for line in lines]
def_ctx.reset()
functions = []
enums = {}
current_class = ""
is_singleton = False
is_refcounted = False
for idx, line in enumerate(lines):
if not def_ctx.parse_line(line):
trace_print(f"\t\tSkipping: {idx + 1}: {line}")
continue
def get_doc_lines(start_idx: int):
found_docs = []
if lines[start_idx - 1] == "*/":
doc_idx = start_idx - 1
while lines[doc_idx] != "/**" and doc_idx >= 0:
doc_idx -= 1
doc_idx += 1 # ignore /**
code_blocks = 0
for d_line, line in enumerate(lines[doc_idx : start_idx - 1]):
l: str = line
code_blocks += l.count("```")
if l.startswith("* "):
l = l.removeprefix("* ")
elif len(l) > 1 and l.startswith("*"):
raise Exception(
f'{header}:{doc_idx + d_line + 1}: Incorrect formatting of doxygen comment. The line must begin with "* "'
)
else:
l = l.removeprefix("*")
# replaces images with placeholder
l = re.sub(r"(\!\[.*\]\(.*\))", "[THERE WAS AN IMAGE]", l)
if code_blocks % 2 == 0:
l = l.strip()
else:
l = l.rstrip()
found_docs.append(l)
return found_docs
def search_for_docs_override(start_idx: int):
new_docs = []
cur_idx = start_idx - 1
while (lines[cur_idx].startswith("//") or len(lines[cur_idx]) == 0) and cur_idx >= 0:
match = re.search(r"\#docs_func (\w*)", lines[cur_idx])
if match:
override_func = match.group(1)
for o_idx, l in enumerate(lines):
o_match = re.search(f" {override_func}\\(", l)
if o_match:
new_docs = get_doc_lines(o_idx)
break
break
cur_idx -= 1
return new_docs
docs = get_doc_lines(idx)
class_prefixes = ["NAPI_CLASS_REF class ", "NAPI_CLASS_SINGLETON class "]
class_prefix = ""
for p in class_prefixes:
if line.startswith(p):
class_prefix = p
break
if len(class_prefix):
class_type = "regular"
if line.startswith("NAPI_CLASS_SINGLETON "):
is_singleton = True
class_type = "singleton"
elif line.startswith("NAPI_CLASS_REF "):
is_refcounted = True
class_type = "refcounted"
current_class = re.search(r"\w+", line[len(class_prefix) :])[0].strip()
functions = []
enums = {}
classes[current_class] = {"enums": enums, "functions": functions, "type": class_type, "docs": docs}
if is_singleton:
print(f" Found Singleton {current_class}")
elif is_refcounted:
print(f" Found RefCounted {current_class}")
continue
"""
Enum fields:
"type": str
"values": dict
"""
if line.startswith("NAPI_ENUM enum "):
split = line[len("NAPI_ENUM enum ") : line.find("{")].split(":")
name = split[0].strip()
if len(split) != 2:
raise Exception(f'Enum "{name}" must have an explicit type of constants.')
e_type = split[1].strip()
if e_type not in allowed_enum_types:
raise Exception(f'Enum must be one of these types: {allowed_enum_types}, but "{e_type}" was found.')
dev_print(f"\tFound Enum {name} of type {e_type}")
enum_lines = [line[line.rfind("{") + 1 :]]
eidx = idx + 1
while True:
el = lines[eidx]
bpos = el.rfind("}")
if bpos != -1:
el = el[:bpos]
enum_lines.append(el)
if bpos != -1:
break
eidx += 1
# remove comments and newlines
enum_lines = [
(l[: l.rfind("//")] if l.rfind("//") != -1 else l).strip() for l in enum_lines if len(l.strip())
]
enum_lines = "".join(enum_lines)
# split by comma and remove empty
enum_lines = [l.strip() for l in enum_lines.split(",") if len(l.strip())]
dev_print("\t\tEnum lines: " + str(enum_lines))
values = {}
last_val = -1
for e in enum_lines:
split = e.split("=")
key = split[0].strip()
last_val += 1
value = last_val
if len(split) == 2:
value = split[1].strip()
if value.isdigit():
last_val = int(value)
values[key] = str(value)
enums[name] = {"type": e_type, "values": values}
continue
"""
Function fields:
"name": str - original name
"c_name": str - C API name
"docs": list
"args": list
"return": dict
"self_return": bool
"arg_arrays" (opt): list
"private" (opt): str
"""
if line.startswith("NAPI "):
def check_array_usage(type_to_check: str, is_return: bool = False):
for arr_t in godot_array_types:
if arr_t in type_to_check:
if not is_return:
raise Exception(
f"Arguments with array types ({arr_t}) must be exposed using a pointer and size, "
+ 'e.g. "const godot::Vector3 *lines_data, const uint64_t lines_size" (suffixes "_data" and "_size" are required).'
)
else:
raise Exception(f"Returning array types ({arr_t}) is not supported.")
def check_argument_types(arg_dict: dict):
for basic_t in basic_godot_types:
words = re.findall(r"\w+", arg_dict["type"])
if basic_t in arg_dict["type"]:
if basic_t in disallowed_godot_types:
raise Exception(
f'Use of the "{basic_t}" type in the Native API is currently disallowed.'
)
else:
arg_dict["basic_godot_type"] = basic_t
elif len(words) and basic_t.replace("godot::", "") == words[-1]:
if "name" in arg_dict:
msg = f'Type "{basic_t}" is incorrectly specified for argument "{arg_dict["name"]}": "{arg_dict["type"]}".'
else:
msg = f'Type "{basic_t}" is incorrectly specified for the return value "{arg_dict["type"]}".'
raise Exception(msg + ' Godot types must explicitly specify the namespace "godot::".')
"""
Return fields:
"type": str
"c_type": str
"basic_godot_type": str
"ref_class" (opt) or "object_class" (opt): str
"enum_type" (opt): dict
"""
if len(docs) == 0:
docs = search_for_docs_override(idx)
func_name_match = re.search(r"\b(\w+)\s*\(", line)
func_name = func_name_match.group(1).strip()
ret_type = line[: line.index(func_name)].replace("NAPI ", "").strip()
dev_print(f"\tFound method {func_name}")
is_self_return = False
if is_refcounted:
if ret_type == "NSELF_RETURN" or ret_type == f"Ref<{current_class}>":
ret_type = "void"
is_self_return = True
c_ret_type = ret_type
ret_ref_class = ""
ret_type_match = re.search(r"Ref\<(godot\:\:\w*)\>", ret_type)
if ret_type_match:
c_ret_type = "const uint64_t"
ret_ref_class = ret_type_match.group(1).strip()
ret_dict = {
"type": ret_type,
"c_type": c_ret_type,
}
check_array_usage(ret_type, True)
check_argument_types(ret_dict)
if len(ret_ref_class):
ret_dict["ref_class"] = ret_ref_class
elif (
ret_type != "void *"
and "basic_godot_type" not in ret_dict
and ret_type.endswith("*")
and "godot::" in ret_type
):
ret_dict["type"] = "const uint64_t"
ret_dict["c_type"] = "const uint64_t"
ret_dict["object_class"] = (
ret_type.replace("const ", "").replace("class ", "").replace("*", "").strip()
)
dev_print("\t\tFound Godot's Object* type in return: " + str(ret_type))
# get all args even in one-line functions
cbrace_end = line.rfind("{")
args_str = line[
line.find("(") + 1 : line.rfind(")", 0, cbrace_end if cbrace_end != -1 else len(line) - 1)
]
args = []
if not is_singleton:
args.append("void *inst_ptr")
if len(args_str):
# args = [a.strip() for a in args]
tmp_args_str = args_str
while len(tmp_args_str):
found_comma = False
nesting = 0
for idx, c in enumerate(tmp_args_str):
if c in ["(", "[", "{", "<"]:
nesting += 1
if c in [")", "]", "}", ">"]:
nesting -= 1
if nesting == 0 and c == ",":
args.append(tmp_args_str[:idx].strip())
tmp_args_str = tmp_args_str[idx + 1 :]
found_comma = True
break
if nesting < 0:
raise Exception("There are more closing brackets than opening ones:\n" + tmp_args_str)
if nesting > 0:
raise Exception("There are more opening brackets than closing ones:\n" + tmp_args_str)
if not found_comma:
args.append(tmp_args_str)
break
"""
Arg fields:
"name": str
"type": str
"c_type": str
"default" (opt): str
"basic_godot_type": str
"ref_class" (opt) or "object_class" (opt): str
"enum_type" (opt): dict
"""
args_dict = []
for aidx, a in enumerate(args):
arg_name_match = re.search(r"\b(\w+)\s*=", a)
if arg_name_match:
new_arg = {
"name": arg_name_match.group(1).strip(),
"type": a[: a.index(arg_name_match.group(1))].strip(),
"default": a[a.find("=") + 1 :].strip(),
}
tmp_default = new_arg["default"]
if tmp_default.startswith("Colors::"):
new_arg["default"] = default_colors_map[tmp_default]
new_arg["c_type"] = new_arg["type"].replace("&", "").strip()
else:
arg_name_match = re.search(r"\b(\w+)$", a)
if arg_name_match:
new_arg = {
"name": arg_name_match.group(1).strip(),
"type": a[: a.index(arg_name_match.group(1))].strip(),
}
else:
new_arg = {
"name": f"arg{aidx}",
"type": a.strip(),
}
new_arg["c_type"] = new_arg["type"].replace("&", "").strip()
# Search for PackedArray
check_array_usage(new_arg["type"])
# Search for basic Variant types
check_argument_types(new_arg)
tmp_type = new_arg["type"]
ref_type_match = re.search(r"Ref\<(godot\:\:\w*)\>", tmp_type)
if ref_type_match:
new_arg["type"] = tmp_type
new_arg["c_type"] = "const uint64_t"
new_arg["ref_class"] = ref_type_match.group(1).strip()
dev_print("\t\tFound Godot's Ref type: " + tmp_type)
elif (
new_arg["name"] != "inst_ptr"
and tmp_type != "void *"
and "basic_godot_type" not in new_arg
and tmp_type.endswith("*")
and "godot::" in tmp_type
):
new_arg["type"] = "const uint64_t"
new_arg["c_type"] = "const uint64_t"
new_arg["object_class"] = (
tmp_type.replace("const ", "").replace("class ", "").replace("*", "").strip()
)
dev_print("\t\tFound Godot's Object* type: " + tmp_type)
args_dict.append(new_arg)
fun_dict = {
"name": func_name,
"c_name": f"{current_class}_{func_name}",
"docs": docs,
"args": args_dict,
"return": ret_dict,
"self_return": is_self_return,
}
"""
Array fields:
"data_name": str
"data_idx": int
"size_name" (opt): str
"size_idx" (opt): int
"array_type": str
"is_const": bool
"not_godot_array_type" (opt): bool
"""
found_arrays = []
for idx in range(len(args_dict)):
a1 = args_dict[idx]
const_array = a1["type"].startswith("const")
words1 = re.findall(r"\w+", a1["type"])
array_type = None
not_godot_array_type = False
if a1.get("basic_godot_type", "") in basic_types_to_arrays:
array_type = basic_types_to_arrays[a1["basic_godot_type"]]
elif words1[-1] in basic_types_to_arrays:
array_type = basic_types_to_arrays[words1[-1]]
else:
# for array without native godot's type, e.g. godot::Plane *
if "basic_godot_type" in a1 and a1["c_type"].endswith("*"):
array_type = a1["basic_godot_type"]
not_godot_array_type = True
if (
(
(a1["name"].endswith("_data") and idx + 1 < len(args_dict))
or (a1["name"].endswith("_string"))
)
and "ref_class" not in a1
and "object_class" not in a1
and "enum_type" not in a1
and a1["type"].endswith("*")
and array_type
):
if a1["name"].endswith("_data"):
a2 = args_dict[idx + 1]
if a2["name"].endswith("_size"):
if not a2["name"].startswith(a1["name"].removesuffix("_data")):
print(
f'WARN: Argument name for array size "{a2["name"]}" does not match pointer name "{a1["name"]}".'
)
words2 = re.findall(r"\w+", a2["type"])
size_types = ["uint64_t", "int64_t"]
if words2[-1] in size_types:
arr_dict = {
"data_name": a1["name"],
"data_idx": idx,
"size_name": a2["name"],
"size_idx": idx + 1,
"array_type": array_type,
"is_const": const_array,
}
if not_godot_array_type:
arr_dict["not_godot_array_type"] = not_godot_array_type
found_arrays.append(arr_dict)
dev_print(
"\t\tArguments suitable for the PackedArray wrapper have been found: "
+ f'{idx} - {a1["name"]} and {idx + 1} - {a2["name"]}'
)
if not func_name.endswith("_c"):
raise Exception('Function that use C arrays should have name ending in "_c".')
else:
raise Exception(
"Arguments suitable for the PackedArray wrapper have been found, "
+ f'but the "{a2["type"]} {a2["name"]}" argument type must be one of: {size_types}'
)
else:
arr_dict = {
"data_name": a1["name"],
"data_idx": idx,
"array_type": array_type,
"is_const": const_array,
}
found_arrays.append(arr_dict)
dev_print(
f'\t\tArguments suitable for the String wrapper have been found: {idx} - {a1["name"]}'
)
if not func_name.endswith("_c"):
raise Exception('Function that use C strings should have name ending in "_c".')
if len(found_arrays):
fun_dict["arg_arrays"] = found_arrays
# Name of the generated C API function
functions.append(fun_dict)
dev_print(f"\t Parsing of method {func_name} completed")
###
print("Mark all Enum's in args and return types...")
"""
Enum arg fields:
"class": str
"name": str
"type": str
"""
exposed_enums = {}
exposed_enums_only_names = []
exposed_enums_only_names_map = {}
for cls_name in classes:
cls = classes[cls_name]
for e_name in cls["enums"]:
e = cls["enums"][e_name]
new_dict = {"class": cls_name, "name": e_name, "type": e["type"]}
name = f"{cls_name}::{e_name}"
exposed_enums[name] = new_dict
exposed_enums_only_names.append(e_name)
if e_name in exposed_enums_only_names_map:
raise Exception(
f'The enum "{e_name}" already exists in another class "{exposed_enums_only_names_map[e_name]}".'
)
exposed_enums_only_names_map[e_name] = name
for cls_name in classes:
cls = classes[cls_name]
for f in cls["functions"]:
def check_type_name(type: str):
for e in exposed_enums_only_names:
if e in type:
if exposed_enums_only_names_map[e] not in type:
print(
f'ERROR: "{exposed_enums_only_names_map[e]}" is named incorrectly in the "{f["name"]}" function.'
+ f' "{e}" should be called "{exposed_enums_only_names_map[e]}".'
)
return None
else:
return exposed_enums_only_names_map[e]
return None
e_name = check_type_name(f["return"]["type"])
if e_name:
f["return"]["enum_type"] = exposed_enums[e_name]
for a in f["args"]:
e_name = check_type_name(a["type"])
if e_name:
a["enum_type"] = exposed_enums[e_name]
###
print("Search for all possible properties...")
"""
Properties fields:
"name": str
"return": dict
"set": str
"get": str
"""
for cls_name in classes:
cls = classes[cls_name]
properties = []
cls["properties"] = properties
for f in cls["functions"]:
func_name = f["name"]
if func_name.startswith("set_") and (
len(f["args"]) == 1 or (len(f["args"]) == 2 and f["args"][0]["name"] == "inst_ptr")
): # 1 arg or 2 args for instance
prop_name = func_name.removeprefix("set_")
for f2 in cls["functions"]:
func_name2 = f2["name"]
if (func_name2.startswith("get_") or func_name2.startswith("is_")) and (
len(f2["args"]) == 0 or (len(f2["args"]) == 1 and f2["args"][0]["name"] == "inst_ptr")
):
prop_name2 = func_name2
if prop_name2.startswith("get_"):
prop_name2 = prop_name2.removeprefix("get_")
elif prop_name2.startswith("is_"):
prop_name2 = prop_name2.removeprefix("is_")
if prop_name == prop_name2:
dev_print(f'\tFound Property in "{cls_name}" named "{prop_name}"')
properties.append(
{
"name": prop_name,
"return": f2["return"],
"set": func_name,
"get": func_name2,
}
)
return classes
####################################
####################################
## c_api.gen.cpp
####################################
####################################
def generate_native_api(
env: SConsEnvironment,
header_files: list,
c_api_template: str,
out_folder: str,
src_out: list,
additional_include_classes: list = [],
) -> dict:
classes = get_api_functions(env, header_files)
new_funcs = []
new_class_regs = []
new_func_regs = []
new_ref_clears = []
extern_c_dbg = 'extern "C" '
extern_c_dbg = ""
for cls in classes:
print(f"Genearating DD3D C_API constructors for {cls}...")
is_refcounted = classes[cls]["type"] == "refcounted"
if not is_refcounted:
continue
line(new_funcs, f"struct {cls}_NAPIWrapper {{")
line(new_funcs, f"Ref<{cls}> ref;", 1)
line(new_funcs, "};")
line(new_funcs, "")
line(new_funcs, f"static std::unordered_set<{cls}_NAPIWrapper*> {cls}_NAPIWrapper_storage;")
line(
new_funcs,
f"static std::recursive_mutex {cls}_NAPIWrapper_storage_datalock;",
)
line(new_funcs, "")
line(new_funcs, f"{extern_c_dbg}static void* {cls}_create() {{")
line(new_funcs, "ZoneScoped;", 1)
line(new_funcs, f"auto* inst_ptr = new {cls}_NAPIWrapper{{Ref<{cls}>(memnew({cls}))}};", 1)
line(new_funcs, f"std::lock_guard<std::recursive_mutex> __guard({cls}_NAPIWrapper_storage_datalock);", 1)
line(new_funcs, f"{cls}_NAPIWrapper_storage.insert(inst_ptr);", 1)
line(new_funcs, "return inst_ptr;", 1)
line(new_funcs, "};")
line(new_funcs, "")
line(new_funcs, f"{extern_c_dbg}static void* {cls}_create_nullptr() {{")
line(new_funcs, "ZoneScoped;", 1)
line(new_funcs, f"auto* inst_ptr = new {cls}_NAPIWrapper{{}};", 1)
line(new_funcs, f"std::lock_guard<std::recursive_mutex> __guard({cls}_NAPIWrapper_storage_datalock);", 1)
line(new_funcs, f"{cls}_NAPIWrapper_storage.insert(inst_ptr);", 1)
line(new_funcs, "return inst_ptr;", 1)
line(new_funcs, "};")
line(new_funcs, "")
line(new_funcs, f"static void* {cls}_create_from_ref(Ref<{cls}> ref) {{")
line(new_funcs, "ZoneScoped;", 1)
line(new_funcs, f"auto* inst_ptr = new {cls}_NAPIWrapper{{ref}};", 1)
line(new_funcs, f"std::lock_guard<std::recursive_mutex> __guard({cls}_NAPIWrapper_storage_datalock);", 1)
line(new_funcs, f"{cls}_NAPIWrapper_storage.insert(inst_ptr);", 1)
line(new_funcs, "return inst_ptr;", 1)
line(new_funcs, "};")
line(new_funcs, "")
line(new_funcs, f"{extern_c_dbg}static void {cls}_destroy(void *inst_ptr) {{")
line(new_funcs, "ZoneScoped;", 1)
line(new_funcs, f"auto obj = static_cast<{cls}_NAPIWrapper*>(inst_ptr);", 1)
line(new_funcs, f"std::lock_guard<std::recursive_mutex> __guard({cls}_NAPIWrapper_storage_datalock);", 1)
line(
new_funcs,
f"if (const auto it = {cls}_NAPIWrapper_storage.find(obj); it != {cls}_NAPIWrapper_storage.end()){{",
1,
)
line(new_funcs, f"{cls}_NAPIWrapper_storage.erase(it);", 2)
line(new_funcs, f"delete obj;", 2)
line(new_funcs, "};", 1)
line(new_funcs, "};")
line(new_funcs)
line(new_class_regs, f"ADD_CLASS({cls});", 2)
line(new_func_regs, f"ADD_FUNC({cls}_create);", 2)
line(new_func_regs, f"ADD_FUNC({cls}_create_nullptr);", 2)
line(new_func_regs, f"ADD_FUNC({cls}_destroy);", 2)
line(new_ref_clears, f"CLEAR_REFS({cls}, {cls}_NAPIWrapper_storage);", 1)
for cls in classes:
print(f"Genearating DD3D C_API for {cls}...")
class_type = classes[cls]["type"]
is_singleton = class_type == "singleton"
is_refcounted = class_type == "refcounted"
functions = classes[cls]["functions"]
def get_ref_class_name(ret_type: str):
if ret_type.startswith("Ref<"):
return ret_type[4:-1]
return ret_type
def is_ref_in_api(ret_type: str):
if ret_type.startswith("Ref<"):
if get_ref_class_name(ret_type) in classes:
return True
return False
for func in functions:
def process_ret_type(ret: dict):
type = get_trivial_c_type(ret["c_type"])
if "enum_type" in ret:
e = ret["enum_type"]
return f"{e['type']} /*{e['class']}::{e['name']}*/"
return type
def process_ret_calls(line: str, ret: dict):
if "ref_class" in ret or "object_class" in ret:
return f"{line}->get_instance_id()"
if "enum_type" in ret:
e = ret["enum_type"]
return f"static_cast<{e['type']} /*{e['class']}::{e['name']}*/>({line})"
return line
def process_arg_decl(arg: dict):
type = get_trivial_c_type(arg["c_type"])
name = arg["name"]
if is_ref_in_api(type):
return f"void *{name}"
if "ref_class" in arg:
return f"{type} /*{arg['ref_class']}*/ {name}"
if "object_class" in arg:
return f"{type} /*{arg['object_class']}*/ {name}"
if "enum_type" in arg:
e = arg["enum_type"]
return f"{e['type']} /*{e['class']}::{e['name']}*/ {name}"
return f"{type} {name}"
def process_arg_calls(arg: dict):
type = arg["type"]
name = arg["name"]
if is_ref_in_api(type):
return f"static_cast<{get_ref_class_name(type)}_NAPIWrapper *>({name})->ref"
if "ref_class" in arg:
return f"godot::Ref<{arg['ref_class']}>(godot::Object::cast_to<{arg['ref_class']}>(godot::ObjectDB::get_instance({name})))"
if "object_class" in arg: