binding_generator.py 64 KB

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