binding_generator.py 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431
  1. #!/usr/bin/env python
  2. import json
  3. import re
  4. import shutil
  5. from pathlib import Path
  6. def generate_mod_version(argcount, const=False, returns=False):
  7. s = """
  8. #define MODBIND$VER($RETTYPE m_name$ARG) \\
  9. virtual $RETVAL _##m_name($FUNCARGS) $CONST override; \\
  10. """
  11. sproto = str(argcount)
  12. if returns:
  13. sproto += "R"
  14. s = s.replace("$RETTYPE", "m_ret, ")
  15. s = s.replace("$RETVAL", "m_ret")
  16. else:
  17. s = s.replace("$RETTYPE", "")
  18. s = s.replace("$RETVAL", "void")
  19. if const:
  20. sproto += "C"
  21. s = s.replace("$CONST", "const")
  22. else:
  23. s = s.replace("$CONST", "")
  24. s = s.replace("$VER", sproto)
  25. argtext = ""
  26. funcargs = ""
  27. for i in range(argcount):
  28. if i > 0:
  29. funcargs += ", "
  30. argtext += ", m_type" + str(i + 1)
  31. funcargs += "m_type" + str(i + 1) + " arg" + str(i + 1)
  32. if argcount:
  33. s = s.replace("$ARG", argtext)
  34. s = s.replace("$FUNCARGS", funcargs)
  35. else:
  36. s = s.replace("$ARG", "")
  37. s = s.replace("$FUNCARGS", funcargs)
  38. return s
  39. def generate_wrappers(target):
  40. max_versions = 12
  41. txt = """
  42. #ifndef GDEXTENSION_WRAPPERS_GEN_H
  43. #define GDEXTENSION_WRAPPERS_GEN_H
  44. """
  45. for i in range(max_versions + 1):
  46. txt += "\n/* Module Wrapper " + str(i) + " Arguments */\n"
  47. txt += generate_mod_version(i, False, False)
  48. txt += generate_mod_version(i, False, True)
  49. txt += generate_mod_version(i, True, False)
  50. txt += generate_mod_version(i, True, True)
  51. txt += "\n#endif\n"
  52. with open(target, "w", encoding="utf-8") as f:
  53. f.write(txt)
  54. def get_file_list(api_filepath, output_dir, headers=False, sources=False):
  55. api = {}
  56. files = []
  57. with open(api_filepath, encoding="utf-8") as api_file:
  58. api = json.load(api_file)
  59. core_gen_folder = Path(output_dir) / "gen" / "include" / "godot_cpp" / "core"
  60. include_gen_folder = Path(output_dir) / "gen" / "include" / "godot_cpp"
  61. source_gen_folder = Path(output_dir) / "gen" / "src"
  62. files.append(str((core_gen_folder / "ext_wrappers.gen.inc").as_posix()))
  63. for builtin_class in api["builtin_classes"]:
  64. if is_pod_type(builtin_class["name"]):
  65. continue
  66. if is_included_type(builtin_class["name"]):
  67. continue
  68. header_filename = include_gen_folder / "variant" / (camel_to_snake(builtin_class["name"]) + ".hpp")
  69. source_filename = source_gen_folder / "variant" / (camel_to_snake(builtin_class["name"]) + ".cpp")
  70. if headers:
  71. files.append(str(header_filename.as_posix()))
  72. if sources:
  73. files.append(str(source_filename.as_posix()))
  74. for engine_class in api["classes"]:
  75. # Generate code for the ClassDB singleton under a different name.
  76. if engine_class["name"] == "ClassDB":
  77. engine_class["name"] = "ClassDBSingleton"
  78. engine_class["alias_for"] = "ClassDB"
  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. include_gen_folder / "core" / "version.hpp",
  100. ]:
  101. files.append(str(path.as_posix()))
  102. if sources:
  103. utility_functions_source_path = source_gen_folder / "variant" / "utility_functions.cpp"
  104. files.append(str(utility_functions_source_path.as_posix()))
  105. return files
  106. def print_file_list(api_filepath, output_dir, headers=False, sources=False):
  107. print(*get_file_list(api_filepath, output_dir, headers, sources), sep=";", end=None)
  108. def scons_emit_files(target, source, env):
  109. files = [env.File(f) for f in get_file_list(str(source[0]), target[0].abspath, True, True)]
  110. env.Clean(target, files)
  111. env["godot_cpp_gen_dir"] = target[0].abspath
  112. return files, source
  113. def scons_generate_bindings(target, source, env):
  114. generate_bindings(
  115. str(source[0]),
  116. env["generate_template_get_node"],
  117. "32" if "32" in env["arch"] else "64",
  118. env["precision"],
  119. env["godot_cpp_gen_dir"],
  120. )
  121. return None
  122. def generate_bindings(api_filepath, use_template_get_node, bits="64", precision="single", output_dir="."):
  123. api = None
  124. target_dir = Path(output_dir) / "gen"
  125. with open(api_filepath, encoding="utf-8") as api_file:
  126. api = json.load(api_file)
  127. shutil.rmtree(target_dir, ignore_errors=True)
  128. target_dir.mkdir(parents=True)
  129. real_t = "double" if precision == "double" else "float"
  130. print("Built-in type config: " + real_t + "_" + bits)
  131. generate_global_constants(api, target_dir)
  132. generate_version_header(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", encoding="utf-8") 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+", encoding="utf-8") 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+", encoding="utf-8") 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+", encoding="utf-8") 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+", encoding="utf-8") 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("#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("\t\tGDExtensionPtrIndexedSetter indexed_setter;")
  327. result.append("\t\tGDExtensionPtrIndexedGetter indexed_getter;")
  328. if "is_keyed" in builtin_api and builtin_api["is_keyed"]:
  329. result.append("\t\tGDExtensionPtrKeyedSetter keyed_setter;")
  330. result.append("\t\tGDExtensionPtrKeyedGetter keyed_getter;")
  331. result.append("\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, int64_t len = -1);")
  414. result.append("\tvoid parse_utf8(const char *from, int64_t len = -1);")
  415. result.append("\tstatic String utf16(const char16_t *from, int64_t len = -1);")
  416. result.append("\tvoid parse_utf16(const char16_t *from, int64_t 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[](int64_t p_index) const;")
  470. result.append("\tchar32_t &operator[](int64_t 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} &operator[](int64_t p_index) const;")
  487. result.append(f"\t{return_type} &operator[](int64_t p_index);")
  488. result.append(f"\tconst {return_type} *ptr() const;")
  489. result.append(f"\t{return_type} *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("\tconst Variant &operator[](int64_t p_index) const;")
  549. result.append("\tVariant &operator[](int64_t p_index);")
  550. result.append("\tvoid set_typed(uint32_t p_type, const StringName &p_class_name, const Variant &p_script);")
  551. result.append("\tvoid _ref(const Array &p_from) const;")
  552. if class_name == "Dictionary":
  553. result.append("\tconst Variant &operator[](const Variant &p_key) const;")
  554. result.append("\tVariant &operator[](const Variant &p_key);")
  555. result.append("};")
  556. if class_name == "String":
  557. result.append("")
  558. result.append("bool operator==(const char *p_chr, const String &p_str);")
  559. result.append("bool operator==(const wchar_t *p_chr, const String &p_str);")
  560. result.append("bool operator==(const char16_t *p_chr, const String &p_str);")
  561. result.append("bool operator==(const char32_t *p_chr, const String &p_str);")
  562. result.append("bool operator!=(const char *p_chr, const String &p_str);")
  563. result.append("bool operator!=(const wchar_t *p_chr, const String &p_str);")
  564. result.append("bool operator!=(const char16_t *p_chr, const String &p_str);")
  565. result.append("bool operator!=(const char32_t *p_chr, const String &p_str);")
  566. result.append("String operator+(const char *p_chr, const String &p_str);")
  567. result.append("String operator+(const wchar_t *p_chr, const String &p_str);")
  568. result.append("String operator+(const char16_t *p_chr, const String &p_str);")
  569. result.append("String operator+(const char32_t *p_chr, const String &p_str);")
  570. result.append("String operator+(char32_t p_char, const String &p_str);")
  571. result.append("String itos(int64_t p_val);")
  572. result.append("String uitos(uint64_t p_val);")
  573. result.append("String rtos(double p_val);")
  574. result.append("String rtoss(double p_val);")
  575. result.append("")
  576. result.append("} // namespace godot")
  577. result.append(f"#endif // ! {header_guard}")
  578. return "\n".join(result)
  579. def generate_builtin_class_source(builtin_api, size, used_classes, fully_used_classes):
  580. result = []
  581. class_name = builtin_api["name"]
  582. snake_class_name = camel_to_snake(class_name)
  583. enum_type_name = f"GDEXTENSION_VARIANT_TYPE_{snake_class_name.upper()}"
  584. add_header(f"{snake_class_name}.cpp", result)
  585. result.append("")
  586. result.append(f"#include <godot_cpp/variant/{snake_class_name}.hpp>")
  587. result.append("")
  588. result.append("#include <godot_cpp/core/binder_common.hpp>")
  589. result.append("")
  590. result.append("#include <godot_cpp/godot.hpp>")
  591. result.append("")
  592. # Only used since the "fully used" is included in header already.
  593. for include in used_classes:
  594. result.append(f"#include <godot_cpp/{get_include_path(include)}>")
  595. if len(used_classes) > 0:
  596. result.append("")
  597. result.append("#include <godot_cpp/core/builtin_ptrcall.hpp>")
  598. result.append("")
  599. result.append("#include <utility>")
  600. result.append("")
  601. result.append("namespace godot {")
  602. result.append("")
  603. result.append(f"{class_name}::_MethodBindings {class_name}::_method_bindings;")
  604. result.append("")
  605. result.append(f"void {class_name}::_init_bindings_constructors_destructor() {{")
  606. if "constructors" in builtin_api:
  607. for constructor in builtin_api["constructors"]:
  608. result.append(
  609. f'\t_method_bindings.constructor_{constructor["index"]} = internal::gdextension_interface_variant_get_ptr_constructor({enum_type_name}, {constructor["index"]});'
  610. )
  611. if builtin_api["has_destructor"]:
  612. result.append(
  613. f"\t_method_bindings.destructor = internal::gdextension_interface_variant_get_ptr_destructor({enum_type_name});"
  614. )
  615. result.append("}")
  616. result.append(f"void {class_name}::init_bindings() {{")
  617. # StringName's constructor internally uses String, so it constructor must be ready !
  618. if class_name == "StringName":
  619. result.append("\tString::_init_bindings_constructors_destructor();")
  620. result.append(f"\t{class_name}::_init_bindings_constructors_destructor();")
  621. result.append("\tStringName _gde_name;")
  622. if "methods" in builtin_api:
  623. for method in builtin_api["methods"]:
  624. # TODO: Add error check for hash mismatch.
  625. result.append(f'\t_gde_name = StringName("{method["name"]}");')
  626. result.append(
  627. f'\t_method_bindings.method_{method["name"]} = internal::gdextension_interface_variant_get_ptr_builtin_method({enum_type_name}, _gde_name._native_ptr(), {method["hash"]});'
  628. )
  629. if "members" in builtin_api:
  630. for member in builtin_api["members"]:
  631. result.append(f'\t_gde_name = StringName("{member["name"]}");')
  632. result.append(
  633. f'\t_method_bindings.member_{member["name"]}_setter = internal::gdextension_interface_variant_get_ptr_setter({enum_type_name}, _gde_name._native_ptr());'
  634. )
  635. result.append(
  636. f'\t_method_bindings.member_{member["name"]}_getter = internal::gdextension_interface_variant_get_ptr_getter({enum_type_name}, _gde_name._native_ptr());'
  637. )
  638. if "indexing_return_type" in builtin_api:
  639. result.append(
  640. f"\t_method_bindings.indexed_setter = internal::gdextension_interface_variant_get_ptr_indexed_setter({enum_type_name});"
  641. )
  642. result.append(
  643. f"\t_method_bindings.indexed_getter = internal::gdextension_interface_variant_get_ptr_indexed_getter({enum_type_name});"
  644. )
  645. if "is_keyed" in builtin_api and builtin_api["is_keyed"]:
  646. result.append(
  647. f"\t_method_bindings.keyed_setter = internal::gdextension_interface_variant_get_ptr_keyed_setter({enum_type_name});"
  648. )
  649. result.append(
  650. f"\t_method_bindings.keyed_getter = internal::gdextension_interface_variant_get_ptr_keyed_getter({enum_type_name});"
  651. )
  652. result.append(
  653. f"\t_method_bindings.keyed_checker = internal::gdextension_interface_variant_get_ptr_keyed_checker({enum_type_name});"
  654. )
  655. if "operators" in builtin_api:
  656. for operator in builtin_api["operators"]:
  657. if "right_type" in operator:
  658. if operator["right_type"] == "Variant":
  659. right_type_variant_type = "GDEXTENSION_VARIANT_TYPE_NIL"
  660. else:
  661. right_type_variant_type = (
  662. f"GDEXTENSION_VARIANT_TYPE_{camel_to_snake(operator['right_type']).upper()}"
  663. )
  664. result.append(
  665. f'\t_method_bindings.operator_{get_operator_id_name(operator["name"])}_{operator["right_type"]} = internal::gdextension_interface_variant_get_ptr_operator_evaluator(GDEXTENSION_VARIANT_OP_{get_operator_id_name(operator["name"]).upper()}, {enum_type_name}, {right_type_variant_type});'
  666. )
  667. else:
  668. result.append(
  669. f'\t_method_bindings.operator_{get_operator_id_name(operator["name"])} = internal::gdextension_interface_variant_get_ptr_operator_evaluator(GDEXTENSION_VARIANT_OP_{get_operator_id_name(operator["name"]).upper()}, {enum_type_name}, GDEXTENSION_VARIANT_TYPE_NIL);'
  670. )
  671. result.append("}")
  672. result.append("")
  673. copy_constructor_index = -1
  674. if "constructors" in builtin_api:
  675. for constructor in builtin_api["constructors"]:
  676. method_signature = f"{class_name}::{class_name}("
  677. if "arguments" in constructor:
  678. method_signature += make_function_parameters(
  679. constructor["arguments"], include_default=False, for_builtin=True
  680. )
  681. method_signature += ") {"
  682. result.append(method_signature)
  683. method_call = (
  684. f'\tinternal::_call_builtin_constructor(_method_bindings.constructor_{constructor["index"]}, &opaque'
  685. )
  686. if "arguments" in constructor:
  687. if len(constructor["arguments"]) == 1 and constructor["arguments"][0]["type"] == class_name:
  688. copy_constructor_index = constructor["index"]
  689. method_call += ", "
  690. arguments = []
  691. for argument in constructor["arguments"]:
  692. (encode, arg_name) = get_encoded_arg(
  693. argument["name"],
  694. argument["type"],
  695. argument["meta"] if "meta" in argument else None,
  696. )
  697. result += encode
  698. arguments.append(arg_name)
  699. method_call += ", ".join(arguments)
  700. method_call += ");"
  701. result.append(method_call)
  702. result.append("}")
  703. result.append("")
  704. # Move constructor.
  705. result.append(f"{class_name}::{class_name}({class_name} &&other) {{")
  706. if needs_copy_instead_of_move(class_name) and copy_constructor_index >= 0:
  707. result.append(
  708. f"\tinternal::_call_builtin_constructor(_method_bindings.constructor_{copy_constructor_index}, &opaque, &other);"
  709. )
  710. else:
  711. result.append("\tstd::swap(opaque, other.opaque);")
  712. result.append("}")
  713. result.append("")
  714. if builtin_api["has_destructor"]:
  715. result.append(f"{class_name}::~{class_name}() {{")
  716. result.append("\t_method_bindings.destructor(&opaque);")
  717. result.append("}")
  718. result.append("")
  719. method_list = []
  720. if "methods" in builtin_api:
  721. for method in builtin_api["methods"]:
  722. method_list.append(method["name"])
  723. if "is_vararg" in method and method["is_vararg"]:
  724. # Done in the header because of the template.
  725. continue
  726. method_signature = make_signature(class_name, method, for_builtin=True)
  727. result.append(method_signature + "{")
  728. method_call = "\t"
  729. is_ref = False
  730. if "return_type" in method:
  731. return_type = method["return_type"]
  732. if is_enum(return_type):
  733. method_call += f"return ({get_gdextension_type(correct_type(return_type))})internal::_call_builtin_method_ptr_ret<int64_t>("
  734. elif is_pod_type(return_type) or is_variant(return_type):
  735. method_call += f"return internal::_call_builtin_method_ptr_ret<{get_gdextension_type(correct_type(return_type))}>("
  736. elif is_refcounted(return_type):
  737. method_call += f"return Ref<{return_type}>::_gde_internal_constructor(internal::_call_builtin_method_ptr_ret_obj<{return_type}>("
  738. is_ref = True
  739. else:
  740. method_call += f"return internal::_call_builtin_method_ptr_ret_obj<{return_type}>("
  741. else:
  742. method_call += "internal::_call_builtin_method_ptr_no_ret("
  743. method_call += f'_method_bindings.method_{method["name"]}, '
  744. if "is_static" in method and method["is_static"]:
  745. method_call += "nullptr"
  746. else:
  747. method_call += "(GDExtensionTypePtr)&opaque"
  748. if "arguments" in method:
  749. arguments = []
  750. method_call += ", "
  751. for argument in method["arguments"]:
  752. (encode, arg_name) = get_encoded_arg(
  753. argument["name"],
  754. argument["type"],
  755. argument["meta"] if "meta" in argument else None,
  756. )
  757. result += encode
  758. arguments.append(arg_name)
  759. method_call += ", ".join(arguments)
  760. if is_ref:
  761. method_call += ")" # Close Ref<> constructor.
  762. method_call += ");"
  763. result.append(method_call)
  764. result.append("}")
  765. result.append("")
  766. if "members" in builtin_api:
  767. for member in builtin_api["members"]:
  768. if f'get_{member["name"]}' not in method_list:
  769. result.append(f'{correct_type(member["type"])} {class_name}::get_{member["name"]}() const {{')
  770. result.append(
  771. f'\treturn internal::_call_builtin_ptr_getter<{correct_type(member["type"])}>(_method_bindings.member_{member["name"]}_getter, (GDExtensionConstTypePtr)&opaque);'
  772. )
  773. result.append("}")
  774. if f'set_{member["name"]}' not in method_list:
  775. result.append(f'void {class_name}::set_{member["name"]}({type_for_parameter(member["type"])}value) {{')
  776. (encode, arg_name) = get_encoded_arg("value", member["type"], None)
  777. result += encode
  778. result.append(
  779. f'\t_method_bindings.member_{member["name"]}_setter((GDExtensionConstTypePtr)&opaque, (GDExtensionConstTypePtr){arg_name});'
  780. )
  781. result.append("}")
  782. result.append("")
  783. if "operators" in builtin_api:
  784. for operator in builtin_api["operators"]:
  785. if operator["name"] not in ["in", "xor"]:
  786. if "right_type" in operator:
  787. result.append(
  788. f'{correct_type(operator["return_type"])} {class_name}::operator{operator["name"]}({type_for_parameter(operator["right_type"])}other) const {{'
  789. )
  790. (encode, arg_name) = get_encoded_arg("other", operator["right_type"], None)
  791. result += encode
  792. result.append(
  793. 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});'
  794. )
  795. result.append("}")
  796. else:
  797. result.append(
  798. f'{correct_type(operator["return_type"])} {class_name}::operator{operator["name"].replace("unary", "")}() const {{'
  799. )
  800. result.append(
  801. 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);'
  802. )
  803. result.append("}")
  804. result.append("")
  805. # Copy assignment.
  806. if copy_constructor_index >= 0:
  807. result.append(f"{class_name} &{class_name}::operator=(const {class_name} &other) {{")
  808. if builtin_api["has_destructor"]:
  809. result.append("\t_method_bindings.destructor(&opaque);")
  810. (encode, arg_name) = get_encoded_arg(
  811. "other",
  812. class_name,
  813. None,
  814. )
  815. result += encode
  816. result.append(
  817. f"\tinternal::_call_builtin_constructor(_method_bindings.constructor_{copy_constructor_index}, &opaque, {arg_name});"
  818. )
  819. result.append("\treturn *this;")
  820. result.append("}")
  821. result.append("")
  822. # Move assignment.
  823. result.append(f"{class_name} &{class_name}::operator=({class_name} &&other) {{")
  824. if needs_copy_instead_of_move(class_name) and copy_constructor_index >= 0:
  825. result.append(
  826. f"\tinternal::_call_builtin_constructor(_method_bindings.constructor_{copy_constructor_index}, &opaque, &other);"
  827. )
  828. else:
  829. result.append("\tstd::swap(opaque, other.opaque);")
  830. result.append("\treturn *this;")
  831. result.append("}")
  832. result.append("")
  833. result.append("} //namespace godot")
  834. return "\n".join(result)
  835. def generate_engine_classes_bindings(api, output_dir, use_template_get_node):
  836. global engine_classes
  837. global singletons
  838. global native_structures
  839. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  840. source_gen_folder = Path(output_dir) / "src" / "classes"
  841. include_gen_folder.mkdir(parents=True, exist_ok=True)
  842. source_gen_folder.mkdir(parents=True, exist_ok=True)
  843. # First create map of classes and singletons.
  844. for class_api in api["classes"]:
  845. # Generate code for the ClassDB singleton under a different name.
  846. if class_api["name"] == "ClassDB":
  847. class_api["name"] = "ClassDBSingleton"
  848. class_api["alias_for"] = "ClassDB"
  849. engine_classes[class_api["name"]] = class_api["is_refcounted"]
  850. for native_struct in api["native_structures"]:
  851. engine_classes[native_struct["name"]] = False
  852. native_structures.append(native_struct["name"])
  853. for singleton in api["singletons"]:
  854. # Generate code for the ClassDB singleton under a different name.
  855. if singleton["name"] == "ClassDB":
  856. singleton["name"] = "ClassDBSingleton"
  857. singleton["alias_for"] = "ClassDB"
  858. singletons.append(singleton["name"])
  859. for class_api in api["classes"]:
  860. # Check used classes for header include.
  861. used_classes = set()
  862. fully_used_classes = set()
  863. class_name = class_api["name"]
  864. header_filename = include_gen_folder / (camel_to_snake(class_api["name"]) + ".hpp")
  865. source_filename = source_gen_folder / (camel_to_snake(class_api["name"]) + ".cpp")
  866. if "methods" in class_api:
  867. for method in class_api["methods"]:
  868. if "arguments" in method:
  869. for argument in method["arguments"]:
  870. type_name = argument["type"]
  871. if type_name.startswith("const "):
  872. type_name = type_name[6:]
  873. if type_name.endswith("*"):
  874. type_name = type_name[:-1]
  875. if is_included(type_name, class_name):
  876. if type_name.startswith("typedarray::"):
  877. fully_used_classes.add("TypedArray")
  878. array_type_name = type_name.replace("typedarray::", "")
  879. if array_type_name.startswith("const "):
  880. array_type_name = array_type_name[6:]
  881. if array_type_name.endswith("*"):
  882. array_type_name = array_type_name[:-1]
  883. if is_included(array_type_name, class_name):
  884. if is_enum(array_type_name):
  885. fully_used_classes.add(get_enum_class(array_type_name))
  886. elif "default_value" in argument:
  887. fully_used_classes.add(array_type_name)
  888. else:
  889. used_classes.add(array_type_name)
  890. elif is_enum(type_name):
  891. fully_used_classes.add(get_enum_class(type_name))
  892. elif "default_value" in argument:
  893. fully_used_classes.add(type_name)
  894. else:
  895. used_classes.add(type_name)
  896. if is_refcounted(type_name):
  897. fully_used_classes.add("Ref")
  898. if "return_value" in method:
  899. type_name = method["return_value"]["type"]
  900. if type_name.startswith("const "):
  901. type_name = type_name[6:]
  902. if type_name.endswith("*"):
  903. type_name = type_name[:-1]
  904. if is_included(type_name, class_name):
  905. if type_name.startswith("typedarray::"):
  906. fully_used_classes.add("TypedArray")
  907. array_type_name = type_name.replace("typedarray::", "")
  908. if array_type_name.startswith("const "):
  909. array_type_name = array_type_name[6:]
  910. if array_type_name.endswith("*"):
  911. array_type_name = array_type_name[:-1]
  912. if is_included(array_type_name, class_name):
  913. if is_enum(array_type_name):
  914. fully_used_classes.add(get_enum_class(array_type_name))
  915. elif is_variant(array_type_name):
  916. fully_used_classes.add(array_type_name)
  917. else:
  918. used_classes.add(array_type_name)
  919. elif is_enum(type_name):
  920. fully_used_classes.add(get_enum_class(type_name))
  921. elif is_variant(type_name):
  922. fully_used_classes.add(type_name)
  923. else:
  924. used_classes.add(type_name)
  925. if is_refcounted(type_name):
  926. fully_used_classes.add("Ref")
  927. if "members" in class_api:
  928. for member in class_api["members"]:
  929. if is_included(member["type"], class_name):
  930. if is_enum(member["type"]):
  931. fully_used_classes.add(get_enum_class(member["type"]))
  932. else:
  933. used_classes.add(member["type"])
  934. if is_refcounted(member["type"]):
  935. fully_used_classes.add("Ref")
  936. if "inherits" in class_api:
  937. if is_included(class_api["inherits"], class_name):
  938. fully_used_classes.add(class_api["inherits"])
  939. if is_refcounted(class_api["name"]):
  940. fully_used_classes.add("Ref")
  941. else:
  942. fully_used_classes.add("Wrapped")
  943. # In order to ensure that PtrToArg specializations for native structs are
  944. # always used, let's move any of them into 'fully_used_classes'.
  945. for type_name in used_classes:
  946. if is_struct_type(type_name) and not is_included_struct_type(type_name):
  947. fully_used_classes.add(type_name)
  948. for type_name in fully_used_classes:
  949. if type_name in used_classes:
  950. used_classes.remove(type_name)
  951. used_classes = list(used_classes)
  952. used_classes.sort()
  953. fully_used_classes = list(fully_used_classes)
  954. fully_used_classes.sort()
  955. with header_filename.open("w+", encoding="utf-8") as header_file:
  956. header_file.write(
  957. generate_engine_class_header(class_api, used_classes, fully_used_classes, use_template_get_node)
  958. )
  959. with source_filename.open("w+", encoding="utf-8") as source_file:
  960. source_file.write(
  961. generate_engine_class_source(class_api, used_classes, fully_used_classes, use_template_get_node)
  962. )
  963. for native_struct in api["native_structures"]:
  964. struct_name = native_struct["name"]
  965. snake_struct_name = camel_to_snake(struct_name)
  966. header_filename = include_gen_folder / (snake_struct_name + ".hpp")
  967. result = []
  968. add_header(f"{snake_struct_name}.hpp", result)
  969. header_guard = f"GODOT_CPP_{snake_struct_name.upper()}_HPP"
  970. result.append(f"#ifndef {header_guard}")
  971. result.append(f"#define {header_guard}")
  972. used_classes = []
  973. expanded_format = native_struct["format"].replace("(", " ").replace(")", ";").replace(",", ";")
  974. for field in expanded_format.split(";"):
  975. field_type = field.strip().split(" ")[0].split("::")[0]
  976. if field_type != "" and not is_included_type(field_type) and not is_pod_type(field_type):
  977. if not field_type in used_classes:
  978. used_classes.append(field_type)
  979. result.append("")
  980. for included in used_classes:
  981. result.append(f"#include <godot_cpp/{get_include_path(included)}>")
  982. if len(used_classes) == 0:
  983. result.append("#include <godot_cpp/core/method_ptrcall.hpp>")
  984. result.append("")
  985. result.append("namespace godot {")
  986. result.append("")
  987. result.append(f"struct {struct_name} {{")
  988. for field in native_struct["format"].split(";"):
  989. if field != "":
  990. result.append(f"\t{field};")
  991. result.append("};")
  992. result.append("")
  993. result.append(f"GDVIRTUAL_NATIVE_PTR({struct_name});")
  994. result.append("")
  995. result.append("} // namespace godot")
  996. result.append("")
  997. result.append(f"#endif // ! {header_guard}")
  998. with header_filename.open("w+", encoding="utf-8") as header_file:
  999. header_file.write("\n".join(result))
  1000. def generate_engine_class_header(class_api, used_classes, fully_used_classes, use_template_get_node):
  1001. global singletons
  1002. result = []
  1003. class_name = class_api["name"]
  1004. snake_class_name = camel_to_snake(class_name).upper()
  1005. is_singleton = class_name in singletons
  1006. add_header(f"{snake_class_name.lower()}.hpp", result)
  1007. header_guard = f"GODOT_CPP_{snake_class_name}_HPP"
  1008. result.append(f"#ifndef {header_guard}")
  1009. result.append(f"#define {header_guard}")
  1010. result.append("")
  1011. for included in fully_used_classes:
  1012. if included == "TypedArray":
  1013. result.append("#include <godot_cpp/variant/typed_array.hpp>")
  1014. else:
  1015. result.append(f"#include <godot_cpp/{get_include_path(included)}>")
  1016. if class_name == "EditorPlugin":
  1017. result.append("#include <godot_cpp/classes/editor_plugin_registration.hpp>")
  1018. if len(fully_used_classes) > 0:
  1019. result.append("")
  1020. if class_name != "Object" and class_name != "ClassDBSingleton":
  1021. result.append("#include <godot_cpp/core/class_db.hpp>")
  1022. result.append("")
  1023. result.append("#include <type_traits>")
  1024. result.append("")
  1025. result.append("namespace godot {")
  1026. result.append("")
  1027. for type_name in used_classes:
  1028. if is_struct_type(type_name):
  1029. result.append(f"struct {type_name};")
  1030. else:
  1031. result.append(f"class {type_name};")
  1032. if len(used_classes) > 0:
  1033. result.append("")
  1034. inherits = class_api["inherits"] if "inherits" in class_api else "Wrapped"
  1035. result.append(f"class {class_name} : public {inherits} {{")
  1036. if "alias_for" in class_api:
  1037. result.append(f"\tGDEXTENSION_CLASS_ALIAS({class_name}, {class_api['alias_for']}, {inherits})")
  1038. else:
  1039. result.append(f"\tGDEXTENSION_CLASS({class_name}, {inherits})")
  1040. result.append("")
  1041. result.append("public:")
  1042. result.append("")
  1043. if "enums" in class_api:
  1044. for enum_api in class_api["enums"]:
  1045. result.append(f'\tenum {enum_api["name"]} {{')
  1046. for value in enum_api["values"]:
  1047. result.append(f'\t\t{value["name"]} = {value["value"]},')
  1048. result.append("\t};")
  1049. result.append("")
  1050. if "constants" in class_api:
  1051. for value in class_api["constants"]:
  1052. if "type" not in value:
  1053. value["type"] = "int"
  1054. result.append(f'\tstatic const {value["type"]} {value["name"]} = {value["value"]};')
  1055. result.append("")
  1056. if is_singleton:
  1057. result.append(f"\tstatic {class_name} *get_singleton();")
  1058. result.append("")
  1059. if "methods" in class_api:
  1060. for method in class_api["methods"]:
  1061. if method["is_virtual"]:
  1062. # Will be done later.
  1063. continue
  1064. vararg = "is_vararg" in method and method["is_vararg"]
  1065. method_signature = "\t"
  1066. if vararg:
  1067. method_signature += "private: "
  1068. method_signature += make_signature(
  1069. class_name, method, for_header=True, use_template_get_node=use_template_get_node
  1070. )
  1071. result.append(method_signature + ";")
  1072. if vararg:
  1073. # Add templated version.
  1074. result += make_varargs_template(method)
  1075. # Virtuals now.
  1076. for method in class_api["methods"]:
  1077. if not method["is_virtual"]:
  1078. continue
  1079. method_signature = "\t"
  1080. method_signature += make_signature(
  1081. class_name, method, for_header=True, use_template_get_node=use_template_get_node
  1082. )
  1083. result.append(method_signature + ";")
  1084. result.append("protected:")
  1085. # T is the custom class we want to register (from which the call initiates, going up the inheritance chain),
  1086. # B is its base class (can be a custom class too, that's why we pass it).
  1087. result.append("\ttemplate <class T, class B>")
  1088. result.append("\tstatic void register_virtuals() {")
  1089. if class_name != "Object":
  1090. result.append(f"\t\t{inherits}::register_virtuals<T, B>();")
  1091. if "methods" in class_api:
  1092. for method in class_api["methods"]:
  1093. if not method["is_virtual"]:
  1094. continue
  1095. method_name = escape_identifier(method["name"])
  1096. result.append(
  1097. # If the method is different from the base class, it means T overrides it, so it needs to be bound.
  1098. # Note that with an `if constexpr`, the code inside the `if` will not even be compiled if the
  1099. # condition returns false (in such cases it can't compile due to ambiguity).
  1100. f"\t\tif constexpr (!std::is_same_v<decltype(&B::{method_name}),decltype(&T::{method_name})>) {{"
  1101. )
  1102. result.append(f"\t\t\tBIND_VIRTUAL_METHOD(T, {method_name});")
  1103. result.append("\t\t}")
  1104. result.append("\t}")
  1105. result.append("")
  1106. result.append("public:")
  1107. # Special cases.
  1108. if class_name == "XMLParser":
  1109. result.append("\tError _open_buffer(const uint8_t *p_buffer, size_t p_size);")
  1110. if class_name == "FileAccess":
  1111. result.append("\tuint64_t get_buffer(uint8_t *p_dst, uint64_t p_length) const;")
  1112. result.append("\tvoid store_buffer(const uint8_t *p_src, uint64_t p_length);")
  1113. if class_name == "WorkerThreadPool":
  1114. result.append("\tenum {")
  1115. result.append("\tINVALID_TASK_ID = -1")
  1116. result.append("\t};")
  1117. result.append("\ttypedef int64_t TaskID;")
  1118. result.append("\ttypedef int64_t GroupID;")
  1119. result.append(
  1120. "\tTaskID add_native_task(void (*p_func)(void *), void *p_userdata, bool p_high_priority = false, const String &p_description = String());"
  1121. )
  1122. result.append(
  1123. "\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());"
  1124. )
  1125. if class_name == "Object":
  1126. result.append("")
  1127. result.append("\ttemplate<class T>")
  1128. result.append("\tstatic T *cast_to(Object *p_object);")
  1129. result.append("\ttemplate<class T>")
  1130. result.append("\tstatic const T *cast_to(const Object *p_object);")
  1131. result.append("\tvirtual ~Object() = default;")
  1132. elif use_template_get_node and class_name == "Node":
  1133. result.append("\ttemplate<class T>")
  1134. result.append(
  1135. "\tT *get_node(const NodePath &p_path) const { return Object::cast_to<T>(get_node_internal(p_path)); }"
  1136. )
  1137. result.append("")
  1138. result.append("};")
  1139. result.append("")
  1140. result.append("} // namespace godot")
  1141. result.append("")
  1142. if "enums" in class_api and class_name != "Object":
  1143. for enum_api in class_api["enums"]:
  1144. if enum_api["is_bitfield"]:
  1145. result.append(f'VARIANT_BITFIELD_CAST({class_name}::{enum_api["name"]});')
  1146. else:
  1147. result.append(f'VARIANT_ENUM_CAST({class_name}::{enum_api["name"]});')
  1148. result.append("")
  1149. if class_name == "ClassDBSingleton":
  1150. result.append("#define CLASSDB_SINGLETON_FORWARD_METHODS \\")
  1151. for method in class_api["methods"]:
  1152. # ClassDBSingleton shouldn't have any static or vararg methods, but if some appear later, lets skip them.
  1153. if vararg:
  1154. continue
  1155. if "is_static" in method and method["is_static"]:
  1156. continue
  1157. method_signature = "\tstatic "
  1158. if "return_type" in method:
  1159. method_signature += f'{correct_type(method["return_type"])} '
  1160. elif "return_value" in method:
  1161. method_signature += (
  1162. correct_type(method["return_value"]["type"], method["return_value"].get("meta", None)) + " "
  1163. )
  1164. else:
  1165. method_signature += "void "
  1166. method_signature += f'{method["name"]}('
  1167. method_arguments = []
  1168. if "arguments" in method:
  1169. method_arguments = method["arguments"]
  1170. method_signature += make_function_parameters(
  1171. method_arguments, include_default=True, for_builtin=True, is_vararg=False
  1172. )
  1173. method_signature += ") { \\"
  1174. result.append(method_signature)
  1175. method_body = "\t\t"
  1176. if "return_type" in method or "return_value" in method:
  1177. method_body += "return "
  1178. method_body += f'ClassDBSingleton::get_singleton()->{method["name"]}('
  1179. method_body += ", ".join(map(lambda x: escape_identifier(x["name"]), method_arguments))
  1180. method_body += "); \\"
  1181. result.append(method_body)
  1182. result.append("\t} \\")
  1183. result.append("\t;")
  1184. result.append("")
  1185. result.append(f"#endif // ! {header_guard}")
  1186. return "\n".join(result)
  1187. def generate_engine_class_source(class_api, used_classes, fully_used_classes, use_template_get_node):
  1188. global singletons
  1189. result = []
  1190. class_name = class_api["name"]
  1191. snake_class_name = camel_to_snake(class_name)
  1192. is_singleton = class_name in singletons
  1193. add_header(f"{snake_class_name}.cpp", result)
  1194. result.append(f"#include <godot_cpp/classes/{snake_class_name}.hpp>")
  1195. result.append("")
  1196. result.append("#include <godot_cpp/core/engine_ptrcall.hpp>")
  1197. result.append("#include <godot_cpp/core/error_macros.hpp>")
  1198. result.append("")
  1199. for included in used_classes:
  1200. result.append(f"#include <godot_cpp/{get_include_path(included)}>")
  1201. if len(used_classes) > 0:
  1202. result.append("")
  1203. result.append("namespace godot {")
  1204. result.append("")
  1205. if is_singleton:
  1206. result.append(f"{class_name} *{class_name}::get_singleton() {{")
  1207. # We assume multi-threaded access is OK because each assignment will assign the same value every time
  1208. result.append(f"\tstatic {class_name} *singleton = nullptr;")
  1209. result.append("\tif (unlikely(singleton == nullptr)) {")
  1210. result.append(
  1211. f"\t\tGDExtensionObjectPtr singleton_obj = internal::gdextension_interface_global_get_singleton({class_name}::get_class_static()._native_ptr());"
  1212. )
  1213. result.append("#ifdef DEBUG_ENABLED")
  1214. result.append("\t\tERR_FAIL_NULL_V(singleton_obj, nullptr);")
  1215. result.append("#endif // DEBUG_ENABLED")
  1216. result.append(
  1217. f"\t\tsingleton = reinterpret_cast<{class_name} *>(internal::gdextension_interface_object_get_instance_binding(singleton_obj, internal::token, &{class_name}::_gde_binding_callbacks));"
  1218. )
  1219. result.append("#ifdef DEBUG_ENABLED")
  1220. result.append("\t\tERR_FAIL_NULL_V(singleton, nullptr);")
  1221. result.append("#endif // DEBUG_ENABLED")
  1222. result.append("\t}")
  1223. result.append("\treturn singleton;")
  1224. result.append("}")
  1225. result.append("")
  1226. if "methods" in class_api:
  1227. for method in class_api["methods"]:
  1228. if method["is_virtual"]:
  1229. # Will be done later
  1230. continue
  1231. vararg = "is_vararg" in method and method["is_vararg"]
  1232. # Method signature.
  1233. method_signature = make_signature(class_name, method, use_template_get_node=use_template_get_node)
  1234. result.append(method_signature + " {")
  1235. # Method body.
  1236. result.append(
  1237. f'\tstatic GDExtensionMethodBindPtr _gde_method_bind = internal::gdextension_interface_classdb_get_method_bind({class_name}::get_class_static()._native_ptr(), StringName("{method["name"]}")._native_ptr(), {method["hash"]});'
  1238. )
  1239. method_call = "\t"
  1240. has_return = "return_value" in method and method["return_value"]["type"] != "void"
  1241. if has_return:
  1242. result.append(
  1243. f'\tCHECK_METHOD_BIND_RET(_gde_method_bind, {get_default_value_for_type(method["return_value"]["type"])});'
  1244. )
  1245. else:
  1246. result.append("\tCHECK_METHOD_BIND(_gde_method_bind);")
  1247. is_ref = False
  1248. if not vararg:
  1249. if has_return:
  1250. return_type = method["return_value"]["type"]
  1251. meta_type = method["return_value"]["meta"] if "meta" in method["return_value"] else None
  1252. if is_enum(return_type):
  1253. if method["is_static"]:
  1254. method_call += f"return ({get_gdextension_type(correct_type(return_type, meta_type))})internal::_call_native_mb_ret<int64_t>(_gde_method_bind, nullptr"
  1255. else:
  1256. method_call += f"return ({get_gdextension_type(correct_type(return_type, meta_type))})internal::_call_native_mb_ret<int64_t>(_gde_method_bind, _owner"
  1257. elif is_pod_type(return_type) or is_variant(return_type):
  1258. if method["is_static"]:
  1259. method_call += f"return internal::_call_native_mb_ret<{get_gdextension_type(correct_type(return_type, meta_type))}>(_gde_method_bind, nullptr"
  1260. else:
  1261. method_call += f"return internal::_call_native_mb_ret<{get_gdextension_type(correct_type(return_type, meta_type))}>(_gde_method_bind, _owner"
  1262. elif is_refcounted(return_type):
  1263. if method["is_static"]:
  1264. method_call += f"return Ref<{return_type}>::_gde_internal_constructor(internal::_call_native_mb_ret_obj<{return_type}>(_gde_method_bind, nullptr"
  1265. else:
  1266. method_call += f"return Ref<{return_type}>::_gde_internal_constructor(internal::_call_native_mb_ret_obj<{return_type}>(_gde_method_bind, _owner"
  1267. is_ref = True
  1268. else:
  1269. if method["is_static"]:
  1270. method_call += (
  1271. f"return internal::_call_native_mb_ret_obj<{return_type}>(_gde_method_bind, nullptr"
  1272. )
  1273. else:
  1274. method_call += (
  1275. f"return internal::_call_native_mb_ret_obj<{return_type}>(_gde_method_bind, _owner"
  1276. )
  1277. else:
  1278. if method["is_static"]:
  1279. method_call += "internal::_call_native_mb_no_ret(_gde_method_bind, nullptr"
  1280. else:
  1281. method_call += "internal::_call_native_mb_no_ret(_gde_method_bind, _owner"
  1282. if "arguments" in method:
  1283. method_call += ", "
  1284. arguments = []
  1285. for argument in method["arguments"]:
  1286. (encode, arg_name) = get_encoded_arg(
  1287. argument["name"],
  1288. argument["type"],
  1289. argument["meta"] if "meta" in argument else None,
  1290. )
  1291. result += encode
  1292. arguments.append(arg_name)
  1293. method_call += ", ".join(arguments)
  1294. else: # vararg.
  1295. result.append("\tGDExtensionCallError error;")
  1296. result.append("\tVariant ret;")
  1297. method_call += "internal::gdextension_interface_object_method_bind_call(_gde_method_bind, _owner, reinterpret_cast<GDExtensionConstVariantPtr *>(args), arg_count, &ret, &error"
  1298. if is_ref:
  1299. method_call += ")" # Close Ref<> constructor.
  1300. method_call += ");"
  1301. result.append(method_call)
  1302. if vararg and ("return_value" in method and method["return_value"]["type"] != "void"):
  1303. return_type = get_enum_fullname(method["return_value"]["type"])
  1304. if return_type != "Variant":
  1305. result.append(f"\treturn VariantCaster<{return_type}>::cast(ret);")
  1306. else:
  1307. result.append("\treturn ret;")
  1308. result.append("}")
  1309. result.append("")
  1310. # Virtuals now.
  1311. for method in class_api["methods"]:
  1312. if not method["is_virtual"]:
  1313. continue
  1314. method_signature = make_signature(class_name, method, use_template_get_node=use_template_get_node)
  1315. method_signature += " {"
  1316. if "return_value" in method and correct_type(method["return_value"]["type"]) != "void":
  1317. result.append(method_signature)
  1318. result.append(f'\treturn {get_default_value_for_type(method["return_value"]["type"])};')
  1319. result.append("}")
  1320. else:
  1321. method_signature += "}"
  1322. result.append(method_signature)
  1323. result.append("")
  1324. result.append("")
  1325. result.append("} // namespace godot ")
  1326. return "\n".join(result)
  1327. def generate_global_constants(api, output_dir):
  1328. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  1329. source_gen_folder = Path(output_dir) / "src" / "classes"
  1330. include_gen_folder.mkdir(parents=True, exist_ok=True)
  1331. source_gen_folder.mkdir(parents=True, exist_ok=True)
  1332. # Generate header
  1333. header = []
  1334. add_header("global_constants.hpp", header)
  1335. header_filename = include_gen_folder / "global_constants.hpp"
  1336. header_guard = "GODOT_CPP_GLOBAL_CONSTANTS_HPP"
  1337. header.append(f"#ifndef {header_guard}")
  1338. header.append(f"#define {header_guard}")
  1339. header.append("")
  1340. header.append("namespace godot {")
  1341. header.append("")
  1342. for constant in api["global_constants"]:
  1343. header.append(f'\tconst int64_t {escape_identifier(constant["name"])} = {constant["value"]};')
  1344. header.append("")
  1345. for enum_def in api["global_enums"]:
  1346. if enum_def["name"].startswith("Variant."):
  1347. continue
  1348. header.append(f'\tenum {enum_def["name"]} {{')
  1349. for value in enum_def["values"]:
  1350. header.append(f'\t\t{value["name"]} = {value["value"]},')
  1351. header.append("\t};")
  1352. header.append("")
  1353. header.append("} // namespace godot")
  1354. header.append("")
  1355. header.append(f"#endif // ! {header_guard}")
  1356. with header_filename.open("w+", encoding="utf-8") as header_file:
  1357. header_file.write("\n".join(header))
  1358. def generate_version_header(api, output_dir):
  1359. header = []
  1360. header_filename = "version.hpp"
  1361. add_header(header_filename, header)
  1362. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "core"
  1363. include_gen_folder.mkdir(parents=True, exist_ok=True)
  1364. header_file_path = include_gen_folder / header_filename
  1365. header_guard = "GODOT_CPP_VERSION_HPP"
  1366. header.append(f"#ifndef {header_guard}")
  1367. header.append(f"#define {header_guard}")
  1368. header.append("")
  1369. header.append(f"#define GODOT_VERSION_MAJOR {api['header']['version_major']}")
  1370. header.append(f"#define GODOT_VERSION_MINOR {api['header']['version_minor']}")
  1371. header.append(f"#define GODOT_VERSION_PATCH {api['header']['version_patch']}")
  1372. header.append(f"#define GODOT_VERSION_STATUS \"{api['header']['version_status']}\"")
  1373. header.append(f"#define GODOT_VERSION_BUILD \"{api['header']['version_build']}\"")
  1374. header.append("")
  1375. header.append(f"#endif // {header_guard}")
  1376. header.append("")
  1377. with header_file_path.open("w+", encoding="utf-8") as header_file:
  1378. header_file.write("\n".join(header))
  1379. def generate_global_constant_binds(api, output_dir):
  1380. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  1381. source_gen_folder = Path(output_dir) / "src" / "classes"
  1382. include_gen_folder.mkdir(parents=True, exist_ok=True)
  1383. source_gen_folder.mkdir(parents=True, exist_ok=True)
  1384. # Generate header
  1385. header = []
  1386. add_header("global_constants_binds.hpp", header)
  1387. header_filename = include_gen_folder / "global_constants_binds.hpp"
  1388. header_guard = "GODOT_CPP_GLOBAL_CONSTANTS_BINDS_HPP"
  1389. header.append(f"#ifndef {header_guard}")
  1390. header.append(f"#define {header_guard}")
  1391. header.append("")
  1392. header.append("#include <godot_cpp/classes/global_constants.hpp>")
  1393. header.append("")
  1394. for enum_def in api["global_enums"]:
  1395. if enum_def["name"].startswith("Variant."):
  1396. continue
  1397. if enum_def["is_bitfield"]:
  1398. header.append(f'VARIANT_BITFIELD_CAST({enum_def["name"]});')
  1399. else:
  1400. header.append(f'VARIANT_ENUM_CAST({enum_def["name"]});')
  1401. # Variant::Type is not a global enum, but only one line, it is worth to place in this file instead of creating new file.
  1402. header.append(f"VARIANT_ENUM_CAST(godot::Variant::Type);")
  1403. header.append("")
  1404. header.append(f"#endif // ! {header_guard}")
  1405. with header_filename.open("w+", encoding="utf-8") as header_file:
  1406. header_file.write("\n".join(header))
  1407. def generate_utility_functions(api, output_dir):
  1408. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "variant"
  1409. source_gen_folder = Path(output_dir) / "src" / "variant"
  1410. include_gen_folder.mkdir(parents=True, exist_ok=True)
  1411. source_gen_folder.mkdir(parents=True, exist_ok=True)
  1412. # Generate header.
  1413. header = []
  1414. add_header("utility_functions.hpp", header)
  1415. header_filename = include_gen_folder / "utility_functions.hpp"
  1416. header_guard = "GODOT_CPP_UTILITY_FUNCTIONS_HPP"
  1417. header.append(f"#ifndef {header_guard}")
  1418. header.append(f"#define {header_guard}")
  1419. header.append("")
  1420. header.append("#include <godot_cpp/variant/builtin_types.hpp>")
  1421. header.append("#include <godot_cpp/variant/variant.hpp>")
  1422. header.append("")
  1423. header.append("#include <array>")
  1424. header.append("")
  1425. header.append("namespace godot {")
  1426. header.append("")
  1427. header.append("class UtilityFunctions {")
  1428. header.append("public:")
  1429. for function in api["utility_functions"]:
  1430. vararg = "is_vararg" in function and function["is_vararg"]
  1431. function_signature = "\t"
  1432. function_signature += make_signature("UtilityFunctions", function, for_header=True, static=True)
  1433. header.append(function_signature + ";")
  1434. if vararg:
  1435. # Add templated version.
  1436. header += make_varargs_template(function, static=True)
  1437. header.append("};")
  1438. header.append("")
  1439. header.append("} // namespace godot")
  1440. header.append("")
  1441. header.append(f"#endif // ! {header_guard}")
  1442. with header_filename.open("w+", encoding="utf-8") as header_file:
  1443. header_file.write("\n".join(header))
  1444. # Generate source.
  1445. source = []
  1446. add_header("utility_functions.cpp", source)
  1447. source_filename = source_gen_folder / "utility_functions.cpp"
  1448. source.append("#include <godot_cpp/variant/utility_functions.hpp>")
  1449. source.append("")
  1450. source.append("#include <godot_cpp/core/error_macros.hpp>")
  1451. source.append("#include <godot_cpp/core/engine_ptrcall.hpp>")
  1452. source.append("")
  1453. source.append("namespace godot {")
  1454. source.append("")
  1455. for function in api["utility_functions"]:
  1456. vararg = "is_vararg" in function and function["is_vararg"]
  1457. function_signature = make_signature("UtilityFunctions", function)
  1458. source.append(function_signature + " {")
  1459. # Function body.
  1460. source.append(
  1461. f'\tstatic GDExtensionPtrUtilityFunction _gde_function = internal::gdextension_interface_variant_get_ptr_utility_function(StringName("{function["name"]}")._native_ptr(), {function["hash"]});'
  1462. )
  1463. has_return = "return_type" in function and function["return_type"] != "void"
  1464. if has_return:
  1465. source.append(
  1466. f'\tCHECK_METHOD_BIND_RET(_gde_function, {get_default_value_for_type(function["return_type"])});'
  1467. )
  1468. else:
  1469. source.append("\tCHECK_METHOD_BIND(_gde_function);")
  1470. function_call = "\t"
  1471. if not vararg:
  1472. if has_return:
  1473. function_call += "return "
  1474. if function["return_type"] == "Object":
  1475. function_call += "internal::_call_utility_ret_obj(_gde_function"
  1476. else:
  1477. function_call += f'internal::_call_utility_ret<{get_gdextension_type(correct_type(function["return_type"]))}>(_gde_function'
  1478. else:
  1479. function_call += "internal::_call_utility_no_ret(_gde_function"
  1480. if "arguments" in function:
  1481. function_call += ", "
  1482. arguments = []
  1483. for argument in function["arguments"]:
  1484. (encode, arg_name) = get_encoded_arg(
  1485. argument["name"],
  1486. argument["type"],
  1487. argument["meta"] if "meta" in argument else None,
  1488. )
  1489. source += encode
  1490. arguments.append(arg_name)
  1491. function_call += ", ".join(arguments)
  1492. else:
  1493. if has_return:
  1494. source.append(f'\t{get_gdextension_type(correct_type(function["return_type"]))} ret;')
  1495. else:
  1496. source.append("\tVariant ret;")
  1497. function_call += "_gde_function(&ret, reinterpret_cast<GDExtensionConstVariantPtr *>(args), arg_count"
  1498. function_call += ");"
  1499. source.append(function_call)
  1500. if vararg and has_return:
  1501. source.append("\treturn ret;")
  1502. source.append("}")
  1503. source.append("")
  1504. source.append("} // namespace godot")
  1505. with source_filename.open("w+", encoding="utf-8") as source_file:
  1506. source_file.write("\n".join(source))
  1507. # Helper functions.
  1508. def camel_to_snake(name):
  1509. name = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
  1510. name = re.sub("([a-z0-9])([A-Z])", r"\1_\2", name)
  1511. return name.replace("2_D", "2D").replace("3_D", "3D").lower()
  1512. def make_function_parameters(parameters, include_default=False, for_builtin=False, is_vararg=False):
  1513. signature = []
  1514. for index, par in enumerate(parameters):
  1515. parameter = type_for_parameter(par["type"], par["meta"] if "meta" in par else None)
  1516. parameter_name = escape_identifier(par["name"])
  1517. if len(parameter_name) == 0:
  1518. parameter_name = "arg_" + str(index + 1)
  1519. parameter += parameter_name
  1520. if include_default and "default_value" in par and (not for_builtin or par["type"] != "Variant"):
  1521. parameter += " = "
  1522. if is_enum(par["type"]):
  1523. parameter_type = correct_type(par["type"])
  1524. if parameter_type == "void":
  1525. parameter_type = "Variant"
  1526. parameter += f"({parameter_type})"
  1527. parameter += correct_default_value(par["default_value"], par["type"])
  1528. signature.append(parameter)
  1529. if is_vararg:
  1530. signature.append("const Args&... args")
  1531. return ", ".join(signature)
  1532. def type_for_parameter(type_name, meta=None):
  1533. if type_name == "void":
  1534. return "Variant "
  1535. elif is_pod_type(type_name) and type_name != "Nil" or is_enum(type_name):
  1536. return f"{correct_type(type_name, meta)} "
  1537. elif is_variant(type_name) or is_refcounted(type_name):
  1538. return f"const {correct_type(type_name)} &"
  1539. else:
  1540. return f"{correct_type(type_name)}"
  1541. def get_include_path(type_name):
  1542. base_dir = ""
  1543. if type_name == "Object":
  1544. base_dir = "core"
  1545. elif is_variant(type_name):
  1546. base_dir = "variant"
  1547. else:
  1548. base_dir = "classes"
  1549. return f"{base_dir}/{camel_to_snake(type_name)}.hpp"
  1550. def get_encoded_arg(arg_name, type_name, type_meta):
  1551. result = []
  1552. name = escape_identifier(arg_name)
  1553. arg_type = correct_type(type_name)
  1554. if is_pod_type(arg_type):
  1555. result.append(f"\t{get_gdextension_type(arg_type)} {name}_encoded;")
  1556. result.append(f"\tPtrToArg<{correct_type(type_name)}>::encode({name}, &{name}_encoded);")
  1557. name = f"&{name}_encoded"
  1558. elif is_engine_class(type_name):
  1559. # `{name}` is a C++ wrapper, it contains a field which is the object's pointer Godot expects.
  1560. # We have to check `nullptr` because when the caller sends `nullptr`, the wrapper itself will be null.
  1561. name = f"({name} != nullptr ? &{name}->_owner : nullptr)"
  1562. else:
  1563. name = f"&{name}"
  1564. return (result, name)
  1565. def make_signature(
  1566. class_name, function_data, for_header=False, use_template_get_node=True, for_builtin=False, static=False
  1567. ):
  1568. function_signature = ""
  1569. is_vararg = "is_vararg" in function_data and function_data["is_vararg"]
  1570. if for_header:
  1571. if "is_virtual" in function_data and function_data["is_virtual"]:
  1572. function_signature += "virtual "
  1573. if is_vararg:
  1574. function_signature += "private: "
  1575. if static:
  1576. function_signature += "static "
  1577. return_type = "void"
  1578. return_meta = None
  1579. if "return_type" in function_data:
  1580. return_type = correct_type(function_data["return_type"])
  1581. elif "return_value" in function_data:
  1582. return_type = function_data["return_value"]["type"]
  1583. return_meta = function_data["return_value"]["meta"] if "meta" in function_data["return_value"] else None
  1584. function_signature += correct_type(
  1585. return_type,
  1586. return_meta,
  1587. )
  1588. if not function_signature.endswith("*"):
  1589. function_signature += " "
  1590. if not for_header:
  1591. function_signature += f"{class_name}::"
  1592. function_signature += escape_identifier(function_data["name"])
  1593. if is_vararg or (
  1594. not for_builtin and use_template_get_node and class_name == "Node" and function_data["name"] == "get_node"
  1595. ):
  1596. function_signature += "_internal"
  1597. function_signature += "("
  1598. arguments = function_data["arguments"] if "arguments" in function_data else []
  1599. if not is_vararg:
  1600. function_signature += make_function_parameters(arguments, for_header, for_builtin, is_vararg)
  1601. else:
  1602. function_signature += "const Variant **args, GDExtensionInt arg_count"
  1603. function_signature += ")"
  1604. if "is_static" in function_data and function_data["is_static"] and for_header:
  1605. function_signature = "static " + function_signature
  1606. elif "is_const" in function_data and function_data["is_const"]:
  1607. function_signature += " const"
  1608. return function_signature
  1609. def make_varargs_template(function_data, static=False):
  1610. result = []
  1611. function_signature = "\tpublic: template<class... Args> "
  1612. if static:
  1613. function_signature += "static "
  1614. return_type = "void"
  1615. return_meta = None
  1616. if "return_type" in function_data:
  1617. return_type = correct_type(function_data["return_type"])
  1618. elif "return_value" in function_data:
  1619. return_type = function_data["return_value"]["type"]
  1620. return_meta = function_data["return_value"]["meta"] if "meta" in function_data["return_value"] else None
  1621. function_signature += correct_type(
  1622. return_type,
  1623. return_meta,
  1624. )
  1625. if not function_signature.endswith("*"):
  1626. function_signature += " "
  1627. function_signature += f'{escape_identifier(function_data["name"])}'
  1628. method_arguments = []
  1629. if "arguments" in function_data:
  1630. method_arguments = function_data["arguments"]
  1631. function_signature += "("
  1632. is_vararg = "is_vararg" in function_data and function_data["is_vararg"]
  1633. function_signature += make_function_parameters(method_arguments, include_default=True, is_vararg=is_vararg)
  1634. function_signature += ")"
  1635. if "is_const" in function_data and function_data["is_const"]:
  1636. function_signature += " const"
  1637. function_signature += " {"
  1638. result.append(function_signature)
  1639. args_array = f"\t\tstd::array<Variant, {len(method_arguments)} + sizeof...(Args)> variant_args {{ "
  1640. for argument in method_arguments:
  1641. if argument["type"] == "Variant":
  1642. args_array += argument["name"]
  1643. else:
  1644. args_array += f'Variant({argument["name"]})'
  1645. args_array += ", "
  1646. args_array += "Variant(args)... };"
  1647. result.append(args_array)
  1648. result.append(f"\t\tstd::array<const Variant *, {len(method_arguments)} + sizeof...(Args)> call_args;")
  1649. result.append("\t\tfor(size_t i = 0; i < variant_args.size(); i++) {")
  1650. result.append("\t\t\tcall_args[i] = &variant_args[i];")
  1651. result.append("\t\t}")
  1652. call_line = "\t\t"
  1653. if return_type != "void":
  1654. call_line += "return "
  1655. call_line += f'{escape_identifier(function_data["name"])}_internal(call_args.data(), variant_args.size());'
  1656. result.append(call_line)
  1657. result.append("\t}")
  1658. return result
  1659. # Engine idiosyncrasies.
  1660. def is_pod_type(type_name):
  1661. """
  1662. Those are types for which no class should be generated.
  1663. """
  1664. return type_name in [
  1665. "Nil",
  1666. "void",
  1667. "bool",
  1668. "real_t",
  1669. "float",
  1670. "double",
  1671. "int",
  1672. "int8_t",
  1673. "uint8_t",
  1674. "int16_t",
  1675. "uint16_t",
  1676. "int32_t",
  1677. "int64_t",
  1678. "uint32_t",
  1679. "uint64_t",
  1680. ]
  1681. def is_included_type(type_name):
  1682. # Types which we already have implemented.
  1683. return is_included_struct_type(type_name) or type_name in ["ObjectID"]
  1684. def is_included_struct_type(type_name):
  1685. # Struct types which we already have implemented.
  1686. return type_name in [
  1687. "AABB",
  1688. "Basis",
  1689. "Color",
  1690. "Plane",
  1691. "Projection",
  1692. "Quaternion",
  1693. "Rect2",
  1694. "Rect2i",
  1695. "Transform2D",
  1696. "Transform3D",
  1697. "Vector2",
  1698. "Vector2i",
  1699. "Vector3",
  1700. "Vector3i",
  1701. "Vector4",
  1702. "Vector4i",
  1703. ]
  1704. def is_packed_array(type_name):
  1705. """
  1706. Those are types for which we add our extra packed array functions.
  1707. """
  1708. return type_name in [
  1709. "PackedByteArray",
  1710. "PackedColorArray",
  1711. "PackedFloat32Array",
  1712. "PackedFloat64Array",
  1713. "PackedInt32Array",
  1714. "PackedInt64Array",
  1715. "PackedStringArray",
  1716. "PackedVector2Array",
  1717. "PackedVector3Array",
  1718. ]
  1719. def needs_copy_instead_of_move(type_name):
  1720. """
  1721. Those are types which need initialised data or we'll get warning spam so need a copy instead of move.
  1722. """
  1723. return type_name in [
  1724. "Dictionary",
  1725. ]
  1726. def is_enum(type_name):
  1727. return type_name.startswith("enum::") or type_name.startswith("bitfield::")
  1728. def is_bitfield(type_name):
  1729. return type_name.startswith("bitfield::")
  1730. def get_enum_class(enum_name: str):
  1731. if "." in enum_name:
  1732. if is_bitfield(enum_name):
  1733. return enum_name.replace("bitfield::", "").split(".")[0]
  1734. else:
  1735. return enum_name.replace("enum::", "").split(".")[0]
  1736. else:
  1737. return "GlobalConstants"
  1738. def get_enum_fullname(enum_name: str):
  1739. if is_bitfield(enum_name):
  1740. return enum_name.replace("bitfield::", "BitField<") + ">"
  1741. else:
  1742. return enum_name.replace("enum::", "")
  1743. def get_enum_name(enum_name: str):
  1744. if is_bitfield(enum_name):
  1745. return enum_name.replace("bitfield::", "").split(".")[-1]
  1746. else:
  1747. return enum_name.replace("enum::", "").split(".")[-1]
  1748. def is_variant(type_name):
  1749. return (
  1750. type_name == "Variant"
  1751. or type_name in builtin_classes
  1752. or type_name == "Nil"
  1753. or type_name.startswith("typedarray::")
  1754. )
  1755. def is_engine_class(type_name):
  1756. global engine_classes
  1757. return type_name == "Object" or type_name in engine_classes
  1758. def is_struct_type(type_name):
  1759. # This is used to determine which keyword to use for forward declarations.
  1760. global native_structures
  1761. return is_included_struct_type(type_name) or type_name in native_structures
  1762. def is_refcounted(type_name):
  1763. return type_name in engine_classes and engine_classes[type_name]
  1764. def is_included(type_name, current_type):
  1765. """
  1766. Check if a builtin type should be included.
  1767. This removes Variant and POD types from inclusion, and the current type.
  1768. """
  1769. if type_name.startswith("typedarray::"):
  1770. return True
  1771. to_include = get_enum_class(type_name) if is_enum(type_name) else type_name
  1772. if to_include == current_type or is_pod_type(to_include):
  1773. return False
  1774. if to_include == "GlobalConstants" or to_include == "UtilityFunctions":
  1775. return True
  1776. return is_engine_class(to_include) or is_variant(to_include)
  1777. def correct_default_value(value, type_name):
  1778. value_map = {
  1779. "null": "nullptr",
  1780. '""': "String()",
  1781. '&""': "StringName()",
  1782. "[]": "Array()",
  1783. "{}": "Dictionary()",
  1784. "Transform2D(1, 0, 0, 1, 0, 0)": "Transform2D()", # Default transform.
  1785. "Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)": "Transform3D()", # Default transform.
  1786. }
  1787. if value in value_map:
  1788. return value_map[value]
  1789. if value == "":
  1790. return f"{type_name}()"
  1791. if value.startswith("Array["):
  1792. return f"{{}}"
  1793. return value
  1794. def correct_typed_array(type_name):
  1795. if type_name.startswith("typedarray::"):
  1796. return type_name.replace("typedarray::", "TypedArray<") + ">"
  1797. return type_name
  1798. def correct_type(type_name, meta=None):
  1799. type_conversion = {"float": "double", "int": "int64_t", "Nil": "Variant"}
  1800. if meta != None:
  1801. if "int" in meta:
  1802. return f"{meta}_t"
  1803. elif meta in type_conversion:
  1804. return type_conversion[type_name]
  1805. else:
  1806. return meta
  1807. if type_name in type_conversion:
  1808. return type_conversion[type_name]
  1809. if type_name.startswith("typedarray::"):
  1810. return type_name.replace("typedarray::", "TypedArray<") + ">"
  1811. if is_enum(type_name):
  1812. if is_bitfield(type_name):
  1813. base_class = get_enum_class(type_name)
  1814. if base_class == "GlobalConstants":
  1815. return f"BitField<{get_enum_name(type_name)}>"
  1816. return f"BitField<{base_class}::{get_enum_name(type_name)}>"
  1817. else:
  1818. base_class = get_enum_class(type_name)
  1819. if base_class == "GlobalConstants":
  1820. return f"{get_enum_name(type_name)}"
  1821. return f"{base_class}::{get_enum_name(type_name)}"
  1822. if is_refcounted(type_name):
  1823. return f"Ref<{type_name}>"
  1824. if type_name == "Object" or is_engine_class(type_name):
  1825. return f"{type_name} *"
  1826. if type_name.endswith("*"):
  1827. return f"{type_name[:-1]} *"
  1828. return type_name
  1829. def get_gdextension_type(type_name):
  1830. type_conversion_map = {
  1831. "bool": "int8_t",
  1832. "uint8_t": "int64_t",
  1833. "int8_t": "int64_t",
  1834. "uint16_t": "int64_t",
  1835. "int16_t": "int64_t",
  1836. "uint32_t": "int64_t",
  1837. "int32_t": "int64_t",
  1838. "int": "int64_t",
  1839. "float": "double",
  1840. }
  1841. if type_name.startswith("BitField<"):
  1842. return "int64_t"
  1843. if type_name in type_conversion_map:
  1844. return type_conversion_map[type_name]
  1845. return type_name
  1846. def escape_identifier(id):
  1847. cpp_keywords_map = {
  1848. "class": "_class",
  1849. "char": "_char",
  1850. "short": "_short",
  1851. "bool": "_bool",
  1852. "int": "_int",
  1853. "default": "_default",
  1854. "case": "_case",
  1855. "switch": "_switch",
  1856. "export": "_export",
  1857. "template": "_template",
  1858. "new": "new_",
  1859. "operator": "_operator",
  1860. "typeof": "type_of",
  1861. "typename": "type_name",
  1862. "enum": "_enum",
  1863. }
  1864. if id in cpp_keywords_map:
  1865. return cpp_keywords_map[id]
  1866. return id
  1867. def get_operator_id_name(op):
  1868. op_id_map = {
  1869. "==": "equal",
  1870. "!=": "not_equal",
  1871. "<": "less",
  1872. "<=": "less_equal",
  1873. ">": "greater",
  1874. ">=": "greater_equal",
  1875. "+": "add",
  1876. "-": "subtract",
  1877. "*": "multiply",
  1878. "/": "divide",
  1879. "unary-": "negate",
  1880. "unary+": "positive",
  1881. "%": "module",
  1882. "**": "power",
  1883. "<<": "shift_left",
  1884. ">>": "shift_right",
  1885. "&": "bit_and",
  1886. "|": "bit_or",
  1887. "^": "bit_xor",
  1888. "~": "bit_negate",
  1889. "and": "and",
  1890. "or": "or",
  1891. "xor": "xor",
  1892. "not": "not",
  1893. "and": "and",
  1894. "in": "in",
  1895. }
  1896. return op_id_map[op]
  1897. def get_default_value_for_type(type_name):
  1898. if type_name == "int":
  1899. return "0"
  1900. if type_name == "float":
  1901. return "0.0"
  1902. if type_name == "bool":
  1903. return "false"
  1904. if type_name.startswith("typedarray::"):
  1905. return f"{correct_type(type_name)}()"
  1906. if is_enum(type_name):
  1907. return f"{correct_type(type_name)}(0)"
  1908. if is_variant(type_name):
  1909. return f"{type_name}()"
  1910. if is_refcounted(type_name):
  1911. return f"Ref<{type_name}>()"
  1912. return "nullptr"
  1913. header = """\
  1914. /**************************************************************************/
  1915. /* $filename */
  1916. /**************************************************************************/
  1917. /* This file is part of: */
  1918. /* GODOT ENGINE */
  1919. /* https://godotengine.org */
  1920. /**************************************************************************/
  1921. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  1922. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  1923. /* */
  1924. /* Permission is hereby granted, free of charge, to any person obtaining */
  1925. /* a copy of this software and associated documentation files (the */
  1926. /* "Software"), to deal in the Software without restriction, including */
  1927. /* without limitation the rights to use, copy, modify, merge, publish, */
  1928. /* distribute, sublicense, and/or sell copies of the Software, and to */
  1929. /* permit persons to whom the Software is furnished to do so, subject to */
  1930. /* the following conditions: */
  1931. /* */
  1932. /* The above copyright notice and this permission notice shall be */
  1933. /* included in all copies or substantial portions of the Software. */
  1934. /* */
  1935. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  1936. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  1937. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  1938. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  1939. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  1940. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  1941. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  1942. /**************************************************************************/
  1943. """
  1944. def add_header(filename, lines):
  1945. desired_length = len(header.split("\n")[0])
  1946. pad_spaces = desired_length - 6 - len(filename)
  1947. for num, line in enumerate(header.split("\n")):
  1948. if num == 1:
  1949. new_line = f"/* {filename}{' ' * pad_spaces}*/"
  1950. lines.append(new_line)
  1951. else:
  1952. lines.append(line)
  1953. lines.append("// THIS FILE IS GENERATED. EDITS WILL BE LOST.")
  1954. lines.append("")