binding_generator.py 88 KB

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