binding_generator.py 75 KB

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