binding_generator.py 83 KB

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