binding_generator.py 88 KB

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