binding_generator.py 78 KB

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