binding_generator.py 65 KB

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