binding_generator.py 95 KB

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