binding_generator.py 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708
  1. #!/usr/bin/env python
  2. import json
  3. import re
  4. import shutil
  5. from pathlib import Path
  6. def print_file_list(api_filepath, output_dir, headers=False, sources=False):
  7. api = {}
  8. end = ";"
  9. with open(api_filepath) as api_file:
  10. api = json.load(api_file)
  11. include_gen_folder = Path(output_dir) / "gen" / "include" / "godot_cpp"
  12. source_gen_folder = Path(output_dir) / "gen" / "src"
  13. for builtin_class in api["builtin_classes"]:
  14. if is_pod_type(builtin_class["name"]):
  15. continue
  16. header_filename = include_gen_folder / "variant" / (camel_to_snake(builtin_class["name"]) + ".hpp")
  17. source_filename = source_gen_folder / "variant" / (camel_to_snake(builtin_class["name"]) + ".cpp")
  18. if headers:
  19. print(str(header_filename.as_posix()), end=end)
  20. if sources:
  21. print(str(source_filename.as_posix()), end=end)
  22. for engine_class in api["classes"]:
  23. # TODO: Properly setup this singleton since it conflicts with ClassDB in the bindings.
  24. if engine_class["name"] == "ClassDB":
  25. continue
  26. header_filename = include_gen_folder / "classes" / (camel_to_snake(engine_class["name"]) + ".hpp")
  27. source_filename = source_gen_folder / "classes" / (camel_to_snake(engine_class["name"]) + ".cpp")
  28. if headers:
  29. print(str(header_filename.as_posix()), end=end)
  30. if sources:
  31. print(str(source_filename.as_posix()), end=end)
  32. utility_functions_header_path = include_gen_folder / "variant" / "utility_functions.hpp"
  33. utility_functions_source_path = source_gen_folder / "variant" / "utility_functions.cpp"
  34. global_constants_header_path = include_gen_folder / "classes" / "global_constants.hpp"
  35. if headers:
  36. print(str(utility_functions_header_path.as_posix()), end=end)
  37. print(str(global_constants_header_path.as_posix()), end=end)
  38. if sources:
  39. print(str(utility_functions_source_path.as_posix()), end=end)
  40. def generate_bindings(api_filepath, use_template_get_node, output_dir="."):
  41. api = None
  42. target_dir = Path(output_dir) / "gen"
  43. with open(api_filepath) as api_file:
  44. api = json.load(api_file)
  45. shutil.rmtree(target_dir, ignore_errors=True)
  46. target_dir.mkdir(parents=True)
  47. generate_global_constants(api, target_dir)
  48. generate_builtin_bindings(api, target_dir, "float_64")
  49. generate_engine_classes_bindings(api, target_dir, use_template_get_node)
  50. generate_utility_functions(api, target_dir)
  51. builtin_classes = []
  52. # Key is class name, value is boolean where True means the class is refcounted.
  53. engine_classes = {}
  54. singletons = []
  55. def generate_builtin_bindings(api, output_dir, build_config):
  56. global builtin_classes
  57. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "variant"
  58. source_gen_folder = Path(output_dir) / "src" / "variant"
  59. include_gen_folder.mkdir(parents=True, exist_ok=True)
  60. source_gen_folder.mkdir(parents=True, exist_ok=True)
  61. # Store types beforehand.
  62. for builtin_api in api["builtin_classes"]:
  63. if is_pod_type(builtin_api["name"]):
  64. continue
  65. builtin_classes.append(builtin_api["name"])
  66. builtin_sizes = {}
  67. for size_list in api["builtin_class_sizes"]:
  68. if size_list["build_configuration"] == build_config:
  69. for size in size_list["sizes"]:
  70. builtin_sizes[size["name"]] = size["size"]
  71. break
  72. # Create a file for Variant size, since that class isn't generated.
  73. variant_size_filename = include_gen_folder / "variant_size.hpp"
  74. with variant_size_filename.open("+w") as variant_size_file:
  75. variant_size_source = []
  76. add_header("variant_size.hpp", variant_size_source)
  77. header_guard = "GODOT_CPP_VARIANT_SIZE_HPP"
  78. variant_size_source.append(f"#ifndef {header_guard}")
  79. variant_size_source.append(f"#define {header_guard}")
  80. variant_size_source.append(f'#define GODOT_CPP_VARIANT_SIZE {builtin_sizes["Variant"]}')
  81. variant_size_source.append(f"#endif // ! {header_guard}")
  82. variant_size_file.write("\n".join(variant_size_source))
  83. for builtin_api in api["builtin_classes"]:
  84. if is_pod_type(builtin_api["name"]):
  85. continue
  86. size = builtin_sizes[builtin_api["name"]]
  87. header_filename = include_gen_folder / (camel_to_snake(builtin_api["name"]) + ".hpp")
  88. source_filename = source_gen_folder / (camel_to_snake(builtin_api["name"]) + ".cpp")
  89. # Check used classes for header include
  90. used_classes = set()
  91. fully_used_classes = set()
  92. class_name = builtin_api["name"]
  93. if "constructors" in builtin_api:
  94. for constructor in builtin_api["constructors"]:
  95. if "arguments" in constructor:
  96. for argument in constructor["arguments"]:
  97. if is_included(argument["type"], class_name):
  98. if "default_value" in argument and argument["type"] != "Variant":
  99. fully_used_classes.add(argument["type"])
  100. else:
  101. used_classes.add(argument["type"])
  102. if "methods" in builtin_api:
  103. for method in builtin_api["methods"]:
  104. if "arguments" in method:
  105. for argument in method["arguments"]:
  106. if is_included(argument["type"], class_name):
  107. if "default_value" in argument and argument["type"] != "Variant":
  108. fully_used_classes.add(argument["type"])
  109. else:
  110. used_classes.add(argument["type"])
  111. if "return_type" in method:
  112. if is_included(method["return_type"], class_name):
  113. used_classes.add(method["return_type"])
  114. if "members" in builtin_api:
  115. for member in builtin_api["members"]:
  116. if is_included(member["type"], class_name):
  117. used_classes.add(member["type"])
  118. if "indexing_return_type" in builtin_api:
  119. if is_included(builtin_api["indexing_return_type"], class_name):
  120. used_classes.add(builtin_api["indexing_return_type"])
  121. if "operators" in builtin_api:
  122. for operator in builtin_api["operators"]:
  123. if "right_type" in operator:
  124. if is_included(operator["right_type"], class_name):
  125. used_classes.add(operator["right_type"])
  126. for type_name in fully_used_classes:
  127. if type_name in used_classes:
  128. used_classes.remove(type_name)
  129. with header_filename.open("w+") as header_file:
  130. header_file.write(generate_builtin_class_header(builtin_api, size, used_classes, fully_used_classes))
  131. with source_filename.open("w+") as source_file:
  132. source_file.write(generate_builtin_class_source(builtin_api, size, used_classes, fully_used_classes))
  133. # Create a header with all builtin types for convenience.
  134. builtin_header_filename = include_gen_folder / "builtin_types.hpp"
  135. with builtin_header_filename.open("w+") as builtin_header_file:
  136. builtin_header = []
  137. add_header("builtin_types.hpp", builtin_header)
  138. builtin_header.append("#ifndef GODOT_CPP_BUILTIN_TYPES_HPP")
  139. builtin_header.append("#define GODOT_CPP_BUILTIN_TYPES_HPP")
  140. builtin_header.append("")
  141. for builtin in builtin_classes:
  142. builtin_header.append(f"#include <godot_cpp/variant/{camel_to_snake(builtin)}.hpp>")
  143. builtin_header.append("")
  144. builtin_header.append("#endif // ! GODOT_CPP_BUILTIN_TYPES_HPP")
  145. builtin_header_file.write("\n".join(builtin_header))
  146. def generate_builtin_class_header(builtin_api, size, used_classes, fully_used_classes):
  147. result = []
  148. class_name = builtin_api["name"]
  149. snake_class_name = camel_to_snake(class_name).upper()
  150. header_guard = f"GODOT_CPP_{snake_class_name}_HPP"
  151. add_header(f"{snake_class_name.lower()}.hpp", result)
  152. result.append(f"#ifndef {header_guard}")
  153. result.append(f"#define {header_guard}")
  154. result.append("")
  155. result.append("#include <godot_cpp/core/defs.hpp>")
  156. result.append("")
  157. # Special cases.
  158. if class_name == "String":
  159. result.append("#include <godot_cpp/variant/char_string.hpp>")
  160. for include in fully_used_classes:
  161. result.append(f"#include <godot_cpp/{get_include_path(include)}>")
  162. if len(fully_used_classes) > 0:
  163. result.append("")
  164. result.append(f"#include <godot/gdnative_interface.h>")
  165. result.append("")
  166. result.append("namespace godot {")
  167. result.append("")
  168. for type_name in used_classes:
  169. result.append(f"class {type_name};")
  170. if len(used_classes) > 0:
  171. result.append("")
  172. result.append(f"class {class_name} {{")
  173. result.append(f"\tstatic constexpr size_t {snake_class_name}_SIZE = {size};")
  174. result.append(f"\tuint8_t opaque[{snake_class_name}_SIZE] {{ 0 }};")
  175. result.append(
  176. f"\t_FORCE_INLINE_ GDNativeTypePtr ptr() const {{ return const_cast<uint8_t (*)[{snake_class_name}_SIZE]>(&opaque); }}"
  177. )
  178. result.append("")
  179. result.append("\tfriend class Variant;")
  180. result.append("")
  181. result.append("\tstatic struct _MethodBindings {")
  182. if "constructors" in builtin_api:
  183. for constructor in builtin_api["constructors"]:
  184. result.append(f'\t\tGDNativePtrConstructor constructor_{constructor["index"]};')
  185. if builtin_api["has_destructor"]:
  186. result.append("\t\tGDNativePtrDestructor destructor;")
  187. if "methods" in builtin_api:
  188. for method in builtin_api["methods"]:
  189. result.append(f'\t\tGDNativePtrBuiltInMethod method_{method["name"]};')
  190. if "members" in builtin_api:
  191. for member in builtin_api["members"]:
  192. result.append(f'\t\tGDNativePtrSetter member_{member["name"]}_setter;')
  193. result.append(f'\t\tGDNativePtrGetter member_{member["name"]}_getter;')
  194. if "indexing_return_type" in builtin_api:
  195. result.append(f"\t\tGDNativePtrIndexedSetter indexed_setter;")
  196. result.append(f"\t\tGDNativePtrIndexedGetter indexed_getter;")
  197. if "is_keyed" in builtin_api and builtin_api["is_keyed"]:
  198. result.append(f"\t\tGDNativePtrKeyedSetter keyed_setter;")
  199. result.append(f"\t\tGDNativePtrKeyedGetter keyed_getter;")
  200. result.append(f"\t\tGDNativePtrKeyedChecker keyed_checker;")
  201. if "operators" in builtin_api:
  202. for operator in builtin_api["operators"]:
  203. if "right_type" in operator:
  204. result.append(
  205. f'\t\tGDNativePtrOperatorEvaluator operator_{get_operator_id_name(operator["name"])}_{operator["right_type"]};'
  206. )
  207. else:
  208. result.append(f'\t\tGDNativePtrOperatorEvaluator operator_{get_operator_id_name(operator["name"])};')
  209. result.append("\t} _method_bindings;")
  210. result.append("")
  211. result.append("\tstatic void init_bindings();")
  212. result.append("")
  213. result.append("public:")
  214. copy_constructor_index = -1
  215. if "constructors" in builtin_api:
  216. for constructor in builtin_api["constructors"]:
  217. method_signature = f"\t{class_name}("
  218. if "arguments" in constructor:
  219. method_signature += make_function_parameters(
  220. constructor["arguments"], include_default=True, for_builtin=True
  221. )
  222. if len(constructor["arguments"]) == 1 and constructor["arguments"][0]["type"] == class_name:
  223. copy_constructor_index = constructor["index"]
  224. method_signature += ");"
  225. result.append(method_signature)
  226. # Move constructor.
  227. result.append(f'\t{class_name}({class_name} &&other);')
  228. # Special cases.
  229. if class_name == "String" or class_name == "StringName" or class_name == "NodePath":
  230. result.append(f"\t{class_name}(const char *from);")
  231. result.append(f"\t{class_name}(const wchar_t *from);")
  232. result.append(f"\t{class_name}(const char16_t *from);")
  233. result.append(f"\t{class_name}(const char32_t *from);")
  234. if "constants" in builtin_api:
  235. axis_constants_count = 0
  236. for constant in builtin_api["constants"]:
  237. # Special case: Vector3.Axis is the only enum in the bindings.
  238. # It's technically not supported by Variant but works for direct access.
  239. if class_name == "Vector3" and constant["name"].startswith("AXIS"):
  240. if axis_constants_count == 0:
  241. result.append("\tenum Axis {")
  242. result.append(f'\t\t{constant["name"]} = {constant["value"]},')
  243. axis_constants_count += 1
  244. if axis_constants_count == 3:
  245. result.append("\t};")
  246. else:
  247. result.append(f'\tstatic const {correct_type(constant["type"])} {constant["name"]};')
  248. if builtin_api["has_destructor"]:
  249. result.append(f"\t~{class_name}();")
  250. method_list = []
  251. if "methods" in builtin_api:
  252. for method in builtin_api["methods"]:
  253. method_list.append(method["name"])
  254. vararg = method["is_vararg"]
  255. if vararg:
  256. result.append("\ttemplate<class... Args>")
  257. method_signature = "\t"
  258. if "is_static" in method and method["is_static"]:
  259. method_signature += "static "
  260. if "return_type" in method:
  261. method_signature += f'{correct_type(method["return_type"])} '
  262. else:
  263. method_signature += "void "
  264. method_signature += f'{method["name"]}('
  265. method_arguments = []
  266. if "arguments" in method:
  267. method_arguments = method["arguments"]
  268. method_signature += make_function_parameters(
  269. method_arguments, include_default=True, for_builtin=True, is_vararg=vararg
  270. )
  271. method_signature += ")"
  272. if method["is_const"]:
  273. method_signature += " const"
  274. method_signature += ";"
  275. result.append(method_signature)
  276. # Special cases.
  277. if class_name == "String":
  278. result.append("\tCharString utf8() const;")
  279. result.append("\tCharString ascii() const;")
  280. result.append("\tChar16String utf16() const;")
  281. result.append("\tChar32String utf32() const;")
  282. result.append("\tCharWideString wide_string() const;")
  283. if "members" in builtin_api:
  284. for member in builtin_api["members"]:
  285. if f'get_{member["name"]}' not in method_list:
  286. result.append(f'\t{correct_type(member["type"])} get_{member["name"]}() const;')
  287. if f'set_{member["name"]}' not in method_list:
  288. result.append(f'\tvoid set_{member["name"]}({type_for_parameter(member["type"])}value);')
  289. if "operators" in builtin_api:
  290. for operator in builtin_api["operators"]:
  291. if operator["name"] not in ["in", "xor"]:
  292. if "right_type" in operator:
  293. result.append(
  294. f'\t{correct_type(operator["return_type"])} operator{operator["name"]}({type_for_parameter(operator["right_type"])}other) const;'
  295. )
  296. else:
  297. result.append(
  298. f'\t{correct_type(operator["return_type"])} operator{operator["name"].replace("unary", "")}() const;'
  299. )
  300. # Copy assignment.
  301. if copy_constructor_index >= 0:
  302. result.append(f"\t{class_name} &operator=(const {class_name} &other);")
  303. # Move assignment.
  304. result.append(f"\t{class_name} &operator=({class_name} &&other);")
  305. # Special cases.
  306. if class_name == "String":
  307. result.append("String &operator=(const char *p_str);")
  308. result.append("String &operator=(const wchar_t *p_str);")
  309. result.append("String &operator=(const char16_t *p_str);")
  310. result.append("String &operator=(const char32_t *p_str);")
  311. result.append("bool operator==(const char *p_str) const;")
  312. result.append("bool operator==(const wchar_t *p_str) const;")
  313. result.append("bool operator==(const char16_t *p_str) const;")
  314. result.append("bool operator==(const char32_t *p_str) const;")
  315. result.append("bool operator!=(const char *p_str) const;")
  316. result.append("bool operator!=(const wchar_t *p_str) const;")
  317. result.append("bool operator!=(const char16_t *p_str) const;")
  318. result.append("bool operator!=(const char32_t *p_str) const;")
  319. result.append("};")
  320. if class_name == "String":
  321. result.append("")
  322. result.append("bool operator==(const char *p_chr, const String &p_str);")
  323. result.append("bool operator==(const wchar_t *p_chr, const String &p_str);")
  324. result.append("bool operator==(const char16_t *p_chr, const String &p_str);")
  325. result.append("bool operator==(const char32_t *p_chr, const String &p_str);")
  326. result.append("bool operator!=(const char *p_chr, const String &p_str);")
  327. result.append("bool operator!=(const wchar_t *p_chr, const String &p_str);")
  328. result.append("bool operator!=(const char16_t *p_chr, const String &p_str);")
  329. result.append("bool operator!=(const char32_t *p_chr, const String &p_str);")
  330. result.append("String operator+(const char *p_chr, const String &p_str);")
  331. result.append("String operator+(const wchar_t *p_chr, const String &p_str);")
  332. result.append("String operator+(const char16_t *p_chr, const String &p_str);")
  333. result.append("String operator+(const char32_t *p_chr, const String &p_str);")
  334. result.append("")
  335. result.append("} // namespace godot")
  336. result.append(f"#endif // ! {header_guard}")
  337. return "\n".join(result)
  338. def generate_builtin_class_source(builtin_api, size, used_classes, fully_used_classes):
  339. result = []
  340. class_name = builtin_api["name"]
  341. snake_class_name = camel_to_snake(class_name)
  342. enum_type_name = f"GDNATIVE_VARIANT_TYPE_{snake_class_name.upper()}"
  343. add_header(f"{snake_class_name}.cpp", result)
  344. result.append("")
  345. result.append(f"#include <godot_cpp/variant/{snake_class_name}.hpp>")
  346. result.append("")
  347. result.append("#include <godot_cpp/core/binder_common.hpp>")
  348. result.append("")
  349. result.append("#include <godot_cpp/godot.hpp>")
  350. result.append("")
  351. # Only used since the "fully used" is included in header already.
  352. for include in used_classes:
  353. result.append(f"#include <godot_cpp/{get_include_path(include)}>")
  354. if len(used_classes) > 0:
  355. result.append("")
  356. result.append("#include <godot_cpp/core/builtin_ptrcall.hpp>")
  357. result.append("")
  358. result.append("#include <utility>")
  359. result.append("")
  360. result.append("namespace godot {")
  361. result.append("")
  362. result.append(f"{class_name}::_MethodBindings {class_name}::_method_bindings;")
  363. result.append("")
  364. result.append(f"void {class_name}::init_bindings() {{")
  365. if "constructors" in builtin_api:
  366. for constructor in builtin_api["constructors"]:
  367. result.append(
  368. f'\t_method_bindings.constructor_{constructor["index"]} = internal::interface->variant_get_ptr_constructor({enum_type_name}, {constructor["index"]});'
  369. )
  370. if builtin_api["has_destructor"]:
  371. result.append(
  372. f"\t_method_bindings.destructor = internal::interface->variant_get_ptr_destructor({enum_type_name});"
  373. )
  374. if "methods" in builtin_api:
  375. for method in builtin_api["methods"]:
  376. # TODO: Add error check for hash mismatch.
  377. result.append(
  378. f'\t_method_bindings.method_{method["name"]} = internal::interface->variant_get_ptr_builtin_method({enum_type_name}, "{method["name"]}", {method["hash"]});'
  379. )
  380. if "members" in builtin_api:
  381. for member in builtin_api["members"]:
  382. result.append(
  383. f'\t_method_bindings.member_{member["name"]}_setter = internal::interface->variant_get_ptr_setter({enum_type_name}, "{member["name"]}");'
  384. )
  385. result.append(
  386. f'\t_method_bindings.member_{member["name"]}_getter = internal::interface->variant_get_ptr_getter({enum_type_name}, "{member["name"]}");'
  387. )
  388. if "indexing_return_type" in builtin_api:
  389. result.append(
  390. f"\t_method_bindings.indexed_setter = internal::interface->variant_get_ptr_indexed_setter({enum_type_name});"
  391. )
  392. result.append(
  393. f"\t_method_bindings.indexed_getter = internal::interface->variant_get_ptr_indexed_getter({enum_type_name});"
  394. )
  395. if "is_keyed" in builtin_api and builtin_api["is_keyed"]:
  396. result.append(
  397. f"\t_method_bindings.keyed_setter = internal::interface->variant_get_ptr_keyed_setter({enum_type_name});"
  398. )
  399. result.append(
  400. f"\t_method_bindings.keyed_getter = internal::interface->variant_get_ptr_keyed_getter({enum_type_name});"
  401. )
  402. result.append(
  403. f"\t_method_bindings.keyed_checker = internal::interface->variant_get_ptr_keyed_checker({enum_type_name});"
  404. )
  405. if "operators" in builtin_api:
  406. for operator in builtin_api["operators"]:
  407. if "right_type" in operator:
  408. result.append(
  409. 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()});'
  410. )
  411. else:
  412. result.append(
  413. 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);'
  414. )
  415. result.append("}")
  416. result.append("")
  417. copy_constructor_index = -1
  418. if "constructors" in builtin_api:
  419. for constructor in builtin_api["constructors"]:
  420. method_signature = f"{class_name}::{class_name}("
  421. if "arguments" in constructor:
  422. method_signature += make_function_parameters(
  423. constructor["arguments"], include_default=False, for_builtin=True
  424. )
  425. method_signature += ") {"
  426. result.append(method_signature)
  427. method_call = (
  428. f'\tinternal::_call_builtin_constructor(_method_bindings.constructor_{constructor["index"]}, &opaque'
  429. )
  430. if "arguments" in constructor:
  431. if len(constructor["arguments"]) == 1 and constructor["arguments"][0]["type"] == class_name:
  432. copy_constructor_index = constructor["index"]
  433. method_call += ", "
  434. arguments = []
  435. for argument in constructor["arguments"]:
  436. (encode, arg_name) = get_encoded_arg(
  437. argument["name"],
  438. argument["type"],
  439. argument["meta"] if "meta" in argument else None,
  440. )
  441. result += encode
  442. arguments.append(arg_name)
  443. method_call += ", ".join(arguments)
  444. method_call += ");"
  445. result.append(method_call)
  446. result.append("}")
  447. result.append("")
  448. # Move constructor.
  449. result.append(f'{class_name}::{class_name}({class_name} &&other) {{')
  450. result.append("\tstd::swap(opaque, other.opaque);")
  451. result.append("}")
  452. result.append("")
  453. if builtin_api["has_destructor"]:
  454. result.append(f"{class_name}::~{class_name}() {{")
  455. result.append("\t_method_bindings.destructor(&opaque);")
  456. result.append("}")
  457. result.append("")
  458. method_list = []
  459. if "methods" in builtin_api:
  460. for method in builtin_api["methods"]:
  461. method_list.append(method["name"])
  462. if "is_vararg" in method and method["is_vararg"]:
  463. # Done in the header because of the template.
  464. continue
  465. method_signature = make_signature(class_name, method, for_builtin=True)
  466. result.append(method_signature + "{")
  467. method_call = "\t"
  468. if "return_type" in method:
  469. method_call += f'return internal::_call_builtin_method_ptr_ret<{correct_type(method["return_type"])}>('
  470. else:
  471. method_call += f"internal::_call_builtin_method_ptr_no_ret("
  472. method_call += f'_method_bindings.method_{method["name"]}, '
  473. if "is_static" in method and method["is_static"]:
  474. method_call += "nullptr"
  475. else:
  476. method_call += "(GDNativeTypePtr)&opaque"
  477. if "arguments" in method:
  478. arguments = []
  479. method_call += ", "
  480. for argument in method["arguments"]:
  481. (encode, arg_name) = get_encoded_arg(
  482. argument["name"],
  483. argument["type"],
  484. argument["meta"] if "meta" in argument else None,
  485. )
  486. result += encode
  487. arguments.append(arg_name)
  488. method_call += ", ".join(arguments)
  489. method_call += ");"
  490. result.append(method_call)
  491. result.append("}")
  492. result.append("")
  493. if "members" in builtin_api:
  494. for member in builtin_api["members"]:
  495. if f'get_{member["name"]}' not in method_list:
  496. result.append(f'{correct_type(member["type"])} {class_name}::get_{member["name"]}() const {{')
  497. result.append(
  498. f'\treturn internal::_call_builtin_ptr_getter<{correct_type(member["type"])}>(_method_bindings.member_{member["name"]}_getter, (const GDNativeTypePtr)&opaque);'
  499. )
  500. result.append("}")
  501. if f'set_{member["name"]}' not in method_list:
  502. result.append(f'void {class_name}::set_{member["name"]}({type_for_parameter(member["type"])}value) {{')
  503. (encode, arg_name) = get_encoded_arg("value", member["type"], None)
  504. result += encode
  505. result.append(
  506. f'\t_method_bindings.member_{member["name"]}_setter((const GDNativeTypePtr)&opaque, (const GDNativeTypePtr){arg_name});'
  507. )
  508. result.append("}")
  509. result.append("")
  510. if "operators" in builtin_api:
  511. for operator in builtin_api["operators"]:
  512. if operator["name"] not in ["in", "xor"]:
  513. if "right_type" in operator:
  514. result.append(
  515. f'{correct_type(operator["return_type"])} {class_name}::operator{operator["name"]}({type_for_parameter(operator["right_type"])}other) const {{'
  516. )
  517. (encode, arg_name) = get_encoded_arg("other", operator["right_type"], None)
  518. result += encode
  519. result.append(
  520. 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});'
  521. )
  522. result.append("}")
  523. else:
  524. result.append(
  525. f'{correct_type(operator["return_type"])} {class_name}::operator{operator["name"].replace("unary", "")}() const {{'
  526. )
  527. result.append(
  528. 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);'
  529. )
  530. result.append("}")
  531. result.append("")
  532. # Copy assignment.
  533. if copy_constructor_index >= 0:
  534. result.append(f"{class_name} &{class_name}::operator=(const {class_name} &other) {{")
  535. if builtin_api["has_destructor"]:
  536. result.append("\t_method_bindings.destructor(&opaque);")
  537. (encode, arg_name) = get_encoded_arg(
  538. "other",
  539. class_name,
  540. None,
  541. )
  542. result += encode
  543. result.append(
  544. f"\tinternal::_call_builtin_constructor(_method_bindings.constructor_{copy_constructor_index}, &opaque, {arg_name});"
  545. )
  546. result.append("\treturn *this;")
  547. result.append("}")
  548. result.append("")
  549. # Move assignment.
  550. result.append(f"{class_name} &{class_name}::operator=({class_name} &&other) {{")
  551. result.append("\tstd::swap(opaque, other.opaque);")
  552. result.append("\treturn *this;")
  553. result.append("}")
  554. result.append("")
  555. result.append("} //namespace godot")
  556. return "\n".join(result)
  557. def generate_engine_classes_bindings(api, output_dir, use_template_get_node):
  558. global engine_classes
  559. global singletons
  560. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  561. source_gen_folder = Path(output_dir) / "src" / "classes"
  562. include_gen_folder.mkdir(parents=True, exist_ok=True)
  563. source_gen_folder.mkdir(parents=True, exist_ok=True)
  564. # First create map of classes and singletons.
  565. for class_api in api["classes"]:
  566. # TODO: Properly setup this singleton since it conflicts with ClassDB in the bindings.
  567. if class_api["name"] == "ClassDB":
  568. continue
  569. engine_classes[class_api["name"]] = class_api["is_refcounted"]
  570. for native_struct in api["native_structures"]:
  571. engine_classes[native_struct["name"]] = False
  572. for singleton in api["singletons"]:
  573. singletons.append(singleton["name"])
  574. for class_api in api["classes"]:
  575. # TODO: Properly setup this singleton since it conflicts with ClassDB in the bindings.
  576. if class_api["name"] == "ClassDB":
  577. continue
  578. # Check used classes for header include.
  579. used_classes = set()
  580. fully_used_classes = set()
  581. class_name = class_api["name"]
  582. header_filename = include_gen_folder / (camel_to_snake(class_api["name"]) + ".hpp")
  583. source_filename = source_gen_folder / (camel_to_snake(class_api["name"]) + ".cpp")
  584. if "methods" in class_api:
  585. for method in class_api["methods"]:
  586. if "arguments" in method:
  587. for argument in method["arguments"]:
  588. type_name = argument["type"]
  589. if type_name.endswith("*"):
  590. type_name = type_name[:-1]
  591. if is_included(type_name, class_name):
  592. if is_enum(type_name):
  593. fully_used_classes.add(get_enum_class(type_name))
  594. elif "default_value" in argument:
  595. fully_used_classes.add(type_name)
  596. else:
  597. used_classes.add(type_name)
  598. if is_refcounted(type_name):
  599. fully_used_classes.add("Ref")
  600. if "return_value" in method:
  601. type_name = method["return_value"]["type"]
  602. if type_name.endswith("*"):
  603. type_name = type_name[:-1]
  604. if is_included(type_name, class_name):
  605. if is_enum(type_name):
  606. fully_used_classes.add(get_enum_class(type_name))
  607. elif is_variant(type_name):
  608. fully_used_classes.add(type_name)
  609. else:
  610. used_classes.add(type_name)
  611. if is_refcounted(type_name):
  612. fully_used_classes.add("Ref")
  613. if "members" in class_api:
  614. for member in class_api["members"]:
  615. if is_included(member["type"], class_name):
  616. if is_enum(member["type"]):
  617. fully_used_classes.add(get_enum_class(member["type"]))
  618. else:
  619. used_classes.add(member["type"])
  620. if is_refcounted(member["type"]):
  621. fully_used_classes.add("Ref")
  622. if "inherits" in class_api:
  623. if is_included(class_api["inherits"], class_name):
  624. fully_used_classes.add(class_api["inherits"])
  625. if is_refcounted(class_api["name"]):
  626. fully_used_classes.add("Ref")
  627. else:
  628. fully_used_classes.add("Wrapped")
  629. for type_name in fully_used_classes:
  630. if type_name in used_classes:
  631. used_classes.remove(type_name)
  632. with header_filename.open("w+") as header_file:
  633. header_file.write(
  634. generate_engine_class_header(class_api, used_classes, fully_used_classes, use_template_get_node)
  635. )
  636. with source_filename.open("w+") as source_file:
  637. source_file.write(
  638. generate_engine_class_source(class_api, used_classes, fully_used_classes, use_template_get_node)
  639. )
  640. for native_struct in api["native_structures"]:
  641. struct_name = native_struct["name"]
  642. snake_struct_name = camel_to_snake(struct_name)
  643. header_filename = include_gen_folder / (snake_struct_name + ".hpp")
  644. result = []
  645. add_header(f"{snake_struct_name}.hpp", result)
  646. header_guard = f"GODOT_CPP_{snake_struct_name.upper()}_HPP"
  647. result.append(f"#ifndef {header_guard}")
  648. result.append(f"#define {header_guard}")
  649. result.append("")
  650. result.append("namespace godot {")
  651. result.append("")
  652. result.append(f"struct {struct_name} {{")
  653. for field in native_struct["format"].split(","):
  654. result.append(f"\t{field};")
  655. result.append("};")
  656. result.append("")
  657. result.append("} // namespace godot")
  658. result.append("")
  659. result.append(f"#endif // ! {header_guard}")
  660. with header_filename.open("w+") as header_file:
  661. header_file.write("\n".join(result))
  662. def generate_engine_class_header(class_api, used_classes, fully_used_classes, use_template_get_node):
  663. global singletons
  664. result = []
  665. class_name = class_api["name"]
  666. snake_class_name = camel_to_snake(class_name).upper()
  667. is_singleton = class_name in singletons
  668. add_header(f"{snake_class_name.lower()}.hpp", result)
  669. header_guard = f"GODOT_CPP_{snake_class_name}_HPP"
  670. result.append(f"#ifndef {header_guard}")
  671. result.append(f"#define {header_guard}")
  672. result.append("")
  673. for included in fully_used_classes:
  674. result.append(f"#include <godot_cpp/{get_include_path(included)}>")
  675. if len(fully_used_classes) > 0:
  676. result.append("")
  677. if class_name != "Object":
  678. result.append("#include <godot_cpp/core/class_db.hpp>")
  679. result.append("")
  680. result.append("#include <type_traits>")
  681. result.append("")
  682. result.append("namespace godot {")
  683. result.append("")
  684. for type_name in used_classes:
  685. result.append(f"class {type_name};")
  686. if len(used_classes) > 0:
  687. result.append("")
  688. inherits = class_api["inherits"] if "inherits" in class_api else "Wrapped"
  689. result.append(f"class {class_name} : public {inherits} {{")
  690. result.append(f"\tGDNATIVE_CLASS({class_name}, {inherits})")
  691. result.append("")
  692. result.append("public:")
  693. if "enums" in class_api:
  694. for enum_api in class_api["enums"]:
  695. result.append(f'\tenum {enum_api["name"]} {{')
  696. for value in enum_api["values"]:
  697. result.append(f'\t\t{value["name"]} = {value["value"]},')
  698. result.append("\t};")
  699. result.append("")
  700. if is_singleton:
  701. result.append(f"\tstatic {class_name} *get_singleton();")
  702. result.append("")
  703. if "methods" in class_api:
  704. for method in class_api["methods"]:
  705. if method["is_virtual"]:
  706. # Will be done later.
  707. continue
  708. vararg = "is_vararg" in method and method["is_vararg"]
  709. method_signature = "\t"
  710. if vararg:
  711. method_signature += "private: "
  712. method_signature += make_signature(
  713. class_name, method, for_header=True, use_template_get_node=use_template_get_node
  714. )
  715. result.append(method_signature + ";")
  716. if vararg:
  717. # Add templated version.
  718. result += make_varargs_template(method)
  719. # Virtuals now.
  720. for method in class_api["methods"]:
  721. if not method["is_virtual"]:
  722. continue
  723. method_signature = "\t"
  724. method_signature += make_signature(
  725. class_name, method, for_header=True, use_template_get_node=use_template_get_node
  726. )
  727. result.append(method_signature + ";")
  728. result.append("protected:")
  729. result.append("\ttemplate <class T>")
  730. result.append("\tstatic void register_virtuals() {")
  731. if class_name != "Object":
  732. result.append(f"\t\t{inherits}::register_virtuals<T>();")
  733. if "methods" in class_api:
  734. for method in class_api["methods"]:
  735. if not method["is_virtual"]:
  736. continue
  737. method_name = escape_identifier(method["name"])
  738. result.append(
  739. f"\t\tif constexpr (!std::is_same_v<decltype(&{class_name}::{method_name}),decltype(&T::{method_name})>) {{"
  740. )
  741. result.append(f"\t\t\tBIND_VIRTUAL_METHOD(T, {method_name});")
  742. result.append("\t\t}")
  743. result.append("\t}")
  744. result.append("")
  745. result.append("public:")
  746. # Special cases.
  747. if class_name == "Object":
  748. result.append("")
  749. result.append("\ttemplate<class T>")
  750. result.append("\tstatic T *cast_to(Object *p_object);")
  751. elif use_template_get_node and class_name == "Node":
  752. result.append("\ttemplate<class T>")
  753. result.append(
  754. "\tT *get_node(const NodePath &p_path) const { return Object::cast_to<T>(get_node_internal(p_path)); }"
  755. )
  756. # Constructor.
  757. result.append("")
  758. result.append(f"\t{class_name}();")
  759. result.append("")
  760. result.append("};")
  761. result.append("")
  762. result.append("} // namespace godot")
  763. result.append(f"#endif // ! {header_guard}")
  764. return "\n".join(result)
  765. def generate_engine_class_source(class_api, used_classes, fully_used_classes, use_template_get_node):
  766. global singletons
  767. result = []
  768. class_name = class_api["name"]
  769. snake_class_name = camel_to_snake(class_name)
  770. inherits = class_api["inherits"] if "inherits" in class_api else "Wrapped"
  771. is_singleton = class_name in singletons
  772. add_header(f"{snake_class_name}.cpp", result)
  773. result.append(f"#include <godot_cpp/classes/{snake_class_name}.hpp>")
  774. result.append("")
  775. result.append(f"#include <godot_cpp/core/engine_ptrcall.hpp>")
  776. result.append(f"#include <godot_cpp/core/error_macros.hpp>")
  777. result.append("")
  778. for included in used_classes:
  779. result.append(f"#include <godot_cpp/{get_include_path(included)}>")
  780. if len(used_classes) > 0:
  781. result.append(f"")
  782. result.append("namespace godot {")
  783. result.append("")
  784. if is_singleton:
  785. result.append(f"{class_name} *{class_name}::get_singleton() {{")
  786. result.append(
  787. f'\tstatic GDNativeObjectPtr singleton_obj = internal::interface->global_get_singleton("{class_name}");'
  788. )
  789. result.append("#ifdef DEBUG_ENABLED")
  790. result.append("\tERR_FAIL_COND_V(singleton_obj == nullptr, nullptr);")
  791. result.append("#endif // DEBUG_ENABLED")
  792. result.append(
  793. f"\tstatic {class_name} *singleton = reinterpret_cast<{class_name} *>(internal::interface->object_get_instance_binding(singleton_obj, internal::token, &{class_name}::___binding_callbacks));"
  794. )
  795. result.append("\treturn singleton;")
  796. result.append("}")
  797. result.append("")
  798. if "methods" in class_api:
  799. for method in class_api["methods"]:
  800. if method["is_virtual"]:
  801. # Will be done later
  802. continue
  803. vararg = "is_vararg" in method and method["is_vararg"]
  804. # Method signature.
  805. method_signature = make_signature(class_name, method, use_template_get_node=use_template_get_node)
  806. result.append(method_signature + " {")
  807. # Method body.
  808. result.append(
  809. f'\tstatic GDNativeMethodBindPtr ___method_bind = internal::interface->classdb_get_method_bind("{class_name}", "{method["name"]}", {method["hash"]});'
  810. )
  811. method_call = "\t"
  812. has_return = "return_value" in method and method["return_value"]["type"] != "void"
  813. if has_return:
  814. result.append(
  815. f'\tCHECK_METHOD_BIND_RET(___method_bind, {get_default_value_for_type(method["return_value"]["type"])});'
  816. )
  817. else:
  818. result.append(f"\tCHECK_METHOD_BIND(___method_bind);")
  819. is_ref = False
  820. if not vararg:
  821. if has_return:
  822. return_type = method["return_value"]["type"]
  823. meta_type = method["return_value"]["meta"] if "meta" in method["return_value"] else None
  824. if is_pod_type(return_type) or is_variant(return_type) or is_enum(return_type):
  825. method_call += f"return internal::_call_native_mb_ret<{correct_type(return_type, meta_type)}>(___method_bind, _owner"
  826. elif is_refcounted(return_type):
  827. method_call += f"return Ref<{return_type}>::___internal_constructor(internal::_call_native_mb_ret_obj<{return_type}>(___method_bind, _owner"
  828. is_ref = True
  829. else:
  830. method_call += f"return ({correct_type(return_type)})internal::_call_native_mb_ret_obj<{return_type}>(___method_bind, _owner"
  831. else:
  832. method_call += f"internal::_call_native_mb_no_ret(___method_bind, _owner"
  833. if "arguments" in method:
  834. method_call += ", "
  835. arguments = []
  836. for argument in method["arguments"]:
  837. (encode, arg_name) = get_encoded_arg(
  838. argument["name"],
  839. argument["type"],
  840. argument["meta"] if "meta" in argument else None,
  841. )
  842. result += encode
  843. arguments.append(arg_name)
  844. method_call += ", ".join(arguments)
  845. else: # vararg.
  846. result.append("\tGDNativeCallError error;")
  847. result.append("\tVariant ret;")
  848. method_call += "internal::interface->object_method_bind_call(___method_bind, _owner, (const GDNativeVariantPtr *)args, arg_count, &ret, &error"
  849. if is_ref:
  850. method_call += ")" # Close Ref<> constructor.
  851. method_call += ");"
  852. result.append(method_call)
  853. if vararg and ("return_value" in method and method["return_value"]["type"] != "void"):
  854. result.append("\treturn ret;")
  855. result.append("}")
  856. result.append("")
  857. # Virtuals now.
  858. for method in class_api["methods"]:
  859. if not method["is_virtual"]:
  860. continue
  861. method_signature = make_signature(class_name, method, use_template_get_node=use_template_get_node)
  862. method_signature += " {"
  863. if "return_value" in method and correct_type(method["return_value"]["type"]) != "void":
  864. result.append(method_signature)
  865. result.append(f'\treturn {get_default_value_for_type(method["return_value"]["type"])};')
  866. result.append("}")
  867. else:
  868. method_signature += "}"
  869. result.append(method_signature)
  870. result.append("")
  871. # Constructor.
  872. result.append(f"{class_name}::{class_name}() : {inherits}(godot::internal::empty_constructor()) {{")
  873. result.append(
  874. f'\tstatic GDNativeClassConstructor constructor = internal::interface->classdb_get_constructor("{class_name}");'
  875. )
  876. result.append("\t_owner = (GodotObject *)constructor();")
  877. result.append(
  878. f"\tinternal::interface->object_set_instance_binding((GDNativeObjectPtr)_owner, internal::token, this, &{class_name}::___binding_callbacks);"
  879. )
  880. result.append("}")
  881. result.append("")
  882. result.append("} // namespace godot ")
  883. return "\n".join(result)
  884. def generate_global_constants(api, output_dir):
  885. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  886. source_gen_folder = Path(output_dir) / "src" / "classes"
  887. include_gen_folder.mkdir(parents=True, exist_ok=True)
  888. source_gen_folder.mkdir(parents=True, exist_ok=True)
  889. # Generate header
  890. header = []
  891. add_header("global_constants.hpp", header)
  892. header_filename = include_gen_folder / "global_constants.hpp"
  893. header_guard = "GODOT_CPP_GLOBAL_CONSTANTS_HPP"
  894. header.append(f"#ifndef {header_guard}")
  895. header.append(f"#define {header_guard}")
  896. header.append("")
  897. header.append("namespace godot {")
  898. header.append("")
  899. for constant in api["global_constants"]:
  900. header.append(f'\tconst int {escape_identifier(constant["name"])} = {constant["value"]};')
  901. header.append("")
  902. for enum_def in api["global_enums"]:
  903. if enum_def["name"].startswith("Variant."):
  904. continue
  905. header.append(f'\tenum {enum_def["name"]} {{')
  906. for value in enum_def["values"]:
  907. header.append(f'\t\t{value["name"]} = {value["value"]},')
  908. header.append("\t};")
  909. header.append("")
  910. header.append("} // namespace godot")
  911. header.append("")
  912. header.append(f"#endif // ! {header_guard}")
  913. with header_filename.open("w+") as header_file:
  914. header_file.write("\n".join(header))
  915. def generate_utility_functions(api, output_dir):
  916. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "variant"
  917. source_gen_folder = Path(output_dir) / "src" / "variant"
  918. include_gen_folder.mkdir(parents=True, exist_ok=True)
  919. source_gen_folder.mkdir(parents=True, exist_ok=True)
  920. # Generate header.
  921. header = []
  922. add_header("utility_functions.hpp", header)
  923. header_filename = include_gen_folder / "utility_functions.hpp"
  924. header_guard = "GODOT_CPP_UTILITY_FUNCTIONS_HPP"
  925. header.append(f"#ifndef {header_guard}")
  926. header.append(f"#define {header_guard}")
  927. header.append("")
  928. header.append("#include <godot_cpp/variant/builtin_types.hpp>")
  929. header.append("#include <godot_cpp/variant/variant.hpp>")
  930. header.append("")
  931. header.append("#include <array>")
  932. header.append("")
  933. header.append("namespace godot {")
  934. header.append("")
  935. header.append("class UtilityFunctions {")
  936. header.append("public:")
  937. for function in api["utility_functions"]:
  938. vararg = "is_vararg" in function and function["is_vararg"]
  939. function_signature = "\t"
  940. function_signature += make_signature("UtilityFunctions", function, for_header=True, static=True)
  941. header.append(function_signature + ";")
  942. if vararg:
  943. # Add templated version.
  944. header += make_varargs_template(function, static=True)
  945. header.append("};")
  946. header.append("")
  947. header.append("} // namespace godot")
  948. header.append("")
  949. header.append(f"#endif // ! {header_guard}")
  950. with header_filename.open("w+") as header_file:
  951. header_file.write("\n".join(header))
  952. # Generate source.
  953. source = []
  954. add_header("utility_functions.cpp", source)
  955. source_filename = source_gen_folder / "utility_functions.cpp"
  956. source.append("#include <godot_cpp/variant/utility_functions.hpp>")
  957. source.append("")
  958. source.append("#include <godot_cpp/core/error_macros.hpp>")
  959. source.append("#include <godot_cpp/core/engine_ptrcall.hpp>")
  960. source.append("")
  961. source.append("namespace godot {")
  962. source.append("")
  963. for function in api["utility_functions"]:
  964. vararg = "is_vararg" in function and function["is_vararg"]
  965. function_signature = make_signature("UtilityFunctions", function)
  966. source.append(function_signature + " {")
  967. # Function body.
  968. source.append(
  969. f'\tstatic GDNativePtrUtilityFunction ___function = internal::interface->variant_get_ptr_utility_function("{function["name"]}", {function["hash"]});'
  970. )
  971. has_return = "return_type" in function and function["return_type"] != "void"
  972. if has_return:
  973. source.append(
  974. f'\tCHECK_METHOD_BIND_RET(___function, {get_default_value_for_type(function["return_type"])});'
  975. )
  976. else:
  977. source.append(f"\tCHECK_METHOD_BIND(___function);")
  978. function_call = "\t"
  979. if not vararg:
  980. if has_return:
  981. function_call += "return "
  982. if function["return_type"] == "Object":
  983. function_call += "internal::_call_utility_ret_obj(___function"
  984. else:
  985. function_call += f'internal::_call_utility_ret<{correct_type(function["return_type"])}>(___function'
  986. else:
  987. function_call += "internal::_call_utility_no_ret(___function"
  988. if "arguments" in function:
  989. function_call += ", "
  990. arguments = []
  991. for argument in function["arguments"]:
  992. (encode, arg_name) = get_encoded_arg(
  993. argument["name"],
  994. argument["type"],
  995. argument["meta"] if "meta" in argument else None,
  996. )
  997. source += encode
  998. arguments.append(arg_name)
  999. function_call += ", ".join(arguments)
  1000. else:
  1001. source.append("\tVariant ret;")
  1002. function_call += "___function(&ret, (const GDNativeVariantPtr *)args, arg_count"
  1003. function_call += ");"
  1004. source.append(function_call)
  1005. if vararg and has_return:
  1006. source.append("\treturn ret;")
  1007. source.append("}")
  1008. source.append("")
  1009. source.append("} // namespace godot")
  1010. with source_filename.open("w+") as source_file:
  1011. source_file.write("\n".join(source))
  1012. # Helper functions.
  1013. def camel_to_snake(name):
  1014. name = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
  1015. name = re.sub("([a-z0-9])([A-Z])", r"\1_\2", name)
  1016. return name.replace("2_D", "2D").replace("3_D", "3D").lower()
  1017. def make_function_parameters(parameters, include_default=False, for_builtin=False, is_vararg=False):
  1018. signature = []
  1019. for index, par in enumerate(parameters):
  1020. parameter = type_for_parameter(par["type"], par["meta"] if "meta" in par else None)
  1021. parameter_name = escape_identifier(par["name"])
  1022. if len(parameter_name) == 0:
  1023. parameter_name = "arg_" + str(index + 1)
  1024. parameter += parameter_name
  1025. if include_default and "default_value" in par and (not for_builtin or par["type"] != "Variant"):
  1026. parameter += " = "
  1027. if is_enum(par["type"]):
  1028. parameter_type = correct_type(par["type"])
  1029. if parameter_type == "void":
  1030. parameter_type = "Variant"
  1031. parameter += f"({parameter_type})"
  1032. parameter += correct_default_value(par["default_value"], par["type"])
  1033. signature.append(parameter)
  1034. if is_vararg:
  1035. signature.append("const Args&... args")
  1036. return ", ".join(signature)
  1037. def type_for_parameter(type_name, meta=None):
  1038. if type_name == "void":
  1039. return "Variant "
  1040. elif is_pod_type(type_name) and type_name != "Nil" or is_enum(type_name):
  1041. return f"{correct_type(type_name, meta)} "
  1042. elif is_variant(type_name) or is_refcounted(type_name):
  1043. return f"const {correct_type(type_name)} &"
  1044. else:
  1045. return f"{correct_type(type_name)}"
  1046. def get_include_path(type_name):
  1047. base_dir = ""
  1048. if type_name == "Object":
  1049. base_dir = "core"
  1050. elif is_variant(type_name):
  1051. base_dir = "variant"
  1052. else:
  1053. base_dir = "classes"
  1054. return f"{base_dir}/{camel_to_snake(type_name)}.hpp"
  1055. def get_encoded_arg(arg_name, type_name, type_meta):
  1056. result = []
  1057. name = escape_identifier(arg_name)
  1058. arg_type = correct_type(type_name)
  1059. if is_pod_type(arg_type):
  1060. result.append(f"\t{get_gdnative_type(arg_type)} {name}_encoded;")
  1061. result.append(f"\tPtrToArg<{correct_type(type_name)}>::encode({name}, &{name}_encoded);")
  1062. name = f"&{name}_encoded"
  1063. elif is_engine_class(type_name):
  1064. name = f"{name}->_owner"
  1065. else:
  1066. name = f"&{name}"
  1067. return (result, name)
  1068. def make_signature(
  1069. class_name, function_data, for_header=False, use_template_get_node=True, for_builtin=False, static=False
  1070. ):
  1071. function_signature = ""
  1072. is_vararg = "is_vararg" in function_data and function_data["is_vararg"]
  1073. if for_header:
  1074. if "is_virtual" in function_data and function_data["is_virtual"]:
  1075. function_signature += "virtual "
  1076. if is_vararg:
  1077. function_signature += "private: "
  1078. if static:
  1079. function_signature += "static "
  1080. return_type = "void"
  1081. return_meta = None
  1082. if "return_type" in function_data:
  1083. return_type = correct_type(function_data["return_type"])
  1084. elif "return_value" in function_data:
  1085. return_type = function_data["return_value"]["type"]
  1086. return_meta = function_data["return_value"]["meta"] if "meta" in function_data["return_value"] else None
  1087. function_signature += correct_type(
  1088. return_type,
  1089. return_meta,
  1090. )
  1091. if not function_signature.endswith("*"):
  1092. function_signature += " "
  1093. if not for_header:
  1094. function_signature += f"{class_name}::"
  1095. function_signature += escape_identifier(function_data["name"])
  1096. if is_vararg or (
  1097. not for_builtin and use_template_get_node and class_name == "Node" and function_data["name"] == "get_node"
  1098. ):
  1099. function_signature += "_internal"
  1100. function_signature += "("
  1101. arguments = function_data["arguments"] if "arguments" in function_data else []
  1102. if not is_vararg:
  1103. function_signature += make_function_parameters(arguments, for_header, for_builtin, is_vararg)
  1104. else:
  1105. function_signature += "const Variant **args, GDNativeInt arg_count"
  1106. function_signature += ")"
  1107. if "is_const" in function_data and function_data["is_const"]:
  1108. function_signature += " const"
  1109. return function_signature
  1110. def make_varargs_template(function_data, static=False):
  1111. result = []
  1112. function_signature = "\tpublic: template<class... Args> "
  1113. if static:
  1114. function_signature += "static "
  1115. return_type = "void"
  1116. return_meta = None
  1117. if "return_type" in function_data:
  1118. return_type = correct_type(function_data["return_type"])
  1119. elif "return_value" in function_data:
  1120. return_type = function_data["return_value"]["type"]
  1121. return_meta = function_data["return_value"]["meta"] if "meta" in function_data["return_value"] else None
  1122. function_signature += correct_type(
  1123. return_type,
  1124. return_meta,
  1125. )
  1126. if not function_signature.endswith("*"):
  1127. function_signature += " "
  1128. function_signature += f'{escape_identifier(function_data["name"])}'
  1129. method_arguments = []
  1130. if "arguments" in function_data:
  1131. method_arguments = function_data["arguments"]
  1132. function_signature += "("
  1133. is_vararg = "is_vararg" in function_data and function_data["is_vararg"]
  1134. function_signature += make_function_parameters(method_arguments, include_default=True, is_vararg=is_vararg)
  1135. function_signature += ")"
  1136. if "is_const" in function_data and function_data["is_const"]:
  1137. function_signature += " const"
  1138. function_signature += " {"
  1139. result.append(function_signature)
  1140. args_array = f"\t\tstd::array<Variant, {len(method_arguments)} + sizeof...(Args)> variant_args {{ "
  1141. for argument in method_arguments:
  1142. if argument["type"] == "Variant":
  1143. args_array += argument["name"]
  1144. else:
  1145. args_array += f'Variant({argument["name"]})'
  1146. args_array += ", "
  1147. args_array += "Variant(args)... };"
  1148. result.append(args_array)
  1149. result.append(f"\t\tstd::array<const Variant *, {len(method_arguments)} + sizeof...(Args)> call_args;")
  1150. result.append("\t\tfor(size_t i = 0; i < variant_args.size(); i++) {")
  1151. result.append("\t\t\tcall_args[i] = &variant_args[i];")
  1152. result.append("\t\t}")
  1153. call_line = "\t\t"
  1154. if return_type != "void":
  1155. call_line += "return "
  1156. call_line += f'{escape_identifier(function_data["name"])}_internal(call_args.data(), variant_args.size());'
  1157. result.append(call_line)
  1158. result.append("\t}")
  1159. return result
  1160. # Engine idiosyncrasies.
  1161. def is_pod_type(type_name):
  1162. """
  1163. Those are types for which no class should be generated.
  1164. """
  1165. return type_name in [
  1166. "Nil",
  1167. "void",
  1168. "int",
  1169. "float",
  1170. "bool",
  1171. "double",
  1172. "int32_t",
  1173. "int64_t",
  1174. "uint32_t",
  1175. "uint64_t",
  1176. ]
  1177. def is_enum(type_name):
  1178. return type_name.startswith("enum::")
  1179. def get_enum_class(enum_name: str):
  1180. if "." in enum_name:
  1181. return enum_name.replace("enum::", "").split(".")[0]
  1182. else:
  1183. return "GlobalConstants"
  1184. def get_enum_name(enum_name: str):
  1185. return enum_name.replace("enum::", "").split(".")[-1]
  1186. def is_variant(type_name):
  1187. return type_name == "Variant" or type_name in builtin_classes or type_name == "Nil"
  1188. def is_engine_class(type_name):
  1189. global engine_classes
  1190. return type_name == "Object" or type_name in engine_classes
  1191. def is_refcounted(type_name):
  1192. return type_name in engine_classes and engine_classes[type_name]
  1193. def is_included(type_name, current_type):
  1194. """
  1195. Check if a builtin type should be included.
  1196. This removes Variant and POD types from inclusion, and the current type.
  1197. """
  1198. to_include = get_enum_class(type_name) if is_enum(type_name) else type_name
  1199. if to_include == current_type or is_pod_type(to_include):
  1200. return False
  1201. if to_include == "GlobalConstants" or to_include == "UtilityFunctions":
  1202. return True
  1203. return is_engine_class(to_include) or is_variant(to_include)
  1204. def correct_default_value(value, type_name):
  1205. value_map = {
  1206. "null": "nullptr",
  1207. '""': "String()",
  1208. '&""': "StringName()",
  1209. "[]": "Array()",
  1210. "{}": "Dictionary()",
  1211. "Transform2D(1, 0, 0, 1, 0, 0)": "Transform2D()", # Default transform.
  1212. "Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)": "Transform3D()", # Default transform.
  1213. }
  1214. if value in value_map:
  1215. return value_map[value]
  1216. if value == "":
  1217. return f"{type_name}()"
  1218. return value
  1219. def correct_type(type_name, meta=None):
  1220. type_conversion = {"float": "double", "int": "int64_t", "Nil": "Variant"}
  1221. if meta != None:
  1222. if "int" in meta:
  1223. return f"{meta}_t"
  1224. else:
  1225. return meta
  1226. if type_name in type_conversion:
  1227. return type_conversion[type_name]
  1228. if is_enum(type_name):
  1229. base_class = get_enum_class(type_name)
  1230. if base_class == "GlobalConstants":
  1231. return f"{get_enum_name(type_name)}"
  1232. return f"{base_class}::{get_enum_name(type_name)}"
  1233. if is_refcounted(type_name):
  1234. return f"Ref<{type_name}>"
  1235. if type_name == "Object" or is_engine_class(type_name):
  1236. return f"{type_name} *"
  1237. if type_name.endswith("*"):
  1238. return f"{type_name[:-1]} *"
  1239. return type_name
  1240. def get_gdnative_type(type_name):
  1241. type_conversion_map = {
  1242. "bool": "uint32_t",
  1243. "int": "int64_t",
  1244. "float": "double",
  1245. }
  1246. if type_name in type_conversion_map:
  1247. return type_conversion_map[type_name]
  1248. return type_name
  1249. def escape_identifier(id):
  1250. cpp_keywords_map = {
  1251. "class": "_class",
  1252. "char": "_char",
  1253. "short": "_short",
  1254. "bool": "_bool",
  1255. "int": "_int",
  1256. "default": "_default",
  1257. "case": "_case",
  1258. "switch": "_switch",
  1259. "export": "_export",
  1260. "template": "_template",
  1261. "new": "new_",
  1262. "operator": "_operator",
  1263. "typeof": "type_of",
  1264. "typename": "type_name",
  1265. }
  1266. if id in cpp_keywords_map:
  1267. return cpp_keywords_map[id]
  1268. return id
  1269. def get_operator_id_name(op):
  1270. op_id_map = {
  1271. "==": "equal",
  1272. "!=": "not_equal",
  1273. "<": "less",
  1274. "<=": "less_equal",
  1275. ">": "greater",
  1276. ">=": "greater_equal",
  1277. "+": "add",
  1278. "-": "subtract",
  1279. "*": "multiply",
  1280. "/": "divide",
  1281. "unary-": "negate",
  1282. "unary+": "positive",
  1283. "%": "module",
  1284. "<<": "shift_left",
  1285. ">>": "shift_right",
  1286. "&": "bit_and",
  1287. "|": "bit_or",
  1288. "^": "bit_xor",
  1289. "~": "bit_negate",
  1290. "and": "and",
  1291. "or": "or",
  1292. "xor": "xor",
  1293. "not": "not",
  1294. "and": "and",
  1295. "in": "in",
  1296. }
  1297. return op_id_map[op]
  1298. def get_default_value_for_type(type_name):
  1299. if type_name == "int":
  1300. return "0"
  1301. if type_name == "float":
  1302. return "0.0"
  1303. if type_name == "bool":
  1304. return "false"
  1305. if is_enum(type_name):
  1306. return f"{correct_type(type_name)}(0)"
  1307. if is_variant(type_name):
  1308. return f"{type_name}()"
  1309. if is_refcounted(type_name):
  1310. return f"Ref<{type_name}>()"
  1311. return "nullptr"
  1312. header = """\
  1313. /*************************************************************************/
  1314. /* $filename */
  1315. /*************************************************************************/
  1316. /* This file is part of: */
  1317. /* GODOT ENGINE */
  1318. /* https://godotengine.org */
  1319. /*************************************************************************/
  1320. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  1321. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  1322. /* */
  1323. /* Permission is hereby granted, free of charge, to any person obtaining */
  1324. /* a copy of this software and associated documentation files (the */
  1325. /* "Software"), to deal in the Software without restriction, including */
  1326. /* without limitation the rights to use, copy, modify, merge, publish, */
  1327. /* distribute, sublicense, and/or sell copies of the Software, and to */
  1328. /* permit persons to whom the Software is furnished to do so, subject to */
  1329. /* the following conditions: */
  1330. /* */
  1331. /* The above copyright notice and this permission notice shall be */
  1332. /* included in all copies or substantial portions of the Software. */
  1333. /* */
  1334. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  1335. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  1336. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  1337. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  1338. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  1339. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  1340. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  1341. /*************************************************************************/
  1342. """
  1343. def add_header(filename, lines):
  1344. desired_length = len(header.split("\n")[0])
  1345. pad_spaces = desired_length - 6 - len(filename)
  1346. for num, line in enumerate(header.split("\n")):
  1347. if num == 1:
  1348. new_line = f"/* {filename}{' ' * pad_spaces}*/"
  1349. lines.append(new_line)
  1350. else:
  1351. lines.append(line)
  1352. lines.append("// THIS FILE IS GENERATED. EDITS WILL BE LOST.")
  1353. lines.append("")