binding_generator.py 65 KB

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