binding_generator.py 100 KB

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