binding_generator.py 80 KB

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