binding_generator.py 96 KB

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