binding_generator.py 88 KB

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