binding_generator.py 97 KB

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