binding_generator.py 101 KB

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