binding_generator.py 84 KB

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