binding_generator.py 67 KB

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