binding_generator.py 90 KB

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