binding_generator.py 95 KB

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