2
0

binding_generator.py 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004
  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("\tvirtual ~Object() = default;")
  874. elif use_template_get_node and class_name == "Node":
  875. result.append("\ttemplate<class T>")
  876. result.append(
  877. "\tT *get_node(const NodePath &p_path) const { return Object::cast_to<T>(get_node_internal(p_path)); }"
  878. )
  879. result.append("")
  880. result.append("};")
  881. result.append("")
  882. result.append("} // namespace godot")
  883. result.append("")
  884. if "enums" in class_api and class_name != "Object":
  885. for enum_api in class_api["enums"]:
  886. if enum_api["is_bitfield"]:
  887. result.append(f'VARIANT_BITFIELD_CAST({class_name}, {class_name}::{enum_api["name"]});')
  888. else:
  889. result.append(f'VARIANT_ENUM_CAST({class_name}, {class_name}::{enum_api["name"]});')
  890. result.append("")
  891. result.append(f"#endif // ! {header_guard}")
  892. return "\n".join(result)
  893. def generate_engine_class_source(class_api, used_classes, fully_used_classes, use_template_get_node):
  894. global singletons
  895. result = []
  896. class_name = class_api["name"]
  897. snake_class_name = camel_to_snake(class_name)
  898. inherits = class_api["inherits"] if "inherits" in class_api else "Wrapped"
  899. is_singleton = class_name in singletons
  900. add_header(f"{snake_class_name}.cpp", result)
  901. result.append(f"#include <godot_cpp/classes/{snake_class_name}.hpp>")
  902. result.append(f"#include <godot_cpp/classes/global_constants_binds.hpp>")
  903. result.append("")
  904. result.append(f"#include <godot_cpp/core/engine_ptrcall.hpp>")
  905. result.append(f"#include <godot_cpp/core/error_macros.hpp>")
  906. result.append("")
  907. for included in used_classes:
  908. result.append(f"#include <godot_cpp/{get_include_path(included)}>")
  909. if len(used_classes) > 0:
  910. result.append(f"")
  911. result.append("namespace godot {")
  912. result.append("")
  913. if is_singleton:
  914. result.append(f"{class_name} *{class_name}::get_singleton() {{")
  915. result.append(
  916. f'\tstatic GDNativeObjectPtr singleton_obj = internal::gdn_interface->global_get_singleton("{class_name}");'
  917. )
  918. result.append("#ifdef DEBUG_ENABLED")
  919. result.append("\tERR_FAIL_COND_V(singleton_obj == nullptr, nullptr);")
  920. result.append("#endif // DEBUG_ENABLED")
  921. result.append(
  922. f"\tstatic {class_name} *singleton = reinterpret_cast<{class_name} *>(internal::gdn_interface->object_get_instance_binding(singleton_obj, internal::token, &{class_name}::___binding_callbacks));"
  923. )
  924. result.append("\treturn singleton;")
  925. result.append("}")
  926. result.append("")
  927. if "methods" in class_api:
  928. for method in class_api["methods"]:
  929. if method["is_virtual"]:
  930. # Will be done later
  931. continue
  932. vararg = "is_vararg" in method and method["is_vararg"]
  933. # Method signature.
  934. method_signature = make_signature(class_name, method, use_template_get_node=use_template_get_node)
  935. result.append(method_signature + " {")
  936. # Method body.
  937. result.append(
  938. f'\tstatic GDNativeMethodBindPtr ___method_bind = internal::gdn_interface->classdb_get_method_bind("{class_name}", "{method["name"]}", {method["hash"]});'
  939. )
  940. method_call = "\t"
  941. has_return = "return_value" in method and method["return_value"]["type"] != "void"
  942. if has_return:
  943. result.append(
  944. f'\tCHECK_METHOD_BIND_RET(___method_bind, {get_default_value_for_type(method["return_value"]["type"])});'
  945. )
  946. else:
  947. result.append(f"\tCHECK_METHOD_BIND(___method_bind);")
  948. is_ref = False
  949. if not vararg:
  950. if has_return:
  951. return_type = method["return_value"]["type"]
  952. meta_type = method["return_value"]["meta"] if "meta" in method["return_value"] else None
  953. if is_pod_type(return_type) or is_variant(return_type) or is_enum(return_type):
  954. if method["is_static"]:
  955. method_call += f"return internal::_call_native_mb_ret<{get_gdnative_type(correct_type(return_type, meta_type))}>(___method_bind, nullptr"
  956. else:
  957. method_call += f"return internal::_call_native_mb_ret<{get_gdnative_type(correct_type(return_type, meta_type))}>(___method_bind, _owner"
  958. elif is_refcounted(return_type):
  959. if method["is_static"]:
  960. method_call += f"return Ref<{return_type}>::___internal_constructor(internal::_call_native_mb_ret_obj<{return_type}>(___method_bind, nullptr"
  961. else:
  962. method_call += f"return Ref<{return_type}>::___internal_constructor(internal::_call_native_mb_ret_obj<{return_type}>(___method_bind, _owner"
  963. is_ref = True
  964. else:
  965. if method["is_static"]:
  966. method_call += (
  967. f"return internal::_call_native_mb_ret_obj<{return_type}>(___method_bind, nullptr"
  968. )
  969. else:
  970. method_call += (
  971. f"return internal::_call_native_mb_ret_obj<{return_type}>(___method_bind, _owner"
  972. )
  973. else:
  974. if method["is_static"]:
  975. method_call += f"internal::_call_native_mb_no_ret(___method_bind, nullptr"
  976. else:
  977. method_call += f"internal::_call_native_mb_no_ret(___method_bind, _owner"
  978. if "arguments" in method:
  979. method_call += ", "
  980. arguments = []
  981. for argument in method["arguments"]:
  982. (encode, arg_name) = get_encoded_arg(
  983. argument["name"],
  984. argument["type"],
  985. argument["meta"] if "meta" in argument else None,
  986. )
  987. result += encode
  988. arguments.append(arg_name)
  989. method_call += ", ".join(arguments)
  990. else: # vararg.
  991. result.append("\tGDNativeCallError error;")
  992. result.append("\tVariant ret;")
  993. method_call += "internal::gdn_interface->object_method_bind_call(___method_bind, _owner, (const GDNativeVariantPtr *)args, arg_count, &ret, &error"
  994. if is_ref:
  995. method_call += ")" # Close Ref<> constructor.
  996. method_call += ");"
  997. result.append(method_call)
  998. if vararg and ("return_value" in method and method["return_value"]["type"] != "void"):
  999. return_type = get_enum_fullname(method["return_value"]["type"])
  1000. if return_type != "Variant":
  1001. result.append(f"\treturn VariantCaster<{return_type}>::cast(ret);")
  1002. else:
  1003. result.append("\treturn ret;")
  1004. result.append("}")
  1005. result.append("")
  1006. # Virtuals now.
  1007. for method in class_api["methods"]:
  1008. if not method["is_virtual"]:
  1009. continue
  1010. method_signature = make_signature(class_name, method, use_template_get_node=use_template_get_node)
  1011. method_signature += " {"
  1012. if "return_value" in method and correct_type(method["return_value"]["type"]) != "void":
  1013. result.append(method_signature)
  1014. result.append(f'\treturn {get_default_value_for_type(method["return_value"]["type"])};')
  1015. result.append("}")
  1016. else:
  1017. method_signature += "}"
  1018. result.append(method_signature)
  1019. result.append("")
  1020. result.append("")
  1021. result.append("} // namespace godot ")
  1022. return "\n".join(result)
  1023. def generate_global_constants(api, output_dir):
  1024. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  1025. source_gen_folder = Path(output_dir) / "src" / "classes"
  1026. include_gen_folder.mkdir(parents=True, exist_ok=True)
  1027. source_gen_folder.mkdir(parents=True, exist_ok=True)
  1028. # Generate header
  1029. header = []
  1030. add_header("global_constants.hpp", header)
  1031. header_filename = include_gen_folder / "global_constants.hpp"
  1032. header_guard = "GODOT_CPP_GLOBAL_CONSTANTS_HPP"
  1033. header.append(f"#ifndef {header_guard}")
  1034. header.append(f"#define {header_guard}")
  1035. header.append("")
  1036. header.append("namespace godot {")
  1037. header.append("")
  1038. for constant in api["global_constants"]:
  1039. header.append(f'\tconst int {escape_identifier(constant["name"])} = {constant["value"]};')
  1040. header.append("")
  1041. for enum_def in api["global_enums"]:
  1042. if enum_def["name"].startswith("Variant."):
  1043. continue
  1044. header.append(f'\tenum {enum_def["name"]} {{')
  1045. for value in enum_def["values"]:
  1046. header.append(f'\t\t{value["name"]} = {value["value"]},')
  1047. header.append("\t};")
  1048. header.append("")
  1049. header.append("} // namespace godot")
  1050. header.append("")
  1051. header.append(f"#endif // ! {header_guard}")
  1052. with header_filename.open("w+") as header_file:
  1053. header_file.write("\n".join(header))
  1054. def generate_global_constant_binds(api, output_dir):
  1055. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  1056. source_gen_folder = Path(output_dir) / "src" / "classes"
  1057. include_gen_folder.mkdir(parents=True, exist_ok=True)
  1058. source_gen_folder.mkdir(parents=True, exist_ok=True)
  1059. # Generate header
  1060. header = []
  1061. add_header("global_constants_binds.hpp", header)
  1062. header_filename = include_gen_folder / "global_constants_binds.hpp"
  1063. header_guard = "GODOT_CPP_GLOBAL_CONSTANTS_BINDS_HPP"
  1064. header.append(f"#ifndef {header_guard}")
  1065. header.append(f"#define {header_guard}")
  1066. header.append("")
  1067. header.append("#include <godot_cpp/classes/global_constants.hpp>")
  1068. header.append("#include <godot_cpp/core/binder_common.hpp>")
  1069. header.append("")
  1070. for enum_def in api["global_enums"]:
  1071. if enum_def["name"].startswith("Variant."):
  1072. continue
  1073. header.append(f'VARIANT_ENUM_CAST(, godot::{enum_def["name"]});')
  1074. header.append("")
  1075. header.append(f"#endif // ! {header_guard}")
  1076. with header_filename.open("w+") as header_file:
  1077. header_file.write("\n".join(header))
  1078. def generate_utility_functions(api, output_dir):
  1079. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "variant"
  1080. source_gen_folder = Path(output_dir) / "src" / "variant"
  1081. include_gen_folder.mkdir(parents=True, exist_ok=True)
  1082. source_gen_folder.mkdir(parents=True, exist_ok=True)
  1083. # Generate header.
  1084. header = []
  1085. add_header("utility_functions.hpp", header)
  1086. header_filename = include_gen_folder / "utility_functions.hpp"
  1087. header_guard = "GODOT_CPP_UTILITY_FUNCTIONS_HPP"
  1088. header.append(f"#ifndef {header_guard}")
  1089. header.append(f"#define {header_guard}")
  1090. header.append("")
  1091. header.append("#include <godot_cpp/variant/builtin_types.hpp>")
  1092. header.append("#include <godot_cpp/variant/variant.hpp>")
  1093. header.append("")
  1094. header.append("#include <array>")
  1095. header.append("")
  1096. header.append("namespace godot {")
  1097. header.append("")
  1098. header.append("class UtilityFunctions {")
  1099. header.append("public:")
  1100. for function in api["utility_functions"]:
  1101. vararg = "is_vararg" in function and function["is_vararg"]
  1102. function_signature = "\t"
  1103. function_signature += make_signature("UtilityFunctions", function, for_header=True, static=True)
  1104. header.append(function_signature + ";")
  1105. if vararg:
  1106. # Add templated version.
  1107. header += make_varargs_template(function, static=True)
  1108. header.append("};")
  1109. header.append("")
  1110. header.append("} // namespace godot")
  1111. header.append("")
  1112. header.append(f"#endif // ! {header_guard}")
  1113. with header_filename.open("w+") as header_file:
  1114. header_file.write("\n".join(header))
  1115. # Generate source.
  1116. source = []
  1117. add_header("utility_functions.cpp", source)
  1118. source_filename = source_gen_folder / "utility_functions.cpp"
  1119. source.append("#include <godot_cpp/variant/utility_functions.hpp>")
  1120. source.append("")
  1121. source.append("#include <godot_cpp/core/error_macros.hpp>")
  1122. source.append("#include <godot_cpp/core/engine_ptrcall.hpp>")
  1123. source.append("")
  1124. source.append("namespace godot {")
  1125. source.append("")
  1126. for function in api["utility_functions"]:
  1127. vararg = "is_vararg" in function and function["is_vararg"]
  1128. function_signature = make_signature("UtilityFunctions", function)
  1129. source.append(function_signature + " {")
  1130. # Function body.
  1131. source.append(
  1132. f'\tstatic GDNativePtrUtilityFunction ___function = internal::gdn_interface->variant_get_ptr_utility_function("{function["name"]}", {function["hash"]});'
  1133. )
  1134. has_return = "return_type" in function and function["return_type"] != "void"
  1135. if has_return:
  1136. source.append(
  1137. f'\tCHECK_METHOD_BIND_RET(___function, {get_default_value_for_type(function["return_type"])});'
  1138. )
  1139. else:
  1140. source.append(f"\tCHECK_METHOD_BIND(___function);")
  1141. function_call = "\t"
  1142. if not vararg:
  1143. if has_return:
  1144. function_call += "return "
  1145. if function["return_type"] == "Object":
  1146. function_call += "internal::_call_utility_ret_obj(___function"
  1147. else:
  1148. function_call += f'internal::_call_utility_ret<{get_gdnative_type(correct_type(function["return_type"]))}>(___function'
  1149. else:
  1150. function_call += "internal::_call_utility_no_ret(___function"
  1151. if "arguments" in function:
  1152. function_call += ", "
  1153. arguments = []
  1154. for argument in function["arguments"]:
  1155. (encode, arg_name) = get_encoded_arg(
  1156. argument["name"],
  1157. argument["type"],
  1158. argument["meta"] if "meta" in argument else None,
  1159. )
  1160. source += encode
  1161. arguments.append(arg_name)
  1162. function_call += ", ".join(arguments)
  1163. else:
  1164. source.append("\tVariant ret;")
  1165. function_call += "___function(&ret, (const GDNativeVariantPtr *)args, arg_count"
  1166. function_call += ");"
  1167. source.append(function_call)
  1168. if vararg and has_return:
  1169. source.append("\treturn ret;")
  1170. source.append("}")
  1171. source.append("")
  1172. source.append("} // namespace godot")
  1173. with source_filename.open("w+") as source_file:
  1174. source_file.write("\n".join(source))
  1175. # Helper functions.
  1176. def camel_to_snake(name):
  1177. name = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
  1178. name = re.sub("([a-z0-9])([A-Z])", r"\1_\2", name)
  1179. return name.replace("2_D", "2D").replace("3_D", "3D").lower()
  1180. def make_function_parameters(parameters, include_default=False, for_builtin=False, is_vararg=False):
  1181. signature = []
  1182. for index, par in enumerate(parameters):
  1183. parameter = type_for_parameter(par["type"], par["meta"] if "meta" in par else None)
  1184. parameter_name = escape_identifier(par["name"])
  1185. if len(parameter_name) == 0:
  1186. parameter_name = "arg_" + str(index + 1)
  1187. parameter += parameter_name
  1188. if include_default and "default_value" in par and (not for_builtin or par["type"] != "Variant"):
  1189. parameter += " = "
  1190. if is_enum(par["type"]):
  1191. parameter_type = correct_type(par["type"])
  1192. if parameter_type == "void":
  1193. parameter_type = "Variant"
  1194. parameter += f"({parameter_type})"
  1195. parameter += correct_default_value(par["default_value"], par["type"])
  1196. signature.append(parameter)
  1197. if is_vararg:
  1198. signature.append("const Args&... args")
  1199. return ", ".join(signature)
  1200. def type_for_parameter(type_name, meta=None):
  1201. if type_name == "void":
  1202. return "Variant "
  1203. elif is_pod_type(type_name) and type_name != "Nil" or is_enum(type_name):
  1204. return f"{correct_type(type_name, meta)} "
  1205. elif is_variant(type_name) or is_refcounted(type_name):
  1206. return f"const {correct_type(type_name)} &"
  1207. else:
  1208. return f"{correct_type(type_name)}"
  1209. def get_include_path(type_name):
  1210. base_dir = ""
  1211. if type_name == "Object":
  1212. base_dir = "core"
  1213. elif is_variant(type_name):
  1214. base_dir = "variant"
  1215. else:
  1216. base_dir = "classes"
  1217. return f"{base_dir}/{camel_to_snake(type_name)}.hpp"
  1218. def get_encoded_arg(arg_name, type_name, type_meta):
  1219. result = []
  1220. name = escape_identifier(arg_name)
  1221. arg_type = correct_type(type_name)
  1222. if is_pod_type(arg_type):
  1223. result.append(f"\t{get_gdnative_type(arg_type)} {name}_encoded;")
  1224. result.append(f"\tPtrToArg<{correct_type(type_name)}>::encode({name}, &{name}_encoded);")
  1225. name = f"&{name}_encoded"
  1226. elif is_engine_class(type_name):
  1227. name = f"{name}->_owner"
  1228. else:
  1229. name = f"&{name}"
  1230. return (result, name)
  1231. def make_signature(
  1232. class_name, function_data, for_header=False, use_template_get_node=True, for_builtin=False, static=False
  1233. ):
  1234. function_signature = ""
  1235. is_vararg = "is_vararg" in function_data and function_data["is_vararg"]
  1236. if for_header:
  1237. if "is_virtual" in function_data and function_data["is_virtual"]:
  1238. function_signature += "virtual "
  1239. if is_vararg:
  1240. function_signature += "private: "
  1241. if static:
  1242. function_signature += "static "
  1243. return_type = "void"
  1244. return_meta = None
  1245. if "return_type" in function_data:
  1246. return_type = correct_type(function_data["return_type"])
  1247. elif "return_value" in function_data:
  1248. return_type = function_data["return_value"]["type"]
  1249. return_meta = function_data["return_value"]["meta"] if "meta" in function_data["return_value"] else None
  1250. function_signature += correct_type(
  1251. return_type,
  1252. return_meta,
  1253. )
  1254. if not function_signature.endswith("*"):
  1255. function_signature += " "
  1256. if not for_header:
  1257. function_signature += f"{class_name}::"
  1258. function_signature += escape_identifier(function_data["name"])
  1259. if is_vararg or (
  1260. not for_builtin and use_template_get_node and class_name == "Node" and function_data["name"] == "get_node"
  1261. ):
  1262. function_signature += "_internal"
  1263. function_signature += "("
  1264. arguments = function_data["arguments"] if "arguments" in function_data else []
  1265. if not is_vararg:
  1266. function_signature += make_function_parameters(arguments, for_header, for_builtin, is_vararg)
  1267. else:
  1268. function_signature += "const Variant **args, GDNativeInt arg_count"
  1269. function_signature += ")"
  1270. if "is_static" in function_data and function_data["is_static"] and for_header:
  1271. function_signature = "static " + function_signature
  1272. elif "is_const" in function_data and function_data["is_const"]:
  1273. function_signature += " const"
  1274. return function_signature
  1275. def make_varargs_template(function_data, static=False):
  1276. result = []
  1277. function_signature = "\tpublic: template<class... Args> "
  1278. if static:
  1279. function_signature += "static "
  1280. return_type = "void"
  1281. return_meta = None
  1282. if "return_type" in function_data:
  1283. return_type = correct_type(function_data["return_type"])
  1284. elif "return_value" in function_data:
  1285. return_type = function_data["return_value"]["type"]
  1286. return_meta = function_data["return_value"]["meta"] if "meta" in function_data["return_value"] else None
  1287. function_signature += correct_type(
  1288. return_type,
  1289. return_meta,
  1290. )
  1291. if not function_signature.endswith("*"):
  1292. function_signature += " "
  1293. function_signature += f'{escape_identifier(function_data["name"])}'
  1294. method_arguments = []
  1295. if "arguments" in function_data:
  1296. method_arguments = function_data["arguments"]
  1297. function_signature += "("
  1298. is_vararg = "is_vararg" in function_data and function_data["is_vararg"]
  1299. function_signature += make_function_parameters(method_arguments, include_default=True, is_vararg=is_vararg)
  1300. function_signature += ")"
  1301. if "is_const" in function_data and function_data["is_const"]:
  1302. function_signature += " const"
  1303. function_signature += " {"
  1304. result.append(function_signature)
  1305. args_array = f"\t\tstd::array<Variant, {len(method_arguments)} + sizeof...(Args)> variant_args {{ "
  1306. for argument in method_arguments:
  1307. if argument["type"] == "Variant":
  1308. args_array += argument["name"]
  1309. else:
  1310. args_array += f'Variant({argument["name"]})'
  1311. args_array += ", "
  1312. args_array += "Variant(args)... };"
  1313. result.append(args_array)
  1314. result.append(f"\t\tstd::array<const Variant *, {len(method_arguments)} + sizeof...(Args)> call_args;")
  1315. result.append("\t\tfor(size_t i = 0; i < variant_args.size(); i++) {")
  1316. result.append("\t\t\tcall_args[i] = &variant_args[i];")
  1317. result.append("\t\t}")
  1318. call_line = "\t\t"
  1319. if return_type != "void":
  1320. call_line += "return "
  1321. call_line += f'{escape_identifier(function_data["name"])}_internal(call_args.data(), variant_args.size());'
  1322. result.append(call_line)
  1323. result.append("\t}")
  1324. return result
  1325. # Engine idiosyncrasies.
  1326. def is_pod_type(type_name):
  1327. """
  1328. Those are types for which no class should be generated.
  1329. """
  1330. return type_name in [
  1331. "Nil",
  1332. "void",
  1333. "bool",
  1334. "real_t",
  1335. "float",
  1336. "double",
  1337. "int",
  1338. "int8_t",
  1339. "uint8_t",
  1340. "int16_t",
  1341. "uint16_t",
  1342. "int32_t",
  1343. "int64_t",
  1344. "uint32_t",
  1345. "uint64_t",
  1346. ]
  1347. def is_included_type(type_name):
  1348. """
  1349. Those are types for which we already have a class file implemented.
  1350. """
  1351. return type_name in [
  1352. "AABB",
  1353. "Basis",
  1354. "Color",
  1355. "ObjectID",
  1356. "Plane",
  1357. "Quaternion",
  1358. "Rect2",
  1359. "Rect2i",
  1360. "Transform2D",
  1361. "Transform3D",
  1362. "Vector2",
  1363. "Vector2i",
  1364. "Vector3",
  1365. "Vector3i",
  1366. "Vector4",
  1367. "Vector4i",
  1368. "Projection",
  1369. ]
  1370. def is_packed_array(type_name):
  1371. """
  1372. Those are types for which we add our extra packed array functions.
  1373. """
  1374. return type_name in [
  1375. "PackedByteArray",
  1376. "PackedColorArray",
  1377. "PackedFloat32Array",
  1378. "PackedFloat64Array",
  1379. "PackedInt32Array",
  1380. "PackedInt64Array",
  1381. "PackedStringArray",
  1382. "PackedVector2Array",
  1383. "PackedVector3Array",
  1384. ]
  1385. def needs_copy_instead_of_move(type_name):
  1386. """
  1387. Those are types which need initialised data or we'll get warning spam so need a copy instead of move.
  1388. """
  1389. return type_name in [
  1390. "Dictionary",
  1391. ]
  1392. def is_enum(type_name):
  1393. return type_name.startswith("enum::") or type_name.startswith("bitfield::")
  1394. def is_bitfield(type_name):
  1395. return type_name.startswith("bitfield::")
  1396. def get_enum_class(enum_name: str):
  1397. if "." in enum_name:
  1398. if is_bitfield(enum_name):
  1399. return enum_name.replace("bitfield::", "").split(".")[0]
  1400. else:
  1401. return enum_name.replace("enum::", "").split(".")[0]
  1402. else:
  1403. return "GlobalConstants"
  1404. def get_enum_fullname(enum_name: str):
  1405. if is_bitfield(enum_name):
  1406. return enum_name.replace("bitfield::", "BitField<") + ">"
  1407. else:
  1408. return enum_name.replace("enum::", "")
  1409. def get_enum_name(enum_name: str):
  1410. if is_bitfield(enum_name):
  1411. return enum_name.replace("bitfield::", "").split(".")[-1]
  1412. else:
  1413. return enum_name.replace("enum::", "").split(".")[-1]
  1414. def is_variant(type_name):
  1415. return type_name == "Variant" or type_name in builtin_classes or type_name == "Nil"
  1416. def is_engine_class(type_name):
  1417. global engine_classes
  1418. return type_name == "Object" or type_name in engine_classes
  1419. def is_native_struct(type_name):
  1420. global native_structures
  1421. return type_name in native_structures
  1422. def is_refcounted(type_name):
  1423. return type_name in engine_classes and engine_classes[type_name]
  1424. def is_included(type_name, current_type):
  1425. """
  1426. Check if a builtin type should be included.
  1427. This removes Variant and POD types from inclusion, and the current type.
  1428. """
  1429. to_include = get_enum_class(type_name) if is_enum(type_name) else type_name
  1430. if to_include == current_type or is_pod_type(to_include):
  1431. return False
  1432. if to_include == "GlobalConstants" or to_include == "UtilityFunctions":
  1433. return True
  1434. return is_engine_class(to_include) or is_variant(to_include)
  1435. def correct_default_value(value, type_name):
  1436. value_map = {
  1437. "null": "nullptr",
  1438. '""': "String()",
  1439. '&""': "StringName()",
  1440. "[]": "Array()",
  1441. "{}": "Dictionary()",
  1442. "Transform2D(1, 0, 0, 1, 0, 0)": "Transform2D()", # Default transform.
  1443. "Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)": "Transform3D()", # Default transform.
  1444. }
  1445. if value in value_map:
  1446. return value_map[value]
  1447. if value == "":
  1448. return f"{type_name}()"
  1449. return value
  1450. def correct_type(type_name, meta=None):
  1451. type_conversion = {"float": "double", "int": "int64_t", "Nil": "Variant"}
  1452. if meta != None:
  1453. if "int" in meta:
  1454. return f"{meta}_t"
  1455. elif meta in type_conversion:
  1456. return type_conversion[type_name]
  1457. else:
  1458. return meta
  1459. if type_name in type_conversion:
  1460. return type_conversion[type_name]
  1461. if is_enum(type_name):
  1462. if is_bitfield(type_name):
  1463. base_class = get_enum_class(type_name)
  1464. if base_class == "GlobalConstants":
  1465. return f"BitField<{get_enum_name(type_name)}>"
  1466. return f"BitField<{base_class}::{get_enum_name(type_name)}>"
  1467. else:
  1468. base_class = get_enum_class(type_name)
  1469. if base_class == "GlobalConstants":
  1470. return f"{get_enum_name(type_name)}"
  1471. return f"{base_class}::{get_enum_name(type_name)}"
  1472. if is_refcounted(type_name):
  1473. return f"Ref<{type_name}>"
  1474. if type_name == "Object" or is_engine_class(type_name):
  1475. return f"{type_name} *"
  1476. if type_name.endswith("*"):
  1477. return f"{type_name[:-1]} *"
  1478. return type_name
  1479. def get_gdnative_type(type_name):
  1480. type_conversion_map = {
  1481. "bool": "int8_t",
  1482. "uint8_t": "int64_t",
  1483. "int8_t": "int64_t",
  1484. "uint16_t": "int64_t",
  1485. "int16_t": "int64_t",
  1486. "uint32_t": "int64_t",
  1487. "int32_t": "int64_t",
  1488. "int": "int64_t",
  1489. "float": "double",
  1490. }
  1491. if type_name.startswith("BitField<"):
  1492. return "int64_t"
  1493. if type_name in type_conversion_map:
  1494. return type_conversion_map[type_name]
  1495. return type_name
  1496. def escape_identifier(id):
  1497. cpp_keywords_map = {
  1498. "class": "_class",
  1499. "char": "_char",
  1500. "short": "_short",
  1501. "bool": "_bool",
  1502. "int": "_int",
  1503. "default": "_default",
  1504. "case": "_case",
  1505. "switch": "_switch",
  1506. "export": "_export",
  1507. "template": "_template",
  1508. "new": "new_",
  1509. "operator": "_operator",
  1510. "typeof": "type_of",
  1511. "typename": "type_name",
  1512. }
  1513. if id in cpp_keywords_map:
  1514. return cpp_keywords_map[id]
  1515. return id
  1516. def get_operator_id_name(op):
  1517. op_id_map = {
  1518. "==": "equal",
  1519. "!=": "not_equal",
  1520. "<": "less",
  1521. "<=": "less_equal",
  1522. ">": "greater",
  1523. ">=": "greater_equal",
  1524. "+": "add",
  1525. "-": "subtract",
  1526. "*": "multiply",
  1527. "/": "divide",
  1528. "unary-": "negate",
  1529. "unary+": "positive",
  1530. "%": "module",
  1531. "<<": "shift_left",
  1532. ">>": "shift_right",
  1533. "&": "bit_and",
  1534. "|": "bit_or",
  1535. "^": "bit_xor",
  1536. "~": "bit_negate",
  1537. "and": "and",
  1538. "or": "or",
  1539. "xor": "xor",
  1540. "not": "not",
  1541. "and": "and",
  1542. "in": "in",
  1543. }
  1544. return op_id_map[op]
  1545. def get_default_value_for_type(type_name):
  1546. if type_name == "int":
  1547. return "0"
  1548. if type_name == "float":
  1549. return "0.0"
  1550. if type_name == "bool":
  1551. return "false"
  1552. if is_enum(type_name):
  1553. return f"{correct_type(type_name)}(0)"
  1554. if is_variant(type_name):
  1555. return f"{type_name}()"
  1556. if is_refcounted(type_name):
  1557. return f"Ref<{type_name}>()"
  1558. return "nullptr"
  1559. header = """\
  1560. /*************************************************************************/
  1561. /* $filename */
  1562. /*************************************************************************/
  1563. /* This file is part of: */
  1564. /* GODOT ENGINE */
  1565. /* https://godotengine.org */
  1566. /*************************************************************************/
  1567. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  1568. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  1569. /* */
  1570. /* Permission is hereby granted, free of charge, to any person obtaining */
  1571. /* a copy of this software and associated documentation files (the */
  1572. /* "Software"), to deal in the Software without restriction, including */
  1573. /* without limitation the rights to use, copy, modify, merge, publish, */
  1574. /* distribute, sublicense, and/or sell copies of the Software, and to */
  1575. /* permit persons to whom the Software is furnished to do so, subject to */
  1576. /* the following conditions: */
  1577. /* */
  1578. /* The above copyright notice and this permission notice shall be */
  1579. /* included in all copies or substantial portions of the Software. */
  1580. /* */
  1581. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  1582. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  1583. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  1584. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  1585. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  1586. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  1587. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  1588. /*************************************************************************/
  1589. """
  1590. def add_header(filename, lines):
  1591. desired_length = len(header.split("\n")[0])
  1592. pad_spaces = desired_length - 6 - len(filename)
  1593. for num, line in enumerate(header.split("\n")):
  1594. if num == 1:
  1595. new_line = f"/* {filename}{' ' * pad_spaces}*/"
  1596. lines.append(new_line)
  1597. else:
  1598. lines.append(line)
  1599. lines.append("// THIS FILE IS GENERATED. EDITS WILL BE LOST.")
  1600. lines.append("")