binding_generator.py 109 KB

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