binding_generator.py 111 KB

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