binding_generator.py 67 KB

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